{"text": "/* eigen/gensymmv.c\n * \n * Copyright (C) 2007 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module computes the eigenvalues and eigenvectors of a real\n * generalized symmetric-definite eigensystem A x = \\lambda B x, where\n * A and B are symmetric, and B is positive-definite.\n */\n\nstatic void gensymmv_normalize_eigenvectors(gsl_matrix *evec);\n\n/*\ngsl_eigen_gensymmv_alloc()\n\nAllocate a workspace for solving the generalized symmetric-definite\neigenvalue problem. The size of this workspace is O(4n).\n\nInputs: n - size of matrices\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_gensymmv_workspace *\ngsl_eigen_gensymmv_alloc(const size_t n)\n{\n gsl_eigen_gensymmv_workspace *w;\n\n if (n == 0)\n {\n GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n GSL_EINVAL);\n }\n\n w = (gsl_eigen_gensymmv_workspace *) calloc (1, sizeof (gsl_eigen_gensymmv_workspace));\n\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->size = n;\n\n w->symmv_workspace_p = gsl_eigen_symmv_alloc(n);\n if (!w->symmv_workspace_p)\n {\n gsl_eigen_gensymmv_free(w);\n GSL_ERROR_NULL(\"failed to allocate space for symmv workspace\", GSL_ENOMEM);\n }\n\n return (w);\n} /* gsl_eigen_gensymmv_alloc() */\n\n/*\ngsl_eigen_gensymmv_free()\n Free workspace w\n*/\n\nvoid\ngsl_eigen_gensymmv_free (gsl_eigen_gensymmv_workspace * w)\n{\n RETURN_IF_NULL (w);\n\n if (w->symmv_workspace_p)\n gsl_eigen_symmv_free(w->symmv_workspace_p);\n\n free(w);\n} /* gsl_eigen_gensymmv_free() */\n\n/*\ngsl_eigen_gensymmv()\n\nSolve the generalized symmetric-definite eigenvalue problem\n\nA x = \\lambda B x\n\nfor the eigenvalues \\lambda and eigenvectors x.\n\nInputs: A - real symmetric matrix\n B - real symmetric and positive definite matrix\n eval - where to store eigenvalues\n evec - where to store eigenvectors\n w - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_gensymmv (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval,\n gsl_matrix * evec, gsl_eigen_gensymmv_workspace * w)\n{\n const size_t N = A->size1;\n\n /* check matrix and vector sizes */\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n }\n else if ((N != B->size1) || (N != B->size2))\n {\n GSL_ERROR (\"B matrix dimensions must match A\", GSL_EBADLEN);\n }\n else if (eval->size != N)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (evec->size1 != N)\n {\n GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n }\n else if (w->size != N)\n {\n GSL_ERROR (\"matrix size does not match workspace\", GSL_EBADLEN);\n }\n else\n {\n int s;\n\n /* compute Cholesky factorization of B */\n s = gsl_linalg_cholesky_decomp(B);\n if (s != GSL_SUCCESS)\n return s; /* B is not positive definite */\n\n /* transform to standard symmetric eigenvalue problem */\n gsl_eigen_gensymm_standardize(A, B);\n\n /* compute eigenvalues and eigenvectors */\n s = gsl_eigen_symmv(A, eval, evec, w->symmv_workspace_p);\n if (s != GSL_SUCCESS)\n return s;\n\n /* backtransform eigenvectors: evec -> L^{-T} evec */\n gsl_blas_dtrsm(CblasLeft,\n CblasLower,\n CblasTrans,\n CblasNonUnit,\n 1.0,\n B,\n evec);\n\n /* the blas call destroyed the normalization - renormalize */\n gensymmv_normalize_eigenvectors(evec);\n\n return GSL_SUCCESS;\n }\n} /* gsl_eigen_gensymmv() */\n\n/********************************************\n * INTERNAL ROUTINES *\n ********************************************/\n\n/*\ngensymmv_normalize_eigenvectors()\n Normalize eigenvectors so that their Euclidean norm is 1\n\nInputs: evec - eigenvectors\n*/\n\nstatic void\ngensymmv_normalize_eigenvectors(gsl_matrix *evec)\n{\n const size_t N = evec->size1;\n size_t i; /* looping */\n\n for (i = 0; i < N; ++i)\n {\n gsl_vector_view vi = gsl_matrix_column(evec, i);\n double scale = 1.0 / gsl_blas_dnrm2(&vi.vector);\n\n gsl_blas_dscal(scale, &vi.vector);\n }\n} /* gensymmv_normalize_eigenvectors() */\n", "meta": {"hexsha": "b8d575de8630838958eba2de73c21252c8afe4a3", "size": 5288, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/eigen/gensymmv.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/eigen/gensymmv.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/eigen/gensymmv.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": 26.0492610837, "max_line_length": 89, "alphanum_fraction": 0.6492057489, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49998480977099063}} {"text": "#include \"gemm.h\"\n#include \"utils.h\"\n#include \"cuda.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef OPENBLAS\n#include \n#endif\n\n#ifdef OPENGEMM\n#include \"gemm_kernels.h\"\n#endif\n\nvoid gemm_bin(int M, int N, int K, real_t ALPHA, char *A, int lda, real_t *B,\n\t\tint ldb, real_t *C, int ldc) {\n\tint i, j, k;\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (k = 0; k < K; ++k) {\n\t\t\tchar A_PART = A[i * lda + k];\n\t\t\tif (A_PART) {\n\t\t\t\tfor (j = 0; j < N; ++j) {\n\t\t\t\t\tC[i * ldc + j] += B[k * ldb + j];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (j = 0; j < N; ++j) {\n\t\t\t\t\tC[i * ldc + j] -= B[k * ldb + j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nreal_t *random_matrix(int rows, int cols) {\n\tint i;\n\treal_t *m = calloc(rows * cols, sizeof(real_t));\n\tfor (i = 0; i < rows * cols; ++i) {\n\t\tm[i] = (real_t) rand() / RAND_MAX;\n\t}\n\treturn m;\n}\n\nvoid time_random_matrix(int TA, int TB, int m, int k, int n) {\n\treal_t *a;\n\tif (!TA)\n\t\ta = random_matrix(m, k);\n\telse\n\t\ta = random_matrix(k, m);\n\tint lda = (!TA) ? k : m;\n\treal_t *b;\n\tif (!TB)\n\t\tb = random_matrix(k, n);\n\telse\n\t\tb = random_matrix(n, k);\n\tint ldb = (!TB) ? n : k;\n\n\treal_t *c = random_matrix(m, n);\n\tint i;\n\tclock_t start = clock(), end;\n\tfor (i = 0; i < 10; ++i) {\n\t\tgemm_cpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n);\n\t}\n\tend = clock();\n\tprintf(\"Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf ms\\n\", m, k,\n\t\t\tk, n, TA, TB, (real_t)(end - start) / CLOCKS_PER_SEC);\n\tfree(a);\n\tfree(b);\n\tfree(c);\n}\n\nvoid gemm(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A, int lda,\n\t\treal_t *B, int ldb, real_t BETA, real_t *C, int ldc) {\n\tgemm_cpu(TA, TB, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc);\n}\n\nvoid gemm_nn(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,\n\t\tint ldb, real_t *C, int ldc) {\n\tint i, j, k;\n#pragma omp parallel for\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (k = 0; k < K; ++k) {\n\t\t\tregister real_t A_PART = ALPHA * A[i * lda + k];\n\t\t\tfor (j = 0; j < N; ++j) {\n\t\t\t\tC[i * ldc + j] += A_PART * B[k * ldb + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid gemm_nt(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,\n\t\tint ldb, real_t *C, int ldc) {\n\tint i, j, k;\n#pragma omp parallel for\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (j = 0; j < N; ++j) {\n\t\t\tregister real_t sum = 0;\n\t\t\tfor (k = 0; k < K; ++k) {\n\t\t\t\tsum += ALPHA * A[i * lda + k] * B[j * ldb + k];\n\t\t\t}\n\t\t\tC[i * ldc + j] += sum;\n\t\t}\n\t}\n}\n\nvoid gemm_tn(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,\n\t\tint ldb, real_t *C, int ldc) {\n\tint i, j, k;\n#pragma omp parallel for\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (k = 0; k < K; ++k) {\n\t\t\tregister real_t A_PART = ALPHA * A[k * lda + i];\n\t\t\tfor (j = 0; j < N; ++j) {\n\t\t\t\tC[i * ldc + j] += A_PART * B[k * ldb + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid gemm_tt(int M, int N, int K, real_t ALPHA, real_t *A, int lda, real_t *B,\n\t\tint ldb, real_t *C, int ldc) {\n\tint i, j, k;\n#pragma omp parallel for\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (j = 0; j < N; ++j) {\n\t\t\tregister real_t sum = 0;\n\t\t\tfor (k = 0; k < K; ++k) {\n\t\t\t\tsum += ALPHA * A[i + k * lda] * B[k + j * ldb];\n\t\t\t}\n\t\t\tC[i * ldc + j] += sum;\n\t\t}\n\t}\n}\n\nvoid gemm_cpu(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A,\n\t\tint lda, real_t *B, int ldb, real_t BETA, real_t *C, int ldc) {\n\t//printf(\"cpu: %d %d %d %d %d %f %d %d %f %d\\n\",TA, TB, M, N, K, ALPHA, lda, ldb, BETA, ldc);\n\n#ifdef OPENBLAS\n\t/*\n\tvoid cblas_sgemm \t( \tconst CBLAS_LAYOUT \tlayout,\n\t\tconst CBLAS_TRANSPOSE \tTransA,\n\t\tconst CBLAS_TRANSPOSE \tTransB,\n\t\tconst int \tM,\n\t\tconst int \tN,\n\t\tconst int \tK,\n\t\tconst float \talpha,\n\t\tconst float * \tA,\n\t\tconst int \tlda,\n\t\tconst float * \tB,\n\t\tconst int \tldb,\n\t\tconst float \tbeta,\n\t\tfloat * \tC,\n\t\tconst int \tldc\n\t)\n\t */\n\tCBLAS_TRANSPOSE transa, transb;\n\n\tif (!TA && !TB){\n\t\ttransa = CblasNoTrans;\n\t\ttransb = CblasNoTrans;\n\t}else if (TA && !TB){\n\t\ttransa = CblasTrans;\n\t\ttransb = CblasNoTrans;\n\t}else if (!TA && TB){\n\t\ttransa = CblasNoTrans;\n\t\ttransb = CblasTrans;\n\t}else{\n\t\ttransa = CblasTrans;\n\t\ttransb = CblasTrans;\n\t}\n\t//\t 0 1 2 3 4 5 6 7 8 9 10 11 12 13\n\tcblas_sgemm(CblasRowMajor, transa, transb, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc);\n#else\n\n\tint i, j;\n\tfor (i = 0; i < M; ++i) {\n\t\tfor (j = 0; j < N; ++j) {\n\t\t\tC[i * ldc + j] *= BETA;\n\t\t}\n\t}\n\n\tif (!TA && !TB)\n\t\tgemm_nn(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);\n\telse if (TA && !TB)\n\t\tgemm_tn(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);\n\telse if (!TA && TB)\n\t\tgemm_nt(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);\n\telse\n\t\tgemm_tt(M, N, K, ALPHA, A, lda, B, ldb, C, ldc);\n#endif\n}\n\n#ifdef GPU\n\nvoid gemm_gpu(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A_gpu,\n\t\tint lda, real_t *B_gpu, int ldb, real_t BETA, real_t *C_gpu, int ldc,\n\t\tunsigned char use_tensor_cores, cudaStream_t st) {\n\tcublasHandle_t handle = blas_handle(use_tensor_cores);\n\tcublasSetStream(handle, st);\n//\tif(TB || TA)\n//\t{\n//\t\tprintf(\"Matrix need to be transposed %d %d\\n\", TB, TA);\n//\t}\n#ifndef OPENGEMM\n\n#if REAL_TYPE == HALF\n\t//run_cuda_gemm_half(int TA, int TB, int M, int N, int K, real_t ALPHA, real_t *A_gpu,\n//\tint lda, real_t *B_gpu, int ldb, real_t BETA, real_t *C_gpu, int ldc)\n\trun_cuda_gemm_half(handle, TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc, st);\n#elif REAL_TYPE == FLOAT\n\tcudaError_t status = (cudaError_t) cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),\n\t\t\t(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,\n\t\t\tA_gpu, lda, &BETA, C_gpu, ldc);\n\tcheck_error(status);\n#elif REAL_TYPE == DOUBLE\n\tcudaError_t status = (cudaError_t) cublasDgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),\n\t\t\t(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,\n\t\t\tA_gpu, lda, &BETA, C_gpu, ldc);\n\tcheck_error(status);\n#endif\n\n#else\n\n#if REAL_TYPE == HALF\n\trun_cuda_gemm_half(handle, TA, TB, M, N, K, ALPHA, A_gpu, lda, B_gpu, ldb, BETA, C_gpu, ldc, st);\n#elif REAL_TYPE == FLOAT\n\tsgemm((TB ? CUBLAS_OP_T : CUBLAS_OP_N),\n\t\t\t(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,\n\t\t\tA_gpu, lda, &BETA, C_gpu, ldc);\n\n#elif REAL_TYPE == DOUBLE\n\tdgemm((TB ? CUBLAS_OP_T : CUBLAS_OP_N),\n\t\t\t(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,\n\t\t\tA_gpu, lda, &BETA, C_gpu, ldc);\n\n#endif\n\n#endif\n\n//\tcublasHandle_t handle = blas_handle();\n//\tcudaError_t status = cublasSgemm(handle, (TB ? CUBLAS_OP_T : CUBLAS_OP_N),\n//\t\t\t(TA ? CUBLAS_OP_T : CUBLAS_OP_N), N, M, K, &ALPHA, B_gpu, ldb,\n//\t\t\tA_gpu, lda, &BETA, C_gpu, ldc);\n\n}\n\nvoid time_gpu_random_matrix(int TA, int TB, int m, int k, int n) {\n\treal_t *a;\n\tif (!TA)\n\t\ta = random_matrix(m, k);\n\telse\n\t\ta = random_matrix(k, m);\n\tint lda = (!TA) ? k : m;\n\treal_t *b;\n\tif (!TB)\n\t\tb = random_matrix(k, n);\n\telse\n\t\tb = random_matrix(n, k);\n\tint ldb = (!TB) ? n : k;\n\n\treal_t *c = random_matrix(m, n);\n\tint i;\n\tclock_t start = clock(), end;\n\tfor (i = 0; i < 32; ++i) {\n\t\tgemm_gpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n, 0, 0x0);\n\t}\n\tend = clock();\n\tprintf(\"Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s\\n\", m, k,\n\t\t\tk, n, TA, TB, (real_t)(end - start) / CLOCKS_PER_SEC);\n\tfree(a);\n\tfree(b);\n\tfree(c);\n}\n\nvoid time_gpu(int TA, int TB, int m, int k, int n) {\n\tint iter = 10;\n\treal_t *a = random_matrix(m, k);\n\treal_t *b = random_matrix(k, n);\n\n\tint lda = (!TA) ? k : m;\n\tint ldb = (!TB) ? n : k;\n\n\treal_t *c = random_matrix(m, n);\n\n\treal_t *a_cl = cuda_make_array(a, m * k);\n\treal_t *b_cl = cuda_make_array(b, k * n);\n\treal_t *c_cl = cuda_make_array(c, m * n);\n\n\tint i;\n\tclock_t start = clock(), end;\n\tfor (i = 0; i < iter; ++i) {\n\t\tgemm_gpu(TA, TB, m, n, k, 1, a_cl, lda, b_cl, ldb, 1, c_cl, n, 0, 0x0);\n\t\tcudaDeviceSynchronize();\n\t}\n\tdouble flop = ((double) m) * n * (2. * k + 2.) * iter;\n\tdouble gflop = flop / pow(10., 9);\n\tend = clock();\n\tdouble seconds = sec(end - start);\n\tprintf(\n\t\t\t\"Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %lf s, %lf GFLOPS\\n\",\n\t\t\tm, k, k, n, TA, TB, seconds, gflop / seconds);\n\tcuda_free(a_cl);\n\tcuda_free(b_cl);\n\tcuda_free(c_cl);\n\tfree(a);\n\tfree(b);\n\tfree(c);\n}\n\nvoid test_gpu_accuracy(int TA, int TB, int m, int k, int n) {\n\tsrand(0);\n\treal_t *a;\n\tif (!TA)\n\t\ta = random_matrix(m, k);\n\telse\n\t\ta = random_matrix(k, m);\n\tint lda = (!TA) ? k : m;\n\treal_t *b;\n\tif (!TB)\n\t\tb = random_matrix(k, n);\n\telse\n\t\tb = random_matrix(n, k);\n\tint ldb = (!TB) ? n : k;\n\n\treal_t *c = random_matrix(m, n);\n\treal_t *c_gpu = random_matrix(m, n);\n\tmemset(c, 0, m * n * sizeof(real_t));\n\tmemset(c_gpu, 0, m * n * sizeof(real_t));\n\tint i;\n\t//pm(m,k,b);\n\tgemm_gpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c_gpu, n, 0, 0x0);\n\t//printf(\"GPU\\n\");\n\t//pm(m, n, c_gpu);\n\n\tgemm_cpu(TA, TB, m, n, k, 1, a, lda, b, ldb, 1, c, n);\n\t//printf(\"\\n\\nCPU\\n\");\n\t//pm(m, n, c);\n\tdouble sse = 0;\n\tfor (i = 0; i < m * n; ++i) {\n\t\t//printf(\"%f %f\\n\", c[i], c_gpu[i]);\n\t\tsse += pow(c[i] - c_gpu[i], 2);\n\t}\n\tprintf(\"Matrix Multiplication %dx%d * %dx%d, TA=%d, TB=%d: %g SSE\\n\", m, k,\n\t\t\tk, n, TA, TB, sse / (m * n));\n\tfree(a);\n\tfree(b);\n\tfree(c);\n\tfree(c_gpu);\n}\n\nint test_gpu_blas() {\n\t/*\n\t test_gpu_accuracy(0,0,10,576,75);\n\n\t test_gpu_accuracy(0,0,17,10,10);\n\t test_gpu_accuracy(1,0,17,10,10);\n\t test_gpu_accuracy(0,1,17,10,10);\n\t test_gpu_accuracy(1,1,17,10,10);\n\n\t test_gpu_accuracy(0,0,1000,10,100);\n\t test_gpu_accuracy(1,0,1000,10,100);\n\t test_gpu_accuracy(0,1,1000,10,100);\n\t test_gpu_accuracy(1,1,1000,10,100);\n\n\t test_gpu_accuracy(0,0,10,10,10);\n\n\t time_gpu(0,0,64,2916,363);(cudaError_t) cublasDgemm\n\t time_gpu(0,0,64,2916,363);\n\t time_gpu(0,0,64,2916,363);\n\t time_gpu(0,0,192,729,1600);\n\t time_gpu(0,0,384,196,1728);\n\t time_gpu(0,0,256,196,3456);\n\t time_gpu(0,0,256,196,2304);\n\t time_gpu(0,0,128,4096,12544);\n\t time_gpu(0,0,128,4096,4096);\n\t */\n\ttime_gpu(0, 0, 64, 75, 12544);\n\ttime_gpu(0, 0, 64, 75, 12544);\n\ttime_gpu(0, 0, 64, 75, 12544);\n\ttime_gpu(0, 0, 64, 576, 12544);\n\ttime_gpu(0, 0, 256, 2304, 784);\n\ttime_gpu(1, 1, 2304, 256, 784);\n\ttime_gpu(0, 0, 512, 4608, 196);\n\ttime_gpu(1, 1, 4608, 512, 196);\n\n\treturn 0;\n}\n#endif\n\n", "meta": {"hexsha": "bd15bcab5210d8c558ae7aec7fa749f5f11dc34d", "size": 9910, "ext": "c", "lang": "C", "max_stars_repo_path": "test-apps/darknet_v3/src/gemm.c", "max_stars_repo_name": "divadnauj-GB/nvbitfi", "max_stars_repo_head_hexsha": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15", "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": "test-apps/darknet_v3/src/gemm.c", "max_issues_repo_name": "divadnauj-GB/nvbitfi", "max_issues_repo_head_hexsha": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15", "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": "test-apps/darknet_v3/src/gemm.c", "max_forks_repo_name": "divadnauj-GB/nvbitfi", "max_forks_repo_head_hexsha": "8f7e48a4ffd3f8e819c5fc0891fb62422080aa15", "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.0886075949, "max_line_length": 98, "alphanum_fraction": 0.5750756811, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.49969550919902855}} {"text": "static char help[] = \"DAE system solver example using TS. Models two\\n\"\n\"equal-mass balls (particles) moving in the plane with a rigid connecting\\n\"\n\"rod between. (Alternatively, -rod_free removes the rod and the motion\\n\"\n\"is free and independent.) A stabilized index-2 constrained Lagrangian\\n\"\n\"dynamics formulation is used. We use cartesian coordinates (x,y) and\\n\" \"velocities (v=dx/dt,w=dy/dt). The system has dimension 10.\\n\\n\";\n\n// DEBUG possibly a good solution using BDF3 and -snes_fd\n// ./rod -ts_type bdf -ksp_type preonly -pc_type svd -ts_monitor binary:t.dat -ts_monitor_solution binary:u.dat -ts_dt 0.01 -ts_max_time 1.0 -snes_fd -ts_bdf_order 3\n// ./trajectory.py -o figure.png t.dat u.dat\n\n// DEBUG check Jacobian for rod problem using one backward-Euler step\n// (2nd case with -snes_fd):\n// ./rod -ts_type beuler -ts_max_time 0.1 -ts_dt 0.1 -ksp_type preonly -pc_type svd -snes_monitor -ksp_view_mat\n// ./rod -ts_type beuler -ts_max_time 0.1 -ts_dt 0.1 -ksp_type preonly -pc_type svd -snes_monitor -ksp_view_mat -snes_fd\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 ./rod -rod_free -ts_type bdf -ts_rtol 1.0e-$T -ts_atol 1.0e-$T; done\n\n#include \n\ntypedef struct {\n PetscBool free;\n PetscReal g, // m s-2; acceleration of gravity\n m, // kg; ball mass\n l; // m; spring or rod length\n} RodCtx;\n\nextern PetscErrorCode SetInitial(Vec, RodCtx*);\nextern PetscErrorCode FreeExact(Vec, PetscReal, Vec, RodCtx*);\nextern PetscErrorCode LagrangeIFcn(TS, PetscReal, Vec, Vec, Vec, void*);\nextern PetscErrorCode LagrangeIJac(TS, PetscReal, Vec, Vec, PetscReal,\n Mat, Mat, 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 Mat A;\n TS ts;\n RodCtx user;\n char probstr[20] = \"rod\";\n\n ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr;\n\n user.free = PETSC_FALSE;\n user.g = 9.81;\n user.m = 58.0e-3; // 58 g for a tennis ball\n user.l = 0.5; // rod length, and determines initial condition\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"rod_\", \"options for rod\",\n \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-free\",\"remove rod for free motion\",\n \"rod.c\", user.free, &user.free,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-g\", \"acceleration of gravity (m s-2)\",\n \"rod.c\", user.g, &user.g, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-l\", \"rod length (m)\", \"rod.c\",\n user.l, &user.l, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-m\", \"mass of each ball (kg)\", \"rod.c\",\n user.m, &user.m, 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 dimension, equation type, and solver type\n ierr = VecSetSizes(u,PETSC_DECIDE,10); CHKERRQ(ierr);\n ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);\n ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,10,10); CHKERRQ(ierr);\n ierr = MatSetFromOptions(A); CHKERRQ(ierr);\n ierr = MatSetUp(A); CHKERRQ(ierr);\n if (user.free) {\n ierr = TSSetEquationType(ts, TS_EQ_DAE_IMPLICIT_INDEX1);\n CHKERRQ(ierr);\n } else {\n ierr = TSSetEquationType(ts, TS_EQ_DAE_IMPLICIT_INDEX2);\n CHKERRQ(ierr);\n }\n ierr = TSSetIFunction(ts,NULL,LagrangeIFcn,&user); CHKERRQ(ierr);\n ierr = TSSetIJacobian(ts,A,A,LagrangeIJac,&user);CHKERRQ(ierr);\n ierr = TSSetType(ts,TSBEULER); CHKERRQ(ierr); // FIXME BDF3 as default?\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.free) {\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 = VecView(uexact, PETSC_VIEWER_STDOUT_WORLD); 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.free)\n strcpy(probstr, \"free\");\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"%s problem solved to tf = %.3f (%d steps)\\n\",\n probstr, tf, steps); CHKERRQ(ierr);\n\n MatDestroy(&A); VecDestroy(&u); TSDestroy(&ts);\n return PetscFinalize();\n}\n\n/* Regarding the following functions:\nIn the rod case the solution is a 10-dimensional vector u.\nHere is the correspondence with the notes (doc/rod.pdf):\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)\nu[8] = mu\nu[9] = lambda\n*/\n\nPetscErrorCode SetInitial(Vec u, RodCtx *user) {\n /* Set initial conditions compatible with the rod constraint\n 0 = g(q) = (1/2) ( (q1 - q3)^2 + (q2 - q4)^2 - l^2 ) (1)\n and the velocity constraint\n 0 = G(q) v = (q1 - q3)(v1 - v3) + (q2 - q4)(v2 - v4) (2)\n The initial conditions are based on the location of the first mass\n being at cartesian location (q1,q2)=(0,1) and the second at\n (q3,q4)=(0,1+l). The initial velocity of the first mass is\n (v1,v2)=(10,10) and the second is (v3,v4)=(15,10). In fact we \n adjust q4 and v4 from the other values so as to satisfy constraints\n (1) and (2). The initial value mu=0 is always set. We set lambda\n from the other values according to the acceleration constraint\n lambda = (m / (2 l^2)) ((v1-v3)^2 + (v2-v4)^2) (3)\n Initial values of mu and lambda are ignored in BDF solutions. */\n PetscErrorCode ierr;\n const PetscReal c = user->m / (2.0 * user->l * user->l);\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 au[8] = 0.0; // mu\n if (user->free)\n au[9] = 0.0;\n else // set lambda to satisfy (3)\n au[9] = c * ( (au[4] - au[6]) * (au[4] - au[6])\n + (au[5] - au[7]) * (au[5] - au[7]));\n ierr = VecRestoreArray(u,&au); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FreeExact(Vec u0, PetscReal tf, Vec uexact, RodCtx *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->free) {\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 auex[8] = 0.0; // mu\n auex[9] = 0.0; // lambda\n ierr = VecRestoreArray(u0, &au0); CHKERRQ(ierr);\n ierr = VecRestoreArray(uexact, &auex); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode LagrangeIFcn(TS ts, PetscReal t, Vec u, Vec udot, Vec F,\n void *ctx) {\n PetscErrorCode ierr;\n RodCtx *user = (RodCtx*)ctx;\n const PetscReal *au, *audot, mg = user->m * user->g;\n PetscReal *aF, dx, dy, dvx, dvy;\n\n PetscFunctionBeginUser;\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecGetArrayRead(udot,&audot); CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF); CHKERRQ(ierr);\n dx = au[0] - au[2];\n dy = au[1] - au[3];\n dvx = au[4] - au[6];\n dvy = au[5] - au[7];\n aF[0] = audot[0] - au[4] + au[8] * dx;\n aF[1] = audot[1] - au[5] + au[8] * dy;\n aF[2] = audot[2] - au[6] - au[8] * dx;\n aF[3] = audot[3] - au[7] - au[8] * dy;\n aF[4] = user->m * audot[4] + au[9] * dx;\n aF[5] = user->m * audot[5] + mg + au[9] * dy;\n aF[6] = user->m * audot[6] - au[9] * dx;\n aF[7] = user->m * audot[7] + mg - au[9] * dy;\n if (user->free) { // trivial index 1 DAE\n aF[8] = au[8]; // equation: mu = 0\n aF[9] = au[9]; // equation: lambda = 0\n } else {\n aF[8] = 0.5 * ( dx * dx + dy * dy - user->l * user->l ); // constraint\n aF[9] = dx * dvx + dy * dvy; // velocity constraint\n }\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(udot,&audot); CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\nPetscErrorCode LagrangeIJac(TS ts, PetscReal t, Vec u, Vec udot,\n PetscReal sigma, Mat J, Mat Jpre, void *ctx) {\n PetscErrorCode ierr;\n RodCtx *user = (RodCtx*)ctx;\n const PetscReal *au;\n PetscInt row, col[8], n; // max nonzeros in a row of J is 4\n PetscReal val[8];\n\n PetscFunctionBeginUser;\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n // construct Jacobian by rows, inserting nonzeros\n row = 0; n = 4; // row 0 has 4 nonzeros ...\n col[0] = 0; col[1] = 2; col[2] = 4; col[3] = 8;\n val[0] = sigma + au[8]; val[1] = - au[8];\n val[2] = -1; val[3] = au[0] - au[2];\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 1; n = 4;\n col[0] = 1; col[1] = 3; col[2] = 5; col[3] = 8;\n val[0] = sigma + au[8]; val[1] = - au[8];\n val[2] = -1; val[3] = au[1] - au[3];\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 2; n = 4;\n col[0] = 0; col[1] = 2; col[2] = 6; col[3] = 8;\n val[0] = - au[8]; val[1] = sigma + au[8];\n val[2] = -1; val[3] = -(au[0] - au[2]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 3; n = 4;\n col[0] = 1; col[1] = 3; col[2] = 7; col[3] = 8;\n val[0] = - au[8]; val[1] = sigma + au[8];\n val[2] = -1; val[3] = -(au[1] - au[3]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 4; n = 4;\n col[0] = 0; col[1] = 2; col[2] = 4; col[3] = 9;\n val[0] = au[9]; val[1] = - au[9];\n val[2] = sigma*user->m; val[3] = au[0] - au[2];\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 5; n = 4;\n col[0] = 1; col[1] = 3; col[2] = 5; col[3] = 9;\n val[0] = au[9]; val[1] = - au[9];\n val[2] = sigma*user->m; val[3] = au[1] - au[3];\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 6; n = 4;\n col[0] = 0; col[1] = 2; col[2] = 6; col[3] = 9;\n val[0] = -au[9]; val[1] = au[9];\n val[2] = sigma*user->m; val[3] = -(au[0] - au[2]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 7; n = 4;\n col[0] = 1; col[1] = 3; col[2] = 7; col[3] = 9;\n val[0] = -au[9]; val[1] = au[9];\n val[2] = sigma*user->m; val[3] = -(au[1] - au[3]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n if (user->free) {\n n = 1;\n row = 8; col[0] = 8; val[0] = 1.0; // equation mu = 0\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n row = 9; col[0] = 9; val[0] = 1.0; // equation lambda = 0\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n } else {\n n = 4; row = 8; n = 4;\n col[0] = 0; col[1] = 1; col[2] = 2; col[3] = 3;\n val[0] = au[0] - au[2]; val[1] = au[1] - au[3];\n val[2] = -(au[0] - au[2]); val[3] = -(au[1] - au[3]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n n = 4; row = 9; n = 8;\n col[0] = 0; col[1] = 1; col[2] = 2; col[3] = 3;\n col[4] = 4; col[5] = 5; col[6] = 6; col[7] = 7;\n val[0] = au[4] - au[6]; val[1] = au[5] - au[7];\n val[2] = -(au[4] - au[6]); val[3] = -(au[5] - au[7]);\n val[4] = au[0] - au[2]; val[5] = au[1] - au[3];\n val[6] = -(au[0] - au[2]); val[7] = -(au[1] - au[3]);\n ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);\n }\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n if (J != Jpre) {\n ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n }\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "365bee8d7f9e4289998371d260b05c44b9fa3f9a", "size": 14374, "ext": "c", "lang": "C", "max_stars_repo_path": "petsc/rod.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/rod.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/rod.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": 44.2276923077, "max_line_length": 165, "alphanum_fraction": 0.5505774315, "num_tokens": 5173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4996140585502038}} {"text": "/* Standalone c program to use viscdisk to run the Pringle (1981) ring\n problem, with a complex equation of state */\n\n#include \n#include \n#include \"init.h\"\n#include \"vader.h\"\n#include \"vader_common.h\"\n#include \n\n/* Physical constants */\n#define KB 1.3806488e-16\n#define MH 1.6737236e-24\n#define MU 0.61\n#define A 7.5657314e-15\n\n/* Problem parameters */\n\n/* Set this to a non-empty value to restart from a checkpoint */\n#define CHECKPOINT \"ringrad_00001.vader\"\n\n/* Grid parmeters */\n#define NR 4096\n#define RMIN 1.5e10\n#define RMAX 1.5e12\n#define LINEAR 1\n\n/* EOS parameters */\n#define EOS_FUNC 1\n#define GAMMA 1.66666666667\n#define DELTA 0.0\n\n/* Viscosity parameters */\n#define ALPHA_FUNC 1\n#define ALPHA 0.0\n\n/* Inner boundary condition */\n#define IBC_PRES_TYPE FIXED_TORQUE\n#define IBC_ENTH_TYPE FIXED_ENTHALPY_VALUE\n#define IBC_FUNC 1\n#define IBC_PRES_VAL 0.0\n#define IBC_ENTH_VAL 0.0\n\n/* Outer boundary condition */\n#define OBC_PRES_TYPE FIXED_TORQUE\n#define OBC_ENTH_TYPE FIXED_ENTHALPY_VALUE\n#define OBC_FUNC 1\n#define OBC_PRES_VAL 0.0\n#define OBC_ENTH_VAL 0.0\n\n/* Source functions */\n#define MASS_SRC_FUNC 0\n#define MASS_SRC_VAL 0.0\n#define INT_EN_SRC_FUNC 0\n#define INT_EN_SRC_VAL 0.0\n\n/* Control parameters */\n#define ERR_TOL 1.0e-6\n#define DT_TOL 0.1\n#define MAX_ITER 40\n#define INTERP_ORDER 1\n#define MAX_DT_INCREASE 1.5\n#define DT_MIN 1.0e-20\n#define MAX_STEP 100000\n#define USE_BE 0\n#define PRE_TIMESTEP 0\n#define POST_TIMESTEP 0\n#define VERBOSITY 1\n\n/* Output parameters */\n#define NSAVE 65\n#define OUTFILE \"ringrad.out\"\n#define NUSEROUT 0\n#define CHECKNAME \"ringrad\"\n#define USERREADCHK false\n#define USERWRITECHK false\n\n/* Time parameters */\n#define DT_START -1\n#define END_TIME 0.128\n\n/* Problem-specific parameters*/\n#define MSTAR (1.99e33*1.4)\n#define RING_MASS 1.99e27\n#define INIT_TEMP 1.0e4\n#define COL_RATIO 1.0e10\n#define RING_LOC 7.5e11\n#define NU 5.93e8\n#define FZ0 7.5e9\n#define GAMMA_GAS (5.0/3.0)\n\n/* Main */\nint main () {\n\n grid *grd;\n double col0, t0, colAnalyt, x, tau;\n double *col, *pres, *eInt;\n double *colOut, *presOut, *mBndOut, *eBndOut, *eIntOut, *tOut;\n double param[5];\n double tSave[NSAVE];\n bool writeCheckpoint[NSAVE];\n char *checkpoint = CHECKPOINT;\n int i, j, idx;\n FILE *fp;\n unsigned long nStep, nIter, nFail, nOut;\n\n /* Allocate grid and workspace */\n grd = gridInitKeplerian(NR, RMIN, RMAX, MSTAR, LINEAR);\n\n /* Allocate data */\n col = (double *) calloc(NR, sizeof(double));\n pres = (double *) calloc(NR, sizeof(double));\n eInt = (double *) calloc(NR, sizeof(double));\n\n /* Initialize column density and pressure arrays, and associated variables */\n col0 = RING_MASS / (M_PI*SQR(RING_LOC));\n t0 = SQR(RING_LOC)/(12.0*NU);\n for (i=0, idx=-1; ir_h[i] < RING_LOC) && (RING_LOC <= grd->r_h[i+1])) idx = i;\n for (i=0; iarea[idx] / COL_RATIO;\n col[idx] = RING_MASS / grd->area[idx];\n for (i=0; iarea[idx] / COL_RATIO;\n param[4] = INIT_TEMP*KB/(MU*MH);\n\n /* Set output times */\n for (i=0; ir_g[j+1]/RING_LOC;\n tau = tOut[i]/t0;\n colAnalyt = col0/ (pow(x, 0.25)*tau) * exp(-SQR(x-1.0)/tau) *\n\tgsl_sf_bessel_Inu_scaled(0.25, 2*x/tau);\n if (!isfinite(colAnalyt)) colAnalyt=0.0;\n if (colAnalyt < RING_MASS / grd->area[idx] / COL_RATIO)\n\tcolAnalyt = RING_MASS / grd->area[idx] / COL_RATIO;\n fprintf(fp, \"%e %e %e %e %e %e\\n\", \n\t tau, x,\n\t colOut[grd->nr*i+j], \n\t colAnalyt,\n\t presOut[grd->nr*i+j],\n\t eIntOut[grd->nr*i+j]);\n }\n }\n fclose(fp);\n\n /* Return successful exit */\n return(0);\n}\n\n\n\n", "meta": {"hexsha": "6a7e0c9bb6fe0a02fa6128c9890b54369751127f", "size": 6006, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/prob/main_ringrad.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/prob/main_ringrad.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/prob/main_ringrad.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 27.8055555556, "max_line_length": 99, "alphanum_fraction": 0.627039627, "num_tokens": 1967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4996140559026607}} {"text": "#include \n#include \n\n/* function names generated by removing \"gsl_sf\" from the beginning\n of the name. Thus gsl_sf_airy_Ai goes to airy_Ai. */\n\nstatic int sf_mode[] = { GSL_PREC_DOUBLE, GSL_PREC_SINGLE, GSL_PREC_APPROX } ;\n\nvoid airy_Ai_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n\tgsl_set_error_handler_off();\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Ai_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Bi_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Bi_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Ai_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Ai_scaled_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Bi_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Bi_scaled_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Ai_deriv_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Ai_deriv_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Bi_deriv_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Bi_deriv_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Ai_deriv_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Ai_deriv_scaled_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_Bi_deriv_scaled_e(double *x, int *len, int *mode, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n \n\tfor(i = 0; i< *len ; i++){\n\t\tstatus[i] = gsl_sf_airy_Bi_deriv_scaled_e(x[i], sf_mode[*mode], &result) ;\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n} \n\nvoid airy_zero_Ai_e(int *n, int *len, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n\tfor(i = 0; i< *len ; i++){\n\t\tif(n[i]>0){\n\t\t\tstatus[i] = gsl_sf_airy_zero_Ai_e(n[i], &result) ;\n\t\t} else {\n\t\t\tresult.val=0.0;\n\t\t\tresult.err=GSL_EDOM;\n\t\t}\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n}\n\nvoid airy_zero_Bi_e(int *n, int *len, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n\tfor(i = 0; i< *len ; i++){\n\t\tif(n[i]>0){\n\t\t\tstatus[i] = gsl_sf_airy_zero_Bi_e(n[i], &result) ;\n\t\t} else {\n\t\t\tresult.val=0.0;\n\t\t\tresult.err=GSL_EDOM;\n\t\t}\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n}\n\nvoid airy_zero_Ai_deriv_e(int *n, int *len, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n\tfor(i = 0; i< *len ; i++){\n\t\tif(n[i]>0){\n\t\t\tstatus[i] = gsl_sf_airy_zero_Ai_deriv_e(n[i], &result) ;\n\t\t} else {\n\t\t\tresult.val=0.0;\n\t\t\tresult.err=GSL_EDOM;\n\t\t}\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n}\n\nvoid airy_zero_Bi_deriv_e(int *n, int *len, double *val, double *err, int *status)\n{\n\tint i;\n\tgsl_sf_result result;\n\tfor(i = 0; i< *len ; i++){\n\t\tif(n[i]>0){\n\t\t\tstatus[i] = gsl_sf_airy_zero_Bi_deriv_e(n[i], &result) ;\n\t\t} else {\n\t\t\tresult.val=0.0;\n\t\t\tresult.err=GSL_EDOM;\n\t\t}\n\t\tval[i] = result.val;\n\t\terr[i] = result.err;\n\t}\n}\n", "meta": {"hexsha": "b154d1fae4d04861ece167361ddc6c262843b7ef", "size": 3835, "ext": "c", "lang": "C", "max_stars_repo_path": "src/airy.c", "max_stars_repo_name": "kbroman/fluctuationDomains", "max_stars_repo_head_hexsha": "d646a22b258d92199845446d914c1d3866e7b43f", "max_stars_repo_licenses": ["CC0-1.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/airy.c", "max_issues_repo_name": "kbroman/fluctuationDomains", "max_issues_repo_head_hexsha": "d646a22b258d92199845446d914c1d3866e7b43f", "max_issues_repo_licenses": ["CC0-1.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/airy.c", "max_forks_repo_name": "kbroman/fluctuationDomains", "max_forks_repo_head_hexsha": "d646a22b258d92199845446d914c1d3866e7b43f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6923076923, "max_line_length": 98, "alphanum_fraction": 0.6221642764, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.49935435776272447}} {"text": "#ifndef _MATH_UTIL_EULER_H_\n#define\t_MATH_UTIL_EULER_H_\n\n\n/* space group numbers for structures known by this program */\n/* these are from the International Tables, allowed values are [1-230] */\n/*\n * #define FCC 225\n * #define BCC 229\n * #define DIA 227\n * #define SIMPLE_CUBIC 221\n * #define HEX 194\n * #define SAPPHIRE 167\n * #define TRICLINIC 1\n */\n\n#ifndef CHECK_FREE\n#define CHECK_FREE(A) { if(A) free(A); (A)=NULL;}\n#endif\n\n#ifdef _MSC_VER\t\t\t\t\t\t/* identifies this as a Microsoft compiler */\n#include \t\t\t/* added RX2011 for NaN handling */\n#define round(A) ceil(A-0.5)\t\t/* added RX2011 for round() function */\n#define NAN gsl_nan()\t\t\t\t/* added RX2011 */\n#define isNAN(A) gsl_isnan(A)\t\t/* added RX2011 */\n#endif\n\n#ifndef NAN\t\t\t\t\t\t\t/* probably only needed for pcs */\n#define NAN nan(\"\")\t\t\t\t\t/* probably only needed for cygwin on pc */\n#endif\n\n#ifndef isNAN\t\t\t\t\t\t/* a good test for NAN */\n#define isNAN(A) ( (A) != (A) )\n#endif\n\n\n#define VECTOR_COPY3(A,B) {A[0]=B[0]; A[1]=B[1]; A[2]=B[2];}\n\n\nvoid DeletePoints(size_t len, void *ptr, size_t pntLen, size_t numDel);\n\nvoid EulerMatrix(double alpha,double beta,double gamma,double M_Euler[3][3]);\nvoid rot2EulerAngles(double A[3][3], double *alpha, double *beta, double *gamma);\nvoid MatrixRz(double Rz[3][3],double angle);\nvoid MatrixRy(double Ry[3][3],double angle);\n\n/* void lowestOrderHKL(int hkl[3]); */\n/* void lowestAllowedHKL(int hkl[3], int structure); */\n/* long allowedHKL(long h, long k, long l, int structure); */\nint gcf(int n1, int n2, int n3);\n\ndouble normalize3(double a[3]);\nvoid cross(double a[3], double b[3], double c[3]);\nvoid vector3cons(double a[3], double x);\ndouble dot3(double a[3],double b[3]);\ndouble determinant33(double a[3][3]);\nvoid MatrixMultiply31(double a[3][3], double v[3], double c[3]);\nvoid MatrixMultiply33(double a[3][3], double b[3][3], double c[3][3]);\nvoid MatrixTranspose33(double A[3][3]);\t\t\t\t\t/* transpose the 3x3 matrix A */\nvoid MatrixCopy33(double dest[3][3], double source[3][3]);\ndouble diff3(double a[3], double b[3]);\ndouble matsDelta(double a[3][3], double b[3][3]);\n\nchar *num2sexigesmal(char str[40], double seconds, long places);\n\n\n#endif\n", "meta": {"hexsha": "55549a6f6fcf40456aa88b437145e6a4ee48be76", "size": 2167, "ext": "h", "lang": "C", "max_stars_repo_path": "legacy/Euler3/include/mathUtil.h", "max_stars_repo_name": "carterbox/cold", "max_stars_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "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": "legacy/Euler3/include/mathUtil.h", "max_issues_repo_name": "carterbox/cold", "max_issues_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T17:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:34:20.000Z", "max_forks_repo_path": "legacy/Euler3/include/mathUtil.h", "max_forks_repo_name": "carterbox/cold", "max_forks_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T17:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T17:48:28.000Z", "avg_line_length": 31.8676470588, "max_line_length": 81, "alphanum_fraction": 0.6815874481, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6584175072643415, "lm_q1q2_score": 0.4989450809535977}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"SE_trans.h\"\n#include \"sigma.h\"\n\n#define ALPHA 0.99\n#define DOMD 3.14\n\ndouble* AllocVec(int dim)\n{\n double* vec;\n vec = (double*)calloc(dim, sizeof(double));\n\n /* Check memory */\n if (vec == NULL) {\n free(vec);\n fprintf(stderr,\"Vector was not allocated! \\n\");\n exit(1);\n }\n\n return vec; /* Return the first address of the allocated memory */\n}\n\nvoid FreeVec(double* v)\n{\n free(v);\n}\n\ndouble f(double t)\n{\n return 0.25 * ((1+t) * log1p(t) + (1-t) * log1p(-t) - 2 * M_LN2) / M_LN2;\n}\n\ndouble G(double x)\n{\n return 0.25 * x * SE_trans_div(-1, 1, x) / M_LN2;\n}\n\ndouble Fapp(double* p, double t, int m)\n{\n double h = sqrt(M_PI*DOMD / (ALPHA*m));\n\n int j;\n\n double sum = 0;\n\n for (j = -m; j <= m; j++) {\n sum += p[j+m] * gsl_sf_sinc((SE_trans_inv(-1, 1, t) - j*h) / h);\n }\n\n return sum;\n}\n\ndouble eta(double x)\n{\n return 0.5*(1 + x);\n}\n\nint main()\n{\n int i, j;\n int n, N;\n double t, h;\n double err, maxerr;\n double Iast;\n clock_t start, end;\n double time;\n double *J, *g, *c;\n\n int STEP = 1000;\n\n for (n = 3; n <= 180; n += 6) {\n start = clock();\n\n N = 2*n+1;\n J = AllocVec(N*N);\n g = AllocVec(N);\n c = AllocVec(N);\n\n h = sqrt(M_PI*DOMD / (ALPHA*n));\n\n Iast = 0;\n for (i = -n; i <= n; i++) {\n Iast += G(i*h);\n }\n Iast *= h;\n\n for (i = -n; i <= n; i++) {\n for (j = -n; j <= n; j++) {\n J[(i+n)*N + (j+n)] = 0.5 + (double)sigma_orig[1000 + (i - j)];\n }\n g[(i+n)] = G(i*h) - 0.5 * Iast * SE_trans_div(-1, 1, i*h);\n }\n\n /* c = h J g */\n cblas_dgemv(CblasRowMajor, CblasNoTrans, N, N, h, J, N, g, 1, 0.0, c, 1);\n\n maxerr = 0;\n for (i = - STEP + 1; i <= STEP - 1; i++) {\n t = (double)i / (double)(STEP);\n\n err = fabs(f(t) - Fapp(c, t, n) - Iast*eta(t));\n maxerr = fmax(err, maxerr);\n }\n end = clock();\n\n time = (double)(end - start) / CLOCKS_PER_SEC;\n printf(\"%d\\t%e\\t%e\\n\", n, err, time);\n\n FreeVec(J);\n FreeVec(g);\n FreeVec(c);\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ec7e1b977266ba0a4d3d43d1442a197ea2d89298", "size": 2126, "ext": "c", "lang": "C", "max_stars_repo_path": "Ex2SE2.c", "max_stars_repo_name": "okayamat/sinc-indef", "max_stars_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "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": "Ex2SE2.c", "max_issues_repo_name": "okayamat/sinc-indef", "max_issues_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "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": "Ex2SE2.c", "max_forks_repo_name": "okayamat/sinc-indef", "max_forks_repo_head_hexsha": "7a05757979d9d5178bda879bcd9dc8ebac5c05e9", "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.7166666667, "max_line_length": 77, "alphanum_fraction": 0.512229539, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4988423922459654}} {"text": "/* These functions compute linear preprocessing for\n the UE using LAPACKE and CBLAS modules of\n LAPACK libraries.\n MMSE and MMSE whitening filters are available.\n Functions are using RowMajor storage of the\n matrices, like in conventional C. Traditional\n Fortran functions of LAPACK employ ColumnMajor\n data storage. */\n\n#include\n#include\n#include\n#include \n#include \n#include \n#include \n#if RHEL_RELEASE_CODE >= 1796\n #include \n #include \n#else\n #include \n #include \n#endif\n//#define DEBUG_PREPROC\n\n\nvoid transpose(int N, float complex *A, float complex *Result)\n{\n // COnputes C := alpha*op(A)*op(B) + beta*C,\n enum CBLAS_TRANSPOSE transa = CblasTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = N; // number of rows in op(A) and in C\n int col_opB = N; //number of columns of op(B) and in C\n int col_opA = N; //number of columns in op(A) and rows in op(B)\n int col_B; //number of columns in B\n float complex alpha = 1.0 + I * 0;\n int lda = rows_opA;\n float complex beta = 0.0 + I * 0;\n int ldc = rows_opA;\n int i;\n float complex *B;\n\n int ldb = col_opB;\n\n if(transb == CblasNoTrans)\n {\n B = (float complex *)calloc(ldb * col_opB, sizeof(float complex));\n col_B = col_opB;\n }\n else\n {\n B = (float complex *)calloc(ldb * col_opA, sizeof(float complex));\n col_B = col_opA;\n }\n float complex *C = (float complex *)malloc(ldc * col_opB * sizeof(float complex));\n\n for(i = 0; i < lda * col_B; i += N + 1)\n {\n B[i] = 1.0 + I * 0;\n }\n\n cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc);\n\n memcpy(Result, C, N * N * sizeof(float complex));\n\n free(B);\n free(C);\n}\n\n\nvoid conjugate_transpose(int N, float complex *A, float complex *Result)\n{\n // Computes C := alpha*op(A)*op(B) + beta*C,\n enum CBLAS_TRANSPOSE transa = CblasConjTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = N; // number of rows in op(A) and in C\n int col_opB = N; //number of columns of op(B) and in C\n int col_opA = N; //number of columns in op(A) and rows in op(B)\n int col_B; //number of columns in B\n float complex alpha = 1.0 + I * 0;\n int lda = rows_opA;\n float complex beta = 0.0 + I * 0;\n int ldc = rows_opA;\n int i;\n float complex *B;\n int ldb = col_opB;\n\n if(transb == CblasNoTrans)\n {\n B = (float complex *)calloc(ldb * col_opB, sizeof(float complex));\n col_B = col_opB;\n }\n else\n {\n B = (float complex *)calloc(ldb * col_opA, sizeof(float complex));\n col_B = col_opA;\n }\n float complex *C = (float complex *)malloc(ldc * col_opB * sizeof(float complex));\n\n for(i = 0; i < lda * col_B; i += N + 1)\n {\n B[i] = 1.0 + I * 0;\n }\n\n cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc);\n\n memcpy(Result, C, N * N * sizeof(float complex));\n\n free(B);\n free(C);\n}\n\nvoid H_hermH_plus_sigma2I(int N, int M, float complex *A, float sigma2, float complex *Result)\n{\n //C := alpha*op(A)*op(B) + beta*C,\n enum CBLAS_TRANSPOSE transa = CblasConjTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = N; // number of rows in op(A) and in C\n int col_opB = N; //number of columns of op(B) and in C\n int col_opA = N; //number of columns in op(A) and rows in op(B)\n int col_C = N; //number of columns in B\n float complex alpha = 1.0 + I * 0;\n int lda = col_opA;\n float complex beta = 1.0 + I * 0;\n int ldc = col_opA;\n int i;\n\n float complex *C = (float complex *)calloc(ldc * col_opB, sizeof(float complex));\n\n for(i = 0; i < lda * col_C; i += N + 1)\n {\n C[i] = sigma2 * (1.0 + I * 0);\n }\n\n cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, A, lda, &beta, C, ldc);\n\n memcpy(Result, C, N * M * sizeof(float complex));\n free(C);\n\n}\n\nvoid HH_herm_plus_sigma2I(int M, int N, float complex *A, float sigma2, float complex *Result)\n{\n //C := alpha*op(A)*op(B) + beta*C,\n enum CBLAS_TRANSPOSE transa = CblasNoTrans;\n enum CBLAS_TRANSPOSE transb = CblasConjTrans;\n int k = N; //number of columns in op(A) and rows in op(B),k\n float complex alpha = 1.0 + I * 0;\n int lda = N;\n int ldb = N;\n int ldc = M;\n int i;\n\n float complex *C = (float complex *)calloc(M * M, sizeof(float complex));\n\n for(i = 0; i < M * M; i += M + 1)\n {\n C[i] = 1.0 + I * 0;\n }\n\n cblas_cgemm(CblasRowMajor, transa, transb, M, M, k, &alpha, A, lda, A, ldb, &sigma2, C, ldc);\n\n memcpy(Result, C, M * M * sizeof(float complex));\n free(C);\n\n}\n\nvoid eigen_vectors_values(int N, float complex *A, float complex *Vectors, float *Values_Matrix)\n{\n // This function computes ORTHONORMAL eigenvectors and eigenvalues of matrix A,\n // where Values_Matrix is a diagonal matrix of eigenvalues.\n // A=Vectors*Values_Matrix*Vectors'\n char jobz = 'V';\n char uplo = 'U';\n int order_A = N;\n int lda = N;\n int i;\n float *Values = (float *)malloc(sizeof(float) * 1 * N);\n\n LAPACKE_cheev(LAPACK_ROW_MAJOR, jobz, uplo, order_A, A, lda, Values);\n\n memcpy(Vectors, A, N * N * sizeof(float complex));\n\n for(i = 0; i < lda; i += 1)\n {\n Values_Matrix[i * (lda + 1)] = Values[i];\n }\n\n free(Values);\n}\n\nvoid lin_eq_solver(int N, float complex *A, float complex *B, float complex *Result)\n{\n int n = N;\n int lda = N;\n int ldb = N;\n int nrhs = N;\n\n char transa = 'N';\n int *IPIV = malloc(N * N * sizeof(int));\n\n // Compute LU-factorization\n LAPACKE_cgetrf(LAPACK_ROW_MAJOR, n, nrhs, A, lda, IPIV);\n\n // Solve AX=B\n LAPACKE_cgetrs(LAPACK_ROW_MAJOR, transa, n, nrhs, A, lda, IPIV, B, ldb);\n\n // cgetrs( \"N\", N, 4, A, lda, IPIV, B, ldb, INFO )\n\n memcpy(Result, B, N * N * sizeof(float complex));\n\n free(IPIV);\n\n}\n\nvoid mutl_matrix_matrix_row_based(float complex *M0, float complex *M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex *Result)\n{\n enum CBLAS_TRANSPOSE transa = CblasNoTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = rows_M0; // number of rows in op(A) and in C\n int col_opB = col_M1; //number of columns of op(B) and in C\n int col_opA = col_M0; //number of columns in op(A) and rows in op(B)\n float complex alpha = 1.0;\n int lda = col_M0;\n float complex beta = 0.0;\n int ldc = col_M1;\n int ldb = col_M1;\n\n#ifdef DEBUG_PREPROC\n int i = 0;\n printf(\"rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\\n\", rows_M0, col_M0, rows_M1, col_M1);\n\n for(i = 0; i < rows_M0 * col_M0; ++i)\n {\n printf(\" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\\n\", rows_opA, col_opB, i, creal(M0[i]), cimag(M0[i]));\n }\n\n for(i = 0; i < rows_M1 * col_M1; ++i)\n {\n printf(\" M1[%d] = (%f + i%f)\\n\", i, creal(M1[i]), cimag(M1[i]));\n }\n#endif\n\n cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc);\n\n#ifdef DEBUG_PREPROC\n for(i = 0; i < rows_opA * col_opB; ++i)\n {\n printf(\" result[%d] = (%f + i%f)\\n\", i, creal(Result[i]), cimag(Result[i]));\n }\n#endif\n\n}\nvoid mutl_matrix_matrix_col_based(float complex *M0, float complex *M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex *Result)\n{\n enum CBLAS_TRANSPOSE transa = CblasNoTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = rows_M0; // number of rows in op(A) and in C\n int col_opB = col_M1; //number of columns of op(B) and in C\n int col_opA = col_M0; //number of columns in op(A) and rows in op(B)\n float complex alpha = 1.0;\n int lda = col_M0;\n float complex beta = 0.0;\n int ldc = rows_M1;\n int ldb = rows_M1;\n\n#ifdef DEBUG_PREPROC\n int i = 0;\n printf(\"rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\\n\", rows_M0, col_M0, rows_M1, col_M1);\n\n for(i = 0; i < rows_M0 * col_M0; ++i)\n {\n printf(\" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\\n\", rows_opA, col_opB, i, creal(M0[i]), cimag(M0[i]));\n }\n\n\n for(i = 0; i < rows_M1 * col_M1; ++i)\n {\n printf(\" M1[%d] = (%f + i%f)\\n\", i, creal(M1[i]), cimag(M1[i]));\n }\n#endif\n\n cblas_cgemm(CblasColMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc);\n\n#ifdef DEBUG_PREPROC\n for(i = 0; i < rows_opA * col_opB; ++i)\n {\n printf(\" result[%d] = (%f + i%f)\\n\", i, creal(Result[i]), cimag(Result[i]));\n }\n#endif\n}\n\n\n/*FILTERS */\nvoid compute_MMSE(float complex *H, int order_H, float sigma2, float complex *W_MMSE)\n{\n int N = order_H;\n float complex *H_hermH_sigmaI = malloc(N * N * sizeof(float complex));\n float complex *H_herm = malloc(N * N * sizeof(float complex));\n\n H_hermH_plus_sigma2I(N, N, H, sigma2, H_hermH_sigmaI);\n\n#ifdef DEBUG_PREPROC\n int i = 0;\n for(i = 0; i < N * N; i++)\n {\n printf(\" H_hermH_sigmaI[%d] = (%f + i%f)\\n\", i, creal(H_hermH_sigmaI[i]), cimag(H_hermH_sigmaI[i]));\n }\n#endif\n\n conjugate_transpose(N, H, H_herm); //equals H_herm\n\n#ifdef DEBUG_PREPROC\n for(i = 0; i < N * N; i++)\n {\n printf(\" H_herm[%d] = (%f + i%f)\\n\", i, creal(H_herm[i]), cimag(H_herm[i]));\n }\n#endif\n\n lin_eq_solver(N, H_hermH_sigmaI, H_herm, W_MMSE);\n\n#ifdef DEBUG_PREPROC\n for(i = 0; i < N * N; i++)\n {\n printf(\" W_MMSE[%d] = (%f + i%f)\\n\", i, creal(W_MMSE[i]), cimag(W_MMSE[i]));\n }\n#endif\n\n free(H_hermH_sigmaI);\n free(H_herm);\n}\n\n\nfloat sqrt_float(float x, float sqrt_x)\n{\n sqrt_x = (float)(sqrt((double)(x)));\n return sqrt_x;\n}\n", "meta": {"hexsha": "0f7863384cb25cdbf0768d3a670da7a506919bdb", "size": 9871, "ext": "c", "lang": "C", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_stars_repo_name": "AManTw/oai5g", "max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_issues_repo_name": "AManTw/oai5g", "max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_forks_repo_name": "AManTw/oai5g", "max_forks_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1179941003, "max_line_length": 144, "alphanum_fraction": 0.6040927971, "num_tokens": 3344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4983982081233217}} {"text": "/**\n* @license Apache-2.0\n*\n* Copyright (c) 2018 The Stdlib Authors.\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#include \n#include \n\nint main() {\n\tdouble A[ 6 ] = { 1.0, 2.0, 1.0, -3.0, 4.0, -1.0 };\n\tdouble B[ 6 ] = { 1.0, 2.0, 1.0, -3.0, 4.0, -1.0 };\n\tdouble C[ 9 ] = { 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 };\n\tint i = 0;\n\n\tcblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans, 3, 3, 2, 1, A, 3, B, 3, 2, C, 3 );\n\n\tfor( i = 0; i < 9; i++ ) {\n\t\tprintf( \"%lf \", C[ i ] );\n\t}\n\tprintf( \"\\n\" );\n}\n", "meta": {"hexsha": "275da67cf30ef070c10787983b69afc60bf36d28", "size": 1024, "ext": "c", "lang": "C", "max_stars_repo_path": "deps/test/openblas/test_install.c", "max_stars_repo_name": "ghalimi/stdlib", "max_stars_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3428.0, "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:48:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:32:13.000Z", "max_issues_repo_path": "deps/test/openblas/test_install.c", "max_issues_repo_name": "ghalimi/stdlib", "max_issues_repo_head_hexsha": "88f50b88aa945875ef053e2f89d26f9150a18c12", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 435.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T18:12:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T15:43:17.000Z", "max_forks_repo_path": "deps/test/openblas/test_install.c", "max_forks_repo_name": "sthagen/stdlib", "max_forks_repo_head_hexsha": "042b6215818db0e2a784e72c7e054167dcefcd2a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 188.0, "max_forks_repo_forks_event_min_datetime": "2016-11-29T22:58:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T06:46:43.000Z", "avg_line_length": 29.2571428571, "max_line_length": 89, "alphanum_fraction": 0.6318359375, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.4981325098866607}} {"text": "/* multifit_nlinear/nielsen.c\n * \n * Copyright (C) 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * This module contains routines for updating the Levenberg-Marquardt\n * damping parameter on each iteration using Nielsen's method:\n *\n * [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and\n * Data Fitting, Informatics and Mathematical Modeling,\n * Technical University of Denmark (DTU), 2010.\n *\n * 5 routines are needed to implement the update procedure:\n *\n * 1. accept - update parameter after a step has been accepted\n * 2. reject - update parameter after a step has been rejected\n * 3. free - free workspace state\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define LM_ONE_THIRD (0.333333333333333)\n\nstatic int nielsen_init(const gsl_matrix * J, const gsl_vector * diag,\n double * mu, long * nu);\nstatic int nielsen_accept(const double rho, double * mu, long * nu);\nstatic int nielsen_reject(double * mu, long * nu);\n\nstatic int\nnielsen_init(const gsl_matrix * J, const gsl_vector * diag,\n double * mu, long * nu)\n{\n const double mu0 = 1.0e-3;\n const size_t p = J->size2;\n size_t j;\n double max = -1.0;\n\n *nu = 2;\n\n /* set mu = mu0 * max(diag(J~^T J~)), with J~ = J D^{-1} */\n\n for (j = 0; j < p; ++j)\n {\n gsl_vector_const_view v = gsl_matrix_const_column(J, j);\n double dj = gsl_vector_get(diag, j);\n double norm = gsl_blas_dnrm2(&v.vector) / dj;\n max = GSL_MAX(max, norm);\n }\n\n *mu = mu0 * max * max;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nnielsen_accept(const double rho, double * mu, long * nu)\n{\n double b;\n \n /* reset nu */\n *nu = 2;\n\n b = 2.0 * rho - 1.0;\n b = 1.0 - b*b*b;\n *mu *= GSL_MAX(LM_ONE_THIRD, b);\n\n return GSL_SUCCESS;\n}\n\nstatic int\nnielsen_reject(double * mu, long * nu)\n{\n *mu *= (double) *nu;\n\n /* nu := 2*nu */\n *nu <<= 1;\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "73c0f15031f5f1aeb4944ee69c12a2109a56a361", "size": 2770, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/nielsen.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/nielsen.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/nielsen.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.1568627451, "max_line_length": 81, "alphanum_fraction": 0.6696750903, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.49813250115112073}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"util.h\"\n\n\n\nint main(int argc, char *argv[]) {\n char* input_fileName1 = argv[1];\n char* input_fileName2 = argv[2];\n int N_doc_bg = atoi(argv[3]);\n int N_kw = atoi(argv[4]);\n int N_obs = atoi(argv[5]);\n int N_iter = atoi(argv[6]);\n char* output_fileName = argv[7];\n int N_doc = 480000 / 2;\n\n int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw);\n int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* true_index = (int*) malloc(sizeof(int) * N_kw);\n int* permutation = (int*) malloc(sizeof(int) * N_obs);\n gsl_matrix* matrix_obs;\n\n\n for (int round = 0; round < 10; round++)\n {\n char input_fileName1_extend[40];\n char input_fileName2_extend[40];\n sprintf(input_fileName1_extend, \"%s%d\", input_fileName1, round);\n sprintf(input_fileName2_extend, \"%s%d\", input_fileName2, round);\n \n // Setup\n struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);\n read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);\n gettimeofday(&tv2, NULL);\n printf(\"Reading done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n // compute the maximum frequency of a keyword\n int freq_max = 0;\n for (int ii = 0; ii < N_kw; ii++)\n if (matrix_bg[ii*N_kw+ii] > freq_max)\n freq_max = matrix_bg[ii*N_kw+ii];\n for (int ii = 0; ii < N_obs; ii++)\n if (matrix[ii*N_obs+ii] > freq_max)\n freq_max = matrix[ii*N_obs+ii];\n printf(\"Max frequency: %d\\n\", freq_max);\n \n\n for (int iter = 0; iter < 10; iter++)\n {\n printf(\"Run %d\\n\", iter);\n matrix_obs = gsl_matrix_alloc(N_obs, N_obs);\n\n gettimeofday(&tv1, NULL);\n pad_matrix(&matrix_padded, &matrix, N_obs, N_doc, freq_max);\n gettimeofday(&tv2, NULL);\n printf(\"Padding done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n gettimeofday(&tv1, NULL);\n observe_matrix(matrix_obs, &matrix_padded, N_obs);\n gettimeofday(&tv2, NULL);\n printf(\"Observed matrix generated: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n\n // Permute observed matrix randomly and attack\n gettimeofday(&tv1, NULL);\n attack(matrix_obs, &matrix_bg, &permutation, N_kw, N_obs, N_doc, freq_max, N_iter);\n gettimeofday(&tv2, NULL);\n printf(\"Main attack done: %d.\\n\", (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n char output_fileName_full[40];\n sprintf(output_fileName_full, \"%s%d-%d\", output_fileName, round, iter);\n print_result(output_fileName_full, &permutation, &true_index, N_obs);\n //sprintf(output_fileName_full, \"%s%d-%d-full\", output_fileName, round, iter);\n //print_full_result(output_fileName_full, &permutation, &true_index, N_obs);\n }\n }\n\n\n free(matrix);\n free(matrix_padded);\n gsl_matrix_free(matrix_obs);\n return(0);\n}\n\n\ndouble log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc, int freq_max)\n{\n if (idx1 == idx2)\n return(0.0);\n\n\n int idx1_m = (*permutation)[idx1];\n int idx2_m = (*permutation)[idx2];\n\n int n1 = 2*freq_max - (*matrix)[idx1_m*N_kw + idx1_m];\n int n2 = 2*freq_max - (*matrix)[idx2_m*N_kw + idx2_m];\n\n /*\n int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);\n int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;\n N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;\n int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n\n double score = 0;\n double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc;\n for (int kk = N_lower; kk < N_upper+1; kk+=20)\n score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_hypergeometric_pdf(count_total - kk, n1, 2*N_doc - n1, n2);\n */\n\n double mean = 1.0 * freq_max / N_doc * (n1 + n2);\n double var = 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n var += 1.0 * n1 / N_doc * freq_max * (2 * N_doc - 2*freq_max) / N_doc;\n var += 1.0 * n2 / N_doc * freq_max * (2 * N_doc - 2*freq_max) / N_doc;\n int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n\n int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);\n int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;\n N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;\n\n\n mean += (*matrix)[idx1_m*N_kw + idx2_m];\n var += (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n\n double score = gsl_ran_gaussian_pdf(count_total - mean, sqrt(var));\n\n if (score == 0)\n return(-500.0);\n return(log(score));\n}\n\n\n\n\nvoid attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, int freq_max, int N_iter)\n{\n // Initialise data structures\n double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs);\n double* score_row1 = (double*) malloc(sizeof(double) * N_obs);\n double* score_row2 = (double*) malloc(sizeof(double) * N_obs);\n\n int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);\n int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);\n\n // Initialise permutations\n for (int ii = 0; ii < N_obs; ii++)\n (*permutation)[ii] = ii;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_tmp[ii] = ii;\n for (int ii = 0; ii < N_kw; ii++)\n permutation_inv[ii] = -1;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_inv[permutation_tmp[ii]] = ii;\n\n // Initialising RNG\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 struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n\n // Compute initial score\n #pragma omp parallel for shared(score_matrix, matrix_obs, matrix)\n for (int ii = 0; ii < N_obs * N_obs; ii++)\n score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc, freq_max);\n gettimeofday(&tv2, NULL);\n printf(\"Initial score computed: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n \n // Iterations of simulated annealing\n double temp = (double) N_kw;\n int N_stuck = 0;\n for (int iter = 0; iter < N_iter; iter++)\n {\n /* Status code */\n if (iter % (N_iter / 10) == 0)\n {\n gettimeofday(&tv1, NULL);\n printf(\"Iteration: %d, %d, %d.\\n\", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));\n fflush(stdout);\n gettimeofday(&tv2, NULL);\n }\n\n\t // used to be 20k\n if (N_stuck >= 80000)\n iter = N_iter;\n\n /* Main code */\n int idx1, idx2;\n permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, N_kw, N_obs);\n\n int ii = 0;\n #pragma omp parallel for shared(score_row1)\n for (ii = 0; ii < N_obs; ii++)\n score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, freq_max);\n\n if (idx2 >= 0)\n #pragma omp parallel for shared(score_row2)\n for (ii = 0; ii < N_obs; ii++)\n score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, freq_max);\n\n\n\n double score_diff = 0;\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx1*N_obs + ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx2*N_obs + ii];\n }\n\n // compute difference in score, with exponentiation\n score_diff = score_diff / temp;\n \n if (score_diff < -40)\n score_diff = 0;\n else if (score_diff > 0)\n score_diff = 1.01;\n else\n score_diff = exp(score_diff);\n\n if (gsl_ran_flat(r, 0, 1) < score_diff)\n {\n // Update the scores\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx1*N_obs + ii] = score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx1] = score_row1[ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx2*N_obs + ii] = score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx2] = score_row2[ii];\n }\n\n // Update the permutation\n permutation_inv[(*permutation)[idx1]] = -1;\n (*permutation)[idx1] = permutation_tmp[idx1];\n permutation_inv[permutation_tmp[idx1]] = idx1;\n if (idx2 >= 0)\n {\n (*permutation)[idx2] = permutation_tmp[idx2];\n permutation_inv[permutation_tmp[idx2]] = idx2;\n }\n N_stuck = 0; \n }\n else\n {\n // Update the permutation\n permutation_tmp[idx1] = (*permutation)[idx1];\n if (idx2 >= 0)\n permutation_tmp[idx2] = (*permutation)[idx2];\n N_stuck += 1;\n }\n\n temp *= 0.995;\n }\n\n free(score_matrix);\n free(score_row1);\n free(score_row2);\n gsl_rng_free(r);\n}\n\n\n\nvoid print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n fprintf(fp, \"%d\\n\", count);\n fclose(fp);\n printf(\"Success: %d/%d.\\n\", count, N_obs);\n}\n\n\n\nvoid print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n printf(\"Success: %d/%d.\\n\", count, N_obs);\n fprintf(fp, \"%d\\n\", count);\n for (int ii = 0; ii < N_obs; ii++)\n fprintf(fp, \"%d,%d\\n\", (*permutation)[ii], (*true_index)[ii]);\n\n\n fclose(fp);\n}", "meta": {"hexsha": "b6f0feacba7587329611e9b25cb6e88463d11b29", "size": 11144, "ext": "c", "lang": "C", "max_stars_repo_path": "FP-EMM/attack_mp.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "FP-EMM/attack_mp.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "FP-EMM/attack_mp.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.7165109034, "max_line_length": 140, "alphanum_fraction": 0.5677494616, "num_tokens": 3255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.49751942836626856}} {"text": "#include \n#include \n#include \n#include \"extra_compile_macros.h\"\n\n#if USE_GSL == 1\n#include \n#endif\n\ndouble nan_density(double t, double *pars, double *q, int n_dim) { return NAN; }\ndouble nan_value(double t, double *pars, double *q, int n_dim) { return NAN; }\nvoid nan_gradient(double t, double *pars, double *q, int n_dim, double *grad) {}\nvoid nan_hessian(double t, double *pars, double *q, int n_dim, double *hess) {}\n\ndouble null_density(double t, double *pars, double *q, int n_dim) { return 0; }\ndouble null_value(double t, double *pars, double *q, int n_dim) { return 0; }\nvoid null_gradient(double t, double *pars, double *q, int n_dim, double *grad){}\nvoid null_hessian(double t, double *pars, double *q, int n_dim, double *hess) {}\n\n/* Note: many Hessians generated with sympy in\n gala-notebooks/Make-all-Hessians.ipynb\n*/\n\n/* ---------------------------------------------------------------------------\n Henon-Heiles potential\n*/\ndouble henon_heiles_value(double t, double *pars, double *q, int n_dim) {\n /* no parameters... */\n return 0.5 * (q[0]*q[0] + q[1]*q[1] + 2*q[0]*q[0]*q[1] - 2/3.*q[1]*q[1]*q[1]);\n}\n\nvoid henon_heiles_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* no parameters... */\n grad[0] = grad[0] + q[0] + 2*q[0]*q[1];\n grad[1] = grad[1] + q[1] + q[0]*q[0] - q[1]*q[1];\n}\n\nvoid henon_heiles_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* no parameters... */\n double x = q[0];\n double y = q[1];\n\n double tmp_0 = 2.0 * y;\n double tmp_1 = 2.0 * x;\n\n hess[0] = hess[0] + tmp_0 + 1.0;\n hess[1] = hess[1] + tmp_1;\n hess[2] = hess[2] + tmp_1;\n hess[3] = hess[3] + 1.0 - tmp_0;\n}\n\n/* ---------------------------------------------------------------------------\n Kepler potential\n*/\ndouble kepler_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n */\n double R;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n return -pars[0] * pars[1] / R;\n}\n\nvoid kepler_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n */\n double R, fac;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n fac = pars[0] * pars[1] / (R*R*R);\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2];\n}\n\ndouble kepler_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n */\n double r2;\n r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n\n if (r2 == 0.) {\n return INFINITY;\n } else {\n return 0.;\n }\n}\n\nvoid kepler_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n */\n double G = pars[0];\n double m = pars[1];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = G*m;\n double tmp_5 = tmp_4/pow(tmp_3, 3.0/2.0);\n double tmp_6 = 3*tmp_4/pow(tmp_3, 5.0/2.0);\n double tmp_7 = tmp_6*x;\n double tmp_8 = -tmp_7*y;\n double tmp_9 = -tmp_7*z;\n double tmp_10 = -tmp_6*y*z;\n\n hess[0] = hess[0] + -tmp_0*tmp_6 + tmp_5;\n hess[1] = hess[1] + tmp_8;\n hess[2] = hess[2] + tmp_9;\n hess[3] = hess[3] + tmp_8;\n hess[4] = hess[4] + -tmp_1*tmp_6 + tmp_5;\n hess[5] = hess[5] + tmp_10;\n hess[6] = hess[6] + tmp_9;\n hess[7] = hess[7] + tmp_10;\n hess[8] = hess[8] + -tmp_2*tmp_6 + tmp_5;\n}\n\n/* ---------------------------------------------------------------------------\n Isochrone potential\n*/\ndouble isochrone_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (core scale)\n */\n double R2;\n R2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n return -pars[0] * pars[1] / (sqrt(R2 + pars[2]*pars[2]) + pars[2]);\n}\n\nvoid isochrone_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (core scale)\n */\n double sqrt_r2_b2, fac, denom;\n sqrt_r2_b2 = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*pars[2]);\n denom = sqrt_r2_b2 * (sqrt_r2_b2 + pars[2])*(sqrt_r2_b2 + pars[2]);\n fac = pars[0] * pars[1] / denom;\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2];\n}\n\ndouble isochrone_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (core scale)\n */\n double r2, a, b;\n b = pars[2];\n r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n a = sqrt(b*b + r2);\n\n return pars[1] * (3*(b+a)*a*a - r2*(b+3*a)) / (4*M_PI*pow(b+a,3)*a*a*a);\n}\n\nvoid isochrone_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (length scale)\n */\n double G = pars[0];\n double m = pars[1];\n double b = pars[2];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = pow(b, 2) + tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = sqrt(tmp_3);\n double tmp_5 = b + tmp_4;\n double tmp_6 = G*m;\n double tmp_7 = tmp_6/pow(tmp_5, 2);\n double tmp_8 = tmp_7/tmp_4;\n double tmp_9 = 2*tmp_6/(tmp_3*pow(tmp_5, 3));\n double tmp_10 = tmp_7/pow(tmp_3, 3.0/2.0);\n double tmp_11 = tmp_9*x;\n double tmp_12 = tmp_10*x;\n double tmp_13 = -tmp_11*y - tmp_12*y;\n double tmp_14 = -tmp_11*z - tmp_12*z;\n double tmp_15 = y*z;\n double tmp_16 = -tmp_10*tmp_15 - tmp_15*tmp_9;\n\n hess[0] = hess[0] + -tmp_0*tmp_10 - tmp_0*tmp_9 + tmp_8;\n hess[1] = hess[1] + tmp_13;\n hess[2] = hess[2] + tmp_14;\n hess[3] = hess[3] + tmp_13;\n hess[4] = hess[4] + -tmp_1*tmp_10 - tmp_1*tmp_9 + tmp_8;\n hess[5] = hess[5] + tmp_16;\n hess[6] = hess[6] + tmp_14;\n hess[7] = hess[7] + tmp_16;\n hess[8] = hess[8] + -tmp_10*tmp_2 - tmp_2*tmp_9 + tmp_8;\n\n}\n\n/* ---------------------------------------------------------------------------\n Hernquist sphere\n*/\ndouble hernquist_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double R;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n return -pars[0] * pars[1] / (R + pars[2]);\n}\n\nvoid hernquist_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double R, fac;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n fac = pars[0] * pars[1] / ((R + pars[2]) * (R + pars[2]) * R);\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2];\n}\n\ndouble hernquist_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double r, rho0;\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n rho0 = pars[1]/(2*M_PI*pars[2]*pars[2]*pars[2]);\n return rho0 / ((r/pars[2]) * pow(1+r/pars[2],3));\n}\n\nvoid hernquist_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double G = pars[0];\n double m = pars[1];\n double c = pars[2];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = sqrt(tmp_3);\n double tmp_5 = c + tmp_4;\n double tmp_6 = G*m;\n double tmp_7 = tmp_6/pow(tmp_5, 2);\n double tmp_8 = tmp_7/tmp_4;\n double tmp_9 = 2*tmp_6/(tmp_3*pow(tmp_5, 3));\n double tmp_10 = tmp_7/pow(tmp_3, 3.0/2.0);\n double tmp_11 = tmp_9*x;\n double tmp_12 = tmp_10*x;\n double tmp_13 = -tmp_11*y - tmp_12*y;\n double tmp_14 = -tmp_11*z - tmp_12*z;\n double tmp_15 = y*z;\n double tmp_16 = -tmp_10*tmp_15 - tmp_15*tmp_9;\n\n hess[0] = hess[0] + -tmp_0*tmp_10 - tmp_0*tmp_9 + tmp_8;\n hess[1] = hess[1] + tmp_13;\n hess[2] = hess[2] + tmp_14;\n hess[3] = hess[3] + tmp_13;\n hess[4] = hess[4] + -tmp_1*tmp_10 - tmp_1*tmp_9 + tmp_8;\n hess[5] = hess[5] + tmp_16;\n hess[6] = hess[6] + tmp_14;\n hess[7] = hess[7] + tmp_16;\n hess[8] = hess[8] + -tmp_10*tmp_2 - tmp_2*tmp_9 + tmp_8;\n}\n\n\n/* ---------------------------------------------------------------------------\n Plummer sphere\n*/\ndouble plummer_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (length scale)\n */\n double R2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n return -pars[0]*pars[1] / sqrt(R2 + pars[2]*pars[2]);\n}\n\nvoid plummer_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (length scale)\n */\n double R2b, fac;\n R2b = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*pars[2];\n fac = pars[0] * pars[1] / sqrt(R2b) / R2b;\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2];\n}\n\ndouble plummer_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (length scale)\n */\n double r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n return 3*pars[1] / (4*M_PI*pars[2]*pars[2]*pars[2]) * pow(1 + r2/(pars[2]*pars[2]), -2.5);\n}\n\nvoid plummer_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - b (length scale)\n */\n double G = pars[0];\n double m = pars[1];\n double b = pars[2];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = pow(b, 2) + tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = G*m;\n double tmp_5 = tmp_4/pow(tmp_3, 3.0/2.0);\n double tmp_6 = 3*tmp_4/pow(tmp_3, 5.0/2.0);\n double tmp_7 = tmp_6*x;\n double tmp_8 = -tmp_7*y;\n double tmp_9 = -tmp_7*z;\n double tmp_10 = -tmp_6*y*z;\n\n hess[0] = hess[0] + -tmp_0*tmp_6 + tmp_5;\n hess[1] = hess[1] + tmp_8;\n hess[2] = hess[2] + tmp_9;\n hess[3] = hess[3] + tmp_8;\n hess[4] = hess[4] + -tmp_1*tmp_6 + tmp_5;\n hess[5] = hess[5] + tmp_10;\n hess[6] = hess[6] + tmp_9;\n hess[7] = hess[7] + tmp_10;\n hess[8] = hess[8] + -tmp_2*tmp_6 + tmp_5;\n}\n\n/* ---------------------------------------------------------------------------\n Jaffe sphere\n*/\ndouble jaffe_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double R;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n return -pars[0] * pars[1] / pars[2] * log(1 + pars[2]/R);\n}\n\nvoid jaffe_gradient(double t, double *pars, double *q, int n_dim, double *grad){\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double R, fac;\n R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n fac = pars[0] * pars[1] / pars[2] * (pars[2] / (R * (pars[2] + R)));\n\n grad[0] = grad[0] + fac*q[0]/R;\n grad[1] = grad[1] + fac*q[1]/R;\n grad[2] = grad[2] + fac*q[2]/R;\n}\n\ndouble jaffe_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double r, rho0;\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n rho0 = pars[1] / (4*M_PI*pars[2]*pars[2]*pars[2]);\n return rho0 / (pow(r/pars[2],2) * pow(1+r/pars[2],2));\n}\n\nvoid jaffe_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - c (length scale)\n */\n double G = pars[0];\n double m = pars[1];\n double c = pars[2];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = 1.0/tmp_3;\n double tmp_5 = sqrt(tmp_3);\n double tmp_6 = c + tmp_5;\n double tmp_7 = pow(tmp_6, -2);\n double tmp_8 = tmp_7*x;\n double tmp_9 = 1.0/tmp_5;\n double tmp_10 = 1.0/tmp_6;\n double tmp_11 = tmp_10*tmp_9;\n double tmp_12 = G*m/c;\n double tmp_13 = tmp_12*(tmp_11*x - tmp_8);\n double tmp_14 = tmp_13*tmp_4;\n double tmp_15 = pow(tmp_3, -3.0/2.0);\n double tmp_16 = tmp_13*tmp_15*tmp_6;\n double tmp_17 = tmp_10*tmp_15;\n double tmp_18 = tmp_4*tmp_7;\n double tmp_19 = 2*tmp_9/pow(tmp_6, 3);\n double tmp_20 = tmp_11 - tmp_7;\n double tmp_21 = tmp_12*tmp_6;\n double tmp_22 = tmp_21*tmp_9;\n double tmp_23 = tmp_19*x;\n double tmp_24 = tmp_4*tmp_8;\n double tmp_25 = tmp_17*x;\n double tmp_26 = tmp_14*y - tmp_16*y + tmp_22*(tmp_23*y - tmp_24*y - tmp_25*y);\n double tmp_27 = tmp_4*z;\n double tmp_28 = tmp_13*tmp_27 - tmp_16*z + tmp_22*(tmp_23*z - tmp_24*z - tmp_25*z);\n double tmp_29 = tmp_7*y;\n double tmp_30 = tmp_11*y - tmp_29;\n double tmp_31 = tmp_12*tmp_30;\n double tmp_32 = tmp_15*tmp_21;\n double tmp_33 = tmp_30*tmp_32;\n double tmp_34 = y*z;\n double tmp_35 = tmp_22*(-tmp_17*tmp_34 + tmp_19*tmp_34 - tmp_27*tmp_29) + tmp_27*tmp_31 - tmp_33*z;\n double tmp_36 = tmp_11*z - tmp_7*z;\n\n hess[0] = hess[0] + tmp_14*x - tmp_16*x + tmp_22*(-tmp_0*tmp_17 - tmp_0*tmp_18 + tmp_0*tmp_19 + tmp_20);\n hess[1] = hess[1] + tmp_26;\n hess[2] = hess[2] + tmp_28;\n hess[3] = hess[3] + tmp_26;\n hess[4] = hess[4] + tmp_22*(-tmp_1*tmp_17 - tmp_1*tmp_18 + tmp_1*tmp_19 + tmp_20) + tmp_31*tmp_4*y - tmp_33*y;\n hess[5] = hess[5] + tmp_35;\n hess[6] = hess[6] + tmp_28;\n hess[7] = hess[7] + tmp_35;\n hess[8] = hess[8] + tmp_12*tmp_27*tmp_36 + tmp_22*(-tmp_17*tmp_2 - tmp_18*tmp_2 + tmp_19*tmp_2 + tmp_20) - tmp_32*tmp_36*z;\n}\n\n/* ---------------------------------------------------------------------------\n Power-law potential with exponential cutoff\n*/\n#if USE_GSL == 1\n\ndouble safe_gamma_inc(double a, double x) {\n int N, m, n;\n double A = 1.;\n double B = 0.;\n double tmp;\n\n if (a > 0) {\n return gsl_sf_gamma_inc_P(a, x) * gsl_sf_gamma(a);;\n } else {\n N = (int) ceil(-a);\n\n for (n=0; n < N; n++) {\n A = A * (a + n);\n\n tmp = 1.;\n for (m=N-1; m > n; m--) {\n tmp = tmp * (a + m);\n }\n B = B + pow(x, a+n) * exp(-x) * tmp;\n }\n return (B + gsl_sf_gamma_inc_P(a + N, x) * gsl_sf_gamma(a + N)) / A;\n }\n}\n\ndouble powerlawcutoff_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n 0 - G (Gravitational constant)\n 1 - m (total mass)\n 2 - a (power-law index)\n 3 - c (cutoff radius)\n */\n double G = pars[0];\n double m = pars[1];\n double alpha = pars[2];\n double r_c = pars[3];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n double r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n\n if (r == 0.) {\n return -INFINITY;\n } else {\n double tmp_0 = (1.0/2.0)*alpha;\n double tmp_1 = -tmp_0;\n double tmp_2 = tmp_1 + 1.5;\n double tmp_3 = pow(x, 2) + pow(y, 2) + pow(z, 2);\n double tmp_4 = tmp_3/pow(r_c, 2);\n double tmp_5 = G*m;\n double tmp_6 = tmp_5*safe_gamma_inc(tmp_2, tmp_4)/(sqrt(tmp_3)*tgamma(tmp_1 + 2.5));\n return tmp_0*tmp_6 - 3.0/2.0*tmp_6 + tmp_5*safe_gamma_inc(tmp_1 + 1, tmp_4)/(r_c*tgamma(tmp_2));\n }\n}\n\ndouble powerlawcutoff_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n 0 - G (Gravitational constant)\n 1 - m (total mass)\n 2 - a (power-law index)\n 3 - c (cutoff radius)\n */\n double r, A;\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n A = pars[1] / (2*M_PI) * pow(pars[3], pars[2] - 3) / gsl_sf_gamma(0.5 * (3 - pars[2]));\n return A * pow(r, -pars[2]) * exp(-r*r / (pars[3]*pars[3]));\n}\n\nvoid powerlawcutoff_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n 0 - G (Gravitational constant)\n 1 - m (total mass)\n 2 - a (power-law index)\n 3 - c (cutoff radius)\n */\n double r, dPhi_dr;\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n dPhi_dr = (pars[0] * pars[1] / (r*r) *\n gsl_sf_gamma_inc_P(0.5 * (3-pars[2]), r*r/(pars[3]*pars[3]))); // / gsl_sf_gamma(0.5 * (3-pars[2])));\n\n grad[0] = grad[0] + dPhi_dr * q[0]/r;\n grad[1] = grad[1] + dPhi_dr * q[1]/r;\n grad[2] = grad[2] + dPhi_dr * q[2]/r;\n}\n\nvoid powerlawcutoff_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - alpha (exponent)\n - r_c (cutoff radius)\n */\n double G = pars[0];\n double m = pars[1];\n double alpha = pars[2];\n double r_c = pars[3];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = (1.0/2.0)*alpha;\n double tmp_5 = -tmp_4;\n double tmp_6 = tmp_5 + 1.5;\n double tmp_7 = pow(r_c, -2);\n double tmp_8 = tmp_3*tmp_7;\n double tmp_9 = G*m;\n double tmp_10 = tmp_9/tgamma(tmp_5 + 2.5);\n double tmp_11 = tmp_10*safe_gamma_inc(tmp_6, tmp_8);\n double tmp_12 = tmp_11/pow(tmp_3, 5.0/2.0);\n double tmp_13 = (9.0/2.0)*tmp_12;\n double tmp_14 = exp(-tmp_8);\n double tmp_15 = tmp_0*tmp_14;\n double tmp_16 = pow(tmp_8, -tmp_4)*tmp_9/tgamma(tmp_6);\n double tmp_17 = 4*tmp_16/pow(r_c, 5);\n double tmp_18 = alpha*tmp_0;\n double tmp_19 = (3.0/2.0)*tmp_12;\n double tmp_20 = 6*tmp_15;\n double tmp_21 = pow(r_c, -4);\n double tmp_22 = tmp_5 + 0.5;\n double tmp_23 = pow(tmp_8, tmp_22);\n double tmp_24 = tmp_10*tmp_23/sqrt(tmp_3);\n double tmp_25 = tmp_21*tmp_24;\n double tmp_26 = pow(tmp_3, -3.0/2.0);\n double tmp_27 = tmp_10*tmp_23*tmp_26*tmp_7;\n double tmp_28 = tmp_20*tmp_27;\n double tmp_29 = 2*tmp_14;\n double tmp_30 = tmp_18*tmp_29;\n double tmp_31 = tmp_16*tmp_29/pow(r_c, 3);\n double tmp_32 = tmp_31/tmp_3;\n double tmp_33 = tmp_27*tmp_30;\n double tmp_34 = tmp_11*tmp_26;\n double tmp_35 = tmp_14*tmp_24;\n double tmp_36 = tmp_35*tmp_7;\n double tmp_37 = alpha*tmp_36 + tmp_31 - tmp_34*tmp_4 + (3.0/2.0)*tmp_34 - 3*tmp_36;\n double tmp_38 = tmp_13*x;\n double tmp_39 = alpha*tmp_19;\n double tmp_40 = x*y;\n double tmp_41 = tmp_14*tmp_17;\n double tmp_42 = alpha*tmp_40;\n double tmp_43 = tmp_21*tmp_35;\n double tmp_44 = 6*tmp_40;\n double tmp_45 = tmp_14*tmp_27;\n double tmp_46 = tmp_44*tmp_45;\n double tmp_47 = tmp_29*tmp_42;\n double tmp_48 = tmp_27*tmp_47;\n double tmp_49 = -tmp_22*tmp_46 + tmp_22*tmp_48 - tmp_25*tmp_47 - tmp_32*tmp_42 - tmp_38*y + tmp_39*tmp_40 - tmp_40*tmp_41 + tmp_43*tmp_44 + tmp_46 - tmp_48;\n double tmp_50 = x*z;\n double tmp_51 = alpha*tmp_50;\n double tmp_52 = 6*tmp_50;\n double tmp_53 = tmp_45*tmp_52;\n double tmp_54 = tmp_29*tmp_51;\n double tmp_55 = tmp_27*tmp_54;\n double tmp_56 = -tmp_22*tmp_53 + tmp_22*tmp_55 - tmp_25*tmp_54 - tmp_32*tmp_51 - tmp_38*z + tmp_39*tmp_50 - tmp_41*tmp_50 + tmp_43*tmp_52 + tmp_53 - tmp_55;\n double tmp_57 = 6*tmp_1;\n double tmp_58 = tmp_45*tmp_57;\n double tmp_59 = alpha*tmp_1;\n double tmp_60 = tmp_29*tmp_59;\n double tmp_61 = tmp_27*tmp_60;\n double tmp_62 = y*z;\n double tmp_63 = alpha*tmp_62;\n double tmp_64 = 6*tmp_62;\n double tmp_65 = tmp_45*tmp_64;\n double tmp_66 = tmp_29*tmp_63;\n double tmp_67 = tmp_27*tmp_66;\n double tmp_68 = -tmp_13*tmp_62 - tmp_22*tmp_65 + tmp_22*tmp_67 - tmp_25*tmp_66 - tmp_32*tmp_63 + tmp_39*tmp_62 - tmp_41*tmp_62 + tmp_43*tmp_64 + tmp_65 - tmp_67;\n double tmp_69 = 6*tmp_2;\n double tmp_70 = tmp_45*tmp_69;\n double tmp_71 = alpha*tmp_2;\n double tmp_72 = tmp_29*tmp_71;\n double tmp_73 = tmp_27*tmp_72;\n\n hess[0] = hess[0] + -tmp_0*tmp_13 - tmp_15*tmp_17 + tmp_18*tmp_19 - tmp_18*tmp_32 + tmp_20*tmp_25 - tmp_22*tmp_28 + tmp_22*tmp_33 - tmp_25*tmp_30 + tmp_28 - tmp_33 + tmp_37;\n hess[1] = hess[1] + tmp_49;\n hess[2] = hess[2] + tmp_56;\n hess[3] = hess[3] + tmp_49;\n hess[4] = hess[4] + -tmp_1*tmp_13 + tmp_1*tmp_39 - tmp_1*tmp_41 - tmp_22*tmp_58 + tmp_22*tmp_61 - tmp_25*tmp_60 - tmp_32*tmp_59 + tmp_37 + tmp_43*tmp_57 + tmp_58 - tmp_61;\n hess[5] = hess[5] + tmp_68;\n hess[6] = hess[6] + tmp_56;\n hess[7] = hess[7] + tmp_68;\n hess[8] = hess[8] + -tmp_13*tmp_2 + tmp_2*tmp_39 - tmp_2*tmp_41 - tmp_22*tmp_70 + tmp_22*tmp_73 - tmp_25*tmp_72 - tmp_32*tmp_71 + tmp_37 + tmp_43*tmp_69 + tmp_70 - tmp_73;\n}\n\n#endif\n\n/* ---------------------------------------------------------------------------\n Stone-Ostriker potential from Stone & Ostriker (2015)\n*/\ndouble stone_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - M (total mass)\n - r_c (core radius)\n - r_h (halo radius)\n */\n double r, u_c, u_h, fac;\n\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n u_c = r / pars[2];\n u_h = r / pars[3];\n\n fac = 2*pars[0]*pars[1] / M_PI / (pars[3] - pars[2]);\n\n return -fac * (atan(u_h)/u_h - atan(u_c)/u_c +\n 0.5*log((r*r + pars[3]*pars[3])/(r*r + pars[2]*pars[2])));\n}\n\nvoid stone_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - M (total mass)\n - r_c (core radius)\n - r_h (halo radius)\n */\n double r, u_c, u_h, fac, dphi_dr;\n\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n u_c = r / pars[2];\n u_h = r / pars[3];\n\n fac = 2*pars[0]*pars[1] / (M_PI*r*r) / (pars[2] - pars[3]); // order flipped from value\n dphi_dr = fac * (pars[2]*atan(u_c) - pars[3]*atan(u_h));\n\n grad[0] = grad[0] + dphi_dr*q[0]/r;\n grad[1] = grad[1] + dphi_dr*q[1]/r;\n grad[2] = grad[2] + dphi_dr*q[2]/r;\n}\n\ndouble stone_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - M (total mass)\n - r_c (core radius)\n - r_h (halo radius)\n */\n double r, u_c, u_t, rho;\n rho = pars[1] * (pars[2] + pars[3]) / (2*M_PI*M_PI*pars[2]*pars[2]*pars[3]*pars[3]);\n\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n u_c = r / pars[2];\n u_t = r / pars[3];\n\n return rho / ((1 + u_c*u_c)*(1 + u_t*u_t));\n}\n\nvoid stone_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_c (core radius)\n - r_h (halo radius)\n */\n double G = pars[0];\n double m = pars[1];\n double r_c = pars[2];\n double r_h = pars[3];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(r_h, 2);\n double tmp_1 = 1.0/tmp_0;\n double tmp_2 = pow(x, 2);\n double tmp_3 = pow(y, 2);\n double tmp_4 = pow(z, 2);\n double tmp_5 = tmp_2 + tmp_3 + tmp_4;\n double tmp_6 = tmp_1*tmp_5 + 1;\n double tmp_7 = 1.0/tmp_6;\n double tmp_8 = 3/pow(tmp_5, 2);\n double tmp_9 = tmp_2*tmp_8;\n double tmp_10 = pow(r_c, 2);\n double tmp_11 = 1.0/tmp_10;\n double tmp_12 = tmp_11*tmp_5 + 1;\n double tmp_13 = 1.0/tmp_12;\n double tmp_14 = tmp_10 + tmp_5;\n double tmp_15 = pow(tmp_14, -2);\n double tmp_16 = 8*tmp_15;\n double tmp_17 = tmp_0 + tmp_5;\n double tmp_18 = 8*tmp_17/pow(tmp_14, 3);\n double tmp_19 = 2/tmp_14;\n double tmp_20 = 2*tmp_15*tmp_17;\n double tmp_21 = tmp_19 - tmp_20;\n double tmp_22 = 1.0/tmp_17;\n double tmp_23 = 0.5*tmp_14*tmp_22;\n double tmp_24 = tmp_19*x - tmp_20*x;\n double tmp_25 = 1.0*tmp_22;\n double tmp_26 = tmp_24*tmp_25;\n double tmp_27 = sqrt(tmp_5);\n double tmp_28 = r_c*atan(tmp_27/r_c);\n double tmp_29 = 3/pow(tmp_5, 5.0/2.0);\n double tmp_30 = tmp_2*tmp_29;\n double tmp_31 = 1.0/tmp_5;\n double tmp_32 = 2*tmp_31;\n double tmp_33 = tmp_2*tmp_32;\n double tmp_34 = tmp_1/pow(tmp_6, 2);\n double tmp_35 = tmp_11/pow(tmp_12, 2);\n double tmp_36 = r_h*atan(tmp_27/r_h);\n double tmp_37 = 1.0*tmp_14/pow(tmp_17, 2);\n double tmp_38 = tmp_24*tmp_37;\n double tmp_39 = pow(tmp_5, -3.0/2.0);\n double tmp_40 = -tmp_13*tmp_31 + tmp_28*tmp_39 + tmp_31*tmp_7 - tmp_36*tmp_39;\n double tmp_41 = 2*G*m/(-3.1415926535897931*r_c + 3.1415926535897931*r_h);\n double tmp_42 = x*y;\n double tmp_43 = tmp_42*tmp_8;\n double tmp_44 = tmp_29*tmp_42;\n double tmp_45 = tmp_32*tmp_42;\n double tmp_46 = tmp_16*x;\n double tmp_47 = -tmp_41*(tmp_13*tmp_43 + tmp_23*(tmp_18*tmp_42 - tmp_46*y) + tmp_26*y - tmp_28*tmp_44 - tmp_34*tmp_45 + tmp_35*tmp_45 + tmp_36*tmp_44 - tmp_38*y - tmp_43*tmp_7);\n double tmp_48 = x*z;\n double tmp_49 = tmp_48*tmp_8;\n double tmp_50 = tmp_29*tmp_48;\n double tmp_51 = tmp_32*tmp_48;\n double tmp_52 = -tmp_41*(tmp_13*tmp_49 + tmp_23*(tmp_18*tmp_48 - tmp_46*z) + tmp_26*z - tmp_28*tmp_50 - tmp_34*tmp_51 + tmp_35*tmp_51 + tmp_36*tmp_50 - tmp_38*z - tmp_49*tmp_7);\n double tmp_53 = tmp_3*tmp_8;\n double tmp_54 = tmp_19*y - tmp_20*y;\n double tmp_55 = tmp_25*tmp_54;\n double tmp_56 = tmp_29*tmp_3;\n double tmp_57 = tmp_3*tmp_32;\n double tmp_58 = tmp_37*tmp_54;\n double tmp_59 = y*z;\n double tmp_60 = tmp_59*tmp_8;\n double tmp_61 = tmp_29*tmp_59;\n double tmp_62 = tmp_32*tmp_59;\n double tmp_63 = -tmp_41*(tmp_13*tmp_60 + tmp_23*(-tmp_16*tmp_59 + tmp_18*tmp_59) - tmp_28*tmp_61 - tmp_34*tmp_62 + tmp_35*tmp_62 + tmp_36*tmp_61 + tmp_55*z - tmp_58*z - tmp_60*tmp_7);\n double tmp_64 = tmp_4*tmp_8;\n double tmp_65 = z*(tmp_19*z - tmp_20*z);\n double tmp_66 = tmp_29*tmp_4;\n double tmp_67 = tmp_32*tmp_4;\n\n hess[0] = hess[0] + -tmp_41*(tmp_13*tmp_9 + tmp_23*(-tmp_16*tmp_2 + tmp_18*tmp_2 + tmp_21) + tmp_26*x - tmp_28*tmp_30 + tmp_30*tmp_36 - tmp_33*tmp_34 + tmp_33*tmp_35 - tmp_38*x + tmp_40 - tmp_7*tmp_9);\n hess[1] = hess[1] + tmp_47;\n hess[2] = hess[2] + tmp_52;\n hess[3] = hess[3] + tmp_47;\n hess[4] = hess[4] + -tmp_41*(tmp_13*tmp_53 + tmp_23*(-tmp_16*tmp_3 + tmp_18*tmp_3 + tmp_21) - tmp_28*tmp_56 - tmp_34*tmp_57 + tmp_35*tmp_57 + tmp_36*tmp_56 + tmp_40 - tmp_53*tmp_7 + tmp_55*y - tmp_58*y);\n hess[5] = hess[5] + tmp_63;\n hess[6] = hess[6] + tmp_52;\n hess[7] = hess[7] + tmp_63;\n hess[8] = hess[8] + -tmp_41*(tmp_13*tmp_64 + tmp_23*(-tmp_16*tmp_4 + tmp_18*tmp_4 + tmp_21) + tmp_25*tmp_65 - tmp_28*tmp_66 - tmp_34*tmp_67 + tmp_35*tmp_67 + tmp_36*tmp_66 - tmp_37*tmp_65 + tmp_40 - tmp_64*tmp_7);\n}\n\n/* ---------------------------------------------------------------------------\n Spherical NFW\n*/\ndouble sphericalnfw_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n */\n double u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = -pars[0] * pars[1] / pars[2];\n u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]) / pars[2];\n return v_h2 * log(1 + u) / u;\n}\n\nvoid sphericalnfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n */\n double fac, u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = pars[0] * pars[1] / pars[2];\n\n u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]) / pars[2];\n fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2];\n}\n\ndouble sphericalnfw_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n */\n // double v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n double v_h2 = pars[0] * pars[1] / pars[2];\n double r, rho0;\n r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);\n\n rho0 = v_h2 / (4*M_PI*pars[0]*pars[2]*pars[2]);\n return rho0 / ((r/pars[2]) * pow(1+r/pars[2],2));\n}\n\nvoid sphericalnfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n */\n double G = pars[0];\n double m = pars[1];\n double r_s = pars[2];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = tmp_0 + tmp_1 + tmp_2;\n double tmp_4 = pow(tmp_3, 7);\n double tmp_5 = 3*tmp_0;\n double tmp_6 = sqrt(tmp_3);\n double tmp_7 = r_s + tmp_6;\n double tmp_8 = pow(tmp_3, 13.0/2.0)*tmp_7;\n double tmp_9 = pow(tmp_7, 2);\n double tmp_10 = 1.0/r_s;\n double tmp_11 = tmp_9*log(tmp_10*tmp_7);\n double tmp_12 = tmp_11*pow(tmp_3, 6);\n double tmp_13 = tmp_11*tmp_4 - pow(tmp_3, 15.0/2.0)*tmp_7;\n double tmp_14 = G*m;\n double tmp_15 = tmp_14/tmp_9;\n double tmp_16 = tmp_15/pow(tmp_3, 17.0/2.0);\n double tmp_17 = x*y;\n double tmp_18 = 4*tmp_15/pow(tmp_3, 3.0/2.0);\n double tmp_19 = 3*tmp_17;\n double tmp_20 = r_s*tmp_15/pow(tmp_3, 2);\n double tmp_21 = tmp_14*log(tmp_10*tmp_6 + 1)/pow(tmp_3, 5.0/2.0);\n double tmp_22 = tmp_17*tmp_18 + tmp_19*tmp_20 - tmp_19*tmp_21;\n double tmp_23 = x*z;\n double tmp_24 = 3*tmp_20;\n double tmp_25 = 3*tmp_21;\n double tmp_26 = tmp_18*tmp_23 + tmp_23*tmp_24 - tmp_23*tmp_25;\n double tmp_27 = 3*tmp_8;\n double tmp_28 = 3*tmp_12;\n double tmp_29 = y*z;\n double tmp_30 = tmp_18*tmp_29 + tmp_24*tmp_29 - tmp_25*tmp_29;\n\n hess[0] = hess[0] + tmp_16*(tmp_0*tmp_4 - tmp_12*tmp_5 + tmp_13 + tmp_5*tmp_8);\n hess[1] = hess[1] + tmp_22;\n hess[2] = hess[2] + tmp_26;\n hess[3] = hess[3] + tmp_22;\n hess[4] = hess[4] + tmp_16*(tmp_1*tmp_27 - tmp_1*tmp_28 + tmp_1*tmp_4 + tmp_13);\n hess[5] = hess[5] + tmp_30;\n hess[6] = hess[6] + tmp_26;\n hess[7] = hess[7] + tmp_30;\n hess[8] = hess[8] + tmp_16*(tmp_13 + tmp_2*tmp_27 - tmp_2*tmp_28 + tmp_2*tmp_4);\n}\n\n/* ---------------------------------------------------------------------------\n Flattened NFW\n*/\ndouble flattenednfw_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (scale mass)\n - r_s (scale radius)\n - qz (flattening)\n */\n double u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = -pars[0] * pars[1] / pars[2];\n u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]/(pars[3]*pars[3])) / pars[2];\n return v_h2 * log(1 + u) / u;\n}\n\nvoid flattenednfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (scale mass)\n - r_s (scale radius)\n - qz (flattening)\n */\n double fac, u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = pars[0] * pars[1] / pars[2];\n u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]/(pars[3]*pars[3])) / pars[2];\n\n fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2]/(pars[3]*pars[3]);\n}\n\nvoid flattenednfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n - c (flattening)\n */\n double G = pars[0];\n double m = pars[1];\n double r_s = pars[2];\n double c = pars[3];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(z, 2);\n double tmp_2 = pow(c, 2);\n double tmp_3 = pow(y, 2);\n double tmp_4 = tmp_1 + tmp_2*(tmp_0 + tmp_3);\n double tmp_5 = pow(tmp_4, 4);\n double tmp_6 = 3*tmp_0;\n double tmp_7 = tmp_4/tmp_2;\n double tmp_8 = sqrt(tmp_7);\n double tmp_9 = r_s + tmp_8;\n double tmp_10 = pow(c, 8);\n double tmp_11 = tmp_10*tmp_9;\n double tmp_12 = tmp_11*pow(tmp_7, 7.0/2.0);\n double tmp_13 = pow(tmp_4, 3);\n double tmp_14 = pow(tmp_9, 2);\n double tmp_15 = tmp_14*log(tmp_9/r_s);\n double tmp_16 = tmp_15*tmp_2;\n double tmp_17 = -tmp_11*pow(tmp_7, 9.0/2.0) + tmp_15*tmp_5;\n double tmp_18 = G*m/tmp_14;\n double tmp_19 = tmp_18/pow(tmp_7, 11.0/2.0);\n double tmp_20 = tmp_19/tmp_10;\n double tmp_21 = pow(c, 4);\n double tmp_22 = pow(tmp_4, 2);\n double tmp_23 = 3*tmp_9;\n double tmp_24 = pow(tmp_7, 3.0/2.0);\n double tmp_25 = tmp_18*x;\n double tmp_26 = tmp_21*tmp_25*y*(-3*tmp_15*tmp_21*tmp_24 + tmp_21*pow(tmp_7, 5.0/2.0) + tmp_22*tmp_23)/tmp_5;\n double tmp_27 = 3*tmp_16;\n double tmp_28 = tmp_2*z*(tmp_2*tmp_24 + tmp_23*tmp_4 - tmp_27*tmp_8)/tmp_13;\n double tmp_29 = tmp_25*tmp_28;\n double tmp_30 = tmp_18*tmp_28*y;\n\n hess[0] = hess[0] + tmp_20*(tmp_0*tmp_5 + tmp_12*tmp_6 - tmp_13*tmp_16*tmp_6 + tmp_17);\n hess[1] = hess[1] + tmp_26;\n hess[2] = hess[2] + tmp_29;\n hess[3] = hess[3] + tmp_26;\n hess[4] = hess[4] + tmp_20*(3*tmp_12*tmp_3 - tmp_13*tmp_27*tmp_3 + tmp_17 + tmp_3*tmp_5);\n hess[5] = hess[5] + tmp_30;\n hess[6] = hess[6] + tmp_29;\n hess[7] = hess[7] + tmp_30;\n hess[8] = hess[8] + tmp_13*tmp_19*(tmp_1*tmp_2*tmp_23*tmp_8 - tmp_1*tmp_27 + tmp_1*tmp_4 + tmp_16*tmp_4 - tmp_22*tmp_9/tmp_8)/pow(c, 12);\n\n}\n\n/* ---------------------------------------------------------------------------\n Triaxial NFW - triaxiality in potential!\n*/\ndouble triaxialnfw_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (scale mass)\n - r_s (scale radius)\n - a (major axis)\n - b (intermediate axis)\n - c (minor axis)\n */\n double u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = -pars[0] * pars[1] / pars[2];\n u = sqrt(q[0]*q[0]/(pars[3]*pars[3])\n + q[1]*q[1]/(pars[4]*pars[4])\n + q[2]*q[2]/(pars[5]*pars[5])) / pars[2];\n return v_h2 * log(1 + u) / u;\n}\n\nvoid triaxialnfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - v_c (circular velocity at the scale radius)\n - r_s (scale radius)\n - a (major axis)\n - b (intermediate axis)\n - c (minor axis)\n */\n double fac, u, v_h2;\n // v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);\n v_h2 = pars[0] * pars[1] / pars[2];\n u = sqrt(q[0]*q[0]/(pars[3]*pars[3])\n + q[1]*q[1]/(pars[4]*pars[4])\n + q[2]*q[2]/(pars[5]*pars[5])) / pars[2];\n\n fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));\n\n grad[0] = grad[0] + fac*q[0]/(pars[3]*pars[3]);\n grad[1] = grad[1] + fac*q[1]/(pars[4]*pars[4]);\n grad[2] = grad[2] + fac*q[2]/(pars[5]*pars[5]);\n}\n\nvoid triaxialnfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - r_s (scale radius)\n - a (major axis)\n - b (intermediate axis)\n - c (minor axis)\n */\n double G = pars[0];\n double m = pars[1];\n double r_s = pars[2];\n double a = pars[3];\n double b = pars[4];\n double c = pars[5];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(a, -2);\n double tmp_1 = G*m;\n double tmp_2 = tmp_0*tmp_1;\n double tmp_3 = pow(x, 2);\n double tmp_4 = pow(b, -2);\n double tmp_5 = pow(y, 2);\n double tmp_6 = pow(c, -2);\n double tmp_7 = pow(z, 2);\n double tmp_8 = tmp_0*tmp_3 + tmp_4*tmp_5 + tmp_6*tmp_7;\n double tmp_9 = pow(tmp_8, -3.0/2.0);\n double tmp_10 = 1.0/r_s;\n double tmp_11 = tmp_10*sqrt(tmp_8) + 1;\n double tmp_12 = log(tmp_11);\n double tmp_13 = tmp_12*tmp_9;\n double tmp_14 = tmp_3/pow(a, 4);\n double tmp_15 = 3*tmp_1;\n double tmp_16 = tmp_12/pow(tmp_8, 5.0/2.0);\n double tmp_17 = tmp_15*tmp_16;\n double tmp_18 = tmp_10/tmp_11;\n double tmp_19 = tmp_18/tmp_8;\n double tmp_20 = tmp_9/(pow(r_s, 2)*pow(tmp_11, 2));\n double tmp_21 = tmp_1*tmp_20;\n double tmp_22 = tmp_18/pow(tmp_8, 2);\n double tmp_23 = tmp_15*tmp_22;\n double tmp_24 = tmp_4*y;\n double tmp_25 = tmp_2*x;\n double tmp_26 = 3*tmp_25;\n double tmp_27 = tmp_16*tmp_26;\n double tmp_28 = tmp_20*tmp_25;\n double tmp_29 = tmp_22*tmp_26;\n double tmp_30 = -tmp_24*tmp_27 + tmp_24*tmp_28 + tmp_24*tmp_29;\n double tmp_31 = tmp_6*z;\n double tmp_32 = -tmp_27*tmp_31 + tmp_28*tmp_31 + tmp_29*tmp_31;\n double tmp_33 = tmp_1*tmp_13;\n double tmp_34 = tmp_5/pow(b, 4);\n double tmp_35 = tmp_1*tmp_19;\n double tmp_36 = tmp_24*tmp_31;\n double tmp_37 = -tmp_17*tmp_36 + tmp_21*tmp_36 + tmp_23*tmp_36;\n double tmp_38 = tmp_7/pow(c, 4);\n\n hess[0] = hess[0] + tmp_13*tmp_2 - tmp_14*tmp_17 + tmp_14*tmp_21 + tmp_14*tmp_23 - tmp_19*tmp_2;\n hess[1] = hess[1] + tmp_30;\n hess[2] = hess[2] + tmp_32;\n hess[3] = hess[3] + tmp_30;\n hess[4] = hess[4] + -tmp_17*tmp_34 + tmp_21*tmp_34 + tmp_23*tmp_34 + tmp_33*tmp_4 - tmp_35*tmp_4;\n hess[5] = hess[5] + tmp_37;\n hess[6] = hess[6] + tmp_32;\n hess[7] = hess[7] + tmp_37;\n hess[8] = hess[8] + -tmp_17*tmp_38 + tmp_21*tmp_38 + tmp_23*tmp_38 + tmp_33*tmp_6 - tmp_35*tmp_6;\n}\n\n/* ---------------------------------------------------------------------------\n Satoh potential\n*/\ndouble satoh_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n double S2;\n S2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*(pars[2] + 2*sqrt(q[2]*q[2] + pars[3]*pars[3]));\n return -pars[0] * pars[1] / sqrt(S2);\n}\n\nvoid satoh_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n\n double S2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*(pars[2] + 2*sqrt(q[2]*q[2] + pars[3]*pars[3]));\n double dPhi_dS = pars[0] * pars[1] / S2;\n\n grad[0] = grad[0] + dPhi_dS*q[0]/sqrt(S2);\n grad[1] = grad[1] + dPhi_dS*q[1]/sqrt(S2);\n grad[2] = grad[2] + dPhi_dS/sqrt(S2) * q[2]*(1 + pars[2] / sqrt(q[2]*q[2] + pars[3]*pars[3]));\n}\n\ndouble satoh_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n double z2b2 = q[2]*q[2] + pars[3]*pars[3];\n double xyz2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];\n double S2 = xyz2 + pars[2]*(pars[2] + 2*sqrt(z2b2));\n double A = pars[1] * pars[2] * pars[3]*pars[3] / (4*M_PI*S2*sqrt(S2)*z2b2);\n return A * (1/sqrt(z2b2) + 3/pars[2]*(1 - xyz2/S2));\n}\n\nvoid satoh_hessian(double t, double *pars, double *q, int n_dim, double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a ()\n - b ()\n */\n double G = pars[0];\n double m = pars[1];\n double a = pars[2];\n double b = pars[3];\n\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = pow(b, 2) + tmp_2;\n double tmp_4 = sqrt(tmp_3);\n double tmp_5 = a*(a + 2*tmp_4) + tmp_0 + tmp_1 + tmp_2;\n double tmp_6 = G*m;\n double tmp_7 = tmp_6/pow(tmp_5, 3.0/2.0);\n double tmp_8 = tmp_6/pow(tmp_5, 5.0/2.0);\n double tmp_9 = 3*tmp_8;\n double tmp_10 = -tmp_9*x*y;\n double tmp_11 = 3*z;\n double tmp_12 = a/tmp_4;\n double tmp_13 = tmp_8*(-tmp_11*tmp_12 - tmp_11);\n double tmp_14 = tmp_13*x;\n double tmp_15 = tmp_13*y;\n\n hess[0] = hess[0] + -tmp_0*tmp_9 + tmp_7;\n hess[1] = hess[1] + tmp_10;\n hess[2] = hess[2] + tmp_14;\n hess[3] = hess[3] + tmp_10;\n hess[4] = hess[4] + -tmp_1*tmp_9 + tmp_7;\n hess[5] = hess[5] + tmp_15;\n hess[6] = hess[6] + tmp_14;\n hess[7] = hess[7] + tmp_15;\n hess[8] = hess[8] + -tmp_13*(-tmp_12*z - z) - tmp_7*(a*tmp_2/pow(tmp_3, 3.0/2.0) - tmp_12 - 1);\n}\n\n/* ---------------------------------------------------------------------------\n Kuzmin potential\n*/\ndouble kuzmin_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n */\n double S2 = q[0]*q[0] + q[1]*q[1] + pow(pars[2] + fabs(q[2]), 2);\n return -pars[0] * pars[1] / sqrt(S2);\n}\n\nvoid kuzmin_gradient(double t, double *pars, double *q, int n_dim,\n double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n */\n\n double S2 = q[0]*q[0] + q[1]*q[1] + pow(pars[2] + fabs(q[2]), 2);\n double fac = pars[0] * pars[1] * pow(S2, -1.5);\n double zsign;\n\n if (q[2] > 0) {\n zsign = 1.;\n } else if (q[2] < 0) {\n zsign = -1.;\n } else {\n zsign = 0.;\n }\n\n grad[0] = grad[0] + fac * q[0];\n grad[1] = grad[1] + fac * q[1];\n grad[2] = grad[2] + fac * zsign * (pars[2] + fabs(q[2]));\n}\n\ndouble kuzmin_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n */\n if (q[2] != 0.) {\n return 0.;\n } else {\n return pars[1] * pars[2] / (2 * M_PI) *\n pow(q[0]*q[0] + q[1]*q[1] + pars[2]*pars[2], -1.5);\n }\n\n}\n\n/* ---------------------------------------------------------------------------\n Miyamoto-Nagai flattened potential\n*/\ndouble miyamotonagai_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n double zd;\n zd = (pars[2] + sqrt(q[2]*q[2] + pars[3]*pars[3]));\n return -pars[0] * pars[1] / sqrt(q[0]*q[0] + q[1]*q[1] + zd*zd);\n}\n\nvoid miyamotonagai_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n double sqrtz, zd, fac;\n\n sqrtz = sqrt(q[2]*q[2] + pars[3]*pars[3]);\n zd = pars[2] + sqrtz;\n fac = pars[0]*pars[1] * pow(q[0]*q[0] + q[1]*q[1] + zd*zd, -1.5);\n\n grad[0] = grad[0] + fac*q[0];\n grad[1] = grad[1] + fac*q[1];\n grad[2] = grad[2] + fac*q[2] * (1. + pars[2] / sqrtz);\n}\n\ndouble miyamotonagai_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n\n double M, a, b;\n M = pars[1];\n a = pars[2];\n b = pars[3];\n\n double R2 = q[0]*q[0] + q[1]*q[1];\n double sqrt_zb = sqrt(q[2]*q[2] + b*b);\n double numer = (b*b*M / (4*M_PI)) * (a*R2 + (a + 3*sqrt_zb)*(a + sqrt_zb)*(a + sqrt_zb));\n double denom = pow(R2 + (a + sqrt_zb)*(a + sqrt_zb), 2.5) * sqrt_zb*sqrt_zb*sqrt_zb;\n\n return numer/denom;\n}\n\nvoid miyamotonagai_hessian(double t, double *pars, double *q, int n_dim,\n double *hess) {\n /* pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a (length scale 1) TODO\n - b (length scale 2) TODO\n */\n double G = pars[0];\n double m = pars[1];\n double a = pars[2];\n double b = pars[3];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(x, 2);\n double tmp_1 = pow(y, 2);\n double tmp_2 = pow(z, 2);\n double tmp_3 = pow(b, 2) + tmp_2;\n double tmp_4 = sqrt(tmp_3);\n double tmp_5 = a + tmp_4;\n double tmp_6 = pow(tmp_5, 2);\n double tmp_7 = tmp_0 + tmp_1 + tmp_6;\n double tmp_8 = G*m;\n double tmp_9 = tmp_8/pow(tmp_7, 3.0/2.0);\n double tmp_10 = 3*tmp_8/pow(tmp_7, 5.0/2.0);\n double tmp_11 = tmp_10*x;\n double tmp_12 = -tmp_11*y;\n double tmp_13 = tmp_5/tmp_4;\n double tmp_14 = tmp_13*z;\n double tmp_15 = -tmp_11*tmp_14;\n double tmp_16 = -tmp_10*tmp_14*y;\n double tmp_17 = 1.0/tmp_3;\n double tmp_18 = tmp_2*tmp_9;\n\n hess[0] = hess[0] + -tmp_0*tmp_10 + tmp_9;\n hess[1] = hess[1] + tmp_12;\n hess[2] = hess[2] + tmp_15;\n hess[3] = hess[3] + tmp_12;\n hess[4] = hess[4] + -tmp_1*tmp_10 + tmp_9;\n hess[5] = hess[5] + tmp_16;\n hess[6] = hess[6] + tmp_15;\n hess[7] = hess[7] + tmp_16;\n hess[8] = hess[8] + -tmp_10*tmp_17*tmp_2*tmp_6 + tmp_13*tmp_9 + tmp_17*tmp_18 - tmp_18*tmp_5/pow(tmp_3, 3.0/2.0);\n}\n\n/* ---------------------------------------------------------------------------\n Lee-Suto triaxial NFW from Lee & Suto (2003)\n*/\ndouble leesuto_value(double t, double *pars, double *q, int n_dim) {\n /* pars: (alpha = 1)\n 0 - G\n 1 - v_c\n 2 - r_s\n 3 - a\n 4 - b\n 5 - c\n */\n double x, y, z, _r, u, phi0;\n double e_b2 = 1-pow(pars[4]/pars[3],2);\n double e_c2 = 1-pow(pars[5]/pars[3],2);\n double F1,F2,F3,costh2,sinth2,sinph2;\n\n phi0 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);\n\n x = q[0];\n y = q[1];\n z = q[2];\n\n _r = sqrt(x*x + y*y + z*z);\n u = _r / pars[2];\n\n F1 = -log(1+u)/u;\n F2 = -1/3. + (2*u*u - 3*u + 6)/(6*u*u) + (1/u - pow(u,-3.))*log(1+u);\n F3 = (u*u - 3*u - 6)/(2*u*u*(1+u)) + 3*pow(u,-3)*log(1+u);\n costh2 = z*z / (_r*_r);\n sinth2 = 1 - costh2;\n sinph2 = y*y / (x*x + y*y);\n //return phi0 * ((e_b2/2 + e_c2/2)*((1/u - 1/(u*u*u))*log(u + 1) - 1 + (2*u*u - 3*u + 6)/(6*u*u)) + (e_b2*y*y/(2*_r*_r) + e_c2*z*z/(2*_r*_r))*((u*u - 3*u - 6)/(2*u*u*(u + 1)) + 3*log(u + 1)/(u*u*u)) - log(u + 1)/u);\n return phi0 * (F1 + (e_b2+e_c2)/2.*F2 + (e_b2*sinth2*sinph2 + e_c2*costh2)/2. * F3);\n}\n\nvoid leesuto_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars: (alpha = 1)\n 0 - G\n 1 - v_c\n 2 - r_s\n 3 - a\n 4 - b\n 5 - c\n */\n double x, y, z, _r, _r2, _r4, ax, ay, az;\n double v_h2, x0, x2, x22;\n double x20, x21, x7, x1;\n double x10, x13, x15, x16, x17;\n double e_b2 = 1-pow(pars[4]/pars[3],2);\n double e_c2 = 1-pow(pars[5]/pars[3],2);\n\n v_h2 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);\n\n x = q[0];\n y = q[1];\n z = q[2];\n\n _r2 = x*x + y*y + z*z;\n _r = sqrt(_r2);\n _r4 = _r2*_r2;\n\n x0 = _r + pars[2];\n x1 = x0*x0;\n x2 = v_h2/(12.*_r4*_r2*_r*x1);\n x10 = log(x0/pars[2]);\n\n x13 = _r*3.*pars[2];\n x15 = x13 - _r2;\n x16 = x15 + 6.*(pars[2]*pars[2]);\n x17 = 6.*pars[2]*x0*(_r*x16 - x0*x10*6.*(pars[2]*pars[2]));\n x20 = x0*_r2;\n x21 = 2.*_r*x0;\n x7 = e_b2*y*y + e_c2*z*z;\n x22 = -12.*_r4*_r*pars[2]*x0 + 12.*_r4*pars[2]*x1*x10 + 3.*pars[2]*x7*(x16*_r2 - 18.*x1*x10*(pars[2]*pars[2]) + x20*(2.*_r - 3.*pars[2]) + x21*(x15 + 9.*(pars[2]*pars[2]))) - x20*(e_b2 + e_c2)*(-6.*_r*pars[2]*(_r2 - (pars[2]*pars[2])) + 6.*pars[2]*x0*x10*(_r2 - 3.*(pars[2]*pars[2])) + x20*(-4.*_r + 3.*pars[2]) + x21*(-x13 + 2.*_r2 + 6.*(pars[2]*pars[2])));\n\n ax = x2*x*(x17*x7 + x22);\n ay = x2*y*(x17*(x7 - _r2*e_b2) + x22);\n az = x2*z*(x17*(x7 - _r2*e_c2) + x22);\n\n grad[0] = grad[0] + ax;\n grad[1] = grad[1] + ay;\n grad[2] = grad[2] + az;\n}\n\ndouble leesuto_density(double t, double *pars, double *q, int n_dim) {\n /* pars: (alpha = 1)\n 0 - G\n 1 - v_c\n 2 - r_s\n 3 - a\n 4 - b\n 5 - c\n */\n double x, y, z, u, v_h2;\n double b_a2, c_a2;\n b_a2 = pars[4]*pars[4] / (pars[3]*pars[3]);\n c_a2 = pars[5]*pars[5] / (pars[3]*pars[3]);\n double e_b2 = 1-b_a2;\n double e_c2 = 1-c_a2;\n v_h2 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);\n\n x = q[0];\n y = q[1];\n z = q[2];\n\n u = sqrt(x*x + y*y/b_a2 + z*z/c_a2) / pars[2];\n return v_h2 / (u * (1+u)*(1+u)) / (4.*M_PI*pars[2]*pars[2]*pars[0]);\n}\n\n/* ---------------------------------------------------------------------------\n Logarithmic (triaxial)\n*/\ndouble logarithmic_value(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - v_c (velocity scale)\n - r_h (length scale)\n - q1\n - q2\n - q3\n */\n double x, y, z;\n\n x = q[0]*cos(pars[6]) + q[1]*sin(pars[6]);\n y = -q[0]*sin(pars[6]) + q[1]*cos(pars[6]);\n z = q[2];\n\n return 0.5*pars[1]*pars[1] * log(pars[2]*pars[2] + // scale radius\n x*x/(pars[3]*pars[3]) +\n y*y/(pars[4]*pars[4]) +\n z*z/(pars[5]*pars[5]));\n}\n\ndouble logarithmic_density(double t, double *pars, double *q, int n_dim) {\n /* pars:\n - G (Gravitational constant)\n - v_c (velocity scale)\n - r_h (length scale)\n - q1\n - q2\n - q3\n */\n double tmp_0 = pow(pars[3], 2);\n double tmp_1 = pow(pars[4], 2);\n double tmp_2 = tmp_0*tmp_1;\n double tmp_3 = tmp_2*pow(q[2], 2);\n double tmp_4 = pow(pars[5], 2);\n double tmp_5 = tmp_0*tmp_4;\n double tmp_6 = tmp_5*pow(q[1], 2);\n double tmp_7 = tmp_1*tmp_4;\n double tmp_8 = tmp_7*pow(q[0], 2);\n double tmp_9 = pow(pars[2], 2)*tmp_2*tmp_4;\n double tmp_10 = tmp_6 + tmp_8 + tmp_9;\n double tmp_11 = tmp_3 + tmp_9;\n return pow(pars[1], 2)*(tmp_2*(tmp_10 - tmp_3) + tmp_5*(tmp_11 - tmp_6 + tmp_8) + tmp_7*(tmp_11 + tmp_6 - tmp_8))/pow(tmp_10 + tmp_3, 2) / (4*M_PI*pars[0]);\n}\n\nvoid logarithmic_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* pars:\n - G (Gravitational constant)\n - v_c (velocity scale)\n - r_h (length scale)\n - q1\n - q2\n - q3\n */\n double x, y, z, ax, ay, az, fac;\n\n x = q[0]*cos(pars[6]) + q[1]*sin(pars[6]);\n y = -q[0]*sin(pars[6]) + q[1]*cos(pars[6]);\n z = q[2];\n\n fac = pars[1]*pars[1] / (pars[2]*pars[2] + x*x/(pars[3]*pars[3]) + y*y/(pars[4]*pars[4]) + z*z/(pars[5]*pars[5]));\n ax = fac*x/(pars[3]*pars[3]);\n ay = fac*y/(pars[4]*pars[4]);\n az = fac*z/(pars[5]*pars[5]);\n\n grad[0] = grad[0] + (ax*cos(pars[6]) - ay*sin(pars[6]));\n grad[1] = grad[1] + (ax*sin(pars[6]) + ay*cos(pars[6]));\n grad[2] = grad[2] + az;\n}\n\nvoid logarithmic_hessian(double t, double *pars, double *q, int n_dim,\n double *hess) {\n /* pars:\n - G (Gravitational constant)\n - v_c (velocity scale)\n - r_h (length scale)\n - q1\n - q2\n - q3\n */\n double v_c = pars[1];\n double r_h = pars[2];\n double q1 = pars[3];\n double q2 = pars[4];\n double q3 = pars[5];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = pow(q1, -2);\n double tmp_1 = pow(v_c, 2);\n double tmp_2 = tmp_0*tmp_1;\n double tmp_3 = pow(x, 2);\n double tmp_4 = pow(q2, -2);\n double tmp_5 = pow(y, 2);\n double tmp_6 = pow(q3, -2);\n double tmp_7 = pow(z, 2);\n double tmp_8 = pow(r_h, 2) + tmp_0*tmp_3 + tmp_4*tmp_5 + tmp_6*tmp_7;\n double tmp_9 = 1.0/tmp_8;\n double tmp_10 = 2.0/pow(tmp_8, 2);\n double tmp_11 = tmp_1*tmp_10;\n double tmp_12 = tmp_4*y;\n double tmp_13 = tmp_10*tmp_2*x;\n double tmp_14 = tmp_12*tmp_13;\n double tmp_15 = tmp_6*z;\n double tmp_16 = tmp_13*tmp_15;\n double tmp_17 = tmp_1*tmp_9;\n double tmp_18 = tmp_11*tmp_12*tmp_15;\n\n // minus signs because I initially borked the sympy definition\n hess[0] = hess[0] - (-tmp_2*tmp_9 + tmp_11*tmp_3/pow(q1, 4));\n hess[1] = hess[1] - (tmp_14);\n hess[2] = hess[2] - (tmp_16);\n hess[3] = hess[3] - (tmp_14);\n hess[4] = hess[4] - (-tmp_17*tmp_4 + tmp_11*tmp_5/pow(q2, 4));\n hess[5] = hess[5] - (tmp_18);\n hess[6] = hess[6] - (tmp_16);\n hess[7] = hess[7] - (tmp_18);\n hess[8] = hess[8] - (-tmp_17*tmp_6 + tmp_11*tmp_7/pow(q3, 4));\n}\n\n/* ---------------------------------------------------------------------------\n Logarithmic (triaxial)\n*/\ndouble longmuralibar_value(double t, double *pars, double *q, int n_dim) {\n /* http://adsabs.harvard.edu/abs/1992ApJ...397...44L\n\n pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a\n - b\n - c\n - alpha\n */\n double x, y, z;\n double a, b, c;\n double Tm, Tp;\n\n x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);\n y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);\n z = q[2];\n\n a = pars[2];\n b = pars[3];\n c = pars[4];\n\n Tm = sqrt((a-x)*(a-x) + y*y + pow(b + sqrt(c*c + z*z),2));\n Tp = sqrt((a+x)*(a+x) + y*y + pow(b + sqrt(c*c + z*z),2));\n\n return pars[0]*pars[1]/(2*a) * log((x - a + Tm) / (x + a + Tp));\n}\n\nvoid longmuralibar_gradient(double t, double *pars, double *q, int n_dim, double *grad) {\n /* http://adsabs.harvard.edu/abs/1992ApJ...397...44L\n\n pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a\n - b\n - c\n - alpha\n */\n double x, y, z;\n double a, b, c;\n double Tm, Tp, fac1, fac2, fac3, bcz;\n double gx, gy, gz;\n\n x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);\n y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);\n z = q[2];\n\n a = pars[2];\n b = pars[3];\n c = pars[4];\n\n bcz = b + sqrt(c*c + z*z);\n Tm = sqrt((a-x)*(a-x) + y*y + bcz*bcz);\n Tp = sqrt((a+x)*(a+x) + y*y + bcz*bcz);\n\n fac1 = pars[0]*pars[1] / (2*Tm*Tp);\n fac2 = 1 / (y*y + bcz*bcz);\n fac3 = Tp + Tm - (4*x*x)/(Tp+Tm);\n\n gx = 4 * fac1 * x / (Tp + Tm);\n gy = fac1 * y * fac2 * fac3;\n gz = fac1 * z * fac2 * fac3 * bcz / sqrt(z*z + c*c);\n\n grad[0] = grad[0] + (gx*cos(pars[5]) - gy*sin(pars[5]));\n grad[1] = grad[1] + (gx*sin(pars[5]) + gy*cos(pars[5]));\n grad[2] = grad[2] + gz;\n}\n\ndouble longmuralibar_density(double t, double *pars, double *q, int n_dim) {\n /*\n Generated by sympy...\n\n pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a\n - b\n - c\n - alpha\n */\n double a = pars[2];\n double b = pars[3];\n double c = pars[4];\n\n double x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);\n double y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);\n double z = q[2];\n\n double tmp0 = a - x;\n double tmp1 = pow(tmp0, 2);\n double tmp2 = pow(y, 2);\n double tmp3 = pow(z, 2);\n double tmp4 = pow(c, 2) + tmp3;\n double tmp5 = sqrt(tmp4);\n double tmp6 = b + tmp5;\n double tmp7 = pow(tmp6, 2);\n double tmp8 = tmp2 + tmp7;\n double tmp9 = tmp1 + tmp8;\n double tmp10 = sqrt(tmp9);\n double tmp11 = -a + tmp10 + x;\n double tmp12 = 1.0/tmp11;\n double tmp13 = 1.0/tmp10;\n double tmp14 = pow(tmp9, -1.5);\n double tmp15 = 1.0/tmp4;\n double tmp16 = tmp13*tmp3;\n double tmp17 = tmp6/tmp5;\n double tmp18 = pow(tmp4, -1.5);\n double tmp19 = tmp15*tmp3*tmp7;\n double tmp20 = 2*tmp2;\n double tmp21 = a + x;\n double tmp22 = pow(tmp21, 2);\n double tmp23 = tmp22 + tmp8;\n double tmp24 = sqrt(tmp23);\n double tmp25 = 1.0/tmp24;\n double tmp26 = tmp21 + tmp24;\n double tmp27 = 1.0/tmp26;\n double tmp28 = tmp25*tmp27;\n double tmp29 = tmp11*tmp28;\n double tmp30 = tmp11*tmp27/pow(tmp23, 1.5);\n double tmp31 = 1.0/tmp23;\n double tmp32 = pow(tmp26, -2);\n double tmp33 = tmp11*tmp31*tmp32;\n double tmp34 = tmp21*tmp25 + 1;\n double tmp35 = tmp27*tmp34;\n double tmp36 = tmp13*tmp15*tmp3*tmp7;\n double tmp37 = -tmp13 + tmp29;\n double tmp38 = tmp2*tmp37;\n double tmp39 = tmp0*tmp13;\n double tmp40 = tmp11*tmp27*tmp34 + tmp39 - 1;\n return pars[1]/8.*tmp12*(2*tmp11*tmp32*pow(tmp34, 2) +\n tmp12*tmp13*tmp38 + tmp12*tmp36*tmp37 + tmp12*tmp40*(-tmp39 + 1) +\n tmp13*tmp17 - tmp13*tmp20*tmp25*tmp27 + tmp13*(-tmp1/tmp9 + 1) + tmp13 -\n tmp14*tmp19 - tmp14*tmp2 + tmp15*tmp16 - tmp15*tmp28*tmp3*tmp37*tmp7 -\n tmp15*tmp29*tmp3 + 2*tmp15*tmp3*tmp33*tmp7 - tmp16*tmp18*tmp6 -\n tmp17*tmp29 + tmp18*tmp29*tmp3*tmp6 + tmp19*tmp30 + tmp2*tmp30 +\n tmp20*tmp33 - 2*tmp25*tmp27*tmp36 - tmp28*tmp38 - tmp29*(-tmp22*tmp31 +\n 1) - tmp29 - tmp35*tmp40 - tmp35*(-2*tmp0*tmp13 + 2))/(M_PI*a);\n}\n\nvoid longmuralibar_hessian(double t, double *pars, double *q, int n_dim,\n double *hess) {\n /* Generated by sympy...\n\n pars:\n - G (Gravitational constant)\n - m (mass scale)\n - a\n - b\n - c\n - alpha\n */\n double G = pars[0];\n double m = pars[1];\n double a = pars[2];\n double b = pars[3];\n double c = pars[4];\n double alpha = pars[5];\n double x = q[0];\n double y = q[1];\n double z = q[2];\n\n double tmp_0 = cos(alpha);\n double tmp_1 = tmp_0*x;\n double tmp_2 = sin(alpha);\n double tmp_3 = tmp_2*y;\n double tmp_4 = tmp_1 + tmp_3;\n double tmp_5 = a + tmp_4;\n double tmp_6 = tmp_0*tmp_5;\n double tmp_7 = tmp_0*y - tmp_2*x;\n double tmp_8 = tmp_2*tmp_7;\n double tmp_9 = -tmp_8;\n double tmp_10 = tmp_6 + tmp_9;\n double tmp_11 = pow(z, 2);\n double tmp_12 = pow(c, 2) + tmp_11;\n double tmp_13 = sqrt(tmp_12);\n double tmp_14 = b + tmp_13;\n double tmp_15 = pow(tmp_14, 2);\n double tmp_16 = tmp_15 + pow(tmp_7, 2);\n double tmp_17 = tmp_16 + pow(tmp_5, 2);\n double tmp_18 = sqrt(tmp_17);\n double tmp_19 = 1.0/tmp_18;\n double tmp_20 = tmp_10*tmp_19;\n double tmp_21 = tmp_18 + tmp_5;\n double tmp_22 = 1.0/tmp_21;\n double tmp_23 = a - tmp_1 - tmp_3;\n double tmp_24 = tmp_0*tmp_23;\n double tmp_25 = -tmp_24 + tmp_9;\n double tmp_26 = tmp_16 + pow(tmp_23, 2);\n double tmp_27 = sqrt(tmp_26);\n double tmp_28 = 1.0/tmp_27;\n double tmp_29 = tmp_25*tmp_28;\n double tmp_30 = tmp_0 + tmp_29;\n double tmp_31 = -tmp_0;\n double tmp_32 = -tmp_20 + tmp_31;\n double tmp_33 = pow(tmp_21, -2);\n double tmp_34 = -a + tmp_27 + tmp_4;\n double tmp_35 = tmp_33*tmp_34;\n double tmp_36 = tmp_22*tmp_30 + tmp_32*tmp_35;\n double tmp_37 = (1.0/2.0)*G*m/a;\n double tmp_38 = tmp_37/tmp_34;\n double tmp_39 = tmp_36*tmp_38;\n double tmp_40 = tmp_21*tmp_37/pow(tmp_34, 2);\n double tmp_41 = tmp_36*tmp_40;\n double tmp_42 = tmp_32*tmp_33;\n double tmp_43 = pow(tmp_0, 2) + pow(tmp_2, 2);\n double tmp_44 = tmp_28*tmp_43;\n double tmp_45 = pow(tmp_26, -3.0/2.0);\n double tmp_46 = tmp_25*tmp_45;\n double tmp_47 = -tmp_19*tmp_43;\n double tmp_48 = pow(tmp_17, -3.0/2.0);\n double tmp_49 = tmp_10*tmp_48;\n double tmp_50 = tmp_34/pow(tmp_21, 3);\n double tmp_51 = tmp_32*tmp_50;\n double tmp_52 = tmp_21*tmp_38;\n double tmp_53 = tmp_0*tmp_7;\n double tmp_54 = tmp_2*tmp_5;\n double tmp_55 = tmp_53 + tmp_54;\n double tmp_56 = tmp_19*tmp_55;\n double tmp_57 = tmp_2 + tmp_56;\n double tmp_58 = -tmp_2;\n double tmp_59 = tmp_2*tmp_23;\n double tmp_60 = tmp_53 - tmp_59;\n double tmp_61 = tmp_28*tmp_60;\n double tmp_62 = tmp_58 - tmp_61;\n double tmp_63 = -tmp_53;\n double tmp_64 = tmp_59 + tmp_63;\n double tmp_65 = tmp_22*tmp_46;\n double tmp_66 = -tmp_56 + tmp_58;\n double tmp_67 = tmp_33*tmp_66;\n double tmp_68 = tmp_2 + tmp_61;\n double tmp_69 = -tmp_54 + tmp_63;\n double tmp_70 = tmp_35*tmp_49;\n double tmp_71 = -2*tmp_2 - 2*tmp_56;\n double tmp_72 = tmp_39*tmp_57 + tmp_41*tmp_62 + tmp_52*(tmp_30*tmp_67 + tmp_42*tmp_68 + tmp_51*tmp_71 + tmp_64*tmp_65 - tmp_69*tmp_70);\n double tmp_73 = 1.0/tmp_13;\n double tmp_74 = tmp_14*tmp_73;\n double tmp_75 = tmp_74*z;\n double tmp_76 = tmp_19*tmp_75;\n double tmp_77 = tmp_28*tmp_75;\n double tmp_78 = tmp_19*tmp_33;\n double tmp_79 = tmp_75*tmp_78;\n double tmp_80 = 2*tmp_76;\n double tmp_81 = tmp_39*tmp_76 - tmp_41*tmp_77 + tmp_52*(-tmp_30*tmp_79 + tmp_42*tmp_77 - tmp_51*tmp_80 - tmp_65*tmp_75 + tmp_70*tmp_75);\n double tmp_82 = tmp_22*tmp_68 + tmp_35*tmp_66;\n double tmp_83 = tmp_38*tmp_82;\n double tmp_84 = tmp_40*tmp_82;\n double tmp_85 = tmp_45*tmp_60;\n double tmp_86 = tmp_50*tmp_66;\n double tmp_87 = tmp_48*tmp_55;\n double tmp_88 = tmp_52*(-tmp_22*tmp_75*tmp_85 + tmp_35*tmp_75*tmp_87 + tmp_67*tmp_77 - tmp_68*tmp_79 - tmp_80*tmp_86) + tmp_76*tmp_83 - tmp_77*tmp_84;\n double tmp_89 = tmp_22*tmp_28;\n double tmp_90 = tmp_14*tmp_89;\n double tmp_91 = tmp_73*tmp_90;\n double tmp_92 = tmp_19*tmp_35;\n double tmp_93 = tmp_74*tmp_92;\n double tmp_94 = tmp_91*z - tmp_93*z;\n double tmp_95 = tmp_11/tmp_12;\n double tmp_96 = tmp_11/pow(tmp_12, 3.0/2.0);\n double tmp_97 = tmp_15*tmp_95;\n double tmp_98 = 2*tmp_97;\n\n hess[0] = hess[0] + tmp_39*(tmp_0 + tmp_20) + tmp_41*(-tmp_29 + tmp_31) + tmp_52*(tmp_22*(tmp_44 + tmp_46*(tmp_24 + tmp_8)) + 2*tmp_30*tmp_42 + tmp_35*(tmp_47 - tmp_49*(-tmp_6 + tmp_8)) + tmp_51*(-2*tmp_0 - 2*tmp_20));\n hess[1] = hess[1] + tmp_72;\n hess[2] = hess[2] + tmp_81;\n hess[3] = hess[3] + tmp_72;\n hess[4] = hess[4] + tmp_52*(tmp_22*(tmp_44 + tmp_64*tmp_85) + tmp_35*(tmp_47 - tmp_69*tmp_87) + 2*tmp_67*tmp_68 + tmp_71*tmp_86) + tmp_57*tmp_83 + tmp_62*tmp_84;\n hess[5] = hess[5] + tmp_88;\n hess[6] = hess[6] + tmp_81;\n hess[7] = hess[7] + tmp_88;\n hess[8] = hess[8] + tmp_38*tmp_76*tmp_94 - tmp_40*tmp_77*tmp_94 + tmp_52*(tmp_14*tmp_92*tmp_96 - tmp_22*tmp_45*tmp_97 - tmp_28*tmp_78*tmp_98 + tmp_35*tmp_48*tmp_97 + tmp_89*tmp_95 - tmp_90*tmp_96 + tmp_91 - tmp_92*tmp_95 - tmp_93 + tmp_50*tmp_98/tmp_17);\n}\n", "meta": {"hexsha": "3f820ef9ad22e2051c24b79bcf72153651db886e", "size": 63163, "ext": "c", "lang": "C", "max_stars_repo_path": "gala/potential/potential/builtin/builtin_potentials.c", "max_stars_repo_name": "akeemlh/gala", "max_stars_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "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": "gala/potential/potential/builtin/builtin_potentials.c", "max_issues_repo_name": "akeemlh/gala", "max_issues_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "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": "gala/potential/potential/builtin/builtin_potentials.c", "max_forks_repo_name": "akeemlh/gala", "max_forks_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48", "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.4195767196, "max_line_length": 362, "alphanum_fraction": 0.5374982189, "num_tokens": 25274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.49683882500289644}} {"text": "//This takes the output of STFT, X, and a transform matrix, T,\n//and outputs a T*X or X*T', depending on orientation of X.\n//X is either WxF or FxW.\n//T must be BxF, as from get_spectrogram_T_mat.\n//Y is either WxB or BxW.\n\n#include \n#include \n#include \n//#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint apply_spectrogram_T_mat_s (float *Y, const float *X, const float *T, const size_t W, const size_t F, const size_t B);\nint apply_spectrogram_T_mat_d (double *Y, const double *X, const double *T, const size_t W, const size_t F, const size_t B);\n\n\nint apply_spectrogram_T_mat_s (float *Y, const float *X, const float *T, const size_t W, const size_t F, const size_t B)\n{\n if (B<1u) { fprintf(stderr,\"error in apply_spectrogram_T_mat_s: B (num output freq bands) must be positive\\n\"); return 1; }\n if (F<1u) { fprintf(stderr,\"error in apply_spectrogram_T_mat_s: F (num STFT freqs) must be positive\\n\"); return 1; }\n\n if (B*W<1200000u)\n {\n //struct timespec tic, toc; clock_gettime(CLOCK_REALTIME,&tic);\n for (size_t w=W; w>0u; --w, X+=F, T-=B*F)\n {\n for (size_t b=B; b>0u; --b, X-=F, ++Y)\n {\n float sm = 0.0f;\n //size_t f = 0u;\n //while (f0u; --f, ++X, ++T) { sm += *X * *T; }\n *Y = sm;\n }\n }\n //clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,\"fmaf: elapsed time = %.6f ms\\n\",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);\n }\n else\n {\n //struct timespec tic, toc; clock_gettime(CLOCK_REALTIME,&tic);\n cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,(int)W,(int)B,(int)F,1.0f,X,(int)F,T,(int)F,0.0f,Y,(int)B);\n //clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,\"sgemm: elapsed time = %.6f ms\\n\",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);\n }\n \n return 0;\n}\n\n\nint apply_spectrogram_T_mat_d (double *Y, const double *X, const double *T, const size_t W, const size_t F, const size_t B)\n{\n if (B<1u) { fprintf(stderr,\"error in apply_spectrogram_T_mat_d: B (num output freq bands) must be positive\\n\"); return 1; }\n if (F<1u) { fprintf(stderr,\"error in apply_spectrogram_T_mat_d: F (num STFT freqs) must be positive\\n\"); return 1; }\n\n if (B*W<12000u)\n {\n for (size_t w=W; w>0u; --w, X+=F, T-=B*F)\n {\n for (size_t b=B; b>0u; --b, X-=F, ++Y)\n {\n double sm = 0.0;\n //size_t f = F;\n //while (*T==0.0f && f>0u) { ++X; ++T; --f; }\n //while (*T!=0.0f && f>0u) { sm += *X**T; ++X; ++T; --f; }\n //X -= f; T -= f;\n //for (size_t f=F; f>0u; --f, ++X, ++T) { sm = fma(*X,*T,sm); }\n for (size_t f=F; f>0u; --f, ++X, ++T) { sm += *X * *T; }\n *Y = sm;\n }\n }\n }\n else\n {\n cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasTrans,(int)W,(int)B,(int)F,1.0,X,(int)F,T,(int)F,0.0,Y,(int)B);\n }\n \n return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "cd4141f15620bc3474c9ddf8bcb30d59b6e7428e", "size": 3270, "ext": "c", "lang": "C", "max_stars_repo_path": "c/apply_spectrogram_T_mat.c", "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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": "c/apply_spectrogram_T_mat.c", "max_issues_repo_name": "erikedwards4/aud", "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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/apply_spectrogram_T_mat.c", "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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.9340659341, "max_line_length": 154, "alphanum_fraction": 0.5403669725, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49658280501623997}} {"text": "/* filter/impulse.c\n *\n * Impulse detecting filters\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nstatic int filter_impulse(const double scale, const double epsilon, const double t, const gsl_vector * x, const gsl_vector * xmedian,\n gsl_vector * y, gsl_vector * xsigma, size_t * noutlier, gsl_vector_int * ioutlier);\n \n/*\ngsl_filter_impulse_alloc()\n Allocate a workspace for impulse detection filtering.\n\nInputs: K - number of samples in window; if even, it is rounded up to\n the next odd, to have a symmetric window\n\nReturn: pointer to workspace\n*/\n\ngsl_filter_impulse_workspace *\ngsl_filter_impulse_alloc(const size_t K)\n{\n gsl_filter_impulse_workspace *w;\n\n w = calloc(1, sizeof(gsl_filter_impulse_workspace));\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->movstat_workspace_p = gsl_movstat_alloc(K);\n if (w->movstat_workspace_p == 0)\n {\n gsl_filter_impulse_free(w);\n return NULL;\n }\n\n return w;\n}\n\nvoid\ngsl_filter_impulse_free(gsl_filter_impulse_workspace * w)\n{\n if (w->movstat_workspace_p)\n gsl_movstat_free(w->movstat_workspace_p);\n\n free(w);\n}\n\n/*\ngsl_filter_impulse()\n Apply an impulse detection filter to an input vector. The filter output is\n\ny_i = { x_i, |x_i - m_i| <= t * S_i\n { m_i, |x_i - m_i| > t * S_i\n\nwhere m_i is the median of the window W_i^H and S_i is the scale estimate (MAD, IQR, S_n, Q_n)\n\nInputs: endtype - how to handle signal end points\n scale_type - which statistic to use for scale estimate (MAD, IQR, etc)\n t - number of standard deviations required to identity outliers (>= 0)\n x - input vector, size n\n y - (output) filtered vector, size n\n xmedian - (output) vector of median values of x, size n\n xmedian_i = median of window centered on x_i\n xsigma - (output) vector of estimated local standard deviations of x, size n\n xsigma_i = sigma for i-th window: scale*MAD\n noutlier - (output) number of outliers detected\n ioutlier - (output) int array indicating outliers identified, size n; may be NULL\n ioutlier_i = 1 if outlier detected, 0 if not\n w - workspace\n\nNotes:\n*/\n\nint\ngsl_filter_impulse(const gsl_filter_end_t endtype, const gsl_filter_scale_t scale_type, const double t,\n const gsl_vector * x, gsl_vector * y, gsl_vector * xmedian, gsl_vector * xsigma, size_t * noutlier,\n gsl_vector_int * ioutlier, gsl_filter_impulse_workspace * w)\n{\n const size_t n = x->size;\n\n if (n != y->size)\n {\n GSL_ERROR(\"input and output vectors must have same length\", GSL_EBADLEN);\n }\n else if (xmedian->size != n)\n {\n GSL_ERROR(\"xmedian vector must match input size\", GSL_EBADLEN);\n }\n else if (xsigma->size != n)\n {\n GSL_ERROR(\"xsigma vector must match input size\", GSL_EBADLEN);\n }\n else if ((ioutlier != NULL) && (ioutlier->size != n))\n {\n GSL_ERROR(\"ioutlier vector must match input size\", GSL_EBADLEN);\n }\n else if (t < 0.0)\n {\n GSL_ERROR(\"t must be non-negative\", GSL_EDOM);\n }\n else\n {\n int status;\n double scale = 1.0;\n\n switch (scale_type)\n {\n case GSL_FILTER_SCALE_MAD:\n {\n /* compute window medians and MADs */\n gsl_movstat_mad(endtype, x, xmedian, xsigma, w->movstat_workspace_p);\n\n break;\n }\n\n case GSL_FILTER_SCALE_IQR:\n {\n /* multiplication factor for IQR to estimate stddev for Gaussian signal */\n scale = 0.741301109252801;\n\n /* calculate the window medians */\n gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p);\n \n /* calculate window IQRs */\n gsl_movstat_qqr(endtype, x, 0.25, xsigma, w->movstat_workspace_p);\n\n break;\n }\n\n case GSL_FILTER_SCALE_SN:\n {\n /* calculate the window medians */\n gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p);\n \n /* calculate window S_n values */\n gsl_movstat_Sn(endtype, x, xsigma, w->movstat_workspace_p);\n\n break;\n }\n\n case GSL_FILTER_SCALE_QN:\n {\n /* calculate the window medians */\n gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p);\n \n /* calculate window Q_n values */\n gsl_movstat_Qn(endtype, x, xsigma, w->movstat_workspace_p);\n\n break;\n }\n\n default:\n GSL_ERROR(\"unknown scale type\", GSL_EDOM);\n break;\n }\n\n /* apply impulse detecting filter using previously computed scale estimate */\n status = filter_impulse(scale, 0.0, t, x, xmedian, y, xsigma, noutlier, ioutlier);\n\n return status;\n }\n}\n\n/*\nfilter_impulse()\n Apply an impulse detection filter to an input vector. The filter output is\n\ny_i = { x_i, |x_i - m_i| <= t * S_i OR S_i < epsilon\n { m_i, |x_i - m_i| > t * S_i\n\nwhere m_i is the median of the window W_i^H and S_i is the scale estimate (MAD, IQR, etc)\n\nInputs: scale - scale factor to multiply xsigma to get unbiased estimate of stddev for Gaussian data\n epsilon - minimum allowed scale estimate for identifying outliers\n t - number of standard deviations required to identity outliers (>= 0)\n x - input vector, size n\n xmedian - vector of median values of x, size n\n xmedian_i = median of window centered on x_i\n y - (output) filtered vector, size n\n xsigma - (output) vector of estimated local standard deviations of x, size n\n xsigma_i = S_n for i-th window\n noutlier - (output) number of outliers detected\n ioutlier - (output) int array indicating outliers identified, size n; may be NULL\n ioutlier_i = 1 if outlier detected, 0 if not\n\nNotes:\n1) If S_i = 0 or is very small for a particular sample, then the filter may erroneously flag the\nsample as an outlier, since it will act as a standard median filter. To avoid this scenario, the\nparameter epsilon specifies the minimum value of S_i which can be used in the filter test. Any\nsamples for which S_i < epsilon are passed through unchanged.\n*/\n\nstatic int\nfilter_impulse(const double scale, const double epsilon, const double t, const gsl_vector * x, const gsl_vector * xmedian,\n gsl_vector * y, gsl_vector * xsigma, size_t * noutlier, gsl_vector_int * ioutlier)\n{\n const size_t n = x->size;\n\n if (n != y->size)\n {\n GSL_ERROR(\"input and output vectors must have same length\", GSL_EBADLEN);\n }\n else if (xmedian->size != n)\n {\n GSL_ERROR(\"xmedian vector must match input size\", GSL_EBADLEN);\n }\n else if (xsigma->size != n)\n {\n GSL_ERROR(\"xsigma vector must match input size\", GSL_EBADLEN);\n }\n else if ((ioutlier != NULL) && (ioutlier->size != n))\n {\n GSL_ERROR(\"ioutlier vector must match input size\", GSL_EBADLEN);\n }\n else if (t < 0.0)\n {\n GSL_ERROR(\"t must be non-negative\", GSL_EDOM);\n }\n else\n {\n size_t i;\n\n *noutlier = 0;\n\n /* build output vector */\n for (i = 0; i < n; ++i)\n {\n double xi = gsl_vector_get(x, i);\n double xmedi = gsl_vector_get(xmedian, i);\n double absdevi = fabs(xi - xmedi); /* absolute deviation for this sample */\n double *xsigmai = gsl_vector_ptr(xsigma, i);\n\n /* multiply by scale factor to get estimate of standard deviation */\n *xsigmai *= scale;\n\n /*\n * If the absolute deviation for this sample is more than t stddevs\n * for this window (and S_i is sufficiently large to avoid scale implosion),\n * set the output value to the window median, otherwise use the original sample\n */\n if ((*xsigmai >= epsilon) && (absdevi > t * (*xsigmai)))\n {\n gsl_vector_set(y, i, xmedi);\n ++(*noutlier);\n if (ioutlier)\n gsl_vector_int_set(ioutlier, i, 1);\n }\n else\n {\n gsl_vector_set(y, i, xi);\n if (ioutlier)\n gsl_vector_int_set(ioutlier, i, 0);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "201aa1050746c468b9cb635749180893f3fdf96b", "size": 9362, "ext": "c", "lang": "C", "max_stars_repo_path": "test/lib/gsl-2.6/filter/impulse.c", "max_stars_repo_name": "karanbirsandhu/nu-sense", "max_stars_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "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": "test/lib/gsl-2.6/filter/impulse.c", "max_issues_repo_name": "karanbirsandhu/nu-sense", "max_issues_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/filter/impulse.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9647887324, "max_line_length": 133, "alphanum_fraction": 0.6179235206, "num_tokens": 2341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.49651941445493847}} {"text": "/* randist/gamma.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#include \n\nstatic double gamma_large (const gsl_rng * r, const double a);\nstatic double gamma_frac (const gsl_rng * r, const double a);\n\n/* The Gamma distribution of order a>0 is defined by:\n\n p(x) dx = {1 / \\Gamma(a) b^a } x^{a-1} e^{-x/b} dx\n\n for x>0. If X and Y are independent gamma-distributed random\n variables of order a1 and a2 with the same scale parameter b, then\n X+Y has gamma distribution of order a1+a2.\n\n The algorithms below are from Knuth, vol 2, 2nd ed, p. 129. */\n\ndouble\ngsl_ran_gamma_knuth (const gsl_rng * r, const double a, const double b)\n{\n /* assume a > 0 */\n unsigned int na = floor (a);\n\n if (a == na)\n {\n return b * gsl_ran_gamma_int (r, na);\n }\n else if (na == 0)\n {\n return b * gamma_frac (r, a);\n }\n else\n {\n return b * (gsl_ran_gamma_int (r, na) + gamma_frac (r, a - na)) ;\n }\n}\n\ndouble\ngsl_ran_gamma_int (const gsl_rng * r, const unsigned int a)\n{\n if (a < 12)\n {\n unsigned int i;\n double prod = 1;\n\n for (i = 0; i < a; i++)\n {\n prod *= gsl_rng_uniform_pos (r);\n }\n\n /* Note: for 12 iterations we are safe against underflow, since\n the smallest positive random number is O(2^-32). This means\n the smallest possible product is 2^(-12*32) = 10^-116 which\n is within the range of double precision. */\n\n return -log (prod);\n }\n else\n {\n return gamma_large (r, (double) a);\n }\n}\n\nstatic double\ngamma_large (const gsl_rng * r, const double a)\n{\n /* Works only if a > 1, and is most efficient if a is large\n\n This algorithm, reported in Knuth, is attributed to Ahrens. A\n faster one, we are told, can be found in: J. H. Ahrens and\n U. Dieter, Computing 12 (1974) 223-246. */\n\n double sqa, x, y, v;\n sqa = sqrt (2 * a - 1);\n do\n {\n do\n {\n y = tan (M_PI * gsl_rng_uniform (r));\n x = sqa * y + a - 1;\n }\n while (x <= 0);\n v = gsl_rng_uniform (r);\n }\n while (v > (1 + y * y) * exp ((a - 1) * log (x / (a - 1)) - sqa * y));\n\n return x;\n}\n\nstatic double\ngamma_frac (const gsl_rng * r, const double a)\n{\n /* This is exercise 16 from Knuth; see page 135, and the solution is\n on page 551. */\n\n double p, q, x, u, v;\n p = M_E / (a + M_E);\n do\n {\n u = gsl_rng_uniform (r);\n v = gsl_rng_uniform_pos (r);\n\n if (u < p)\n {\n x = exp ((1 / a) * log (v));\n q = exp (-x);\n }\n else\n {\n x = 1 - log (v);\n q = exp ((a - 1) * log (x));\n }\n }\n while (gsl_rng_uniform (r) >= q);\n\n return x;\n}\n\ndouble\ngsl_ran_gamma_pdf (const double x, const double a, const double b)\n{\n if (x < 0)\n {\n return 0 ;\n }\n else if (x == 0)\n {\n if (a == 1)\n return 1/b ;\n else\n return 0 ;\n }\n else if (a == 1)\n {\n return exp(-x/b)/b ;\n }\n else \n {\n double p;\n double lngamma = gsl_sf_lngamma (a);\n p = exp ((a - 1) * log (x/b) - x/b - lngamma)/b;\n return p;\n }\n}\n\n\n/* New version based on Marsaglia and Tsang, \"A Simple Method for\n * generating gamma variables\", ACM Transactions on Mathematical\n * Software, Vol 26, No 3 (2000), p363-372.\n *\n * Implemented by J.D.Lamb@btinternet.com, minor modifications for GSL\n * by Brian Gough\n */\n\ndouble\ngsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b)\n{\n return gsl_ran_gamma (r, a, b);\n}\n\ndouble\ngsl_ran_gamma (const gsl_rng * r, const double a, const double b)\n{\n /* assume a > 0 */\n\n if (a < 1)\n {\n double u = gsl_rng_uniform_pos (r);\n return gsl_ran_gamma (r, 1.0 + a, b) * pow (u, 1.0 / a);\n }\n\n {\n double x, v, u;\n double d = a - 1.0 / 3.0;\n double c = (1.0 / 3.0) / sqrt (d);\n\n while (1)\n {\n do\n {\n x = gsl_ran_gaussian_ziggurat (r, 1.0);\n v = 1.0 + c * x;\n }\n while (v <= 0);\n\n v = v * v * v;\n u = gsl_rng_uniform_pos (r);\n\n if (u < 1 - 0.0331 * x * x * x * x) \n break;\n\n if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))\n break;\n }\n \n return b * d * v;\n }\n}\n", "meta": {"hexsha": "37d167cd945f17b14998d8787d539fb156afd5ff", "size": 5118, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/gamma.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/gamma.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/gamma.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.1583710407, "max_line_length": 81, "alphanum_fraction": 0.5617428683, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.4955326868163908}} {"text": "/*\n * SpectrumTransformer.h\n *\n * Created on: Jul 30, 2015\n * Author: dpayne\n */\n\n#ifndef _SPECTRUM_TRANSFORMER_H\n#define _SPECTRUM_TRANSFORMER_H\n\n#include \n#include \"Transformer/GenericTransformer.h\"\n#include \"Writer/NcursesWriter.h\"\n#include \"Domain/Settings.h\"\n\nnamespace vis\n{\n\nclass SpectrumTransformer : public GenericTransformer\n{\n public:\n explicit SpectrumTransformer(const Settings *const settings);\n\n ~SpectrumTransformer() override;\n\n void execute_mono(pcm_stereo_sample *buffer,\n vis::NcursesWriter *writer) override;\n void execute_stereo(pcm_stereo_sample *buffer,\n vis::NcursesWriter *writer) override;\n\n private:\n void execute(pcm_stereo_sample *buffer, vis::NcursesWriter *writer,\n const bool is_stereo);\n const Settings *const m_settings;\n\n /** --- BEGIN MEMBER VARIABLES --- */\n\n /** --- BEGIN --- fft calculations vars **/\n size_t m_fftw_results;\n\n double *m_fftw_input_left;\n double *m_fftw_input_right;\n\n fftw_complex *m_fftw_output_left;\n fftw_complex *m_fftw_output_right;\n\n fftw_plan m_fftw_plan_left;\n fftw_plan m_fftw_plan_right;\n /** --- END --- fft calculations vars **/\n\n /** --- BEGIN --- frequency cutoff calculations vars **/\n std::vector m_low_cutoff_frequencies;\n\n std::vector m_high_cutoff_frequencies;\n\n std::vector m_frequency_constants_per_bin;\n\n int32_t m_previous_win_width; // Used to determine if freq cutoffs need to\n // be re-calculated\n /** --- END --- frequency cutoff calculations vars **/\n\n uint64_t m_silent_runs; // Used to determine if the transformer should sleep\n // and wait for input\n\n // Holds the current bar heights after processing, this is done as a member\n // function to avoid memory allocations on every run\n std::vector m_bars_left;\n std::vector m_bars_right;\n\n // falloff vectors hold the previous runs values, this is used to to apply\n // falloff effect for the current run\n std::vector m_bars_falloff_left;\n std::vector m_bars_falloff_right;\n\n std::vector m_previous_max_heights;\n\n // Used by monstercat smoothing to apply weights to a bar's height as\n // determined by it's frequency range\n // Note: this is only re-computed when screen width changes\n std::vector m_monstercat_smoothing_weights;\n\n // Pre-compute colors calculations to avoid duplicate work\n // Note: this is only re-computed when screen height changes\n std::vector m_precomputed_colors;\n\n /** --- END MEMBER VARIABLES --- */\n\n /** --- BEGIN MEMBER FUNCTIONS --- */\n\n /**\n * Copies the channel given by \"channel_mode\" to the fftw_input buffer\n */\n bool prepare_fft_input(pcm_stereo_sample *buffer, uint32_t sample_size,\n double *fftw_input, ChannelMode channel_mode);\n\n /**\n * Populates \"bars\" and \"bars_falloff\" with the bar heights to be displayed\n */\n virtual void create_spectrum_bars(fftw_complex *fftw_output,\n const size_t fftw_results,\n const int32_t win_height,\n const int32_t win_width,\n const uint32_t number_of_bars,\n std::vector &bars,\n std::vector &bars_falloff);\n\n void\n generate_bars(std::vector &bars, const uint32_t number_of_bars,\n const fftw_complex *fftw_output, const size_t fftw_results,\n const std::vector &low_cutoff_frequencies,\n const std::vector &high_cutoff_frequencies) const;\n\n void recalculate_cutoff_frequencies(\n uint32_t number_of_bars, std::vector *low_cutoff_frequencies,\n std::vector *high_cutoff_frequencies,\n std::vector *freqconst_per_bin);\n\n /**\n * Applies the smoothing operations based on the settings in m_settings to\n * \"bars\"\n */\n void smooth_bars(std::vector &bars);\n\n /**\n * Applies the falloff effect based on the settings in m_settings to \"bars\".\n * The old falloff from the previous run should be in \"falloff_bars\". The\n * new falloff values will be updated in-place in \"falloff_bars\"\n */\n std::vector apply_falloff(const std::vector &bars,\n std::vector &falloff_bars) const;\n\n /**\n * Calculates the moving average and the standard deviation for a given\n * range of elements.\n *\n * \"new_value\" is added to \"old_values\".\n *\n * If \"old_values.size()\" > \"max_number_of_elements\" the first element of\n * old_values is erased.\n */\n void calculate_moving_average_and_std_dev(\n const double new_value, const size_t max_number_of_elements,\n std::vector &old_values, double *moving_average,\n double *std_dev) const;\n\n /**\n * A long term and short term running average are kept of the max bar\n * heights for each frame. If the short term running average is very\n * different than the long term running average then the scaling size\n * should be reset to better suit the current music.\n *\n * This happens commonly if a there is a new song that is a lot quieter\n * or louder than the previous song.\n */\n void maybe_reset_scaling_window(const double current_max_height,\n const size_t max_number_of_elements,\n std::vector *values,\n double *moving_average, double *std_dev);\n\n /**\n * Renders the spectrum bars to the screen.\n */\n virtual void draw_bars(const std::vector &bars,\n const std::vector &bars_falloff,\n int32_t win_height, const bool flipped,\n const std::wstring &bar_row_msg,\n vis::NcursesWriter *writer);\n\n /**\n * Scaling the given vector of points \"bars\" to a fit a screen with a window\n * height of \"height\".\n */\n virtual void scale_bars(std::vector &bars, const int32_t height);\n\n /**\n * Creates the to be used for every section of the bar to be printed. For\n * example if the bar width is set to two, and the bar character to '#'.\n * Then the bar row msg would be \"##\";\n */\n std::wstring create_bar_row_msg(const wchar_t character,\n uint32_t bar_width);\n\n /**\n * Savitzky-Golay smoothng. This type of smoothing is usually much faster\n * than monstercat.\n *\n * https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter\n */\n void sgs_smoothing(std::vector &bars);\n\n /**\n * This type of smoothing is inspired by monstercat\n * (https://www.youtube.com/user/MonstercatMedia). The code was largely\n * taken from cava git@github.com:karlstav/cava.git\n */\n void monstercat_smoothing(std::vector &bars);\n\n /** --- END MEMBER FUNCTIONS --- */\n};\n}\n\n#endif\n", "meta": {"hexsha": "64fc7151e26031f2bab55dd00b011ce3e970688a", "size": 7328, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Transformer/SpectrumTransformer.h", "max_stars_repo_name": "kevinarefunny/cli-visualizer", "max_stars_repo_head_hexsha": "5ab9253830f51918840da7b067bed132aabda2f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-16T07:22:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-16T07:22:51.000Z", "max_issues_repo_path": "src/Transformer/SpectrumTransformer.h", "max_issues_repo_name": "kevinarefunny/cli-visualizer", "max_issues_repo_head_hexsha": "5ab9253830f51918840da7b067bed132aabda2f3", "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/Transformer/SpectrumTransformer.h", "max_forks_repo_name": "kevinarefunny/cli-visualizer", "max_forks_repo_head_hexsha": "5ab9253830f51918840da7b067bed132aabda2f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0985221675, "max_line_length": 80, "alphanum_fraction": 0.6352347162, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.49551219729488827}} {"text": "/* The MIT License\n\n Copyright (c) 2013-2015 Genome Research Ltd.\n\n Author: Petr Danecek \n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n\n */\n\n#include \"peakfit.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define NPARAMS 5\n\n// gauss params: sqrt(scale), center, sigma\ntypedef struct _peak_t\n{\n int fit_mask;\n double params[NPARAMS], ori_params[NPARAMS]; // current and input parameters\n struct { int scan; double min, max, best; } mc[NPARAMS]; // monte-carlo settings and best parameter\n void (*calc_f) (int nvals, double *xvals, double *yvals, void *args);\n void (*calc_df) (int nvals, double *xvals, double *yvals, double *dfvals, int idf, void *args);\n void (*print_func) (struct _peak_t *pk, kstring_t *str);\n void (*convert_get) (struct _peak_t *pk, double *params);\n double (*convert_set) (struct _peak_t *pk, int iparam, double value);\n}\npeak_t;\n\nstruct _peakfit_t\n{\n int npeaks, mpeaks, nparams, mparams;\n peak_t *peaks;\n double *params;\n int nvals, mvals;\n double *xvals, *yvals, *vals;\n kstring_t str;\n int verbose, nmc_iter;\n};\n\n\n/*\n Gaussian peak with the center bound in the interval :\n yi = scale^2 * exp(-(xi-z)^2/sigma^2)\n\n dy/dscale = 2*scale * EXP\n dy/dcenter = -scale^2 * sin(center) * (e-d) * (xi - z) * EXP / sigma^2\n dy/dsigma = 2*scale^2 * (xi - z)^2 * EXP / sigma^3\n\n where\n z = 0.5*(cos(center)+1)*(e-d) + d\n EXP = exp(-(xi-z)^2/sigma^2)\n*/\nvoid bounded_gaussian_calc_f(int nvals, double *xvals, double *yvals, void *args)\n{\n peak_t *pk = (peak_t*) args;\n\n double scale2 = pk->params[0] * pk->params[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n double d = pk->params[3];\n double e = pk->params[4];\n double z = 0.5*(cos(center)+1)*(e-d) + d;\n\n int i;\n for (i=0; iparams[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n double d = pk->params[3];\n double e = pk->params[4];\n double z = 0.5*(cos(center)+1)*(e-d) + d;\n\n int i;\n for (i=0; iparams[1];\n double d = pk->params[3];\n double e = pk->params[4];\n double z = 0.5*(cos(center)+1)*(e-d) + d;\n ksprintf(str,\"%f**2 * exp(-(x-%f)**2/%f**2)\",fabs(pk->params[0]),z,fabs(pk->params[2]));\n}\ndouble bounded_gaussian_convert_set(peak_t *pk, int iparam, double value)\n{\n if ( iparam!=1 ) return value;\n double d = pk->ori_params[3];\n double e = pk->ori_params[4];\n if ( valuee ) value = e;\n return acos(2*(value-d)/(e-d) - 1);\n}\nvoid bounded_gaussian_convert_get(peak_t *pk, double *params)\n{\n params[0] = fabs(pk->params[0]);\n params[2] = fabs(pk->params[2]);\n double center = pk->params[1];\n double d = pk->params[3];\n double e = pk->params[4];\n params[1] = 0.5*(cos(center)+1)*(e-d) + d;\n}\n\nvoid peakfit_add_bounded_gaussian(peakfit_t *pkf, double a, double b, double c, double d, double e, int fit_mask)\n{\n pkf->npeaks++;\n hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks);\n\n int i, nfit = 0;\n for (i=0; inparams += nfit;\n hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params);\n\n peak_t *pk = &pkf->peaks[pkf->npeaks-1];\n memset(pk, 0, sizeof(peak_t));\n\n pk->calc_f = bounded_gaussian_calc_f;\n pk->calc_df = bounded_gaussian_calc_df;\n pk->print_func = bounded_gaussian_sprint_func;\n pk->convert_set = bounded_gaussian_convert_set;\n pk->convert_get = bounded_gaussian_convert_get;\n pk->fit_mask = fit_mask;\n pk->ori_params[0] = a;\n pk->ori_params[2] = c;\n pk->ori_params[3] = d;\n pk->ori_params[4] = e;\n pk->ori_params[1] = pk->convert_set(pk, 1, b);\n}\n\n\n/*\n Gaussian peak:\n yi = scale^2 * exp(-(x-center)^2/sigma^2)\n\n dy/dscale = 2 * scale * EXP\n dy/dcenter = 2 * scale^2 * (x-center) * EXP / sigma^2\n dy/dsigma = 2 * scale^2 * (x-center)^2 * EXP / sigma^3\n\n where \n EXP = exp(-(x-center)^2/sigma^2)\n*/\nvoid gaussian_calc_f(int nvals, double *xvals, double *yvals, void *args)\n{\n peak_t *pk = (peak_t*) args;\n\n double scale2 = pk->params[0] * pk->params[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n\n int i;\n for (i=0; iparams[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n\n int i;\n for (i=0; iparams[0]),pk->params[1],fabs(pk->params[2]));\n}\nvoid gaussian_convert_get(peak_t *pk, double *params)\n{\n params[0] = fabs(pk->params[0]);\n params[1] = fabs(pk->params[1]);\n params[2] = fabs(pk->params[2]);\n}\n\n\nvoid peakfit_add_gaussian(peakfit_t *pkf, double a, double b, double c, int fit_mask)\n{\n pkf->npeaks++;\n hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks);\n\n int i, nfit = 0;\n for (i=0; inparams += nfit;\n hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params);\n\n peak_t *pk = &pkf->peaks[pkf->npeaks-1];\n memset(pk, 0, sizeof(peak_t));\n\n pk->calc_f = gaussian_calc_f;\n pk->calc_df = gaussian_calc_df;\n pk->print_func = gaussian_sprint_func;\n pk->convert_get = gaussian_convert_get;\n pk->fit_mask = fit_mask;\n pk->ori_params[0] = a;\n pk->ori_params[1] = b;\n pk->ori_params[2] = c;\n}\n\n\n/*\n exp peak:\n yi = scale^2 * exp((x-center)/sigma^2)\n\n dy/dscale = 2 * scale * EXP\n dy/dcenter = -scale^2 * EXP / sigma^2\n dy/dsigma = -2 * scale^2 * (x-center) * EXP / sigma^3\n\n where \n EXP = exp((x-center)/sigma^2)\n*/\nvoid exp_calc_f(int nvals, double *xvals, double *yvals, void *args)\n{\n peak_t *pk = (peak_t*) args;\n\n double scale2 = pk->params[0] * pk->params[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n\n int i;\n for (i=0; iparams[0];\n double center = pk->params[1];\n double sigma = pk->params[2];\n\n int i;\n for (i=0; iparams[0]),pk->params[1],fabs(pk->params[2]));\n}\nvoid exp_convert_get(peak_t *pk, double *params)\n{\n params[0] = fabs(pk->params[0]);\n params[1] = fabs(pk->params[1]);\n params[2] = fabs(pk->params[2]);\n}\n\nvoid peakfit_add_exp(peakfit_t *pkf, double a, double b, double c, int fit_mask)\n{\n pkf->npeaks++;\n hts_expand0(peak_t,pkf->npeaks,pkf->mpeaks,pkf->peaks);\n\n int i, nfit = 0;\n for (i=0; inparams += nfit;\n hts_expand0(double,pkf->nparams,pkf->mparams,pkf->params);\n\n peak_t *pk = &pkf->peaks[pkf->npeaks-1];\n memset(pk, 0, sizeof(peak_t));\n\n pk->calc_f = exp_calc_f;\n pk->calc_df = exp_calc_df;\n pk->print_func = exp_sprint_func;\n pk->convert_get = exp_convert_get;\n pk->fit_mask = fit_mask;\n pk->ori_params[0] = a;\n pk->ori_params[1] = b;\n pk->ori_params[2] = c;\n}\n\n\nvoid peakfit_set_params(peakfit_t *pkf, int ipk, double *params, int nparams)\n{\n peak_t *pk = &pkf->peaks[ipk];\n int i;\n if ( pk->convert_set )\n for (i=0; iparams[i] = pk->convert_set(pk, i, params[i]);\n else\n for (i=0; iparams[i] = params[i];\n}\n\nvoid peakfit_get_params(peakfit_t *pkf, int ipk, double *params, int nparams)\n{\n peak_t *pk = &pkf->peaks[ipk];\n if ( pk->convert_get ) pk->convert_get(pk, params);\n else\n {\n int i;\n for (i=0; iparams[i];\n }\n}\n\npeakfit_t *peakfit_init(void)\n{\n return (peakfit_t*)calloc(1,sizeof(peakfit_t));\n}\n\nvoid peakfit_reset(peakfit_t *pkf)\n{\n pkf->npeaks = pkf->nparams = 0;\n memset(pkf->peaks,0,sizeof(peak_t)*pkf->mpeaks);\n}\n\nvoid peakfit_destroy(peakfit_t *pkf)\n{\n free(pkf->str.s);\n free(pkf->vals);\n free(pkf->params);\n free(pkf->peaks);\n free(pkf);\n}\n\nint peakfit_calc_f(const gsl_vector *params, void *data, gsl_vector *yvals)\n{\n peakfit_t *pkf = (peakfit_t *) data;\n\n int i,j;\n for (i=0; invals; i++)\n pkf->vals[i] = 0;\n\n int iparam = 0;\n for (i=0; inpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n for (j=0; jfit_mask & (1<params[j] = gsl_vector_get(params,iparam);\n iparam++;\n }\n pk->calc_f(pkf->nvals, pkf->xvals, pkf->vals, pk);\n }\n\n for (i=0; invals; i++)\n gsl_vector_set(yvals, i, (pkf->vals[i] - pkf->yvals[i])/0.01);\n\n return GSL_SUCCESS;\n}\nint peakfit_calc_df(const gsl_vector *params, void *data, gsl_matrix *jacobian)\n{\n peakfit_t *pkf = (peakfit_t *) data;\n\n int i,j,k,iparam = 0;\n for (i=0; inpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n int iparam_prev = iparam;\n for (j=0; jfit_mask & (1<params[j] = gsl_vector_get(params,iparam);\n iparam++;\n }\n iparam = iparam_prev;\n for (j=0; jfit_mask & (1<nvals; k++) pkf->vals[k] = 0;\n pk->calc_df(pkf->nvals, pkf->xvals, pkf->yvals, pkf->vals, j, pk);\n for (k=0; knvals; k++) gsl_matrix_set(jacobian, k, iparam, pkf->vals[k]);\n iparam++;\n }\n }\n return GSL_SUCCESS;\n}\nint peakfit_calc_fdf(const gsl_vector *params, void *data, gsl_vector *yvals, gsl_matrix *jacobian)\n{\n peakfit_calc_f(params, data, yvals);\n peakfit_calc_df(params, data, jacobian);\n return GSL_SUCCESS;\n}\n\ndouble peakfit_evaluate(peakfit_t *pkf)\n{\n int i;\n for (i=0; invals; i++)\n pkf->vals[i] = 0;\n\n for (i=0; inpeaks; i++)\n pkf->peaks[i].calc_f(pkf->nvals, pkf->xvals, pkf->vals, &pkf->peaks[i]);\n\n double sum = 0;\n for (i=0; invals; i++)\n sum += fabs(pkf->vals[i] - pkf->yvals[i]);\n\n return sum;\n}\n\nconst char *peakfit_sprint_func(peakfit_t *pkf)\n{\n pkf->str.l = 0;\n int i;\n for (i=0; inpeaks; i++)\n {\n if ( i>0 ) kputs(\" + \", &pkf->str);\n pkf->peaks[i].print_func(&pkf->peaks[i], &pkf->str);\n }\n return (const char*)pkf->str.s;\n}\n\nvoid peakfit_verbose(peakfit_t *pkf, int level)\n{\n pkf->verbose = level;\n}\n\nvoid peakfit_set_mc(peakfit_t *pkf, double xmin, double xmax, int iparam, int niter)\n{\n peak_t *pk = &pkf->peaks[ pkf->npeaks-1 ];\n pk->mc[iparam].scan = 1;\n pk->mc[iparam].min = xmin;\n pk->mc[iparam].max = xmax;\n pkf->nmc_iter = niter;\n}\n\ndouble peakfit_run(peakfit_t *pkf, int nvals, double *xvals, double *yvals)\n{\n srand(0); // for reproducibility\n\n pkf->nvals = nvals;\n pkf->xvals = xvals;\n pkf->yvals = yvals;\n hts_expand0(double,pkf->nvals,pkf->mvals,pkf->vals);\n if ( !pkf->nparams ) return peakfit_evaluate(pkf);\n\n gsl_multifit_function_fdf mfunc;\n mfunc.f = &peakfit_calc_f;\n mfunc.df = &peakfit_calc_df;\n mfunc.fdf = &peakfit_calc_fdf;\n mfunc.n = nvals;\n mfunc.p = pkf->nparams;\n mfunc.params = pkf;\n\n const gsl_multifit_fdfsolver_type *solver_type;\n gsl_multifit_fdfsolver *solver;\n solver_type = gsl_multifit_fdfsolver_lmsder;\n solver = gsl_multifit_fdfsolver_alloc(solver_type, nvals, mfunc.p);\n gsl_vector *grad = gsl_vector_alloc(pkf->nparams);\n\n int imc_iter, i,j, iparam;\n double best_fit = HUGE_VAL;\n for (imc_iter=0; imc_iter<=pkf->nmc_iter; imc_iter++) // possibly multiple monte-carlo iterations\n {\n // set GSL parameters\n iparam = 0;\n for (i=0; inpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n for (j=0; jparams[j] = pk->ori_params[j];\n if ( pk->mc[j].scan )\n {\n pk->params[j] = rand()*(pk->mc[j].max - pk->mc[j].min)/RAND_MAX + pk->mc[j].min;\n if ( pk->convert_set ) pk->params[j] = pk->convert_set(pk, j, pk->params[j]);\n }\n if ( !(pk->fit_mask & (1<params[iparam] = pk->params[j];\n iparam++;\n }\n }\n\n gsl_vector_view vview = gsl_vector_view_array(pkf->params, mfunc.p);\n gsl_multifit_fdfsolver_set(solver, &mfunc, &vview.vector);\n\n // iterate until convergence (or lack of it)\n int ret, test1 = 0, test2 = 0, niter = 0, niter_max = 500;\n do\n {\n ret = gsl_multifit_fdfsolver_iterate(solver);\n if ( pkf->verbose >1 )\n {\n fprintf(stderr, \"%d: \", niter);\n for (i=0; inpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n fprintf(stderr,\"\\t%f %f %f\", pk->params[0],pk->params[1],pk->params[2]);\n }\n fprintf(stderr, \"\\t.. %s\\n\", gsl_strerror(ret));\n }\n if ( ret ) break;\n\n#if GSL_MAJOR_VERSION >= 2\n int info;\n test1 = gsl_multifit_fdfsolver_test(solver, 1e-8,1e-8, 0.0, &info);\n#else\n gsl_multifit_gradient(solver->J, solver->f, grad);\n test1 = gsl_multifit_test_gradient(grad, 1e-8);\n test2 = gsl_multifit_test_delta(solver->dx, solver->x, 1e-8, 1e-8);\n#endif\n }\n while ((test1==GSL_CONTINUE || test2==GSL_CONTINUE) && ++niterverbose >1 )\n {\n fprintf(stderr,\"test1=%s\\n\", gsl_strerror(test1));\n fprintf(stderr,\"test2=%s\\n\", gsl_strerror(test2));\n }\n\n // recover parameters\n iparam = 0;\n for (i=0; inpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n for (j=0; jfit_mask & (1<params[j] = gsl_vector_get(solver->x, iparam++);\n }\n }\n\n // evaluate fit, update best parameters\n double fit = peakfit_evaluate(pkf);\n if ( fitnpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n for (j=0; jmc[j].best = pk->params[j];\n }\n }\n if ( fitnpeaks; i++)\n {\n peak_t *pk = &pkf->peaks[i];\n for (j=0; jparams[j] = pk->mc[j].best;\n }\n return best_fit;\n}\n\n\n", "meta": {"hexsha": "8094b5d52b86dd675a9d8fec5542906e9ef9f28b", "size": 18029, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/bcftools/peakfit.c", "max_stars_repo_name": "benranco/test", "max_stars_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-05-07T21:12:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T16:14:22.000Z", "max_issues_repo_path": "tools/bcftools/peakfit.c", "max_issues_repo_name": "benranco/test", "max_issues_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-02-13T10:53:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T02:51:15.000Z", "max_forks_repo_path": "tools/bcftools/peakfit.c", "max_forks_repo_name": "benranco/test", "max_forks_repo_head_hexsha": "7cf9740108844da30dcc506e733015fd5dd76a05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-11-21T08:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T22:03:05.000Z", "avg_line_length": 29.7508250825, "max_line_length": 113, "alphanum_fraction": 0.5720783183, "num_tokens": 5865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.49538675863039544}} {"text": "/*! \\file GMatrix.h\n * \\brief this file defines the \\ref Math::GMatrix class that is part of the Math namespace\n */\n\n#ifndef GMATRIX_H\n#define GMATRIX_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nnamespace Math\n{\n\n/*! \\class Math::GMatrix\n \\brief General n x m matrix\n General matrix class that eventually should replace \\ref Math::Matrix class.\n will have to adjust error checks for this class and adjust inverse\n and make most calls inline to increase speed.\n*/\nclass GMatrix\n{\n private:\n\n int row,col;\n Double_t *matrix;\n\n protected:\n\n ///useful comparison functions which can be used with qsort\n int compare_Double(const void* a,const void* b) {\n Double_t arg1 = *((Double_t*) a);\n Double_t arg2 = *((Double_t*) b);\n if( arg1 < arg2 ) return -1;\n else if( arg1==arg2 ) return 0;\n else return 1;\n }\n\n public:\n\n /// \\name Constructors & Destructors\n //@{\n /// Constructor (where data can be is initilized) otherwise set to zero\n GMatrix(int r, int c, Double_t *data=NULL)\n {\n if (r*c>0){\n row=r;col=c;\n matrix=new Double_t[row*col];\n if (data!=NULL){\n for (int i = 0; i < row; i++)\n for (int j = 0; j < col; j++)\n matrix[i*col+j] = data[i*col+j];\n }\n else{\n for (int i = 0; i < row; i++)\n for (int j = 0; j < col; j++)\n matrix[i*col+j] = 0.;\n }\n }\n else {\n row=0;col=0;matrix=NULL;\n printf(\"Error, net size 0 with row,col=%d,%d\\n\",row,col);\n }\n }\n\n /// Constructor based on Coordinate.\n GMatrix(const Coordinate &c)\n {\n row=3;col=1;\n matrix=new Double_t[row*col];\n for (int i = 0; i < row; i++) matrix[i] = c[i];\n }\n\n /// Constructor Matrix\n GMatrix(const Matrix &m)\n {\n row=3;col=3;\n matrix=new Double_t[row*col];\n for (int i=0; i0&&col>0) delete[] matrix;\n }\n //@}\n\n /// \\name Get & Set functions\n //@{\n ///get row dimensions\n int Row()const {return row;}\n ///get col dimensions\n int Col()const {return col;}\n ///get rank\n int Rank()const {return min(row,col);}\n //@}\n\n /// \\name Overloaded Operators\n //@{\n /// How to access a matrix element: M(i, j)\n Double_t& operator () (int i, int j) {\n //if (j1e-32&&ipivot)){\n k++;\n if (k==row)k=0;\n ipivot=(P(k,k)==1);\n }\n P(j,j)=0;P(k,k)=0;\n P(j,k)=1;P(k,j)=1;\n for (int l=0;l1e-32&&ipivot)){\n k++;\n if (k==row)k=0;\n ipivot=(P(k,k)==1);\n }\n P(j,j)=0;P(k,k)=0;\n P(j,k)=1;P(k,j)=1;\n for (int l=0;l1e-8) return 0;\n return 1;\n }\n /// Check if matrix is zero matrix\n int isZero() const\n {\n Double_t sm=0;\n for (int i=0;ij : & l_{i1}*u_{1j}+l_{i2}*u_{2j}+...+l_{ij}*u_{ij}&=a_{ij}\n \\end{array}\n \\f]\n with condition that \\f$ l_{ii}=1 \\f$. \\n\n If matrix singular and no decomposition, print error and return zero matrix.\n Here matrix is singular if diagonal element is zero. \\n\n Must alter this to pivot method so that subroutine reorder matrix if necessary and diagonals\n can be zero.\n */\n GMatrix LUDecomp() const\n {\n if (row!=col) {\n printf(\"only implemented for square, returning zeros\\n\");\n return GMatrix(row,col);\n }\n else {\n Double_t A[row*col];\n Int_t i, j, k, p, p_k, p_row, p_col;\n for (j=0;j=0; p_i -= row, i-- ) {\n for (j = row - 1; j > i; j--) {\n U[p_i + j] = -U[p_i + j];\n for (k = i + 1, p_k = p_i + row; k < j; p_k += row, k++ )\n U[p_i + j] -= U[p_i + k] * U[p_k + j];\n }\n }\n return GMatrix(row,row,U);\n }\n\n /// \\brief Adjugate (classical adjoint) of matrix\n /// This is simply the transpose of the cofactor of the matrix\n GMatrix Adjugate() const\n {\n GMatrix cofactorT(row,col);\n for (int i=0;i 4 && (sqrt(eigen[ip]*eigen[ip])+temp1)==(sqrt(eigen[ip]*eigen[ip])+tol)\n && (sqrt(eigen[iq]*eigen[iq])+temp1)==(sqrt(eigen[iq]*eigen[iq])+tol))\n m(ip,iq)=0.0;\n else if (thres 4 && (sqrt(eigen[ip]*eigen[ip])+temp1)==(sqrt(eigen[ip]*eigen[ip])+tol)\n && (sqrt(eigen[iq]*eigen[iq])+temp1)==(sqrt(eigen[iq]*eigen[iq])+tol))\n m(ip,iq)=0.0;\n else if (thres=10) {\n printf(\"Too many iterations in routine jacobi, giving zeros\\n\");\n for (int i=0;ie1>e2..>eN\n //qsort(eigen.matrix,row,sizeof(Double_t),compare_Double);\n return eigen;\n }\n }\n\n // Computes the eigenvectors of the matrix, given the eigenvalues. Sadly, this function will only work\n // properly on symmetric matrices -- i.e., all real eigenvalues.\n //GMatrix Eigenvectors(const Coordinate& e) const;\n\n /// Calculate eigenvalues \\e and eigenvector of matrix of rank N. Stored as a GMatrix, e1, e2 ...eN.\n void Eigenvalvec(GMatrix &eigenval, GMatrix &eigenvector, Double_t tol=1e-2) const\n {\n if (isSymmetric()==0||isZero()==1) {\n printf(\"only implemented for nonzero symmetric matrices, returning null matrix\\n\");\n for (int i=0;i\n#include \n#include \"advanceCN.h\"\n#include \"applyBC.h\"\n#include \"userFunc.h\"\n#include \"ppmExtrap.h\"\n#include \"getNextIterate.h\"\n\n/**************************************************************************/\n/* Time step advance routine with Crank-Nicolson time centering */\n/**************************************************************************/\n\ndouble \nadvanceCN(const double t, const double dt, const grid *grd, \n\t double *col, double *pres, double *eInt,\n\t double *mBnd, double *eBnd, double *mSrc, double *eSrc,\n\t const bool eos_func, const double gamma_val, \n\t const double delta_val,\n\t const bool alpha_func, const double alpha_val,\n\t const pres_bc_type ibc_pres, const enth_bc_type ibc_enth,\n\t const bool ibc_func, const double ibc_pres_val, \n\t const double ibc_enth_val,\n\t const pres_bc_type obc_pres, const enth_bc_type obc_enth,\n\t const bool obc_func, const double obc_pres_val, \n\t const double obc_enth_val,\n\t const bool massSrc_func, const double massSrc_val,\n\t const bool intEnSrc_func, const double intEnSrc_val,\n\t const double errTol, const double dtTol, \n\t const unsigned long maxIter, const unsigned long interpOrder, \n\t const bool noUpdate, const bool verbose,\n\t const wksp *w, void *params, unsigned long *itCount\n#ifdef TESTING_MODE\n\t , double *resid, unsigned long *rtype,\n\t double *advanceTime, double *nextIterTime,\n\t double *userTime\n#endif\n\t ) {\n\n double pIn, qIn, pOut, qOut;\n double err, errCell;\n double dPres, dCol, dEInt, dtMin;\n double ibc_pres_val1, ibc_enth_val1, obc_pres_val1, obc_enth_val1;\n double h_up, h_up1;\n double mBndTemp[2], eBndTemp[2];\n unsigned long maxErrCell, converged, residType;\n long i;\n#if AA_M > 0\n long nHist;\n double residMax = 0.0;\n#endif\n#ifdef TESTING_MODE\n clock_t start_t, end_t, user_start_t, user_end_t;\n clock_t next_iter_start_t, next_iter_end_t;\n\n start_t = clock();\n#endif\n\n /****************************************************************/\n /* Step 1: initialize workspace arrays from starting conditions */\n /****************************************************************/\n\n /* Copy column density and pressure */\n for (i=0; inr; i++) {\n w->colNew[i] = col[i];\n w->pres_g[i+1] = w->presNew_g[i+1] = pres[i];\n }\n /* Evaluate EOS parameters and get enthalpy */\n if (eos_func == 1) {\n#if AA_M > 0\n nHist = 3*grd->nr;\n#endif\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userEOS(t, dt, grd, col, pres, eInt, params,\n\t w->gammaLast, w->deltaLast);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n / CLOCKS_PER_SEC;\n#endif\n for (i=0; inr; i++) {\n w->eIntTmp[i] = w->eIntNew[i] = eInt[i];\n w->gammaNew[i] = w->gammaLast[i];\n w->deltaNew[i] = w->deltaLast[i];\n w->hint_g[i+1] = (pres[i] + eInt[i])/col[i];\n }\n } else {\n#if AA_M > 0\n nHist = 2*grd->nr;\n#endif\n for (i=0; inr; i++) {\n w->gammaLast[i] = w->gammaNew[i] = gamma_val;\n w->deltaLast[i] = w->deltaNew[i] = delta_val;\n w->hint_g[i+1] = gamma_val/(gamma_val-1.0)*pres[i]/col[i];\n }\n }\n /* Get starting viscosity */\n if (alpha_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userAlpha(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, \n\t params, w->alpha_g+1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n / CLOCKS_PER_SEC;\n#endif\n } else {\n for (i=1; i<=grd->nr; i++) w->alpha_g[i] = alpha_val;\n }\n\n /* Store starting mass and energy fluxes through boundary */\n mBndTemp[0] = mBnd[0];\n mBndTemp[1] = mBnd[1];\n eBndTemp[0] = eBnd[0];\n eBndTemp[1] = eBnd[1];\n\n /* Store starting source function values */\n if (massSrc_func == 1) {\n for (i=0; inr; i++) {\n w->mSrc[i] = mSrc[i];\n w->eSrc[i] = eSrc[i];\n }\n } else if (intEnSrc_func == 1) {\n for (i=0; inr; i++) w->eSrc[i] = eSrc[i];\n }\n\n /****************************************************************/\n /* Step 2: apply boundary conditions at old time */\n /****************************************************************/\n\n /* Set alpha in ghost cells */\n w->alpha_g[0] = w->alpha_g[1];\n w->alpha_g[grd->nr+1] = w->alpha_g[grd->nr];\n\n /* Get pressure / enthalpy boundary values */\n if (ibc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userIBC(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, \n\t ibc_pres, ibc_enth, params, \n\t &ibc_pres_val1, &ibc_enth_val1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) /\n CLOCKS_PER_SEC;\n#endif\n } else {\n ibc_pres_val1 = ibc_pres_val;\n ibc_enth_val1 = ibc_enth_val;\n }\n if (obc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userOBC(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast, \n\t obc_pres, obc_enth, params, \n\t &obc_pres_val1, &obc_enth_val1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) /\n CLOCKS_PER_SEC;\n#endif\n } else {\n obc_pres_val1 = obc_pres_val;\n obc_enth_val1 = obc_enth_val;\n }\n\n /* Set boundary conditions from user-specified parameters */\n applyBC(grd, w->alpha_g, \n\t ibc_pres, ibc_enth, ibc_pres_val1, ibc_enth_val1,\n\t obc_pres, obc_enth, obc_pres_val1, obc_enth_val1,\n\t w->pres_g, w->hint_g, &pIn, &qIn, &pOut, &qOut);\n\n /****************************************************************/\n /* Step 3: get mass flux, source terms, and RHS at old time */\n /****************************************************************/\n\n /* Mass and energy source terms */\n if (massSrc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userMassSrc(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast,\n\t\tparams, w->massSrcLast);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) /\n CLOCKS_PER_SEC;\n#endif\n for (i=0; inr; i++) {\n w->mSrc[i] += 0.5 * dt * w->massSrcLast[i];\n w->eSrc[i] += 0.5 * dt * w->massSrcLast[i] *\n\t(grd->psiEff_g[i+1] + w->deltaLast[i]*pres[i]/col[i]);\n }\n } else {\n for (i=0; inr; i++) w->massSrcLast[i] = massSrc_val;\n }\n if (intEnSrc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userIntEnSrc(t, dt, grd, col, pres, eInt, w->gammaLast, w->deltaLast,\n\t\t params, w->intEnSrc);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) /\n CLOCKS_PER_SEC;\n#endif\n for (i=0; inr; i++)\n w->eSrc[i] += 0.5 * dt * w->intEnSrc[i];\n } else {\n for (i=0; inr; i++) w->intEnSrc[i] = intEnSrc_val;\n }\n\n /* Reconstruct internal enthalpies at cell edges */\n if (interpOrder == 1) {\n for (i=0; i<=grd->nr+1; i++)\n w->hintL_g[i] = w->hintR_g[i] = w->hint_g[i];\n } else if (interpOrder == 2) {\n if (grd->linear == 1) {\n for (i=1; i<=grd->nr+1; i++)\n\tw->hintR_g[i-1] = w->hintL_g[i] = \n\t ((grd->r_g[i]-grd->r_h[i-1]) * w->hint_g[i-1] +\n\t (grd->r_h[i-1]-grd->r_g[i-1]) * w->hint_g[i]) /\n\t (grd->r_g[i] - grd->r_g[i-1]);\n } else {\n for (i=1; i<=grd->nr+1; i++)\n\tw->hintR_g[i-1] = w->hintL_g[i] = \n\t (log(grd->r_g[i]/grd->r_h[i-1]) * w->hint_g[i-1] +\n\t log(grd->r_h[i-1]/grd->r_g[i-1]) * w->hint_g[i]) /\n\t log(grd->r_g[i]/grd->r_g[i-1]);\n }\n /* Limit the slope */\n for (i=1; i<=grd->nr+1; i++) {\n if (w->hintR_g[i-1]/w->hint_g[i-1]-1.0 > SLOPELIMIT) {\n\tw->hintR_g[i-1] = w->hint_g[i-1]*(1.0+SLOPELIMIT);\n } else if (w->hintR_g[i-1]/w->hint_g[i-1] < 1.0-SLOPELIMIT) {\n\tw->hintR_g[i-1] = w->hint_g[i-1]*(1.0-SLOPELIMIT);\n }\n if (w->hintL_g[i]/w->hint_g[i]-1.0 > SLOPELIMIT) {\n\tw->hintL_g[i] = w->hint_g[i]*(1.0+SLOPELIMIT);\n } else if (w->hintL_g[i]/w->hint_g[i] < 1.0-SLOPELIMIT) {\n\tw->hintL_g[i] = w->hint_g[i]*(1.0-SLOPELIMIT);\n }\n }\n } else if (interpOrder == 3) {\n ppmExtrap(grd->nr+2, grd->dr_g, w->hint_g, w->hintL_g, w->hintR_g, \n\t w->ppmwksp_g);\n }\n\n /* Compute fluxes at cell edges */\n for (i=0; i<=grd->nr; i++) {\n\n /* Mass flux; initialize the new mass flux to match the old one,\n as is appropriate for the first guess in the iteration below */\n w->fmLast_h[i] = w->fmNew_h[i] = -grd->g_h[i] *\n (SQR(grd->r_g[i+1])*(1-grd->beta_g[i+1]) * \n w->pres_g[i+1]*w->alpha_g[i+1] - \n SQR(grd->r_g[i])*(1-grd->beta_g[i]) * \n w->pres_g[i]*w->alpha_g[i]);\n\n /* Enthalpy flux; use upwinding */\n if (w->fmLast_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i];\n else h_up = w->hintL_g[i+1] + grd->psiEff_h[i];\n w->feLast_h[i] = h_up * w->fmLast_h[i];\n\n /* Torque flux */\n w->ftLast_h[i] = M_PI * grd->r_h[i] * grd->vphi_h[i] *\n (1-grd->beta_h[i]) *\n (w->pres_g[i+1]*w->alpha_g[i+1] + \n w->pres_g[i]*w->alpha_g[i]);\n }\n\n /* Fill RHS vector */\n for (i=0; inr; i++) {\n gsl_vector_set(w->rhs_g, i+1, \n\t\t pres[i] - 0.5*dt/grd->area[i] *\n\t\t (w->gammaLast[i]-1.0) * \n\t\t (w->feLast_h[i+1] - w->feLast_h[i] +\n\t\t w->ftLast_h[i+1] - w->ftLast_h[i] -\n\t\t (grd->psiEff_g[i+1] + \n\t\t w->deltaLast[i+1]*pres[i]/col[i]) \n\t\t *(w->fmLast_h[i+1] - w->fmLast_h[i])) +\n\t\t 0.5*dt*(w->gammaLast[i]-1) * w->intEnSrc[i]);\n }\n \n /* Zero out energy source, since below we expect this to\n be the rate from the previous iteration of the loop */\n for (i=0; inr; i++) w->intEnSrc[i] = 0.0;\n\n /****************************************************************/\n /* Step 4: main iteration loop */\n /****************************************************************/\n\n /* Status message */\n if (verbose)\n printf(\"advanceCN: starting iteration, dt = %e\\n\", dt);\n\n /* Start loop */\n for (*itCount = 1, converged = 0; 1; (*itCount)++) {\n\n /**************************************************************/\n /* Step 4a: compute enthalpy, alpha, and BC for current guess */\n /**************************************************************/\n\n /* Get new EOS parameters and cell-center enthalpies */\n if (eos_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userEOS(t+dt, dt, grd, w->colNew, w->presNew_g+1, w->eIntNew,\n\t params, w->gammaNew, w->deltaNew);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n for (i=1; i<=grd->nr; i++) \n\tw->hint_g[i] = (w->presNew_g[i] + w->eIntNew[i-1]) /\n\t w->colNew[i-1];\n } else {\n for (i=1; i<=grd->nr; i++) {\n\tw->hint_g[i] = gamma_val/(gamma_val-1.0) * \n\t w->presNew_g[i]/w->colNew[i-1];\n }\n }\n\n /* If alpha is non-constant, get new values */\n if (alpha_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userAlpha(t+dt, dt, grd, w->colNew, w->presNew_g+1, \n\t\tw->eIntNew, w->gammaNew, \n\t\tw->deltaNew, params, w->alpha_g+1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n w->alpha_g[0] = w->alpha_g[1];\n w->alpha_g[grd->nr+1] = w->alpha_g[grd->nr];\n }\n\n /* Subtract off energy source term from previous iteration; we\n need to do this here because we're about to update gamma */\n for (i=0; inr; i++) {\n gsl_vector_set(w->rhs_g, i+1, \n\t\t gsl_vector_get(w->rhs_g, i+1) - \n\t\t 0.5*dt*(w->gammaNew[i]-1)*w->intEnSrc[i]);\n }\n\n /* Get new pressure / enthalpy boundary values */\n if (ibc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userIBC(t+dt, dt, grd, w->colNew, w->presNew_g+1, \n\t w->eIntNew, w->gammaNew, w->deltaNew, \n\t ibc_pres, ibc_enth, params, \n\t &ibc_pres_val1, &ibc_enth_val1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n }\n if (obc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userOBC(t+dt, dt, grd, w->colNew, w->presNew_g+1, \n\t w->eIntNew, w->gammaNew, w->deltaNew, \n\t obc_pres, obc_enth, params, \n\t &obc_pres_val1, &obc_enth_val1);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n }\n\n /* Set boundary conditions from user-specified parameters, and\n also set ghost cell elements in RHS matrix */\n applyBC(grd, w->alpha_g, \n\t ibc_pres, ibc_enth, ibc_pres_val1, ibc_enth_val1,\n\t obc_pres, obc_enth, obc_pres_val1, obc_enth_val1,\n\t w->presNew_g, w->hint_g, &pIn, &qIn, &pOut, &qOut);\n gsl_vector_set(w->rhs_g, 0, pIn);\n gsl_vector_set(w->rhs_g, grd->nr+1, pOut);\n\n /* Get new enthalpies at cell centers and extrapolated to cell edges */\n if (interpOrder == 1) {\n for (i=0; i<=grd->nr+1; i++)\n\tw->hintL_g[i] = w->hintR_g[i] = w->hint_g[i];\n } else if (interpOrder == 2) {\n if (grd->linear == 1) {\n\tfor (i=1; i<=grd->nr+1; i++)\n\t w->hintR_g[i-1] = w->hintL_g[i] = \n\t ((grd->r_g[i]-grd->r_h[i-1]) * w->hint_g[i-1] +\n\t (grd->r_h[i-1]-grd->r_g[i-1]) * w->hint_g[i]) /\n\t (grd->r_g[i] - grd->r_g[i-1]);\n } else {\n\tfor (i=1; i<=grd->nr+1; i++)\n\t w->hintR_g[i-1] = w->hintL_g[i] = \n\t (log(grd->r_g[i]/grd->r_h[i-1]) * w->hint_g[i-1] +\n\t log(grd->r_h[i-1]/grd->r_g[i-1]) * w->hint_g[i]) /\n\t log(grd->r_g[i]/grd->r_g[i-1]);\n }\n /* Limit the slope */\n for (i=1; i<=grd->nr+1; i++) {\n\tif (w->hintR_g[i-1]/w->hint_g[i-1]-1.0 > SLOPELIMIT) {\n\t w->hintR_g[i-1] = w->hint_g[i-1]*(1.0+SLOPELIMIT);\n\t} else if (w->hintR_g[i-1]/w->hint_g[i-1] < 1.0-SLOPELIMIT) {\n\t w->hintR_g[i-1] = w->hint_g[i-1]*(1.0-SLOPELIMIT);\n\t}\n\tif (w->hintL_g[i]/w->hint_g[i]-1.0 > SLOPELIMIT) {\n\t w->hintL_g[i] = w->hint_g[i]*(1.0+SLOPELIMIT);\n\t} else if (w->hintL_g[i]/w->hint_g[i] < 1.0-SLOPELIMIT) {\n\t w->hintL_g[i] = w->hint_g[i]*(1.0-SLOPELIMIT);\n\t}\n }\n } else if (interpOrder == 3) {\n ppmExtrap(grd->nr+2, grd->dr_g, w->hint_g, w->hintL_g, w->hintR_g, \n\t\tw->ppmwksp_g);\n }\n\n /**************************************************************/\n /* Step 4b: add energy source term to RHS vector for pressure */\n /* solve */\n /**************************************************************/\n\n /* If source term can vary, compute its value for this \n iteration */\n if (intEnSrc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userIntEnSrc(t+dt, dt, grd, w->colNew, w->presNew_g+1, \n\t\t w->eIntNew, w->gammaNew, w->deltaNew, params, \n\t\t w->intEnSrc);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n }\n for (i=0; inr; i++) {\n gsl_vector_set(w->rhs_g, i+1, \n\t\t gsl_vector_get(w->rhs_g, i+1) +\n\t\t 0.5*dt*(w->gammaNew[i]-1)*w->intEnSrc[i]);\n }\n\n /**************************************************************/\n /* Step 4c: construct the tridiagonal matrix */\n /**************************************************************/\n\n /* Upper diagonal */\n gsl_vector_set(w->ud_g, 0, -qIn);\n for (i=1; i<=grd->nr; i++) {\n if (w->fmNew_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i];\n else h_up = w->hintL_g[i+1] + grd->psiEff_h[i];\n gsl_vector_set(w->ud_g, i,\n\t\t 0.5*dt*w->alpha_g[i+1]*(w->gammaNew[i-1]-1.0)\n\t\t / grd->area[i-1] *\n\t\t (grd->g_h[i]*SQR(grd->r_g[i+1]) *\n\t\t (1-grd->beta_g[i+1]) *\n\t\t (grd->psiEff_g[i]\n\t\t + w->deltaNew[i-1] * \n\t\t w->presNew_g[i]/w->colNew[i-1] \n\t\t - h_up) +\n\t\t M_PI*grd->r_h[i]*grd->vphi_h[i] *\n\t\t (1-grd->beta_h[i])));\n }\n\n /* Lower diagonal */\n for (i=0; inr; i++) {\n if (w->fmNew_h[i] > 0) h_up = w->hintR_g[i] + grd->psiEff_h[i];\n else h_up = w->hintL_g[i+1] + grd->psiEff_h[i];\n gsl_vector_set(w->ld_g, i,\n\t\t 0.5*dt*w->alpha_g[i]*(w->gammaNew[i]-1.0)\n\t\t / grd->area[i] *\n\t\t (grd->g_h[i]*SQR(grd->r_g[i]) *\n\t\t (1-grd->beta_g[i]) *\n\t\t (grd->psiEff_g[i+1] \n\t\t + w->deltaNew[i] * \n\t\t w->presNew_g[i+1]/w->colNew[i]\n\t\t - h_up) -\n\t\t M_PI*grd->r_h[i]*grd->vphi_h[i] *\n\t\t (1-grd->beta_h[i])));\n }\n gsl_vector_set(w->ld_g, grd->nr, -qOut);\n\n /* Diagonal */\n for (i=1; i<=grd->nr; i++) {\n if (w->fmNew_h[i-1] > 0) h_up = w->hintR_g[i-1] + grd->psiEff_h[i-1];\n else h_up = w->hintL_g[i] + grd->psiEff_h[i-1];\n if (w->fmNew_h[i] > 0) h_up1 = w->hintR_g[i] + grd->psiEff_h[i];\n else h_up1 = w->hintL_g[i+1] + grd->psiEff_h[i];\n gsl_vector_set(w->diag_g, i,\n\t\t 1.0 + 0.5*dt*w->alpha_g[i]*(w->gammaNew[i-1]-1.0) \n\t\t / grd->area[i-1] *\n\t\t ((grd->g_h[i]*\n\t\t (h_up1 - grd->psiEff_g[i]\n\t\t\t- w->deltaNew[i-1] * \n\t\t\tw->presNew_g[i]/w->colNew[i-1]) +\n\t\t grd->g_h[i-1]*\n\t\t (h_up - grd->psiEff_g[i]\n\t\t\t- w->deltaNew[i-1] * \n\t\t\tw->presNew_g[i]/w->colNew[i-1])) *\n\t\t SQR(grd->r_g[i]) * (1-grd->beta_g[i]) +\n\t\t M_PI*(grd->r_h[i]*grd->vphi_h[i]*\n\t\t\t (1-grd->beta_h[i]) -\n\t\t\t grd->r_h[i-1]*grd->vphi_h[i-1]*\n\t\t\t (1-grd->beta_h[i-1]))));\n }\n\n /**************************************************************/\n /* Step 4d: solve the matrix equation to get the new pressure */\n /* guess */\n /**************************************************************/\n\n if (gsl_linalg_solve_tridiag(w->diag_g, w->ud_g, w->ld_g, \n\t\t\t\t w->rhs_g, w->presTmp_g)) {\n /* Non-zero return code means error has occured, probably due to\n\t bad inputs data. Bail out, and let the driver try again */\n if (verbose) \n\tprintf(\" ...iteration %ld, detected NaN or Inf in tridiagonal inputs, exiting without convergence!\\n\", *itCount);\n#ifdef TESTING_MODE\n end_t = clock();\n *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC;\n#endif\n return(-1.0);\n }\n\n /**************************************************************/\n /* Step 4e: get the new column density guess */\n /**************************************************************/\n\n /* Get new mass fluxes */\n for (i=0; i<=grd->nr; i++)\n w->fmNew_h[i] = -grd->g_h[i] * \n\t(SQR(grd->r_g[i+1])*\n\t (1-grd->beta_g[i+1]) *\n\t gsl_vector_get(w->presTmp_g, i+1)*w->alpha_g[i+1] - \n\t SQR(grd->r_g[i])*\n\t (1-grd->beta_g[i]) * \n\t gsl_vector_get(w->presTmp_g, i)*w->alpha_g[i]);\n\n /* Get source terms at new time */\n if (massSrc_func == 1) {\n#ifdef TESTING_MODE\n user_start_t = clock();\n#endif\n userMassSrc(t+dt, dt, grd, w->colNew, w->presNew_g, w->eIntNew,\n\t\t w->gammaNew, w->deltaNew, params, w->massSrcNew);\n#ifdef TESTING_MODE\n user_end_t = clock();\n *userTime += (double) (user_end_t - user_start_t) \n\t/ CLOCKS_PER_SEC;\n#endif\n } else {\n for (i=0; inr; i++) w->massSrcNew[i] = massSrc_val;\n }\n\n /* Get new column density guess */\n for (i=0; inr; i++) {\n w->colTmp[i] = col[i] - dt/grd->area[i] * 0.5 *\n\t(w->fmNew_h[i+1] - w->fmNew_h[i] + \n\t w->fmLast_h[i+1] - w->fmLast_h[i]) +\n\tdt * 0.5 * (w->massSrcLast[i] + w->massSrcNew[i]);\n }\n\n /**************************************************************/\n /* Step 4f: if doing separate internal energy evolution, get */\n /* new internal energy guess */\n /**************************************************************/\n\n if (eos_func == 1) {\n for (i=0; inr; i++) {\n\tw->eIntTmp[i] = eInt[i] + \n\t 0.5 * (1.0/(w->gammaLast[i]-1.0) + \n\t\t 1.0/(w->gammaNew[i]-1.0)) *\n\t (gsl_vector_get(w->presTmp_g, i+1) - pres[i]) +\n\t 0.5 * \n\t (w->deltaLast[i]*pres[i]/col[i] +\n\t w->deltaNew[i]*gsl_vector_get(w->presTmp_g, i+1) / \n\t w->colTmp[i]) * (w->colTmp[i]-col[i]);\n }\n }\n\n /**************************************************************/\n /* Step 4g: check for convergence or loop termination; print */\n /* status message */\n /**************************************************************/\n\n /* Compute residuals on pressure */\n err = 0.0;\n maxErrCell = -1;\n residType = 0;\n for (i=0; inr; i++) {\n if (!isfinite(gsl_vector_get(w->presTmp_g, i+1))) {\n\t/* If we've diverged to the point of getting inf's, we won't\n\t converge, so bail out */\n\n\tif (verbose) \n\t printf(\" ...iteration %ld, detected NaN or Inf in tridiagonal solution, cell %ld, exiting without convergence!\\n\", *itCount, i);\n#ifdef TESTING_MODE\n\tend_t = clock();\n\t*advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC;\n#endif\n\treturn(-1.0);\n }\n errCell = (gsl_vector_get(w->presTmp_g, i+1) - \n\t\t w->presNew_g[i+1]) /\n\tgsl_vector_get(w->presTmp_g, i+1);\n if (fabs(errCell) > fabs(err)) {\n\tmaxErrCell = i;\n\terr = errCell;\n }\n }\n\n /* Compute residuals on column density */\n for (i=0; inr; i++) {\n errCell = (w->colTmp[i] - w->colNew[i]) / w->colTmp[i];\n if (fabs(errCell) > fabs(err)) {\n\tmaxErrCell = i;\n\terr = errCell;\n\tresidType = 1;\n }\n }\n\n /* Compute residuals on internal energy */\n for (i=0; inr; i++) {\n errCell = (w->eIntTmp[i] - w->eIntNew[i]) / w->eIntTmp[i];\n if (fabs(errCell) > fabs(err)) {\n\tmaxErrCell = i;\n\terr = errCell;\n\tresidType = 2;\n }\n }\n\n#ifdef TESTING_MODE\n /* In testing mode, store residuals and residual type */\n resid[*itCount-1] += err;\n rtype[*itCount-1] = residType;\n#endif\n\n /* Print status */\n if (fabs(err) < errTol) converged = 1;\n if (verbose) {\n printf(\" ...iteration %ld, max residual = %e in cell %ld\",\n\t *itCount, err, maxErrCell);\n if (residType==0) \n\tprintf(\" pressure\\n\");\n else if (residType==1)\n\tprintf(\" density\\n\");\n else if (residType==2)\n\tprintf(\" internal energy\\n\");\n if (converged == 1) {\n\tprintf(\" ...converged!\\n\");\n } else if (*itCount == maxIter) {\n\tprintf(\" ...reached maximum iterations, exiting without convergence! Max residual = %e in cell %ld\\n\",\n\t err, maxErrCell);\n }\n }\n\n /* If we have converged, shift temporaries into final arrays, then\n exit the loop */\n if (converged) {\n for (i=0; inr; i++) {\n\tw->colNew[i] = w->colTmp[i];\n\tw->presNew_g[i+1] = gsl_vector_get(w->presTmp_g, i+1);\n\tif (eos_func == 1)\n\t w->eIntNew[i] = w->eIntTmp[i];\n }\n w->presNew_g[0] = gsl_vector_get(w->presTmp_g, 0);\n w->presNew_g[grd->nr+1] = gsl_vector_get(w->presTmp_g, grd->nr+1);\n break;\n }\n\n /* If we've exceeded iteration limit, bail out */\n if (*itCount == maxIter) {\n#ifdef TESTING_MODE\n end_t = clock();\n *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC;\n#endif\n return(-1.0);\n }\n\n /**************************************************************/\n /* Step 4h: if we're here, we haven't converged yet, so use */\n /* Anderson acceleration to generate new guesses at solution */\n /**************************************************************/\n\n#ifdef TESTING_MODE\n next_iter_start_t = clock();\n#endif\n getNextIterate(grd, eos_func, w\n#if AA_M > 0\n\t\t , *itCount, nHist, &residMax\n#endif\n\t\t );\n#ifdef TESTING_MODE\n next_iter_end_t = clock();\n *nextIterTime += (double) (next_iter_end_t - next_iter_start_t) /\n CLOCKS_PER_SEC;\n#endif\n\n } /* End main iteration loop */\n \n /****************************************************************/\n /* Step 5: compute rate of change of pressure and column */\n /* density; use this to estimate new time step */\n /****************************************************************/\n\n dtMin = LARGE;\n for (i=0; inr; i++) {\n dCol = fabs(w->colNew[i] - col[i]) + SMALL;\n dPres = fabs(w->presNew_g[i+1] - pres[i]) + SMALL;\n dtMin = fmin( dtMin, dtTol*dt * \n\t\t fmin(col[i]/dCol, pres[i]/dPres) );\n if (eos_func == 1) {\n dEInt = fabs(w->eIntNew[i] - eInt[i]) + SMALL;\n dtMin = fmin( dtMin, dtTol*dt * eInt[i]/dEInt );\n }\n }\n if (verbose > 0)\n printf(\"advanceCN: estimated dtNew = %e\\n\", dtMin);\n\n /****************************************************************/\n /* Step 6: record the total mass and energy transported across */\n /* the inner and outer boundaries during this time step. */\n /****************************************************************/\n\n /* Mass fluxes */\n mBndTemp[0] += 0.5*dt*(w->fmLast_h[0] + w->fmNew_h[0]);\n mBndTemp[1] += 0.5*dt*(w->fmLast_h[grd->nr] + w->fmNew_h[grd->nr]);\n\n /* Old time energy fluxes */\n eBndTemp[0] += 0.5*dt*(w->feLast_h[0] + w->ftLast_h[0]);\n eBndTemp[1] += 0.5*dt*(w->feLast_h[grd->nr] + w->ftLast_h[grd->nr]);\n\n /* New time energy fluxes; need to get enthalpy to evaluate f_E */\n if (w->fmNew_h[0] > 0) h_up = w->hintR_g[0] + grd->psiEff_h[0];\n else h_up = w->hintL_g[1] + grd->psiEff_h[0];\n eBndTemp[0] += 0.5*dt*h_up*w->fmNew_h[0];\n if (w->fmNew_h[grd->nr] > 0) \n h_up1 = w->hintR_g[grd->nr] + grd->psiEff_h[grd->nr];\n else h_up1 = w->hintL_g[grd->nr+1] + grd->psiEff_h[grd->nr];\n eBndTemp[1] += 0.5*dt*h_up1*w->fmNew_h[grd->nr];\n\n /* New time torque fluxes */\n eBndTemp[0] += 0.5*dt*M_PI*grd->r_h[0]*grd->vphi_h[0]*(1.0-grd->beta_h[0]) *\n (w->presNew_g[1]*w->alpha_g[1] + w->presNew_g[0]*w->alpha_g[0]);\n eBndTemp[1] += 0.5*dt*M_PI*grd->r_h[grd->nr]*grd->vphi_h[grd->nr]\n *(1.0-grd->beta_h[grd->nr]) *\n (w->presNew_g[grd->nr+1]*w->alpha_g[grd->nr+1] \n + w->presNew_g[grd->nr]*w->alpha_g[grd->nr]);\n\n /****************************************************************/\n /* Step 7: if using source functions, record total mass and */\n /* energy added to every cell by sources */\n /****************************************************************/\n;\n if (massSrc_func == 1) {\n for (i=0; inr; i++) {\n w->mSrc[i] += 0.5 * dt * w->massSrcNew[i];\n w->eSrc[i] += 0.5 * dt * w->massSrcNew[i] *\n\t(grd->psiEff_g[i+1] + \n\t w->deltaNew[i]*w->presNew_g[i+1]/w->colNew[i]);\n }\n }\n if (intEnSrc_func == 1) {\n for (i=0; inr; i++)\n w->eSrc[i] += 0.5 * dt * w->intEnSrc[i];\n }\n\n /****************************************************************/\n /* Step 8: store final values in arrays */\n /****************************************************************/\n\n if (noUpdate==0) {\n for (i=0; inr; i++) {\n pres[i] = w->presNew_g[i+1];\n col[i] = w->colNew[i];\n }\n if (eos_func==1)\n for (i=0; inr; i++) eInt[i] = w->eIntNew[i];\n mBnd[0] = mBndTemp[0];\n mBnd[1] = mBndTemp[1];\n eBnd[0] = eBndTemp[0];\n eBnd[1] = eBndTemp[1];\n if (massSrc_func == 1) {\n for (i=0; inr; i++) {\n\tmSrc[i] = w->mSrc[i];\n\teSrc[i] = w->eSrc[i];\n }\n } else if (intEnSrc_func == 1) {\n for (i=0; inr; i++) eSrc[i] = w->eSrc[i];\n }\n }\n\n /****************************************************************/\n /* Step 9: return new time step */\n /****************************************************************/\n\n#ifdef TESTING_MODE\n end_t = clock();\n *advanceTime += (double) (end_t - start_t) / CLOCKS_PER_SEC;\n#endif\n return(dtMin);\n}\n\n\n\n", "meta": {"hexsha": "e1b9c950b0fd448c109b5c7ed9412049367d5f5f", "size": 27353, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/advanceCN.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 33.3166869671, "max_line_length": 133, "alphanum_fraction": 0.5161408255, "num_tokens": 9257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4953502775009135}} {"text": "#include \n#include \n#include \n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n//Double exponential disk potential\ndouble DoubleExponentialDiskPotentialEval(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 double amp, alpha;\n int nzeros, glorder;\n if ( R > 6. ) { //Approximate as Keplerian\n nzeros= (int) *(args+4);\n glorder= (int) *(args+5);\n amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));\n alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));\n return - *args * amp * pow(R*R+z*z,1.-0.5*alpha) / (alpha - 2.);\n }\n //Get args\n amp= *args++;\n alpha= *args++;\n double beta= *args++;\n double kmaxFac= *args++;\n double kmax= kmaxFac * beta;\n nzeros= (int) *args++;\n glorder= (int) *args++;\n double * glx= args;\n double * glw= args + glorder;\n double * j0zeros= args + 2 * glorder;\n double * dj0zeros= args + 2 * glorder + nzeros + 1;\n //Calculate potential\n double out= 0.;\n double k;\n int ii, jj;\n if ( R < 1. ) kmax= kmax/R;\n for (ii=0; ii < ( nzeros + 1 ); ii++) {\n for (jj=0; jj < glorder; jj++) {\n k= 0.5 * ( *(glx+jj) + 1. ) * *(dj0zeros+ii+1) + *(j0zeros+ii);\n out+= *(glw+jj) * *(dj0zeros+ii+1) * gsl_sf_bessel_J0(k*R) \n\t* pow(alpha * alpha + k * k,-1.5) \n\t* (beta * exp(-k * fabs(z) ) - k * exp(-beta * fabs(z) ))\n\t/ (beta * beta - k * k);\n }\n if ( k > kmax ) break;\n }\n return - amp * 2 * M_PI * alpha * out;\n}\ndouble DoubleExponentialDiskPotentialRforce(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 double amp, alpha;\n int nzeros,glorder;\n if ( R > 6. ) { //Approximate as Keplerian\n nzeros= (int) *(args+4);\n glorder= (int) *(args+5);\n amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));\n alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));\n return - *args * amp * R * pow(R*R+z*z,-0.5*alpha);\n }\n //Get args\n amp= *args++;\n alpha= *args++;\n double beta= *args++;\n double kmaxFac= *args++;\n double kmax= 2. * kmaxFac * beta;\n nzeros= (int) *args++;\n glorder= (int) *args++;\n double * glx= args;\n double * glw= args + glorder;\n double * j1zeros= args + 2 * glorder + 2 * (nzeros + 1);\n double * dj1zeros= args + 2 * glorder + 3 * (nzeros + 1);\n //Calculate potential\n double out= 0.;\n double k;\n int ii, jj;\n if ( R < 1. ) kmax= kmax/R;\n for (ii=0; ii < ( nzeros + 1 ); ii++) {\n for (jj=0; jj < glorder; jj++) {\n k= 0.5 * ( *(glx+jj) + 1. ) * *(dj1zeros+ii+1) + *(j1zeros+ii);\n out+= *(glw+jj) * *(dj1zeros+ii+1) * k * gsl_sf_bessel_J1(k*R) \n\t* pow(alpha * alpha + k * k,-1.5) \n\t* (beta * exp(-k * fabs(z) ) - k * exp(-beta * fabs(z) ))\n\t/ (beta * beta - k * k);\n }\n if ( k > kmax ) break;\n }\n return - amp * 2 * M_PI * alpha * out;\n}\ndouble DoubleExponentialDiskPotentialPlanarRforce(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 double amp, alpha;\n int nzeros, glorder;\n if ( R > 6. ) { //Approximate as Keplerian\n nzeros= (int) *(args+4);\n glorder= (int) *(args+5);\n amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));\n alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));\n return - *args * amp * pow(R,-alpha + 1.);\n }\n //Get args\n amp= *args++;\n alpha= *args++;\n double beta= *args++;\n double kmaxFac= *args++;\n double kmax= 2. * kmaxFac * beta;\n nzeros= (int) *args++;\n glorder= (int) *args++;\n double * glx= args;\n double * glw= args + glorder;\n double * j1zeros= args + 2 * glorder + 2 * (nzeros + 1);\n double * dj1zeros= args + 2 * glorder + 3 * (nzeros + 1);\n //Calculate potential\n double out= 0.;\n double k;\n int ii, jj;\n if ( R < 1. ) kmax= kmax/R;\n for (ii=0; ii < ( nzeros + 1 ); ii++) {\n for (jj=0; jj < glorder; jj++) {\n k= 0.5 * ( *(glx+jj) + 1. ) * *(dj1zeros+ii+1) + *(j1zeros+ii);\n out+= *(glw+jj) * *(dj1zeros+ii+1) * k * gsl_sf_bessel_J1(k*R) \n\t* pow(alpha * alpha + k * k,-1.5) \n\t/ (beta + k);\n }\n if ( k > kmax ) break;\n }\n return - amp * 2 * M_PI * alpha * out;\n}\ndouble DoubleExponentialDiskPotentialzforce(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 double amp, alpha;\n int nzeros, glorder;\n if ( R > 6. ) { //Approximate as Keplerian\n nzeros= (int) *(args+4);\n glorder= (int) *(args+5);\n amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));\n alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));\n return - *args * amp * z * pow(R*R+z*z,-0.5*alpha);\n }\n //Get args\n amp= *args++;\n alpha= *args++;\n double beta= *args++;\n double kmaxFac= *args++;\n double kmax= kmaxFac * beta;\n nzeros= (int) *args++;\n glorder= (int) *args++;\n double * glx= args;\n double * glw= args + glorder;\n double * j0zeros= args + 2 * glorder;\n double * dj0zeros= args + 2 * glorder + nzeros + 1;\n //Calculate potential\n double out= 0.;\n double k;\n int ii, jj;\n if ( R < 1. ) kmax= kmax/R;\n for (ii=0; ii < ( nzeros + 1 ); ii++) {\n for (jj=0; jj < glorder; jj++) {\n k= 0.5 * ( *(glx+jj) + 1. ) * *(dj0zeros+ii+1) + *(j0zeros+ii);\n out+= *(glw+jj) * *(dj0zeros+ii+1) * k * gsl_sf_bessel_J0(k*R) \n\t* pow(alpha * alpha + k * k,-1.5) \n\t* (exp(-k * fabs(z) ) - exp(-beta * fabs(z) ))\n\t/ (beta * beta - k * k);\n }\n if ( k > kmax ) break;\n }\n if ( z > 0. )\n return - amp * 2 * M_PI * alpha * beta * out;\n else\n return amp * 2 * M_PI * alpha * beta * out;\n}\ndouble DoubleExponentialDiskPotentialDens(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 beta= *args;\n // calculate density\n return amp * exp ( - alpha * R - beta * fabs ( z ) );\n}\n", "meta": {"hexsha": "e634b1ef24f1d8168982463c6eb195407d1c684b", "size": 5933, "ext": "c", "lang": "C", "max_stars_repo_path": "galpy/potential/potential_c_ext/DoubleExponentialDiskPotential.c", "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "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": "galpy/potential/potential_c_ext/DoubleExponentialDiskPotential.c", "max_issues_repo_name": "gusbeane/galpy", "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "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/DoubleExponentialDiskPotential.c", "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3915343915, "max_line_length": 74, "alphanum_fraction": 0.5546940839, "num_tokens": 2204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.49531368172847795}} {"text": "\n/*\n*/\n\n#ifndef MINIMIZER_H\n#define MINIMIZER_H\n\n#include \n#include \"Vector.h\"\n#include \n\n#ifdef USE_GSL\nextern \"C\" {\n#include \n}\n\nnamespace PsimagLite {\n\ntemplate\ntypename FunctionType::FieldType myFunction(const gsl_vector *v, void *params)\n{\n\tFunctionType* ft = (FunctionType *)params;\n\treturn ft->operator()(v->data,v->size);\n}\n\ntemplate\nvoid myDfunction(const gsl_vector *v,\n void *params,\n gsl_vector* df)\n{\n\tFunctionType* ft = (FunctionType *)params;\n\tft->df(v->data,v->size,df->data,df->size);\n}\n\ntemplate\nvoid myFdFunction(const gsl_vector *v,\n void *params,\n double *f,\n gsl_vector *df)\n{\n\t*f = myFunction(v, params);\n\tmyDfunction(v, params, df);\n}\n\ntemplate\nclass Minimizer {\n\n\ttypedef typename FunctionType::FieldType FieldType;\n\ttypedef typename Vector::Type VectorType;\n\ttypedef Minimizer ThisType;\n\npublic:\n\n\tenum {GSL_SUCCESS=::GSL_SUCCESS, GSL_CONTINUE=::GSL_CONTINUE};\n\n\tMinimizer(FunctionType& function,SizeType maxIter, bool verbose = false)\n\t : function_(function),\n\t maxIter_(maxIter),\n\t verbose_(verbose),\n\t status_(100),\n\t gslT_(gsl_multimin_fminimizer_nmsimplex2),\n\t gslS_(gsl_multimin_fminimizer_alloc(gslT_,function_.size())),\n\t gslDt_(gsl_multimin_fdfminimizer_conjugate_fr),\n\t gslDs_(gsl_multimin_fdfminimizer_alloc (gslDt_, function_.size()))\n\t{}\n\n\t~Minimizer()\n\t{\n\t\tgsl_multimin_fminimizer_free(gslS_);\n\t\tgsl_multimin_fdfminimizer_free(gslDs_);\n\t}\n\n\tint simplex(VectorType& minVector,RealType delta=1e-3,RealType tolerance=1e-3)\n\t{\n\t\tgsl_vector *x;\n\t\t/* Starting point, */\n\t\tx = gsl_vector_alloc (function_.size());\n\t\tfor (SizeType i=0;i;\n\t\tfunc.n = function_.size();\n\t\tfunc.params = &function_;\n\t\tgsl_multimin_fminimizer_set (gslS_, &func, x, xs);\n\n\t\tSizeType iter = 0;\n\t\tRealType prevValue = 0;\n\n\t\tfor (;iterx->data,func.n);\n\t\t\t\tRealType diff = fabs(thisValue - prevValue);\n\t\t\t\tstd::cerr<<\"simplex: \"<x,iter);\n\t\tgsl_vector_free (x);\n\t\tgsl_vector_free (xs);\n\t\treturn iter;\n\t}\n\n\tint conjugateGradient(VectorType& minVector,\n\t RealType delta=1e-3,\n\t RealType delta2=1e-3,\n\t RealType tolerance=1e-3,\n\t SizeType saveEvery = 0)\n\t{\n\t\tgsl_vector *x;\n\t\t/* Starting point, */\n\t\tx = gsl_vector_alloc (function_.size());\n\t\tfor (SizeType i=0;i;\n\t\tfunc.df = myDfunction;\n\t\tfunc.fdf = myFdFunction;\n\t\tfunc.n = function_.size();\n\t\tfunc.params = &function_;\n\n\t\tgsl_multimin_fdfminimizer_set(gslDs_, &func, x, delta, delta2);\n\n\t\tRealType prevValue = 0;\n\t\tSizeType iter = 0;\n\t\tfor (;itergradient, tolerance);\n\n\t\t\tif (verbose_) {\n\t\t\t\tRealType thisValue = function_(gslDs_->x->data,func.n);\n\t\t\t\tRealType diff = fabs(thisValue - prevValue);\n\t\t\t\tstd::cerr<<\"conjugateGradient: \"<x);\n\t\t\t\tstd::cerr<<\" status= \"< 0 && iter%saveEvery==0)\n\t\t\t\tprintIntermediate(gslDs_->x, iter);\n\t\t}\n\n\t\tfound(minVector,gslDs_->x,iter);\n\t\tgsl_vector_free (x);\n\t\treturn iter;\n\t}\n\n\tint status() const { return status_; }\n\n\tString statusString() const\n\t{\n\t\tswitch (status_) {\n\t\tcase GSL_SUCCESS:\n\t\t\treturn \"GSL_SUCCESS\";\n\t\t\tbreak;\n\t\tcase GSL_CONTINUE:\n\t\t\treturn \"GSL_CONTINUE\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn \"UNKNOWN\";\n\t\t\tbreak;\n\t\t}\n\t}\n\nprivate:\n\n\tvoid found(VectorType& minVector,gsl_vector* x,SizeType iter)\n\t{\n\t\tfor (SizeType i=0;isize<<\"\\n\";\n\t\tfor (SizeType i=0;isize;i++)\n\t\t\tstd::cerr<(v,&function_,df);\n\t\tRealType sum = 0;\n\t\tfor (int i = 0; i < df->size; ++i) {\n\t\t\tRealType tmp = gsl_vector_get(df,i);\n\t\t\tsum += PsimagLite::conj(tmp) * tmp;\n\t\t}\n\n\t\tgsl_vector_free (df);\n\t\treturn sqrt(sum);\n\t}\n\n\tFunctionType& function_;\n\tSizeType maxIter_;\n\tbool verbose_;\n\tint status_;\n\tconst gsl_multimin_fminimizer_type *gslT_;\n\tgsl_multimin_fminimizer *gslS_;\n\tconst gsl_multimin_fdfminimizer_type *gslDt_;\n\tgsl_multimin_fdfminimizer *gslDs_;\n\n}; // class Minimizer\n}\n\n#else\n\nnamespace PsimagLite {\n\ntemplate\nclass Minimizer {\n\n\ttypedef typename FunctionType::FieldType FieldType;\n\ttypedef typename Vector::Type VectorType;\n\npublic:\n\n\tenum {GSL_SUCCESS=0, GSL_CONTINUE=1};\n\n\tMinimizer(FunctionType&,SizeType, bool = false)\n\t{\n\t\tString str(\"Minimizer needs the gsl\\n\");\n\t\tthrow RuntimeError(str);\n\t}\n\n\tint simplex(VectorType&,RealType=1e-3,RealType=1e-3)\n\t{\n\t\tString str(\"Minimizer needs the gsl\\n\");\n\t\tthrow RuntimeError(str);\n\t}\n\n\tint status() const { return 1; }\n\n\tString statusString() const\n\t{\n\t\treturn \"Minimizer needs the gsl\";\n\t}\n};\n\n} // namespace PsimagLite\n#endif\n\n#endif // MINIMIZER_H\n\n", "meta": {"hexsha": "1761598a5dcd9f0d506e4206298d76e06d3bdd89", "size": 6698, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Minimizer.h", "max_stars_repo_name": "npatel37/PsimagLiteORNL", "max_stars_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T22:13:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T22:13:51.000Z", "max_issues_repo_path": "src/Minimizer.h", "max_issues_repo_name": "npatel37/PsimagLiteORNL", "max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Minimizer.h", "max_forks_repo_name": "npatel37/PsimagLiteORNL", "max_forks_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0071684588, "max_line_length": 79, "alphanum_fraction": 0.6760226933, "num_tokens": 1913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.4952648037178069}} {"text": "/*\n For more information, please see: http://software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*/\n\n///@brief \n///@file DenseMatrixMultiplication.h\n\n#ifndef CORE_DATATYPES_DENSEMATRIXMULTIPLICATION_H\n#define CORE_DATATYPES_DENSEMATRIXMULTIPLICATION_H \n\n#if defined(HAVE_CBLAS)\n#if defined(__APPLE__)\n#include \n#else\nextern \"C\"{\n#include \n}\n#endif\n#endif\n\nnamespace SCIRun {\n\ntemplate \nvoid\nDenseMatrixGeneric::mult(const ColumnMatrix& x, ColumnMatrix& b,\n index_type beg, index_type end,\n int spVec) const\n{\n ASSERTEQ(x.nrows(), this->ncols_);\n ASSERTEQ(b.nrows(), this->nrows_);\n\n if (beg == -1) beg = 0;\n if (end == -1) end = this->nrows_;\n\n#if defined(HAVE_CBLAS)\n double ALPHA = 1.0;\n double BETA = 0.0;\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (end-beg),\n 1, this->ncols_, ALPHA, dataptr_+(beg*this->ncols_), this->ncols_,\n x.get_data_pointer(), 1, BETA,\n b.get_data_pointer()+beg, 1);\n#else\n\n double* xdata = x.get_data_pointer();\n double* bdata = b.get_data_pointer();\n\n size_type m8 = (this->ncols_)/8;\n size_type m = (this->ncols_)-m8*8;\n\n index_type i, j;\n if(!spVec)\n {\n for (i=beg; incols_; j++)\n {\n if (x[j])\n for (i=beg; i\nvoid\nDenseMatrixGeneric::multiply(ColumnMatrix& x, ColumnMatrix& b) const\n{\n index_type i, j;\n\n double* xdata = x.get_data_pointer();\n double* bdata = b.get_data_pointer();\n\n size_type m8 = (this->ncols_)/8;\n size_type m = (this->ncols_)-m8*8;\n\n for (i=0; inrows_; i++)\n {\n double sum=0;\n double* row = data[i];\n double* xd = xdata;\n for (j=0; j\nvoid\nDenseMatrixGeneric::mult_transpose(const ColumnMatrix& x, ColumnMatrix& b,\n index_type beg, index_type end,\n int spVec) const\n{\n // Compute At*x=b\n ASSERT(x.nrows() == this->nrows_);\n ASSERT(b.nrows() == this->ncols_);\n if (beg == -1) beg = 0;\n if (end == -1) end = this->ncols_;\n index_type i, j;\n if (!spVec)\n {\n for (i=beg; inrows_; j++)\n {\n sum+=data[j][i]*x[j];\n }\n b[i]=sum;\n }\n }\n else\n {\n for (i=beg; inrows_; j++)\n if (x[j])\n {\n double *row=data[j];\n for (i=beg; i\nDenseMatrix*\nDenseMatrixGeneric::make_diagonal_from_column(const ColumnMatrix& column, size_type rows, size_type cols)\n{\n DenseMatrix* result = zero_matrix(rows, cols);\n for (size_type i = 0; i < column.nrows(); ++i)\n (*result)[i][i] = column[i];\n\n return result;\n}\n\n} // End namespace SCIRun\n\n#endif\n", "meta": {"hexsha": "eb127bec2ede780e3660e9ee136a5c3fc23a36da", "size": 5269, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h", "max_stars_repo_name": "mhansen1/SCIRun", "max_stars_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h", "max_issues_repo_name": "mhansen1/SCIRun", "max_issues_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Datatypes/Legacy/Matrix/DenseMatrixMultiplication.h", "max_forks_repo_name": "mhansen1/SCIRun", "max_forks_repo_head_hexsha": "9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2114537445, "max_line_length": 108, "alphanum_fraction": 0.5581704308, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.49516395882630393}} {"text": "/* rng/lecuyer21.c\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/*\n * This generator is taken from\n *\n * Donald E. Knuth\n * The Art of Computer Programming\n * Volume 2\n * Third Edition\n * Addison-Wesley\n * Page 108\n *\n * This implementation copyright (C) 2001 Brian Gough, Carlo Perassi\n * and (C) 2003 Heiko Bauke.\n */\n\n#include \n#include \n#include \n\n#define AAA 40692\n#define MMM 2147483399UL\n#define QQQ 52774\n#define RRR 3791\n\nstatic inline unsigned long int ran_get (void *vstate);\nstatic double ran_get_double (void *vstate);\nstatic void ran_set (void *state, unsigned long int s);\n\ntypedef struct\n{\n unsigned long int x;\n}\nran_state_t;\n\nstatic inline unsigned long int\nran_get (void *vstate)\n{\n ran_state_t *state = (ran_state_t *) vstate;\n\n long int y = state->x;\n long int r = RRR * (y / QQQ);\n\n y = AAA * (y % QQQ) - r;\n if (y < 0)\n y += MMM;\n\n state->x = y;\n\n return state->x;\n}\n\nstatic double\nran_get_double (void *vstate)\n{\n ran_state_t *state = (ran_state_t *) vstate;\n\n return ran_get (state) / 2147483399.0;\n}\n\nstatic void\nran_set (void *vstate, unsigned long int s)\n{\n ran_state_t *state = (ran_state_t *) vstate;\n\n if ((s%MMM) == 0)\n s = 1; /* default seed is 1 */\n\n state->x = s % MMM;\n\n return;\n}\n\nstatic const gsl_rng_type ran_type = {\n \"lecuyer21\", /* name */\n MMM-1, /* RAND_MAX */\n 1, /* RAND_MIN */\n sizeof (ran_state_t),\n &ran_set,\n &ran_get,\n &ran_get_double\n};\n\nconst gsl_rng_type *gsl_rng_lecuyer21 = &ran_type;\n", "meta": {"hexsha": "ee581283ed5d14170c746642074513c76c349dd0", "size": 2275, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/rng/lecuyer21.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.75, "max_line_length": 81, "alphanum_fraction": 0.6624175824, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.4950793497483759}} {"text": "//#include \n#include \n#include \n#include \n#include \n\n#define NSPLINELD\t1001\n#define NSPLINEEZ\t1001\n#define NSPLINERR\t10001\n#define NSPLINEDF\t10001\ngsl_interp_accel *accLD, *accRed, *accEz, *accDF;\ngsl_spline *splineLD, *splineRed, *splineEz, *splineDF;\n\n#define MPC_IN_M\t\t3.08567758e22\n#define GPC_IN_M\t\t(1e3 * MPC_IN_M)\n#define C_LIGHT\t\t\t2.99792458e8\n#define HUBBLE0\t\t\t(1e5 * 0.71 / MPC_IN_M)\n#define DH\t\t\t\t(C_LIGHT / HUBBLE0 / GPC_IN_M)\n#define DH3\t\t\t\t(DH * DH * DH)\n\nvoid load_splines()\n{\n\tlong int i;\n\t\n\t// Luminosity distribution\n\n\taccLD = gsl_interp_accel_alloc();\n\tsplineLD = gsl_spline_alloc(gsl_interp_cspline, NSPLINELD);\n\t\n\tdouble z1[NSPLINELD], ld[NSPLINELD];\n\tFILE *fp1 = fopen(\"support_data/splines_LuminosityDistance.txt\",\"r\");\n\tfor ( i=0; i (v2)) ? (v1) : (v2));\n}\n\ndouble log_sum_exp(double x, double y)\n{\n\t//convert to natural log\n\tx /= M_LOG10E;\n\ty /= M_LOG10E;\n\t\n\tdouble mx = MAX(x,y);\n\tdouble val = log(exp(x - mx) + exp(y - mx)) + mx;\n\t\n\treturn val/M_LN10;\n}\n\ndouble log_subtract_exp(double x, double y)\n{\n\t// x >= y must be true!\n\tif (y>x)\n\t{\n\t\tfprintf(stderr, \"%lf < %lf !\\n\", x, y);\n\t\texit(-1);\n\t}\n\t//convert to natural log\n\tx /= M_LOG10E;\n\ty /= M_LOG10E;\n\tdouble val = x + log1p(-exp(y-x));\n\treturn val/M_LN10;\n}\n\ndouble lumdist_logpowint(double log_lum_min, double log_lum_max, double pwr)\n{\n\tdouble val;\n\tif ( pwr > -1.0 )\n\t{\n\t\tval = -pwr * log_lum_star_global - log10(pwr+1.0) + log_subtract_exp((pwr+1.0)*log_lum_max, (pwr+1.0)*log_lum_min);\n\t}\n\telse\n\t{\n\t\tval = -pwr * log_lum_star_global - log10(-(pwr+1.0)) + log_subtract_exp((pwr+1.0)*log_lum_min, (pwr+1.0)*log_lum_max);\n\t}\n\t//fprintf(stderr, \"%lf -> %lf : %lf\\n\", log_lum_min, log_lum_max, val);\n\treturn val;\n}\n\ndouble lumdist_logpowinv(double prob, double log_lum_min, double log_lum_max, double pwr)\n{\n\tdouble temp = lumdist_logpowint(log_lum_min, log_lum_max, pwr) + log10(prob);\n\ttemp += pwr * log_lum_star_global;\n\t\n\tif ( pwr > -1.0 )\n\t{\n\t\ttemp += log10(pwr+1.0);\n\t\ttemp = log_sum_exp((pwr+1.0)*log_lum_min, temp);\n\t}\n\telse\n\t{\n\t\ttemp += log10(-(pwr+1.0));\n\t\ttemp = log_subtract_exp((pwr+1.0)*log_lum_min, temp);\n\t}\n\n\treturn temp/(pwr+1.0);\n}\n\ndouble luminosity_distr_fast(double prob, double log_lum_min, double log_lum_max)\n{\n\t//fprintf(stderr, \"%lf, %lf, %lf, %lf, %lf, %lf\\n\", prob, log_lum_min, log_lum_max, log_lum_star_global, alpha1_global, beta1_global);\n\n\tdouble log_lum_int_lower = lumdist_logpowint(log_lum_min, log_lum_star_global, alpha1_global);\n\tdouble log_lum_int_upper = lumdist_logpowint(log_lum_star_global, log_lum_max, beta1_global);\n\tdouble log_lum_int_total = log_sum_exp(log_lum_int_lower, log_lum_int_upper);\n\tdouble lower_frac = pow(10.0, log_lum_int_lower - log_lum_int_total), upper_frac = 1.0 - lower_frac;\n\n\t//fprintf(stderr, \"%lf, %lf, %lf, %lf, %lf\\n\", log_lum_int_lower, log_lum_int_upper, log_lum_int_total, lower_frac, upper_frac);\n\n\tif ( prob <= lower_frac )\n\t{\n\t\treturn lumdist_logpowinv(prob/lower_frac, log_lum_min, log_lum_star_global, alpha1_global);\n\t}\n\telse\n\t{\n\t\treturn lumdist_logpowinv((prob - lower_frac)/upper_frac, log_lum_star_global, log_lum_max, beta1_global);\n\t}\n}\n\ndouble lum2flux_integrand(double E, void *params)\n{\n\tdouble *vals = (double *)params;\n\tdouble alpha = vals[0];\n\tdouble beta = vals[1];\n\tdouble E0 = vals[2];\n\tdouble Ebreak = vals[3];\n\n\tif ( E < Ebreak )\n\t{\n\t\treturn pow(E/100.0,alpha) * exp(-E/E0) * E;\n\t}\n\telse\n\t{\n\t\treturn pow((alpha-beta)*E0/100.0,alpha-beta) * exp(beta-alpha) * pow(E/100.0,beta) * E;\n\t}\n}\n\ndouble lum2flux_integral_numeric(double alpha, double beta, double Epeak, double Emin, double Emax)\n{\n\tdouble E0 = Epeak / (2.0+alpha);\n\tdouble Ebreak = (alpha-beta)*E0;\n\n\t//gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n\n\tdouble result, error;\n\tunsigned long int neval;\n\tdouble vals[4] = {alpha, beta, E0, Ebreak};\n\tgsl_function F;\n \tF.function = &lum2flux_integrand;\n \tF.params = &vals[0];\n\n \tgsl_set_error_handler_off();\n \t//gsl_integration_qag(&F, Emin, Emax, 1e-7, 1e-6, 1000, 1, w, &result, &error);\n \tgsl_integration_qng(&F, Emin, Emax, 1e-7, 1e-6, &result, &error, &neval);\n \t//fprintf(stderr, \"%d evaluations\\t\", neval);\n\n \t//gsl_integration_workspace_free (w);\n\n \treturn result;\n}\n\ndouble Redshift_distribution_unnormalized(double z, double n1, double n2, double z1)\n{\n\tif (z <= z1)\n\t{\n\t\treturn pow(1.0 + z, n1);\n\t} else {\n\t\treturn pow(1.0 + z1, n1 - n2) * pow(1.0 + z, n2);\n\t}\n}\n\ndouble Redshift_distribution_normalized(double z, double n0, double n1, double n2, double z1)\n{\n\treturn n0 * Redshift_distribution_unnormalized(z, n1, n2, z1);\n}\n\ndouble Redshift_rescaled(double z, void *params)\n{\n\tdouble *pars = (double *) params;\n\tdouble n0 = pars[0];\n\tdouble n1 = pars[1];\n\tdouble n2 = pars[2];\n\tdouble z1 = pars[3];\n\n\tdouble Rprime = Redshift_distribution_normalized(z, n0, n1, n2, z1) / (1.0 + z);\n\n\tRprime *= DH3 * gsl_spline_eval(splineEz, z, accEz);\n\n\treturn Rprime;\n}\n\ndouble Redshift_rejection_sampler(long int *seed, double n0, double n1, double n2, double z1)\n{\n\tdouble pars[4] = {n0, n1, n2, z1};\n\t\n\tdouble Rzmax = Redshift_rescaled(z1, (void *) &pars[0]);\n\t\n\tdouble z = 0.0, p, x;\n\tfor (;;)\n\t{\n\t\tz = ran2d(seed) * 10.0;\n\t\t\n\t\tp = Redshift_rescaled(z, (void *) &pars[0]) / Rzmax;\n\n\t\tx = ran2d(seed);\n\n\t\tif (x < p) break;\n\t}\n\n\treturn z;\n}\n\ndouble GRBNumberIntegral(double n0, double n1, double n2, double z1)\n{\n\tdouble pars[4] = {n0, n1, n2, z1};\n\n\tdouble result, error;\n\tunsigned long int neval;\n\tgsl_function F;\n \tF.function = &Redshift_rescaled;\n \tF.params = (void *) &pars[0];\n\n \tgsl_set_error_handler_off();\n \tgsl_integration_qng(&F, ZMIN, ZMAX, 1e-7, 1e-6, &result, &error, &neval);\n\n \tresult *= 4.0 * M_PI;\n\n \treturn result;\n}\n\ndouble GRBRate(double z, double n0, double n1, double n2, double z1)\n{\n\tdouble Rprime = Redshift_distribution_normalized(z, n0, n1, n2, z1) / (1.0 + z);\n\n\tRprime *= DH3 * gsl_spline_eval(splineEz, z, accEz);\n\n\tRprime *= 4.0 * M_PI * runargs.tobs * gsl_spline_eval(splineDF, z, accDF) / 6.0;\n\n\treturn Rprime;\n}\n\ndouble GRBRateFunc(double z, void *params)\n{\n\tdouble *pars = (double *) params;\n\tdouble n0 = pars[0];\n\tdouble n1 = pars[1];\n\tdouble n2 = pars[2];\n\tdouble z1 = pars[3];\n\n\treturn GRBRate(z, n0, n1, n2, z1);\n}\n\ndouble GRBRateIntegral(double n0, double n1, double n2, double z1)\n{\n\tdouble pars[4] = {n0, n1, n2, z1};\n\n\tdouble result, error;\n\tunsigned long int neval;\n\tgsl_function F;\n \tF.function = &GRBRateFunc;\n \tF.params = (void *) &pars[0];\n\n \tgsl_set_error_handler_off();\n \tgsl_integration_qng(&F, ZMIN, ZMAX, 1e-7, 1e-6, &result, &error, &neval);\n\n \treturn result;\n}\n", "meta": {"hexsha": "b7f6782a938020d1feb6ded6f5a0c986de07d6a8", "size": 8990, "ext": "c", "lang": "C", "max_stars_repo_path": "src/poputils.c", "max_stars_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_stars_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-09-04T18:20:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T12:24:14.000Z", "max_issues_repo_path": "src/poputils.c", "max_issues_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_issues_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "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/poputils.c", "max_forks_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_forks_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T20:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:20:56.000Z", "avg_line_length": 24.4959128065, "max_line_length": 135, "alphanum_fraction": 0.675862069, "num_tokens": 3216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.49497014050068283}} {"text": "/* rng/ran0.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\n/* This is an implementation of the algorithm used in Numerical\n Recipe's ran0 generator. It is the same as MINSTD with an XOR mask\n of 123459876 on the seed.\n\n The period of this generator is 2^31. \n\n Note, if you choose a seed of 123459876 it would give a degenerate\n series 0,0,0,0, ... I've made that into an error. */\n\nstatic inline unsigned long int ran0_get (void *vstate);\nstatic double ran0_get_double (void *vstate);\nstatic void ran0_set (void *state, unsigned long int s);\n\nstatic const long int m = 2147483647, a = 16807, q = 127773, r = 2836;\nstatic const unsigned long int mask = 123459876;\n\ntypedef struct\n {\n unsigned long int x;\n }\nran0_state_t;\n\nstatic inline unsigned long int\nran0_get (void *vstate)\n{\n ran0_state_t *state = (ran0_state_t *) vstate;\n\n const unsigned long int x = state->x;\n\n const long int h = x / q;\n const long int t = a * (x - h * q) - h * r;\n\n if (t < 0)\n {\n state->x = t + m;\n }\n else\n {\n state->x = t;\n }\n\n return state->x;\n}\n\nstatic double\nran0_get_double (void *vstate)\n{\n return ran0_get (vstate) / 2147483647.0 ;\n}\n\nstatic void\nran0_set (void *vstate, unsigned long int s)\n{\n ran0_state_t *state = (ran0_state_t *) vstate;\n\n if (s == mask)\n {\n GSL_ERROR_VOID (\"ran0 should not use seed == mask\", \n GSL_EINVAL);\n }\n\n state->x = s ^ mask;\n\n return;\n}\n\nstatic const gsl_rng_type ran0_type =\n{\"ran0\", /* name */\n 2147483646, /* RAND_MAX */\n 1, /* RAND_MIN */\n sizeof (ran0_state_t),\n &ran0_set,\n &ran0_get,\n &ran0_get_double};\n\nconst gsl_rng_type *gsl_rng_ran0 = &ran0_type;\n", "meta": {"hexsha": "108a90598816b43b0de51dadd329f9e391026689", "size": 2594, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/rng/ran0.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/rng/ran0.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/rng/ran0.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.6831683168, "max_line_length": 81, "alphanum_fraction": 0.6580570547, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.49458341627448027}} {"text": "/*\n\n */\n\n#include \"kern.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef WITH_THREADS\n#include \n#define MP_LOOP() PRAGMA(omp for simd)\n#else\n#define MP_LOOP()\n#endif\n\n#define PRAGMA(X) _Pragma(#X)\n\n/*\n * Transform the input vector to the output stream.\n * The m x n matrix is stored with column arrays.\n *\n * y[k * n + j] = x[k * m + i] * w[m * j + i]\n * y(l, n) = x(l,m) * w(m, n)\n *\n */\nvoid trans(uint32_t batch_len, uint32_t m, uint32_t n, const float *w,\n const float *x, float *y) {\n cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, batch_len, n, m,\n 1.0f, x, batch_len, w, m, 0.0f, y, batch_len);\n}\n\n/*\n * Original:\n * w(m,n) -= N * x(l,m)^T * dy(l,n)\n * w[m * $j + i] -= N * x[m * $k + i] * dy[n * k + $j]\n *\n * Optimized:\n * w(m,n)^T -= N * dy(l,n)^T * x(l,m)\n * w[m * j + $i] -= N * dy[n * $k + j] * x[m * k + $i]\n */\nvoid train_sgd(uint32_t batch_len, uint32_t m, uint32_t n,\n const float x[m * batch_len], const float y[n * batch_len],\n float rate, float w[m * n]) {\n cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, m, batch_len, -rate,\n y, n, x, m, 1.0f, w, m);\n}\n\n/*\n * adam optimizer for the weight matrix\n */\nfloat train_adam(uint32_t batch_len, uint32_t m, uint32_t n,\n const float x[restrict m * batch_len],\n const float dy[restrict const n * batch_len], float counter,\n float N, float beta1, float beta2, float epsilon,\n float w[m * n], float mom[n * m], float veloc[n * m]) {\n float *restrict wr;\n float *restrict mr;\n float *restrict vr;\n const float *restrict xr;\n float dr;\n uint32_t k, i;\n for (uint32_t j = 0; j < n; j++) {\n for (k = 0, wr = &w[m * j], vr = &veloc[j * m], mr = &mom[j * m];\n k < batch_len; k++) {\n for (i = 0, xr = &x[k * m], dr = dy[k * n + j]; i < m; i++) {\n const float g = dr * xr[i];\n mr[i] = beta1 * mr[i] + ((1 - beta1) * g);\n const float mr_hat = mr[i] / (1 - powf(beta1, counter));\n vr[i] = beta2 * vr[i] + ((1 - beta2) * (powf(g, 2)));\n const float vr_hat = vr[i] / (1 - powf(beta2, counter));\n wr[i] -= N * mr_hat / (sqrtf(vr_hat + epsilon));\n }\n }\n }\n return counter + 1.0f;\n}\n\n/*\n * Original:\n * dx(l,m) = dy(l,n) * w(m,n)^T\n * dx[m * k + $i] = dy[n * k + $j] * w[m * $j + i]\n */\nvoid loss(uint32_t batch_len, uint32_t m, uint32_t n, const float *w,\n const float *dy, float *dx) {\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, batch_len, m, n, 1.0f,\n dy, n, w, m, .0f, dx, m);\n}\n\n/*\n * Calculate the difference between two vectors of size 'size'.\n *\n * size: The size of the vectors.\n * vec1: The first vector\n * vec2: The second vector\n *\n * Return the mean difference\n */\ndouble vec_delta(uint32_t size, const float *vec1, const float *vec2,\n float *deltas) {\n double error = 0.0;\n for (size_t i = 0; i < size; i++) {\n deltas[i] = vec1[i] - vec2[i];\n error += pow(deltas[i], 2.0);\n }\n return error / (float)size;\n}\n\nbool vec_is_equal_f32(uint32_t n, const float a[n], const float b[n],\n float epsilon) {\n for (uint32_t i = 0; i < n; i++) {\n if (fabsf(a[i] - b[i]) >= epsilon) return false;\n // better:\n // if(fabs(a[ii]-b[ii]) < 1e-10 * (fabs(a[ii]) + fabs(b[ii]))) {\n // with the appropriate tolerance\n }\n return true;\n}\n\n/*\n * In each iteration of the while loop two normal random variables are\n * generated. On the first call of the function, two normal random variables are\n * generated.\n * On the after call, the second generated number will be returned.\n */\nfloat rand_normal(float mu, float sigma) {\n float U1, U2, W, mult;\n static float X1, X2;\n static bool call = false;\n\n if (call == true) {\n call = !call;\n return mu + sigma * X2;\n }\n\n do {\n U1 = -1 + ((float)random() / (float)(RAND_MAX)) * 2;\n U2 = -1 + ((float)random() / (float)(RAND_MAX)) * 2;\n W = powf(U1, 2) + powf(U2, 2);\n } while (W >= 1 || W == 0);\n\n mult = sqrtf((-2 * logf(W)) / W);\n X1 = U1 * mult;\n X2 = U2 * mult;\n\n call = !call;\n return (mu + sigma * X1);\n}\n\nvoid weights_norm_init(uint32_t in_size, uint32_t out_size, float *weights) {\n srandom(time(NULL));\n for (unsigned long long i = 0; i < (in_size * out_size); i++) {\n weights[i] = rand_normal(0.0f, sqrtf(2.0f / in_size));\n }\n}\n\nuint32_t argmax(uint32_t len, const float x[len], float *max) {\n *max = x[0];\n uint32_t max_pos = 0;\n for (uint32_t i = 0; i < len; i++) {\n if (x[i] > *max) {\n *max = x[i];\n max_pos = i;\n }\n }\n return max_pos;\n}\n\nvoid softmax(uint32_t len, const float x[len], float xs[len]) {\n float max;\n argmax(len, x, &max);\n float sum = .0f;\n for (uint32_t i = 0; i < len; i++) {\n xs[i] = expf(x[i] - max);\n sum += xs[i];\n }\n for (uint32_t i = 0; i < len; i++) {\n xs[i] = xs[i] / sum;\n }\n}\n\n// List of activation functions\n// Convention: derived activation functions are prefixed with label 'derived'\n/*\n * The sigmoid function\n */\nfloat fsigmoid(float x) { return 1.0f / (1.0f + expf(-x)); }\n\n/*\n * The derived of the sigmoid function\n */\nfloat derived_fsigmoid(float y) { return (y * (1.0f - y)); }\n\nfloat frelu(float x) { return (float)(x > .0) * x; }\n\nfloat derived_frelu(float x) { return (float)(x > .0); }\n\nfloat ftanh(float x) { return tanhf(x); }\n\nfloat derived_ftanh(float x) { return 1.0f - powf(ftanh(x), 2.0f); }\n\nstatic void vec_func_f32(uint32_t len, float result[len], float (*f)(float)) {\n for (uint32_t d = 0; d < len; d++) {\n result[d] = f(result[d]);\n }\n}\n\nvoid sigmoid(uint32_t len, float *result) {\n vec_func_f32(len, result, fsigmoid);\n}\n\nvoid relu(uint32_t len, float *result) { vec_func_f32(len, result, frelu); }\n\nvoid tanhg(uint32_t len, float *result) { vec_func_f32(len, result, ftanh); }\n\nstatic void vec_derived_f32(uint32_t len, const float result[len],\n float delta[len], float (*f)(float)) {\n for (uint32_t d = 0; d < len; d++) {\n delta[d] = f(result[d]) * delta[d];\n }\n}\n\nvoid relu_derived(uint32_t len, const float *result, float *delta) {\n vec_derived_f32(len, result, delta, derived_frelu);\n}\n\nvoid tanhg_derived(uint32_t len, const float *result, float *delta) {\n vec_derived_f32(len, result, delta, derived_ftanh);\n}\n\nvoid sigmoid_derived(uint32_t len, const float *result, float *delta) {\n vec_derived_f32(len, result, delta, derived_fsigmoid);\n}\n\n/*\n * Allocate memory for a float matrix.\n */\nfloat *matrix_alloc(uint32_t m, uint32_t n) {\n return reallocarray(NULL, m * n, sizeof(float));\n}\n\nvoid matrix_init(uint32_t m, uint32_t n, float matrix[m * n]) {\n for (uint32_t i = 0; i < m * n; i++) {\n matrix[i] = 0.0f;\n }\n}\n\nfloat *weights_create_or_load(const char *filename, uint32_t input_len,\n uint32_t output_len) {\n float *weight;\n if (filename == NULL) {\n weight = matrix_alloc(input_len, output_len);\n weights_norm_init(input_len, output_len, weight);\n } else {\n struct stat statbuf;\n size_t size_expected = input_len * output_len * sizeof(float);\n\n int fd = open(filename, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);\n if (fd < 0) {\n /* failure */\n err(EXIT_FAILURE, \"open file '%s'\", filename);\n }\n /* find size of input file */\n if (fstat(fd, &statbuf) < 0) {\n err(EXIT_FAILURE, \"fstat error\");\n } else if (statbuf.st_size == 0) {\n // file does not exist before - create it with the required size\n if (ftruncate(fd, size_expected)) {\n err(EXIT_FAILURE, \"file truncate\");\n }\n weight = mmap(0, size_expected, PROT_WRITE, MAP_SHARED, fd, 0);\n close(fd);\n weights_norm_init(input_len, output_len, weight);\n return weight;\n } else if (statbuf.st_size > 0 &&\n (unsigned long)statbuf.st_size < size_expected) {\n errx(EXIT_FAILURE, \"invalid data size. Expected: %lu; given: %ld\",\n size_expected, statbuf.st_size);\n }\n weight = mmap(0, size_expected, PROT_WRITE, MAP_SHARED, fd, 0);\n close(fd);\n }\n return weight;\n}\n\nstatic inline float fbernoulli(float p /* must between [0,1] */) {\n return (float)(p < (((float)random() / (float)(RAND_MAX))));\n}\n\nvoid dropout(uint32_t len, const float vec[len], float p, float result[len]) {\n for (uint32_t i = 0; i < len; i++) {\n result[i] = vec[i] * fbernoulli(p);\n }\n}\n", "meta": {"hexsha": "78e08ebffbfab164893f12055a5b61833ab3e916", "size": 9022, "ext": "c", "lang": "C", "max_stars_repo_path": "kern.c", "max_stars_repo_name": "geisten/gstnn", "max_stars_repo_head_hexsha": "520f674d2eb780e45dd1cd7beddf0407625afa0c", "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": "kern.c", "max_issues_repo_name": "geisten/gstnn", "max_issues_repo_head_hexsha": "520f674d2eb780e45dd1cd7beddf0407625afa0c", "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": "kern.c", "max_forks_repo_name": "geisten/gstnn", "max_forks_repo_head_hexsha": "520f674d2eb780e45dd1cd7beddf0407625afa0c", "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.6776315789, "max_line_length": 81, "alphanum_fraction": 0.5558634449, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4945673923062102}} {"text": "/** \\file oposim_fns.c \n \\brief Funciones auxiliares\n*/\n\n#include \n#include \n#include \n#include \n\n#include \"oposim.h\"\n\nstatic gsl_rng *r = NULL; /**< \\a r es el generador de números aleatorios */\n\n/** \\fn void random_init(char opc)\n\\brief Inicializador del generador de números aleatorios.\n\\param opc a character.\n */\nvoid random_init(char opc)\n{\n\n if (!r) {\n switch(opc) {\n case 'm':\n r = gsl_rng_alloc(gsl_rng_mt19937);\n break;\n case 't':\n r = gsl_rng_alloc(gsl_rng_taus);\n break;\n case 'g':\n r = gsl_rng_alloc(gsl_rng_gfsr4);\n break;\n case 'x':\n r = gsl_rng_alloc(gsl_rng_ranlxs0);\n break;\n default:\n r = gsl_rng_alloc(gsl_rng_mrg);\n }\n printf(\"Usando RNG %s\\n\", gsl_rng_name(r));\n gsl_rng_set(r, time(NULL));\n }\n\n}\n\n/** \\fn void random_free()\n\\brief Destructor del generador de números aleatorios\n*/\nvoid random_free()\n{\n\n if (!r) {\n gsl_rng_free(r);\n }\n\n}\n\n/** \\fn int s_experimento(int temas, int bolas, int estudiados)\n\\brief Realiza una simulación.\n\\param temas Número de temas en la oposición.\n\\param bolas Número de bolas que se extraen.\n\\param estudiados Número de temas estudiados.\n\\return Número temas estudiados que estarían entre los extraídos.\n*/\nint s_experimento(int temas, int bolas, int estudiados)\n{\n\n //printf(\"bolas extraidas: \");\n int b_extraidas[bolas];\n int bola;\n\n for (int i = 0; i < bolas; i++) {\n do {\n bola = (int) gsl_rng_uniform_int(r, temas) + 1;\n for (int j = 0; j < i; j++) {\n\tif (b_extraidas[j] == bola) {\n\t bola = 0;\n\t break;\n\t}\n }\n } while (!bola);\n //printf(\"%d \", bola);\n b_extraidas[i] = bola;\n }\n\n int res = 0;\n for (int i = 0; i < bolas; i++) {\n if(b_extraidas[i] <= estudiados) res++;\n }\n\n //printf(\"\\n\");\n return res;\n\n}\n\n/** \\fn int *experimento(int temas, int bolas, int estudiados, int reps)\n\\brief Realiza varias simulaciones y devuelve los resultados.\n\\param temas Número de temas en la oposición.\n\\param bolas Número de bolas que se extraen.\n\\param estudiados Número de temas estudiados.\n\\param reps Número de veces que se realizará el experimento.\n\\return Histograma con las veces que el número de temas estudiados estaba entre las bolas extraídas.\n */\nint *experimento(int temas, int bolas, int estudiados, int reps)\n{\n\n int *res = (int *)calloc(bolas + 1, sizeof(int));\n\n for (int i = 0; i < reps; i++)\n res[s_experimento(temas, bolas, estudiados)]++;\n\n return res;\n\n}\n\n/** \\fn double *frecs(int *histograma, int l)\n\\brief Calcula las frecuencias relativas.\n\\param histograma array de frecuencias absolutas\n\\param l longitud del histograma\n\\return array con las frecuencias relativas\n */\ndouble *frecs(int *histograma, int l)\n{\n\n double suma = 0;\n for (int i = 0; i < l; i++)\n suma += histograma[i];\n\n double *res = (double *)calloc(l, sizeof(double));\n\n for (int i = 0; i < l; i++)\n res[i] = histograma[i] / suma;\n\n return res;\n\n}\n", "meta": {"hexsha": "c5b402a378b43be0367aaa228986153d037d2911", "size": 2970, "ext": "c", "lang": "C", "max_stars_repo_path": "oposim_fns.c", "max_stars_repo_name": "jonatanlv/oposim", "max_stars_repo_head_hexsha": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "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": "oposim_fns.c", "max_issues_repo_name": "jonatanlv/oposim", "max_issues_repo_head_hexsha": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "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": "oposim_fns.c", "max_forks_repo_name": "jonatanlv/oposim", "max_forks_repo_head_hexsha": "4d816ed5e5fddc47171fe39ea7ef2481f9358648", "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.0, "max_line_length": 100, "alphanum_fraction": 0.6478114478, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.49402351825692375}} {"text": "/* linalg/rqr.c\n * \n * Copyright (C) 2019 Patrick Alken, Julien Langou\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * this module contains routines for the QR factorization of a matrix\n * using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with\n * additional modifications courtesy of Julien Langou.\n */\n\nstatic int unpack_Q1(gsl_matrix * Q);\nstatic int unpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q);\nstatic int aux_ULT(const gsl_matrix * L, gsl_matrix * U);\nstatic int aux_mLU(gsl_matrix * A);\nstatic int aux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A);\n\n/*\ngsl_linalg_QR_decomp_r()\n QR decomposition using Level 3 BLAS recursive algorithm of:\n \nElmroth, E. and Gustavson, F.G., 2000. Applying recursion to serial and parallel\n QR factorization leads to better performance. IBM Journal of Research and Development,\n 44(4), pp.605-624.\n\nInputs: A - matrix to be factored, M-by-N with M >= N\n T - N-by-N upper triangular factor of block reflector\n\nReturn: success/error\n\nNotes:\n1) on output, upper triangle of A contains R; elements below the diagonal\nare columns of V. The matrix Q is\n\nQ = I - V T V^T\n\nwhere T is upper triangular. Note that diag(T) = tau\n\n2) implementation provided by Julien Langou\n*/\n\nint\ngsl_linalg_QR_decomp_r (gsl_matrix * A, gsl_matrix * T)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"M must be >= N\", GSL_EBADLEN);\n }\n else if (T->size1 != T->size2)\n {\n GSL_ERROR (\"T matrix must be square\", GSL_ENOTSQR);\n }\n else if (T->size1 != N)\n {\n GSL_ERROR (\"T matrix does not match dimensions of A\", GSL_EBADLEN);\n }\n else if (N == 1)\n {\n /* base case, compute householder transform for single column matrix */\n\n double * T00 = gsl_matrix_ptr(T, 0, 0);\n gsl_vector_view v = gsl_matrix_column(A, 0);\n\n *T00 = gsl_linalg_householder_transform(&v.vector);\n return GSL_SUCCESS;\n }\n else\n {\n /*\n * partition matrices:\n *\n * N1 N2 N1 N2\n * N1 [ A11 A12 ] and N1 [ T11 T12 ]\n * M2 [ A21 A22 ] N2 [ 0 T22 ]\n */\n int status;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n const size_t M2 = M - N1;\n\n gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);\n gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);\n gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, M2, N1);\n gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, M2, N2);\n\n gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);\n\n gsl_matrix_view m;\n\n /*\n * Eq. 2: recursively factor\n *\n * [ A11 ] = Q1 [ R11 ]\n * [ A21 ] [ 0 ]\n * N1\n * Note: Q1 = I - V1 T11 V1^T, where V1 = [ V11 ] N1\n * [ V21 ] M2\n */\n m = gsl_matrix_submatrix(A, 0, 0, M, N1);\n status = gsl_linalg_QR_decomp_r(&m.matrix, &T11.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 3:\n *\n * [ R12 ] := Q1^T [ A12 ] = [ A12 ] - [ V11 W ]\n * [ A22 ] [ A22 ] [ A22 ] [ V21 W ]\n *\n * where W = T11^T (V11^T A12 + V21^T A22), and using T12 as temporary storage\n */\n gsl_matrix_memcpy(&T12.matrix, &A12.matrix); /* W := A12 */\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* W := V11^T * A12 */\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A21.matrix, &A22.matrix, 1.0, &T12.matrix); /* W := W + V21^T * A22 */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T * W */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &T12.matrix, 1.0, &A22.matrix); /* A22 = A22 - V21 * W */\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &A11.matrix, &T12.matrix); /* tmp = V11 * W */\n gsl_matrix_sub(&A12.matrix, &T12.matrix); /* R12 := A12 - V11 * W */\n\n /*\n * Eq. 4: recursively factor\n *\n * A22 = Q2~ R22\n *\n * N1 M2\n * Note: Q2 = [ I 0 ] N1\n * [ 0 Q2~ ] M2\n */\n status = gsl_linalg_QR_decomp_r(&A22.matrix, &T22.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 13: update T12 := -T11 * V1^T * V2 * T22\n *\n * where:\n *\n * N1 N2\n * V1 = [ V11 ] N1 V2 = [ 0 ] N1\n * [ V21 ] N2 [ V22 ] N2\n * [ V31 ] M-N [ V32 ] M-N\n *\n * Note: V1^T V2 = V21^T V22 + V31^T V32\n * Also, V11, V22 are unit lower triangular\n */\n\n m = gsl_matrix_submatrix(&A21.matrix, 0, 0, N2, N1); /* V21 */\n gsl_matrix_transpose_memcpy(&T12.matrix, &m.matrix); /* T12 := V21^T */\n\n m = gsl_matrix_submatrix(A, N1, N1, N2, N2); /* V22 */\n gsl_blas_dtrmm(CblasRight, CblasLower, CblasNoTrans, CblasUnit, 1.0, &m.matrix, &T12.matrix); /* T12 := V21^T * V22 */\n\n if (M > N)\n {\n gsl_matrix_view V31 = gsl_matrix_submatrix(A, N, 0, M - N, N1);\n gsl_matrix_view V32 = gsl_matrix_submatrix(A, N, N1, M - N, N2);\n\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V31.matrix, &V32.matrix, 1.0, &T12.matrix); /* T12 := T12 + V31^T * V32 */\n }\n\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */\n\n return GSL_SUCCESS;\n }\n}\n\n/* Solves the square system A x = b for x using the QR factorisation,\n *\n * R x = Q^T b\n *\n * where Q = I - V T V^T\n */\n\nint\ngsl_linalg_QR_solve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x)\n{\n const size_t N = QR->size2;\n\n if (QR->size1 != N)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (T->size1 != QR->size1 || T->size2 != QR->size2)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (N != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (N != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q^T b = [I - V T^T V^T] b */\n\n /* x := V^T b */\n gsl_vector_memcpy(x, b);\n gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, QR, x);\n\n /* x = T^T * x */\n gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, x);\n\n /* x = V * x */\n gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, QR, x);\n\n /* x = b - V * x */\n for (i = 0; i < N; ++i)\n {\n double * xi = gsl_vector_ptr(x, i);\n double bi = gsl_vector_get(b, i);\n *xi = bi - (*xi);\n }\n\n /* Solve R x = Q^T b, storing x in-place */\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n return GSL_SUCCESS;\n }\n}\n\n/* Find the least squares solution to the overdetermined system \n *\n * A x = b \n * \n * for M >= N using the QR factorization A = Q R. \n *\n * Inputs: QR - [R; V] matrix, M-by-N\n * T - upper triangular block reflector, N-by-N\n * b - right hand side, size M\n * x - (output) solution, size M\n * x(1:N) = least squares solution vector\n * x(N+1:M) = vector whose norm equals ||b - Ax||\n * work - workspace, size N\n */\n\nint\ngsl_linalg_QR_lssolve_r (const gsl_matrix * QR, const gsl_matrix * T, const gsl_vector * b, gsl_vector * x, gsl_vector * work)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"QR matrix must have M >= N\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (M != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (M != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else if (N != work->size)\n {\n GSL_ERROR (\"matrix size must match work size\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view R = gsl_matrix_const_submatrix (QR, 0, 0, N, N);\n gsl_vector_view x1 = gsl_vector_subvector(x, 0, N);\n\n /* compute x = Q^T b */\n gsl_vector_memcpy(x, b);\n gsl_linalg_QR_QTvec_r (QR, T, x, work);\n\n /* Solve R x = Q^T b */\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, &x1.vector);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_QR_unpack_r()\n Unpack matrices Q and R\n\nInputs: QR - packed QR format, M-by-N\n T - block reflector matrix, N-by-N\n Q - (output) Q matrix, M-by-M\n R - (output) R matrix, N-by-N\n\nReturn: success/error\n\nNotes:\n1) Implementation provided by Julien Langou\n*/\n\nint\ngsl_linalg_QR_unpack_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q, gsl_matrix * R)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"M must be >= N\", GSL_EBADLEN);\n }\n else if (Q->size1 != M || Q->size2 != M)\n {\n GSL_ERROR (\"Q matrix must be M-by-M\", GSL_EBADLEN);\n }\n else if (R->size1 != N || R->size2 != N)\n {\n GSL_ERROR (\"R matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view RV = gsl_matrix_const_submatrix(QR, 0, 0, N, N);\n gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, M, N);\n gsl_matrix_view m;\n\n /*\n * set Q1 = [ T ]\n * [ V ]\n */\n m = gsl_matrix_submatrix(Q, 0, 0, N, N);\n gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &m.matrix, T);\n gsl_matrix_tricpy(CblasLower, CblasUnit, &m.matrix, &RV.matrix);\n\n if (M > N)\n {\n gsl_matrix_const_view tmp = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n m = gsl_matrix_submatrix(Q, N, 0, M - N, N);\n gsl_matrix_memcpy(&m.matrix, &tmp.matrix);\n }\n\n unpack_Q1(&Q1.matrix);\n\n if (M > N)\n {\n gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, 0, N, M, M - N);\n unpack_Q2(QR, T, &Q2.matrix);\n }\n\n /* copy R */\n gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, &RV.matrix);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_QR_QTvec_r()\n Apply M-by-M Q^T to the M-by-1 vector b\n\nInputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r\n T - block reflector matrix\n b - M-by-1 vector replaced by Q^T b on output\n work - workspace, length N\n\nNotes:\n1) Q^T b = (I - V T^T V^T) b\n = b - V T^T [ V1^T V2^T ] [ b1 ]\n [ b2 ]\n = b - V T^T [ V1^T b1 + V2^T b2 ]\n = [ b1 ] - [ V1 w ]\n [ b2 ] [ V2 w ]\n\nwhere w = T^T ( V1^T b1 + V2^T b2 )\n*/\n\nint\ngsl_linalg_QR_QTvec_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_vector * b, gsl_vector * work)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"M must be >= N\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (b->size != M)\n {\n GSL_ERROR (\"b vector must have length M\", GSL_EBADLEN);\n }\n else if (work->size != N)\n {\n GSL_ERROR (\"workspace must be length N\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);\n gsl_vector_view b1 = gsl_vector_subvector(b, 0, N);\n gsl_vector_view b2;\n\n /* work := V1^T b1 */\n gsl_vector_memcpy(work, &b1.vector);\n gsl_blas_dtrmv(CblasLower, CblasTrans, CblasUnit, &V1.matrix, work);\n\n if (M > N)\n {\n gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n\n /* work = work + V2^T b2 */\n b2 = gsl_vector_subvector(b, N, M - N);\n gsl_blas_dgemv(CblasTrans, 1.0, &V2.matrix, &b2.vector, 1.0, work);\n }\n\n /* work = T^T * work */\n gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, T, work);\n\n if (M > N)\n {\n /* b2 = b2 - V2 * work */\n gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n gsl_blas_dgemv(CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &b2.vector);\n }\n\n /* b1 = b1 - V1 * work */\n gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasUnit, &V1.matrix, work);\n gsl_vector_sub(&b1.vector, work);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_QR_QTmat_r()\n Apply M-by-M Q^T to the M-by-K matrix B\n\nInputs: QR - [R; V] matrix encoded by gsl_linalg_QR_decomp_r\n T - block reflector matrix\n B - M-by-K matrix replaced by Q^T B on output\n work - N-by-K workspace\n\nNotes:\n1) Provided by Julien Langou\n*/\n\nint\ngsl_linalg_QR_QTmat_r(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * B, gsl_matrix * work)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n const size_t K = B->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"M must be >= N\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (B->size1 != M)\n {\n GSL_ERROR (\"B matrix must have M rows\", GSL_EBADLEN);\n }\n else if (work->size1 != N || work->size2 != K)\n {\n GSL_ERROR (\"workspace must be N-by-K\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);\n gsl_matrix_view B1 = gsl_matrix_submatrix(B, 0, 0, N, K);\n gsl_matrix_view B2;\n\n /* work := V1^T B1 */\n gsl_matrix_memcpy(work, &B1.matrix);\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasTrans, CblasUnit, 1.0, &V1.matrix, work);\n\n if (M > N)\n {\n gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n\n /* work = work + V2^T B2 */\n B2 = gsl_matrix_submatrix(B, N, 0, M - N, K);\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &V2.matrix, &B2.matrix, 1.0, work);\n }\n\n /* work = T^T * work */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, T, work);\n\n if (M > N)\n {\n /* B2 = B2 - V2 * work */\n gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &V2.matrix, work, 1.0, &B2.matrix);\n }\n\n /* B1 = B1 - V1 * work */\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, work);\n gsl_matrix_sub(&B1.matrix, work);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\nunpack_Q1()\n Compute Q_1\n\nInputs: Q - on input, contains T in upper triangle and V in lower trapezoid\n on output, contains Q_1\n M-by-N\n\nReturn: success/error\n\nNotes:\n1) N\nQ1 = [ Q1 Q2 ] [ I_n ] = (I - V T V^T) [ I; 0 ] = [ I - V1 T V1^T ] N\n [ 0 ] [ - V2 T V1^T ] M - N\n*/\n\nstatic int\nunpack_Q1(gsl_matrix * Q)\n{\n int status;\n const size_t M = Q->size1;\n const size_t N = Q->size2;\n gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, N);\n gsl_vector_view diag = gsl_matrix_diagonal(&Q1.matrix);\n\n /* Q1 := T V1^T */\n status = aux_ULT(&Q1.matrix, &Q1.matrix);\n if (status)\n return status;\n\n if (M > N)\n {\n /* compute Q2 := - V2 T V1^T */\n gsl_matrix_view V2 = gsl_matrix_submatrix(Q, N, 0, M - N, N);\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Q1.matrix, &V2.matrix);\n }\n\n /* Q1 := - V1 T V1^T */\n status = aux_mLU(&Q1.matrix);\n if (status)\n return status;\n\n /* Q1 := I - V1 T V1^T */\n gsl_vector_add_constant(&diag.vector, 1.0);\n\n return GSL_SUCCESS;\n}\n\n/*\nunpack_Q2()\n Compute Q_2\n\nInputs: QR - [R; V] from QR_decomp_r, M-by-N\n T - upper triangular T factor, N-by-N\n Q - (output) Q_2 factor, M-by-(M-N)\n\nReturn: success/error\n\nNotes: N M-N\n1) Since Q = I - V T V^T = M [ Q1 Q2 ], we have\n\n M-N\nQ2 = Q [ 0 ] N\n [ I_{M-N} ] M-N\n\nSo, Q2 = Q [ 0; I ] = (I - V T V^T) [ 0; I ] = [ - V1 T V2^T ]\n [ I - V2 T V2^T ]\n*/\n\nstatic int\nunpack_Q2(const gsl_matrix * QR, const gsl_matrix * T, gsl_matrix * Q)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M <= N)\n {\n GSL_ERROR (\"M must be > N\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (Q->size1 != M || Q->size2 != (M - N))\n {\n GSL_ERROR (\"Q matrix must be M-by-(M-N)\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view V1 = gsl_matrix_const_submatrix(QR, 0, 0, N, N);\n gsl_matrix_const_view V2 = gsl_matrix_const_submatrix(QR, N, 0, M - N, N);\n gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, N, M - N);\n gsl_matrix_view Q2 = gsl_matrix_submatrix(Q, N, 0, M - N, M - N);\n gsl_vector_view diag = gsl_matrix_diagonal(&Q2.matrix);\n\n /* Q1 := V2^T */\n gsl_matrix_transpose_memcpy(&Q1.matrix, &V2.matrix);\n\n /* Q1 := - T V2^T */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, T, &Q1.matrix);\n\n /* Q2 := - V2 T V2^T */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, &V2.matrix, &Q1.matrix, 0.0, &Q2.matrix);\n\n /* Q2 := I - V2 T V2^T */\n gsl_vector_add_constant(&diag.vector, 1.0);\n\n /* Q1 := - V1 T V2^T */\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, 1.0, &V1.matrix, &Q1.matrix);\n\n return GSL_SUCCESS;\n }\n}\n\n/* U := U L^T for triangular matrices L and U; L is unit lower triangular */\nstatic int\naux_ULT(const gsl_matrix * L, gsl_matrix * U)\n{\n const size_t N = L->size1;\n\n if (N != L->size2)\n {\n GSL_ERROR (\"L matrix must be square\", GSL_ENOTSQR);\n }\n else if (U->size1 != N || U->size2 != N)\n {\n GSL_ERROR (\"U matrix must be same size as L\", GSL_EBADLEN);\n }\n else if (N == 1)\n {\n /* nothing to do */\n return GSL_SUCCESS;\n }\n else\n {\n int status;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_const_view L11 = gsl_matrix_const_submatrix(L, 0, 0, N1, N1);\n gsl_matrix_const_view L21 = gsl_matrix_const_submatrix(L, N1, 0, N2, N1);\n gsl_matrix_const_view L22 = gsl_matrix_const_submatrix(L, N1, N1, N2, N2);\n\n gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1);\n gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2);\n gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2);\n\n /* U12 = U12 * L22^T */\n gsl_blas_dtrmm(CblasRight, CblasLower, CblasTrans, CblasUnit, 1.0, &L22.matrix, &U12.matrix);\n\n /* U12 = U12 + U11 * L21^T */\n status = aux_ApUBT(&U11.matrix, &L21.matrix, &U12.matrix);\n if (status)\n return status;\n\n status = aux_ULT(&L11.matrix, &U11.matrix);\n if (status)\n return status;\n\n status = aux_ULT(&L22.matrix, &U22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\n/* store -L*U in A */\nstatic int\naux_mLU(gsl_matrix * A)\n{\n const size_t N = A->size1;\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square\", GSL_ENOTSQR);\n }\n else if (N == 1)\n {\n double *A00 = gsl_matrix_ptr(A, 0, 0);\n *A00 = -(*A00);\n return GSL_SUCCESS;\n }\n else\n {\n int status;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, N1, N1);\n gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, N1, N2);\n gsl_matrix_view A21 = gsl_matrix_submatrix(A, N1, 0, N2, N1);\n gsl_matrix_view A22 = gsl_matrix_submatrix(A, N1, N1, N2, N2);\n\n /* A22 = - L22 U22 */\n status = aux_mLU(&A22.matrix);\n if (status)\n return status;\n\n /* A22 = A22 - L21 U12 */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A21.matrix, &A12.matrix, 1.0, &A22.matrix);\n\n /* A12 - -L11 U12 */\n gsl_blas_dtrmm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, -1.0, &A11.matrix, &A12.matrix);\n\n /* A21 = -L21 U11 */\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &A11.matrix, &A21.matrix);\n\n /* A11 = - L11 U11 */\n status = aux_mLU(&A11.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\n/* A := A + U B^T where U is upper triangular */\nstatic int\naux_ApUBT(const gsl_matrix * U, const gsl_matrix * B, gsl_matrix * A)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (U->size1 != M || U->size2 != M)\n {\n GSL_ERROR (\"U matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (B->size1 != N || B->size2 != M)\n {\n GSL_ERROR (\"B matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (M == 1 && N == 1)\n {\n double *aptr = gsl_matrix_ptr(A, 0, 0);\n const double *uptr = gsl_matrix_const_ptr(U, 0, 0);\n const double *bptr = gsl_matrix_const_ptr(B, 0, 0);\n *aptr += (*uptr) * (*bptr);\n return GSL_SUCCESS;\n }\n else if (M == 1)\n {\n double U00 = gsl_matrix_get(U, 0, 0);\n gsl_vector_view v = gsl_matrix_row(A, 0);\n gsl_vector_const_view w = gsl_matrix_const_column(B, 0);\n gsl_blas_daxpy(U00, &w.vector, &v.vector);\n return GSL_SUCCESS;\n }\n else if (N == 1)\n {\n /*\n * partition:\n *\n * M1 M2\n * B = 1 [ B11 B12 ]\n *\n * 1 M1 M2 1\n * M1 [ A11 ] + [ U11 U12 ] [ B11^T ] M1\n * M2 [ A21 ] [ 0 U22 ] [ B12^T ] M2\n */\n int status;\n const size_t M1 = M / 2;\n const size_t M2 = M - M1;\n\n gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, 1);\n gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, 1);\n gsl_vector_view a1 = gsl_matrix_subcolumn(A, 0, 0, M1);\n\n gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1);\n gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2);\n gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2);\n\n gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, 1, M1);\n gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, 1, M2);\n gsl_vector_const_view b2 = gsl_matrix_const_subrow(B, 0, M1, M2);\n\n /* A(1:M1,1) += U12 * B12^T */\n gsl_blas_dgemv(CblasNoTrans, 1.0, &U12.matrix, &b2.vector, 1.0, &a1.vector);\n\n /* A11 := A11 + U11 B11^T */\n status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix);\n if (status)\n return status;\n\n /* A21 := A21 + U22 B12^T */\n status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n else\n {\n int status;\n const size_t M1 = M / 2;\n const size_t M2 = M - M1;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_view A11 = gsl_matrix_submatrix(A, 0, 0, M1, N1);\n gsl_matrix_view A12 = gsl_matrix_submatrix(A, 0, N1, M1, N2);\n gsl_matrix_view A21 = gsl_matrix_submatrix(A, M1, 0, M2, N1);\n gsl_matrix_view A22 = gsl_matrix_submatrix(A, M1, N1, M2, N2);\n\n gsl_matrix_const_view U11 = gsl_matrix_const_submatrix(U, 0, 0, M1, M1);\n gsl_matrix_const_view U12 = gsl_matrix_const_submatrix(U, 0, M1, M1, M2);\n gsl_matrix_const_view U22 = gsl_matrix_const_submatrix(U, M1, M1, M2, M2);\n\n gsl_matrix_const_view B11 = gsl_matrix_const_submatrix(B, 0, 0, N1, M1);\n gsl_matrix_const_view B12 = gsl_matrix_const_submatrix(B, 0, M1, N1, M2);\n gsl_matrix_const_view B21 = gsl_matrix_const_submatrix(B, N1, 0, N2, M1);\n gsl_matrix_const_view B22 = gsl_matrix_const_submatrix(B, N1, M1, N2, M2);\n\n /* A11 := A11 + U11 B11^T */\n status = aux_ApUBT(&U11.matrix, &B11.matrix, &A11.matrix);\n if (status)\n return status;\n\n /* A11 := A11 + U12 B12^T */\n gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B12.matrix, 1.0, &A11.matrix);\n\n /* A12 := A12 + U11 B21^T */\n status = aux_ApUBT(&U11.matrix, &B21.matrix, &A12.matrix);\n if (status)\n return status;\n\n /* A12 := A12 + U12 B22^T */\n gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, &U12.matrix, &B22.matrix, 1.0, &A12.matrix);\n\n /* A21 := A21 + U22 B12^T */\n status = aux_ApUBT(&U22.matrix, &B12.matrix, &A21.matrix);\n if (status)\n return status;\n\n /* A22 := A22 + U22 B22^T */\n status = aux_ApUBT(&U22.matrix, &B22.matrix, &A22.matrix);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "643f6f10c1d6fc698bd869825e4c0f3d4f65d8ae", "size": 26389, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/rqr.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/rqr.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/rqr.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 30.0216154721, "max_line_length": 135, "alphanum_fraction": 0.5673197165, "num_tokens": 8772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4939023605383288}} {"text": "/* ode-initval2/cscal.c\n * \n * Copyright (C) 2002, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"control_utils.c\"\n\ntypedef struct\n{\n double eps_abs;\n double eps_rel;\n double a_y;\n double a_dydt;\n double *scale_abs;\n}\nsc_control_state_t;\n\nstatic void *\nsc_control_alloc (void)\n{\n sc_control_state_t *s =\n (sc_control_state_t *) malloc (sizeof (sc_control_state_t));\n\n if (s == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for sc_control_state\",\n GSL_ENOMEM);\n }\n\n return s;\n}\n\nstatic int\nsc_control_init (void *vstate,\n double eps_abs, double eps_rel, double a_y, double a_dydt)\n{\n sc_control_state_t *s = (sc_control_state_t *) vstate;\n\n if (eps_abs < 0)\n {\n GSL_ERROR (\"eps_abs is negative\", GSL_EINVAL);\n }\n else if (eps_rel < 0)\n {\n GSL_ERROR (\"eps_rel is negative\", GSL_EINVAL);\n }\n else if (a_y < 0)\n {\n GSL_ERROR (\"a_y is negative\", GSL_EINVAL);\n }\n else if (a_dydt < 0)\n {\n GSL_ERROR (\"a_dydt is negative\", GSL_EINVAL);\n }\n\n s->eps_rel = eps_rel;\n s->eps_abs = eps_abs;\n s->a_y = a_y;\n s->a_dydt = a_dydt;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nsc_control_hadjust (void *vstate, size_t dim, unsigned int ord,\n const double y[], const double yerr[], const double yp[],\n double *h)\n{\n sc_control_state_t *state = (sc_control_state_t *) vstate;\n\n const double eps_abs = state->eps_abs;\n const double eps_rel = state->eps_rel;\n const double a_y = state->a_y;\n const double a_dydt = state->a_dydt;\n const double *scale_abs = state->scale_abs;\n\n const double S = 0.9;\n const double h_old = *h;\n\n double rmax = DBL_MIN;\n size_t i;\n\n for (i = 0; i < dim; i++)\n {\n const double D0 =\n eps_rel * (a_y * fabs (y[i]) + a_dydt * fabs (h_old * yp[i]))\n + eps_abs * scale_abs[i];\n const double r = fabs (yerr[i]) / fabs (D0);\n rmax = GSL_MAX_DBL (r, rmax);\n }\n\n if (rmax > 1.1)\n {\n /* decrease step, no more than factor of 5, but a fraction S more\n than scaling suggests (for better accuracy) */\n double r = S / pow (rmax, 1.0 / ord);\n\n if (r < 0.2)\n r = 0.2;\n\n *h = r * h_old;\n\n return GSL_ODEIV_HADJ_DEC;\n }\n else if (rmax < 0.5)\n {\n /* increase step, no more than factor of maxscale */\n double r = S / pow (rmax, 1.0 / (ord + 1.0));\n const double maxscale = 4.9;\n\n if (r > maxscale)\n r = maxscale;\n\n if (r < 1.0) /* don't allow any decrease caused by S<1 */\n r = 1.0;\n\n *h = r * h_old;\n\n return GSL_ODEIV_HADJ_INC;\n }\n else\n {\n /* no change */\n return GSL_ODEIV_HADJ_NIL;\n }\n}\n\nstatic int\nsc_control_errlevel (void *vstate, const double y, const double dydt,\n const double h, const size_t ind, double *errlev)\n{\n sc_control_state_t *state = (sc_control_state_t *) vstate;\n\n const double eps_abs = state->eps_abs;\n const double eps_rel = state->eps_rel;\n const double a_y = state->a_y;\n const double a_dydt = state->a_dydt;\n const double *scale_abs = state->scale_abs;\n\n *errlev = eps_rel * (a_y * fabs (y) + a_dydt * fabs (h * dydt))\n + eps_abs * scale_abs[ind];\n\n if (*errlev <= 0.0)\n {\n GSL_ERROR (\"errlev <= zero\", GSL_ESANITY);\n }\n\n return GSL_SUCCESS;\n}\n\n\nstatic void\nsc_control_free (void *vstate)\n{\n sc_control_state_t *state = (sc_control_state_t *) vstate;\n free (state->scale_abs);\n free (state);\n}\n\nstatic const gsl_odeiv2_control_type sc_control_type = { \"scaled\", /* name */\n &sc_control_alloc,\n &sc_control_init,\n &sc_control_hadjust,\n &sc_control_errlevel,\n &control_set_driver_null,\n &sc_control_free\n};\n\nconst gsl_odeiv2_control_type *gsl_odeiv2_control_scaled = &sc_control_type;\n\n\ngsl_odeiv2_control *\ngsl_odeiv2_control_scaled_new (double eps_abs, double eps_rel,\n double a_y, double a_dydt,\n const double scale_abs[], size_t dim)\n{\n gsl_odeiv2_control *c =\n gsl_odeiv2_control_alloc (gsl_odeiv2_control_scaled);\n\n int status = gsl_odeiv2_control_init (c, eps_abs, eps_rel, a_y, a_dydt);\n\n if (status != GSL_SUCCESS)\n {\n gsl_odeiv2_control_free (c);\n GSL_ERROR_NULL (\"error trying to initialize control\", status);\n }\n\n {\n sc_control_state_t *s = (sc_control_state_t *) c->state;\n\n s->scale_abs = (double *) malloc (dim * sizeof (double));\n\n if (s->scale_abs == 0)\n {\n free (s);\n GSL_ERROR_NULL (\"failed to allocate space for scale_abs\", GSL_ENOMEM);\n }\n\n memcpy (s->scale_abs, scale_abs, dim * sizeof (double));\n }\n\n return c;\n}\n", "meta": {"hexsha": "cfec4180b69aaad5289ac2925e615a1d8b11d01c", "size": 5521, "ext": "c", "lang": "C", "max_stars_repo_path": "thirdparty/gsl-2.7/ode-initval2/cscal.c", "max_stars_repo_name": "igormcoelho/optstats", "max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "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": "thirdparty/gsl-2.7/ode-initval2/cscal.c", "max_issues_repo_name": "igormcoelho/optstats", "max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "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": "thirdparty/gsl-2.7/ode-initval2/cscal.c", "max_forks_repo_name": "igormcoelho/optstats", "max_forks_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4", "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.5377777778, "max_line_length": 82, "alphanum_fraction": 0.633580873, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4938864780030234}} {"text": "#include \n#include \n#include \n#include \n\nint main(void)\n{\n size_t i, j;\n\n gsl_matrix *m = gsl_matrix_alloc(10,10);\n\n for (i=0; i<10; i++)\n for (j=0; j<10; j++)\n gsl_matrix_set(m, i, j, sin(i) + cos(j));\n\n for (j=0; j<10; j++)\n {\n gsl_vector_view column = gsl_matrix_column(m, j);\n double d;\n\n d = gsl_blas_dnrm2(&column.vector);\n\n printf(\"matrix column %zu, norm = %g\\n\", j, d);\n }\n\n gsl_matrix_free(m);\n\n return 0;\n}\n", "meta": {"hexsha": "7b1663692a4f2efc2c34c7462af863f663253cca", "size": 497, "ext": "c", "lang": "C", "max_stars_repo_path": "playground/norm.c", "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": "playground/norm.c", "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": "playground/norm.c", "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "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": 16.5666666667, "max_line_length": 53, "alphanum_fraction": 0.5875251509, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4938836496551273}} {"text": "#include \"cones.h\"\n#ifdef LAPACK_LIB_FOUND\n#include \n#include \n#endif\nvoid projectsdc(double * X, int n, Work * w); \n\n/* in place projection (with branches) */\nvoid projCone(double *x, Cone * k, Work * w, int iter)\n{\n int i;\n int count;\n\n /* project onto positive orthant */\n for(i = k->f; i < k->f+k->l; ++i)\n {\n if(x[i] < 0.0) x[i] = 0.0;\n //x[i] = (x[i] < 0.0) ? 0.0 : x[i];\n }\n count = k->l+k->f;\n /* project onto SOC */\n for(i = 0; i < k->qsize; ++i)\n {\n double v1 = x[count];\n double s = calcNorm(&(x[count+1]),k->q[i]-1);\n double alpha = (s + v1)/2.0;\n\n if(s <= v1) { /* do nothing */ }\n else if (s <= - v1) {\n memset(&(x[count]), 0, k->q[i]*sizeof(double));\n } else { \n x[count] = alpha;\n scaleArray(&(x[count+1]), alpha/s, k->q[i]-1);\n //cblas_dscal(k->q[i]-1, alpha/s, &(x[count+1]),1);\n } \n count += k->q[i];\n }\n#ifdef LAPACK_LIB_FOUND\n /* project onto PSD cone */\n for (i=0; i < k->ssize; ++i){\n projectsdc(&(x[count]),k->s[i],w);\n count += (k->s[i])*(k->s[i]);\n }\n#else\n if(k->ssize > 0){\n coneOS_printf(\"WARNING: solving SDP, no lapack library specified in makefile!\\n\");\n coneOS_printf(\"ConeOS will return a wrong answer!\\n\");\n }\n#endif\n\n /*\n * exponential cone is not self dual, if s \\in K\n * then y \\in K^* and so if K is the primal cone\n * here we project onto K^*, via Moreau\n */\n scaleArray(&(x[count]), -1, 3*k->ep); // x = -x;\n double r,s,t;\n int idx;\n#pragma omp parallel for private(r,s,t,idx)\n for (i=0; i < k->ep; ++i) {\n idx = count + 3*i;\n r = x[idx];\n s = x[idx+1];\n t = x[idx+2];\n\n projExpCone(&(x[idx]));\n\n x[idx] -= r;\n x[idx+1] -= s;\n x[idx+2] -= t;\n }\n count += 3*k->ep;\n\n // exponential cone:\n#pragma omp parallel for\n for (i=0; i < k->ed; ++i) {\n projExpCone(&(x[count + 3*i]));\n }\n count += 3*k->ed;\n /* project onto OTHER cones */\n}\n\ndouble expNewtonOneD(double rho, double y_hat, double z_hat) {\n double t = fmax( -z_hat , 1e-6);\n double f, fp;\n for (int i=0; i<100; ++i){\n \n f = t * (t + z_hat) / rho / rho - y_hat/rho + log(t/rho) + 1;\n fp = (2 * t + z_hat) / rho / rho + 1/t;\n\n t = t - f/fp;\n \n if (t <= -z_hat) {\n return 0;\n } else if (t <= 0) {\n return z_hat;\n } else if ( fabs(f) < 1e-9 ) {\n break;\n }\n }\n return t + z_hat;\n}\n\nvoid expSolveForXWithRho(double * v, double * x, double rho) {\n x[2] = expNewtonOneD(rho, v[1], v[2]);\n x[1] = (x[2] - v[2]) * x[2] / rho;\n x[0] = v[0] - rho;\n}\n\ndouble expCalcGrad(double * v, double * x, double rho) {\n expSolveForXWithRho(v, x, rho);\n if (x[1] <= 1e-12) {\n return x[0];\n } else {\n return x[0] + x[1] * log( x[1] / x[2] ); \n }\n}\n\nvoid expGetRhoUb(double * v, double * x, double * ub, double * lb) {\n *lb = 0;\n *ub = 0.125;\n while(expCalcGrad(v, x, *ub) > 0) {\n *lb = *ub;\n (*ub) *= 2;\n }\n}\n\n// project onto the exponential cone, v has dimension *exactly* 3\nvoid projExpCone(double * v) {\n\n double r = v[0], s = v[1], t = v[2];\n // v in cl(Kexp)\n if( (s*exp(r/s) <= t && s > 0) || (r <= 0 && s == 0 && t >= 0) ) {\n return;\n }\n\n // -v in Kexp^*\n if ( (-r < 0 && r*exp(s/r) <= -exp(1)*t) || (-r == 0 && -s >= 0 && -t >= 0) ) {\n memset(v, 0, 3*sizeof(double));\n return;\n }\n\n // special case with analytical solution\n if(r < 0 && s < 0) {\n v[1] = 0.0;\n v[2] = fmax(v[2],0);\n return;\n }\n\n double ub, lb, rho, g, x[3];\n expGetRhoUb(v, x, &ub, &lb);\n for(int i = 0; i < 100; ++i){\n rho = (ub + lb)/2;\n g = expCalcGrad(v, x, rho);\n if (g > 0) {\n lb = rho;\n } else{\n ub = rho;\n }\n if (ub - lb < 1e-9) {\n break;\n }\n }\n v[0] = x[0];\n v[1] = x[1];\n v[2] = x[2];\n}\n\n#ifdef LAPACK_LIB_FOUND\nvoid projectsdc(double *X, int n, Work * w)\n{ /* project onto the positive semi-definite cone */\n if (n == 1) {\n if(X[0] < 0.0) X[0] = 0.0; \n return;\n }\n\n int i, j, m=0;\n double * Xs = w->Xs;\n double * Z = w->Z;\n double * e = w->e;\n memcpy(Xs,X,n*n*sizeof(double));\n\n // Xs = X + X', save div by 2 for eigen-recomp\n for (i = 0; i < n; ++i){\n cblas_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);\n //b_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);\n }\n \n double EIG_TOL = 1e-8;\n double vupper = calcNorm(Xs,n*n);\n LAPACKE_dsyevr( LAPACK_COL_MAJOR, 'V', 'V', 'U', n, Xs, n, 0.0, vupper, -1, -1, EIG_TOL, &m, e, Z, n , NULL);\n //printf(\"m is %i, n is %i\\n\", m ,n);\n //printf(\"vupper is %f, max eig is %f\\n\",vupper, e[m>0 ? m-1:0]/2);\n memset(X, 0, n*n*sizeof(double));\n for (i = 0; i < m; ++i) {\n cblas_dsyr(CblasColMajor, CblasLower, n, e[i]/2, &(Z[i*n]), 1, X, n);\n //b_dsyr('L', n, -e[i]/2, &(Z[i*n]), 1, Xs, n);\n }\n // fill in upper half \n for (i = 0; i < n; ++i){ \n for (j = i+1; j < n; ++j){ \n X[i + j*n] = X[j + i*n]; \n } \n }\n}\n#endif\n\n", "meta": {"hexsha": "8e8e6015542f63aed6bd3d53c0f3ed36edec3374", "size": 5230, "ext": "c", "lang": "C", "max_stars_repo_path": "coneOSsparse/cones.c", "max_stars_repo_name": "cvxgrp/coneos", "max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z", "max_issues_repo_path": "coneOSsparse/cones.c", "max_issues_repo_name": "cvxgrp/coneos", "max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coneOSsparse/cones.c", "max_forks_repo_name": "cvxgrp/coneos", "max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z", "avg_line_length": 25.1442307692, "max_line_length": 111, "alphanum_fraction": 0.4504780115, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.493883647201852}} {"text": "/*! @copyright (c) 2017 King Abdullah University of Science and\n * Technology (KAUST). All rights reserved.\n *\n * STARS-H is a software package, provided by King Abdullah\n * University of Science and Technology (KAUST)\n *\n * @file testing/mpi_cauchy.c\n * @version 1.3.0\n * @author Aleksandr Mikhalev\n * @date 2017-11-07\n * */\n\n#ifdef MKL\n #include \n#else\n #include \n #include \n#endif\n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n MPI_Init(&argc, &argv);\n int mpi_size, mpi_rank;\n MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);\n MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n if(argc < 5)\n {\n if(mpi_rank == 0)\n {\n printf(\"%d arguments provided, but 4 are needed\\n\", argc-1);\n printf(\"mpi_cauchy N block_size maxrank tol\\n\");\n }\n MPI_Finalize();\n return 1;\n }\n int N = atoi(argv[1]), block_size = atoi(argv[2]);\n int maxrank = atoi(argv[3]);\n double tol = atof(argv[4]);\n int onfly = 0;\n char dtype = 'd', symm = 'N';\n int ndim = 2;\n STARSH_int shape[2] = {N, N};\n int info;\n srand(0);\n // Init STARS-H\n info = starsh_init();\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n // Generate data for spatial statistics problem\n STARSH_cauchy *data;\n STARSH_kernel *kernel;\n info = starsh_application((void **)&data, &kernel, N, dtype, STARSH_CAUCHY,\n STARSH_CAUCHY_KERNEL1, 0);\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n // Init problem with given data and kernel and print short info\n STARSH_problem *P;\n info = starsh_problem_new(&P, ndim, shape, symm, dtype, data, data,\n kernel, \"Cauchy example\");\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n if(mpi_rank == 0)\n starsh_problem_info(P); \n // Init plain clusterization and print info\n STARSH_cluster *C;\n info = starsh_cluster_new_plain(&C, data, N, block_size);\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n if(mpi_rank == 0)\n starsh_cluster_info(C);\n // Init tlr division into admissible blocks and print short info\n STARSH_blrf *F;\n STARSH_blrm *M;\n info = starsh_blrf_new_tlr_mpi(&F, P, symm, C, C);\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n if(mpi_rank == 0)\n starsh_blrf_info(F);\n // Approximate each admissible block\n MPI_Barrier(MPI_COMM_WORLD);\n double time1 = MPI_Wtime();\n info = starsh_blrm_approximate(&M, F, maxrank, tol, onfly);\n if(info != 0)\n {\n MPI_Finalize();\n return 1;\n }\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime()-time1;\n if(mpi_rank == 0)\n {\n starsh_blrf_info(F);\n starsh_blrm_info(M);\n }\n if(mpi_rank == 0)\n printf(\"TIME TO APPROXIMATE: %e secs\\n\", time1);\n // Measure approximation error\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime();\n double rel_err = starsh_blrm__dfe_mpi(M);\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime()-time1;\n if(mpi_rank == 0)\n {\n printf(\"TIME TO MEASURE ERROR: %e secs\\nRELATIVE ERROR: %e\\n\",\n time1, rel_err);\n if(rel_err/tol > 10.)\n {\n printf(\"Resulting relative error is too big\\n\");\n MPI_Finalize();\n return 1;\n }\n }\n if(rel_err/tol > 10.)\n {\n MPI_Finalize();\n return 1;\n }\n // Measure time for 10 BLRM matvecs and for 10 BLRM TLR matvecs\n double *x, *y, *y_tlr;\n int nrhs = 1;\n x = malloc(N*nrhs*sizeof(*x));\n y = malloc(N*nrhs*sizeof(*y));\n y_tlr = malloc(N*nrhs*sizeof(*y_tlr));\n if(mpi_rank == 0)\n {\n int iseed[4] = {0, 0, 0, 1};\n LAPACKE_dlarnv_work(3, iseed, N*nrhs, x);\n cblas_dscal(N*nrhs, 0.0, y, 1);\n cblas_dscal(N*nrhs, 0.0, y_tlr, 1);\n }\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime();\n for(int i = 0; i < 10; i++)\n starsh_blrm__dmml_mpi(M, nrhs, 1.0, x, N, 0.0, y, N);\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime()-time1;\n if(mpi_rank == 0)\n {\n printf(\"TIME FOR 10 BLRM MATVECS: %e secs\\n\", time1);\n }\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime();\n for(int i = 0; i < 10; i++)\n starsh_blrm__dmml_mpi_tlr(M, nrhs, 1.0, x, N, 0.0, y_tlr, N);\n MPI_Barrier(MPI_COMM_WORLD);\n time1 = MPI_Wtime()-time1;\n if(mpi_rank == 0)\n {\n cblas_daxpy(N, -1.0, y, 1, y_tlr, 1);\n printf(\"TIME FOR 10 TLR MATVECS: %e secs\\n\", time1);\n printf(\"MATVEC DIFF: %e\\n\", cblas_dnrm2(N, y_tlr, 1)\n /cblas_dnrm2(N, y, 1));\n }\n MPI_Finalize();\n return 0;\n}\n\n", "meta": {"hexsha": "3092d3545312593487eefeddc0adfa9e1c0205cb", "size": 4836, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/mpi_cauchy.c", "max_stars_repo_name": "wawando/stars-h", "max_stars_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "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": "testing/mpi_cauchy.c", "max_issues_repo_name": "wawando/stars-h", "max_issues_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "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": "testing/mpi_cauchy.c", "max_forks_repo_name": "wawando/stars-h", "max_forks_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T10:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T10:54:18.000Z", "avg_line_length": 27.0167597765, "max_line_length": 79, "alphanum_fraction": 0.5682382134, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4930705262975761}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"field.h\"\n\n#define StartTest -4E-7\n#define StopTest 4E-7\n\nsignal_type *\nformatExpImpResp(int numPnts, double *timeValues, double *voltageValues,\n\tint samplingFrequencyHz, int verbose)\n{\ndouble *newTimeValues;\ndouble *newVoltageValues;\ndouble timeAtMaxIntensity;\ndouble minTime = DBL_MIN;\ndouble maxTime = -DBL_MIN;\ndouble maxVoltage = -DBL_MIN;\ndouble stepSize;\nint i, j, maxVoltageIndex, numSteps;\nint startIndex, stopIndex;\nsignal_type *impulseResponse;\nint pntsSampled;\n\n/* find the max voltage */\n\n\tfor (i = 0; i < numPnts; i++) {\n\t\tif (maxVoltage < voltageValues[i]) {\n\t\t\tmaxVoltage = voltageValues[i];\n\t\t\tmaxVoltageIndex = i;\n\t\t\t}\n\t\t}\n\n\tif (verbose >= 1) fprintf(stderr, \"index %d max voltage %e\\n\",\n\t\tmaxVoltageIndex, maxVoltage);\n\n/* normalize the voltages */\n\n\tfor (i = 0; i < numPnts; i++)\n\t\tvoltageValues[i] /= maxVoltage;\n\n\n/*\n * center the time axis around the max intensity. the matlab code recalculated\n * the index of the maximum value, but the normalization shouldn't change\n * that, so I skipped it. note that I have to save the time associated with\n * the max intensity, because in the time array, it goes to 0 as I do the\n * centering.\n */\n\n\ttimeAtMaxIntensity = timeValues[maxVoltageIndex];\n\n\tfor (i = 0; i < numPnts; i++)\n\t\ttimeValues[i] = timeValues[i] - timeAtMaxIntensity;\n\n/* now find the min and max times */\n\n\tfor (i = 0; i < numPnts; i++) {\n\t\tif (minTime > timeValues[i]) minTime = timeValues[i];\n\n\t\tif (maxTime < timeValues[i]) maxTime = timeValues[i];\n\t\t}\n\n\tif (verbose >= 1) fprintf(stderr, \"min time %e max time %e\\n\", minTime,\n\t\tmaxTime);\n\n/* re-sample the data to match the Field II sampling frequency */\n\n\tif (verbose >= 1) fprintf(stderr, \"sampling %d\\n\", samplingFrequencyHz);\n\tstepSize = 1.0 / samplingFrequencyHz;\n\n\tif (verbose >= 1) fprintf(stderr, \"diff %e\\n\", maxTime - minTime);\n\tnumSteps = (int )ceil(((maxTime - minTime) * samplingFrequencyHz));\n\n\tif (verbose >= 1) fprintf(stderr, \"step size %e numSteps %d\\n\", stepSize, numSteps);\n\n\tif ((newTimeValues = (double *)malloc(sizeof(double) * numSteps)) == NULL) {\n\t\tfprintf(stderr, \"in readExpData, couldn't allocate space for new times\\n\");\n\t\treturn(0);\n\t\t}\n\n\tfor (i = 0; i < numSteps; i++) {\n\t\tnewTimeValues[i] = minTime + i * stepSize;\n\t\t}\n\n/*\n * now we find the voltage values at each of the new times by interpolating\n * from the old times and voltages.\n */\n\n/* initialize and allocate the gsl objects */\n\n\tgsl_interp *interpolation = gsl_interp_alloc (gsl_interp_linear, numPnts);\n\n\tgsl_interp_init(interpolation, timeValues, voltageValues, numPnts);\n\n\tgsl_interp_accel * accelerator = gsl_interp_accel_alloc();\n\n/* get interpolation the new times */\n\n\tif ((newVoltageValues = (double *)malloc(sizeof(double) * numSteps)) == NULL) {\n\t\tfprintf(stderr, \"in readExpData, couldn't allocate space for new voltage\\n\");\n\t\treturn(0);\n\t\t}\n\n\tfor (i = 0; i < numSteps; i++) {\n\t\tnewVoltageValues[i] = gsl_interp_eval(interpolation, timeValues,\n\t\t\tvoltageValues, newTimeValues[i], accelerator);\n\n\t\tif (verbose >= 3) fprintf(stderr, \"\\n%e\", newVoltageValues[i]);\n\t\t}\n\n/* find the indices of NewTime to use for the Field II impulse response */\n\n\tfor (i = 0; i < numSteps; i++) {\n\t\tif (newTimeValues[i] > StartTest) {\n\t\t\tstartIndex = i;\n\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\tfor (i = 0; i < numSteps; i++)\n\t\tif (newTimeValues[i] > StopTest) {\n\t\t\tstopIndex = i;\n\t\t\tbreak;\n\t\t\t}\n\n\tpntsSampled = stopIndex - startIndex;\n\n\tif (verbose >= 1) fprintf(stderr,\n\t\t\"\\nstartIndex %d, stopIndex %d pntsSampled %d\\n\", startIndex,\n\t\tstopIndex, pntsSampled);\n\n\timpulseResponse = alloc_signal(pntsSampled, 0);\n\n\tfor (i = startIndex, j = 0; i < stopIndex; i++, j++) {\n\t\timpulseResponse->data[j] = newVoltageValues[i];\n\t\tif (verbose >= 3) fprintf(stderr, \"%e\\n\", newVoltageValues[i]);\n\t\t}\n\n\treturn(impulseResponse);\n}\n", "meta": {"hexsha": "d2fc470ee82e82564aa6327660eed830b5d7958e", "size": 3880, "ext": "c", "lang": "C", "max_stars_repo_path": "fieldC/formatExpImpResp.c", "max_stars_repo_name": "suyashkumar/fem", "max_stars_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-02-26T06:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T22:54:08.000Z", "max_issues_repo_path": "fieldC/formatExpImpResp.c", "max_issues_repo_name": "suyashkumar/fem", "max_issues_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2015-02-19T18:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:01:05.000Z", "max_forks_repo_path": "fieldC/formatExpImpResp.c", "max_forks_repo_name": "suyashkumar/fem", "max_forks_repo_head_hexsha": "77fcfb49ea64f81628a5dbcf3951091f0a1d1e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-02-19T00:30:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T23:43:39.000Z", "avg_line_length": 26.7586206897, "max_line_length": 85, "alphanum_fraction": 0.6855670103, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.49290095541275125}} {"text": "/* specfunc/hyperg_U.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#include \n#include \n#include \n#include \n\n#include \"error.h\"\n#include \"hyperg.h\"\n\n#define INT_THRESHOLD (1000.0*GSL_DBL_EPSILON)\n\n#define SERIES_EVAL_OK(a,b,x) ((fabs(a) < 5 && b < 5 && x < 2.0) || (fabs(a) < 10 && b < 10 && x < 1.0))\n\n#define ASYMP_EVAL_OK(a,b,x) (GSL_MAX_DBL(fabs(a),1.0)*GSL_MAX_DBL(fabs(1.0+a-b),1.0) < 0.99*fabs(x))\n\n\n/* Log[U(a,2a,x)]\n * [Abramowitz+stegun, 13.6.21]\n * Assumes x > 0, a > 1/2.\n */\nstatic\nint\nhyperg_lnU_beq2a(const double a, const double x, gsl_sf_result * result)\n{\n const double lx = log(x);\n const double nu = a - 0.5;\n const double lnpre = 0.5*(x - M_LNPI) - nu*lx;\n gsl_sf_result lnK;\n gsl_sf_bessel_lnKnu_e(nu, 0.5*x, &lnK);\n result->val = lnpre + lnK.val;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(0.5*x) + 0.5*M_LNPI + fabs(nu*lx));\n result->err += lnK.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n}\n\n\n/* Evaluate u_{N+1}/u_N by Steed's continued fraction method.\n *\n * u_N := Gamma[a+N]/Gamma[a] U(a + N, b, x)\n *\n * u_{N+1}/u_N = (a+N) U(a+N+1,b,x)/U(a+N,b,x)\n */\nstatic\nint\nhyperg_U_CF1(const double a, const double b, const int N, const double x,\n double * result, int * count)\n{\n const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n const int maxiter = 20000;\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 = -(a + N);\n double b1 = (b - 2.0*a - x - 2.0*(N+1));\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 + n - b)*(a + N + n - 1.0);\n bn = (b - 2.0*a - x - 2.0*(N+n));\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 *count = n;\n\n if(n == maxiter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_SUCCESS;\n}\n\n\n/* Large x asymptotic for x^a U(a,b,x)\n * Based on SLATEC D9CHU() [W. Fullerton]\n *\n * Uses a rational approximation due to Luke.\n * See [Luke, Algorithms for the Computation of Special Functions, p. 252]\n * [Luke, Utilitas Math. (1977)]\n *\n * z^a U(a,b,z) ~ 2F0(a,1+a-b,-1/z)\n *\n * This assumes that a is not a negative integer and\n * that 1+a-b is not a negative integer. If one of them\n * is, then the 2F0 actually terminates, the above\n * relation is an equality, and the sum should be\n * evaluated directly [see below].\n */\nstatic\nint\nd9chu(const double a, const double b, const double x, gsl_sf_result * result)\n{\n const double EPS = 8.0 * GSL_DBL_EPSILON; /* EPS = 4.0D0*D1MACH(4) */\n const int maxiter = 500;\n double aa[4], bb[4];\n int i;\n\n double bp = 1.0 + a - b;\n double ab = a*bp;\n double ct2 = 2.0 * (x - ab);\n double sab = a + bp;\n \n double ct3 = sab + 1.0 + ab;\n double anbn = ct3 + sab + 3.0;\n double ct1 = 1.0 + 2.0*x/anbn;\n\n bb[0] = 1.0;\n aa[0] = 1.0;\n\n bb[1] = 1.0 + 2.0*x/ct3;\n aa[1] = 1.0 + ct2/ct3;\n \n bb[2] = 1.0 + 6.0*ct1*x/ct3;\n aa[2] = 1.0 + 6.0*ab/anbn + 3.0*ct1*ct2/ct3;\n\n for(i=4; ival = aa[3]/bb[3];\n result->err = 8.0 * GSL_DBL_EPSILON * fabs(result->val);\n \n if(i == maxiter) {\n GSL_ERROR (\"error\", GSL_EMAXITER);\n }\n else {\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluate asymptotic for z^a U(a,b,z) ~ 2F0(a,1+a-b,-1/z)\n * We check for termination of the 2F0 as a special case.\n * Assumes x > 0.\n * Also assumes a,b are not too large compared to x.\n */\nstatic\nint\nhyperg_zaU_asymp(const double a, const double b, const double x, gsl_sf_result *result)\n{\n const double ap = a;\n const double bp = 1.0 + a - b;\n const double rintap = floor(ap + 0.5);\n const double rintbp = floor(bp + 0.5);\n const int ap_neg_int = ( ap < 0.0 && fabs(ap - rintap) < INT_THRESHOLD );\n const int bp_neg_int = ( bp < 0.0 && fabs(bp - rintbp) < INT_THRESHOLD );\n\n if(ap_neg_int || bp_neg_int) {\n /* Evaluate 2F0 polynomial.\n */\n double mxi = -1.0/x;\n double nmax = -(int)(GSL_MIN(ap,bp) - 0.1);\n double tn = 1.0;\n double sum = 1.0;\n double n = 1.0;\n double sum_err = 0.0;\n while(n <= nmax) {\n double apn = (ap+n-1.0);\n double bpn = (bp+n-1.0);\n tn *= ((apn/n)*mxi)*bpn;\n sum += tn;\n sum_err += 2.0 * GSL_DBL_EPSILON * fabs(tn);\n n += 1.0;\n }\n result->val = sum;\n result->err = sum_err;\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(nmax)+1.0) * fabs(sum);\n return GSL_SUCCESS;\n }\n else {\n return d9chu(a,b,x,result);\n }\n}\n\n\n/* Evaluate finite sum which appears below.\n */\nstatic\nint\nhyperg_U_finite_sum(int N, double a, double b, double x, double xeps,\n gsl_sf_result * result)\n{\n int i;\n double sum_val;\n double sum_err;\n\n if(N <= 0) {\n double t_val = 1.0;\n double t_err = 0.0;\n gsl_sf_result poch;\n int stat_poch;\n\n sum_val = 1.0;\n sum_err = 0.0;\n for(i=1; i<= -N; i++) {\n const double xi1 = i - 1;\n const double mult = (a+xi1)*x/((b+xi1)*(xi1+1.0));\n t_val *= mult;\n t_err += fabs(mult) * t_err + fabs(t_val) * 8.0 * 2.0 * GSL_DBL_EPSILON;\n sum_val += t_val;\n sum_err += t_err;\n }\n\n stat_poch = gsl_sf_poch_e(1.0+a-b, -a, &poch);\n\n result->val = sum_val * poch.val;\n result->err = fabs(sum_val) * poch.err + sum_err * fabs(poch.val);\n result->err += fabs(poch.val) * (fabs(N) + 2.0) * GSL_DBL_EPSILON * fabs(sum_val);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n result->err *= 2.0; /* FIXME: fudge factor... why is the error estimate too small? */\n return stat_poch;\n }\n else {\n const int M = N - 2;\n if(M < 0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n gsl_sf_result gbm1;\n gsl_sf_result gamr;\n int stat_gbm1;\n int stat_gamr;\n double t_val = 1.0;\n double t_err = 0.0;\n\n sum_val = 1.0;\n sum_err = 0.0;\n for(i=1; i<=M; i++) {\n const double mult = (a-b+i)*x/((1.0-b+i)*i);\n t_val *= mult;\n t_err += t_err * fabs(mult) + fabs(t_val) * 8.0 * 2.0 * GSL_DBL_EPSILON;\n sum_val += t_val;\n sum_err += t_err;\n }\n\n stat_gbm1 = gsl_sf_gamma_e(b-1.0, &gbm1);\n stat_gamr = gsl_sf_gammainv_e(a, &gamr);\n\n if(stat_gbm1 == GSL_SUCCESS) {\n gsl_sf_result powx1N;\n int stat_p = gsl_sf_pow_int_e(x, 1-N, &powx1N);\n double pe_val = powx1N.val * xeps;\n double pe_err = powx1N.err * fabs(xeps) + 2.0 * GSL_DBL_EPSILON * fabs(pe_val);\n double coeff_val = gbm1.val * gamr.val * pe_val;\n double coeff_err = gbm1.err * fabs(gamr.val * pe_val)\n + gamr.err * fabs(gbm1.val * pe_val)\n + fabs(gbm1.val * gamr.val) * pe_err\n + 2.0 * GSL_DBL_EPSILON * fabs(coeff_val);\n\n result->val = sum_val * coeff_val;\n result->err = fabs(sum_val) * coeff_err + sum_err * fabs(coeff_val);\n result->err += 2.0 * GSL_DBL_EPSILON * (M+2.0) * fabs(result->val);\n result->err *= 2.0; /* FIXME: fudge factor... why is the error estimate too small? */\n return stat_p;\n }\n else {\n result->val = 0.0;\n result->err = 0.0;\n return stat_gbm1;\n }\n }\n }\n}\n\n\n/* Based on SLATEC DCHU() [W. Fullerton]\n * Assumes x > 0.\n * This is just a series summation method, and\n * it is not good for large a.\n *\n * I patched up the window for 1+a-b near zero. [GJ]\n */\nstatic\nint\nhyperg_U_series(const double a, const double b, const double x, gsl_sf_result * result)\n{\n const double EPS = 2.0 * GSL_DBL_EPSILON; /* EPS = D1MACH(3) */\n const double SQRT_EPS = M_SQRT2 * GSL_SQRT_DBL_EPSILON;\n\n if(fabs(1.0 + a - b) < SQRT_EPS) {\n /* Original Comment: ALGORITHM IS BAD WHEN 1+A-B IS NEAR ZERO FOR SMALL X\n */\n /* We can however do the following:\n * U(a,b,x) = U(a,a+1,x) when 1+a-b=0\n * and U(a,a+1,x) = x^(-a).\n */\n double lnr = -a * log(x);\n int stat_e = gsl_sf_exp_e(lnr, result);\n result->err += 2.0 * SQRT_EPS * fabs(result->val);\n return stat_e;\n }\n else {\n double aintb = ( b < 0.0 ? ceil(b-0.5) : floor(b+0.5) );\n double beps = b - aintb;\n int N = aintb;\n \n double lnx = log(x);\n double xeps = exp(-beps*lnx);\n\n /* Evaluate finite sum.\n */\n gsl_sf_result sum;\n int stat_sum = hyperg_U_finite_sum(N, a, b, x, xeps, &sum);\n\n\n /* Evaluate infinite sum. */\n\n int istrt = ( N < 1 ? 1-N : 0 );\n double xi = istrt;\n\n gsl_sf_result gamr;\n gsl_sf_result powx;\n int stat_gamr = gsl_sf_gammainv_e(1.0+a-b, &gamr);\n int stat_powx = gsl_sf_pow_int_e(x, istrt, &powx);\n double sarg = beps*M_PI;\n double sfact = ( sarg != 0.0 ? sarg/sin(sarg) : 1.0 );\n double factor_val = sfact * ( GSL_IS_ODD(N) ? -1.0 : 1.0 ) * gamr.val * powx.val;\n double factor_err = fabs(gamr.val) * powx.err + fabs(powx.val) * gamr.err\n + 2.0 * GSL_DBL_EPSILON * fabs(factor_val);\n\n gsl_sf_result pochai;\n gsl_sf_result gamri1;\n gsl_sf_result gamrni;\n int stat_pochai = gsl_sf_poch_e(a, xi, &pochai);\n int stat_gamri1 = gsl_sf_gammainv_e(xi + 1.0, &gamri1);\n int stat_gamrni = gsl_sf_gammainv_e(aintb + xi, &gamrni);\n int stat_gam123 = GSL_ERROR_SELECT_3(stat_gamr, stat_gamri1, stat_gamrni);\n int stat_gamall = GSL_ERROR_SELECT_4(stat_sum, stat_gam123, stat_pochai, stat_powx);\n\n gsl_sf_result pochaxibeps;\n gsl_sf_result gamrxi1beps;\n int stat_pochaxibeps = gsl_sf_poch_e(a, xi-beps, &pochaxibeps);\n int stat_gamrxi1beps = gsl_sf_gammainv_e(xi + 1.0 - beps, &gamrxi1beps);\n\n int stat_all = GSL_ERROR_SELECT_3(stat_gamall, stat_pochaxibeps, stat_gamrxi1beps);\n\n double b0_val = factor_val * pochaxibeps.val * gamrni.val * gamrxi1beps.val;\n double b0_err = fabs(factor_val * pochaxibeps.val * gamrni.val) * gamrxi1beps.err\n + fabs(factor_val * pochaxibeps.val * gamrxi1beps.val) * gamrni.err\n + fabs(factor_val * gamrni.val * gamrxi1beps.val) * pochaxibeps.err\n + fabs(pochaxibeps.val * gamrni.val * gamrxi1beps.val) * factor_err\n + 2.0 * GSL_DBL_EPSILON * fabs(b0_val);\n\n if(fabs(xeps-1.0) < 0.5) {\n /*\n C X**(-BEPS) IS CLOSE TO 1.0D0, SO WE MUST BE\n C CAREFUL IN EVALUATING THE DIFFERENCES.\n */\n int i;\n gsl_sf_result pch1ai;\n gsl_sf_result pch1i;\n gsl_sf_result poch1bxibeps;\n int stat_pch1ai = gsl_sf_pochrel_e(a + xi, -beps, &pch1ai);\n int stat_pch1i = gsl_sf_pochrel_e(xi + 1.0 - beps, beps, &pch1i);\n int stat_poch1bxibeps = gsl_sf_pochrel_e(b+xi, -beps, &poch1bxibeps);\n double c0_t1_val = beps*pch1ai.val*pch1i.val;\n double c0_t1_err = fabs(beps) * fabs(pch1ai.val) * pch1i.err\n + fabs(beps) * fabs(pch1i.val) * pch1ai.err\n + 2.0 * GSL_DBL_EPSILON * fabs(c0_t1_val);\n double c0_t2_val = -poch1bxibeps.val + pch1ai.val - pch1i.val + c0_t1_val;\n double c0_t2_err = poch1bxibeps.err + pch1ai.err + pch1i.err + c0_t1_err\n + 2.0 * GSL_DBL_EPSILON * fabs(c0_t2_val);\n double c0_val = factor_val * pochai.val * gamrni.val * gamri1.val * c0_t2_val;\n double c0_err = fabs(factor_val * pochai.val * gamrni.val * gamri1.val) * c0_t2_err\n + fabs(factor_val * pochai.val * gamrni.val * c0_t2_val) * gamri1.err\n + fabs(factor_val * pochai.val * gamri1.val * c0_t2_val) * gamrni.err\n + fabs(factor_val * gamrni.val * gamri1.val * c0_t2_val) * pochai.err\n + fabs(pochai.val * gamrni.val * gamri1.val * c0_t2_val) * factor_err\n + 2.0 * GSL_DBL_EPSILON * fabs(c0_val);\n /*\n C XEPS1 = (1.0 - X**(-BEPS))/BEPS = (X**(-BEPS) - 1.0)/(-BEPS)\n */\n gsl_sf_result dexprl;\n int stat_dexprl = gsl_sf_exprel_e(-beps*lnx, &dexprl);\n double xeps1_val = lnx * dexprl.val;\n double xeps1_err = 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(beps*lnx)) * fabs(dexprl.val)\n + fabs(lnx) * dexprl.err\n + 2.0 * GSL_DBL_EPSILON * fabs(xeps1_val);\n double dchu_val = sum.val + c0_val + xeps1_val*b0_val;\n double dchu_err = sum.err + c0_err\n + fabs(xeps1_val)*b0_err + xeps1_err * fabs(b0_val)\n + fabs(b0_val*lnx)*dexprl.err\n + 2.0 * GSL_DBL_EPSILON * (fabs(sum.val) + fabs(c0_val) + fabs(xeps1_val*b0_val));\n double xn = N;\n double t_val;\n double t_err;\n\n stat_all = GSL_ERROR_SELECT_5(stat_all, stat_dexprl, stat_poch1bxibeps, stat_pch1i, stat_pch1ai);\n\n for(i=1; i<2000; i++) {\n const double xi = istrt + i;\n const double xi1 = istrt + i - 1;\n const double tmp = (a-1.0)*(xn+2.0*xi-1.0) + xi*(xi-beps);\n const double b0_multiplier = (a+xi1-beps)*x/((xn+xi1)*(xi-beps));\n const double c0_multiplier_1 = (a+xi1)*x/((b+xi1)*xi);\n const double c0_multiplier_2 = tmp / (xi*(b+xi1)*(a+xi1-beps));\n b0_val *= b0_multiplier;\n b0_err += fabs(b0_multiplier) * b0_err + fabs(b0_val) * 8.0 * 2.0 * GSL_DBL_EPSILON;\n c0_val = c0_multiplier_1 * c0_val - c0_multiplier_2 * b0_val;\n c0_err = fabs(c0_multiplier_1) * c0_err\n + fabs(c0_multiplier_2) * b0_err\n + fabs(c0_val) * 8.0 * 2.0 * GSL_DBL_EPSILON\n + fabs(b0_val * c0_multiplier_2) * 16.0 * 2.0 * GSL_DBL_EPSILON;\n t_val = c0_val + xeps1_val*b0_val;\n t_err = c0_err + fabs(xeps1_val)*b0_err;\n t_err += fabs(b0_val*lnx) * dexprl.err;\n t_err += fabs(b0_val)*xeps1_err;\n dchu_val += t_val;\n dchu_err += t_err;\n if(fabs(t_val) < EPS*fabs(dchu_val)) break;\n }\n\n result->val = dchu_val;\n result->err = 2.0 * dchu_err;\n result->err += 2.0 * fabs(t_val);\n result->err += 4.0 * GSL_DBL_EPSILON * (i+2.0) * fabs(dchu_val);\n result->err *= 2.0; /* FIXME: fudge factor */\n\n if(i >= 2000) {\n GSL_ERROR (\"error\", GSL_EMAXITER);\n }\n else {\n return stat_all;\n }\n }\n else {\n /*\n C X**(-BEPS) IS VERY DIFFERENT FROM 1.0, SO THE\n C STRAIGHTFORWARD FORMULATION IS STABLE.\n */\n int i;\n double dchu_val;\n double dchu_err;\n double t_val;\n double t_err;\n gsl_sf_result dgamrbxi;\n int stat_dgamrbxi = gsl_sf_gammainv_e(b+xi, &dgamrbxi);\n double a0_val = factor_val * pochai.val * dgamrbxi.val * gamri1.val / beps;\n double a0_err = fabs(factor_val * pochai.val * dgamrbxi.val / beps) * gamri1.err\n + fabs(factor_val * pochai.val * gamri1.val / beps) * dgamrbxi.err\n + fabs(factor_val * dgamrbxi.val * gamri1.val / beps) * pochai.err\n + fabs(pochai.val * dgamrbxi.val * gamri1.val / beps) * factor_err\n + 2.0 * GSL_DBL_EPSILON * fabs(a0_val);\n stat_all = GSL_ERROR_SELECT_2(stat_all, stat_dgamrbxi);\n\n b0_val = xeps * b0_val / beps;\n b0_err = fabs(xeps / beps) * b0_err + 4.0 * GSL_DBL_EPSILON * fabs(b0_val);\n dchu_val = sum.val + a0_val - b0_val;\n dchu_err = sum.err + a0_err + b0_err\n + 2.0 * GSL_DBL_EPSILON * (fabs(sum.val) + fabs(a0_val) + fabs(b0_val));\n\n for(i=1; i<2000; i++) {\n double xi = istrt + i;\n double xi1 = istrt + i - 1;\n double a0_multiplier = (a+xi1)*x/((b+xi1)*xi);\n double b0_multiplier = (a+xi1-beps)*x/((aintb+xi1)*(xi-beps));\n a0_val *= a0_multiplier;\n a0_err += fabs(a0_multiplier) * a0_err;\n b0_val *= b0_multiplier;\n b0_err += fabs(b0_multiplier) * b0_err;\n t_val = a0_val - b0_val;\n t_err = a0_err + b0_err;\n dchu_val += t_val;\n dchu_err += t_err;\n if(fabs(t_val) < EPS*fabs(dchu_val)) break;\n }\n\n result->val = dchu_val;\n result->err = 2.0 * dchu_err;\n result->err += 2.0 * fabs(t_val);\n result->err += 4.0 * GSL_DBL_EPSILON * (i+2.0) * fabs(dchu_val);\n result->err *= 2.0; /* FIXME: fudge factor */\n\n if(i >= 2000) {\n GSL_ERROR (\"error\", GSL_EMAXITER);\n }\n else {\n return stat_all;\n }\n }\n }\n}\n\n\n/* Assumes b > 0 and x > 0.\n */\nstatic\nint\nhyperg_U_small_ab(const double a, const double b, const double x, gsl_sf_result * result)\n{\n if(a == -1.0) {\n /* U(-1,c+1,x) = Laguerre[c,0,x] = -b + x\n */\n result->val = -b + x;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(b) + fabs(x));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(a == 0.0) {\n /* U(0,c+1,x) = Laguerre[c,0,x] = 1\n */\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(ASYMP_EVAL_OK(a,b,x)) {\n double p = pow(x, -a);\n gsl_sf_result asymp;\n int stat_asymp = hyperg_zaU_asymp(a, b, x, &asymp);\n result->val = asymp.val * p;\n result->err = asymp.err * p;\n result->err += fabs(asymp.val) * GSL_DBL_EPSILON * fabs(a) * p;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_asymp;\n }\n else {\n return hyperg_U_series(a, b, x, result);\n }\n}\n\n\n/* Assumes b > 0 and x > 0.\n */\nstatic\nint\nhyperg_U_small_a_bgt0(const double a, const double b, const double x,\n gsl_sf_result * result,\n double * ln_multiplier\n )\n{\n if(a == 0.0) {\n result->val = 1.0;\n result->err = 1.0;\n *ln_multiplier = 0.0;\n return GSL_SUCCESS;\n }\n else if( (b > 5000.0 && x < 0.90 * fabs(b))\n || (b > 500.0 && x < 0.50 * fabs(b))\n ) {\n int stat = gsl_sf_hyperg_U_large_b_e(a, b, x, result, ln_multiplier);\n if(stat == GSL_EOVRFLW)\n return GSL_SUCCESS;\n else\n return stat;\n }\n else if(b > 15.0) {\n /* Recurse up from b near 1.\n */\n double eps = b - floor(b);\n double b0 = 1.0 + eps;\n gsl_sf_result r_Ubm1;\n gsl_sf_result r_Ub;\n int stat_0 = hyperg_U_small_ab(a, b0, x, &r_Ubm1);\n int stat_1 = hyperg_U_small_ab(a, b0+1.0, x, &r_Ub);\n double Ubm1 = r_Ubm1.val;\n double Ub = r_Ub.val;\n double Ubp1;\n double bp;\n\n for(bp = b0+1.0; bpval = Ub;\n result->err = (fabs(r_Ubm1.err/r_Ubm1.val) + fabs(r_Ub.err/r_Ub.val)) * fabs(Ub);\n result->err += 2.0 * GSL_DBL_EPSILON * (fabs(b-b0)+1.0) * fabs(Ub);\n *ln_multiplier = 0.0;\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n else {\n *ln_multiplier = 0.0;\n return hyperg_U_small_ab(a, b, x, result);\n }\n}\n\n\n/* We use this to keep track of large\n * dynamic ranges in the recursions.\n * This can be important because sometimes\n * we want to calculate a very large and\n * a very small number and the answer is\n * the product, of order 1. This happens,\n * for instance, when we apply a Kummer\n * transform to make b positive and\n * both x and b are large.\n */\n#define RESCALE_2(u0,u1,factor,count) \\\ndo { \\\n double au0 = fabs(u0); \\\n if(au0 > factor) { \\\n u0 /= factor; \\\n u1 /= factor; \\\n count++; \\\n } \\\n else if(au0 < 1.0/factor) { \\\n u0 *= factor; \\\n u1 *= factor; \\\n count--; \\\n } \\\n} while (0)\n\n\n/* Specialization to b >= 1, for integer parameters.\n * Assumes x > 0.\n */\nstatic\nint\nhyperg_U_int_bge1(const int a, const int b, const double x,\n gsl_sf_result_e10 * result)\n{\n if(a == 0) {\n result->val = 1.0;\n result->err = 0.0;\n result->e10 = 0;\n return GSL_SUCCESS;\n }\n else if(a == -1) {\n result->val = -b + x;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(b) + fabs(x));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n result->e10 = 0;\n return GSL_SUCCESS;\n }\n else if(b == a + 1) {\n /* U(a,a+1,x) = x^(-a)\n */\n return gsl_sf_exp_e10_e(-a*log(x), result);\n }\n else if(ASYMP_EVAL_OK(a,b,x)) {\n const double ln_pre_val = -a*log(x);\n const double ln_pre_err = 2.0 * GSL_DBL_EPSILON * fabs(ln_pre_val);\n gsl_sf_result asymp;\n int stat_asymp = hyperg_zaU_asymp(a, b, x, &asymp);\n int stat_e = gsl_sf_exp_mult_err_e10_e(ln_pre_val, ln_pre_err,\n asymp.val, asymp.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_asymp);\n }\n else if(SERIES_EVAL_OK(a,b,x)) {\n gsl_sf_result ser;\n const int stat_ser = hyperg_U_series(a, b, x, &ser);\n result->val = ser.val;\n result->err = ser.err;\n result->e10 = 0;\n return stat_ser;\n }\n else if(a < 0) {\n /* Recurse backward from a = -1,0.\n */\n int scale_count = 0;\n const double scale_factor = GSL_SQRT_DBL_MAX;\n gsl_sf_result lnm;\n gsl_sf_result y;\n double lnscale;\n double Uap1 = 1.0; /* U(0,b,x) */\n double Ua = -b + x; /* U(-1,b,x) */\n double Uam1;\n int ap;\n\n for(ap=-1; ap>a; ap--) {\n Uam1 = ap*(b-ap-1.0)*Uap1 + (x+2.0*ap-b)*Ua;\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count);\n }\n\n lnscale = log(scale_factor);\n lnm.val = scale_count*lnscale;\n lnm.err = 2.0 * GSL_DBL_EPSILON * fabs(lnm.val);\n y.val = Ua;\n y.err = 4.0 * GSL_DBL_EPSILON * (fabs(a)+1.0) * fabs(Ua);\n return gsl_sf_exp_mult_err_e10_e(lnm.val, lnm.err, y.val, y.err, result);\n }\n else if(b >= 2.0*a + x) {\n /* Recurse forward from a = 0,1.\n */\n int scale_count = 0;\n const double scale_factor = GSL_SQRT_DBL_MAX;\n gsl_sf_result r_Ua;\n gsl_sf_result lnm;\n gsl_sf_result y;\n double lnscale;\n double lm;\n int stat_1 = hyperg_U_small_a_bgt0(1.0, b, x, &r_Ua, &lm); /* U(1,b,x) */\n int stat_e;\n double Uam1 = 1.0; /* U(0,b,x) */\n double Ua = r_Ua.val;\n double Uap1;\n int ap;\n\n Uam1 *= exp(-lm);\n\n for(ap=1; apa_target; ap--) {\n Uam1 = -((b-2.0*ap-x)*Ua + ap*(1.0+ap-b)*Uap1);\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count);\n }\n\n if(Ua == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n result->e10 = 0;\n GSL_ERROR (\"error\", GSL_EZERODIV);\n }\n else {\n double lnscl = -scale_count*log(scale_factor);\n double lnpre_val = lnU_target + lnscl;\n double lnpre_err = 2.0 * GSL_DBL_EPSILON * (fabs(lnU_target) + fabs(lnscl));\n double oUa_err = 2.0 * (fabs(a_target-a) + CF1_count + 1.0) * GSL_DBL_EPSILON * fabs(1.0/Ua);\n int stat_e = gsl_sf_exp_mult_err_e10_e(lnpre_val, lnpre_err,\n 1.0/Ua, oUa_err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_CF1);\n }\n }\n else {\n /* Recurse backward to near the b=2a+x line, then\n * determine normalization by either direct evaluation\n * or by a forward recursion. The direct evaluation\n * is needed when x is small (which is precisely\n * when it is easy to do).\n */\n const double scale_factor = GSL_SQRT_DBL_MAX;\n int scale_count_for = 0;\n int scale_count_bck = 0;\n int a0 = 1;\n int a1 = a0 + ceil(0.5*(b-x) - a0);\n double Ua1_bck_val;\n double Ua1_bck_err;\n double Ua1_for_val;\n double Ua1_for_err;\n int stat_for;\n int stat_bck;\n gsl_sf_result lm_for;\n\n {\n /* Recurse back to determine U(a1,b), sans normalization.\n */\n double ru;\n int CF1_count;\n int stat_CF1 = hyperg_U_CF1(a, b, 0, x, &ru, &CF1_count);\n double Ua = 1.0;\n double Uap1 = ru/a * Ua;\n double Uam1;\n int ap;\n for(ap=a; ap>a1; ap--) {\n Uam1 = -((b-2.0*ap-x)*Ua + ap*(1.0+ap-b)*Uap1);\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count_bck);\n }\n Ua1_bck_val = Ua;\n Ua1_bck_err = 2.0 * GSL_DBL_EPSILON * (fabs(a1-a)+CF1_count+1.0) * fabs(Ua);\n stat_bck = stat_CF1;\n }\n\n if(b == 2*a1 && a1 > 1) {\n /* This can happen when x is small, which is\n * precisely when we need to be careful with\n * this evaluation.\n */\n hyperg_lnU_beq2a((double)a1, x, &lm_for);\n Ua1_for_val = 1.0;\n Ua1_for_err = 0.0;\n stat_for = GSL_SUCCESS;\n }\n else if(b == 2*a1 - 1 && a1 > 1) {\n /* Similar to the above. Happens when x is small.\n * Use\n * U(a,2a-1) = (x U(a,2a) - U(a-1,2(a-1))) / (2a - 2)\n */\n gsl_sf_result lnU00, lnU12;\n gsl_sf_result U00, U12;\n hyperg_lnU_beq2a(a1-1.0, x, &lnU00);\n hyperg_lnU_beq2a(a1, x, &lnU12);\n if(lnU00.val > lnU12.val) {\n lm_for.val = lnU00.val;\n lm_for.err = lnU00.err;\n U00.val = 1.0;\n U00.err = 0.0;\n gsl_sf_exp_err_e(lnU12.val - lm_for.val, lnU12.err + lm_for.err, &U12);\n }\n else {\n lm_for.val = lnU12.val;\n lm_for.err = lnU12.err;\n U12.val = 1.0;\n U12.err = 0.0;\n gsl_sf_exp_err_e(lnU00.val - lm_for.val, lnU00.err + lm_for.err, &U00);\n }\n Ua1_for_val = (x * U12.val - U00.val) / (2.0*a1 - 2.0);\n Ua1_for_err = (fabs(x)*U12.err + U00.err) / fabs(2.0*a1 - 2.0);\n Ua1_for_err += 2.0 * GSL_DBL_EPSILON * fabs(Ua1_for_val);\n stat_for = GSL_SUCCESS;\n }\n else {\n /* Recurse forward to determine U(a1,b) with\n * absolute normalization.\n */\n gsl_sf_result r_Ua;\n double Uam1 = 1.0; /* U(a0-1,b,x) = U(0,b,x) */\n double Ua;\n double Uap1;\n int ap;\n double lm_for_local;\n stat_for = hyperg_U_small_a_bgt0(a0, b, x, &r_Ua, &lm_for_local); /* U(1,b,x) */\n Ua = r_Ua.val;\n Uam1 *= exp(-lm_for_local);\n lm_for.val = lm_for_local;\n lm_for.err = 0.0;\n\n for(ap=a0; apval = 0.0;\n result->err = 0.0;\n result->e10 = 0;\n GSL_ERROR (\"error\", GSL_EZERODIV);\n }\n else if(Ua1_for_val == 0.0) {\n /* Should never happen. */\n UNDERFLOW_ERROR_E10(result);\n }\n else {\n double lns = (scale_count_for - scale_count_bck)*log(scale_factor);\n double ln_for_val = log(fabs(Ua1_for_val));\n double ln_for_err = GSL_DBL_EPSILON + fabs(Ua1_for_err/Ua1_for_val);\n double ln_bck_val = log(fabs(Ua1_bck_val));\n double ln_bck_err = GSL_DBL_EPSILON + fabs(Ua1_bck_err/Ua1_bck_val);\n double lnr_val = lm_for.val + ln_for_val - ln_bck_val + lns;\n double lnr_err = lm_for.err + ln_for_err + ln_bck_err\n + 2.0 * GSL_DBL_EPSILON * (fabs(lm_for.val) + fabs(ln_for_val) + fabs(ln_bck_val) + fabs(lns));\n double sgn = GSL_SIGN(Ua1_for_val) * GSL_SIGN(Ua1_bck_val);\n int stat_e = gsl_sf_exp_err_e10_e(lnr_val, lnr_err, result);\n result->val *= sgn;\n return GSL_ERROR_SELECT_3(stat_e, stat_bck, stat_for);\n }\n }\n }\n}\n\n\n/* Handle b >= 1 for generic a,b values.\n */\nstatic\nint\nhyperg_U_bge1(const double a, const double b, const double x,\n gsl_sf_result_e10 * result)\n{\n const double rinta = floor(a+0.5);\n const int a_neg_integer = (a < 0.0 && fabs(a - rinta) < INT_THRESHOLD);\n\n if(a == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n result->e10 = 0;\n return GSL_SUCCESS;\n }\n else if(a_neg_integer && fabs(rinta) < INT_MAX) {\n /* U(-n,b,x) = (-1)^n n! Laguerre[n,b-1,x]\n */\n const int n = -(int)rinta;\n const double sgn = (GSL_IS_ODD(n) ? -1.0 : 1.0);\n gsl_sf_result lnfact;\n gsl_sf_result L;\n const int stat_L = gsl_sf_laguerre_n_e(n, b-1.0, x, &L);\n gsl_sf_lnfact_e(n, &lnfact);\n {\n const int stat_e = gsl_sf_exp_mult_err_e10_e(lnfact.val, lnfact.err,\n sgn*L.val, L.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_L);\n }\n }\n else if(ASYMP_EVAL_OK(a,b,x)) {\n const double ln_pre_val = -a*log(x);\n const double ln_pre_err = 2.0 * GSL_DBL_EPSILON * fabs(ln_pre_val);\n gsl_sf_result asymp;\n int stat_asymp = hyperg_zaU_asymp(a, b, x, &asymp);\n int stat_e = gsl_sf_exp_mult_err_e10_e(ln_pre_val, ln_pre_err,\n asymp.val, asymp.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_asymp);\n }\n else if(fabs(a) <= 1.0) {\n gsl_sf_result rU;\n double ln_multiplier;\n int stat_U = hyperg_U_small_a_bgt0(a, b, x, &rU, &ln_multiplier);\n int stat_e = gsl_sf_exp_mult_err_e10_e(ln_multiplier, 2.0*GSL_DBL_EPSILON*fabs(ln_multiplier), rU.val, rU.err, result);\n return GSL_ERROR_SELECT_2(stat_U, stat_e);\n }\n else if(SERIES_EVAL_OK(a,b,x)) {\n gsl_sf_result ser;\n const int stat_ser = hyperg_U_series(a, b, x, &ser);\n result->val = ser.val;\n result->err = ser.err;\n result->e10 = 0;\n return stat_ser;\n }\n else if(a < 0.0) {\n /* Recurse backward on a and then upward on b.\n */\n const double scale_factor = GSL_SQRT_DBL_MAX;\n const double a0 = a - floor(a) - 1.0;\n const double b0 = b - floor(b) + 1.0;\n int scale_count = 0;\n double lm_0, lm_1;\n double lm_max;\n gsl_sf_result r_Uap1;\n gsl_sf_result r_Ua;\n int stat_0 = hyperg_U_small_a_bgt0(a0+1.0, b0, x, &r_Uap1, &lm_0);\n int stat_1 = hyperg_U_small_a_bgt0(a0, b0, x, &r_Ua, &lm_1);\n int stat_e;\n double Uap1 = r_Uap1.val;\n double Ua = r_Ua.val;\n double Uam1;\n double ap;\n lm_max = GSL_MAX(lm_0, lm_1);\n Uap1 *= exp(lm_0-lm_max);\n Ua *= exp(lm_1-lm_max);\n\n /* Downward recursion on a.\n */\n for(ap=a0; ap>a+0.1; ap -= 1.0) {\n Uam1 = ap*(b0-ap-1.0)*Uap1 + (x+2.0*ap-b0)*Ua;\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count);\n }\n\n if(b < 2.0) {\n /* b == b0, so no recursion necessary\n */\n const double lnscale = log(scale_factor);\n gsl_sf_result lnm;\n gsl_sf_result y;\n lnm.val = lm_max + scale_count * lnscale;\n lnm.err = 2.0 * GSL_DBL_EPSILON * (fabs(lm_max) + scale_count * fabs(lnscale));\n y.val = Ua;\n y.err = fabs(r_Uap1.err/r_Uap1.val) * fabs(Ua);\n y.err += fabs(r_Ua.err/r_Ua.val) * fabs(Ua);\n y.err += 2.0 * GSL_DBL_EPSILON * (fabs(a-a0) + 1.0) * fabs(Ua);\n y.err *= fabs(lm_0-lm_max) + 1.0;\n y.err *= fabs(lm_1-lm_max) + 1.0;\n stat_e = gsl_sf_exp_mult_err_e10_e(lnm.val, lnm.err, y.val, y.err, result);\n }\n else {\n /* Upward recursion on b.\n */\n const double err_mult = fabs(b-b0) + fabs(a-a0) + 1.0;\n const double lnscale = log(scale_factor);\n gsl_sf_result lnm;\n gsl_sf_result y;\n\n double Ubm1 = Ua; /* U(a,b0) */\n double Ub = (a*(b0-a-1.0)*Uap1 + (a+x)*Ua)/x; /* U(a,b0+1) */\n double Ubp1;\n double bp;\n for(bp=b0+1.0; bp= 2*a + x) {\n /* Recurse forward from a near zero.\n * Note that we cannot cross the singularity at\n * the line b=a+1, because the only way we could\n * be in that little wedge is if a < 1. But we\n * have already dealt with the small a case.\n */\n int scale_count = 0;\n const double a0 = a - floor(a);\n const double scale_factor = GSL_SQRT_DBL_MAX;\n double lnscale;\n double lm_0, lm_1, lm_max;\n gsl_sf_result r_Uam1;\n gsl_sf_result r_Ua;\n int stat_0 = hyperg_U_small_a_bgt0(a0-1.0, b, x, &r_Uam1, &lm_0);\n int stat_1 = hyperg_U_small_a_bgt0(a0, b, x, &r_Ua, &lm_1);\n int stat_e;\n gsl_sf_result lnm;\n gsl_sf_result y;\n double Uam1 = r_Uam1.val;\n double Ua = r_Ua.val;\n double Uap1;\n double ap;\n lm_max = GSL_MAX(lm_0, lm_1);\n Uam1 *= exp(lm_0-lm_max);\n Ua *= exp(lm_1-lm_max);\n\n for(ap=a0; apa0+0.1; ap -= 1.0) {\n Uam1 = -((b-2.0*ap-x)*Ua + ap*(1.0+ap-b)*Uap1);\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count);\n }\n\n stat_U0 = hyperg_U_small_a_bgt0(a0, b, x, &U0, &lm_0);\n\n lnscale = log(scale_factor);\n lnm.val = lm_0 - scale_count * lnscale;\n lnm.err = 2.0 * GSL_DBL_EPSILON * (fabs(lm_0) + fabs(scale_count * lnscale));\n y.val = GSL_SQRT_DBL_MIN*(U0.val/Ua);\n y.err = GSL_SQRT_DBL_MIN*(U0.err/fabs(Ua));\n y.err += 2.0 * GSL_DBL_EPSILON * (fabs(a0-a) + CF1_count + 1.0) * fabs(y.val);\n stat_e = gsl_sf_exp_mult_err_e10_e(lnm.val, lnm.err, y.val, y.err, result);\n return GSL_ERROR_SELECT_3(stat_e, stat_U0, stat_CF1);\n }\n else {\n /* Recurse backward to near the b=2a+x line, then\n * forward from a near zero to get the normalization.\n */\n int scale_count_for = 0;\n int scale_count_bck = 0;\n const double scale_factor = GSL_SQRT_DBL_MAX;\n const double eps = a - floor(a);\n const double a0 = ( eps == 0.0 ? 1.0 : eps );\n const double a1 = a0 + ceil(0.5*(b-x) - a0);\n gsl_sf_result lnm;\n gsl_sf_result y;\n double lm_for;\n double lnscale;\n double Ua1_bck;\n double Ua1_for;\n int stat_for;\n int stat_bck;\n int stat_e;\n int CF1_count;\n\n {\n /* Recurse back to determine U(a1,b), sans normalization.\n */\n double Uap1;\n double Ua;\n double Uam1;\n double ap;\n double ru;\n double r;\n int stat_CF1 = hyperg_U_CF1(a, b, 0, x, &ru, &CF1_count);\n r = ru/a;\n Ua = GSL_SQRT_DBL_MIN;\n Uap1 = r * Ua;\n for(ap=a; ap>a1+0.1; ap -= 1.0) {\n Uam1 = -((b-2.0*ap-x)*Ua + ap*(1.0+ap-b)*Uap1);\n Uap1 = Ua;\n Ua = Uam1;\n RESCALE_2(Ua,Uap1,scale_factor,scale_count_bck);\n }\n Ua1_bck = Ua;\n stat_bck = stat_CF1;\n }\n {\n /* Recurse forward to determine U(a1,b) with\n * absolute normalization.\n */\n gsl_sf_result r_Uam1;\n gsl_sf_result r_Ua;\n double lm_0, lm_1;\n int stat_0 = hyperg_U_small_a_bgt0(a0-1.0, b, x, &r_Uam1, &lm_0);\n int stat_1 = hyperg_U_small_a_bgt0(a0, b, x, &r_Ua, &lm_1);\n double Uam1 = r_Uam1.val;\n double Ua = r_Ua.val;\n double Uap1;\n double ap;\n\n lm_for = GSL_MAX(lm_0, lm_1);\n Uam1 *= exp(lm_0 - lm_for);\n Ua *= exp(lm_1 - lm_for);\n\n for(ap=a0; ap= 1) {\n return hyperg_U_int_bge1(a, b, x, result);\n }\n else {\n /* Use the reflection formula\n * U(a,b,x) = x^(1-b) U(1+a-b,2-b,x)\n */\n gsl_sf_result_e10 U;\n double ln_x = log(x);\n int ap = 1 + a - b;\n int bp = 2 - b;\n int stat_e;\n int stat_U = hyperg_U_int_bge1(ap, bp, x, &U);\n double ln_pre_val = (1.0-b)*ln_x;\n double ln_pre_err = 2.0 * GSL_DBL_EPSILON * (fabs(b)+1.0) * fabs(ln_x);\n ln_pre_err += 2.0 * GSL_DBL_EPSILON * fabs(1.0-b); /* error in log(x) */\n stat_e = gsl_sf_exp_mult_err_e10_e(ln_pre_val + U.e10*M_LN10, ln_pre_err,\n U.val, U.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_U);\n }\n }\n}\n\n\nint\ngsl_sf_hyperg_U_e10_e(const double a, const double b, const double x,\n gsl_sf_result_e10 * result)\n{\n const double rinta = floor(a + 0.5);\n const double rintb = floor(b + 0.5);\n const int a_integer = ( fabs(a - rinta) < INT_THRESHOLD );\n const int b_integer = ( fabs(b - rintb) < INT_THRESHOLD );\n\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR_E10(result);\n }\n else if(a == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n result->e10 = 0;\n return GSL_SUCCESS;\n }\n else if(a_integer && b_integer) {\n return gsl_sf_hyperg_U_int_e10_e(rinta, rintb, x, result);\n }\n else {\n if(b >= 1.0) {\n /* Use b >= 1 function.\n */\n return hyperg_U_bge1(a, b, x, result);\n }\n else {\n /* Use the reflection formula\n * U(a,b,x) = x^(1-b) U(1+a-b,2-b,x)\n */\n const double lnx = log(x);\n const double ln_pre_val = (1.0-b)*lnx;\n const double ln_pre_err = fabs(lnx) * 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(b));\n const double ap = 1.0 + a - b;\n const double bp = 2.0 - b;\n gsl_sf_result_e10 U;\n int stat_U = hyperg_U_bge1(ap, bp, x, &U);\n int stat_e = gsl_sf_exp_mult_err_e10_e(ln_pre_val + U.e10*M_LN10, ln_pre_err,\n U.val, U.err,\n result);\n return GSL_ERROR_SELECT_2(stat_e, stat_U);\n }\n }\n}\n\n\nint\ngsl_sf_hyperg_U_int_e(const int a, const int b, const double x, gsl_sf_result * result)\n{\n gsl_sf_result_e10 re;\n int stat_U = gsl_sf_hyperg_U_int_e10_e(a, b, x, &re);\n int stat_c = gsl_sf_result_smash_e(&re, result);\n return GSL_ERROR_SELECT_2(stat_c, stat_U);\n}\n\n\nint\ngsl_sf_hyperg_U_e(const double a, const double b, const double x, gsl_sf_result * result)\n{\n gsl_sf_result_e10 re;\n int stat_U = gsl_sf_hyperg_U_e10_e(a, b, x, &re);\n int stat_c = gsl_sf_result_smash_e(&re, result);\n return GSL_ERROR_SELECT_2(stat_c, stat_U);\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_hyperg_U_int(const int a, const int b, const double x)\n{\n EVAL_RESULT(gsl_sf_hyperg_U_int_e(a, b, x, &result));\n}\n\ndouble gsl_sf_hyperg_U(const double a, const double b, const double x)\n{\n EVAL_RESULT(gsl_sf_hyperg_U_e(a, b, x, &result));\n}\n", "meta": {"hexsha": "9b28835d6f1f9d9a934aef71530b0b4a0c7bcbf0", "size": 44801, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/hyperg_U.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/hyperg_U.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/hyperg_U.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": 31.841506752, "max_line_length": 123, "alphanum_fraction": 0.5611035468, "num_tokens": 15660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4927481443181659}} {"text": "/*\n * SPDX-License-Identifier: BSD-3-Clause\n * \n * example_08-StructOfArrays-CellLinkedList-OuterOmp.c : \n * Example of SPH Density Calculation using \n * fast neighbor search the main density loop via\n * Cell Linked List method, Struct of Arrays (SoA) \n * data layout, OpenMP parallelization at the \n * cell level, SIMD directives in the kernel\n * and in the inner-most loop. \n *\n * (C) Copyright 2021 José Hugo Elsas\n * Author: José Hugo Elsas \n *\n * Command Line Options: \n * -runs : Set the number of repetitions (runs) for\n * calculating the density. The value of\n * the density is based on the last \n * iteration.\n * Default value: 1\n * -run_seed : Flag to set an alternative seed use for\n * for the PRNG. Instead of feeding seed\n * to the PRNG directly, it feeds \n * seed + iteration, as to generate different\n * configurations for each iteration. \n * Default value: 0 - (possible 0/1)\n * -seed : Set the seed to use for the SPH particles \n * uniform position generation in the box\n * Default value: 123123123\n *\n * -N : Set the number of SPH particles to be used\n * Default value: 1e5 = 100,000\n * -h : Set the value of the smoothing kernel \n * parameter h, which corresponds to half\n * of the support of the kernel. \n * Default value: 0.05\n *\n * -Nx : Set the number of Cells in the X direction\n * Default value: 10\n * -Ny : Set the number of Cells in the Y direction\n * Default value: 10\n * -Nz : Set the number of Cells in the Z direction\n * Default value: 10\n * \n * -Xmin : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 0.0\n * \n * -Xmax : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Ymax : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Zmax : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 1.0\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n#include \"sph_utils.h\"\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n#define COMPUTE_BLOCKS 5\n\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times);\n\nint compute_density_3d_outerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box);\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\nint count_box_pairs(linkedListBox *box);\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\ndouble w_bspline_3d_constant(double h);\n\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q);\n\nint main(int argc, char **argv){\n bool run_seed = false; // By default the behavior is is to use the same seed\n int runs = 1,err; // it only runs once\n long int seed = 123123123; // The default seed is 123123123\n int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000\n double h=0.05; // The default kernel smoothing length is h = 0.05\n linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method\n SPHparticle *lsph; // Uninitialized array of SPH particles\n\n box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain\n\n // allow for command line customization of the run\n arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options\n // line arguments and override default values\n\n err = SPHparticle_SoA_malloc(N,&lsph);\n if(err)\n fprintf(stderr,\"error in SPHparticle_SoA_malloc\\n\");\n\n void *swap_arr = malloc(N*sizeof(double));\n double times[runs*COMPUTE_BLOCKS];\n\n for(int run=0;run : index (or value) or the present iteration\n * run_seed : boolean defining whether to use run index for seed or not\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * seed : seed for GSL PRNG generator to generate particle positions\n * box : Box of linked list cells, encapsulating the 3d domain\n * lsph : Array (pointer) of SPH particles to be updated\n * times : Array to store the computation timings to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n * times : Times is updated by reference\n */\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times)\n{\n int err;\n \n if(run_seed)\n err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);\n else\n err = gen_unif_rdn_pos_box(N,seed,box,lsph);\n\n if(err)\n fprintf(stderr,\"error in gen_unif_rdn_pos\\n\");\n\n // ------------------------------------------------------ //\n\n double t0,t1,t2,t3,t4,t5;\n\n t0 = omp_get_wtime();\n\n err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the \n if(err) // cell index for each of the X, Y and Z \n fprintf(stderr,\"error in compute_hash_MC3D\\n\"); // directions, in which a given particle reside\n\n t1 = omp_get_wtime();\n \n qsort(lsph->hash,N,2*sizeof(int64_t),compare_int64_t); // Sort the Particle Hash Hashes, getting the shuffled\n // index necessary to re-shuffle the remaining arrays\n t2 = omp_get_wtime();\n\n err = reorder_lsph_SoA(N,lsph,swap_arr); // Reorder all arrays according to the sorted hash,\n if(err) // As to have a quick way to retrieve a cell \n fprintf(stderr,\"error in reorder_lsph_SoA\\n\"); // given its hash. \n\n t3 = omp_get_wtime();\n\n err = setup_interval_hashtables(N,lsph,box); // Annotate the begining and end of each cell\n if(err) // on the cell linked list method for fast\n fprintf(stderr,\"error in setup_interval_hashtables\\n\"); // neighbor search\n\n t4 = omp_get_wtime();\n\n err = compute_density_3d_outerOmp(N,h,lsph,box); // Compute the density of the particles based\n if(err) // on the cell linked list method for fast\n fprintf(stderr,\"error in compute_density\\n\"); // neighbor search\n\n // ------------------------------------------------------ //\n\n t5 = omp_get_wtime();\n\n times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash\n times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles' hashes\n times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for reordering all other arrays accordingly\n times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for setting up the interval hash tables\n times[COMPUTE_BLOCKS*run+4] = t5-t4; // Time for computing the SPH particle densities\n\n return 0;\n}\n\n/*\n * Function compute_density_3d_outerOmp:\n * Computes the SPH density from the particles using cell linked list with\n * vectorization at the compute_density_3d_chunk level, but the parallelization\n * done at the level of the outer-most loop of the compute_density_3d_cll_outerOmp\n * function, not at the chunk level. \n * \n * Arguments:\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * lsph : Array (pointer) of SPH particles to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n */\nint compute_density_3d_outerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){\n memset(lsph->rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero\n\n #pragma omp parallel for // Execute the iteration in parallel\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // Iterate over each receiver cell begin index \n int64_t node_hash=-1,node_begin=0, node_end=0; // Start initializing the node indexes on the array \n int64_t nb_begin= 0, nb_end = 0; // initialize the neighbor indexes \n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; // prepare a list of potential neighbor hashes\n\n if (kh_exist(box->hbegin, kbegin)){ // verify if that given iterator actually exists\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // Then get the end of the receiver cell iterator\n\n node_hash = kh_key(box->hbegin, kbegin); // Then get the hash corresponding to it\n node_begin = kh_value(box->hbegin, kbegin); // Get the receiver cell begin index in the array\n node_end = kh_value(box->hend, kend); // Get the receiver cell end index in the array\n\n neighbour_hash_3d(node_hash,nblist,box->width,box); // then find the hashes of its neighbors \n for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and the iterate over them\n if(nblist[j]>=0){ // if a given neighbor actually has particles\n nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // then get the contributing cell begin index\n nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // and get the contributing cell end index \n\n compute_density_3d_chunk_noomp(node_begin,node_end,nb_begin,nb_end,h, // and compute the density contribution from \n lsph->x,lsph->y,lsph->z,lsph->nu,lsph->rho); // the contributing cell to the receiver cell\n }\n }\n }\n }\n\n return 0;\n}\n\n/*\n * Function compute_density_3d_chunk_noomp:\n * Computes the SPH density contribution for a pair of cells, from nb_ indexes\n * to the node_ indexes. No parallelization is performed with vectorization \n * performed in the inner loop.\n * \n * Arguments:\n * node_begin : Begin index of the receiver cell\n * node_end : End index of the receiver cell\n * nb_begin : Begin index of the sender (neighbor) cell\n * nb_end : End index of the sender (neighbor) cell\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * x : Array of particles' X positions\n * y : Array of particles' Y positions\n * z : Array of particles' Z positions\n * nu : Array of particles' density weights (i.e. masses)\n * Returns:\n * 0 : error code returned\n * rho : Array of particles' densities\n */\nint compute_density_3d_chunk_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;ii : Smoothing Length for the Smoothing Kernel w_bspline\n * Returns:\n * 3d bspline normalization density \n */\ndouble w_bspline_3d_constant(double h){ \n return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel\n}\n\n/*\n * Function w_bspline_3d_simd:\n * Returns the un-normalized value of the cubic b-spline SPH smoothing kernel\n * \n * Arguments:\n * q : Distance between particles normalized by the smoothing length h\n * Returns:\n * wq : Unnormalized value of the kernel\n * \n * Observation: \n * Why not else if(q<2.)? \n * Because if you use \"else if\", the compiler refuses to vectorize, \n * This results in a large slowdown, as of 2.5x slower for example_04\n */\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q){\n double wq=0;\n double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline\n double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline\n \n\n if(q<2.) // If the distance is below 2\n wq = wq2; // Use the 2nd polynomial for the spline\n \n if(q<1.) // If the distance is below 1\n wq = wq1; // Use the 1st polynomial for the spline\n\n return wq; // return which ever value corresponds to the distance\n}", "meta": {"hexsha": "8ad322d32feafff0e75aa34ddc00d60a491a02b5", "size": 18129, "ext": "c", "lang": "C", "max_stars_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c", "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c", "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoA/exec/example_08-StructOfArrays-CellLinkedList-OuterOmp.c", "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.6032171582, "max_line_length": 143, "alphanum_fraction": 0.5638479784, "num_tokens": 4320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.49270037511627734}} {"text": "/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. 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#ifndef SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n#define SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n\n#include \"./tensor_math.h\"\n#include \n#include \"singa/core/common.h\"\n#include \n\n#ifdef USE_CBLAS\n#include \n#endif\n\nnamespace singa {\n\ntemplate <>\nvoid Abs(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = fabs(inPtr[i]);\n }\n}\n\ntemplate <>\nvoid Add(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = inPtr[i] + x;\n }\n}\n\ntemplate <>\nvoid Add(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n // CHECK_EQ(ctx->stream, nullptr);\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = in1Ptr[i] + in2Ptr[i];\n }\n}\n\ntemplate <>\nvoid Clamp(const size_t num, const float low,\n const float high, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n if (inPtr[i] > high) {\n outPtr[i] = high;\n } else if (inPtr[i] < low) {\n outPtr[i] = low;\n } else {\n outPtr[i] = inPtr[i];\n }\n }\n}\n\ntemplate <>\nvoid Div(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n CHECK_NE(in2Ptr[i], 0.f);\n outPtr[i] = in1Ptr[i] / in2Ptr[i];\n }\n}\n\ntemplate <>\nvoid Div(const size_t num, const float x, const Block *in,\n Block *out, Context *ctx) {\n const float *inPtr = static_cast(in->data());\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) {\n CHECK_NE(inPtr[i], 0.f);\n outPtr[i] = x / inPtr[i];\n }\n}\n\ntemplate <>\nvoid EltwiseMult(const size_t num, const Block *in,\n const float x, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = inPtr[i] * x;\n }\n}\n\ntemplate <>\nvoid EltwiseMult(const size_t num, const Block *in1,\n const Block *in2, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = in1Ptr[i] * in2Ptr[i];\n }\n}\ntemplate <>\nvoid Exp(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = exp(inPtr[i]);\n }\n}\n\ntemplate <>\nvoid GE(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] >= x) ? 1.f : 0.f;\n }\n}\n\ntemplate <>\nvoid GE(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr1 = static_cast(in1->data());\n const float *inPtr2 = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr1[i] >= inPtr2[i]) ? 1.f : 0.f;\n }\n}\ntemplate <>\nvoid GT(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] > x) ? 1.f : 0.f;\n }\n}\ntemplate <>\nvoid GT(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr1 = static_cast(in1->data());\n const float *inPtr2 = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr1[i] > inPtr2[i]) ? 1.f : 0.f;\n }\n}\n\ntemplate <>\nvoid LE(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] <= x) ? 1.f : 0.f;\n }\n}\ntemplate <>\nvoid LE(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr1 = static_cast(in1->data());\n const float *inPtr2 = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr1[i] <= inPtr2[i]) ? 1.f : 0.f;\n }\n}\ntemplate <>\nvoid Log(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n CHECK_GT(inPtr[i], 0.f);\n outPtr[i] = log(inPtr[i]);\n }\n}\ntemplate <>\nvoid LT(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] < x) ? 1.f : 0.f;\n }\n}\ntemplate <>\nvoid LT(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr1 = static_cast(in1->data());\n const float *inPtr2 = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr1[i] < inPtr2[i]) ? 1.f : 0.f;\n }\n}\n\ntemplate <>\nvoid Pow(const size_t num, const Block *in, const float x,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = pow(inPtr[i], x);\n }\n}\n\ntemplate <>\nvoid Pow(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = pow(in1Ptr[i], in2Ptr[i]);\n }\n}\ntemplate <>\nvoid ReLU(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] >= 0.f) ? inPtr[i] : 0.f;\n }\n}\ntemplate <>\nvoid Set(const size_t num, const float x, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) outPtr[i] = x;\n}\ntemplate <>\nvoid Set(const size_t num, const int x, Block *out,\n Context *ctx) {\n int *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) outPtr[i] = x;\n}\n\ntemplate <>\nvoid Sigmoid(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = 1.f / (1.f + exp(-inPtr[i]));\n }\n}\n\ntemplate <>\nvoid Sign(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = (inPtr[i] > 0) - (inPtr[i] < 0);\n }\n}\n\ntemplate <>\nvoid Sqrt(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n CHECK_GE(inPtr[i], 0.f);\n outPtr[i] = sqrt(inPtr[i]);\n }\n}\n/*\ntemplate <>\nvoid Square(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = inPtr[i] * inPtr[i];\n }\n}\n*/\n\ntemplate <>\nvoid Sub(const size_t num, const Block *in1, const Block *in2,\n Block *out, Context *ctx) {\n // CHECK_EQ(ctx->stream, nullptr);\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = in1Ptr[i] - in2Ptr[i];\n }\n}\n\n// sum all elements of input into out\n// TODO(wangwei) optimize using omp\ntemplate <>\nvoid Sum(const size_t num, const Block *in, float *out,\n Context *ctx) {\n float s = 0.f;\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n s += inPtr[i];\n }\n *out = s;\n}\n\ntemplate <>\nvoid Tanh(const size_t num, const Block *in, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = tanh(inPtr[i]);\n }\n}\n\n// ===============Random operations==========================================\ntemplate <>\nvoid Bernoulli(const size_t num, const float p, Block *out,\n Context *ctx) {\n std::bernoulli_distribution distribution(p);\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = distribution(ctx->random_generator) ? 1.0f : 0.0f;\n }\n}\n\ntemplate <>\nvoid Gaussian(const size_t num, const float mean,\n const float std, Block *out, Context *ctx) {\n std::normal_distribution distribution(mean, std);\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = static_cast(distribution(ctx->random_generator));\n }\n}\ntemplate <>\nvoid Uniform(const size_t num, const float low,\n const float high, Block *out, Context *ctx) {\n std::uniform_real_distribution distribution(low, high);\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] = static_cast(distribution(ctx->random_generator));\n }\n}\n\n// ====================Blas operations======================================\n\ntemplate <>\nvoid DGMM(const bool side_right, const size_t nrow,\n const size_t ncol, const Block *M, const Block *v,\n Block *out, Context *ctx) {\n const float *MPtr = static_cast(M->data());\n const float *vPtr = static_cast(v->data());\n float *outPtr = static_cast(out->mutable_data());\n if (side_right) {\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[offset + c] = MPtr[offset + c] * vPtr[c];\n }\n }\n } else {\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[offset + c] = MPtr[offset + c] * vPtr[r];\n }\n }\n }\n}\n\n#ifdef USE_CBLAS\ntemplate <>\nvoid Amax(const size_t num, const Block *in, size_t *out,\n Context *ctx) {\n const float *inPtr = static_cast(in->data());\n *out = cblas_isamax(num, inPtr, 1);\n}\n\ntemplate <>\nvoid Asum(const size_t num, const Block *in, float *out,\n Context *ctx) {\n const float *inPtr = static_cast(in->data());\n *out = cblas_sasum(num, inPtr, 1);\n}\n\ntemplate <>\nvoid Axpy(const size_t num, const float alpha,\n const Block *in, Block *out, Context *ctx) {\n const float *inPtr = static_cast(in->data());\n float *outPtr = static_cast(out->mutable_data());\n cblas_saxpy(num, alpha, inPtr, 1, outPtr, 1);\n}\n\ntemplate <>\nvoid Dot(const size_t num, const Block *in1, const Block *in2,\n float *out, Context *ctx) {\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n *out = cblas_sdot(num, in1Ptr, 1, in2Ptr, 1);\n}\ntemplate <>\nvoid Scale(const size_t num, const float x, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n cblas_sscal(num, x, outPtr, 1);\n}\ntemplate <>\nvoid Nrm2(const size_t num, const Block *in, float *out,\n Context *ctx) {\n const float *inPtr = static_cast(in->data());\n *out = cblas_snrm2(num, inPtr, 1);\n}\n\ntemplate <>\nvoid GEMV(bool trans, const size_t m, const size_t n,\n const float alpha, const Block *A, const Block *v,\n const float beta, Block *out, Context *ctx) {\n const float *APtr = static_cast(A->data());\n const float *vPtr = static_cast(v->data());\n float *outPtr = static_cast(out->mutable_data());\n if (!trans) {\n cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, APtr, n, vPtr, 1,\n beta, outPtr, 1);\n } else {\n cblas_sgemv(CblasRowMajor, CblasTrans, n, m, alpha, APtr, m, vPtr, 1, beta,\n outPtr, 1);\n }\n}\n\ntemplate <>\nvoid GEMM(const bool transA, const bool transB,\n const size_t nrowA, const size_t ncolB,\n const size_t ncolA, const float alpha,\n const Block *A, const Block *B, const float beta,\n Block *C, Context *ctx) {\n auto transa = transA ? CblasTrans : CblasNoTrans;\n auto transb = transB ? CblasTrans : CblasNoTrans;\n auto lda = transA ? nrowA : ncolA;\n auto ldb = transB ? ncolA : ncolB;\n auto ldc = ncolB;\n const float *APtr = static_cast(A->data());\n const float *BPtr = static_cast(B->data());\n float *CPtr = static_cast(C->mutable_data());\n cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha, APtr,\n\t lda, BPtr, ldb, beta, CPtr, ldc);\n}\n\n#else\n\ntemplate <>\nvoid Amax(const size_t num, const Block *in, size_t *out,\n Context *ctx) {\n size_t maxPos = 0;\n float maxVal = 0;\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n if (i == 0) {\n maxVal = inPtr[i];\n } else if (inPtr[i] > maxVal) {\n maxVal = inPtr[i];\n maxPos = i;\n }\n }\n *out = maxPos;\n}\ntemplate <>\nvoid Amin(const size_t num, const Block *in, size_t *out,\n Context *ctx) {\n size_t minPos = 0;\n float minVal = 0;\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n if (i == 0) {\n minVal = inPtr[i];\n } else if (inPtr[i] > minVal) {\n minVal = inPtr[i];\n minPos = i;\n }\n }\n *out = minPos;\n}\n\ntemplate <>\nvoid Asum(const size_t num, const Block *in, float *out,\n Context *ctx) {\n float sum = 0;\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n sum += fabs(inPtr[i]);\n }\n}\n\ntemplate <>\nvoid Axpy(const size_t num, const float alpha,\n const Block *in, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] += alpha * inPtr[i];\n }\n}\n\ntemplate <>\nvoid Scale(const size_t num, const float x, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n for (size_t i = 0; i < num; i++) {\n outPtr[i] *= x;\n }\n}\n\ntemplate <>\nvoid Dot(const size_t num, const Block *in1, const Block *in2,\n float *out, Context *ctx) {\n float sum = 0;\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t i = 0; i < num; i++) {\n sum += in1Ptr[i] * in2Ptr[i];\n }\n}\n\ntemplate <>\nvoid GEMV(bool trans, const size_t m, const size_t n,\n const float alpha, const Block *A, const Block *v,\n const float beta, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *APtr = static_cast(A->data());\n const float *vPtr = static_cast(v->data());\n for (size_t r = 0; r < m; r++) {\n float sum = 0;\n for (size_t c = 0; c < n; c++) {\n size_t idx = trans ? c * m + r : r * n + c;\n sum += APtr[idx] * vPtr[c];\n }\n outPtr[r] = alpha * sum + beta * outPtr[r];\n }\n}\n\n#endif // USE_CBLAS\ntemplate <>\nvoid ComputeCrossEntropy(bool int_target,\n const size_t batchsize,\n const size_t dim, const Block *p,\n const Block *t, Block *loss,\n Context *ctx) {\n const float *pPtr = static_cast(p->data());\n const int *tPtr = static_cast(t->data());\n float *lossPtr = static_cast(loss->mutable_data());\n if (int_target) {\n for (size_t i = 0; i < batchsize; i++) {\n int truth_idx = tPtr[i];\n CHECK_GE(truth_idx, 0);\n float prob_of_truth = pPtr[i * dim + truth_idx];\n lossPtr[i] = -std::log((std::max)(prob_of_truth, FLT_MIN));\n }\n } else {\n for (size_t i = 0;i < batchsize; i++) {\n float sum = 0.f;\n for (size_t j = 0; j < dim; j++) {\n sum += tPtr[i * dim + j];\n }\n float loss = 0.f;\n for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {\n loss -= tPtr[offset] / sum * std::log((std::max)(pPtr[offset], FLT_MIN));\n }\n lossPtr[i] = loss;\n }\n }\n}\n\ntemplate <>\nvoid SoftmaxCrossEntropyBwd(bool int_target,\n const size_t batchsize,\n const size_t dim, const Block *p,\n const Block *t, Block *grad,\n Context *ctx) {\n CHECK_EQ(p, grad) << \"Use the same pointer to optimize performance\";\n // const float* pPtr = static_cast(p->data());\n const int *tPtr = static_cast(t->data());\n float *gradPtr = static_cast(grad->mutable_data());\n\n if (int_target) {\n for (size_t i = 0; i < batchsize; i++) {\n int truth_idx = static_cast(tPtr[i]);\n CHECK_GE(truth_idx, 0);\n gradPtr[i * dim + truth_idx] -= 1.0;\n }\n } else {\n for (size_t i = 0; i < batchsize; i++) {\n float sum = 0.f;\n for (size_t j = 0; j < dim; j++) {\n sum += tPtr[i * dim + j];\n }\n for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {\n gradPtr[offset] -= tPtr[offset] / sum;\n }\n }\n }\n}\n\ntemplate <>\nvoid RowMax(const size_t nrow, const size_t ncol,\n const Block *in, Block *out, Context *ctx) {\n const float *inPtr = static_cast(in->data());\n float *outPtr = static_cast(out->mutable_data());\n for (size_t r = 0; r < nrow; r++) {\n int offset = (int)(r * ncol);\n float maxval = inPtr[offset];\n for (size_t c = 1; c < ncol; c++)\n maxval = (std::max)(maxval, inPtr[offset + c]);\n outPtr[r] = maxval;\n }\n}\n\n// =========Matrix operations ================================================\n/*\ntemplate <>\nvoid AddCol(const size_t nrow, const size_t ncol,\n const Block *A, const Block *v, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *APtr = static_cast(A->data());\n const float *vPtr = static_cast(v->data());\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[offset + c] = APtr[offset + c] + vPtr[r];\n }\n }\n}\n\ntemplate <>\nvoid AddRow(const size_t nrow, const size_t ncol,\n const Block *A, const Block *v, Block *out,\n Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *APtr = static_cast(A->data());\n const float *vPtr = static_cast(v->data());\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[offset + c] = APtr[offset + c] + vPtr[c];\n }\n }\n}\ntemplate <>\nvoid Outer(const size_t m, const size_t n, const Block *in1,\n const Block *in2, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *in1Ptr = static_cast(in1->data());\n const float *in2Ptr = static_cast(in2->data());\n for (size_t r = 0; r < m; r++) {\n size_t offset = r * n;\n for (size_t c = 0; c < n; c++) {\n outPtr[offset + c] = in1Ptr[r] * in2Ptr[c];\n }\n }\n}\ntemplate <>\nvoid Softmax(const size_t nrow, const size_t ncol,\n const Block *in, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n float *bPtr = new float[ncol];\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n float denom = 0.f;\n for (size_t c = 0; c < ncol; c++) {\n bPtr[c] = exp(inPtr[offset + c]);\n denom += bPtr[c];\n }\n for (size_t c = 0; c < ncol; c++) {\n size_t idx = offset + c;\n outPtr[idx] = bPtr[c] / denom;\n }\n }\n delete bPtr;\n}\n\ntemplate <>\nvoid SumColumns(const size_t nrow, const size_t ncol,\n const Block *in, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t c = 0; c < ncol; c++) {\n outPtr[c] = 0.f;\n }\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[c] += inPtr[offset + c];\n }\n }\n}\n\ntemplate <>\nvoid SumRows(const size_t nrow, const size_t ncol,\n const Block *in, Block *out, Context *ctx) {\n float *outPtr = static_cast(out->mutable_data());\n const float *inPtr = static_cast(in->data());\n for (size_t r = 0; r < nrow; r++) {\n size_t offset = r * ncol;\n outPtr[r] = 0.f;\n for (size_t c = 0; c < ncol; c++) {\n outPtr[r] += inPtr[offset + c];\n }\n }\n}\n*/\n} // namespace singa\n\n#endif // SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_\n", "meta": {"hexsha": "4f510edbce1785e0dc5b280a3e38ddba6da54484", "size": 26520, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_stars_repo_name": "pavan87/Machine-learning", "max_stars_repo_head_hexsha": "e5c438c3410c714df3a9cdf4fd760676e5eeb721", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T23:28:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-04T23:28:33.000Z", "max_issues_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_issues_repo_name": "TsinghuaDatabaseGroup/incubator-singa", "max_issues_repo_head_hexsha": "b4ea650efb79584261e88e4ea8dd7b97fef7a758", "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/core/tensor/tensor_math_cpp.h", "max_forks_repo_name": "TsinghuaDatabaseGroup/incubator-singa", "max_forks_repo_head_hexsha": "b4ea650efb79584261e88e4ea8dd7b97fef7a758", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7894736842, "max_line_length": 81, "alphanum_fraction": 0.5664781297, "num_tokens": 7639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4925489917423555}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n//Threshold for testing validity of matrix matrix multiplication\n#define ERROR_THRESHOLD 0.0001\n\n//For measuring wall time using omp_get_wtime()\nstatic double start;\nstatic double end;\n\n//Serial version. Do not change this!\nvoid serial_mxm(const double *A, const double *B, double *C, int m, int n, int k)\n{\n clock_t start, end;\n start = clock();\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n C[i * n + j] = 0;\n for (int l = 0; l < k; l++)\n {\n C[i * n + j] += A[i * k + l] * B[l * n + j];\n }\n }\n }\n end = clock();\n printf(\"\\nUsage: %f\", (((double)end - (double)start) / (double)CLOCKS_PER_SEC));\n}\n\nvoid omp_mxm(double *A, double *B, double *C, int m, int n, int k)\n{\n clock_t start, end;\n start = clock();\n#pragma omp parallell for\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n C[i * n + j] = 0;\n for (int l = 0; l < k; l++)\n {\n C[i * n + j] += A[i * k + l] * B[l * n + j];\n }\n }\n }\n end = clock();\n printf(\"\\nUsage: %f\", (((double)end - (double)start) / (double)CLOCKS_PER_SEC));\n}\n\nvoid blas_mxm(double *A, double *B, double *C, int m, int n, int k)\n{\n clock_t start, end;\n start = clock();\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, A, k, B, n, 1.0, C, n);\n end = clock();\n printf(\"\\nUsage: %f\", (((double)end - (double)start) / (double)CLOCKS_PER_SEC));\n}\n\nint main(const unsigned int argc, char **argv)\n{\n if (argc <= optind)\n {\n printf(\"Please provide version:\\n\");\n printf(\"\\ts(serial),\\n\");\n printf(\"\\to(penmp) or\\n\");\n printf(\"\\tb(las)\\n\");\n return 0;\n }\n char input = argv[optind][0];\n optind++;\n //Simple assumptions that any additional arguments means we want to test the results\n bool test = !(argc <= optind);\n\n int m = 2000;\n int n = 1000;\n int k = 200;\n\n double *A = (double *)malloc(m * k * sizeof(double));\n double *B = (double *)malloc(k * n * sizeof(double));\n double *C = (double *)malloc(m * n * sizeof(double));\n\n //Intializing matrix data\n for (int i = 0; i < (m * k); i++)\n {\n A[i] = (double)(i + 1);\n }\n\n for (int i = 0; i < (k * n); i++)\n {\n B[i] = (double)(-i - 1);\n }\n\n for (int i = 0; i < (m * n); i++)\n {\n C[i] = 0.0;\n }\n switch (input)\n {\n case 's':\n serial_mxm(A, B, C, m, n, k);\n break;\n case 'o':\n omp_mxm(A, B, C, m, n, k);\n break;\n case 'b':\n blas_mxm(A, B, C, m, n, k);\n break;\n default:\n printf(\"Please provide version:\\n\");\n printf(\"\\ts(serial),\\n\");\n printf(\"\\to(penmp) or\\n\");\n printf(\"\\tb(las)\\n\");\n return 0;\n }\n\n printf(\"\\nTop left of A:\\n\");\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n printf(\"%8.2f\\t\", A[i * k + j]);\n }\n printf(\"\\n\");\n }\n\n printf(\"\\nTop left of B:\\n\");\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n printf(\"%8.2f\\t\", B[i * n + j]);\n }\n printf(\"\\n\");\n }\n\n printf(\"\\nTop left of C:\\n\");\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n printf(\"%8.2f\\t\", C[i * n + j]);\n }\n printf(\"\\n\");\n }\n\n if (test)\n {\n double *C2 = (double *)malloc(m * n * sizeof(double));\n serial_mxm(A, B, C2, m, n, k);\n bool correct = true;\n for (int i = 0; i < (m * n); i++)\n {\n if (abs(C[i] - C2[i]) > ERROR_THRESHOLD)\n {\n correct = false;\n }\n }\n if (correct)\n {\n printf(\"\\nMatrix multiplication succeeded\\n\");\n }\n else\n {\n printf(\"\\nMatrix multiplication failed\\n\");\n printf(\"Top left of correct C:\\n\");\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n printf(\"%8.2f\\t\", C2[i * n + j]);\n }\n printf(\"\\n\");\n }\n }\n }\n\n printf(\"\\nVersion: %c, time: %.4f\\n\", input, end - start);\n\n return 0;\n}\n", "meta": {"hexsha": "e7110747fe6664feb2f7bd24507a09326560e607", "size": 3993, "ext": "c", "lang": "C", "max_stars_repo_path": "Assignment5/openmp/main.c", "max_stars_repo_name": "andham97/TDT4200", "max_stars_repo_head_hexsha": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "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": "Assignment5/openmp/main.c", "max_issues_repo_name": "andham97/TDT4200", "max_issues_repo_head_hexsha": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "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": "Assignment5/openmp/main.c", "max_forks_repo_name": "andham97/TDT4200", "max_forks_repo_head_hexsha": "f11a2ce557c56b1a0e0641a77ae5155af13c2fe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2393617021, "max_line_length": 94, "alphanum_fraction": 0.4953668921, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.49171753888722186}} {"text": "/* specfunc/hyperg.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/* Miscellaneous implementations of use\n * for evaluation of hypergeometric functions.\n */\n#ifndef _HYPERG_H_\n#define _HYPERG_H_\n\n#include \n\n\n/* Direct implementation of 1F1 series.\n */\nint\ngsl_sf_hyperg_1F1_series_e(const double a, const double b, const double x, gsl_sf_result * result);\n\n\n/* Implementation of the 1F1 related to the\n * incomplete gamma function: 1F1(1,b,x), b >= 1.\n */\nint\ngsl_sf_hyperg_1F1_1_e(double b, double x, gsl_sf_result * result);\n\n\n/* 1F1(1,b,x) for integer b >= 1\n */\nint\ngsl_sf_hyperg_1F1_1_int_e(int b, double x, gsl_sf_result * result);\n\n\n/* Implementation of large b asymptotic.\n * [Bateman v. I, 6.13.3 (18)]\n * [Luke, The Special Functions and Their Approximations v. I, p. 129, 4.8 (4)]\n *\n * a^2 << b, |x|/|b| < 1 - delta\n */\nint\ngsl_sf_hyperg_1F1_large_b_e(const double a, const double b, const double x, gsl_sf_result * result);\n\n\n/* Implementation of large b asymptotic.\n *\n * Assumes a > 0 is small, x > 0, and |x|<|b|.\n */\nint\ngsl_sf_hyperg_U_large_b_e(const double a, const double b, const double x,\n gsl_sf_result * result,\n double * ln_multiplier\n );\n\n\n/* Implementation of 2F0 asymptotic series.\n */\nint\ngsl_sf_hyperg_2F0_series_e(const double a, const double b, const double x, int n_trunc,\n gsl_sf_result * result);\n\n\n#endif /* !_HYPERG_H_ */\n", "meta": {"hexsha": "37d11b046509880969de3b6bd8b807cf1c37f310", "size": 2270, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/hyperg.h", "max_stars_repo_name": "vinej/sml", "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "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/hyperg.h", "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/hyperg.h", "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": 28.7341772152, "max_line_length": 100, "alphanum_fraction": 0.6841409692, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.49170070632819374}} {"text": "/*\n * SpecialFunctions.h\n * PSCAcoustic\n *\n * Special functions and more.\n *\n *\n * Copyright 2014 Pierre-David Letourneau\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n*/\n\n\n#ifndef SPECIALFUNCTIONS_H\n#define SPECIALFUNCTIONS_H\n\n#include \"General.h\"\n\n// GSL library\n//#include \"../gsl-1.16/include/gsl/gsl_sf_bessel.h\" //spherical bessel functions\n#include //spherical bessel functions\n#include \"./gsl-1.16/include/gsl/gsl_sf_legendre.h\" //associated Legendre polynomials (for spherical harmonics)\n#include \"./gsl-1.16/include/gsl/gsl_complex_math.h\"\n#include \"./gsl-1.16/include/gsl/gsl_sf_gamma.h\"\n#include \"./gsl-1.16/include/gsl/gsl_sf_hyperg.h\"\n#include \"./gsl-1.16/include/gsl/gsl_sf_coupling.h\"\n#include \"./gsl-1.16/include/gsl/gsl_integration.h\"\n#include \"./gsl-1.16/include/gsl/gsl_complex.h\"\n#include \"./gsl-1.16/include/gsl/gsl_sf_coupling.h\"\n#include \"./gsl-1.16/include/gsl/gsl_math.h\"\n#include \"./gsl-1.16/include/gsl/gsl_ieee_utils.h\"\n#include \"./gsl-1.16/include/gsl/gsl_errno.h\"\n#include \"./gsl-1.16/include/gsl/gsl_integration.h\"\n\n// Complex Bessel functions\n//#include \"../AmosBessel/libAmosBessel.h\"\n\n\n//GSL wrappers (Cannot handle complex arguments)\n\n//Hankel function of the 1st kind (gsl)\ninline complex gsl_sf_hankel_1( int l, double x){\n return gsl_sf_bessel_jl(l,x) + gsl_sf_bessel_yl(l,x) * CI;\n}\n\ninline double gsl_sf_legendre( int l, int m, double x){\n double C = 1;\n if( m < 0 )\n C *= pow(-1, std::abs(m));\n\n return (C * gsl_sf_legendre_sphPlm ( l, std::abs(m), x) );\n}\n\n\n// Y_lm (spherical harmonics) \n//\\sqrt{(2l+1)/(4\\pi)} \\sqrt{(l-m)!/(l+m)!} P_l^m(x) exp(I*m*phi) )\ninline complex gsl_sf_harmonic( int l, int m, double theta, double phi){\n if( l >= std::abs(m) ){\n return gsl_sf_legendre(l, m, cos(theta)) * exp(m*phi*CI);\n } else {\n return 0.;\n }\n}\n\ninline complex gsl_sf_clebsch(int l1, int l2, int l3, int m1, int m2, int m3){\n return pow(-1., (double) l1-l2+m3) * sqrt(2.*l3+1.) * gsl_sf_coupling_3j(2*l1, 2*l2, 2*l3, 2*m1, 2*m2, -2*m3);\n}\n\ninline double gsl_sf_gaunt(int n, int m, int nu, int mu, int q){\n return pow(-1., (double) (m+mu) ) * sqrt((2*n+1)*(2*nu+1)*(2*q+1)/(4*PI)) * \n gsl_sf_coupling_3j(2.*n,2.*nu,2.*q,0,0,0) * gsl_sf_coupling_3j(2.*n,2.*nu,2.*q,2.*m,2.*mu,-2.*(m+mu));\n}\n\n\n// TODO: FIX AMOS\n//Amos wrappers for Bessel functions (these can handle complex arguments)\ninline complex Amos_sf_bessel_jl(int l, complex z){\n \tcomplex value;\n\t//AmosBessel('j', z, (double) l, 1, 0, &value);\n\tvalue = gsl_sf_bessel_jl(l,std::real(z));\n\treturn value;\n}\n\ninline complex Amos_sf_bessel_yl(int l, complex z){\n \tcomplex value;\n\t//AmosBessel('y', z, (double) l, 1, 0, &value);\n\tvalue = gsl_sf_bessel_yl(l,std::real(z));\n\treturn value;\n}\n\n\ninline complex Amos_sf_hankel_1(int l, complex z){\n //complex valueR;\n\t//AmosBessel('j', z, (double) l, 1, 0, &valueR);\n \t//complex valueI;\n\t//AmosBessel('y', z, (double) l, 1, 0, &valueI);\n\t//return (valueR + valueI*CI);\n\n\tcomplex value = gsl_sf_hankel_1(l, std::real(z));\n\treturn value;\n}\n\n\n// Derivatives\n\ninline double gsl_sf_bessel_jl_prime(int l, double z){\n return l/z * gsl_sf_bessel_jl(l,z) - gsl_sf_bessel_jl(l+1,z);\n}\n\ninline complex gsl_sf_hankel_l_prime(int l, double z){\n return l/z * gsl_sf_hankel_1( l, z) - gsl_sf_hankel_1(l+1, z);\n}\n\ninline complex Amos_sf_bessel_jl_prime(double l, complex z){\n return l/z * Amos_sf_bessel_jl(l,z) - Amos_sf_bessel_jl(l+1,z);\n}\n\ninline complex Amos_sf_hankel_l_prime(double l, complex z){\n return l/z * Amos_sf_hankel_1( l, z) - Amos_sf_hankel_1(l+1, z);\n}\n\n\n\n\n// Chebyshev polynomial evaluation\ninline double Cheb(int n, double x){\n return cos(n*acos(x));\n}\n\n\n\n\n\n\n\n// Gauss-Legendre quadrature\ninline void getGaussLegendreQuad(int N, std::vector& x, std::vector& w)\n{\n x.resize(N);\n w.resize(N);\n\n gsl_integration_glfixed_table* GLTable = gsl_integration_glfixed_table_alloc(N);\n \n for( int n = 0; n < (N+1)/2; ++n ) {\n x[n + N/2] = GLTable->x[n];\n w[n + N/2] = GLTable->w[n];\n }\n for( int n = 0; n < N/2; ++n ) {\n x[n] = -x[N-1-n];\n w[n] = w[N-1-n];\n }\n \n gsl_integration_glfixed_table_free( GLTable );\n}\n\n// Gauss-Chebyshev quadrature\ninline void getGaussChebyshevQuad(int N, std::vector& x, std::vector& w)\n{\n x.resize(N);\n w.resize(N);\n\n for( int n = 0; n < N; n++ ) {\n x[n] = cos( (2.*n+1.)/(2.*N)*PI );\n w[n] = 2./N;\n }\n}\n\n\n\n\n//---------General Functions--------//\n\n#define ISODD(x) ((x) & 1)\n#define ISNAN(x) ((x) != (x))\n\n\n\n\n//TODO : still needed?\ninline int choose( int n, int r ){\n \n if( (n < r) || (r < 0) || (n < 0) ){\n return 0;\n } else {\n return gsl_sf_gamma(n+1) / (gsl_sf_gamma(r+1) * gsl_sf_gamma(n-r+1));\n }\n \n}\n\n\n\n\n\n\n// Implementation os Sparse Matrix class\n// TODO: this takes a lot of memory?\nclass SpMatrix\n{\n map, complex > M;\n\n public:\n\n // Empty constructor\n SpMatrix(){}\n\n ~SpMatrix(){}\n\n void add(int i, int j, complex val){\n assert( i >= 0 );\n assert( j >= 0 );\n\n std::pair coord = std::make_pair(i,j);\n if( M.count(coord) ){\n M.insert(std::make_pair(coord, val));\n } else {\n M[coord] = val;\n }\n\n }\n\n\n \n complex operator () (int i, int j){\n std::pair coord = std::make_pair(i,j);\n complex val = 0.;\n\n ( M.count(coord) ) ? val = M.find(coord)->second : val = 0.;\n \n return val;\n }\n\n inline int size() { return M.size(); }\n\n};\n\n\n\n\n#endif\n\n", "meta": {"hexsha": "4e671062372e718e25b9efaefecc5d44f10225ce", "size": 6475, "ext": "h", "lang": "C", "max_stars_repo_path": "SpecialFunctions.h", "max_stars_repo_name": "pl2526/PSCAcoustic", "max_stars_repo_head_hexsha": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "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": "SpecialFunctions.h", "max_issues_repo_name": "pl2526/PSCAcoustic", "max_issues_repo_head_hexsha": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "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": "SpecialFunctions.h", "max_forks_repo_name": "pl2526/PSCAcoustic", "max_forks_repo_head_hexsha": "eaf127f0bd6aa9bdf4a051b4390966e86fdf6751", "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.1945525292, "max_line_length": 112, "alphanum_fraction": 0.6563706564, "num_tokens": 2130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.49170068278657403}} {"text": "/* linalg/sytd.c\n * \n * Copyright (C) 2001, 2007 Brian Gough\n * Copyright (C) 2019 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Factorise a symmetric matrix A into\n *\n * A = Q T Q'\n *\n * where Q is orthogonal and T is symmetric tridiagonal. Only the\n * diagonal and lower triangular part of A is referenced and modified.\n *\n * On exit, T is stored in the diagonal and first subdiagonal of\n * A. Since T is symmetric the upper diagonal is not stored.\n *\n * Q is stored as a packed set of Householder transformations in the\n * lower triangular part of the input matrix below the first subdiagonal.\n *\n * The full matrix for Q can be obtained as the product\n *\n * Q = Q_1 Q_2 ... Q_(N-2)\n *\n * where \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 = [0, ... , 0, 1, A(i+1,i), A(i+2,i), ... , A(N,i)]\n *\n * This storage scheme is the same as in LAPACK. See LAPACK's\n * ssytd2.f for details.\n *\n * See Golub & Van Loan, \"Matrix Computations\" (3rd ed), Section 8.3 \n *\n * Note: this description uses 1-based indices. The code below uses\n * 0-based indices \n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint \ngsl_linalg_symmtd_decomp (gsl_matrix * A, gsl_vector * tau) \n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"symmetric tridiagonal decomposition requires square matrix\",\n GSL_ENOTSQR);\n }\n else if (tau->size + 1 != A->size1)\n {\n GSL_ERROR (\"size of tau must be N-1\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n size_t i;\n \n for (i = 0 ; i < N - 2; i++)\n {\n gsl_vector_view v = gsl_matrix_subcolumn (A, i, i + 1, N - i - 1);\n double tau_i = gsl_linalg_householder_transform (&v.vector);\n \n /* Apply the transformation H^T A H to the remaining columns */\n\n if (tau_i != 0.0) \n {\n gsl_matrix_view m = gsl_matrix_submatrix (A, i + 1, i + 1, N - i - 1, N - i - 1);\n double ei = gsl_vector_get(&v.vector, 0);\n gsl_vector_view x = gsl_vector_subvector (tau, i, N - i - 1);\n\n gsl_vector_set (&v.vector, 0, 1.0);\n \n /* x = tau * A * v */\n gsl_blas_dsymv (CblasLower, tau_i, &m.matrix, &v.vector, 0.0, &x.vector);\n\n /* w = x - (1/2) tau * (x' * v) * v */\n {\n double xv, alpha;\n gsl_blas_ddot(&x.vector, &v.vector, &xv);\n alpha = -0.5 * tau_i * xv;\n gsl_blas_daxpy(alpha, &v.vector, &x.vector);\n }\n \n /* apply the transformation A = A - v w' - w v' */\n gsl_blas_dsyr2(CblasLower, -1.0, &v.vector, &x.vector, &m.matrix);\n\n gsl_vector_set (&v.vector, 0, ei);\n }\n \n gsl_vector_set (tau, i, tau_i);\n }\n \n return GSL_SUCCESS;\n }\n} \n\n\n/* Form the orthogonal matrix Q from the packed QR matrix */\n\nint\ngsl_linalg_symmtd_unpack (const gsl_matrix * A, \n const gsl_vector * tau,\n gsl_matrix * Q, \n gsl_vector * diag, \n gsl_vector * sdiag)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix A must be square\", GSL_ENOTSQR);\n }\n else if (tau->size + 1 != A->size1)\n {\n GSL_ERROR (\"size of tau must be (matrix size - 1)\", GSL_EBADLEN);\n }\n else if (Q->size1 != A->size1 || Q->size2 != A->size1)\n {\n GSL_ERROR (\"size of Q must match size of A\", GSL_EBADLEN);\n }\n else if (diag->size != A->size1)\n {\n GSL_ERROR (\"size of diagonal must match size of A\", GSL_EBADLEN);\n }\n else if (sdiag->size + 1 != A->size1)\n {\n GSL_ERROR (\"size of subdiagonal must be (matrix size - 1)\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n gsl_vector_const_view d = gsl_matrix_const_diagonal(A);;\n gsl_vector_const_view sd = gsl_matrix_const_subdiagonal(A, 1);;\n size_t i;\n\n /* Initialize Q to the identity */\n\n gsl_matrix_set_identity (Q);\n\n for (i = N - 2; i-- > 0;)\n {\n gsl_vector_const_view h = gsl_matrix_const_subcolumn (A, i, i + 1, N - i - 1);\n double ti = gsl_vector_get (tau, i);\n gsl_matrix_view m = gsl_matrix_submatrix (Q, i + 1, i + 1, N - i - 1, N - i - 1);\n gsl_vector_view work = gsl_vector_subvector(diag, 0, N - i - 1);\n\n gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector);\n }\n\n /* copy diagonal into diag */\n gsl_vector_memcpy(diag, &d.vector);\n\n /* copy subdiagonal into sd */\n gsl_vector_memcpy(sdiag, &sd.vector);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_symmtd_unpack_T (const gsl_matrix * A, \n gsl_vector * diag, \n gsl_vector * sdiag)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix A must be square\", GSL_ENOTSQR);\n }\n else if (diag->size != A->size1)\n {\n GSL_ERROR (\"size of diagonal must match size of A\", GSL_EBADLEN);\n }\n else if (sdiag->size + 1 != A->size1)\n {\n GSL_ERROR (\"size of subdiagonal must be (matrix size - 1)\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n gsl_vector_const_view d = gsl_matrix_const_diagonal(A);;\n gsl_vector_const_view sd = gsl_matrix_const_subdiagonal(A, 1);;\n\n /* copy diagonal into diag */\n gsl_vector_memcpy(diag, &d.vector);\n\n /* copy subdiagonal into sd */\n gsl_vector_memcpy(sdiag, &sd.vector);\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "b10d4db57d505bdb83c788e5225c53de6f407272", "size": 6441, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/symmtd.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "gsl-2.6/linalg/symmtd.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/symmtd.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "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.2394366197, "max_line_length": 95, "alphanum_fraction": 0.5789473684, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.49121972795567026}} {"text": "/* multimin/diff.c\n * \n * Copyright (C) 2000 David Morrison\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\nint\ngsl_multimin_diff (const gsl_multimin_function * f,\n const gsl_vector * x, gsl_vector * g)\n{\n size_t i, n = f->n;\n\n double h = GSL_SQRT_DBL_EPSILON;\n\n\n gsl_vector * x1 = gsl_vector_alloc (n); /* FIXME: pass as argument */\n\n gsl_vector_memcpy (x1, x);\n\n for (i = 0; i < n; i++)\n {\n double fl, fh;\n \n double xi = gsl_vector_get (x, i);\n double dx = fabs(xi) * h;\n\n if (dx == 0.0) dx = h;\n\n gsl_vector_set (x1, i, xi + dx);\n fh = GSL_MULTIMIN_FN_EVAL(f, x1);\n\n gsl_vector_set (x1, i, xi - dx);\n fl = GSL_MULTIMIN_FN_EVAL(f, x1);\n\n gsl_vector_set (x1, i, xi);\n gsl_vector_set (g, i, (fh - fl) / (2.0 * dx));\n }\n\n gsl_vector_free (x1);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "f6937245206c3ee9768445df93e6b6293fbab307", "size": 1582, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multimin/diff.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/multimin/diff.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/multimin/diff.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.813559322, "max_line_length": 81, "alphanum_fraction": 0.6536030341, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.4910380573602375}} {"text": "/*\n * Kabsch's algorithm: compute least-square-best transformation\n * Copyright (C) 2003, Arno Formella (formella@ei.uvigo.es)\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 * This is a gsl-based implementation of Kabsch's algorithm presented in:\n *\n * W. Kabsch, A solution for the best rotation to relate two sets of vectors,\n * Acta Cryst. (1976), A32, 922-923\n *\n * W. Kabsch, A discussion of the solution for the best rotation to relate\n * two sets of vectors, Acta Cryst. (1978), A34, 827-828\n *\n * The code is C++-robust.\n *\n * More information about GSL\n * ==========================\n *\n * The project homepage is http://www.gnu.org/software/gsl/\n * The development site is http://sources.redhat.com/gsl/\n */\n\n#ifndef KABSCH_H\n#define KABSCH_H\n\n#include \n#include \n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n/*\n preconditions:\n size > 0\n X and Y point to (size x 3)-matrices specifying 3D points x_i and y_i\n U points to a (3 x 3)-matrix\n t points to a (3)-vector\n s points to double\n postconditions if return 1:\n X and Y will be centralized at their respective origins\n U will hold the rotation\n t will hold the translation\n s will hold the scaling value\n such that:\n sum_i (U * s * x_i + t - y_i)^2 is minimal\n postconditions if return 0:\n X and Y will be centralized at their respective origins\n U will hold the identity\n t will hold the difference vector of the centroids t = cy -cx\n s will hold 1.0\n note:\n if s == NULL, no scaling is computed\n*/\nint kabsch(\n unsigned int size,\n gsl_matrix *X,\n gsl_matrix *Y,\n gsl_matrix *U,\n gsl_vector *t,\n double *s\n);\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "3220d18d336d58b95c951f767f4584b3639f25c4", "size": 2217, "ext": "h", "lang": "C", "max_stars_repo_path": "bin/EvoDesignX/src/kabsch.h", "max_stars_repo_name": "robpearc/FoldDesign", "max_stars_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bin/EvoDesignX/src/kabsch.h", "max_issues_repo_name": "robpearc/FoldDesign", "max_issues_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bin/EvoDesignX/src/kabsch.h", "max_forks_repo_name": "robpearc/FoldDesign", "max_forks_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4230769231, "max_line_length": 79, "alphanum_fraction": 0.6878664862, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4910326844255042}} {"text": "/* bspline/bspline.c\n *\n * Copyright (C) 2006, 2007, 2008, 2009 Patrick Alken\n * Copyright (C) 2008 Rhys Ulerich\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n\n/*\n * This module contains routines related to calculating B-splines.\n * The algorithms used are described in\n *\n * [1] Carl de Boor, \"A Practical Guide to Splines\", Springer\n * Verlag, 1978.\n *\n * The bspline_pppack_* internal routines contain code adapted from\n *\n * [2] \"PPPACK - Piecewise Polynomial Package\",\n * http://www.netlib.org/pppack/\n *\n */\n\n#include \"bspline.h\"\n\n/*\ngsl_bspline_alloc()\n Allocate space for a bspline workspace. The size of the\nworkspace is O(5k + nbreak)\n\nInputs: k - spline order (cubic = 4)\n nbreak - number of breakpoints\n\nReturn: pointer to workspace\n*/\n\ngsl_bspline_workspace *\ngsl_bspline_alloc (const size_t k, const size_t nbreak)\n{\n if (k == 0)\n {\n GSL_ERROR_NULL (\"k must be at least 1\", GSL_EINVAL);\n }\n else if (nbreak < 2)\n {\n GSL_ERROR_NULL (\"nbreak must be at least 2\", GSL_EINVAL);\n }\n else\n {\n gsl_bspline_workspace *w;\n\n w = (gsl_bspline_workspace *) malloc (sizeof (gsl_bspline_workspace));\n\n if (w == 0)\n\t{\n\t GSL_ERROR_NULL (\"failed to allocate space for workspace\",\n\t\t\t GSL_ENOMEM);\n\t}\n\n w->k = k;\n w->km1 = k - 1;\n w->nbreak = nbreak;\n w->l = nbreak - 1;\n w->n = w->l + k - 1;\n\n w->knots = gsl_vector_alloc (w->n + k);\n if (w->knots == 0)\n\t{\n\t free (w);\n\t GSL_ERROR_NULL (\"failed to allocate space for knots vector\",\n\t\t\t GSL_ENOMEM);\n\t}\n\n w->deltal = gsl_vector_alloc (k);\n if (w->deltal == 0)\n\t{\n\t gsl_vector_free (w->knots);\n\t free (w);\n\t GSL_ERROR_NULL (\"failed to allocate space for deltal vector\",\n\t\t\t GSL_ENOMEM);\n\t}\n\n w->deltar = gsl_vector_alloc (k);\n if (w->deltar == 0)\n\t{\n\t gsl_vector_free (w->deltal);\n\t gsl_vector_free (w->knots);\n\t free (w);\n\t GSL_ERROR_NULL (\"failed to allocate space for deltar vector\",\n\t\t\t GSL_ENOMEM);\n\t}\n\n\n w->B = gsl_vector_alloc (k);\n if (w->B == 0)\n\t{\n\t gsl_vector_free (w->deltar);;\n\t gsl_vector_free (w->deltal);\n\t gsl_vector_free (w->knots);\n\t free (w);\n\t GSL_ERROR_NULL\n\t (\"failed to allocate space for temporary spline vector\",\n\t GSL_ENOMEM);\n\t}\n\n return w;\n }\n}\t\t\t\t/* gsl_bspline_alloc() */\n\n/*\ngsl_bspline_deriv_alloc()\n Allocate space for a bspline derivative workspace. The size of the\nworkspace is O(2k^2)\n\nInputs: k - spline order (cubic = 4)\n\nReturn: pointer to workspace\n*/\n\ngsl_bspline_deriv_workspace *\ngsl_bspline_deriv_alloc (const size_t k)\n{\n if (k == 0)\n {\n GSL_ERROR_NULL (\"k must be at least 1\", GSL_EINVAL);\n }\n else\n {\n gsl_bspline_deriv_workspace *dw;\n\n dw =\n\t(gsl_bspline_deriv_workspace *)\n\tmalloc (sizeof (gsl_bspline_deriv_workspace));\n\n if (dw == 0)\n\t{\n\t GSL_ERROR_NULL (\"failed to allocate space for workspace\",\n\t\t\t GSL_ENOMEM);\n\t}\n\n dw->A = gsl_matrix_alloc (k, k);\n if (dw->A == 0)\n\t{\n\t free (dw);\n\t GSL_ERROR_NULL\n\t (\"failed to allocate space for derivative work matrix\",\n\t GSL_ENOMEM);\n\t}\n\n dw->dB = gsl_matrix_alloc (k, k + 1);\n if (dw->dB == 0)\n\t{\n\t gsl_matrix_free (dw->A);\n\t free (dw);\n\t GSL_ERROR_NULL\n\t (\"failed to allocate space for temporary derivative matrix\",\n\t GSL_ENOMEM);\n\t}\n\n dw->k = k;\n\n return dw;\n }\n}\t\t\t\t/* gsl_bspline_deriv_alloc() */\n\n/* Return number of coefficients */\nsize_t\ngsl_bspline_ncoeffs (gsl_bspline_workspace * w)\n{\n return w->n;\n}\n\n/* Return order */\nsize_t\ngsl_bspline_order (gsl_bspline_workspace * w)\n{\n return w->k;\n}\n\n/* Return number of breakpoints */\nsize_t\ngsl_bspline_nbreak (gsl_bspline_workspace * w)\n{\n return w->nbreak;\n}\n\n/* Return the location of the i-th breakpoint*/\ndouble\ngsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w)\n{\n size_t j = i + w->k - 1;\n return gsl_vector_get (w->knots, j);\n}\n\n/*\ngsl_bspline_free()\n Free a gsl_bspline_workspace.\n\nInputs: w - workspace to free\n\nReturn: none\n*/\n\nvoid\ngsl_bspline_free (gsl_bspline_workspace * w)\n{\n RETURN_IF_NULL (w);\n gsl_vector_free (w->knots);\n gsl_vector_free (w->deltal);\n gsl_vector_free (w->deltar);\n gsl_vector_free (w->B);\n free (w);\n}\t\t\t\t/* gsl_bspline_free() */\n\n/*\ngsl_bspline_deriv_free()\n Free a gsl_bspline_deriv_workspace.\n\nInputs: dw - workspace to free\n\nReturn: none\n*/\n\nvoid\ngsl_bspline_deriv_free (gsl_bspline_deriv_workspace * dw)\n{\n RETURN_IF_NULL (dw);\n gsl_matrix_free (dw->A);\n gsl_matrix_free (dw->dB);\n free (dw);\n}\t\t\t\t/* gsl_bspline_deriv_free() */\n\n/*\ngsl_bspline_knots()\n Compute the knots from the given breakpoints:\n\n knots(1:k) = breakpts(1)\n knots(k+1:k+l-1) = breakpts(i), i = 2 .. l\n knots(n+1:n+k) = breakpts(l + 1)\n\nwhere l is the number of polynomial pieces (l = nbreak - 1) and\n n = k + l - 1\n(using matlab syntax for the arrays)\n\nThe repeated knots at the beginning and end of the interval\ncorrespond to the continuity condition there. See pg. 119\nof [1].\n\nInputs: breakpts - breakpoints\n w - bspline workspace\n\nReturn: success or error\n*/\n\nint\ngsl_bspline_knots (const gsl_vector * breakpts, gsl_bspline_workspace * w)\n{\n if (breakpts->size != w->nbreak)\n {\n GSL_ERROR (\"breakpts vector has wrong size\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\t\t\t/* looping */\n\n for (i = 0; i < w->k; i++)\n\tgsl_vector_set (w->knots, i, gsl_vector_get (breakpts, 0));\n\n for (i = 1; i < w->l; i++)\n\t{\n\t gsl_vector_set (w->knots, w->k - 1 + i,\n\t\t\t gsl_vector_get (breakpts, i));\n\t}\n\n for (i = w->n; i < w->n + w->k; i++)\n\tgsl_vector_set (w->knots, i, gsl_vector_get (breakpts, w->l));\n\n return GSL_SUCCESS;\n }\n}\t\t\t\t/* gsl_bspline_knots() */\n\n/*\ngsl_bspline_knots_uniform()\n Construct uniformly spaced knots on the interval [a,b] using\nthe previously specified number of breakpoints. 'a' is the position\nof the first breakpoint and 'b' is the position of the last\nbreakpoint.\n\nInputs: a - left side of interval\n b - right side of interval\n w - bspline workspace\n\nReturn: success or error\n\nNotes: 1) w->knots is modified to contain the uniformly spaced\n knots\n\n 2) The knots vector is set up as follows (using octave syntax):\n\n knots(1:k) = a\n knots(k+1:k+l-1) = a + i*delta, i = 1 .. l - 1\n knots(n+1:n+k) = b\n*/\n\nint\ngsl_bspline_knots_uniform (const double a, const double b,\n\t\t\t gsl_bspline_workspace * w)\n{\n size_t i;\t\t\t/* looping */\n double delta;\t\t\t/* interval spacing */\n double x;\n\n delta = (b - a) / (double) w->l;\n\n for (i = 0; i < w->k; i++)\n gsl_vector_set (w->knots, i, a);\n\n x = a + delta;\n for (i = 0; i < w->l - 1; i++)\n {\n gsl_vector_set (w->knots, w->k + i, x);\n x += delta;\n }\n\n for (i = w->n; i < w->n + w->k; i++)\n gsl_vector_set (w->knots, i, b);\n\n return GSL_SUCCESS;\n}\t\t\t\t/* gsl_bspline_knots_uniform() */\n\n/*\ngsl_bspline_eval()\n Evaluate the basis functions B_i(x) for all i. This is\na wrapper function for gsl_bspline_eval_nonzero() which\nformats the output in a nice way.\n\nInputs: x - point for evaluation\n B - (output) where to store B_i(x) values\n the length of this vector is\n n = nbreak + k - 2 = l + k - 1 = w->n\n w - bspline workspace\n\nReturn: success or error\n\nNotes: The w->knots vector must be initialized prior to calling\n this function (see gsl_bspline_knots())\n*/\n\nint\ngsl_bspline_eval (const double x, gsl_vector * B, gsl_bspline_workspace * w)\n{\n if (B->size != w->n)\n {\n GSL_ERROR (\"vector B not of length n\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\t\t\t/* looping */\n size_t istart;\t\t/* first non-zero spline for x */\n size_t iend;\t\t/* last non-zero spline for x, knot for x */\n int error;\t\t/* error handling */\n\n /* find all non-zero B_i(x) values */\n error = gsl_bspline_eval_nonzero (x, w->B, &istart, &iend, w);\n if (error)\n\t{\n\t return error;\n\t}\n\n /* store values in appropriate part of given vector */\n for (i = 0; i < istart; i++)\n\tgsl_vector_set (B, i, 0.0);\n\n for (i = istart; i <= iend; i++)\n\tgsl_vector_set (B, i, gsl_vector_get (w->B, i - istart));\n\n for (i = iend + 1; i < w->n; i++)\n\tgsl_vector_set (B, i, 0.0);\n\n return GSL_SUCCESS;\n }\n}\t\t\t\t/* gsl_bspline_eval() */\n\n/*\ngsl_bspline_eval_nonzero()\n Evaluate all non-zero B-spline functions at point x.\nThese are the B_i(x) for i in [istart, iend].\nAlways B_i(x) = 0 for i < istart and for i > iend.\n\nInputs: x - point at which to evaluate splines\n Bk - (output) where to store B-spline values (length k)\n istart - (output) B-spline function index of\n first non-zero basis for given x\n iend - (output) B-spline function index of\n last non-zero basis for given x.\n This is also the knot index corresponding to x.\n w - bspline workspace\n\nReturn: success or error\n\nNotes: 1) the w->knots vector must be initialized before calling\n this function\n\n 2) On output, B contains\n\n [B_{istart,k}, B_{istart+1,k},\n ..., B_{iend-1,k}, B_{iend,k}]\n\n evaluated at the given x.\n*/\n\nint\ngsl_bspline_eval_nonzero (const double x, gsl_vector * Bk, size_t * istart,\n\t\t\t size_t * iend, gsl_bspline_workspace * w)\n{\n if (Bk->size != w->k)\n {\n GSL_ERROR (\"Bk vector length does not match order k\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\t\t\t/* spline index */\n size_t j;\t\t\t/* looping */\n int flag = 0;\t\t/* interval search flag */\n int error = 0;\t\t/* error flag */\n\n i = bspline_find_interval (x, &flag, w);\n error = bspline_process_interval_for_eval (x, &i, flag, w);\n if (error)\n\t{\n\t return error;\n\t}\n\n *istart = i - w->k + 1;\n *iend = i;\n\n bspline_pppack_bsplvb (w->knots, w->k, 1, x, *iend, &j, w->deltal,\n\t\t\t w->deltar, Bk);\n\n return GSL_SUCCESS;\n }\n}\t\t\t\t/* gsl_bspline_eval_nonzero() */\n\n/*\ngsl_bspline_deriv_eval()\n Evaluate d^j/dx^j B_i(x) for all i, 0 <= j <= nderiv.\nThis is a wrapper function for gsl_bspline_deriv_eval_nonzero()\nwhich formats the output in a nice way.\n\nInputs: x - point for evaluation\n nderiv - number of derivatives to compute, inclusive.\n dB - (output) where to store d^j/dx^j B_i(x)\n values. the size of this matrix is\n (n = nbreak + k - 2 = l + k - 1 = w->n)\n by (nderiv + 1)\n w - bspline derivative workspace\n\nReturn: success or error\n\nNotes: 1) The w->knots vector must be initialized prior to calling\n this function (see gsl_bspline_knots())\n\n 2) based on PPPACK's bsplvd\n*/\n\nint\ngsl_bspline_deriv_eval (const double x, const size_t nderiv, gsl_matrix * dB,\n\t\t\tgsl_bspline_workspace * w,\n\t\t\tgsl_bspline_deriv_workspace * dw)\n{\n if (dB->size1 != w->n)\n {\n GSL_ERROR (\"dB matrix first dimension not of length n\", GSL_EBADLEN);\n }\n else if (dB->size2 < nderiv + 1)\n {\n GSL_ERROR\n\t(\"dB matrix second dimension must be at least length nderiv+1\",\n\t GSL_EBADLEN);\n }\n else if (dw->k < w->k) \n {\n GSL_ERROR (\"derivative workspace is too small\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\t\t\t/* looping */\n size_t j;\t\t\t/* looping */\n size_t istart;\t\t/* first non-zero spline for x */\n size_t iend;\t\t/* last non-zero spline for x, knot for x */\n int error;\t\t/* error handling */\n\n /* find all non-zero d^j/dx^j B_i(x) values */\n error =\n\tgsl_bspline_deriv_eval_nonzero (x, nderiv, dw->dB, &istart, &iend, w,\n\t\t\t\t\tdw);\n if (error)\n\t{\n\t return error;\n\t}\n\n /* store values in appropriate part of given matrix */\n for (j = 0; j <= nderiv; j++)\n\t{\n\t for (i = 0; i < istart; i++)\n\t gsl_matrix_set (dB, i, j, 0.0);\n\n\t for (i = istart; i <= iend; i++)\n\t gsl_matrix_set (dB, i, j, gsl_matrix_get (dw->dB, i - istart, j));\n\n\t for (i = iend + 1; i < w->n; i++)\n\t gsl_matrix_set (dB, i, j, 0.0);\n\t}\n\n return GSL_SUCCESS;\n }\n}\t\t\t\t/* gsl_bspline_deriv_eval() */\n\n/*\ngsl_bspline_deriv_eval_nonzero()\n At point x evaluate all requested, non-zero B-spline function\nderivatives and store them in dB. These are the\nd^j/dx^j B_i(x) with i in [istart, iend] and j in [0, nderiv].\nAlways d^j/dx^j B_i(x) = 0 for i < istart and for i > iend.\n\nInputs: x - point at which to evaluate splines\n nderiv - number of derivatives to request, inclusive\n dB - (output) where to store dB-spline derivatives\n (size k by nderiv + 1)\n istart - (output) B-spline function index of\n first non-zero basis for given x\n iend - (output) B-spline function index of\n last non-zero basis for given x.\n This is also the knot index corresponding to x.\n w - bspline derivative workspace\n\nReturn: success or error\n\nNotes: 1) the w->knots vector must be initialized before calling\n this function\n\n 2) On output, dB contains\n\n [[B_{istart, k}, ..., d^nderiv/dx^nderiv B_{istart ,k}],\n [B_{istart+1,k}, ..., d^nderiv/dx^nderiv B_{istart+1,k}],\n ...\n [B_{iend-1, k}, ..., d^nderiv/dx^nderiv B_{iend-1, k}],\n [B_{iend, k}, ..., d^nderiv/dx^nderiv B_{iend, k}]]\n\n evaluated at x. B_{istart, k} is stored in dB(0,0).\n Each additional column contains an additional derivative.\n\n 3) Note that the zero-th column of the result contains the\n 0th derivative, which is simply a function evaluation.\n\n 4) based on PPPACK's bsplvd\n*/\n\nint\ngsl_bspline_deriv_eval_nonzero (const double x, const size_t nderiv,\n\t\t\t\tgsl_matrix * dB, size_t * istart,\n\t\t\t\tsize_t * iend, gsl_bspline_workspace * w,\n\t\t\t\tgsl_bspline_deriv_workspace * dw)\n{\n if (dB->size1 != w->k)\n {\n GSL_ERROR (\"dB matrix first dimension not of length k\", GSL_EBADLEN);\n }\n else if (dB->size2 < nderiv + 1)\n {\n GSL_ERROR\n\t(\"dB matrix second dimension must be at least length nderiv+1\",\n\t GSL_EBADLEN);\n }\n else if (dw->k < w->k) \n {\n GSL_ERROR (\"derivative workspace is too small\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\t\t\t/* spline index */\n size_t j;\t\t\t/* looping */\n int flag = 0;\t\t/* interval search flag */\n int error = 0;\t\t/* error flag */\n size_t min_nderivk;\n\n i = bspline_find_interval (x, &flag, w);\n error = bspline_process_interval_for_eval (x, &i, flag, w);\n if (error)\n\t{\n\t return error;\n\t}\n\n *istart = i - w->k + 1;\n *iend = i;\n\n bspline_pppack_bsplvd (w->knots, w->k, x, *iend,\n\t\t\t w->deltal, w->deltar, dw->A, dB, nderiv);\n\n /* An order k b-spline has at most k-1 nonzero derivatives\n so we need to zero all requested higher order derivatives */\n min_nderivk = GSL_MIN_INT (nderiv, w->k - 1);\n for (j = min_nderivk + 1; j <= nderiv; j++)\n\t{\n\t for (i = 0; i < w->k; i++)\n\t {\n\t gsl_matrix_set (dB, i, j, 0.0);\n\t }\n\t}\n\n return GSL_SUCCESS;\n }\n}\t\t\t\t/* gsl_bspline_deriv_eval_nonzero() */\n\n/****************************************\n * INTERNAL ROUTINES *\n ****************************************/\n\n/*\nbspline_find_interval()\n Find knot interval such that t_i <= x < t_{i + 1}\nwhere the t_i are knot values.\n\nInputs: x - x value\n flag - (output) error flag\n w - bspline workspace\n\nReturn: i (index in w->knots corresponding to left limit of interval)\n\nNotes: The error conditions are reported as follows:\n\n Condition Return value Flag\n --------- ------------ ----\n x < t_0 0 -1\n t_i <= x < t_{i+1} i 0\n t_i < x = t_{i+1} = t_{n+k-1} i 0\n t_{n+k-1} < x l+k-1 +1\n*/\n\nstatic inline size_t\nbspline_find_interval (const double x, int *flag, gsl_bspline_workspace * w)\n{\n size_t i;\n\n if (x < gsl_vector_get (w->knots, 0))\n {\n *flag = -1;\n return 0;\n }\n\n /* find i such that t_i <= x < t_{i+1} */\n for (i = w->k - 1; i < w->k + w->l - 1; i++)\n {\n const double ti = gsl_vector_get (w->knots, i);\n const double tip1 = gsl_vector_get (w->knots, i + 1);\n\n if (tip1 < ti)\n\t{\n\t GSL_ERROR (\"knots vector is not increasing\", GSL_EINVAL);\n\t}\n\n if (ti <= x && x < tip1)\n\tbreak;\n\n if (ti < x && x == tip1 && tip1 == gsl_vector_get (w->knots, w->k + w->l\n\t\t\t\t\t\t\t - 1))\n\tbreak;\n }\n\n if (i == w->k + w->l - 1)\n *flag = 1;\n else\n *flag = 0;\n\n return i;\n}\t\t\t\t/* bspline_find_interval() */\n\n/*\nbspline_process_interval_for_eval()\n Consumes an x location, left knot from bspline_find_interval, flag\nfrom bspline_find_interval, and a workspace. Checks that x lies within\nthe splines' knots, enforces some endpoint continuity requirements, and\navoids divide by zero errors in the underlying bspline_pppack_* functions.\n*/\nstatic inline int\nbspline_process_interval_for_eval (const double x, size_t * i, const int flag,\n\t\t\t\t gsl_bspline_workspace * w)\n{\n if (flag == -1)\n {\n GSL_ERROR (\"x outside of knot interval\", GSL_EINVAL);\n }\n else if (flag == 1)\n {\n if (x <= gsl_vector_get (w->knots, *i) + GSL_DBL_EPSILON)\n\t{\n\t *i -= 1;\n\t}\n else\n\t{\n\t GSL_ERROR (\"x outside of knot interval\", GSL_EINVAL);\n\t}\n }\n\n if (gsl_vector_get (w->knots, *i) == gsl_vector_get (w->knots, *i + 1))\n {\n GSL_ERROR (\"knot(i) = knot(i+1) will result in division by zero\",\n\t\t GSL_EINVAL);\n }\n\n return GSL_SUCCESS;\n}\t\t\t\t/* bspline_process_interval_for_eval */\n\n/********************************************************************\n * PPPACK ROUTINES\n *\n * The routines herein deliberately avoid using the bspline workspace,\n * choosing instead to pass all work areas explicitly. This allows\n * others to more easily adapt these routines to low memory or\n * parallel scenarios.\n ********************************************************************/\n\n/*\nbspline_pppack_bsplvb()\n calculates the value of all possibly nonzero b-splines at x of order\njout = max( jhigh , (j+1)*(index-1) ) with knot sequence t.\n\nParameters:\n t - knot sequence, of length left + jout , assumed to be\n nondecreasing. assumption t(left).lt.t(left + 1).\n division by zero will result if t(left) = t(left+1)\n jhigh -\n index - integers which determine the order jout = max(jhigh,\n (j+1)*(index-1)) of the b-splines whose values at x\n are to be returned. index is used to avoid\n recalculations when several columns of the triangular\n array of b-spline values are needed (e.g., in bsplpp\n or in bsplvd ). precisely,\n\n if index = 1 ,\n the calculation starts from scratch and the entire\n triangular array of b-spline values of orders\n 1,2,...,jhigh is generated order by order , i.e.,\n column by column .\n\n if index = 2 ,\n only the b-spline values of order j+1, j+2, ..., jout\n are generated, the assumption being that biatx, j,\n deltal, deltar are, on entry, as they were on exit\n at the previous call.\n\n in particular, if jhigh = 0, then jout = j+1, i.e.,\n just the next column of b-spline values is generated.\n x - the point at which the b-splines are to be evaluated.\n left - an integer chosen (usually) so that\n t(left) .le. x .le. t(left+1).\n j - (output) a working scalar for indexing\n deltal - (output) a working area which must be of length at least jout\n deltar - (output) a working area which must be of length at least jout\n biatx - (output) array of length jout, with biatx(i)\n containing the value at x of the polynomial of order\n jout which agrees with the b-spline b(left-jout+i,jout,t)\n on the interval (t(left), t(left+1)) .\n\nMethod:\n the recurrence relation\n\n x - t(i) t(i+j+1) - x\n b(i,j+1)(x) = -----------b(i,j)(x) + ---------------b(i+1,j)(x)\n t(i+j)-t(i) t(i+j+1)-t(i+1)\n\n is used (repeatedly) to generate the (j+1)-vector b(left-j,j+1)(x),\n ...,b(left,j+1)(x) from the j-vector b(left-j+1,j)(x),...,\n b(left,j)(x), storing the new values in biatx over the old. the\n facts that\n\n b(i,1) = 1 if t(i) .le. x .lt. t(i+1)\n\n and that\n\n b(i,j)(x) = 0 unless t(i) .le. x .lt. t(i+j)\n\n are used. the particular organization of the calculations follows\n algorithm (8) in chapter x of [1].\n\nNotes:\n\n (1) This is a direct translation of PPPACK's bsplvb routine with\n j, deltal, deltar rewritten as input parameters and\n utilizing zero-based indexing.\n\n (2) This routine contains no error checking. Please use routines\n like gsl_bspline_eval().\n*/\n\nstatic void\nbspline_pppack_bsplvb (const gsl_vector * t,\n\t\t const size_t jhigh,\n\t\t const size_t index,\n\t\t const double x,\n\t\t const size_t left,\n\t\t size_t * j,\n\t\t gsl_vector * deltal,\n\t\t gsl_vector * deltar, gsl_vector * biatx)\n{\n size_t i;\t\t\t/* looping */\n double saved;\n double term;\n\n if (index == 1)\n {\n *j = 0;\n gsl_vector_set (biatx, 0, 1.0);\n }\n\n for ( /* NOP */ ; *j < jhigh - 1; *j += 1)\n {\n gsl_vector_set (deltar, *j, gsl_vector_get (t, left + *j + 1) - x);\n gsl_vector_set (deltal, *j, x - gsl_vector_get (t, left - *j));\n\n saved = 0.0;\n\n for (i = 0; i <= *j; i++)\n\t{\n\t term = gsl_vector_get (biatx, i) / (gsl_vector_get (deltar, i)\n\t\t\t\t\t + gsl_vector_get (deltal,\n\t\t\t\t\t\t\t\t*j - i));\n\n\t gsl_vector_set (biatx, i,\n\t\t\t saved + gsl_vector_get (deltar, i) * term);\n\n\t saved = gsl_vector_get (deltal, *j - i) * term;\n\t}\n\n gsl_vector_set (biatx, *j + 1, saved);\n }\n\n return;\n}\t\t\t\t/* gsl_bspline_pppack_bsplvb */\n\n/*\nbspline_pppack_bsplvd()\n calculates value and derivs of all b-splines which do not vanish at x\n\nParameters:\n t - the knot array, of length left+k (at least)\n k - the order of the b-splines to be evaluated\n x - the point at which these values are sought\n left - an integer indicating the left endpoint of the interval\n of interest. the k b-splines whose support contains the\n interval (t(left), t(left+1)) are to be considered.\n it is assumed that t(left) .lt. t(left+1)\n division by zero will result otherwise (in bsplvb).\n also, the output is as advertised only if\n t(left) .le. x .le. t(left+1) .\n deltal - a working area which must be of length at least k\n deltar - a working area which must be of length at least k\n a - an array of order (k,k), to contain b-coeffs of the\n derivatives of a certain order of the k b-splines\n of interest.\n dbiatx - an array of order (k,nderiv). its entry (i,m) contains\n value of (m)th derivative of (left-k+i)-th b-spline\n of order k for knot sequence t, i=1,...,k, m=0,...,nderiv.\n nderiv - an integer indicating that values of b-splines and\n their derivatives up to AND INCLUDING the nderiv-th\n are asked for. (nderiv is replaced internally by the\n integer mhigh in (1,k) closest to it.)\n\nMethod:\n values at x of all the relevant b-splines of order k,k-1,..., k+1-nderiv\n are generated via bsplvb and stored temporarily in dbiatx. then, the\n b-coeffs of the required derivatives of the b-splines of interest are\n generated by differencing, each from the preceeding one of lower order,\n and combined with the values of b-splines of corresponding order in\n dbiatx to produce the desired values .\n\nNotes:\n\n (1) This is a direct translation of PPPACK's bsplvd routine with\n deltal, deltar rewritten as input parameters (to later feed them\n to bspline_pppack_bsplvb) and utilizing zero-based indexing.\n\n (2) This routine contains no error checking.\n*/\n\nstatic void\nbspline_pppack_bsplvd (const gsl_vector * t,\n\t\t const size_t k,\n\t\t const double x,\n\t\t const size_t left,\n\t\t gsl_vector * deltal,\n\t\t gsl_vector * deltar,\n\t\t gsl_matrix * a,\n\t\t gsl_matrix * dbiatx, const size_t nderiv)\n{\n int i, ideriv, il, j, jlow, jp1mid, kmm, ldummy, m, mhigh;\n double factor, fkmm, sum;\n\n size_t bsplvb_j;\n gsl_vector_view dbcol = gsl_matrix_column (dbiatx, 0);\n\n mhigh = GSL_MIN_INT (nderiv, k - 1);\n bspline_pppack_bsplvb (t, k - mhigh, 1, x, left, &bsplvb_j, deltal, deltar,\n\t\t\t &dbcol.vector);\n if (mhigh > 0)\n {\n /* the first column of dbiatx always contains the b-spline\n values for the current order. these are stored in column\n k-current order before bsplvb is called to put values\n for the next higher order on top of it. */\n ideriv = mhigh;\n for (m = 1; m <= mhigh; m++)\n\t{\n\t for (j = ideriv, jp1mid = 0; j < (int) k; j++, jp1mid++)\n\t {\n\t gsl_matrix_set (dbiatx, j, ideriv,\n\t\t\t gsl_matrix_get (dbiatx, jp1mid, 0));\n\t }\n\t ideriv--;\n\t bspline_pppack_bsplvb (t, k - ideriv, 2, x, left, &bsplvb_j, deltal,\n\t\t\t\t deltar, &dbcol.vector);\n\t}\n\n /* at this point, b(left-k+i, k+1-j)(x) is in dbiatx(i,j)\n for i=j,...,k-1 and j=0,...,mhigh. in particular, the\n first column of dbiatx is already in final form. to obtain\n corresponding derivatives of b-splines in subsequent columns,\n generate their b-repr. by differencing, then evaluate at x. */\n jlow = 0;\n for (i = 0; i < (int) k; i++)\n\t{\n\t for (j = jlow; j < (int) k; j++)\n\t {\n\t gsl_matrix_set (a, j, i, 0.0);\n\t }\n\t jlow = i;\n\t gsl_matrix_set (a, i, i, 1.0);\n\t}\n\n /* at this point, a(.,j) contains the b-coeffs for the j-th of the\n k b-splines of interest here. */\n for (m = 1; m <= mhigh; m++)\n\t{\n\t kmm = k - m;\n\t fkmm = (float) kmm;\n\t il = left;\n\t i = k - 1;\n\n\t /* for j=1,...,k, construct b-coeffs of (m)th derivative\n\t of b-splines from those for preceding derivative by\n\t differencing and store again in a(.,j) . the fact that\n\t a(i,j) = 0 for i .lt. j is used. */\n\t for (ldummy = 0; ldummy < kmm; ldummy++)\n\t {\n\t factor =\n\t\tfkmm / (gsl_vector_get (t, il + kmm) -\n\t\t\tgsl_vector_get (t, il));\n\t /* the assumption that t(left).lt.t(left+1) makes\n\t denominator in factor nonzero. */\n\t for (j = 0; j <= i; j++)\n\t\t{\n\t\t gsl_matrix_set (a, i, j, factor * (gsl_matrix_get (a, i, j)\n\t\t\t\t\t\t - gsl_matrix_get (a,\n\t\t\t\t\t\t\t\t i - 1,\n\t\t\t\t\t\t\t\t j)));\n\t\t}\n\t il--;\n\t i--;\n\t }\n\n\t /* for i=1,...,k, combine b-coeffs a(.,i) with b-spline values\n\t stored in dbiatx(.,m) to get value of (m)th derivative\n\t of i-th b-spline (of interest here) at x, and store in\n\t dbiatx(i,m). storage of this value over the value of a\n\t b-spline of order m there is safe since the remaining\n\t b-spline derivatives of the same order do not use this\n\t value due to the fact that a(j,i) = 0 for j .lt. i . */\n\t for (i = 0; i < (int) k; i++)\n\t {\n\t sum = 0;\n\t jlow = GSL_MAX_INT (i, m);\n\t for (j = jlow; j < (int) k; j++)\n\t\t{\n\t\t sum +=\n\t\t gsl_matrix_get (a, j, i) * gsl_matrix_get (dbiatx, j, m);\n\t\t}\n\t gsl_matrix_set (dbiatx, i, m, sum);\n\t }\n\t}\n }\n\n return;\n\n}\t\t\t\t/* bspline_pppack_bsplvd */\n", "meta": {"hexsha": "cf19574129d7fc1ee6ca6673fc99ee1637d98f3c", "size": 28240, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/bspline.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/bspline/bspline.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/bspline/bspline.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": 27.9603960396, "max_line_length": 81, "alphanum_fraction": 0.5937677054, "num_tokens": 8504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.49095499342114274}} {"text": "/*\n**\n** Lit: \n** Y.Yu, S.T. Acton:\n** Speckle reducing anisotropic diffusion.\n** IEEE Trans Image Proc., Vol. 11, No. 11, Nov 2002\n**\n** G.Lohmann, MPI-CBS, 2008\n*/\n\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n/*\n** repair border\n*/\nvoid\nBorder(VImage src)\n{\n int b=0,r,c,nrows,ncols;\n double u;\n\n nrows = VImageNRows(src);\n ncols = VImageNColumns(src);\n\n for (r=0; r 0) {\n\t q = sqrt(q);\n\t u = (q*q - q0*q0) / ((q0*q0)*(1.0 + q0*q0));\n\t }\n\t else\n\t u = 0;\n\n\t cx = 0;\n\t if (type == 0) \n\t cx = 1.0 / (1.0 + u);\n\t else \n\t cx = exp(-u);\n\n\t if (gsl_isnan(cx) || gsl_isinf(cx)) {\n\t cx = 0;\n\t VWarning(\" cx, insnan, isinf\");\n\t }\n\n\t VPixel(ctmp,0,r,c,VFloat) = cx;\n\t}\n }\n Border(ctmp);\n \n for (r=1; r VPixelMaxValue (tmp2)) u = VPixelMaxValue (tmp2);\n\t if (u < VPixelMinValue (tmp2)) u = VPixelMinValue (tmp2);\n\t VPixel(tmp2,0,r,c,VFloat) = u;\n\n\t}\n }\n q0 *= exp(-rho*t);\n\n Border(tmp2);\n tmp1 = VCopyImagePixels(tmp2,tmp1,VAllBands);\n t += dt;\n }\n \n /*\n ** output\n */\n for (r=1; r VPixelMaxValue (dest)) v = VPixelMaxValue (dest);\n\tif (v < VPixelMinValue (dest)) v = VPixelMinValue (dest);\n\tVSetPixel(dest,b,r,c,(VDouble) v);\n }\n }\n }\n\n /*\n VDestroyImage(tmp1);\n VDestroyImage(tmp2);\n */\n return dest;\n}\n", "meta": {"hexsha": "958e3f0fb113e84a6f7ef9266f576f89f5a7dd1d", "size": 4049, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prep/vsrad/SRAD.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/prep/vsrad/SRAD.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/prep/vsrad/SRAD.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": 20.0445544554, "max_line_length": 67, "alphanum_fraction": 0.5302543838, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4909549875154424}} {"text": "// build commmand:\n// gcc -c test_fresnel.c -O2 -std=c99 -I../LISAsim -I/opt/local/include\n// gcc -o test_fresnel test_fresnel.o struct.o ../LISAsim/LISAnoise.o -lgsl -lgslcblas\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"splinecoeffs.h\"\n\n\n/* Implementation of the Thomas algorithm to solve a tridiagonal system */\n/* Note: assumes numerical stability (e.g. diagonal-dominated matrix) */\nstatic void SolveTridiagThomas(\n gsl_vector* vectx, /* Output: solution vector, length n - already allocated */\n gsl_vector* vecta, /* Diagonal of the matrix, length n */\n gsl_vector* vectb, /* Lower diagonal, length n-1 */\n gsl_vector* vectc, /* Upper diagonal, length n-1 */\n gsl_vector* vecty, /* Right-hand-side vector, length n */\n int n) /* Length of vectx, vecty */\n{\n /* Check lengths */\n if(!(vectx->size==n && vecty->size==n && vecta->size==n && vectb->size==n-1 && vectc->size==n-1)) {\n printf(\"Error: incompatible lengths in SolveTridiagThomas.\\n\");\n exit(1);\n }\n \n /* Note: we modify the vectors c, y in place */\n double* chat = vectc->data;\n double* yhat = vecty->data;\n double* x = vectx->data;\n double* a = vecta->data;\n double* b = vectb->data;\n\n /* Sweep forward, computing the chat and yhat values */\n chat[0] = chat[0] / a[0];\n yhat[0] = yhat[0] / a[0];\n double factor;\n for(int i=1; i<=n-2; i++) {\n factor = 1./(a[i] - b[i-1]*chat[i-1]);\n chat[i] = chat[i] * factor;\n yhat[i] = (yhat[i] - b[i-1]*yhat[i-1]) * factor;\n }\n factor = 1./(a[n-1] - b[n-2]*chat[n-2]);\n yhat[n-1] = (yhat[n-1] - b[n-2]*yhat[n-2]) * factor;\n\n /* Solve for x going backward */\n x[n-1] = yhat[n-1];\n for(int i=n-2; i>=0; i--) {\n x[i] = yhat[i] - chat[i] * x[i+1];\n }\n}\n\nvoid BuildNotAKnotSpline(\n gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */\n gsl_vector* vectx, /* Input: vector x*/\n gsl_vector* vecty, /* Input: vector y */\n int n) /* Size of x, y, and of output matrix */\n{\n /* Check lengths */\n if(!(vectx->size==n && vecty->size==n && splinecoeffs->size1==n && splinecoeffs->size2==5)) {\n printf(\"Error: incompatible lengths in NotAKnotSpline.\\n\");\n exit(1);\n }\n double* x = vectx->data;\n double* y = vecty->data;\n \n /* Computing vecth and vectDeltay */\n gsl_vector* vecth = gsl_vector_alloc(n-1);\n gsl_vector* vectDeltay = gsl_vector_alloc(n-1);\n gsl_vector* vectDeltayoverh = gsl_vector_alloc(n-1);\n double* h = vecth->data;\n double* Deltay = vectDeltay->data;\n double* Deltayoverh = vectDeltayoverh->data;\n for(int i=0; idata;\n double* a = vecta->data;\n double* b = vectb->data;\n double* c = vectc->data;\n for(int i=0; i<=n-3; i++) {\n Y[i] = 3.*(Deltayoverh[i+1] - Deltayoverh[i]);\n a[i] = 2.*(h[i+1] + h[i]);\n }\n for(int i=0; i<=n-4; i++) {\n b[i] = h[i+1];\n c[i] = h[i+1];\n }\n /* Adjusting for the not-a-knot condition */\n a[0] += h[0] + h[0]*h[0]/h[1];\n c[0] += -h[0]*h[0]/h[1];\n a[n-3] += h[n-2] + h[n-2]*h[n-2]/h[n-3];\n b[n-4] += -h[n-2]*h[n-2]/h[n-3];\n \n /* Solving the tridiagonal system */\n gsl_vector* vectp2 = gsl_vector_alloc(n);\n gsl_vector_view viewp2trunc = gsl_vector_subvector(vectp2, 1, n-2);\n SolveTridiagThomas(&viewp2trunc.vector, vecta, vectb, vectc, vectY, n-2);\n double* p2 = vectp2->data;\n p2[0] = p2[1] - h[0]/h[1] * (p2[2] - p2[1]);\n p2[n-1] = p2[n-2] + h[n-2]/h[n-3] * (p2[n-2] - p2[n-3]);\n\n /* Deducing the p1's and the p3's */\n gsl_vector* vectp1 = gsl_vector_alloc(n);\n gsl_vector* vectp3 = gsl_vector_alloc(n);\n double* p1 = vectp1->data;\n double* p3 = vectp3->data;\n for(int i=0; i<=n-2; i++) {\n p1[i] = Deltayoverh[i] - h[i]/3. * (p2[i+1] + 2.*p2[i]);\n p3[i] = (p2[i+1] - p2[i]) / (3*h[i]);\n }\n /* Note: p1[n-1], p2[n-1], p3[n-1] are set to values coherent with the derivatives of the spline at the last point, but they are not stricly speaking coefficients of the spline. */\n p1[n-1] = p1[n-2] + 2.*p2[n-2]*h[n-2] + 3.*p3[n-2]*h[n-2]*h[n-2];\n p3[n-1] = p3[n-2];\n\n /* Copying the results in the output matrix */\n gsl_vector_view viewx = gsl_matrix_column(splinecoeffs, 0);\n gsl_vector_view viewp0 = gsl_matrix_column(splinecoeffs, 1);\n gsl_vector_view viewp1 = gsl_matrix_column(splinecoeffs, 2);\n gsl_vector_view viewp2 = gsl_matrix_column(splinecoeffs, 3);\n gsl_vector_view viewp3 = gsl_matrix_column(splinecoeffs, 4);\n gsl_vector_memcpy(&viewx.vector, vectx);\n gsl_vector_memcpy(&viewp0.vector, vecty);\n gsl_vector_memcpy(&viewp1.vector, vectp1);\n gsl_vector_memcpy(&viewp2.vector, vectp2);\n gsl_vector_memcpy(&viewp3.vector, vectp3);\n\n /* Cleanup*/\n gsl_vector_free(vecth);\n gsl_vector_free(vectDeltay);\n gsl_vector_free(vectDeltayoverh);\n gsl_vector_free(vectY);\n gsl_vector_free(vecta);\n gsl_vector_free(vectb);\n gsl_vector_free(vectc);\n gsl_vector_free(vectp1);\n gsl_vector_free(vectp2);\n gsl_vector_free(vectp3);\n}\n\nvoid BuildQuadSpline(\n gsl_matrix* splinecoeffs, /* Output: matrix containing all the spline coeffs (already allocated) */\n gsl_vector* vectx, /* Input: vector x*/\n gsl_vector* vecty, /* Input: vector y */\n int n) /* Size of x, y, and of output matrix */\n{\n /* Check lengths */\n if(!(vectx->size==n && vecty->size==n && splinecoeffs->size1==n && splinecoeffs->size2==4)) {\n printf(\"Error: incompatible lengths in NotAKnotSpline.\\n\");\n exit(1);\n }\n double* x = vectx->data;\n double* y = vecty->data;\n\n /* Computing vecth and vectDeltay */\n gsl_vector* vecth = gsl_vector_alloc(n-1);\n gsl_vector* vectDeltay = gsl_vector_alloc(n-1);\n gsl_vector* vectDeltayoverh = gsl_vector_alloc(n-1);\n double* h = vecth->data;\n double* Deltay = vectDeltay->data;\n double* Deltayoverh = vectDeltayoverh->data;\n for(int i=0; idata;\n double ratio = h[n-2] / h[n-3];\n p1[n-3] = ((2. + ratio)*Deltayoverh[n-3] - Deltayoverh[n-2]) / (1. + ratio);\n p1[n-2] = -p1[n-3] + 2.*Deltayoverh[n-3];\n for(int i=n-4; i>=0; i--) {\n p1[i] = -p1[i+1] + 2.*Deltayoverh[i];\n }\n p1[n-1] = (1. + ratio)*p1[n-2] - ratio*p1[n-3];\n\n /* Deducing the p2's */\n gsl_vector* vectp2 = gsl_vector_alloc(n);\n double* p2 = vectp2->data;\n for(int i=0; i<=n-2; i++) {\n p2[i] = (p1[i+1] - p1[i]) / (2.*h[i]);\n }\n /* Note: p2[n-1] is set to values coherent with the derivatives of the spline at the last point, but not stricly speaking a coefficient of the spline. */\n p2[n-1] = p2[n-2];\n\n /* Copying the results in the output matrix */\n gsl_vector_view viewx = gsl_matrix_column(splinecoeffs, 0);\n gsl_vector_view viewp0 = gsl_matrix_column(splinecoeffs, 1);\n gsl_vector_view viewp1 = gsl_matrix_column(splinecoeffs, 2);\n gsl_vector_view viewp2 = gsl_matrix_column(splinecoeffs, 3);\n gsl_vector_memcpy(&viewx.vector, vectx);\n gsl_vector_memcpy(&viewp0.vector, vecty);\n gsl_vector_memcpy(&viewp1.vector, vectp1);\n gsl_vector_memcpy(&viewp2.vector, vectp2);\n\n /* Cleanup*/\n gsl_vector_free(vecth);\n gsl_vector_free(vectDeltay);\n gsl_vector_free(vectDeltayoverh);\n gsl_vector_free(vectp1);\n gsl_vector_free(vectp2);\n}\n\nvoid BuildSplineCoeffs(\n CAmpPhaseSpline** splines, /* */\n CAmpPhaseFrequencySeries* freqseries) /* */\n{\n /* Initialize output structure */\n int n = (int) freqseries->freq->size;\n CAmpPhaseSpline_Init(splines, n);\n\n /* Build the splines */\n BuildNotAKnotSpline((*splines)->spline_amp_real, freqseries->freq, freqseries->amp_real, n);\n BuildNotAKnotSpline((*splines)->spline_amp_imag, freqseries->freq, freqseries->amp_imag, n);\n BuildQuadSpline((*splines)->quadspline_phase, freqseries->freq, freqseries->phase, n);\n}\n\nvoid BuildListmodesCAmpPhaseSpline(\n ListmodesCAmpPhaseSpline** listspline, /* Output: list of modes of splines in matrix form */\n ListmodesCAmpPhaseFrequencySeries* listh) /* Input: list of modes in amplitude/phase form */\n{\n if(*listspline){ /* We don't allow for the case where listspline already points to something */\n printf(\"Error: Tried to add a mode to an already existing ListmodesCAmpPhaseSpline \");\n exit(1);\n }\n else {\n ListmodesCAmpPhaseFrequencySeries* listelementh = listh;\n while(listelementh) {\n\tint l = listelementh->l;\n\tint m = listelementh->m;\n\tCAmpPhaseSpline* splines = NULL;\n\tBuildSplineCoeffs(&splines, listelementh->freqseries);\n\t*listspline = ListmodesCAmpPhaseSpline_AddModeNoCopy(*listspline, splines, l, m);\n\tlistelementh = listelementh->next;\t\n }\n }\n}\n\n/* Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 */\ndouble EvalCubic(\n gsl_vector* coeffs, /**/\n double eps, /**/\n double eps2, /**/\n double eps3) /**/\n{\n double p0 = gsl_vector_get(coeffs, 1);\n double p1 = gsl_vector_get(coeffs, 2);\n double p2 = gsl_vector_get(coeffs, 3);\n double p3 = gsl_vector_get(coeffs, 4);\n return p0 + p1*eps + p2*eps2 + p3*eps3;\n}\n\ndouble EvalQuad(\n gsl_vector* coeffs, /**/\n double eps, /**/\n double eps2) /**/\n{\n double p0 = gsl_vector_get(coeffs, 1);\n double p1 = gsl_vector_get(coeffs, 2);\n double p2 = gsl_vector_get(coeffs, 3);\n return p0 + p1*eps + p2*eps2;\n}\n\n\nvoid EvalCAmpPhaseSpline(\n CAmpPhaseSpline* splines, //input\n CAmpPhaseFrequencySeries* freqseries) //in/out defines CAmpPhase from defined freqs \n{\n int ispline=0;\n //printf(\"Enter: n=%i\\n\",freqseries->freq->size);\n for(int i=0;ifreq->size;i++){\n double f=gsl_vector_get(freqseries->freq,i);\n //printf(\" f:%g < %g < %g\\n\",gsl_matrix_get(splines->quadspline_phase, 0, 0),f,gsl_matrix_get(splines->quadspline_phase, splines->quadspline_phase->size1-1, 0));\n\n /* Adjust the index in the spline if necessary and compute */\n while(gsl_matrix_get(splines->quadspline_phase, ispline+1, 0)quadspline_phase, ispline, 0);\n double eps2 = eps*eps;\n double eps3 = eps2*eps;\n gsl_vector_view coeffsampreal = gsl_matrix_row(splines->spline_amp_real, ispline);\n gsl_vector_view coeffsampimag = gsl_matrix_row(splines->spline_amp_imag, ispline);\n gsl_vector_view coeffsphase = gsl_matrix_row(splines->quadspline_phase, ispline);\n double Ar = EvalCubic(&coeffsampreal.vector, eps, eps2, eps3);\n double Ai = EvalCubic(&coeffsampimag.vector, eps, eps2, eps3);\n double Ph = EvalQuad(&coeffsphase.vector, eps, eps2);\n \n gsl_vector_set(freqseries->amp_real,i,Ar);\n gsl_vector_set(freqseries->amp_imag,i,Ai);\n gsl_vector_set(freqseries->phase,i,Ph);\n }\n};\n\n", "meta": {"hexsha": "ca11e57d858ee3c7e4e627206d845c23e0ff3e5a", "size": 11407, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/splinecoeffs.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/splinecoeffs.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/splinecoeffs.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 36.2126984127, "max_line_length": 182, "alphanum_fraction": 0.647146489, "num_tokens": 3868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.49089784843852735}} {"text": "#define USE_GSL_INTEGRATION 0\n\n#if USE_GSL_INTEGRATION\n\t#include \n#endif\n\nstruct integrand_params {\n\tu32 n[2];\n\tu32 component_count;\n\tu32 coeff_count;\n\tf64* coeff;\n\n\tnlse_operator_func* op;\n\tvoid* op_userdata;\n\n\tstruct basis basis;\n};\n\nstatic void sbmf_log_integration_result(struct quadgk_result* res) {\n\tsbmf_log_info(\"integral: %.10e\", res->integral);\n\tsbmf_log_info(\"error: %.10e\", res->error);\n\t//sbmf_log_info(\"performed evals: %d\", res->performed_evals);\n\tsbmf_log_info(\"converged: %s\", (res->converged) ? \"yes\" : \"no\");\n}\n\n/* functions to handle spatial guesses */\n\nstruct guess_integrand_params {\n u32 n;\n\tnlse_spatial_guess_func* func;\n\tstruct basis b;\n};\n\nvoid guess_integrand(f64* out, f64* in, u32 len, void* data) {\n struct guess_integrand_params* params = data;\n\n f64 eig[len];\n\tparams->b.eigenfunc(params->n, len, eig, in);\n\n\tf64 sample[len];\n\tparams->func(sample, in, len, NULL);\n\n for (u32 i = 0; i < len; ++i) {\n out[i] = eig[i] * sample[i];\n }\n}\n\n/* function to sample linear and non-linear matrix elements */\nstatic void linear_me_integrand(f64* out, f64* in, u32 len, void* data) {\n\tstruct integrand_params* params = data;\n\n\tf64 eig1[len];\n\tf64 eig2[len];\n\tparams->basis.eigenfunc(params->n[0], len, eig1, in);\n\tparams->basis.eigenfunc(params->n[1], len, eig2, in);\n\n\tf64 op[len];\n\tparams->op(len, op, in, 0, NULL, params->op_userdata);\n\n\tfor (u32 i = 0; i < len; ++i) {\n\t\tout[i] = eig1[i]*eig2[i]*op[i];\n\t}\n}\n\nstatic void nonlinear_me_integrand(f64* out, f64* in, u32 len, void* data) {\n\tstruct integrand_params* params = data;\n\n\tf64 eig1[len];\n\tf64 eig2[len];\n\tparams->basis.eigenfunc(params->n[0], len, eig1, in);\n\tparams->basis.eigenfunc(params->n[1], len, eig2, in);\n\n\tf64 sample[len*params->component_count];\n\tfor (u32 i = 0; i < params->component_count; ++i) {\n\t\tparams->basis.sample(params->coeff_count, ¶ms->coeff[i*params->coeff_count], len, &sample[i*len], in);\n\t}\n\n\tf64 op[len];\n\tparams->op(len, op, in, params->component_count, sample, params->op_userdata);\n\n\tfor (u32 i = 0; i < len; ++i) {\n\t\tout[i] = eig1[i]*eig2[i]*op[i];\n\t}\n}\n\n#if USE_GSL_INTEGRATION\nstatic f64 nonlinear_me_integrand_gsl(f64 in, void* data) {\n\tstruct integrand_params* params = data;\n\n\tf64 eig1;\n\tf64 eig2;\n\tparams->basis.eigenfunc(params->n[0], 1, &eig1, &in);\n\tparams->basis.eigenfunc(params->n[1], 1, &eig2, &in);\n\n\tf64 sample[params->component_count];\n\tfor (u32 i = 0; i < params->component_count; ++i) {\n\t\tparams->basis.sample(params->coeff_count, ¶ms->coeff[i*params->coeff_count], 1, &sample[i], &in);\n\t}\n\n\tf64 op;\n\tparams->op(1, &op, &in, params->component_count, sample, params->op_userdata);\n\n\treturn eig1*eig2*op;\n}\n#endif\n\nstruct nlse_result nlse_solver(struct nlse_settings settings, const u32 component_count, struct nlse_component* component) {\n\t/* Lazy */\n\tconst u32 N = settings.num_basis_funcs;\n\n\t/* Setup results struct */\n\tstruct nlse_result res = {\n\t\t.iterations = 0,\n\t\t.component_count = component_count,\n\t\t.coeff_count = N,\n\t\t.coeff \t\t = sbmf_stack_push(component_count*(N*sizeof(f64))),\n\t\t.abs_error \t = sbmf_stack_push(component_count*sizeof(f64)),\n\t\t.energy \t = sbmf_stack_push(component_count*sizeof(f64)),\n\t\t.residual \t = sbmf_stack_push(component_count*sizeof(f64)),\n\t\t.hamiltonian = sbmf_stack_push(component_count * sizeof(struct symmetric_bandmat)),\n\t\t.converged = false,\n\t};\n\tfor (u32 i = 0; i < component_count; ++i) {\n\t\tres.hamiltonian[i] = symmetric_bandmat_new(N,N);\n\t}\n\n\t/* Place to store coeffs from previous iterations */\n\tf64* old_coeff = sbmf_stack_push(component_count*(N*sizeof(f64)));\n\tf64* old_energy = sbmf_stack_push(component_count * sizeof(f64));\n\n\tstruct quadgk_settings int_settings = {\n\t\t.gk = (settings.gk.gauss_size > 0) ? settings.gk : gk15,\n\t\t.abs_error_tol = 1e-15,\n\t\t.rel_error_tol = 1e-8,\n\t\t.max_iters = settings.max_quadgk_iters,\n\t};\n\n\t/* Setup intial guess values for coeffs */\n\tfor (u32 i = 0; i < component_count; ++i) {\n\t\tswitch (component[i].guess.type) {\n\t\t\tcase DEFAULT_GUESS: {\n\t\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\t\tres.coeff[i*res.coeff_count + j] = 0;\n\t\t\t\t}\n\t\t\t\t/* Initialize the i:th component to the i:th eigenfunction */\n\t\t\t\tres.coeff[i*res.coeff_count + i] = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase SPATIAL_GUESS: {\n\t\t\t\tstruct guess_integrand_params p = {\n\t\t\t\t\t.func = component[i].guess.data.spatial_guess,\n\t\t\t\t\t.b = settings.basis,\n\t\t\t\t};\n\t\t\t\tint_settings.userdata = &p;\n\t\t\t\tf64* out = &res.coeff[i*res.coeff_count];\n\t\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\t\tp.n = j;\n\t\t\t\t\tstruct quadgk_result r;\n\n\t\t\t\t\tu8 quadgk_memory[quadgk_required_memory_size(&int_settings)];\n\t\t\t\t\tquadgk_infinite_interval(guess_integrand, &int_settings, quadgk_memory, &r);\n\t\t\t\t\tout[j] = r.integral;\n\t\t\t\t}\n\t\t\t\tf64_normalize(out, out, res.coeff_count);\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase COEFF_GUESS: {\n\t\t\t\tcomponent[i].guess.data.coeff_guess(&res.coeff[i*res.coeff_count], res.coeff_count, i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase RANDOM_GUESS: {\n\t\t\t\tstruct symmetric_bandmat bm = symmetric_bandmat_new_zero(N,N);\n\t\t\t\tSYMMETRIC_BANDMAT_FOREACH(bm, r,c) {\n\t\t\t\t\tu32 index = symmetric_bandmat_index(bm, r,c);\n\t\t\t\t\tbm.data[index] = 2.0 * ((f64)rand()/(f64)RAND_MAX) - 1.0;\n\t\t\t\t}\n\t\t\t\tstruct eigen_result_real eigres = find_eigenpairs_sparse_real(bm, 1, EV_SMALLEST);\n\t\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\t\tres.coeff[i*res.coeff_count + j] = eigres.eigenvectors[j];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tsbmf_log_error(\"nlse_solver: component %u has invalid guess!\", i);\n\t\t\t\treturn res;\n\t\t};\n\t}\n\n\tstruct integrand_params params = {\n\t\t.component_count = res.component_count,\n\t\t.coeff_count = res.coeff_count,\n\t\t.coeff = res.coeff,\n\t\t.op = NULL,\n\t\t.basis = settings.basis,\n\t};\n\n\t/*\n\t * Unique number of me's that need to be calculated in\n\t * a symmetric matrix\n\t */\n\tconst u32 matrix_element_count = symmetric_bandmat_element_count(N);\n\n\t/* Precompute indices for matrix elements\n\t * \tThis way we get a single array looping\n\t * \tover the matrix which is easier to\n\t * \tparallelize well.\n\t * \t\tPicking the first hamiltonian as a\n\t * \tdummny matrix just to get the correct\n\t * \titeration.\n\t * */\n\tu32 matrix_element_rows[matrix_element_count];\n\tu32 matrix_element_cols[matrix_element_count];\n\t{\n\t\tu32 matrix_element_index = 0;\n\t\tSYMMETRIC_BANDMAT_FOREACH(res.hamiltonian[0], r,c) {\n\t\t\tmatrix_element_rows[matrix_element_index] = r;\n\t\t\tmatrix_element_cols[matrix_element_index] = c;\n\t\t\tmatrix_element_index++;\n\t\t}\n\t}\n\n\t/* Construct linear hamiltonian */\n\tstruct symmetric_bandmat linear_hamiltonian = symmetric_bandmat_new_zero(N,N);\n\t{\n\t\tif (settings.spatial_pot_perturbation) {\n\t\t\tparams.op = settings.spatial_pot_perturbation;\n#pragma omp parallel for firstprivate(params, int_settings) shared(res)\n\t\t\tfor (u32 i = 0; i < matrix_element_count; ++i) {\n\t\t\t\tu32 r = matrix_element_rows[i];\n\t\t\t\tu32 c = matrix_element_cols[i];\n\n\t\t\t\tint_settings.userdata = ¶ms;\n\t\t\t\tparams.n[0] = r;\n\t\t\t\tparams.n[1] = c;\n\n\t\t\t\tu8 quadgk_memory[quadgk_required_memory_size(&int_settings)];\n\t\t\t\tstruct quadgk_result int_res;\n\t\t\t\tquadgk_infinite_interval(linear_me_integrand, &int_settings, quadgk_memory, &int_res);\n\n\t\t\t\tif (fabs(int_res.integral) <= settings.zero_threshold)\n\t\t\t\t\tint_res.integral = 0.0;\n\n\t\t\t\tif (!int_res.converged) {\n\t\t\t\t\tsbmf_log_error(\"In construction of linear hamiltonian:\");\n\t\t\t\t\tsbmf_log_error(\"\\tIntegration failed for %d,%d\", r,c);\n\t\t\t\t\tsbmf_log_integration_result(&int_res);\n\t\t\t\t}\n\t\t\t\tassert(int_res.converged);\n\n\t\t\t\tu32 me_index = symmetric_bandmat_index(linear_hamiltonian, r,c);\n\t\t\t\tlinear_hamiltonian.data[me_index] = int_res.integral;\n\t\t\t}\n\t\t}\n\n\t\tfor (u32 i = 0; i < res.coeff_count; ++i) {\n\t\t\tu32 me_index = symmetric_bandmat_index(linear_hamiltonian, i,i);\n\t\t\tlinear_hamiltonian.data[me_index] += settings.basis.eigenval(i);\n\t\t}\n\n\t\tassert(symmetric_bandmat_is_valid(linear_hamiltonian));\n\t}\n\n#if USE_GSL_INTEGRATION\n\tconst u32 num_threads = omp_get_max_threads();\n\tgsl_integration_workspace* ws[num_threads];\n\t/* Create gsl workspaces if necessary */\n\tfor (u32 i = 0; i < num_threads; ++i) {\n\t\tws[i] = gsl_integration_workspace_alloc(settings.max_iterations);\n\t}\n#endif\n\n\tstruct symmetric_bandmat old_Hs[res.component_count];\n\tstruct symmetric_bandmat premix_Hs[res.component_count];\n\tfor (u32 i = 0; i < res.component_count; ++i) {\n\t\told_Hs[i] = symmetric_bandmat_new(N,N);\n\t\tpremix_Hs[i] = symmetric_bandmat_new(N,N);\n\t}\n\n\t/* Do the actual iterations */\n\tfor (; res.iterations < settings.max_iterations; ++res.iterations) {\n\t\tsbmf_log_info(\"nlse starting iteration %u\", res.iterations);\n\t\tmemcpy(old_energy, res.energy, res.component_count * sizeof(f64));\n\n\t\t/* Call debug callback if requested by user */\n\t\tif (settings.measure_every > 0 &&\n\t\t\t\tsettings.debug_callback &&\n\t\t\t\tres.iterations % settings.measure_every == 0) {\n\t\t\tsettings.debug_callback(settings, res);\n\t\t}\n\n\t\t/* Should we still apply mixing? */\n\t\tif (settings.orbital_mixing > 0 && settings.mix_until_iteration > 0 && res.iterations == settings.mix_until_iteration) {\n\t\t\tsettings.orbital_mixing = 0;\n\t\t}\n\t\tif (settings.hamiltonian_mixing > 0 && settings.mix_until_iteration > 0 && res.iterations == settings.mix_until_iteration) {\n\t\t\tsettings.hamiltonian_mixing = 0;\n\t\t}\n\n\t\tif (settings.orbital_choice != NLSE_ORBITAL_MAXIMUM_OVERLAP && settings.mom_enable_at_iteration > 0 && res.iterations == settings.mom_enable_at_iteration) {\n\t\t\tsettings.orbital_choice = NLSE_ORBITAL_MAXIMUM_OVERLAP;\n\t\t}\n\n\t\t/* Apply orbital mixing */\n\t\tfor (u32 i = 0; i < component_count; ++i) {\n\t\t\tif (settings.orbital_mixing > 0.0) {\n\t\t\t\t//res.energy[i] = (1.0 - settings.orbital_mixing) * res.energy[i] + settings.orbital_mixing*old_energy[i];\n\n\t\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\t\tres.coeff[i*res.coeff_count + j] =\n\t\t\t\t\t\t(1.0 - settings.orbital_mixing) * res.coeff[i*res.coeff_count + j] + settings.orbital_mixing * old_coeff[i*res.coeff_count + j];\n\t\t\t\t}\n\t\t\t\tf64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);\n\t\t\t}\n\t\t}\n\t\tmemcpy(old_coeff, res.coeff, res.component_count * N * sizeof(f64));\n\n\t\t/*\n\t\t * Construct all the Hamiltonians\n\t\t */\n\t\tfor (u32 i = 0; i < component_count; ++i) {\n\t\t\tparams.op = component[i].op;\n\t\t\tparams.op_userdata = component[i].userdata;\n\n\t\t\tmemcpy(old_Hs[i].data, res.hamiltonian[i].data, N*N*sizeof(f64));\n\n\t\t\t/* Construct the i:th component's hamiltonian */\n#pragma omp parallel for firstprivate(params, int_settings) shared(res, linear_hamiltonian)\n\t\t\tfor (u32 j = 0; j < matrix_element_count; ++j) {\n\t\t\t\tu32 r = matrix_element_rows[j];\n\t\t\t\tu32 c = matrix_element_cols[j];\n\t\t\t\tint_settings.userdata = ¶ms;\n\t\t\t\tparams.n[0] = r;\n\t\t\t\tparams.n[1] = c;\n\n#if USE_GSL_INTEGRATION\n\t\t\t\tintegration_result int_res;\n\t\t\t\tgsl_function F;\n\t\t\t\tF.function = nonlinear_me_integrand_gsl;\n\t\t\t\tF.params = ¶ms;\n\t\t\t\tgsl_integration_qagi(&F, 1e-10, 1e-7, settings.max_iterations, ws[omp_get_thread_num()], &int_res.integral, &int_res.error);\n\t\t\t\tint_res.converged = true;\n#else\n\t\t\t\tu8 quadgk_memory[quadgk_required_memory_size(&int_settings)];\n\n\t\t\t\tstruct quadgk_result int_res;\n\t\t\t\tquadgk_infinite_interval(nonlinear_me_integrand, &int_settings, quadgk_memory, &int_res);\n#endif\n\n\t\t\t\t/* Check if the resultant integral is less than what we can resolve,\n\t\t\t\t * if so, zero it.\n\t\t\t\t */\n\t\t\t\tif (fabs(int_res.integral) <= settings.zero_threshold)\n\t\t\t\t\tint_res.integral = 0.0;\n\n\t\t\t\tif (!int_res.converged) {\n\t\t\t\t\tsbmf_log_error(\"In construction of component %u's hamiltonian:\", i);\n\t\t\t\t\tsbmf_log_error(\"\\tIntegration failed for %d,%d\", r,c);\n\t\t\t\t\tsbmf_log_integration_result(&int_res);\n\t\t\t\t}\n\t\t\t\tassert(int_res.converged);\n\n\t\t\t\tu32 me_index = symmetric_bandmat_index(res.hamiltonian[i], r,c);\n\t\t\t\tres.hamiltonian[i].data[me_index] = linear_hamiltonian.data[me_index] + int_res.integral;\n\t\t\t\tpremix_Hs[i].data[me_index] = res.hamiltonian[i].data[me_index];\n\n\t\t\t\tif (settings.hamiltonian_mixing > 0) {\n\t\t\t\t\tres.hamiltonian[i].data[me_index] = (1.0 - settings.hamiltonian_mixing)*res.hamiltonian[i].data[me_index] + settings.hamiltonian_mixing*old_Hs[i].data[me_index];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert(symmetric_bandmat_is_valid(res.hamiltonian[i]));\n\t\t}\n\n\t\t/*\n\t\t * Solve and normalize all the Hamiltonian\n\t\t * eigenvalue problems\n\t\t */\n\t\tfor (u32 i = 0; i < component_count; ++i) {\n\t\t\tstruct eigen_result_real eigres;\n\t\t\tu32 new_orbital_index = 0;\n\t\t\tswitch (settings.orbital_choice) {\n\t\t\t\tcase NLSE_ORBITAL_LOWEST_ENERGY: {\n\t\t\t\t\teigres = find_eigenpairs_sparse_real(res.hamiltonian[i], 1, EV_SMALLEST);\n\t\t\t\t\tf64_normalize(&eigres.eigenvectors[0], &eigres.eigenvectors[0], res.coeff_count);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase NLSE_ORBITAL_MAXIMUM_OVERLAP: {\n\t\t\t\t\teigres = find_eigenpairs_sparse_real(res.hamiltonian[i], settings.mom_orbitals_to_consider, EV_SMALLEST);\n\t\t\t\t\tf64 maximum_overlap = -INFINITY;\n\t\t\t\t\tfor (u32 j = 0; j < settings.mom_orbitals_to_consider; ++j) {\n\t\t\t\t\t\tf64_normalize(&eigres.eigenvectors[j*res.coeff_count], &eigres.eigenvectors[j*res.coeff_count], res.coeff_count);\n\t\t\t\t\t\tf64 overlap = 0.0;\n\t\t\t\t\t\tfor (u32 k = 0; k < res.coeff_count; ++k) {\n\t\t\t\t\t\t\tf64 a = eigres.eigenvectors[j*res.coeff_count + k];\n\t\t\t\t\t\t\tf64 b = old_coeff[i*res.coeff_count + k];\n\t\t\t\t\t\t\toverlap += a*b;\n\t\t\t\t\t\t}\n\t\t\t\t\t\toverlap = fabs(overlap);\n\n\t\t\t\t\t\tif (overlap > maximum_overlap) {\n\t\t\t\t\t\t\tnew_orbital_index = j;\n\t\t\t\t\t\t\tmaximum_overlap = overlap;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\tsbmf_log_panic(\"nlse_solver(...): Unspecified energy selection method!\");\n\t\t\t\t\tassert(0);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t/* Copy energies and coeffs */\n\t\t\tres.energy[i] = eigres.eigenvalues[new_orbital_index];\n\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\tres.coeff[i*res.coeff_count + j] = eigres.eigenvectors[res.coeff_count*new_orbital_index + j];\n\t\t\t}\n\t\t\tf64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);\n\n\t\t\t///* Apply orbital mixing */\n\t\t\t//if (settings.orbital_mixing > 0.0) {\n\t\t\t//\tres.energy[i] = (1.0 - settings.orbital_mixing) * res.energy[i] + settings.orbital_mixing*old_energy[i];\n\n\t\t\t//\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t//\t\tres.coeff[i*res.coeff_count + j] =\n\t\t\t//\t\t\t(1.0 - settings.orbital_mixing) * res.coeff[i*res.coeff_count + j] + settings.orbital_mixing * old_coeff[i*res.coeff_count + j];\n\t\t\t//\t}\n\t\t\t//\tf64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);\n\t\t\t//}\n\n\t\t}\n\n\t\t/* Calculate error */\n\t\tfor (u32 i = 0; i < component_count; ++i) {\n\t\t\tf64 sum_diff = 0.0;\n\t\t\tf64 sum_prev = 0.0;\n\t\t\tfor (u32 j = 0; j < res.coeff_count; ++j) {\n\t\t\t\tf64 diff = fabs(res.coeff[i*res.coeff_count + j]) - fabs(old_coeff[i*res.coeff_count + j]);\n\t\t\t\tsum_diff += diff*diff;\n\t\t\t\tsum_prev += old_coeff[i*res.coeff_count + j]*old_coeff[i*res.coeff_count + j];\n\t\t\t}\n\t\t\tres.abs_error[i] = sqrt(sum_diff);\n\t\t}\n\n\t\t/* Break condition */\n\t\tbool should_exit = true;\n\t\tfor (u32 i = 0; i < component_count; ++i) {\n\t\t\tif (res.abs_error[i] > settings.abs_error_tol)\n\t\t\t\tshould_exit = false;\n\t\t\tsbmf_log_info(\"\\t[%u] -- abs error: %.10e energy: %.10e\", i, res.abs_error[i], res.energy[i]);\n\t\t}\n\n\t\tif (should_exit) {\n\t\t\tres.converged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n#if USE_GSL_INTEGRATION\n\t/* free gsl workspaces if necessary */\n\tfor (u32 i = 0; i < num_threads; ++i) {\n\t\tgsl_integration_workspace_free(ws[i]);\n\t}\n#endif\n\n\t/* Compute residuals */\n\tfor (u32 i = 0; i < component_count; ++i) {\n\t\tf64 ans1[N], ans2[N];\n\t\tsymmetric_bandmat_mulv(ans1, premix_Hs[i], &res.coeff[i*N]);\n\n\t\tfor (u32 j = 0; j < N; ++j) {\n\t\t\tans2[j] = res.energy[i] * res.coeff[i*N + j];\n\t\t}\n\n\t\tf64 sum = 0.0;\n\t\tfor (u32 j = 0; j < N; ++j) {\n\t\t\tsum += fabs(ans1[j] - ans2[j]);\n\t\t}\n\t\tsum = sqrt(sum);\n\n\t\tres.residual[i] = sum;\n\t\tsbmf_log_info(\"\\t[%u] residual %e\", i, sum);\n\t}\n\n\treturn res;\n}\n\n/*\n * basic serialization\n */\n\nvoid nlse_write_to_binary_file(const char* file, struct nlse_result res) {\n\tFILE* fd = fopen(file, \"w\");\n\tfwrite(&res.iterations, \t sizeof(u32), 1, fd);\n\tfwrite(&res.component_count, sizeof(u32), 1, fd);\n\tfwrite(&res.coeff_count, \t sizeof(u32), 1, fd);\n\n\tfwrite(res.coeff, sizeof(f64), res.coeff_count*res.component_count, fd);\n\tfwrite(res.abs_error, sizeof(f64), res.component_count, fd);\n\tfwrite(res.energy, sizeof(f64), res.component_count, fd);\n\n\tfor (u32 i = 0; i < res.component_count; ++i) {\n\t\tfwrite(&res.hamiltonian[i].size, \t sizeof(u32), 1, fd);\n\t\tfwrite(&res.hamiltonian[i].bandcount, sizeof(u32), 1, fd);\n\t\tu32 elements_written = fwrite(res.hamiltonian[i].data, sizeof(f64),\n\t\t\t\tres.hamiltonian[i].bandcount*res.hamiltonian[i].size,\n\t\t\t\tfd);\n\t\tassert(elements_written == res.hamiltonian[i].bandcount*res.hamiltonian[i].size);\n\t}\n\tfwrite(&res.converged, sizeof(bool), 1, fd);\n\tfclose(fd);\n}\n\nstruct nlse_result nlse_read_from_binary_file(const char* file) {\n\tstruct nlse_result res;\n\n\tFILE* fd = fopen(file, \"r\");\n\tfread(&res.iterations, \t \tsizeof(u32), 1, fd);\n\tfread(&res.component_count, sizeof(u32), 1, fd);\n\tfread(&res.coeff_count, \tsizeof(u32), 1, fd);\n\n\tres.coeff = sbmf_stack_push(sizeof(f64)*res.coeff_count*res.component_count);\n\tfread(res.coeff, sizeof(f64), res.coeff_count*res.component_count, fd);\n\n\tres.abs_error = sbmf_stack_push(sizeof(f64)*res.component_count);\n\tfread(res.abs_error, sizeof(f64), res.component_count, fd);\n\n\tres.energy = sbmf_stack_push(sizeof(f64)*res.component_count);\n\tfread(res.energy, sizeof(f64), res.component_count, fd);\n\n\tres.hamiltonian = sbmf_stack_push(res.component_count * sizeof(struct symmetric_bandmat));\n\tfor (u32 i = 0; i < res.component_count; ++i) {\n\t\tu32 size, bandcount;\n\t\tfread(&size, \t sizeof(u32), 1, fd);\n\t\tfread(&bandcount, sizeof(u32), 1, fd);\n\t\tres.hamiltonian[i] = symmetric_bandmat_new(bandcount, size);\n\t\tu32 bytes_written = fread(res.hamiltonian[i].data, sizeof(f64),\n\t\t\t\tbandcount*size,\n\t\t\t\tfd);\n\t\tassert(bytes_written == bandcount*size);\n\t}\n\tfread(&res.converged, sizeof(bool), 1, fd);\n\tfclose(fd);\n\n\tsbmf_log_info(\"loaded:\");\n\tsbmf_log_info(\" iterations: %u\", res.iterations);\n\tsbmf_log_info(\" component_count: %u\", res.component_count);\n\tsbmf_log_info(\" coeff_count: %u\", res.coeff_count);\n\tfor (u32 i = 0; i < res.component_count; ++i) {\n\t\tsbmf_log_info(\" [%u]: size: %u\", i, res.hamiltonian[i].size);\n\t\tsbmf_log_info(\" [%u]: bandcount: %u\", i, res.hamiltonian[i].bandcount);\n\t}\n\n\treturn res;\n}\n", "meta": {"hexsha": "810f1f427920efc4bf55dd61d05efbfdf040a5fe", "size": 18185, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sbmf/methods/nlse_solver.c", "max_stars_repo_name": "AntonJohansson/sbmf", "max_stars_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "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/sbmf/methods/nlse_solver.c", "max_issues_repo_name": "AntonJohansson/sbmf", "max_issues_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "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/sbmf/methods/nlse_solver.c", "max_forks_repo_name": "AntonJohansson/sbmf", "max_forks_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6481149013, "max_line_length": 166, "alphanum_fraction": 0.6826505362, "num_tokens": 5525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.49062906560437786}} {"text": "//CELL operation: does output side of Elman RNN layer.\n//There is no strict definition of Elman RNN in the literature.\n//For example, the Wikipedia article doesn't specify the dims of the hidden or other vectors.\n//Here I implement an interpretation where there are N neurons and thus N inputs/outputs.\n//The inputs here are from the IN stage, so reduced to N driving input time-series in X.\n\n//Again, this is not an \"Elman network\", rather a layer of N neurons\n//that I have named \"Elman\" neurons due to their great similarity to an Elman RNN.\n\n//To do: should I allow other output activations other than logistic?\n\n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint elman_s (float *Y, const float *X, const float *U, float *H, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint elman_d (double *Y, const double *X, const double *U, double *H, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint elman_s (float *Y, const float *X, const float *U, float *H, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n\n if (N==1u)\n {\n for (size_t t=0u; t\n\n#include \n#include \n\n// Info about a particle pair that we will pass to the weight function\ntypedef struct\n{\n int64_t nprojbins;\n int64_t nsbins;\n double sqr_s;\n double *supp_sqr; //proper way to have array in struct?\n\n} proj_struct_double;\n\n//typedef double (*weight_func_t_double)(const pair_struct_double*);\n\n\n//////////////////////////////////\n// Projection functions\n//////////////////////////////////\n\nstatic inline void tophat_double(const proj_struct_double *proj, double *u){\n\n int ins = -1;\n for(int p=0;pnsbins;p++){\n u[p] = 0;\n if (proj->sqr_s >= proj->supp_sqr[p] && proj->sqr_s < proj->supp_sqr[p+1]){\n ins = p;\n }\n }\n if (ins>=0 && insnprojbins){\n u[ins] = 1.0;\n }\n}\n\n\n//////////////////////////////////\n// Utility functions\n//////////////////////////////////\n\nstatic inline void compute_amplitudes(int nprojbins, int nd1, int nd2, int nr1, int nr2,\n double *dd, double *dr, double *rd, double *rr, double *qq, double *amps){\n\n printf(\"Computing amps\\n\");\n printf(\"qq:\\n\");\n for(int i=0;i\n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\n/* Cash-Karp constants */\nstatic const double ah[] = { 1.0 / 5.0, 0.3, 3.0 / 5.0, 1.0, 7.0 / 8.0 };\nstatic const double b21 = 1.0 / 5.0;\nstatic const double b3[] = { 3.0 / 40.0, 9.0 / 40.0 };\nstatic const double b4[] = { 0.3, -0.9, 1.2 };\nstatic const double b5[] = { -11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0 };\nstatic const double b6[] =\n { 1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0, 44275.0 / 110592.0,\n 253.0 / 4096.0 };\nstatic const double c1 = 37.0 / 378.0;\nstatic const double c3 = 250.0 / 621.0;\nstatic const double c4 = 125.0 / 594.0;\nstatic const double c6 = 512.0 / 1771.0;\nstatic const double ec[] = { 0.0,\n /* the first value is the same as c1, above */\n 37.0 / 378.0 - 2825.0 / 27648.0,\n 0.0,\n /* the first value is the same as c3, above */\n 250.0 / 621.0 - 18575.0 / 48384.0,\n /* the first value is the same as c4, above */\n 125.0 / 594.0 - 13525.0 / 55296.0,\n -277.00 / 14336.0,\n /* the first value is the same as c6, above */\n 512.0 / 1771.0 - 0.25\n};\n\ntypedef struct\n{\n double *k1;\n double *k2;\n double *k3;\n double *k4;\n double *k5;\n double *k6;\n double *y0;\n double *ytmp;\n}\nrkck_state_t;\n\nstatic void *\nrkck_alloc (size_t dim)\n{\n rkck_state_t *state = (rkck_state_t *) malloc (sizeof (rkck_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rkck_state\", GSL_ENOMEM);\n }\n\n state->k1 = (double *) malloc (dim * sizeof (double));\n\n if (state->k1 == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k1\", GSL_ENOMEM);\n }\n\n state->k2 = (double *) malloc (dim * sizeof (double));\n\n if (state->k2 == 0)\n {\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2\", GSL_ENOMEM);\n }\n\n state->k3 = (double *) malloc (dim * sizeof (double));\n\n if (state->k3 == 0)\n {\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k3\", GSL_ENOMEM);\n }\n\n state->k4 = (double *) malloc (dim * sizeof (double));\n\n if (state->k4 == 0)\n {\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k4\", GSL_ENOMEM);\n }\n\n state->k5 = (double *) malloc (dim * sizeof (double));\n\n if (state->k5 == 0)\n {\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k5\", GSL_ENOMEM);\n }\n\n state->k6 = (double *) malloc (dim * sizeof (double));\n\n if (state->k6 == 0)\n {\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k6\", GSL_ENOMEM);\n }\n\n state->y0 = (double *) malloc (dim * sizeof (double));\n\n if (state->y0 == 0)\n {\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->y0);\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\nstatic int\nrkck_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], const gsl_odeiv_system * sys)\n{\n rkck_state_t *state = (rkck_state_t *) vstate;\n\n size_t i;\n int status = 0;\n\n double *const k1 = state->k1;\n double *const k2 = state->k2;\n double *const k3 = state->k3;\n double *const k4 = state->k4;\n double *const k5 = state->k5;\n double *const k6 = state->k6;\n double *const ytmp = state->ytmp;\n\n /* k1 step */\n if (dydt_in != NULL)\n {\n DBL_MEMCPY (k1, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + b21 * h * k1[i];\n\n /* k2 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[0] * h, ytmp, k2);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + h * (b3[0] * k1[i] + b3[1] * k2[i]);\n\n /* k3 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[1] * h, ytmp, k3);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] = y[i] + h * (b4[0] * k1[i] + b4[1] * k2[i] + b4[2] * k3[i]);\n\n /* k4 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[2] * h, ytmp, k4);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] =\n y[i] + h * (b5[0] * k1[i] + b5[1] * k2[i] + b5[2] * k3[i] +\n b5[3] * k4[i]);\n\n /* k5 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[3] * h, ytmp, k5);\n GSL_STATUS_UPDATE (&status, s);\n }\n for (i = 0; i < dim; i++)\n ytmp[i] =\n y[i] + h * (b6[0] * k1[i] + b6[1] * k2[i] + b6[2] * k3[i] +\n b6[3] * k4[i] + b6[4] * k5[i]);\n\n /* k6 step and final sum */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + ah[4] * h, ytmp, k6);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n const double d_i = c1 * k1[i] + c3 * k3[i] + c4 * k4[i] + c6 * k6[i];\n y[i] += h * d_i;\n if (dydt_out != NULL)\n dydt_out[i] = d_i;\n }\n\n /* difference between 4th and 5th order */\n for (i = 0; i < dim; i++)\n yerr[i] =\n h * (ec[1] * k1[i] + ec[3] * k3[i] + ec[4] * k4[i] + ec[5] * k5[i] +\n ec[6] * k6[i]);\n\n return status;\n}\n\n\nstatic int\nrkck_reset (void *vstate, size_t dim)\n{\n rkck_state_t *state = (rkck_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->k1, dim);\n DBL_ZERO_MEMSET (state->k2, dim);\n DBL_ZERO_MEMSET (state->k3, dim);\n DBL_ZERO_MEMSET (state->k4, dim);\n DBL_ZERO_MEMSET (state->k5, dim);\n DBL_ZERO_MEMSET (state->k6, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrkck_order (void *vstate)\n{\n rkck_state_t *state = (rkck_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 5;\n}\n\nstatic void\nrkck_free (void *vstate)\n{\n rkck_state_t *state = (rkck_state_t *) vstate;\n\n free (state->ytmp);\n free (state->y0);\n free (state->k6);\n free (state->k5);\n free (state->k4);\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type rkck_type = { \"rkck\", /* name */\n 1, /* can use dydt_in */\n 0, /* gives exact dydt_out */\n &rkck_alloc,\n &rkck_apply,\n &rkck_reset,\n &rkck_order,\n &rkck_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_rkck = &rkck_type;\n", "meta": {"hexsha": "b869542b77733abbdaf298565c5d371846aada15", "size": 8015, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl_subset/ode-initval/rkck.c", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/ode-initval/rkck.c", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/ode-initval/rkck.c", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 24.6615384615, "max_line_length": 77, "alphanum_fraction": 0.5629444791, "num_tokens": 2854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4895237106023206}} {"text": "/*\n * Copyright (c) 2018-2021 Aleksas Mazeliauskas, Stefan Floerchinger, \n * Eduardo Grossi, and Derek Teaney\n * All rights reserved.\n *\n * FastReso is distributed under MIT license;\n * see the LICENSE file that should be present in the root\n * of the source distribution, or alternately available at:\n * https://github.com/amazeliauskas/FastReso/\n */\n#ifndef FASTRESO_TFastReso_formulas_h\n#define FASTRESO_TFastReso_formulas_h\n#include \n#include \"TParticle.h\"\n#include \n// List of parameters for GSL integration procedure.\n#include \"qag_params.h\"\n#include \"grid_params.h\"\n\n#include \n//using namespace std;\n//! Eabc -- energy of b in restframe of a in a->b+c decay\ndouble get_Eabc(double ma,double mb,double mc) { return (ma*ma+mb*mb-mc*mc)/(2*ma);}\n//! particle momenta\ndouble get_p(double E, double m) { return sqrt(E*E-m*m);}\n//! pabc -- momentum of b or c in restframe of a in a->b+c decay\ndouble get_pabc(double ma,double mb,double mc) { return get_p(get_Eabc(ma,mb,mc),mb);}\n\n//! returns thermal Bose-Einstein, Fermi-Dirac or Boltzmann distribution\ndouble get_thermal_F(double Ebar, double T, double QMu, EParticleType type);\n//! returns derivative of thermal Bose-Einstein, Fermi-Dirac or Boltzmann distribution\ndouble get_thermal_dF(double Ebar, double T, double QMu, EParticleType type);\n\n\n//! Initialize f_j on the freeze-out surface\n//! Here you can add additional fj's\ndouble get_initial_Fj(EFjIndex j, double Ebar, double T, double QMu, EParticleType type, double m, double Cs2)\n{\n double pbar = sqrt(Ebar*Ebar-m*m);\n switch(j){\n case EFjIndex::kFeq1: //feq 1\n return pbar*get_thermal_F(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFeq2: //feq 2\n return pbar*get_thermal_F(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFshear1: //fshear 1\n return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFshear2: //fshear 2\n return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFshear3: //fshear 3\n return pbar*pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFbulk1: //fbulk 1\n return pbar*get_thermal_dF(Ebar,T, QMu, type)*(1./3.*m*m/T/Ebar-Ebar/T*(1./3.-Cs2));\n break;\n case EFjIndex::kFbulk2: //fbulk 2\n return pbar*get_thermal_dF(Ebar,T, QMu, type)*(1./3.*m*m/T/Ebar-Ebar/T*(1./3.-Cs2));\n break;\n case EFjIndex::kFtemp1: //ftemperature. 1\n return pbar*get_thermal_dF(Ebar,T, QMu, type)*Ebar/T;\n break;\n case EFjIndex::kFtemp2: //ftemperature 2\n return pbar*get_thermal_dF(Ebar,T, QMu, type)*Ebar/T;\n break;\n case EFjIndex::kFvel1: //fvelocity 1\n return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFvel2: //fvelocity 2\n return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n case EFjIndex::kFvel3: //fvelocity 3\n return pbar*pbar*get_thermal_dF(Ebar,T, QMu, type);\n break;\n default:\n std::cerr << \"\\033[1mTFastReso.cpp::get_initial_Fj\\033[0m : \\033[1;31merror\\033[0m : wrong index \" << (int) j << std::endl;\n exit(EXIT_FAILURE);\n }\n}\n//! Transformation rule factor A for Fj in a 2-body decay\n//! Here you can add additional rules for fj's\ndouble get_factor_Aj(EFjIndex j, double Qw, double Ew, double Ebar, double pbar, double Ma, double pw)\n{\n\n// double A= (Ma*Eabc/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar/pbar);\n// double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb);\n \n switch( j){\n case EFjIndex::kFeq1: // feq 1\n return Qw/pw;\n break;\n case EFjIndex::kFeq2: // feq 2\n return pbar/pw*Ew/Ebar;\n break;\n case EFjIndex::kFshear1: // fshear 1\n return Qw/pw*(2.5*Qw/pw*Qw/pw-1.5);\n break;\n case EFjIndex::kFshear2: // fshear 2\n return Qw/pw;\n break;\n case EFjIndex::kFshear3: // fshear 3\n return (1.5*Qw/pw*Qw/pw-0.5)*Ew/Ebar*pbar/pw;\n break;\n case EFjIndex::kFbulk1: // fbulk 1\n return Qw/pw;\n break;\n case EFjIndex::kFbulk2: // fbulk 2\n return pbar/pw*Ew/Ebar;\n break;\n case EFjIndex::kFtemp1: // ftemperature 1\n return Qw/pw;\n break;\n case EFjIndex::kFtemp2: // ftemperature 2\n return pbar/pw*Ew/Ebar;\n break;\n case EFjIndex::kFvel1: // fvelocity 1\n return 1.5*Qw/pw*Qw/pw-0.5;\n break;\n case EFjIndex::kFvel2: // fvelocity 2\n return 1;\n break;\n case EFjIndex::kFvel3: // fvelocity 3\n return pbar/pw*Qw/pw*Ew/Ebar;\n break;\n default:\n std::cerr << \"\\033[1mTFastReso.cpp::get_factor_Aj\\033[0m : \\033[1;31merror\\033[0m : wrong index \" << (int) j << std::endl;\n exit(EXIT_FAILURE);\n }\n}\n\n//! Parameters for integration of thermal distribution\nstruct thermal_params{\n double m;\n double Tfo;\n double QMu; \n EParticleType type;\n};\n//! Thermal distribution function for integration over vbar=[0,1]\ndouble get_F_p_dvbar(double vbar, void * p) {\n double &m = ((struct thermal_params *) p)->m;\n double &Tfo = ((struct thermal_params *) p)->Tfo;\n double &QMu = ((struct thermal_params *) p)->QMu;\n EParticleType &type = ((struct thermal_params *) p)->type;\n double Ebar=m/sqrt(1-vbar*vbar);\n double pbar=vbar*Ebar;\n double F_p = get_thermal_F(Ebar,Tfo,QMu, type);\n return F_p*pbar*pbar*4*M_PI*m/pow(2*M_PI*sqrt(1-vbar*vbar),3);\n}\n//! Parameters for integration of two body decay function\nstruct twobody_params{\n double Ebar;\n double Ma;\n double Mb;\n double Mc;\n TParticle * Parent;\n EFjIndex index; \n}; \n//! Integrand of two body decay formula for f_j components\ndouble get_F_pu_dw(double w, void * p) {\n double &Ebar = ((struct twobody_params *) p)->Ebar;\n double &Ma = ((struct twobody_params *) p)->Ma;\n double &Mb = ((struct twobody_params *) p)->Mb;\n double &Mc = ((struct twobody_params *) p)->Mc;\n TParticle *Parent = ((struct twobody_params *) p)->Parent;\n EFjIndex &index = ((struct twobody_params *) p)->index;\n\n double Eabc = get_Eabc(Ma,Mb,Mc);\n double pabc = get_p(Eabc, Mb); \n //double pbar = GSL_MAX(get_p(Ebar, Mb),DBL_EPSILON); \n double pbar = get_p(Ebar, Mb);// ,DBL_EPSILON); \n double Ebar_old = Ebar*Eabc*Ma/Mb/Mb-w*pbar*pabc*Ma/Mb/Mb;\n //double Ebar_old = pbar*pabc*Ma/Mb/Mb*(1-w);\n //double Ebar_old = pbar*pabc/Ma*u;\n double F_old=Parent->get_Fj( (int) index, Ebar_old);\n double Qw= (Ma*Eabc*pbar/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar);\n //double Qw = pabc/Ma*u;\n// double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb);\n double A = get_factor_Aj(index, Qw, Ebar_old, Ebar, pbar, Ma,sqrt(Qw*Qw+(1-w*w)*Ma*Ma/Mb/Mb*pabc*pabc));\n return F_old*A;\n}\ndouble get_F_pu_du(double u, void * p) {\n double &Ebar = ((struct twobody_params *) p)->Ebar;\n double &Ma = ((struct twobody_params *) p)->Ma;\n double &Mb = ((struct twobody_params *) p)->Mb;\n double &Mc = ((struct twobody_params *) p)->Mc;\n TParticle *Parent = ((struct twobody_params *) p)->Parent;\n EFjIndex &index = ((struct twobody_params *) p)->index;\n\n double Eabc = get_Eabc(Ma,Mb,Mc);\n double pabc = get_p(Eabc, Mb); \n //double pbar = GSL_MAX(get_p(Ebar, Mb),DBL_EPSILON); \n double pbar = get_p(Ebar, Mb);// ,DBL_EPSILON); \n //double Ebar_old = Ebar*Eabc*Ma/Mb/Mb-w*pbar*pabc*Ma/Mb/Mb;\n //double Ebar_old = pbar*pabc*Ma/Mb/Mb*(1-w);\n if (pbar==0) { return 0;};\n double Ebar_old = Ma/2*(pbar/pabc+pabc/pbar)+u*Ma;\n double F_old=Parent->get_Fj((int) index, Ebar_old);\n //double Qw= (Ma*Eabc/Mb/Mb-w*Ma*pabc/Mb/Mb*Ebar/pbar);\n double Qw = Ma/2/pbar*(pbar*pbar/pabc-pabc)+Ma*u;\n// double Ew= (Ma*Eabc*Ebar/Mb/Mb-w*Ma*pabc*pbar/Mb/Mb);\n double A = get_factor_Aj(index, Qw, Ebar_old, Ebar, pbar, Ma,sqrt(Qw*Qw+2*u*pabc/pbar*Ma*Ma));\n return F_old*A/(pbar*pabc/Ma/Ma);\n}\n\n//! Parameters for three body decay mass integral\nstruct threebody_params{\n gsl_function *twobody_function;\n double Mc;\n double Md;\n gsl_integration_workspace *twobody_workspace;\n};\n\n//! Integrand for three body decay normalization\ndouble get_B_dm(double mct, void * p) {\n gsl_function *twobody_function = ((struct threebody_params *) p)->twobody_function;\n double &Ma = ((struct twobody_params *) twobody_function->params)->Ma;\n double &Mb = ((struct twobody_params *) twobody_function->params)->Mb;\n double &Mc = ((struct threebody_params *) p)->Mc;\n double &Md = ((struct threebody_params *) p)->Md;\n return get_pabc(Ma,Mb,mct)*get_pabc(mct, Mc, Md);\n}\n//! Integrand for three body decay function\ndouble get_F_pu_dm(double mct, void * p) {\n gsl_function *twobody_function = ((struct threebody_params *) p)->twobody_function;\n ((struct twobody_params *) twobody_function->params)->Mc = mct;\n gsl_integration_workspace *twobody_workspace = ((struct threebody_params *) p)->twobody_workspace;\n double &Ma = ((struct twobody_params *) twobody_function->params)->Ma;\n double &Mb = ((struct twobody_params *) twobody_function->params)->Mb;\n double &Mc = ((struct threebody_params *) p)->Mc;\n double &Md = ((struct threebody_params *) p)->Md;\n double result,error;\n\n using namespace qag_params;\n int status = gsl_integration_qag (twobody_function, -1, 1, fEpsAbs,fEpsRel, fLimit,fKey ,twobody_workspace, &result, &error); \n // Check status of integration and reduce accuracy if failing\n if (status) { \n status = gsl_integration_qag (twobody_function, -1, 1, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15,twobody_workspace, &result, &error); \n if (status) { \n status = gsl_integration_qag (twobody_function, -1, 1, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15,twobody_workspace, &result, &error); \n if (status) { std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31merror\\033[0m : integration failure! status = \" <twobody_function;\n ((struct twobody_params *) twobody_function->params)->Mc = mct;\n gsl_integration_workspace *twobody_workspace = ((struct threebody_params *) p)->twobody_workspace;\n double &Ma = ((struct twobody_params *) twobody_function->params)->Ma;\n double &Mb = ((struct twobody_params *) twobody_function->params)->Mb;\n double &Mc = ((struct threebody_params *) p)->Mc;\n double &Md = ((struct threebody_params *) p)->Md;\n double result,error;\n\n using namespace qag_params;\n int status = gsl_integration_qagiu (twobody_function, 0.0, fEpsAbs,fEpsRel, fLimit,twobody_workspace, &result, &error); \n // Check status of integration and reduce accuracy if failing\n if (status) { \n status = gsl_integration_qagiu (twobody_function, 0.0, fEpsAbs,1e-4, fLimit,twobody_workspace, &result, &error); \n if (status) { \n status = gsl_integration_qagiu (twobody_function, 0.0, 1e-4,1e-4, fLimit,twobody_workspace, &result, &error); \n if (status) { std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31merror\\033[0m : integration failure! status = \" << gsl_strerror (status )<< \". \" << result << \"+_\" << error << std::endl;\n exit(EXIT_FAILURE); \n }else {\n std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31mwarning\\033[0m : reduced relative and absolute error (1e-4) integration. Result = \" << result << \"+-\" << error <Child1 + Child2\nvoid do_2bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, double BranchingRatio){\n using namespace qag_params;\n\n gsl_integration_workspace * fWorkspace2body ;\n fWorkspace2body = gsl_integration_workspace_alloc (fLimit);\n Parent->lock();\n double Ma = Parent->getM();\n double Mb = Child1->getM();\n double Mc = Child2->getM();\n double nua = Parent->getNu();\n double nub = Child1->getNu();\n double Ebar=0.0;\n Child1->clean_buffer();\n if (Ma < Mb+Mc) {\n std::cerr << \"\\033[1mTFastReso.cpp::do_2bodydecays\\033[0m : \\033[1;31merror\\033[0m : father particle lighter than childern! \" << Ma << \" < \" << Mb+Mc << std::endl;\n exit(EXIT_FAILURE);\n }\n gsl_function func2body;\n if (Mb==0) {\n func2body.function = get_F_pu_du;\n } else {\n func2body.function = get_F_pu_dw;\n }\n twobody_params params = {Ebar, Ma, Mb, Mc, Parent, EFjIndex::kFeq1};\n func2body.params = ¶ms;\n double error, result ;\n int sym=1 ;\n if (Child1==Child2 ){ sym=2; } else { sym=1; }\n\n double Nfather = Parent->getN();\n //! add fraction of the total yield to child\n Child1->addN(BranchingRatio*Nfather*sym);\n for (int i=0; i < Child1->getNpbar(); i++){\n double Ebar =Child1->getEbar(i);\n params.Ebar =Ebar;\n\n //for (int j=0; j < grid_params::fNf ; j++){\n for(auto j: Parent->fComponents) {\n params.index =j;\n double fac = 0;\n if (Mb==0) {\nint status = gsl_integration_qagiu (&func2body, 0.0, fEpsAbs,fEpsRel, fLimit ,fWorkspace2body, &result, &error); \n\n // Check status of integration and reduce accuracy if failing\n if (status) { \nstatus = gsl_integration_qagiu (&func2body, 0.0, fEpsAbs,1e-4, fLimit ,fWorkspace2body, &result, &error); \n if (status) { \nstatus = gsl_integration_qagiu (&func2body, 0.0, 1e-4,1e-4, fLimit ,fWorkspace2body, &result, &error); \n if (status) { std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31merror\\033[0m : integration failure! status = \" << gsl_strerror (status )<< \". \" << result << \"+_\" << error << std::endl;\n exit(EXIT_FAILURE); \n }else {\n std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31mwarning\\033[0m : reduced relative and absolute error (1e-4) integration. Result = \" << result << \"+-\" << error <addFj((int) j,i, fac*result);\n\n }\n }\n //if (Child1==\"pi0139plu\" ) { getParticle(Child1)->print_buffer(Child1+\"_\"+Parent+\"_\"+Child2);}\n gsl_integration_workspace_free (fWorkspace2body);\n\n}\n\n//! Perform three body decay integral Parent->Child1 + Child2 + Child3\nvoid do_3bodydecay(TParticle * Parent, TParticle * Child1, TParticle * Child2, TParticle * Child3, double BranchingRatio){\n using namespace qag_params;\n gsl_integration_workspace * fWorkspace2body ;\n gsl_integration_workspace * fWorkspace3body ;\n fWorkspace2body = gsl_integration_workspace_alloc (fLimit);\n fWorkspace3body = gsl_integration_workspace_alloc (fLimit);\n Parent->lock();\n double Ma = Parent->getM();\n double Mb = Child1->getM();\n double Mc = Child2->getM();\n double Md = Child3->getM();\n double nua = Parent->getNu();\n double nub = Child1->getNu();\n double Ebar=0.0;\n\n Child1->clean_buffer();\n if (Ma < Mb+Mc+Md) {\n std::cerr << \"\\033[1mTFastReso.cpp::do_3bdoydecays\\033[0m : \\033[1;31merror\\033[0m : father particle lighter than childern! \" << Ma << \" < \" << Mb+Mc+Md << std::endl;\n exit(EXIT_FAILURE);\n }\n gsl_function func2body;\n gsl_function func3body;\n if (Mb==0) {\n func2body.function = get_F_pu_du;\n } else {\n func2body.function = get_F_pu_dw;\n }\n func3body.function = get_B_dm;\n twobody_params params2 = {Ebar, Ma, Mb, Mc+Md, Parent, EFjIndex::kFeq1};\n func2body.params = ¶ms2;\n threebody_params params3 = {&func2body, Mc,Md, fWorkspace2body};\n func3body.params = ¶ms3;\n double error, result ;\n int status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,fEpsRel, fLimit,fKey ,fWorkspace3body, &result, &error); \n // Check status of integration and reduce accuracy if failing\n if (status) { \n status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); \n if (status) { \n status =gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); \n if (status) { std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31merror\\033[0m : integration failure! status = \" << gsl_strerror (status )<< \". \" << result << \"+_\" << error << std::endl;\n exit(EXIT_FAILURE); \n }else {\n std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31mwarning\\033[0m : reduced relative and absolute error (1e-4) integration. Result = \" << result << \"+-\" << error <getN();\n // add fraction of yield to child\n Child1->addN(BranchingRatio*Nfather*sym);\n for (int i=0; i < Child1->getNpbar(); i++){\n double Ebar =Child1->getEbar(i);\n params2.Ebar =Ebar;\n //for (int j=0; j < grid_params::fNf ; j++){\n for(auto j: Parent->fComponents) {\n params2.index =j;\n int status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,fEpsRel, fLimit,fKey ,fWorkspace3body, &result, &error); \n // Check status of integration and reduce accuracy if failing\n if (status) { \n status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, fEpsAbs,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); \n if (status) { \n status = gsl_integration_qag (&func3body, Mc+Md, Ma-Mb, 1e-4,1e-4, fLimit,GSL_INTEG_GAUSS15 ,fWorkspace3body, &result, &error); \n if (status) { std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31merror\\033[0m : integration failure! status = \" << gsl_strerror (status )<< \". \" << result << \"+_\" << error << std::endl;\n exit(EXIT_FAILURE); \n }else {\n std::cerr << \"\\033[1mTFastReso_formulas.h\\033[0m : \\033[1;31mwarning\\033[0m : reduced relative and absolute error (1e-4) integration. Result = \" << result << \"+-\" << error <addFj((int) j,i, fac*result);\n\n }\n }\n\n\n //if (Child1==\"pi0139plu\" ) { getParticle(Child1)->print_buffer(Child1+\"_\"+Parent+\"_\"+Child2+\"_\"+Child3);}\n gsl_integration_workspace_free (fWorkspace2body);\n gsl_integration_workspace_free (fWorkspace3body);\n}\n\n\n#endif\n", "meta": {"hexsha": "a5f1d28467534230bb1a36879c57887bddd435fe", "size": 22429, "ext": "h", "lang": "C", "max_stars_repo_path": "TFastReso_formulas.h", "max_stars_repo_name": "amazeliauskas/FastReso", "max_stars_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-11T02:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T14:25:58.000Z", "max_issues_repo_path": "TFastReso_formulas.h", "max_issues_repo_name": "amazeliauskas/FastReso", "max_issues_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "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": "TFastReso_formulas.h", "max_forks_repo_name": "amazeliauskas/FastReso", "max_forks_repo_head_hexsha": "a694de368e79e3d21afa5d57b47209d5c9c55ed9", "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.3188679245, "max_line_length": 206, "alphanum_fraction": 0.6540639351, "num_tokens": 7450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4894293260345463}} {"text": "/*\n * Adapted from bits and pieces in https://code.google.com/p/eq-polar-alignment/\n * Could not find copyright statement from there, but license seems to be GPLv3...\n *\n * Copyright 2014, Kalle Vahlman, zuh@iki.fi\n * Licensed under the GNU GPL v3\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct coord\n{\n double ra;\n double dec;\n double x;\n double y;\n};\n\nstruct state\n{\n anwcs_t* h_wcs;\n anwcs_t* v_wcs;\n double pixel_scale;\n struct coord ncp;\n struct coord polaris;\n struct coord lambda;\n struct coord axis;\n\n};\n\ndouble julian_date()\n{\n time_t now = time(NULL);\n struct tm *t = localtime(&now);\n int day = t->tm_mday;\n int month = t->tm_mon+1;\n int year = 1900 + t->tm_year;\n\n return 367*year-7*(year+(month+9)/12)/4-3*((year+(month-9)/7)/100+1)/4+275*month/9+day+1721029;\n}\n\nint calculate_ncp (double julian, struct coord *c)\n{\n double t, zeta, theta;\n if (c == NULL)\n return 0;\n\n t = (julian-2451545)/36525;\n zeta = (2306.2181*t+0.30188*t*t+0.017998*t*t*t)/3600;\n theta = (2004.3109*t-0.42665*t*t-0.041833*t*t*t)/3600;\n c->dec = 90 - theta;\n c->ra = -zeta;\n\n return 1;\n}\n\nint solve_field(struct state *ps, const char *dir, const char *in, const char *out)\n{\n char run[512];\n // TODO: Run the solving with code rather than system()\n#define SOLVE \"solve-field -B none -M none -S none -R none -U none -N none \" \\\n \"--no-plots --temp-dir %s --dir %s --out %s \" \\\n \"--downsample 2 --ra %.4f --dec %.4f --radius 10 %s\"\n sprintf(run, SOLVE, dir, dir, out, ps->ncp.ra, ps->ncp.dec, in);\n printf(\"%s\\n\", run);\n return system(run);\n}\n\nint fvec(const gsl_vector *x, void *params, gsl_vector *f)\n{\n struct state *s = (struct state *)params;\n double ra, dec, xp, yp;\n double xi = gsl_vector_get(x, 0);\n double yi = gsl_vector_get(x, 1);\n\n anwcs_pixelxy2radec(s->h_wcs, xi, yi, &ra, &dec);\n anwcs_radec2pixelxy(s->v_wcs, ra, dec, &xp, &yp);\n xp = xp - xi;\n yp = yp - yi;\n gsl_vector_set(f, 0, xp);\n gsl_vector_set(f, 1, yp);\n\n return GSL_SUCCESS;\n}\n\nint solve_axis(struct state *ps)\n{\n int s;\n size_t iter=0;\n const size_t n=2;\n gsl_multiroot_fsolver *solver;\n gsl_multiroot_function f = { &fvec, n, ps};\n gsl_vector *x = gsl_vector_alloc(n);\n\n gsl_vector_set(x, 0, ps->polaris.x);\n gsl_vector_set(x, 1, ps->polaris.y);\n solver = gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrids, 2);\n gsl_multiroot_fsolver_set(solver, &f, x);\n do {\n iter++;\n s = gsl_multiroot_fsolver_iterate(solver);\n if (s) break;\n s = gsl_multiroot_test_residual(solver->f,1e-7);\n } while (s == GSL_CONTINUE && iter < 1000);\n ps->axis.x = gsl_vector_get(solver->x, 0);\n ps->axis.y = gsl_vector_get(solver->x, 1);\n\n gsl_multiroot_fsolver_free(solver);\n gsl_vector_free(x);\n return s;\n}\n\n#define MAX(a, b) a < b ? b : a\n\nint plot(struct state *ps, char *in, char *out)\n{\n char convert[2048];\n double arcmin = 60/ps->pixel_scale;\n double cropwidth = MAX(400, 120 * arcmin);\n double cropheight = MAX(400, 120 * arcmin);\n double cropx = ps->ncp.x - cropwidth/2;\n double cropy = ps->ncp.y - cropheight/2;\n int fontsize = ps->pixel_scale < 24 ? 16 : 8;\n\n#define CONVERT \"convert -fill none \" \\\n \"-pointsize %d \" \\\n \"-font Courier -stroke cyan \" \\\n \"-draw 'point %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-stroke red \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'circle %.0f,%.0f %.0f,%.0f' \" \\\n \"-stroke white \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-font Symbol -fill white \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-fill none \" \\\n \"-stroke orange \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-draw 'line %.0f,%.0f %.0f,%.0f' \" \\\n \"-font Symbol -fill orange \" \\\n \"-draw \\\"text %.0f,%.0f '%s'\\\" \" \\\n \"-fill none \" \\\n \"-font Courier -stroke white -fill white \" \\\n \"-draw \\\"text %.0f,%.0f 'Current pixel offset from NCP: %.0f, %.0f'\\\" \" \\\n \"-draw \\\"text %.0f,%.0f '%s %s %s %s'\\\" \" \\\n \"-crop '%.0fx%.0f+%.0f+%.0f' \" \\\n \"%s %s\"\n\n sprintf(convert, CONVERT, fontsize,\n // Target circles\n ps->ncp.x, ps->ncp.y,\n ps->ncp.x, ps->ncp.y, ps->ncp.x+2*arcmin, ps->ncp.y,\n ps->ncp.x, ps->ncp.y, ps->ncp.x+5*arcmin, ps->ncp.y,\n ps->ncp.x, ps->ncp.y, ps->ncp.x+10*arcmin, ps->ncp.y,\n ps->ncp.x, ps->ncp.y, ps->ncp.x+20*arcmin, ps->ncp.y,\n ps->ncp.x, ps->ncp.y, ps->ncp.x+40*arcmin, ps->ncp.y,\n ps->ncp.x-2*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? \"2\\\\'\" : \"\",\n ps->ncp.x-5*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? \"5\\\\'\" : \"\",\n ps->ncp.x-10*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? \"10\\\\'\" : \"\",\n ps->ncp.x-20*arcmin+2, ps->ncp.y, \"20\\\\'\",\n ps->ncp.x-40*arcmin+2, ps->ncp.y, \"40\\\\'\",\n // Current axis\n ps->axis.x-5*arcmin, ps->axis.y-5*arcmin, ps->axis.x+5*arcmin, ps->axis.y+5*arcmin,\n ps->axis.x-5*arcmin, ps->axis.y+5*arcmin, ps->axis.x+5*arcmin, ps->axis.y-5*arcmin,\n ps->axis.x, ps->axis.y, ps->axis.x+2*arcmin, ps->axis.y,\n ps->axis.x, ps->axis.y, ps->axis.x+5*arcmin, ps->axis.y,\n // Polaris\n ps->polaris.x, ps->polaris.y-1*arcmin,\n ps->polaris.x, ps->polaris.y+1*arcmin,\n ps->polaris.x-1*arcmin, ps->polaris.y,\n ps->polaris.x+1*arcmin, ps->polaris.y,\n ps->polaris.x+1*arcmin, ps->polaris.y-1*arcmin, \"a\",\n // λ UMi\n ps->lambda.x, ps->lambda.y-1*arcmin,\n ps->lambda.x, ps->lambda.y+1*arcmin,\n ps->lambda.x-1*arcmin, ps->lambda.y,\n ps->lambda.x+1*arcmin, ps->lambda.y,\n ps->lambda.x+1*arcmin, ps->lambda.y-1*arcmin, \"l\",\n // Offset report\n cropx + 16, cropy + 32, ps->ncp.x-ps->axis.x, ps->ncp.y-ps->axis.y,\n cropx + 16, cropy + 64,\n (ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)\n ? \"Well done, perfect alignment!\"\n : \"Adjust mount alignment to\",\n (ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)\n ? \"\"\n : ps->ncp.x < ps->axis.x ? \"left\" : \"right\",\n (ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y) ? \"\" : \"and\",\n (ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)\n ? \"\"\n : ps->ncp.y < ps->axis.y ? \"up\" : \"down\",\n // Crop\n cropwidth, cropheight, cropx, cropy,\n in, out);\n\n printf(\"%s\\n\", convert);\n return system(convert);\n}\n\nint main (int argc, char **argv)\n{\n char dir[20] = \"/tmp/polar-XXXXXX\";\n char h_dst[30];\n char v_dst[30];\n sip_t *sip;\n struct state ps = { NULL, NULL, 0,\n { 0, 0, 0, 0 }, // NCP\n { 37.9529, 89.2642, 0, 0 }, // Polaris\n { 259.2367, 89.0378, 0, 0 }, // λ UMi\n { 0, 0, 0, 0 } // axis\n };\n\n if (argc < 3) {\n printf(\"E: Not enough parameters!\\n\");\n printf(\"Usage: %s [output]\\n\", argv[0]);\n return -1;\n }\n\n if (mkdtemp(dir) == NULL) {\n printf(\"E: Could not create working directory!\\n\");\n return -1;\n }\n\n // Calculate current ra,dec position of North Celestial Pole\n calculate_ncp(julian_date(), &ps.ncp);\n\n // Solve horizontal and vertical images of Polaris and Lambda UMi\n sprintf(h_dst, \"%s/h.wcs\", dir);\n sprintf(v_dst, \"%s/v.wcs\", dir);\n solve_field(&ps, dir, argv[1], \"h.wcs\");\n solve_field(&ps, dir, argv[2], \"v.wcs\");\n\n // Pick pixel coordinates from horizontal image\n ps.h_wcs = anwcs_open(h_dst, 0);\n anwcs_radec2pixelxy(ps.h_wcs, ps.polaris.ra, ps.polaris.dec, &ps.polaris.x, &ps.polaris.y);\n anwcs_radec2pixelxy(ps.h_wcs, ps.lambda.ra, ps.lambda.dec, &ps.lambda.x, &ps.lambda.y);\n anwcs_radec2pixelxy(ps.h_wcs, ps.ncp.ra, ps.ncp.dec, &ps.ncp.x, &ps.ncp.y);\n\n // Solve rotational axis in pixel coordinates of the horizontal image\n ps.v_wcs = anwcs_open(v_dst, 0);\n solve_axis(&ps);\n anwcs_pixelxy2radec(ps.h_wcs, ps.axis.x, ps.axis.y, &ps.axis.ra, &ps.axis.dec);\n anwcs_free(ps.v_wcs);\n\n // Grab pixel scale from horizontal image\n sip = anwcs_get_sip(ps.h_wcs);\n ps.pixel_scale = sip_pixel_scale(sip);\n anwcs_free(ps.h_wcs);\n\n // Print what we found\n printf(\"Pixel scale: %.4f\\n\", ps.pixel_scale);\n printf(\"Polaris: %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\\n\",\n ps.lambda.ra, ps.lambda.dec, ps.lambda.x, ps.lambda.y);\n printf(\"λ UMi : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\\n\",\n ps.polaris.ra, ps.polaris.dec, ps.polaris.x, ps.polaris.y);\n printf(\"NCP : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\\n\",\n ps.ncp.ra, ps.ncp.dec, ps.ncp.x, ps.ncp.y);\n printf(\"Axis : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\\n\",\n ps.axis.ra, ps.axis.dec, ps.axis.x, ps.axis.y);\n printf(\"Offset : %4.0f x, %4.0f y\\n\",\n ps.ncp.x-ps.axis.x, ps.ncp.y-ps.axis.y);\n\n // Plot a chart of the polar alignment, if user asks for it\n if (argc == 4)\n plot(&ps, argv[1], argv[3]);\n\n return 0;\n}\n", "meta": {"hexsha": "5515141bfd3b70832de14c563a95e653416ce473", "size": 9810, "ext": "c", "lang": "C", "max_stars_repo_path": "polar-plot/polar-plot.c", "max_stars_repo_name": "zuh/starflow", "max_stars_repo_head_hexsha": "61bf261c7921d289e0bb9addb0a22b219e895503", "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": "polar-plot/polar-plot.c", "max_issues_repo_name": "zuh/starflow", "max_issues_repo_head_hexsha": "61bf261c7921d289e0bb9addb0a22b219e895503", "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": "polar-plot/polar-plot.c", "max_forks_repo_name": "zuh/starflow", "max_forks_repo_head_hexsha": "61bf261c7921d289e0bb9addb0a22b219e895503", "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": 33.9446366782, "max_line_length": 99, "alphanum_fraction": 0.54617737, "num_tokens": 3537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.48939962853107966}} {"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 multi-steps.c\n * \\brief Source file to define the multi-steps 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 \"config.h\"\n#include \"utils.h\"\n#include \"equation.h\"\n#include \"method.h\"\n#include \"runge-kutta.h\"\n#include \"multi-steps.h\"\n\n#define DEBUG_MULTI_STEPS 0 ///< macro to debug the multi-steps functions.\n\n///> array of a coefficients of the 2nd order multi-steps method. \nconst long double ms_a2[3] = { 0.75L, 0.L, 0.25L };\n\n///> array of c coefficients of the 2nd order multi-steps method. \nconst long double ms_c2[3] = { 2.L, 0.L, 0.L };\n\n///> array of error a coefficients of the 2nd order multi-steps method. \nconst long double ms_ea2[3] = { 0.25L, 0.L, -0.25L };\n\n///> array of error b coefficients of the 2nd order multi-steps method. \nconst long double ms_eb2[3] = { 0.5L, 0.L, 0.L };\n\n\n///> array of a coefficients of the 3rd order multi-steps method. \nconst long double ms_a3[4] = { 16.L / 27.L, 0.L, 0.L, 11.L / 27.L };\n\n///> array of c coefficients of the 3rd order multi-steps method. \nconst long double ms_c3[4] = { 3.L, 0.L, 0.L, 12.L / 11.L };\n\n///> array of error a coefficients of the 3rd order multi-steps method. \nconst long double ms_ea3[4] = { 17.L / 108.L, 0.L, 0.25L, -11.L / 27.L };\n\n///> array of error b coefficients of the 3rd order multi-steps method. \nconst long double ms_eb3[4] = { -5.L / 18.L, 0.L, 0.L, -4.L / 9.L };\n\n/**\n * Function to init the multi-steps method coefficients.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nmulti_steps_init (MultiSteps * ms) ///< MultiSteps struct.\n{\n Method *m;\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_init: start\\n\");\n#endif\n m = MULTI_STEPS_METHOD (ms);\n switch (ms->type)\n {\n case 1:\n method_init (m, 3, 2);\n ms->a = ms_a2;\n ms->c = ms_c2;\n ms->ea = ms_ea2;\n ms->eb = ms_eb2;\n break;\n case 2:\n method_init (m, 4, 3);\n ms->a = ms_a3;\n ms->c = ms_c3;\n ms->ea = ms_ea3;\n ms->eb = ms_eb3;\n break;\n default:\n printf (\"Error reading multi-steps data\\n\");\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_init: error\\n\");\n fprintf (stderr, \"multi_steps_init: end\\n\");\n#endif\n return 0;\n }\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_init: success\\n\");\n fprintf (stderr, \"multi_steps_init: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to init the variables used by the multi-steps methods.\n */\nvoid\nmulti_steps_init_variables (MultiSteps * ms)\n{\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_init_variables: start\\n\");\n#endif\n runge_kutta_init_variables (MULTI_STEPS_RUNGE_KUTTA (ms));\n method_init_variables (MULTI_STEPS_METHOD (ms));\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_init_variables: end\\n\");\n#endif\n}\n\n/**\n * Function to perform a step of the multi-steps method.\n */\nstatic inline void\nmulti_steps_step (MultiSteps * ms, ///< MultiSteps struct.\n Equation * eq, ///< Equation struct.\n long double t, ///< actual time.\n long double dt) ///< time step size.\n{\n long double msr0[3], msr1[3];\n Method *m;\n const long double *a;\n const long double *c;\n unsigned int i, n;\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_step: start\\n\");\n#endif\n m = MULTI_STEPS_METHOD (ms);\n#if DEBUG_MULTI_STEPS\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r0[0][%u]=%Lg\\n\", i, m->r0[0][i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r1[0][%u]=%Lg\\n\", i, m->r1[0][i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r2[0][%u]=%Lg\\n\", i, m->r2[0][i]);\n#endif\n n = m->nsteps;\n a = ms->a;\n c = ms->c;\n#if DEBUG_MULTI_STEPS\n for (i = 0; i < n; ++i)\n fprintf (stderr, \"multi_steps_step: a%u=%Lg\\n\", i, a[i]);\n for (i = 0; i < n; ++i)\n fprintf (stderr, \"multi_steps_step: c%u=%Lg\\n\", i, c[i]);\n#endif\n msr0[0] = a[0] * (r0[0] + dt * c[0] * r1[0]);\n msr0[1] = a[0] * (r0[1] + dt * c[0] * r1[1]);\n msr0[2] = a[0] * (r0[2] + dt * c[0] * r1[2]);\n msr1[0] = a[0] * (r1[0] + dt * c[0] * r2[0]);\n msr1[1] = a[0] * (r1[1] + dt * c[0] * r2[1]);\n msr1[2] = a[0] * (r1[2] + dt * c[0] * r2[2]);\n for (i = 1; i < n; ++i)\n {\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_step: r0[%u][0]=%Lg\\n\", i, m->r0[i][0]);\n fprintf (stderr, \"multi_steps_step: r0[%u][1]=%Lg\\n\", i, m->r0[i][1]);\n fprintf (stderr, \"multi_steps_step: r0[%u][2]=%Lg\\n\", i, m->r0[i][2]);\n fprintf (stderr, \"multi_steps_step: r1[%u][0]=%Lg\\n\", i, m->r1[i][0]);\n fprintf (stderr, \"multi_steps_step: r1[%u][1]=%Lg\\n\", i, m->r1[i][1]);\n fprintf (stderr, \"multi_steps_step: r1[%u][2]=%Lg\\n\", i, m->r1[i][2]);\n fprintf (stderr, \"multi_steps_step: r2[%u][0]=%Lg\\n\", i, m->r2[i][0]);\n fprintf (stderr, \"multi_steps_step: r2[%u][1]=%Lg\\n\", i, m->r2[i][1]);\n fprintf (stderr, \"multi_steps_step: r2[%u][2]=%Lg\\n\", i, m->r2[i][2]);\n#endif\n msr0[0] += a[i] * (m->r0[i][0] + dt * c[i] * m->r1[i][0]);\n msr0[1] += a[i] * (m->r0[i][1] + dt * c[i] * m->r1[i][1]);\n msr0[2] += a[i] * (m->r0[i][2] + dt * c[i] * m->r1[i][2]);\n msr1[0] += a[i] * (m->r1[i][0] + dt * c[i] * m->r2[i][0]);\n msr1[1] += a[i] * (m->r1[i][1] + dt * c[i] * m->r2[i][1]);\n msr1[2] += a[i] * (m->r1[i][2] + dt * c[i] * m->r2[i][2]);\n }\n#if DEBUG_MULTI_STEPS\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r0[0][%u]=%Lg\\n\", i, msr0[i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r1[0][%u]=%Lg\\n\", i, msr1[i]);\n#endif\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 for (i = n; --i > 0;)\n {\n memcpy (m->r0[i], m->r0[i - 1], 3 * sizeof (long double));\n memcpy (m->r1[i], m->r1[i - 1], 3 * sizeof (long double));\n memcpy (m->r2[i], m->r2[i - 1], 3 * sizeof (long double));\n }\n memcpy (r0, msr0, 3 * sizeof (long double));\n memcpy (r1, msr1, 3 * sizeof (long double));\n equation_acceleration (eq, r0, r1, r2, t + dt);\n#if DEBUG_MULTI_STEPS\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r0[0][%u]=%Lg\\n\", i, r0[i]);\n for (i = 0; i < 3; ++i)\n fprintf (stderr, \"multi_steps_step: r1[0][%u]=%Lg\\n\", i, r1[i]);\n fprintf (stderr, \"multi_steps_step: end\\n\");\n#endif\n}\n\n/**\n * Function to estimate the error on a multi-steps method step.\n */\nstatic inline void\nmulti_steps_error (MultiSteps * ms, ///< MultiSteps 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_MULTI_STEPS\n fprintf (stderr, \"multi_steps_error: start\\n\");\n#endif\n m = MULTI_STEPS_METHOD (ms);\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] += ms->ea[i] * m->r0[i][0] + dt * ms->eb[i] * m->r1[i][0];\n e0[1] += ms->ea[i] * m->r0[i][1] + dt * ms->eb[i] * m->r1[i][1];\n e0[2] += ms->ea[i] * m->r0[i][2] + dt * ms->eb[i] * m->r1[i][2];\n e1[0] += ms->ea[i] * m->r1[i][0] + dt * ms->eb[i] * m->r2[i][0];\n e1[1] += ms->ea[i] * m->r1[i][1] + dt * ms->eb[i] * m->r2[i][1];\n e1[2] += ms->ea[i] * m->r1[i][2] + dt * ms->eb[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_MULTI_STEPS\n fprintf (stderr, \"multi_steps_error: e0=%Lg et0=%Lg\\n\", m->e0, m->et0);\n fprintf (stderr, \"multi_steps_error: e1=%Lg et1=%Lg\\n\", m->e1, m->et1);\n fprintf (stderr, \"multi_steps_error: end\\n\");\n#endif\n}\n\n/**\n * Function to run the multi-steps method bucle.\n *\n * \\return final time. \n */\nlong double\nmulti_steps_run (MultiSteps * ms, ///< MultiSteps struct.\n Equation * eq) ///< Equation struct.\n{\n RungeKutta *rk;\n Method *m, *mrk;\n long double t, dt, to, dto, et0o, et1o;\n unsigned int i, n;\n\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_run: start\\n\");\n#endif\n\n // variables backup \n rk = MULTI_STEPS_RUNGE_KUTTA (ms);\n mrk = RUNGE_KUTTA_METHOD (rk);\n m = MULTI_STEPS_METHOD (ms);\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 first steps\n n = m->nsteps;\n for (t = 0.L, i = n; --i > 0;)\n {\n\n // time step size\n if (t > 0.L && mrk->error_dt)\n {\n dto = dt;\n dt = method_dt (mrk, dt);\n\n // revert the step if big error\n if (dt < mrk->beta * dto)\n {\n ++i;\n t = to;\n mrk->et0 = et0o;\n mrk->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 goto end;\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_run: t=%Lg dt=%Lg\\n\", t, dt);\n#endif\n\n // saving step \n memcpy (m->r0[i], r0, 3 * sizeof (long double));\n memcpy (m->r1[i], r1, 3 * sizeof (long double));\n memcpy (m->r2[i], r2, 3 * sizeof (long double));\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 (mrk->error_dt)\n {\n et0o = mrk->et0;\n et1o = mrk->et1;\n runge_kutta_error (rk, dt);\n }\n }\n\n // saving last step \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\n // initing errors\n m->et0 = mrk->et0;\n m->et1 = mrk->et1;\n\n // temporal bucle\n while (1)\n {\n\n // time step size\n if (m->error_dt)\n {\n dto = dt;\n dt = method_dt (m, dt);\n\n // revert the step if big error\n if (dt < mrk->beta * dto)\n {\n ++i;\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 dto = dt;\n if (equation_land (eq, to, &t, &dt))\n break;\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_run: t=%Lg dt=%Lg\\n\", t, dt);\n#endif\n\n // variables backup\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 // multi-steps step\n if (dto == dt)\n multi_steps_step (ms, eq, to, dt);\n else\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 multi_steps_error (ms, dt);\n }\n }\nend:\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_run: end\\n\");\n#endif\n return t;\n}\n\n/**\n * Function to free the memory used by a MultiSteps struct.\n */\nvoid\nmulti_steps_delete (MultiSteps * ms) ///< RungeKutta struct.\n{\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_delete: start\\n\");\n#endif\n runge_kutta_delete (MULTI_STEPS_RUNGE_KUTTA (ms));\n method_delete (MULTI_STEPS_METHOD (ms));\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_delete: end\\n\");\n#endif\n}\n\n/**\n * Function to read on a XML node the multi-steps method input data.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nmulti_steps_read_xml (MultiSteps * ms, ///< MultiSteps struct.\n xmlNode * node) ///< XML node.\n{\n\tchar *message[] = {\n\t\tNULL,\n\t\t\"Bad steps number\",\n\t\t\"Bad numerical method data\",\n\t\t\"No Runge-Kutta XML node\",\n\t\t\"Bad Runge-Kutta XML node\",\n\t\t\"Bad Runge-Kutta method data\",\n\t\t\"Bad multi-steps data\"\n\t};\n int e, error_code;\n#if DEBUG_MULTI_STEPS\n fprintf (stderr, \"multi_steps_read_xml: start\\n\");\n#endif\n ms->type = xml_node_get_uint (node, XML_TYPE, &error_code);\n if (error_code || !ms->type)\n e = 1;\n\telse if (!method_read_xml (MULTI_STEPS_METHOD (ms), node))\n e = 2;\n else\n\t {\n\t\t\tnode = node->children;\n\t\t\tif (!node)\n\t\t\t\te = 3;\n\t\t\telse if (xmlStrcmp (node->name, XML_RUNGE_KUTTA))\n\t\t\t\te = 4;\n\t\t\telse if (!runge_kutta_read_xml (MULTI_STEPS_RUNGE_KUTTA (ms), node))\n\t\t\t\te = 5;\n\t\t\telse if (!multi_steps_init (ms))\n\t\t\t\te = 6;\n\t\t\telse\n\t\t\t\te = 0;\n\t\t}\n\tif (e)\n\t{\n\t\terror_add (message[e]);\n\t\te = 0;\n\t}\n\telse\n\t\te = 1;\n#if DEBUG_MULTI_STEPS\n if (e)\n fprintf (stderr, \"multi_steps_read: success\\n\");\n else\n fprintf (stderr, \"multi_steps_read: error\\n\");\n fprintf (stderr, \"multi_steps_read: end\\n\");\n#endif\n return e;\n}\n", "meta": {"hexsha": "2995736a45796cdbae5390e3a0247a968c3e1379", "size": 14585, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/multi-steps.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/multi-steps.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/multi-steps.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": 30.2593360996, "max_line_length": 80, "alphanum_fraction": 0.5784024683, "num_tokens": 5037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.48931481774683183}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"imshift.h\"\n#include \"conv1.h\"\n\nvoid showMatrix(double * I, size_t M, size_t N)\n{\n for(size_t kk = 0; kk1)\n K[0][kk] = a*ax*ax*ax -5*a*ax*ax +8*a*ax -4*a;\n if(ax>2)\n K[0][kk] = 0;\n }\n return 0;\n }\n\n return -2;\n}\n\nint main(int argc, char ** argv)\n{\n\n printf(\"Running %s\\n\", argv[0]);\n\n if(argc>1)\n printf(\"Warning: unused command line arguments\\n\");\n\n {\n printf(\"--> Testing kernels\\n\");\n double * K;\n double sum;\n\n for(double delta = -.5; delta < .6; delta+=.1) {\n for(int method = 1; method < 4; method = method +2)\n {\n K = NULL;\n size_t nK = 0;\n assert(generateShift(&K, delta, &nK, 3)==0);\n\n sum = 0;\n for(int kk = 0; kk<(int) nK; kk++)\n sum += K[kk];\n\n printf(\"delta: %f order: %d sum: %f\\n\", delta, method, sum);\n\n free(K);\n }\n }\n }\n\n\n {\n printf(\"--> Testing 1D\\n\");\n double delta = .3;\n size_t N = 10;\n double * V = malloc(N*sizeof(double));\n\n for(size_t kk=0; kk. \r\n\r\n The Python interface is written by Davide Albanese .\r\n (C) 2009 mlpy Developers.\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n*/\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#define SQRT_2 1.4142135623730951\r\n\r\n\r\nvoid\r\nuwt_forward (double *V, int n, int j,\r\n\t double *h, double *g, int l,\r\n\t double *Wj, double *Vj)\r\n{\r\n int t, k, z;\r\n double k_div;\r\n\r\n for(t = 0; t < n; t++)\r\n {\r\n k = t;\r\n Wj[t] = h[0] * V[k];\r\n Vj[t] = g[0] * V[k];\r\n \r\n for(z = 1; z < l; z++)\r\n\t{\r\n\t k -= (int) pow(2, (j - 1));\r\n\t \r\n\t k_div = -k / (double) n;\r\n\t \r\n\t if(k < 0) \r\n\t k += (int) ceil(k_div) * n;\r\n\t \r\n\t Wj[t] += h[z] * V[k];\r\n\t Vj[t] += g[z] * V[k];\r\n\t} \r\n }\r\n}\r\n\r\n\r\nvoid\r\nuwt_backward (double *W, double *V, int j,\r\n\t int n, double *h, double *g,\r\n\t int l, double *Vj)\r\n{\r\n int t, k, z;\r\n double k_div;\r\n\r\n for(t = 0; t < n; t++)\r\n {\r\n k = t;\r\n Vj[t] = h[0] * W[k] + g[0] * V[k];\r\n \r\n for(z = 1; z < l; z++)\r\n\t{\r\n\t k += (int) pow(2, (j - 1));\r\n\t k_div = (double) k / (double) n;\r\n\t \r\n\t if(k >= n)\r\n\t k -= (int) floor(k_div) * n;\r\n\t \r\n\t Vj[t] += h[z] * W[k] + g[z] * V[k];\r\n\t}\r\n }\r\n}\r\n\r\n\r\nstatic PyObject *uwt_uwt(PyObject *self, PyObject *args, PyObject *keywds)\r\n{\r\n PyObject *x = NULL; PyObject *xa = NULL;\r\n PyObject *Xa = NULL;\r\n int levels = 0;\r\n char wf;\r\n\r\n int i, k, j, n, J;\r\n \r\n double *_x;\r\n double *_X;\r\n\r\n double *v;\r\n double *wj, *vj;\r\n double *h, *g;\r\n\r\n npy_intp Xa_dims[2];\r\n\r\n gsl_wavelet *wave;\r\n \r\n\r\n /* Parse Tuple*/\r\n static char *kwlist[] = {\"x\", \"wf\", \"k\", \"levels\", NULL};\r\n if (!PyArg_ParseTupleAndKeywords(args, keywds, \"Oci|i\", kwlist, &x, &wf, &k, &levels))\r\n return NULL;\r\n\r\n xa = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_IN_ARRAY);\r\n if (xa == NULL) return NULL;\r\n \r\n n = (int) PyArray_DIM(xa, 0);\r\n _x = (double *) PyArray_DATA(xa);\r\n \r\n switch (wf)\r\n {\r\n case 'd':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered, k);\r\n break;\r\n \r\n case 'h':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_haar_centered, k);\r\n break;\r\n\r\n case 'b':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_bspline_centered, k);\r\n break;\r\n\r\n default:\r\n PyErr_SetString(PyExc_ValueError, \"wavelet family is not valid\");\r\n return NULL;\r\n }\r\n\r\n h = (double *) malloc(wave->nc * sizeof(double));\r\n g = (double *) malloc(wave->nc * sizeof(double));\r\n \r\n for(i=0; inc; i++)\r\n {\r\n h[i] = wave->h1[i] / SQRT_2;\r\n g[i] = wave->g1[i] / SQRT_2;\r\n }\r\n\r\n if (levels == 0)\r\n J = (int) floor(log(((n-1) / (wave->nc-1)) + 1) / log(2));\r\n else\r\n J = levels;\r\n\r\n Xa_dims[0] = (npy_intp) (2 * J);\r\n Xa_dims[1] = PyArray_DIM(xa, 0);\r\n Xa = PyArray_SimpleNew(2, Xa_dims, NPY_DOUBLE);\r\n _X = (double *) PyArray_DATA(Xa);\r\n\r\n v = _x;\r\n for(j=0; jnc, wj, vj);\r\n v = vj;\r\n }\r\n \r\n gsl_wavelet_free(wave);\r\n free(h);\r\n free(g);\r\n Py_DECREF(xa);\r\n\r\n return Py_BuildValue(\"N\", Xa);\r\n}\r\n\r\n\r\nstatic PyObject *uwt_iuwt(PyObject *self, PyObject *args, PyObject *keywds)\r\n{\r\n PyObject *X = NULL; PyObject *Xa = NULL;\r\n \r\n PyObject *xa = NULL;\r\n \r\n char wf;\r\n int i, k, n, J;\r\n double *w1, *v1;\r\n\r\n double *_X;\r\n double *_x;\r\n double *h, *g;\r\n\r\n npy_intp xa_dims[1];\r\n\r\n gsl_wavelet *wave;\r\n \r\n /* Parse Tuple*/\r\n static char *kwlist[] = {\"X\", \"wf\", \"k\", NULL};\r\n if (!PyArg_ParseTupleAndKeywords(args, keywds, \"Oci\", kwlist, &X, &wf, &k))\r\n return NULL;\r\n\r\n Xa = PyArray_FROM_OTF(X, NPY_DOUBLE, NPY_IN_ARRAY);\r\n if (Xa == NULL) return NULL;\r\n \r\n n = (int) PyArray_DIM(Xa, 1);\r\n J = ((int) PyArray_DIM(Xa, 0)) / 2;\r\n \r\n _X = (double *) PyArray_DATA(Xa);\r\n \r\n switch (wf)\r\n {\r\n case 'd':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_daubechies, k);\r\n break;\r\n \r\n case 'h':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_haar, k);\r\n break;\r\n\r\n case 'b':\r\n wave = gsl_wavelet_alloc (gsl_wavelet_bspline, k);\r\n break;\r\n\r\n default:\r\n PyErr_SetString(PyExc_ValueError, \"wavelet family is not valid\");\r\n return NULL;\r\n }\r\n\r\n h = (double *) malloc(wave->nc * sizeof(double));\r\n g = (double *) malloc(wave->nc * sizeof(double));\r\n \r\n for(i=0; inc; i++)\r\n {\r\n h[i] = wave->h2[i] / SQRT_2;\r\n g[i] = wave->g2[i] / SQRT_2;\r\n }\r\n\r\n w1 = _X;\r\n v1 = _X + (J * n);\r\n\r\n xa_dims[0] = (npy_intp) n; \r\n xa = PyArray_SimpleNew(1, xa_dims, NPY_DOUBLE);\r\n _x = (double *) PyArray_DATA(xa);\r\n\r\n uwt_backward (w1, v1, 1, n, g, h, wave->nc, _x);\r\n \r\n gsl_wavelet_free(wave);\r\n free(h);\r\n free(g);\r\n Py_DECREF(Xa);\r\n\r\n return Py_BuildValue(\"N\", xa);\r\n}\r\n\r\n\r\n/* Doc strings: */\r\nstatic char module_doc[] = \"Undecimated Wavelet Transform Module\";\r\n\r\nstatic char uwt_uwt_doc[] =\r\n \"Undecimated Wavelet Tranform\\n\\n\"\r\n \":Parameters:\\n\"\r\n \" x : 1d array_like object (the length is restricted to powers of two)\\n\"\r\n \" data\\n\"\r\n \" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\\n\"\r\n \" wavelet family\\n\"\r\n \" k : int\\n\"\r\n \" member of the wavelet family\\n\\n\"\r\n \" * daubechies: k = 4, 6, ..., 20 with k even\\n\"\r\n \" * haar: the only valid choice of k is k = 2\\n\"\r\n \" * bspline: k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\\n\\n\"\r\n \" levels : int\\n\"\r\n \" level of the decomposition (J).\\n\"\r\n \" If levels = 0 this is the value J such that the length of X\\n\"\r\n \" is at least as great as the length of the level J wavelet filter,\\n\"\r\n \" but less than the length of the level J+1 wavelet filter.\\n\"\r\n \" Thus, j <= log_2((n-1)/(l-1)+1), where n is the length of x\\n\\n\"\r\n \":Returns:\\n\"\r\n \" X : 2d numpy array (2J * len(x))\\n\"\r\n \" misaligned scaling and wavelet coefficients::\\n\\n\"\r\n \" [[wavelet coefficients W_1]\\n\"\r\n \" [wavelet coefficients W_2]\\n\"\r\n \" :\\n\"\r\n \" [wavelet coefficients W_J]\\n\"\r\n \" [scaling coefficients V_1]\\n\"\r\n \" [scaling coefficients V_2]\\n\"\r\n \" :\\n\"\r\n \" [scaling coefficients V_J]]\"\r\n ;\r\n\r\nstatic char uwt_iuwt_doc[] =\r\n \"Inverse Undecimated Wavelet Tranform\\n\\n\"\r\n \":Parameters:\\n\"\r\n \" X : 2d array_like object (the length is restricted to powers of two)\\n\"\r\n \" misaligned scaling and wavelet coefficients\\n\"\r\n \" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\\n\"\r\n \" wavelet family\\n\"\r\n \" k : int\\n\"\r\n \" member of the wavelet family\\n\\n\"\r\n \" * daubechies: k = 4, 6, ..., 20 with k even\\n\"\r\n \" * haar: the only valid choice of k is k = 2\\n\"\r\n \" * bspline: k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\\n\\n\"\r\n \":Returns:\\n\"\r\n \" x : 1d numpy array\\n\"\r\n \" data\"\r\n ;\r\n\r\n\r\n/* Method table */\r\nstatic PyMethodDef uwt_methods[] = {\r\n {\"uwt\",\r\n (PyCFunction)uwt_uwt,\r\n METH_VARARGS | METH_KEYWORDS,\r\n uwt_uwt_doc},\r\n {\"iuwt\",\r\n (PyCFunction)uwt_iuwt,\r\n METH_VARARGS | METH_KEYWORDS,\r\n uwt_iuwt_doc},\r\n {NULL, NULL, 0, NULL}\r\n};\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\n\r\nstatic struct PyModuleDef moduledef = {\r\n PyModuleDef_HEAD_INIT,\r\n \"_uwt\",\r\n module_doc,\r\n -1,\r\n uwt_methods,\r\n NULL, NULL, NULL, NULL\r\n};\r\n\r\nPyObject *PyInit__uwt(void)\r\n{\r\n PyObject *m;\r\n m = PyModule_Create(&moduledef);\r\n if (!m) {\r\n return NULL;\r\n }\r\n\r\n import_array();\r\n\r\n return m;\r\n}\r\n\r\n#else\r\n\r\nPyMODINIT_FUNC init_uwt(void)\r\n{\r\n PyObject *m;\r\n \r\n m = Py_InitModule3(\"_uwt\", uwt_methods, module_doc);\r\n if (m == NULL) {\r\n return;\r\n }\r\n \r\n import_array();\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "03afb7a8f4cbc849c8e61b02f3c832fd22ee7004", "size": 8641, "ext": "c", "lang": "C", "max_stars_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/uwt.c", "max_stars_repo_name": "xuanxiaoliqu/CRC4Docker", "max_stars_repo_head_hexsha": "5ee26f9a590b727693202d8ad3b6460970304bd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T12:02:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T12:02:08.000Z", "max_issues_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/uwt.c", "max_issues_repo_name": "TonyZPW/CRC4Docker", "max_issues_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea", "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/mlpy-3.5.0/mlpy/wavelet/uwt.c", "max_forks_repo_name": "TonyZPW/CRC4Docker", "max_forks_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea", "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.8044077135, "max_line_length": 89, "alphanum_fraction": 0.5466959843, "num_tokens": 2852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.48893164203042233}} {"text": "/*\n NAME:\n calc_splitnmerge\n PURPOSE:\n calculates the split and merge hierarchy after an proj_EM convergence\n CALLING SEQUENCE:\n calc_splitnmerge(struct datapoint * data,int N,\n struct gaussian * gaussians, int K, gsl_matrix * qij, \n int * snmhierarchy){\n INPUT:\n data - the data\n N - number of data points\n gaussians - model gaussians\n K - number of gaussians\n qij - matrix of log(posterior likelihoods)\n bs - bs from previous EM estimate\n OUTPUT:\n snmhierarchy - the hierarchy, first row has the highest prioriry, \n goes down from there\n REVISION HISTORY:\n 2008-09-21 - Written Bovy\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid calc_splitnmerge(struct datapoint * data,int N,\n\t\t struct gaussian * gaussians, int K, \n\t\t gsl_matrix * qij, int * snmhierarchy){\n gsl_matrix * tempqij = gsl_matrix_alloc(N,K);\n gsl_matrix_memcpy(tempqij,qij);\n gsl_matrix * Jmerge = gsl_matrix_alloc(K,K);\n gsl_matrix_set_all(Jmerge,-1.);\n int kk1, kk2, kk, ii,maxsnm= K*(K-1)*(K-2)/2;\n int d = (gaussians->VV)->size1;//dim of mm\n double temp1,temp2,temp;\n for (kk1 = 0; kk1 != K; ++kk1)\n for (kk2 = kk1+1; kk2 != K; ++kk2){\n temp = 0.;\n for (ii=0; ii != N; ++ii){\n\t//make them all exps\n\ttemp1 = exp(gsl_matrix_get(qij,ii,kk1));\n\ttemp2 = exp(gsl_matrix_get(qij,ii,kk2));\n\ttemp += temp1*temp2;\n }\n gsl_matrix_set(Jmerge,kk1,kk2,temp);\n }\n\n //Then calculate Jsplit\n gsl_vector * Jsplit = gsl_vector_alloc(K);\n gsl_vector * Jsplit_temp = gsl_vector_alloc(K);\n gsl_vector_set_all(Jsplit,-1.);\n //if there is missing data, fill in the missing data\n struct missingdatapoint{\n gsl_vector *ww;\n };\n struct missingdatapoint * missingdata;\n missingdata = (struct missingdatapoint *) malloc(N * sizeof (struct missingdatapoint) );\n for (ii=0; ii != N; ++ii){\n missingdata->ww = gsl_vector_alloc(d);\n ++missingdata;\n }\n missingdata -= N;\n\n gsl_matrix * tempRR,* tempVV;\n gsl_vector * tempSS,* tempwork;\n gsl_vector * expectedww = gsl_vector_alloc(d);\n //gsl_vector_view tempUcol;\n double lambda;\n int di,signum;\n for (ii=0; ii != N; ++ii){\n //First check whether there is any missing data\n if ((data->ww)->size == d){\n gsl_vector_memcpy(missingdata->ww,data->ww);\n ++missingdata;\n ++data;\n continue;\n }\n\n /*AS IT STANDS THE MISSING DATA PART IS *NOT* IMPLEMENTED CORRECTLY: \n A CORRECT IMPLEMENTATION NEEDS THE NULL SPACE OF THE PROJECTION \n MATRIX WHICH CAN BE FOUND FROM THE FULL SINGULAR VALUE DECOMPOSITIIN, \n UNFORTUNATELY GSL DOES NOT COMPUTE THE FULL SVD, BUT ONLY THE THIN SVD. \n LAPACK MIGHT DO, BUT MIGHT NOT BE INSTALLED (?) AND THIS MIGHT BE HARD TO IMPLEMENT.\n\n INDICATED BELOW ARE THE SECTION THAT WOULD HAVE TO BE FIXED TO MAKE THIS WORK\n */\n\n //calculate expectation, for this we need to calculate the bbijs (EXACTLY THE SAME AS IN PROJ_EM, SHOULD WRITE GENERAL FUNCTION TO DO THIS)\n gsl_vector_set_zero(expectedww);\n for (kk = 0; kk != K; ++kk){\n //prepare...\n di = (data->SS)->size1;\n p = gsl_permutation_alloc (di);\n wminusRm = gsl_vector_alloc (di);\n gsl_vector_memcpy(wminusRm,data->ww);\n TinvwminusRm = gsl_vector_alloc (di);\n Tij = gsl_matrix_alloc(di,di);\n gsl_matrix_memcpy(Tij,data->SS);\n Tij_inv = gsl_matrix_alloc(di,di);\n VRT = gsl_matrix_alloc(d,di);\n VRTTinv = gsl_matrix_alloc(d,di);\n Rtrans = gsl_matrix_alloc(d,di);\n //Calculate Tij\n gsl_matrix_transpose_memcpy(Rtrans,data->RR);\n gsl_blas_dsymm(CblasLeft,CblasUpper,1.0,gaussians->VV,Rtrans,0.0,VRT);//Only the upper right part of VV is calculated\n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,data->RR,VRT,1.0,Tij);//This is Tij\n //Calculate LU decomp of Tij and Tij inverse\n gsl_linalg_LU_decomp(Tij,p,&signum);\n gsl_linalg_LU_invert(Tij,p,Tij_inv);\n //Calculate Tijinv*(w-Rm)\n gsl_blas_dgemv(CblasNoTrans,-1.0,data->RR,gaussians->mm,1.0,wminusRm);\n gsl_blas_dsymv(CblasUpper,1.0,Tij_inv,wminusRm,0.0,TinvwminusRm);\n //Now calculate bij and Bij\n gsl_vector_memcpy(bs->bbij,gaussians->mm);\n gsl_blas_dgemv(CblasNoTrans,1.0,VRT,TinvwminusRm,1.0,bs->bbij);\n //..and add the result to expectedww\n gsl_vector_scale(bs->bbij,exp(gsl_matrix_get(qij,ii,kk)));\n gsl_vector_add(expectedww,bs->bbij);\n //Clean up\n gsl_permutation_free (p);\n gsl_vector_free(wminusRm);\n gsl_vector_free(TinvwminusRm);\n gsl_matrix_free(Tij);\n gsl_matrix_free(Tij_inv);\n gsl_matrix_free(VRT);\n gsl_matrix_free(VRTTinv);\n gsl_matrix_free(Rtrans);\n ++gaussians;\n }\n gaussians -= K;\n //if missing, fill in the missing data\n tempRR = gsl_matrix_alloc((data->RR)->size2,(data->RR)->size1);//will hold the transpose of RR\n //tempVV = gsl_matrix_alloc((data->RR)->size1,(data->RR)->size1);\n //tempSS = gsl_vector_alloc((data->RR)->size1);\n //tempwork = gsl_vector_alloc((data->RR)->size1);\n gsl_matrix_transpose_memcpy(tempRR,data->RR);\n gsl_blas_dgemv(CblasNoTrans,1.,tempRR,data->ww,0.,missingdata->ww);\n //gsl_linalg_SV_decomp(tempRR,tempVV,tempSS,tempwork);\n //compute the missing data THIS PART IS NOT IMPLEMENTED CORRECTLY\n //for (kk = 0; kk != d-(data->ww)->size; ++kk){\n //tempUcol = gsl_matrix_column(tempRR,d-1-kk);\n //gsl_blas_ddot(&(tempUcol.vector),expectedww,&lambda);\n //gsl_vector_scale(&(tempUcol.vector),lambda);\n //gsl_vector_add(missingdata->ww,&(tempUcol.vector));\n //}\n ++missingdata;\n ++data;\n //free\n gsl_matrix_free(tempRR);\n //gsl_matrix_free(tempVV);\n //gsl_vector_free(tempSS);\n //gsl_vector_free(tempwork);\n }\n data -= N;\n missingdata -= N;\n\n //then for every gaussian, calculate the KL divergence between the local data density and the l-th gaussian\n double tempsplit;\n p = gsl_permutation_alloc (d);\n tempVV= gsl_matrix_alloc(d,d);\n tempRR= gsl_matrix_alloc(d,d);\n tempSS= gsl_vector_alloc(d);\n tempwork= gsl_vector_alloc(d);\n for (kk = 0; kk != K; ++kk){\n //calculate qil/ql factors\n normalize_row(tempqij,kk,false,true,0.);\n //calculate inverse of V and det(V)\n gsl_matrix_memcpy(tempVV,gaussians->VV);\n gsl_linalg_LU_decomp(tempVV,p,&signum);\n gsl_linalg_LU_invert(tempVV,p,tempRR);//tempRR now has the inverse of VV\n tempsplit = d * halflogtwopi + 0.5 * gsl_linalg_LU_lndet(tempVV);\n for (ii=0; ii != N; ++ii){\n if (exp(gsl_matrix_get(tempqij,ii,kk)) == 0.){\n\t++missingdata;\n\tcontinue;\n }\n tempsplit += gsl_matrix_get(tempqij,ii,kk) * exp(gsl_matrix_get(tempqij,ii,kk));\n gsl_vector_memcpy(tempSS,gaussians->mm);\n gsl_vector_scale(tempSS,-1.);\n gsl_vector_add(tempSS,missingdata->ww);\n gsl_blas_dgemv(CblasNoTrans,1.0,tempRR,tempSS,0.,tempwork);\n gsl_blas_ddot(tempSS,tempwork,&lambda);\n tempsplit += 0.5 * exp(gsl_matrix_get(tempqij,ii,kk)) * lambda;\n ++missingdata;\n }\n gsl_vector_set(Jsplit,kk,tempsplit);\n //printf(\"Jsplit for gaussian %i = %f\\n\",kk,tempsplit);\n missingdata -= N;\n ++gaussians;\n }\n gaussians -= K;\n\n //free\n gsl_permutation_free(p);\n gsl_matrix_free(tempRR);\n gsl_matrix_free(tempVV);\n gsl_vector_free(tempSS);\n gsl_vector_free(tempwork);\n \n\n //and put everything in the hierarchy\n size_t maxj, maxk, maxl;\n for (kk1 = 0; kk1 != maxsnm; kk1 += (K-2)){\n gsl_matrix_max_index(Jmerge,&maxj,&maxk);\n gsl_vector_memcpy(Jsplit_temp,Jsplit);\n gsl_vector_set(Jsplit_temp,maxj,-1.);\n gsl_vector_set(Jsplit_temp,maxk,-1.);\n for (kk2=0; kk2 != K-2; ++kk2){\n maxl = gsl_vector_max_index(Jsplit_temp);\n gsl_vector_set(Jsplit_temp,maxl,-1.);\n *(snmhierarchy++)= maxj;\n *(snmhierarchy++)= maxk;\n *(snmhierarchy++)= maxl;\n //printf(\"j = %i, k = %i, l = %i\\n\",(int)maxj,(int)maxk,(int)maxl);\n }\n //then set it to zero and find the next\n gsl_matrix_set(Jmerge,maxj,maxk,-1.);\n }\n snmhierarchy -= 3*maxsnm;\n \n\n\n //clean up\n gsl_matrix_free(Jmerge);\n gsl_vector_free(Jsplit);\n gsl_vector_free(Jsplit_temp);\n\n return ;\n}\n", "meta": {"hexsha": "645bcb5889c458081422ba8a18c9d2fc8150c305", "size": 8310, "ext": "c", "lang": "C", "max_stars_repo_path": "src/calc_splitnmerge.c", "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_issues_repo_path": "src/calc_splitnmerge.c", "max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_forks_repo_path": "src/calc_splitnmerge.c", "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "avg_line_length": 35.3617021277, "max_line_length": 143, "alphanum_fraction": 0.6641395909, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4888014330710104}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the implementation of the Fourier domain response for LIGO-VIRGO detectors.\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"LLVgeometry.h\"\n#include \"struct.h\"\n#include \"LLVFDresponse.h\"\n#include \"timeconversion.h\"\n\n\n/************************************************************/\n/********* Functions setting detector geometry **************/\n\n/* Function setting the response matrix of a given detector, in cartesian coordinates */\nvoid SetMatrixD(\n gsl_matrix* D, /* Output: matrix of the detector response Dij */\n const Detectortag tag) /* Tag identifying the detector */\n{\n /* Allocating and defining the cartesian unit vectors along the two arms */\n gsl_vector* nx = gsl_vector_alloc(3);\n gsl_vector* ny = gsl_vector_alloc(3);\n if(tag==LHO) {\n gsl_vector_set(nx, 0, LAL_LHO_4K_ARM_X_DIRECTION_X);\n gsl_vector_set(nx, 1, LAL_LHO_4K_ARM_X_DIRECTION_Y);\n gsl_vector_set(nx, 2, LAL_LHO_4K_ARM_X_DIRECTION_Z);\n gsl_vector_set(ny, 0, LAL_LHO_4K_ARM_Y_DIRECTION_X);\n gsl_vector_set(ny, 1, LAL_LHO_4K_ARM_Y_DIRECTION_Y);\n gsl_vector_set(ny, 2, LAL_LHO_4K_ARM_Y_DIRECTION_Z);\n }\n else if(tag==LLO) {\n gsl_vector_set(nx, 0, LAL_LLO_4K_ARM_X_DIRECTION_X);\n gsl_vector_set(nx, 1, LAL_LLO_4K_ARM_X_DIRECTION_Y);\n gsl_vector_set(nx, 2, LAL_LLO_4K_ARM_X_DIRECTION_Z);\n gsl_vector_set(ny, 0, LAL_LLO_4K_ARM_Y_DIRECTION_X);\n gsl_vector_set(ny, 1, LAL_LLO_4K_ARM_Y_DIRECTION_Y);\n gsl_vector_set(ny, 2, LAL_LLO_4K_ARM_Y_DIRECTION_Z);\n }\n else if(tag==VIRGO) {\n gsl_vector_set(nx, 0, LAL_VIRGO_ARM_X_DIRECTION_X);\n gsl_vector_set(nx, 1, LAL_VIRGO_ARM_X_DIRECTION_Y);\n gsl_vector_set(nx, 2, LAL_VIRGO_ARM_X_DIRECTION_Z);\n gsl_vector_set(ny, 0, LAL_VIRGO_ARM_Y_DIRECTION_X);\n gsl_vector_set(ny, 1, LAL_VIRGO_ARM_Y_DIRECTION_Y);\n gsl_vector_set(ny, 2, LAL_VIRGO_ARM_Y_DIRECTION_Z);\n }\n else {\n printf(\"Error: invalid detector tag\\n\");\n exit(1);\n }\n\n /* Setting the components of the matrix D = 1/2 (nx nx - ny ny) */\n for(int i=0; i<3; i++) {\n for(int j=0; j<3; j++) {\n gsl_matrix_set(D, i, j, 1./2*(gsl_vector_get(nx, i)*gsl_vector_get(nx, j) - gsl_vector_get(ny, i)*gsl_vector_get(ny, j)));\n }\n }\n gsl_vector_free(nx);\n gsl_vector_free(ny);\n}\n\n/* Function setting the position of a detector, in cartesian coordinates */\nvoid SetVectorXd(\n gsl_vector* Xd, /* Output: position vector of the detector */\n const Detectortag tag) /* Tag identifying the detector */\n{\n if(tag==LHO) {\n gsl_vector_set(Xd, 0, LAL_LHO_4K_VERTEX_LOCATION_X_SI);\n gsl_vector_set(Xd, 1, LAL_LHO_4K_VERTEX_LOCATION_Y_SI);\n gsl_vector_set(Xd, 2, LAL_LHO_4K_VERTEX_LOCATION_Z_SI);\n }\n else if(tag==LLO) {\n gsl_vector_set(Xd, 0, LAL_LLO_4K_VERTEX_LOCATION_X_SI);\n gsl_vector_set(Xd, 1, LAL_LLO_4K_VERTEX_LOCATION_Y_SI);\n gsl_vector_set(Xd, 2, LAL_LLO_4K_VERTEX_LOCATION_Z_SI);\n }\n else if(tag==VIRGO) {\n gsl_vector_set(Xd, 0, LAL_VIRGO_VERTEX_LOCATION_X_SI);\n gsl_vector_set(Xd, 1, LAL_VIRGO_VERTEX_LOCATION_Y_SI);\n gsl_vector_set(Xd, 2, LAL_VIRGO_VERTEX_LOCATION_Z_SI);\n }\n else {\n printf(\"Error: invalid detector tag\\n\");\n exit(1);\n }\n}\n\n/* Function setting the cartesian coordinates of the wave frame vectors (X,Y,Z), given the position in the sky and polarization */\nvoid SetVectorsXYZ(\n gsl_vector* X, /* Output: cartesian vector of the wave frame unit vector X */\n gsl_vector* Y, /* Output: cartesian vector of the wave frame unit vector Y */\n gsl_vector* Z, /* Output: cartesian vector of the wave frame unit vector Z */\n const double theta, /* First angle for the position in the sky (Earth-based spherical angle) */\n const double phi, /* Second angle for the position in the sky (Earth-based spherical angle) */\n const double psi) /* Polarization angle */\n{\n double cospsi = cos(psi);\n double sinpsi = sin(psi);\n double costheta = cos(theta);\n double sintheta = sin(theta);\n double cosphi = cos(phi);\n double sinphi = sin(phi);\n /* Unit vector X */\n gsl_vector_set(X, 0, -cospsi*sinphi+sinpsi*costheta*cosphi);\n gsl_vector_set(X, 1, cospsi*cosphi+sinpsi*costheta*sinphi);\n gsl_vector_set(X, 2, -sinpsi*sintheta);\n /* Unit vector Y */\n gsl_vector_set(Y, 0, sinpsi*sinphi+cospsi*costheta*cosphi);\n gsl_vector_set(Y, 1, -sinpsi*cosphi+cospsi*costheta*sinphi);\n gsl_vector_set(Y, 2, -cospsi*sintheta);\n /* Unit vector Z */\n gsl_vector_set(Z, 0, -sintheta*cosphi);\n gsl_vector_set(Z, 1, -sintheta*sinphi);\n gsl_vector_set(Z, 2, -costheta);\n}\n\n/***************************************/\n/********* Core functions **************/\n\n/* Function to convert string input network string to Networktag */\nNetworktag ParseNetworktag(char* string) {\n Networktag tag;\n if(strcmp(string, \"L\")==0) tag = L;\n else if(strcmp(string, \"H\")==0) tag = H;\n else if(strcmp(string, \"V\")==0) tag = V;\n else if(strcmp(string, \"LH\")==0) tag = LH;\n else if(strcmp(string, \"LV\")==0) tag = LV;\n else if(strcmp(string, \"HV\")==0) tag = HV;\n else if(strcmp(string, \"LHV\")==0) tag = LHV;\n else {\n printf(\"Error in ParseNetworktag: string not recognized.\\n\");\n exit(1);\n }\n return tag;\n}\n\n/* Function evaluating the Fourier-domain factors for LHV detectors */\n/* Note: in case only one or two detectors are considered, amplitudes for the missing ones are set to 0 */\n/* Contrarily to the LISA case, here returns trivially 0 or 1 */\n/* (allows minimal changes from the old structure that assumed LHV - but not optimal) */\nstatic int EvaluateDetectorFactor3Det(\n double* factor1, /* Output for factor for detector 1 */\n double* factor2, /* Output for factor for detector 2 */\n double* factor3, /* Output for factor for detector 3 */\n const Networktag networktag) /* Selector for the detector network */\n{\n switch(networktag) {\n case L:\n *factor1 = 1.;\n *factor2 = 0;\n *factor3 = 0;\n break;\n case H:\n *factor1 = 0;\n *factor2 = 1.;\n *factor3 = 0;\n break;\n case V:\n *factor1 = 0;\n *factor2 = 0;\n *factor3 = 1.;\n break;\n case LH:\n *factor1 = 1.;\n *factor2 = 1.;\n *factor3 = 0;\n break;\n case LV:\n *factor1 = 1.;\n *factor2 = 0;\n *factor3 = 1.;\n break;\n case HV:\n *factor1 = 0;\n *factor2 = 1.;\n *factor3 = 1.;\n break;\n case LHV:\n *factor1 = 1.;\n *factor2 = 1.;\n *factor3 = 1.;\n break;\n default:\n printf(\"Error in EvaluateDetectorFactor3Det: networktag not recognized.\\n\");\n exit(1);\n }\n return SUCCESS;\n}\n\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response (for a given detector), for given values of the inclination, position in the sky and polarization angle */\nint LLVSimFDResponse(\n struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n struct tagListmodesCAmpPhaseFrequencySeries **lists, /* Output: list of contribution of each mode in the detector signal, in Frequency-domain amplitude and phase form, for the given detector and sky position */\n const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */\n const double ra, /* Position in the sky: J2000.0 right ascension (rad) */\n const double dec, /* Position in the sky: J2000.0 declination (rad) */\n const double inclination, /* Inclination of the source (rad) */\n const double psi, /* Polarization angle (rad) */\n const Detectortag tag) /* Tag identifying the detector */\n{\n /* Define matrix D and position vector Xd of the detector */\n gsl_matrix* D = gsl_matrix_alloc(3,3);\n gsl_vector* Xd = gsl_vector_alloc(3);\n SetVectorXd(Xd, tag);\n SetMatrixD(D, tag);\n\n /* Conversion from (ra, dec) to the Earth-based spherical angles (theta, phi) - neglecting nutation and precession, and identifying UT1 and UTC, so accurate roughly to a second of time */\n double gmst_angle = gmst_angle_from_gpstime(gpstime);\n double theta = PI/2 - dec;\n double phi = ra - gmst_angle;\n\n /* Define waveframe unit vectors (X,Y,Z) */\n gsl_vector* X = gsl_vector_alloc(3);\n gsl_vector* Y = gsl_vector_alloc(3);\n gsl_vector* Z = gsl_vector_alloc(3);\n SetVectorsXYZ(X, Y, Z, theta, phi, psi);\n\n /* Compute the delay from geocenter to the detector */\n double delaylength;\n gsl_blas_ddot(Xd, Z, &delaylength);\n double twopidelay = 2*PI*delaylength/C_SI;\n\n /* Compute the value of pattern functions Fplus, Fcross */\n gsl_vector* DX = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */\n gsl_vector* DY = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */\n gsl_blas_dgemv( CblasNoTrans, 1., D, X, 0, DX);\n gsl_blas_dgemv( CblasNoTrans, 1., D, Y, 0, DY);\n double XDX;\n double XDY;\n double YDY;\n gsl_blas_ddot(X, DX, &XDX);\n gsl_blas_ddot(X, DY, &XDY);\n gsl_blas_ddot(Y, DY, &YDY);\n double Fplus = XDX - YDY;\n double Fcross = 2*XDY;\n\n /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */\n ListmodesCAmpPhaseFrequencySeries* listelement = *listhlm;\n while(listelement) {\n\n /* Definitions: l,m, frequency series and length */\n int l = listelement->l;\n int m = listelement->m;\n CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n gsl_vector* freq = freqseries->freq;\n gsl_vector* amp_real = freqseries->amp_real;\n gsl_vector* amp_imag = freqseries->amp_imag;\n gsl_vector* phase = freqseries->phase;\n int len = (int) freq->size;\n double f;\n double complex camp;\n double complex camps;\n\n /* Computing the Ylm combined factors for plus and cross for this mode */\n /* Capital Phi is set to 0 by convention */\n double complex Yfactorplus;\n double complex Yfactorcross;\n if (!(l%2)) {\n Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n }\n else {\n Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n }\n\n /* Initializing frequency series structure for this mode, for the signal s = F+ h+ + Fx hx */\n CAmpPhaseFrequencySeries *modefreqseriess = NULL;\n CAmpPhaseFrequencySeries_Init(&modefreqseriess, len);\n gsl_vector* freqs = modefreqseriess->freq;\n gsl_vector* amp_reals = modefreqseriess->amp_real;\n gsl_vector* amp_imags = modefreqseriess->amp_imag;\n gsl_vector* phases = modefreqseriess->phase;\n\n /* Loop over the frequencies - multiplying by F+, Fx, and add phase due to the delay from geocenter to the detector */\n double complex factorcamp = Fplus*Yfactorplus + Fcross*Yfactorcross;\n for(int j=0; jnext;\n }\n\n /* Cleaning */\n gsl_matrix_free(D);\n gsl_vector_free(Xd);\n gsl_vector_free(X);\n gsl_vector_free(Y);\n gsl_vector_free(Z);\n gsl_vector_free(DX);\n gsl_vector_free(DY);\n\n return SUCCESS;\n}\n\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response for a given detector network, for given values of the inclination, position in the sky and polarization angle */\n/* Note: as for now, asssumes the three detectors are L,H,V - amplitudes simply set to 0 in those that are not selected by networktag */\nint LLVSimFDResponse3Det(\n struct tagListmodesCAmpPhaseFrequencySeries **list1, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */\n struct tagListmodesCAmpPhaseFrequencySeries **list2, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */\n struct tagListmodesCAmpPhaseFrequencySeries **list3, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */\n struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */\n const double ra, /* Position in the sky: J2000.0 right ascension (rad) */\n const double dec, /* Position in the sky: J2000.0 declination (rad) */\n const double inclination, /* Inclination of the source (rad) */\n const double psi, /* Polarization angle (rad) */\n const Networktag tag) /* Tag identifying the network to use */\n{\n /* Read which detectors are to be included in the network */\n double factor1 = 0;\n double factor2 = 0;\n double factor3 = 0;\n EvaluateDetectorFactor3Det(&factor1, &factor2, &factor3, tag);\n\n /* Define matrix D and position vector Xd for the 3 detectors */\n gsl_matrix* D1 = gsl_matrix_alloc(3,3);\n gsl_matrix* D2 = gsl_matrix_alloc(3,3);\n gsl_matrix* D3 = gsl_matrix_alloc(3,3);\n gsl_vector* Xd1 = gsl_vector_alloc(3);\n gsl_vector* Xd2 = gsl_vector_alloc(3);\n gsl_vector* Xd3 = gsl_vector_alloc(3);\n SetVectorXd(Xd1, LHO);\n SetVectorXd(Xd2, LLO);\n SetVectorXd(Xd3, VIRGO);\n SetMatrixD(D1, LHO);\n SetMatrixD(D2, LLO);\n SetMatrixD(D3, VIRGO);\n\n /* Conversion from (ra, dec) to the Earth-based spherical angles (theta, phi) - neglecting nutation and precession, and identifying UT1 and UTC, so accurate roughly to a second of time */\n double gmst_angle = gmst_angle_from_gpstime(gpstime);\n double theta = PI/2 - dec;\n double phi = ra - gmst_angle;\n\n /* Define waveframe unit vectors (X,Y,Z) */\n gsl_vector* X = gsl_vector_alloc(3);\n gsl_vector* Y = gsl_vector_alloc(3);\n gsl_vector* Z = gsl_vector_alloc(3);\n SetVectorsXYZ(X, Y, Z, theta, phi, psi);\n\n /* Compute the delays from geocenter to each detector */\n double delaylength1 = 0;\n double delaylength2 = 0;\n double delaylength3 = 0;\n gsl_blas_ddot(Xd1, Z, &delaylength1);\n gsl_blas_ddot(Xd2, Z, &delaylength2);\n gsl_blas_ddot(Xd3, Z, &delaylength3);\n double twopidelay1 = 2*PI*delaylength1/C_SI;\n double twopidelay2 = 2*PI*delaylength2/C_SI;\n double twopidelay3 = 2*PI*delaylength3/C_SI;\n\n /* Compute the value of pattern functions Fplus, Fcross for each detector */\n gsl_vector* DX1 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */\n gsl_vector* DY1 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */\n gsl_vector* DX2 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */\n gsl_vector* DY2 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */\n gsl_vector* DX3 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */\n gsl_vector* DY3 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */\n gsl_blas_dgemv( CblasNoTrans, 1., D1, X, 0, DX1);\n gsl_blas_dgemv( CblasNoTrans, 1., D1, Y, 0, DY1);\n gsl_blas_dgemv( CblasNoTrans, 1., D2, X, 0, DX2);\n gsl_blas_dgemv( CblasNoTrans, 1., D2, Y, 0, DY2);\n gsl_blas_dgemv( CblasNoTrans, 1., D3, X, 0, DX3);\n gsl_blas_dgemv( CblasNoTrans, 1., D3, Y, 0, DY3);\n double XDX1 = 0.;\n double XDY1 = 0.;\n double YDY1 = 0.;\n double XDX2 = 0.;\n double XDY2 = 0.;\n double YDY2 = 0.;\n double XDX3 = 0.;\n double XDY3 = 0.;\n double YDY3 = 0.;\n gsl_blas_ddot(X, DX1, &XDX1);\n gsl_blas_ddot(X, DY1, &XDY1);\n gsl_blas_ddot(Y, DY1, &YDY1);\n gsl_blas_ddot(X, DX2, &XDX2);\n gsl_blas_ddot(X, DY2, &XDY2);\n gsl_blas_ddot(Y, DY2, &YDY2);\n gsl_blas_ddot(X, DX3, &XDX3);\n gsl_blas_ddot(X, DY3, &XDY3);\n gsl_blas_ddot(Y, DY3, &YDY3);\n double Fplus1 = XDX1 - YDY1;\n double Fcross1 = 2*XDY1;\n double Fplus2 = XDX2 - YDY2;\n double Fcross2 = 2*XDY2;\n double Fplus3 = XDX3 - YDY3;\n double Fcross3 = 2*XDY3;\n\n /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */\n ListmodesCAmpPhaseFrequencySeries* listelement = *listhlm;\n while(listelement) {\n\n /* Definitions: l,m, frequency series and length */\n int l = listelement->l;\n int m = listelement->m;\n CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n gsl_vector* freq = freqseries->freq;\n gsl_vector* amp_real = freqseries->amp_real;\n gsl_vector* amp_imag = freqseries->amp_imag;\n gsl_vector* phase = freqseries->phase;\n int len = (int) freq->size;\n double f;\n double complex camp;\n double complex camp1;\n double complex camp2;\n double complex camp3;\n\n /* Computing the Ylm combined factors for plus and cross for this mode */\n /* Capital Phi is set to 0 by convention */\n double complex Yfactorplus;\n double complex Yfactorcross;\n if (!(l%2)) {\n Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n }\n else {\n Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n }\n\n /* Initializing frequency series structure for this mode, for the signal s = F+ h+ + Fx hx in each detector */\n CAmpPhaseFrequencySeries *modefreqseries1 = NULL;\n CAmpPhaseFrequencySeries *modefreqseries2 = NULL;\n CAmpPhaseFrequencySeries *modefreqseries3 = NULL;\n CAmpPhaseFrequencySeries_Init(&modefreqseries1, len);\n CAmpPhaseFrequencySeries_Init(&modefreqseries2, len);\n CAmpPhaseFrequencySeries_Init(&modefreqseries3, len);\n gsl_vector* freq1 = modefreqseries1->freq;\n gsl_vector* freq2 = modefreqseries2->freq;\n gsl_vector* freq3 = modefreqseries3->freq;\n gsl_vector* amp_real1 = modefreqseries1->amp_real;\n gsl_vector* amp_real2 = modefreqseries2->amp_real;\n gsl_vector* amp_real3 = modefreqseries3->amp_real;\n gsl_vector* amp_imag1 = modefreqseries1->amp_imag;\n gsl_vector* amp_imag2 = modefreqseries2->amp_imag;\n gsl_vector* amp_imag3 = modefreqseries3->amp_imag;\n gsl_vector* phase1 = modefreqseries1->phase;\n gsl_vector* phase2 = modefreqseries2->phase;\n gsl_vector* phase3 = modefreqseries3->phase;\n\n /* Loop over the frequencies - multiplying by F+, Fx, and add phase due to the delay from geocenter to the detector */\n double complex factorcamp1 = Fplus1*Yfactorplus + Fcross1*Yfactorcross;\n double complex factorcamp2 = Fplus2*Yfactorplus + Fcross2*Yfactorcross;\n double complex factorcamp3 = Fplus3*Yfactorplus + Fcross3*Yfactorcross;\n for(int j=0; jnext;\n }\n\n /* Cleaning */\n gsl_matrix_free(D1);\n gsl_matrix_free(D2);\n gsl_matrix_free(D3);\n gsl_vector_free(Xd1);\n gsl_vector_free(Xd2);\n gsl_vector_free(Xd3);\n gsl_vector_free(X);\n gsl_vector_free(Y);\n gsl_vector_free(Z);\n gsl_vector_free(DX1);\n gsl_vector_free(DX2);\n gsl_vector_free(DX3);\n gsl_vector_free(DY1);\n gsl_vector_free(DY2);\n gsl_vector_free(DY3);\n\n return SUCCESS;\n}\n", "meta": {"hexsha": "ab99925c6a88b32bad6c2d87ac37c41148012b48", "size": 22559, "ext": "c", "lang": "C", "max_stars_repo_path": "LLVsim/LLVFDresponse.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LLVsim/LLVFDresponse.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LLVsim/LLVFDresponse.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 42.0876865672, "max_line_length": 222, "alphanum_fraction": 0.6777339421, "num_tokens": 6591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4885278412455856}} {"text": "/*! @copyright (c) 2017 King Abdullah University of Science and\n * Technology (KAUST). All rights reserved.\n *\n * STARS-H is a software package, provided by King Abdullah\n * University of Science and Technology (KAUST)\n *\n * @file testing/rndtiled.c\n * @version 1.3.0\n * @author Aleksandr Mikhalev\n * @date 2017-11-07\n * */\n\n#ifdef MKL\n #include \n#else\n #include \n #include \n#endif\n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n if(argc != 6)\n {\n printf(\"%d arguments provided, but 5 are needed\\n\", argc-1);\n printf(\"randtlr N NB decay maxrank tol\\n\");\n return 1;\n }\n int N = atoi(argv[1]);\n int block_size = atoi(argv[2]);\n double decay = atof(argv[3]);\n int maxrank = atoi(argv[4]);\n double tol = atof(argv[5]);\n int onfly = 0;\n char symm = 'N', dtype = 'd';\n STARSH_int shape[2] = {N, N};\n int info;\n srand(0);\n // Init STARS-H\n info = starsh_init();\n if(info != 0)\n return info;\n // Generate problem by random matrices\n STARSH_randtlr *data;\n STARSH_kernel *kernel;\n info = starsh_application((void **)&data, &kernel, N, dtype,\n STARSH_RANDTLR, STARSH_RANDTLR_KERNEL1,\n STARSH_RANDTLR_NB, block_size,\n STARSH_RANDTLR_DECAY, decay, STARSH_RANDTLR_DIAG, (double)N, 0);\n if(info != 0)\n {\n printf(\"Problem was NOT generated (wrong parameters)\\n\");\n return info;\n }\n // Init problem with given data and kernel and print short info\n STARSH_problem *P;\n info = starsh_problem_new(&P, 2, shape, symm, dtype, data, data, kernel,\n \"Randomly generated tiled blr-matrix\");\n if(info != 0)\n return info;\n starsh_problem_info(P);\n // Init plain clusterization and print info\n STARSH_cluster *C;\n info = starsh_cluster_new_plain(&C, data, N, block_size);\n if(info != 0)\n return info;\n starsh_cluster_info(C);\n // Init tlr division into admissible blocks and print short info\n STARSH_blrf *F;\n info = starsh_blrf_new_tlr(&F, P, symm, C, C);\n if(info != 0)\n return info;\n starsh_blrf_info(F);\n // Approximate each admissible block\n STARSH_blrm *M;\n double time1 = omp_get_wtime();\n info = starsh_blrm_approximate(&M, F, maxrank, tol, onfly);\n if(info != 0)\n return info;\n time1 = omp_get_wtime()-time1;\n // Print info about updated format and approximation\n starsh_blrf_info(F);\n starsh_blrm_info(M);\n printf(\"TIME TO APPROXIMATE: %e secs\\n\", time1);\n // Measure approximation error\n time1 = omp_get_wtime();\n double rel_err = starsh_blrm__dfe_omp(M);\n time1 = omp_get_wtime()-time1;\n printf(\"TIME TO MEASURE ERROR: %e secs\\nRELATIVE ERROR: %e\\n\",\n time1, rel_err);\n if(rel_err/tol > 10.)\n {\n printf(\"Resulting relative error is too big\\n\");\n return 1;\n }\n // Free block low-rank matrix\n starsh_blrm_free(M);\n // Free block low-rank format\n starsh_blrf_free(F);\n // Free clusterization info\n starsh_cluster_free(C);\n // Free STARS_Problem instance\n starsh_problem_free(P);\n // Free randomly generated data\n starsh_randtlr_free(data);\n return 0;\n}\n", "meta": {"hexsha": "b4068be615b1d1327244cfd1a48f7b2d57ddc4ed", "size": 3335, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/randtlr.c", "max_stars_repo_name": "wawando/stars-h", "max_stars_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "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": "testing/randtlr.c", "max_issues_repo_name": "wawando/stars-h", "max_issues_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "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": "testing/randtlr.c", "max_forks_repo_name": "wawando/stars-h", "max_forks_repo_head_hexsha": "03e11375bf559bc850243c4c38796be21112a5f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T10:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-09T10:54:18.000Z", "avg_line_length": 29.7767857143, "max_line_length": 76, "alphanum_fraction": 0.6248875562, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4884908874520522}} {"text": "/* ----------------------------------------------------------------------------\n JAM_AXI_RMS_WMMT\n \n Calculates weighted second moment.\n \n INPUTS\n xp : projected x' [pc]\n yp : projected y' [pc]\n nxy : number of x' and y' values given\n incl : inclination [radians]\n lum : projected luminous MGE\n pot : projected potential MGE\n beta : velocity anisotropy (1 - vz^2 / vr^2)\n vv : velocity integral selector (1=xx, 2=yy, 3=zz, 4=xy, 5=xz, 6=yz)\n \n NOTES\n * Based on janis2_weighted_second_moment_squared IDL code by Michele\n Cappellari.\n \n Mark den Brok\n Laura L Watkins [lauralwatkins@gmail.com]\n \n This code is released under a BSD 2-clause license.\n If you use this code for your research, please cite:\n Watkins et al. 2013, MNRAS, 436, 2598\n \"Discrete dynamical models of omega Centauri\"\n http://adsabs.harvard.edu/abs/2013MNRAS.436.2598W\n---------------------------------------------------------------------------- */\n\n#include \n#include \n#include \n#include \n#include \n#include \"jam.h\"\n#include \"../mge/mge.h\"\n#include \"../tools/tools.h\"\n\n\ndouble *jam_axi_rms_wmmt( double *xp, double *yp, int nxy, double incl, \\\n struct multigaussexp *lum, struct multigaussexp *pot, \\\n double *beta, int vv , int *gslFlag_rms) {\n \n struct params_rmsint p;\n struct multigaussexp ilum, ipot;\n double ci, si, *kani, *s2l, *q2l, *s2q2l, *s2p, *e2p;\n double result, error, *sb_mu2;\n int i;\n int status = 0;\n \n // convert from projected MGEs to intrinsic MGEs\n ilum = mge_deproject( lum, incl );\n ipot = mge_deproject( pot, incl );\n \n // angles\n ci = cos( incl );\n si = sin( incl );\n \n \n // mge component combinations\n \n kani = (double *) malloc ( lum->ntotal * sizeof( double ) );\n s2l = (double *) malloc( lum->ntotal * sizeof( double ) );\n q2l = (double *) malloc( lum->ntotal * sizeof( double ) );\n s2q2l = (double *) malloc( lum->ntotal * sizeof( double ) );\n s2p = (double *) malloc( pot->ntotal * sizeof( double ) );\n e2p = (double *) malloc( pot->ntotal * sizeof( double ) );\n \n for ( i = 0; i < ilum.ntotal; i++ ) {\n kani[i] = 1. / ( 1. - beta[i] );\n s2l[i] = pow( ilum.sigma[i], 2. );\n q2l[i] = pow( ilum.q[i], 2. );\n s2q2l[i] = s2l[i] * q2l[i];\n }\n \n for ( i = 0; i < ipot.ntotal; i++ ) {\n s2p[i] = pow( ipot.sigma[i], 2. );\n e2p[i] = 1. - pow( ipot.q[i], 2. );\n }\n \n // parameters for the integrand function\n p.ci2 = ci * ci;\n p.si2 = si * si;\n p.cisi = ci * si;\n p.lum = &ilum;\n p.pot = &ipot;\n p.kani = kani;\n p.s2l = s2l;\n p.q2l = q2l;\n p.s2q2l = s2q2l;\n p.s2p = s2p;\n p.e2p = e2p;\n p.vv = vv;\n \n \n // perform integration\n \n gsl_integration_workspace *w = gsl_integration_workspace_alloc( 1000 );\n gsl_function F;\n gsl_set_error_handler_off();\n F.function = &jam_axi_rms_mgeint;\n \n sb_mu2 = (double *) malloc( nxy * sizeof( double ) );\n for ( i = 0; i < nxy; i++ ) {\n p.x2 = xp[i] * xp[i];\n p.y2 = yp[i] * yp[i];\n p.xy = xp[i] * yp[i];\n F.params = &p;\n status += gsl_integration_qag( &F, 0., 1., 0., 1e-5, 1000, 6, w, \\\n &result, &error );\n sb_mu2[i] = result;\n }\n\n /*// if you want to test the gsl flagging thing uncomment these two lines\n int test = 1;\n status += test; \n */\n if (status > 0) { *gslFlag_rms += 1; }\n\n\n gsl_integration_workspace_free( w );\n \n free( kani );\n free( s2l );\n free( q2l );\n free( s2q2l );\n free( s2p );\n free( e2p );\n \n return sb_mu2;\n \n}\n", "meta": {"hexsha": "8fea4889c156aec82be9ecde0ffa2167a211c8b1", "size": 3756, "ext": "c", "lang": "C", "max_stars_repo_path": "src/jam/jam_axi_rms_wmmt.c", "max_stars_repo_name": "tadejaversic/cjam", "max_stars_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/jam/jam_axi_rms_wmmt.c", "max_issues_repo_name": "tadejaversic/cjam", "max_issues_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "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/jam/jam_axi_rms_wmmt.c", "max_forks_repo_name": "tadejaversic/cjam", "max_forks_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2406015038, "max_line_length": 79, "alphanum_fraction": 0.5322151225, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4884063307107272}} {"text": "/* multifit/multiwlinear.c\n * \n * Copyright (C) 2015 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linear_common.c\"\n\n/* General weighted case */ \n\nstatic int\nmultifit_wlinear_svd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n int balance,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n if (X->size1 != y->size)\n {\n GSL_ERROR\n (\"number of observations in y does not match rows of matrix X\",\n GSL_EBADLEN);\n }\n else if (X->size2 != c->size)\n {\n GSL_ERROR (\"number of parameters c does not match columns of matrix X\",\n GSL_EBADLEN);\n }\n else if (w->size != y->size)\n {\n GSL_ERROR (\"number of weights does not match number of observations\",\n GSL_EBADLEN);\n }\n else if (cov->size1 != cov->size2)\n {\n GSL_ERROR (\"covariance matrix is not square\", GSL_ENOTSQR);\n }\n else if (c->size != cov->size1)\n {\n GSL_ERROR\n (\"number of parameters does not match size of covariance matrix\",\n GSL_EBADLEN);\n }\n else if (X->size1 != work->n || X->size2 != work->p)\n {\n GSL_ERROR\n (\"size of workspace does not match size of observation matrix\",\n GSL_EBADLEN);\n }\n else\n {\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n size_t i, j, p_eff;\n\n gsl_matrix *A = work->A;\n gsl_matrix *Q = work->Q;\n gsl_matrix *QSI = work->QSI;\n gsl_vector *S = work->S;\n gsl_vector *t = work->t;\n gsl_vector *xt = work->xt;\n gsl_vector *D = work->D;\n\n /* Scale X, A = sqrt(w) X */\n\n gsl_matrix_memcpy (A, X);\n\n for (i = 0; i < n; i++)\n {\n double wi = gsl_vector_get (w, i);\n\n if (wi < 0)\n wi = 0;\n\n {\n gsl_vector_view row = gsl_matrix_row (A, i);\n gsl_vector_scale (&row.vector, sqrt (wi));\n }\n }\n\n /* Balance the columns of the matrix A if requested */\n\n if (balance) \n {\n gsl_linalg_balance_columns (A, D);\n }\n else\n {\n gsl_vector_set_all (D, 1.0);\n }\n\n /* Decompose A into U S Q^T */\n\n gsl_linalg_SV_decomp_mod (A, QSI, Q, S, xt);\n\n /* Solve sqrt(w) y = A c for c, by first computing t = sqrt(w) y */\n\n for (i = 0; i < n; i++)\n {\n double wi = gsl_vector_get (w, i);\n double yi = gsl_vector_get (y, i);\n if (wi < 0)\n wi = 0;\n gsl_vector_set (t, i, sqrt (wi) * yi);\n }\n\n gsl_blas_dgemv (CblasTrans, 1.0, A, t, 0.0, xt);\n\n /* Scale the matrix Q, Q' = Q S^-1 */\n\n gsl_matrix_memcpy (QSI, Q);\n\n {\n double s0 = gsl_vector_get (S, 0);\n p_eff = 0;\n \n for (j = 0; j < p; j++)\n {\n gsl_vector_view column = gsl_matrix_column (QSI, j);\n double sj = gsl_vector_get (S, j);\n double alpha;\n\n if (sj <= tol * s0)\n {\n alpha = 0.0;\n }\n else\n {\n alpha = 1.0 / sj;\n p_eff++;\n }\n\n gsl_vector_scale (&column.vector, alpha);\n }\n\n *rank = p_eff;\n }\n\n gsl_vector_set_zero (c);\n\n /* solution */\n gsl_blas_dgemv (CblasNoTrans, 1.0, QSI, xt, 0.0, c);\n\n /* unscale the balancing factors */\n gsl_vector_div (c, D);\n\n /* compute chisq, from residual r = y - X c */\n {\n double r2 = 0;\n\n for (i = 0; i < n; i++)\n {\n double yi = gsl_vector_get (y, i);\n double wi = gsl_vector_get (w, i);\n gsl_vector_const_view row = gsl_matrix_const_row (X, i);\n double y_est, ri;\n gsl_blas_ddot (&row.vector, c, &y_est);\n ri = yi - y_est;\n r2 += wi * ri * ri;\n }\n\n *chisq = r2;\n\n /* Form covariance matrix cov = (X^T W X)^-1 = (Q S^-1) (Q S^-1)^T */\n\n for (i = 0; i < p; i++)\n {\n gsl_vector_view row_i = gsl_matrix_row (QSI, i);\n double d_i = gsl_vector_get (D, i);\n\n for (j = i; j < p; j++)\n {\n gsl_vector_view row_j = gsl_matrix_row (QSI, j);\n double d_j = gsl_vector_get (D, j);\n double s;\n\n gsl_blas_ddot (&row_i.vector, &row_j.vector, &s);\n\n gsl_matrix_set (cov, i, j, s / (d_i * d_j));\n gsl_matrix_set (cov, j, i, s / (d_i * d_j));\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_multifit_wlinear (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n size_t rank;\n int status = gsl_multifit_wlinear_tsvd(X, w, y, GSL_DBL_EPSILON, c, cov, chisq, &rank, work);\n\n return status;\n}\n\nint\ngsl_multifit_wlinear_tsvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n const double tol,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n size_t * rank,\n gsl_multifit_linear_workspace * work)\n{\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (y->size != n)\n {\n GSL_ERROR(\"number of observations in y does not match matrix\",\n GSL_EBADLEN);\n }\n else if (w->size != n)\n {\n GSL_ERROR(\"number of weights in w does not match matrix\",\n GSL_EBADLEN);\n }\n else if (p != c->size)\n {\n GSL_ERROR (\"number of parameters c does not match matrix\",\n GSL_EBADLEN);\n }\n else if (tol <= 0)\n {\n GSL_ERROR (\"tolerance must be positive\", GSL_EINVAL);\n }\n else\n {\n int status;\n double rnorm, snorm;\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);\n\n /* compute A = sqrt(W) X, b = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);\n if (status)\n return status;\n\n /* compute SVD of A */\n status = gsl_multifit_linear_bsvd(&A.matrix, work);\n if (status)\n return status;\n\n status = multifit_linear_solve(X, &b.vector, tol, 0.0, rank,\n c, &rnorm, &snorm, work);\n if (status)\n return status;\n\n *chisq = rnorm * rnorm;\n\n /* variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */\n {\n const size_t p = X->size2;\n size_t i, j;\n gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p);\n gsl_vector_view D = gsl_vector_subvector(work->D, 0, p);\n\n for (i = 0; i < p; i++)\n {\n gsl_vector_view row_i = gsl_matrix_row (&QSI.matrix, i);\n double d_i = gsl_vector_get (&D.vector, i);\n\n for (j = i; j < p; j++)\n {\n gsl_vector_view row_j = gsl_matrix_row (&QSI.matrix, j);\n double d_j = gsl_vector_get (&D.vector, j);\n double s;\n\n gsl_blas_ddot (&row_i.vector, &row_j.vector, &s);\n\n gsl_matrix_set (cov, i, j, s / (d_i * d_j));\n gsl_matrix_set (cov, j, i, s / (d_i * d_j));\n }\n }\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_multifit_wlinear_svd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n int status = multifit_wlinear_svd (X, w, y, tol, 1, rank, c,\n cov, chisq, work);\n return status;\n\n}\n\nint\ngsl_multifit_wlinear_usvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n int status = multifit_wlinear_svd (X, w, y, tol, 0, rank, c,\n cov, chisq, work);\n return status;\n\n}\n", "meta": {"hexsha": "eb86c21738c1c4bf07e991a7751b84b4bde0c963", "size": 9775, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/multifit/multiwlinear.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/multifit/multiwlinear.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/multifit/multiwlinear.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": 28.1700288184, "max_line_length": 95, "alphanum_fraction": 0.4964705882, "num_tokens": 2559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.48819014917669623}} {"text": "#if !defined(SM_H)\n#define SM_H\n\n#include \n\n/** \n* @brief Class describing the Standard Model\n*\n* This class holds all the parameters specifying the Standard Model, and\n* methods to access them in convenient ways.\n* \n*/\nclass SM {\n \n public:\n \n /// Default value for EM coupling \\f$ \\alpha_{\\rm{EM}}(M_Z) \\f$\n const static double alpha = 1./127.934; \n \n /// Default value for EM coupling at low energy\n const static double alpha0 = 1./137.0359997; \n \n /// Default value for the Fermi constant \\f$ G_F \\f$ (\\f$ \\rm{GeV}^{-2} \\f$)\n const static double GF = 1.16637E-5; \n\n /// Default value for \\f$ M_Z \\f$ (GeV)\n const static double MZ = 91.15349;\n\n /// Default value for \\f$ M_W \\f$ (GeV)\n const static double MW = 80.36951;\n\n /// Default value for the strong coupling \\f$ \\alpha_s(M_Z) \\f$\n const static double alpha_s = 0.119; \n \n /// Default value for total width \\f$ \\Gamma_Z \\f$ (GeV)\n const static double GammaZ = 2.49581;\n\n /// Default value for total width \\f$ \\Gamma_W \\f$ (GeV)\n const static double GammaW = 2.08856;\n\n /// Default value for quark pole mass \\f$ m_d \\f$ (GeV)\n const static double md_p = 0.0; \n \n /// Default value for quark pole mass \\f$ m_u \\f$ (GeV)\n const static double mu_p = 0.0; \n\n /// Default value for quark pole mass \\f$ m_s \\f$ (GeV)\n const static double ms_p = 0.1; \n \n // Scale for strange quark mass (GeV)\n const static double Q_ms = 2.0; \n \n /// Default value for quark pole mass \\f$ m_c \\f$ (GeV)\n const static double mc_p = 1.42; \n\n /// Default value for quark pole mass \\f$ m_b \\f$ (GeV)\n const static double mb_p = 4.75; \n \n /// Default value for quark pole mass \\f$ m_t \\f$ (GeV)\n const static double mt_p = 172.5;\n \n /// Default value for electron pole mass \\f$ m_e \\f$ (GeV)\n const static double me_p = 0.510998918E-3;\n\n /// Default value for muon pole mass \\f$ m_\\mu \\f$ (GeV)\n const static double mmu_p = 0.105658367;\n \n /// Default value for tau pole mass \\f$ m_\\tau \\f$ (GeV)\n const static double mtau_p = 1.77684; \n\n // PDG booklet 2012\n /// Default value for CKM matrix element \\f$ V_{ud} \\f$\n const static double Vud = 0.97427;\n /// Default value for CKM matrix element \\f$ V_{us} \\f$\n const static double Vus = 0.22534;\n /// Default value for CKM matrix element \\f$ V_{ub} \\f$\n const static double Vub = 0.00351;\n /// Default value for CKM matrix element \\f$ V_{cd} \\f$\n const static double Vcd = 0.22520;\n /// Default value for CKM matrix element \\f$ V_{cs} \\f$\n const static double Vcs = 0.97334;\n /// Default value for CKM matrix element \\f$ V_{cb} \\f$\n const static double Vcb = 0.0412;\n /// Default value for CKM matrix element \\f$ V_{td} \\f$\n const static double Vtd = 0.00867;\n /// Default value for CKM matrix element \\f$ V_{ts} \\f$\n const static double Vts = 0.0404;\n /// Default value for CKM matrix element \\f$ V_{tb} \\f$\n const static double Vtb = 0.999146;\n\n\n /**\n * @brief Default constructor initializing the Standard Model with default parameter\n * values\n * \n * This constructor initializes a new SM object with default parameters. The\n * values used as defaults are specified by public constants in this class.\n */\n SM();\n\n\n /**\n * @brief Sets the EM coupling \\f$ \\alpha \\f$\n *\n * @param alpha_in New value for \\f$ \\alpha(M_Z) \\f$\n */\n void set_alpha(double alpha_in);\n\n /**\n * @brief Sets the EM coupling \\f$ \\alpha_0 \\f at low energy$\n *\n * @param alpha_in New value for \\f$ \\alpha(Q^2=0) \\f$\n */\n void set_alpha0(double alpha_in);\n\n \n /**\n * @brief Sets the Fermi constant \\f$ G_F \\f$\n *\n * @param GF_in New value for \\f$ G_F \\f$ (\\f$ GeV^{-2} \\f$)\n */\n void set_GF(double GF_in);\n\n /**\n * @brief Sets \\f$ M_Z \\f$\n *\n * @param MZ_in New value for \\f$ M_Z \\f$\n */\n void set_MZ(double MZ_in);\n\n /**\n * @brief Sets \\f$ M_W \\f$\n *\n * @param MW_in New value for \\f$ M_W \\f$\n */\n void set_MW(double MW_in);\n\n /**\n * @brief Sets \\f$ \\gamma_Z \\f$\n *\n * @param GammaZ_in New value for \\f$ \\Gamma_Z \\f$\n */\n void set_gamma_Z(double GammaZ_in);\n\n /**\n * @brief Sets \\f$ \\gamma_W \\f$\n *\n * @param GammaW_in New value for \\f$ \\Gamma_W \\f$\n */\n void set_gamma_W(double GammaW_in);\n\n /**\n * @brief Sets the strong coupling \\f$ \\alpha_s \\f$\n *\n * @param alpha_s_in New value for \\f$ \\alpha_s(M_Z) \\f$\n */\n void set_alpha_s(double alpha_s_in);\n\n /**\n * @brief Current value of \\f$ \\alpha \\f$\n *\n * @returns Value of \\f$ \\alpha \\f$\n */\n double get_alpha();\n double get_alpha0();\n\n /**\n * @brief Current value of \\f$ G_F \\f$\n *\n * @returns Value of \\f$ G_F \\f$ (\\f$ \\rm{GeV}^{-2} \\f$)\n */\n double get_GF();\n\n /**\n * @brief Current value of \\f$ \\sin\\theta_W \\f$\n *\n * @returns Value of \\f$ \\sin\\theta_W \\f$\n */\n double get_sintw();\n\n /**\n * @brief Current value of \\f$ \\cos\\theta_W \\f$\n *\n * @returns Value of \\f$ \\cos\\theta_W \\f$\n */\n double get_costw();\n\n /**\n * @brief Current value of weak SU(2) coupling \\f$ g \\f$\n *\n * @returns Value of \\f$ g \\f$\n */\n double get_g();\n \n /**\n * @brief Current value of hypercharge U(1) coupling \\f$ g' \\f$\n *\n * @returns Value of \\f$ g' \\f$\n */\n double get_gprime();\n\n /**\n * @brief Current value of EM coupling \\f$ e \\f$\n *\n * @returns Value of \\f$ g' \\f$\n */\n double get_e();\n\n /**\n * @brief Current value of \\f$ \\alpha_s \\f$\n *\n * @returns Value of \\f$ \\alpha_s \\f$\n */\n double get_alpha_s(); \n\n /**\n * @brief Current value of \\f$ M_W \\f$\n *\n * @returns Value of \\f$ M_W \\f$ (GeV)\n */\n double get_MW();\n\n /**\n * @brief Current value of \\f$ \\Gamma_W \\f$\n *\n * @returns Value of \\f$ \\Gamma_W \\f$ (GeV)\n */\n double get_gamma_W();\n\n /**\n * @brief Current value of \\f$ M_Z \\f$\n *\n * @returns Value of \\f$ M_Z \\f$ (GeV)\n */\n double get_MZ();\n \n /**\n * @brief Current value of \\f$ \\Gamma_Z \\f$\n *\n * @returns Value of \\f$ \\Gamma_Z \\f$ (GeV)\n */\n double get_gamma_Z();\n\n /**\n * @brief Current value of the vev \\f$ v=1/\\sqrt{\\sqrt{2}G_F} \\f$\n *\n * @returns Value of \\f$ v \\f$ (GeV)\n */\n double get_v();\n\n /**\n * @brief Current value of the vev squared \\f$ v^2=1/(\\sqrt{2}G_F) \\f$\n *\n * @returns Value of \\f$ v^2 \\f$ (\\f$ \\rm{GeV}^2 \\f$)\n */\n double get_v2();\n\n /**\n * @brief Vector boson mass\n *\n * This method returns the mass of a given vector boson. The numbering\n * convention used throughout 2HDMC is such that (1 = photon, 2 = Z0, 3 = W+).\n * \n * @param v Index (1-3) for the vector boson\n * \n * @returns Value of \\f$ m_V \\f$ (GeV)\n */\n double get_vmass(int v);\n\n /**\n * @brief Vector boson width\n *\n * This method returns the decay width of a given vector boson. The numbering\n * convention is such that (1 = photon, 2 = Z0, 3 = W+).\n * \n * @param v Index (1-3) for the vector boson\n * \n * @returns Value of \\f$ \\Gamma_V \\f$ (GeV)\n */\n double get_gamma_V(int v);\n\n /**\n * @brief Sets the CKM matrix to a 3x3 unit matrix\n * \n * This method sets the CKM matrix to a 3x3 unit matrix, i.e. eliminating\n * all charged current interactions between different generations.\n */\n void set_diagonal_CKM();\n\n /**\n * @brief Full CKM matrix\n * \n * This method can be used to retrieve the full CKM matrix as a gsl_matrix.\n *\n * @returns CKM matrix\n * \n * @see get_MD, get_MU, get_ML, get_CKM_element\n */\n gsl_matrix* get_CKM_matrix();\n\n /**\n * @brief Element of the CKM matrix\n * \n * This method can be used to retrieve a certain element of the CKM matrix.\n *\n * @param i Row index (1,2,3 = u,c,t) of CKM matrix element\n * @param j Column index (1,2,3 = d,s,b) of CKM matrix element\n * @returns The requested CKM element\n * \n * @see get_CKM\n */\n double get_CKM_element(int i, int j);\n\n /**\n * @brief Sets the pole mass of a lepton\n * \n * This method sets the pole mass of lepton \\a l to the supplied value.\n * \n * @param l Index of lepton (1,2,3 = \\f$ e,\\mu,\\tau \\f$)\n * @param lmass_in New mass of lepton\n */\n void set_lmass_pole(int l, double lmass_in);\n \n /**\n * @brief Sets the pole mass of a quark\n * \n * This method sets the pole mass of quark \\a q to the supplied value.\n * \n * @param q Index of quark (1,2,3,4,5,6 = \\f$ d,u,s,c,b,t \\f$)\n * @param qmass_in New mass of quark\n */\n void set_qmass_pole(int q, double qmass_in);\n \n void set_qmass_msbar(int flav, double qmass_in);\n \n /**\n * @brief Sets the pole mass of a down-type quark\n * \n * This method sets the pole mass of quark \\a d to the supplied value.\n * \n * @param d Index of quark (1,2,3 = \\f$ d,s,b \\f$)\n * @param dmass_in New mass of quark\n */\n void set_dmass_pole(int d, double dmass_in);\n \n /**\n * @brief Sets the pole mass of an up-type quark\n * \n * This method sets the pole mass of quark \\a u to the supplied value.\n * \n * @param u Index of quark (1,2,3 = \\f$ u,c,t \\f$)\n * @param umass_in New mass of quark\n */\n void set_umass_pole(int u, double umass_in); \n\n /**\n * @brief Quark pole mass\n * \n * @param q Index (1,2,3,4,5,6 = \\f$ d,u,s,c,b,t \\f$) of quark\n * \n * @returns The pole mass \\f$ m_q \\f$\n */\n double get_qmass_pole(int q);\n \n /**\n * @brief Down-type quark pole mass\n * \n * @param d Index (1,2,3 = \\f$ d,s,b \\f$) of down-type quark\n * \n * @returns Quark pole mass \\f$ m_d \\f$\n */\n double get_dmass_pole(int d);\n\n /**\n * @brief Up-type quark pole mass\n * \n * @param u Index (1,2,3 = \\f$ u,c,t \\f$) of up-type quark\n * \n * @returns Quark pole mass \\f$ m_u \\f$\n */\n double get_umass_pole(int u);\n\n /**\n * @brief Lepton pole mass\n * \n * @param l Index (1,2,3 = \\f$ e,\\mu,\\tau \\f$) of lepton\n * \n * @returns The pole mass \\f$ m_l \\f$\n */\n double get_lmass_pole(int l);\n\n\n /**\n * @brief Mass matrix for down-type quarks\n * \n * This method can be used to retrieve, in matrix form, the current pole masses \n * used for the down-type quarks. The masses are returned as the diagonal\n * elements of a 3x3 gsl_matrix that must be allocated by the user.\n *\n * @returns Diagonal mass matrix for the down-type quarks\n * \n * @see get_MU, get_ML, get_CKM\n */\n gsl_matrix* get_MD();\n\n /**\n * @brief Mass matrix for up-type quarks\n * \n * This method can be used to retrieve, in matrix form, the current pole masses \n * used for the up-type quarks. The masses are returned as the diagonal\n * elements of a 3x3 gsl_matrix that must be allocated by the user.\n *\n * @returns Diagonal mass matrix for the up-type quarks\n * \n * @see get_MD, get_ML, get_CKM\n */\n gsl_matrix* get_MU();\n\n /**\n * @brief Mass matrix for leptons\n * \n * This method can be used to retrieve, in matrix form, the current pole masses \n * used for the leptons. The masses are returned as the diagonal\n * elements of a 3x3 gsl_matrix that must be allocated by the user.\n *\n * @returns Diagonal mass matrix for the leptons\n * \n * @see get_MD, get_MU, get_CKM\n */\n gsl_matrix* get_ML();\n\n\n /**\n * @brief Quark \\f$ \\overline{\\rm{MS}}\\f$ mass\n * \n * This method determines the \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_q(\\overline{m}_q) \\f$\n * \n * @param q Index (1,2,3,4,5,6 = \\f$ d,u,s,c,b,t \\f$) of quark\n * \n * @returns Quark \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_q(\\overline{m}_q) \\f$\n * \n * @see run_qmass_MSbar\n */\n double get_qmass_MSbar(int q);\n\n /**\n * @brief Down-type quark \\f$ \\overline{\\rm{MS}}\\f$ mass\n * \n * This method determines the \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_d(\\overline{m}_d) \\f$\n * \n * @param d Index (1,2,3 = \\f$ d,s,b \\f$) of down-type quark\n * \n * @returns Quark \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_d(\\overline{m}_d) \\f$\n * \n * @see get_umass_MSbar, run_qmass_MSbar\n */\n double get_dmass_MSbar(int d);\n \n /**\n * @brief Up-type quark \\f$ \\overline{\\rm{MS}}\\f$ mass\n * \n * This method determines the \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_u(\\overline{m}_u) \\f$\n * \n * @param u Index (1,2,3 = \\f$ u,c,t \\f$) of up-type quark\n * \n * @returns Quark \\f$ \\overline{\\rm{MS}}\\f$ mass \\f$ \\overline{m}_u(\\overline{m}_u) \\f$\n * \n * @see get_dmass_MSbar, run_qmass_MSbar\n */\n double get_umass_MSbar(int u);\n\n /**\n * @brief Evaluates running quark masses\n * \n * This method evaluates the running quark_mass \\a quark_mass, initially specified \n * at the input scale \\a Qinit, at the new scale \\a Qfin. The calculation is performed\n * in the \\f$ \\overline{\\rm{MS}} \\f$ scheme with variable number of active\n * flavours and threshold matching.\n * \n * @param quark_mass The input value for the running quark mass\n * @param Qinit Starting scale\n * @param Qfin Final scale at which the mass is to be evaluated\n * @param mtop \\f$ \\overline{\\rm{MS}} \\f$ top mass (for thresholds)\n * @param mbot \\f$ \\overline{\\rm{MS}} \\f$ bottom mass (for thresholds)\n * \n * @returns The running mass at the scale \\a Qfin\n */\n double run_qmass_MSbar(double quark_mass, double Qinit, double Qfin, double mtop, double mbot);\n\n\n /**\n * @brief Evaluates the running strong coupling\n * \n * This method evaluates the running strong coupling \\f$ \\alpha_s \\f$ in the \n * \\f$ \\overline{\\rm{MS}} \\f$ scheme at the scale specified by \\a Q.\n * \n * @param Q Scale at which to evaluate the running coupling\n * @param mtop \\f$ \\overline{\\rm{MS}} \\f$ top mass (for thresholds)\n * @param mbot \\f$ \\overline{\\rm{MS}} \\f$ bottom mass (for thresholds)\n * \n * @returns The strong coupling \\f$ \\alpha_s \\f$ at the scale \\a Q\n */\n double run_alphas_MSbar(double Q, double mtop, double mbot);\n\n /** \n * @brief Number of active flavours\n * \n * This method returns the number of active quark flavours to be used at \n * a certain mass scale when decoupling the heavier quarks. The thresholds\n * are determined from the quark \\f$ \\overline{\\rm{MS}} \\f$ masses.\n * \n * @param M The scale for which the number of flavours is desired\n * \n * @returns The number of quark flavours active at this scale\n */\n int get_Nactivef(double M);\n\n\n /**\n * @brief %SM width of the top quark\n * \n * Calculates the width of the top quark in the %SM, i.e. no contributions from \n * \\f$ t\\to H^+ b \\f$ decays etc. are included.\n * \n * @returns The top width \\f$ \\Gamma_t \\f$\n */\n double get_gamma_top();\n double get_gamma_tWd(int d);\n\n \n \n\n // --- These masses are for compatibility test with HDECAY ---\n // Scale for HD quark masses (HD)\n const static double Q_HD = 5.0; \n \n // switch for HD quark masses (HD)\n const static bool b_HD = false; \n \n /// Default value for running quark mass at 5 GeV \\f$ m_s(5) \\f$ (GeV)\n const static double ms_5 = 0.08160951656; \n\n /// Default value for running quark mass at 5 GeV \\f$ m_c(5) \\f$ (GeV)\n const static double mc_5 = 0.8960809463; \n\n /// Default value for running quark mass at 5 GeV \\f$ m_b(5) \\f$ (GeV)\n const static double mb_5 = 4.310679848; \n \n /// Default value for running quark mass at 5 GeV \\f$ m_t(5) \\f$ (GeV)\n const static double mt_5 = 246.5552058;\n // -------------------------------------------------------------\n\n\n private:\n\n // Internal variables which store the current values of the SM parameters\n double m_alpha;\n double m_alpha0;\n double m_GF;\n double m_s2tW;\n double m_alpha_s;\n double m_md_p[3];\n double m_mu_p[3];\n double m_ml_p[3];\n double m_MW;\n double m_MZ;\n double m_GammaW;\n double m_GammaZ;\n double m_CKM[3][3];\n\n double m_qmass_ms[7];\n \n\t// Support functions for the running mass calculation\t\n double m_threshold(double as);\n double RQ(double as, int nf, int loops);\n double QCD_beta(int c, int nf);\n\n void clear_lookup();\n\n \n};\n\n#endif\n", "meta": {"hexsha": "6bbd352ae85c89cab08828313f8eb904a604fd14", "size": 15599, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SM.h", "max_stars_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_stars_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "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/SM.h", "max_issues_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_issues_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "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/SM.h", "max_forks_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_forks_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z", "avg_line_length": 26.7106164384, "max_line_length": 100, "alphanum_fraction": 0.6166420924, "num_tokens": 5293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4881526482603161}} {"text": "#ifndef _params_h_\r\n#define _params_h_\r\n\r\n#include \r\n#include \r\n#include //For getpid() function\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n//****Simulation Parameters:\r\n#define N_ps (int) 64 //Number of points in PS file\r\n#define N_gen (int) 4 //To generate the 21cm field\r\n#define LEN (double) 8.0 //Length of simulation box (in Mpc h^{-1})\r\n#define freq_width (double) 2.0 //Width of frequency channel (in MHz)\r\n\r\n//****Foreground Removal Parameters:\r\ndouble *expo;\r\nint expo_array;\r\nint count(int);\r\n\r\n//****Function declarations:\r\ndouble interp_ps_lin(double);\r\ndouble read_21cm_cube(char *);\r\ndouble sim_21cm_cube();\r\ndouble generate_full_signal();\r\ndouble count_freq_channels();\r\ndouble noise_removal();\r\n\r\n//****Multifrequency fitting declarations:\r\ndouble *y, *x, *N, *Ni, *xtNi, *xtNix, *xtNix_i, *big_matrix, *a, *xa;\r\n\r\n//****GSL rng declarations:\r\nconst gsl_rng_type *T;\r\ngsl_rng *rand1, *rand2;\r\nlong seed;\r\ndouble a_q, b_q;\r\n\r\n//****Others:\r\nint SimON, XY_pix, Z_pix, Npol; //XY_pix and Z_pix are the box dimensions in pixels\r\ndouble frequency, original_21cm_mean, total_21cm_mean;\r\ndouble *original_21cm_field, *total_21cm_field, *detector_noise_field, *total_noise_field , *recovered_21cm_field, *parameter_a_cube;\r\ndouble k[N_ps], Pk[N_ps];\r\ndouble *freq_array;\r\ndouble sigma, nu, tau, offset;\r\ndouble XY_LEN, Z_LEN; //Length of the box\r\n\r\nFILE *file;\r\nchar cmnd[1000], header[100], polystr[100];\r\n//****polystr is to store the exponents of variables of the fitting polynomial\r\n\r\n#endif", "meta": {"hexsha": "30ac429936de28ef47eeceae7e56ab6b8577fa51", "size": 1776, "ext": "h", "lang": "C", "max_stars_repo_path": "params.h", "max_stars_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_stars_repo_head_hexsha": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-27T07:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-27T07:59:48.000Z", "max_issues_repo_path": "params.h", "max_issues_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_issues_repo_head_hexsha": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "params.h", "max_forks_repo_name": "anand-avinash/21cm-signal-with-multifrequency-fitting", "max_forks_repo_head_hexsha": "fb473c1ef245d2768e6044f5903f5109e7393b69", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6451612903, "max_line_length": 134, "alphanum_fraction": 0.7111486486, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.4879216031637053}} {"text": "/*==========================================================\n * pca.c - Principal component analysis of diffraction data\n *\n * Calculates the two main components of the data\n * by Principal Component Analysis, as detailed in\n * Bernhardt et.al (2016), Biophys. J.\n *\n * The calling syntax is:\n *\n *\t\tpca(data, mask, qx, qy, w, phi, m, n)\n *\n * Copyright 2017 Institute for X-ray Physics (University of Göttingen)\n *\n * Permission is hereby granted, free of charge, to any person obtaining \n * a copy of this software and associated documentation files (the \"Software\"), \n * to deal in the Software without restriction, including without limitation \n * the rights to use, copy, modify, merge, publish, distribute, sublicense, \n * and/or sell copies of the Software, and to permit persons to whom the \n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included \n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE \n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *========================================================*/\n\n#include \n#include \n#include \n\n#define PI 3.14159265\n\n/* The computational routine */\nvoid pca(double *x, double *mask, double *qx, double *qy, double *w, double *phi, int m, int n)\n{ \n int col;\n int row;\n double tr = 0;\n \n /* total sum of x */\n for (row=0; row\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"su3_matrix.c\"\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\nint acc, tot; // acceptance rate\n\n#define FORWARD 1 //true\n#define BACKWARD 0 //false\n\n// Access pattern methods --------------------------------------------------\n\n// index of link site=(t,x,y,z) in direction dir\nint index(const int* site, int dir){\n return dir+site[0]*4+site[1]*N*4+site[2]*N*N*4+site[3]*N*N*N*4;\n}\n\n// shift site array by one to direction dir\nvoid shift(int* site, int dir, int forward){\n if(forward == 1){\n site[dir] = (site[dir]+1)%N;\n }else{\n site[dir] = (site[dir]-1+N)%N;\n }\n}\n\n// spatial rotation by 90deg of shape array\nvoid rotate(int n, int* shape){\n for(int i=0;inu\ndouble plaquette(const su3_matrix* links, int mu, int nu, int* site){\n su3_matrix A,B,C,D;\n A = links[index(site,mu)];\n shift(site,mu,FORWARD);\n B = links[index(site,nu)];\n shift(site,mu,BACKWARD);\n shift(site,nu,FORWARD);\n C = su3_inv(links[index(site,mu)]);\n shift(site,nu,BACKWARD); // restore site position\n D = su3_inv(links[index(site,nu)]);\n\n A = su3_mul(A,B);\n A = su3_mul(A,C);\n A = su3_mul(A,D);\n\n return su3_trace(A)/3.0;\n}\n\n// plaquette spatial mean\ndouble plaq_mean_s(int t, const su3_matrix* links){\n double mean = 0;\n int site[4];\n for(int z=0;z0){\n if(exp(-dS) nu\ndouble action(su3_matrix* links, int* site, int dir){\n int mu,nu;\n double result=0;\n for(int k=0; k<4; k++){\n if(k==dir) continue; // loop over planes\n if(k>dir){mu=k; nu=dir;} // mu=larger number\n if(k\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"qdm.h\"\n\n#define QDM_THETA_MIN_THRESHOLD 0.0001\n\nint\nqdm_theta_optimize(\n gsl_vector *result,\n gsl_vector *emperical_quantiles,\n gsl_matrix *ix\n)\n{\n int status = 0;\n\n gsl_matrix *p = gsl_matrix_alloc(ix->size2, ix->size2);\n gsl_matrix *a = gsl_matrix_alloc(ix->size2, ix->size2);\n gsl_vector *q = gsl_vector_alloc(ix->size2);\n gsl_vector *l = gsl_vector_alloc(ix->size2);\n gsl_vector *u = gsl_vector_alloc(ix->size2);\n\n // FIXME check c_malloc...\n OSQPData *data = c_malloc(sizeof(OSQPData));\n OSQPSettings *settings = c_malloc(sizeof(OSQPSettings));\n OSQPWorkspace *work = NULL;\n\n /* Ensure all data fields are initialized before use. */\n *data = (OSQPData) {\n .n = 0,\n .m = 0,\n .P = NULL,\n .A = NULL,\n .q = NULL,\n .l = NULL,\n .u = NULL,\n };\n\n status = qdm_matrix_tmm(ix, p);\n if (status != 0) {\n goto cleanup;\n }\n\n qdm_matrix_select_upper_triangle(p);\n\n gsl_matrix_set_identity(a);\n\n gsl_vector_set_all(l, QDM_THETA_MIN_THRESHOLD);\n gsl_vector_set_all(u, INFINITY);\n\n status = gsl_blas_dgemv(CblasTrans, -1.0, ix, emperical_quantiles, 0, q);\n if (status != 0) {\n goto cleanup;\n }\n\n /* Solve... */\n data->n = ix->size2;\n data->m = ix->size2;\n\n status = qdm_matrix_to_csc_matrix(&data->P, p);\n if (status != 0) {\n goto cleanup;\n }\n\n status = qdm_matrix_to_csc_matrix(&data->A, a);\n if (status != 0) {\n goto cleanup;\n }\n\n data->q = q->data;\n data->l = l->data;\n data->u = u->data;\n\n osqp_set_default_settings(settings);\n settings->verbose = 0;\n\n status = osqp_setup(&work, data, settings);\n if (status != 0) {\n goto cleanup;\n }\n\n status = osqp_solve(work);\n if (status != 0) {\n goto cleanup;\n }\n\n gsl_vector_view beta0 = gsl_vector_view_array(work->solution->x, ix->size2);\n status = gsl_vector_memcpy(result, &beta0.vector);\n if (status != 0) {\n goto cleanup;\n }\n\ncleanup:\n if (data != NULL) {\n if (data->A != NULL) {\n free(data->A->p);\n free(data->A->i);\n free(data->A->x);\n }\n\n c_free(data->A);\n\n if (data->P != NULL) {\n free(data->P->p);\n free(data->P->i);\n free(data->P->x);\n }\n\n c_free(data->P);\n\n c_free(data);\n }\n\n c_free(settings);\n osqp_cleanup(work);\n\n gsl_vector_free(u);\n gsl_vector_free(l);\n gsl_vector_free(q);\n gsl_matrix_free(a);\n gsl_matrix_free(p);\n\n return status;\n}\n\nvoid\nqdm_theta_matrix_constrain(\n gsl_matrix *theta,\n double min\n)\n{\n /* First row is constrained to be greater than zero. */\n for (size_t j = 0; j < theta->size2; j++) {\n if (gsl_matrix_get(theta, 0, j) < 0) {\n gsl_matrix_set(theta, 0, j, min);\n }\n }\n\n /* Remaining cells are set to zero if the sum of the column is negative.\n *\n * NOTE: The first column is not modified.\n */\n for (size_t i = 1; i < theta->size1; i++) {\n for (size_t j = 1; j < theta->size2; j++) {\n gsl_vector_view column = gsl_matrix_column(theta, j);\n double sum = qdm_vector_sum(&column.vector);\n\n if (sum < 0) {\n gsl_matrix_set(theta, i, j, 0);\n }\n }\n }\n}\n", "meta": {"hexsha": "14a6f04e6b9b2a4e4eb9839fa25e7870e05d8924", "size": 3213, "ext": "c", "lang": "C", "max_stars_repo_path": "src/theta.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theta.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/theta.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2075471698, "max_line_length": 78, "alphanum_fraction": 0.6118892001, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4878298387108655}} {"text": "// --------------------------------------------------------------------------\n// OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// * Neither the name of any author or any participating institution\n// may be used to endorse or promote products derived from this software\n// without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Clemens Groepl $\n// $Authors: $\n// --------------------------------------------------------------------------\n\n#ifndef OPENMS_MATH_STATISTICS_LINEARREGRESSION_H\n#define OPENMS_MATH_STATISTICS_LINEARREGRESSION_H\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace OpenMS\n{\n namespace Math\n {\n /**\n @brief This class offers functions to perform least-squares fits to a straight line model, \\f$ Y(c,x) = c_0 + c_1 x \\f$.\n\n It encapsulates the GSL methods for a weighted and an unweighted linear regression.\n\n Next to the intercept with the y-axis and the slope of the fitted line, this class computes the:\n - squared pearson coefficient\n - value of the t-distribution\n - standard deviation of the residuals\n - standard error of the slope\n - intercept with the x-axis (useful for additive series experiments)\n - lower border of confidence interval\n - higher border of confidence interval\n - chi squared value\n - x mean\n\n @ingroup Math\n */\n class OPENMS_DLLAPI LinearRegression\n {\npublic:\n\n /// Constructor\n LinearRegression() :\n intercept_(0),\n slope_(0),\n x_intercept_(0),\n lower_(0),\n upper_(0),\n t_star_(0),\n r_squared_(0),\n stand_dev_residuals_(0),\n mean_residuals_(0),\n stand_error_slope_(0),\n chi_squared_(0),\n rsd_(0)\n {\n }\n\n /// Destructor\n virtual ~LinearRegression()\n {\n }\n\n /**\n @brief This function computes the best-fit linear regression coefficients \\f$ (c_0,c_1) \\f$\n of the model \\f$ Y = c_0 + c_1 X \\f$ for the dataset \\f$ (x, y) \\f$.\n\n The values in x-dimension of the dataset \\f$ (x,y) \\f$ are given by the iterator range [x_begin,x_end)\n and the corresponding y-values start at position y_begin.\n\n\n For a \"x %\" Confidence Interval use confidence_interval_P = x/100.\n For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of\n containing the true value of the parameter.\n\n @return If an error occurred during the fit.\n\n @exception Exception::UnableToFit is thrown if fitting cannot be performed\n */\n template \n void computeRegression(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin);\n\n /**\n @brief This function computes the best-fit linear regression coefficient \\f$ (c_0) \\f$\n of the model \\f$ Y = c_1 X \\f$ for the dataset \\f$ (x, y) \\f$.\n\n The values in x-dimension of the dataset \\f$ (x,y) \\f$ are given by the iterator range [x_begin,x_end)\n and the corresponding y-values start at position y_begin.\n\n For a \"x %\" Confidence Interval use confidence_interval_P = x/100.\n For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of\n containing the true value of the parameter.\n\n @return If an error occurred during the fit.\n\n @exception Exception::UnableToFit is thrown if fitting cannot be performed\n */\n template \n void computeRegressionNoIntercept(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin);\n\n /**\n @brief This function computes the best-fit linear regression coefficients \\f$ (c_0,c_1) \\f$\n of the model \\f$ Y = c_0 + c_1 X \\f$ for the weighted dataset \\f$ (x, y) \\f$.\n\n The values in x-dimension of the dataset \\f$ (x, y) \\f$ are given by the iterator range [x_begin,x_end)\n and the corresponding y-values start at position y_begin. They will be weighted by the\n values starting at w_begin.\n\n For a \"x %\" Confidence Interval use confidence_interval_P = x/100.\n For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of\n containing the true value of the parameter.\n\n @return If an error occurred during the fit.\n\n @exception Exception::UnableToFit is thrown if fitting cannot be performed\n */\n template \n void computeRegressionWeighted(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin);\n\n\n /// Non-mutable access to the y-intercept of the straight line\n DoubleReal getIntercept() const;\n /// Non-mutable access to the slope of the straight line\n DoubleReal getSlope() const;\n /// Non-mutable access to the x-intercept of the straight line\n DoubleReal getXIntercept() const;\n /// Non-mutable access to the lower border of confidence interval\n DoubleReal getLower() const;\n /// Non-mutable access to the upper border of confidence interval\n DoubleReal getUpper() const;\n /// Non-mutable access to the value of the t-distribution\n DoubleReal getTValue() const;\n /// Non-mutable access to the squared pearson coefficient\n DoubleReal getRSquared() const;\n /// Non-mutable access to the standard deviation of the residuals\n DoubleReal getStandDevRes() const;\n /// Non-mutable access to the residual mean\n DoubleReal getMeanRes() const;\n /// Non-mutable access to the standard error of the slope\n DoubleReal getStandErrSlope() const;\n /// Non-mutable access to the chi squared value\n DoubleReal getChiSquared() const;\n /// Non-mutable access to relative standard deviation\n DoubleReal getRSD() const;\n\nprotected:\n\n /// The intercept of the fitted line with the y-axis\n double intercept_;\n /// The slope of the fitted line\n double slope_;\n /// The intercept of the fitted line with the x-axis\n double x_intercept_;\n /// The lower bound of the confidence interval\n double lower_;\n /// The upper bound of the confidence interval\n double upper_;\n /// The value of the t-statistic\n double t_star_;\n /// The squared correlation coefficient (Pearson)\n double r_squared_;\n /// The standard deviation of the residuals\n double stand_dev_residuals_;\n /// Mean of residuals\n double mean_residuals_;\n /// The standard error of the slope\n double stand_error_slope_;\n /// The value of the Chi Squared statistic\n double chi_squared_;\n /// the relative standard deviation\n double rsd_;\n\n\n /// Computes the goodness of the fitted regression line\n void computeGoodness_(double * X, double * Y, int N, double confidence_interval_P);\n\n /// Copies the distance(x_begin,x_end) elements starting at x_begin and y_begin into the arrays x_array and y_array\n template \n void iteratorRange2Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, double * x_array, double * y_array);\n\n /// Copy the distance(x_begin,x_end) elements starting at x_begin, y_begin and w_begin into the arrays x_array, y_array and w_array\n template \n void iteratorRange3Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double * x_array, double * y_array, double * w_array);\n\nprivate:\n\n /// Not implemented\n LinearRegression(const LinearRegression & arg);\n /// Not implemented\n LinearRegression & operator=(const LinearRegression & arg);\n };\n\n template \n void LinearRegression::computeRegression(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin)\n {\n int N = int(distance(x_begin, x_end));\n\n double * X = new double[N];\n double * Y = new double[N];\n iteratorRange2Arrays_(x_begin, x_end, y_begin, X, Y);\n\n double cov00, cov01, cov11;\n\n // Compute the unweighted linear fit.\n // Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X\n // and the value of Chi squared, the covariances of the intercept and the slope\n int error = gsl_fit_linear(X, 1, Y, 1, N, &intercept_, &slope_, &cov00, &cov01, &cov11, &chi_squared_);\n\n if (!error)\n {\n computeGoodness_(X, Y, N, confidence_interval_P);\n }\n\n delete[] X;\n delete[] Y;\n\n if (error)\n {\n throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"UnableToFit-LinearRegression\", \"Could not fit a linear model to the data\");\n }\n }\n\n template \n void LinearRegression::computeRegressionNoIntercept(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin)\n {\n int N = int(distance(x_begin, x_end));\n\n double * X = new double[N];\n double * Y = new double[N];\n iteratorRange2Arrays_(x_begin, x_end, y_begin, X, Y);\n\n double cov;\n\n // Compute the linear fit.\n // Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X\n // and the value of Chi squared, the covariances of the intercept and the slope\n int error = gsl_fit_mul(X, 1, Y, 1, N, &slope_, &cov, &chi_squared_);\n intercept_ = 0.0;\n\n if (!error)\n {\n computeGoodness_(X, Y, N, confidence_interval_P);\n }\n\n delete[] X;\n delete[] Y;\n\n if (error)\n {\n throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"UnableToFit-LinearRegression\", \"Could not fit a linear model to the data\");\n }\n }\n\n template \n void LinearRegression::computeRegressionWeighted(double confidence_interval_P, Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin)\n {\n int N = int(distance(x_begin, x_end));\n\n double * X = new double[N];\n double * Y = new double[N];\n double * W = new double[N];\n iteratorRange3Arrays_(x_begin, x_end, y_begin, w_begin, X, Y, W);\n\n double cov00, cov01, cov11;\n\n // Compute the weighted linear fit.\n // Get the intercept and the slope of the regression Y_hat=intercept_+slope_*X\n // and the value of Chi squared, the covariances of the intercept and the slope\n int error = gsl_fit_wlinear(X, 1, W, 1, Y, 1, N, &intercept_, &slope_, &cov00, &cov01, &cov11, &chi_squared_);\n\n if (!error)\n {\n computeGoodness_(X, Y, N, confidence_interval_P);\n }\n\n delete[] X;\n delete[] Y;\n delete[] W;\n\n if (error)\n {\n throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, \"UnableToFit-LinearRegression\", \"Could not fit a linear model to the data\");\n }\n }\n\n template \n void LinearRegression::iteratorRange2Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, double * x_array, double * y_array)\n {\n int i = 0;\n while (x_begin < x_end)\n {\n x_array[i] = *x_begin;\n y_array[i] = *y_begin;\n ++x_begin;\n ++y_begin;\n ++i;\n }\n }\n\n template \n void LinearRegression::iteratorRange3Arrays_(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double * x_array, double * y_array, double * w_array)\n {\n int i = 0;\n while (x_begin < x_end)\n {\n x_array[i] = *x_begin;\n y_array[i] = *y_begin;\n w_array[i] = *w_begin;\n ++x_begin;\n ++y_begin;\n ++w_begin;\n ++i;\n }\n }\n\n } // namespace Math\n} // namespace OpenMS\n\n\n#endif\n", "meta": {"hexsha": "4e267d9de9503ed98e129ed9ec16470ede8d1432", "size": 13545, "ext": "h", "lang": "C", "max_stars_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h", "max_stars_repo_name": "kreinert/OpenMS", "max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "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/openms/include/OpenMS/MATH/STATISTICS/LinearRegression.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "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": 38.5897435897, "max_line_length": 172, "alphanum_fraction": 0.6504983389, "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.48781295321864127}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"random_matrix.h\"\n#include \"driver.h\"\n#include \"../../runtime/pcp.h\"\n\n\nstatic double compare_lower_triangular_matrices(int n, double *L1, int ldL1, double *L2, int ldL2)\n{\n#define L1(i,j) L1[(i) + (j) * ldL1]\n#define L2(i,j) L2[(i) + (j) * ldL2]\n\n // Clear out the upper triangular part.\n for (int j = 0; j < n; ++j) {\n for (int i = 0; i < j; i++) {\n L1(i,j) = 0.0;\n L2(i,j) = 0.0;\n }\n }\n\n // Compute L1 := L1 - L2.\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < n; i++) {\n L1(i,j) = L1(i,j) - L2(i,j);\n }\n }\n \n // Compute || L1 ||_F.\n double error = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, L1, ldL1);\n error /= n;\n return error;\n\n#undef L1\n#undef L2\n}\n\n\nstatic void usage(char *prog)\n{\n printf(\"Usage: %s n b p q\\n\", prog);\n printf(\"\\n\");\n printf(\"n: The size of the matrix\\n\");\n printf(\"b: The tile size\\n\");\n printf(\"p: The number of threads (or 0 for one per core)\\n\");\n printf(\"q: The size of the reserved set (or 0 to use the regular mode)\\n\");\n exit(EXIT_FAILURE);\n}\n \n\nint main(int argc, char** argv)\n{\n // Verify the number of command line options.\n if (argc != 5 && argc != 6) {\n usage(argv[0]);\n }\n\n // Parse command line.\n int n = atoi(argv[1]);\n int blksz = atoi(argv[2]);\n int num_threads = atoi(argv[3]);\n int reserved_set_size = atoi(argv[4]);\n int verify = 1;\n if (argc == 6) {\n verify = 0;\n }\n\n // Verify options.\n if (n < 1 ||\n blksz < 1 ||\n num_threads < 0 ||\n reserved_set_size < 0 ||\n (reserved_set_size >= num_threads && num_threads > 0)) {\n usage(argv[0]);\n }\n \n // Initialise random number generator.\n srand(time(NULL));\n\n // Generate random SPD matrix A.\n printf(\"Generating SPD matrix A...\\n\");\n int ldA = n;\n double *A = (double *) malloc(n * ldA * sizeof(double)); \n generate_dense_spd_matrix(n, A, ldA); \n\n // Copy A to Ain.\n printf(\"Copying A to Ain...\\n\");\n double *Ain = (double *) malloc(n * ldA * sizeof(double));\n memcpy(Ain, A, n * ldA * sizeof(double));\n\n // Start the runtime system.\n pcp_start(num_threads);\n\n // Set the execution mode.\n if (reserved_set_size == 0) {\n pcp_set_mode(PCP_REGULAR);\n } else {\n pcp_set_mode(PCP_FIXED);\n pcp_set_reserved_set_size(reserved_set_size);\n }\n\n // Call the driver.\n printf(\"Calling the driver routine...\\n\");\n parallel_block_chol(n, blksz, A, ldA);\n\n if (verify) {\n // Verify the solution.\n printf(\"Verifying the solution... \");\n fflush(stdout);\n double tm = pcp_get_time();\n LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, Ain, ldA);\n tm = pcp_get_time() - tm;\n double error = compare_lower_triangular_matrices(n, Ain, ldA, A, ldA);\n if (error < 1e-14) {\n printf(\"PASSED\\n\");\n } else {\n printf(\"FAILED\\n\");\n }\n printf(\"LAPACK_dpotrf took %.6lf seconds\\n\", tm);\n } else {\n printf(\"Verification disabled\\n\");\n }\n\n // Save the trace.\n printf(\"Saving the trace...\\n\");\n pcp_view_trace_tikz();\n\n // View statistics.\n printf(\"Printing statistics...\\n\");\n pcp_view_statistics_stdout();\n\n // Stop the runtime system.\n pcp_stop();\n\n // Clean up.\n free(A);\n free(Ain);\n\n return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "1bc5f6c126cf6dfbf07f942d2d0de4fe9f97f1b7", "size": 3638, "ext": "c", "lang": "C", "max_stars_repo_path": "src/examples/dpotrf/main.c", "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "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/examples/dpotrf/main.c", "max_issues_repo_name": "NLAFET/pcp-runtime", "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "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/examples/dpotrf/main.c", "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2533333333, "max_line_length": 98, "alphanum_fraction": 0.5511269929, "num_tokens": 1061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4877285098419043}} {"text": "#ifndef TOY_VN_GENERATOR_H\r\n#define TOY_VN_GENERATOR_H\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"sampled_distribution.h\"\r\n#include \r\n#include \r\n\r\nusing namespace std;\r\n\r\nnamespace flow_generator\r\n{\r\n\t// ------------------------------------\r\n\t// Initialize default parameters here.\r\n\t// ------------------------------------\r\n\r\n\tint n_pT = 6;\r\n\tdouble max_pT = 3000000.0;\r\n\tdouble min_pT\t\t\t\t = 0.0;\r\n\tint order = 2;\r\n\t//double eta_low = 2.0;\r\n\t//double eta_high = 10.0;\r\n\r\n\tint N_events_to_generate = 1000;\r\n\tint N_particles_per_event = 100;\r\n\tlong N_total_events = 0;\r\n\tlong N_running_total_events = 0;\r\n\r\n\tbool use_seed = true;\r\n\tint seed_index = -1;\r\n\r\n\tbool print_randomly_generated_data = false;\r\n\r\n\tbool include_psi2_PTslope_fluctuations = false;\r\n\tdouble v2_magnitude = 0.1;\r\n\r\n\tstring resultsDirectory = \"./results/\";\r\n\tstring output_name = resultsDirectory + \"/data.dat\";\r\n\r\n\t// ------------------------------------\r\n\t// Define structs and vectors.\r\n\t// ------------------------------------\r\n\r\n\t// struct for event information\r\n\ttypedef struct\r\n\t{\r\n\t\tint eventID;\r\n\t\tint Nparticles;\r\n\t\r\n\t\tvector > eta_vec;\r\n\t\tvector > pphi_vec;\r\n\t\tvector > pT_vec;\r\n\t} event_data;\r\n\r\n\t// declare needed vectors\r\n\tvector all_events;\r\n\t\r\n\tvector > pT_vec;\r\n\tvector > eta_vec;\r\n\tvector > phi_vec;\r\n\tvector > event_vec;\r\n\r\n\t//---------------------------------------------------------\r\n\t// Generate data randomly to mimic (non-factorizable) flow.\r\n\tvoid generate_random_data(int dataset=-1)\r\n\t{\r\n\t\tdouble delta_pT = (max_pT-min_pT)/(n_pT);\r\n\r\n\t\tpT_vec.clear();\r\n\t\teta_vec.clear();\r\n\t\tphi_vec.clear();\r\n\t\tevent_vec.clear();\r\n\t\tpT_vec = vector >(n_pT, vector (0));\r\n\t\teta_vec = vector >(n_pT, vector (0));\r\n\t\tphi_vec = vector >(n_pT, vector (0));\r\n\t\tevent_vec = vector >(n_pT, vector (0));\r\n\r\n\r\n\t\t// Set up distributions\r\n\t\tunsigned seed = chrono::system_clock::now().time_since_epoch().count();\r\n\t\tdefault_random_engine generator;\r\n\t\tif ( use_seed )\r\n\t\t\tgenerator = default_random_engine(seed);\r\n\t\telse\r\n\t\t\tgenerator = default_random_engine(seed_index);\r\n\r\n\t\tuniform_real_distribution mean_pT_distribution(0.90, 1.10);\r\n\t\t//const double mean_pT = mean_pT_distribution(generator);\r\n\t\tconst double mean_pT = 1.0;\r\n\t\texponential_distribution pT_distribution( mean_pT );\r\n\t\tnormal_distribution eta_distribution(0.0, 2.0);\r\n\t\tuniform_real_distribution v2_distribution(0.05, 0.45);\r\n\t\tuniform_real_distribution psi2_distribution(0.0, 2.0*M_PI);\r\n\t\tuniform_real_distribution pphi_distribution(0.0, 2.0*M_PI);\r\n\t\tnormal_distribution psi2_pTslope_distribution(0.0,0.1);\r\n\r\n\t\r\n\t\tauto phiFunc = [](double x, double v2) { return x + v2*sin(2.0*x); };\r\n\t std::mt19937 gen;\r\n\t\tif ( use_seed )\r\n\t\t\tgen = std::mt19937(seed);\r\n\t\telse\r\n\t\t\tgen = std::mt19937(seed_index);\r\n\r\n\t\tdouble fluctuation_switch_factor\r\n\t\t\t\t= double(include_psi2_PTslope_fluctuations);\r\n\r\n\t\tfor (int iEvent = 0; iEvent < N_events_to_generate; iEvent++)\r\n\t\t{\r\n\t\r\n\t\t\t//double v2 = v2_distribution(generator);\r\n\t\t\tdouble v2 = v2_magnitude;\r\n\t\t\tdouble psi2 = 0.0*psi2_distribution(generator);\r\n\t\t\tdouble psi2_pTslope = fluctuation_switch_factor\r\n\t\t\t\t\t\t\t\t\t* psi2_pTslope_distribution(generator);\r\n\t\t\t\r\n\t\t\tfor (int iParticle = 0; iParticle < N_particles_per_event; iParticle++)\r\n\t\t\t{\t\t\t\t\r\n\t\t\t\t// ---------------------------------------------\r\n\t\t\t\t// Try to mimic different types of flow effects\r\n\t\t\t\t// ---------------------------------------------\r\n\t\t\t\tconst double pT_value = pT_distribution(generator);\r\n\t\t\t //Sampled_distribution<> dist(phiFunc, 0.0, 2.0*M_PI, v2*pT_value / (mean_pT+pT_value));\r\n\t\t\t Sampled_distribution<> dist(phiFunc, 0.0, 2.0*M_PI, v2);\r\n\t\t\t\tconst double pphi_value = dist(gen) + psi2 + psi2_pTslope*pT_value;\r\n\t\t\t\t//const double pphi_value = dist(gen) + psi2 + 0.5*M_PI*pT_value / (mean_pT+pT_value);\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t// Sort into bins.\r\n\t\t\t\tdouble pT = pT_value;\r\n\t\t\t\tdouble eta = 0.0*eta_distribution(generator);\r\n\t\t\t\tdouble phi = pphi_value;\r\n\t\t\t\tint event = iEvent;\r\n\t\t\t\t\r\n\t\t\t\tif(pT > max_pT)\r\n\t\t\t\t{\r\n\t\t\t\t\t//cout << \"Warning: pT = \" << pT << \" larger than max_pT = \" << max_pT << \" in event = \" << event << endl;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tif(pT < min_pT)\r\n\t\t\t\t{\r\n\t\t\t\t\t//cout << \"Warning: pT = \" << pT << \" smaller than min_pT = \" << min_pT << \" in event = \" << event << endl;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tint bin = int((pT-min_pT)/delta_pT);\r\n\t\t\t\t\teta_vec[bin].push_back(eta);\r\n\t\t\t\t\tphi_vec[bin].push_back(phi);\r\n\t\t\t\t\tpT_vec[bin].push_back(pT);\r\n\t\t\t\t\tevent_vec[bin].push_back(event);\r\n\t\t\t\t\t//cout << \"Check: \" << pT << \" \" << eta << \" \" << phi << \" \" << event << \" \" << bin << endl;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\t\t\t\t\r\n\t\t//----------------------------------------------\r\n\t\tall_events.clear();\r\n\t\tall_events = vector(N_events_to_generate);\r\n\t\tfor ( auto & this_event : all_events )\r\n\t\t{\r\n\t\t\tthis_event.eta_vec = vector >( n_pT, vector(0) );\r\n\t\t\tthis_event.pphi_vec = vector >( n_pT, vector(0) );\r\n\t\t\tthis_event.pT_vec = vector >( n_pT, vector(0) );\r\n\t\t}\r\n\t\tfor (int bin = 0; bin < n_pT; bin++)\r\n\t\t{\r\n\t\t\tconst int n_particles_in_this_bin = event_vec[bin].size();\r\n\t\t\tfor (int iParticle = 0; iParticle < n_particles_in_this_bin; iParticle++)\r\n\t\t\t{\r\n\t\t\t\tint event_ID_of_this_particle = event_vec[bin][iParticle];\r\n\t\t\t\t\r\n\t\t\t\tall_events[event_ID_of_this_particle].eta_vec[bin].push_back( eta_vec[bin][iParticle] );\r\n\t\t\t\tall_events[event_ID_of_this_particle].pphi_vec[bin].push_back( phi_vec[bin][iParticle] );\r\n\t\t\t\tall_events[event_ID_of_this_particle].pT_vec[bin].push_back( pT_vec[bin][iParticle] );\r\n\t\t\t\tall_events[event_ID_of_this_particle].eventID = event_ID_of_this_particle;\r\n\t\t\t}\r\n\t\t}\r\n\t\t//----------------------------------------------\r\n\r\n\r\n\t\t//----------------------------------------------\r\n\t\t// Tally number of completed events\r\n\t\tN_running_total_events += N_events_to_generate;\r\n\t\tcout << \"Generated \" << N_particles_per_event * N_events_to_generate\r\n\t\t\t\t<< \" particles belonging to \"\r\n\t\t\t\t<< N_events_to_generate << \" events.\"\r\n\t\t\t\t<< endl;\r\n\t\tcout << \"Currently analyzed \" << N_running_total_events\r\n\t\t\t\t<< \" / \" << N_total_events << \" events.\" << endl;\r\n\r\n\r\n\t\t//----------------------------------------------\r\n\t\t// Dump simulated data to file if desired\r\n\t\tif ( print_randomly_generated_data )\r\n\t\t{\r\n\t\t\tint n_zero = static_cast( log10( N_particles_per_event*N_total_events ) )-1;\r\n\t\t\tstring dataset_stem = ( dataset >= 0 ) ?\r\n\t\t\t\t\t\t\t\t\tstd::string(n_zero - std::to_string(dataset).length(), '0')\r\n\t\t\t\t\t\t\t\t\t+ std::to_string( dataset ) : \"\";\r\n\t\t\tstring RNG_filename = resultsDirectory + \"/event_\" + dataset_stem + \".dat\";\r\n\t\t\tofstream RNG_output( RNG_filename.c_str() );\r\n\t\t\tfor ( auto & this_event : all_events )\r\n\t\t\tfor (int bin = 0; bin < n_pT; bin++)\r\n\t\t\t{\r\n\t\t\t\tconst int n_particles_in_this_bin = this_event.eta_vec[bin].size();\r\n\t\t\t\tconst auto & this_pT_bin = this_event.pT_vec[bin];\r\n\t\t\t\tconst auto & this_pphi_bin = this_event.pphi_vec[bin];\r\n\t\t\t\tconst auto & this_eta_bin = this_event.eta_vec[bin];\r\n\t\t\t\tfor (int iParticle = 0; iParticle < n_particles_in_this_bin; iParticle++)\r\n\t\t\t\t\tRNG_output << setprecision(15) << setw(18)\r\n\t\t\t\t\t\t\t /*<< this_pT_bin[iParticle] << \" \"\r\n << this_eta_bin[iParticle] << \" \"*/\r\n << this_pphi_bin[iParticle] /*<< \" \"\r\n << this_event.eventID*/ << endl;\r\n\t\t\t}\r\n\t\t\tRNG_output.close();\r\n\t\t}\r\n\t\t\r\n\t\treturn;\r\n\t}\r\n\r\n}\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "7fb21322ff1fba779f413603f1c541b48f46a91a", "size": 8345, "ext": "h", "lang": "C", "max_stars_repo_path": "toy_vn_generator/generator/include/toy_vn_generator.h", "max_stars_repo_name": "astrophysicist87/PHripser", "max_stars_repo_head_hexsha": "7a124f6fe66fb802f63a2f6f548f134fc265133f", "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": "toy_vn_generator/generator/include/toy_vn_generator.h", "max_issues_repo_name": "astrophysicist87/PHripser", "max_issues_repo_head_hexsha": "7a124f6fe66fb802f63a2f6f548f134fc265133f", "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": "toy_vn_generator/generator/include/toy_vn_generator.h", "max_forks_repo_name": "astrophysicist87/PHripser", "max_forks_repo_head_hexsha": "7a124f6fe66fb802f63a2f6f548f134fc265133f", "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.2109704641, "max_line_length": 113, "alphanum_fraction": 0.5743559017, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.4875564131630731}} {"text": "/*\n * SPDX-License-Identifier: BSD-3-Clause\n * \n * example_02-StructOfArrays-Naive-Omp.c : \n * Example of SPH Density Calculation using a \n * naive implementation of the main density loop, \n * no neighbours earch, and Struct of Arrays (SoA) \n * data layout and OpenMP parallelization.\n *\n * (C) Copyright 2021 José Hugo Elsas\n * Author: José Hugo Elsas \n *\n * Command Line Options: \n * -runs : Set the number of repetitions (runs) for\n * calculating the density. The value of\n * the density is based on the last \n * iteration.\n * Default value: 1\n * -run_seed : Flag to set an alternative seed use for\n * for the PRNG. Instead of feeding seed\n * to the PRNG directly, it feeds \n * seed + iteration, as to generate different\n * configurations for each iteration. \n * Default value: 0 - (possible 0/1)\n * -seed : Set the seed to use for the SPH particles \n * uniform position generation in the box\n * Default value: 123123123\n *\n * -N : Set the number of SPH particles to be used\n * Default value: 1e5 = 100,000\n * -h : Set the value of the smoothing kernel \n * parameter h, which corresponds to half\n * of the support of the kernel. \n * Default value: 0.05\n *\n * -Nx : Set the number of Cells in the X direction\n * Default value: 10\n * -Ny : Set the number of Cells in the Y direction\n * Default value: 10\n * -Nz : Set the number of Cells in the Z direction\n * Default value: 10\n * \n * -Xmin : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 0.0\n * \n * -Xmax : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Ymax : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Zmax : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 1.0\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n#include \"sph_utils.h\"\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n#define COMPUTE_BLOCKS 1\n\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times);\n\nint compute_density_3d_naive_omp(int N,double h,\n double* restrict x, double* restrict y,\n double* restrict z, double* restrict nu,\n double* restrict rho);\n\ndouble w_bspline_3d(double r,double h);\n\nint main(int argc, char **argv){\n bool run_seed = false; // By default the behavior is is to use the same seed\n int runs = 1,err; // it only runs once\n long int seed = 123123123; // The default seed is 123123123\n int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000\n double h=0.05; // The default kernel smoothing length is h = 0.05\n linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method\n SPHparticle *lsph; // Uninitialized array of SPH particles\n\n box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box\n\n // allow for command line customization of the run\n arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command \n // line arguments and override default values\n\n err = SPHparticle_SoA_malloc(N,&lsph); // Create an array of N particles\n if(err)\n fprintf(stderr,\"error in SPHparticle_SoA_malloc\\n\");\n\n void *swap_arr = malloc(N*sizeof(double));\n double times[runs*COMPUTE_BLOCKS];\n\n for(int run=0;run : index (or value) or the present iteration\n * run_seed : boolean defining whether to use run index for seed or not\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * seed : seed for GSL PRNG generator to generate particle positions\n * box : Box of linked list cells, encapsulating the 3d domain\n * lsph : Array (pointer) of SPH particles to be updated\n * times : Array to store the computation timings to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n * times : Times is updated by reference\n */\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times)\n{\n int err;\n \n // Initialize the particles' positions and other values\n if(run_seed)\n err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);\n else\n err = gen_unif_rdn_pos_box(N,seed,box,lsph);\n\n if(err)\n fprintf(stderr,\"error in gen_unif_rdn_pos\\n\");\n\n // ------------------------------------------------------ //\n\n double t0,t1;\n\n t0 = omp_get_wtime();\n \n compute_density_3d_naive_omp(N,h,lsph->x,lsph->y,lsph->z,\n lsph->nu,lsph->rho); // Compute the density for all particles\n\n t1 = omp_get_wtime();\n\n // ------------------------------------------------------ //\n\n times[COMPUTE_BLOCKS*run+0] = t1-t0; // Only one component to measure time\n\n return 0;\n}\n\n/*\n * Function compute_density_3d_naive_omp:\n * Computes the SPH density from the particles naively (i.e. direct loop).\n * The outer-most loop is parallelized using openMP. \n * \n * Arguments:\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * x : Array of particles' X positions\n * y : Array of particles' Y positions\n * z : Array of particles' Z positions\n * nu : Array of particles' density weights (i.e. masses)\n * Returns:\n * 0 : error code returned\n * rho : Array of particles' densities\n */\nint compute_density_3d_naive_omp(int N,double h,\n double* restrict x, double* restrict y,\n double* restrict z,double* restrict nu,\n double* restrict rho){\n memset(rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero\n\n #pragma omp parallel for // Iterate in parallel\n for(int64_t ii=0;ii : Distance between particles\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * Returns:\n * wq : Normalized value of the kernel\n */\ndouble w_bspline_3d(double r,double h){\n const double A_d = 3./(2.*M_PI*h*h*h); // The 3d normalization constant \n double q=0.; // normalized distance, initialized to zero\n \n if(r<0||h<=0.) // If either distance or smoothing length\n exit(10); // are negative, declare an emergency\n \n q = r/h; // Compute the normalized distance\n if(q<=1) // If the distance is small\n return A_d*(2./3.-q*q + q*q*q/2.0); // Compute this first polynomal\n else if((1.<=q)&&(q<2.)) // If the distance is a bit larger\n return A_d*(1./6.)*(2.-q)*(2.-q)*(2.-q); // Compute this other polynomial \n else // Otherwise, if the distance is large\n return 0.; // The value of the kernel is 0\n}", "meta": {"hexsha": "37bd96a1684f5e29d6bf6c3bd57f3d6f3498370f", "size": 10471, "ext": "c", "lang": "C", "max_stars_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c", "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c", "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoA/exec/example_02-StructOfArrays-Naive-Omp.c", "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3873517787, "max_line_length": 104, "alphanum_fraction": 0.5669945564, "num_tokens": 2614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4869284078079321}} {"text": "/*\n * hubble.c\n * \n * written by christian wagner\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define VC 299792.458\n#define TWOPI 6.283185307179586\n#define PI 3.141592653589793\n#define Tcmb 2.725\n#define pow2(x) ((x)*(x))\n#define pow3(x) ((x)*(x)*(x))\n#define pow4(x) ((x)*(x)*(x)*(x))\n\n#include \"hubble.h\"\n\ndouble hubble(struct cosmo mycosmo, double a){\n double H0=mycosmo.hub*100.;\n double Omega_m = mycosmo.wm/pow2(mycosmo.hub);\n double Omega_r = 4.15e-5/pow2(mycosmo.hub);\n double Omega_X = 1.-Omega_m;\n double Omega_k = 0.;\n\n return H0*sqrt(Omega_r/pow4(a)+Omega_m/pow3(a)+Omega_k/pow2(a)+Omega_X*pow(a,-3*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a)));\n\n}\n\n\ndouble co_distance_int(double a,void * params){\n double t;\n struct cosmo mycosmo = *(struct cosmo *) params;\n\n return 1./(a*a*hubble(mycosmo,a));\n\n}\n\ndouble co_distance(struct cosmo mycosmo, double a){\n\n gsl_function F;\n double result;\n double epsabs=0.001;\n double epsrel=0.001;\n double abserr;\n size_t neval;\n\n F.function = &co_distance_int;\n F.params = &mycosmo;\n\n\n gsl_integration_qng (&F, a, 1., epsabs, epsrel, &result, &abserr, &neval);\n\n return result*VC*mycosmo.hub;\n\n}\n\ndouble ang_dist(struct cosmo mycosmo, double a){\n return co_distance(mycosmo,a); // assuming flatness\n}\n\n\nint\node_growth (double a, const double y[], double f[], void *params)\n{\n\n struct cosmo mycosmo = * (struct cosmo *) params;\n\n\n double w_a=mycosmo.w0+(1-a)*mycosmo.wa;\n double Omega_m=mycosmo.wm/pow2(mycosmo.hub);\n double Omega_X=1-Omega_m;\n double Xvar=(1-Omega_m)*pow(a,-3.*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a))/(Omega_m/(a*a*a)+(1-Omega_m)*pow(a,-3.*(1+mycosmo.w0+mycosmo.wa))*exp(-3.*mycosmo.wa*(1.-a)));\n\n\n f[0] = y[1];\n f[1] = -1.5*(1.-w_a)*Xvar*y[0]/(a*a) - (3.5-1.5*w_a*Xvar)*y[1]/a ;\n\n return GSL_SUCCESS;\n}\n\nint\njac_growth (double a, const double y[], double *dfdy, \n double dfdt[], void *params)\n{\n return GSL_SUCCESS;\n}\n\n\ndouble growth(struct cosmo mycosmo, double a){\n\n const gsl_odeiv_step_type * T \n\t= gsl_odeiv_step_rkf45;\n \n gsl_odeiv_step * s \n\t= gsl_odeiv_step_alloc (T, 2);\n gsl_odeiv_control * c \n\t= gsl_odeiv_control_y_new (1e-12, 0.0);\n gsl_odeiv_evolve * e \n\t= gsl_odeiv_evolve_alloc (2);\n \n double mu = 10;\n gsl_odeiv_system sys = {ode_growth, jac_growth, 2, &mycosmo};\n \n \n\n double t1=a;\n double t = 1.E-12;\n\n double d1;\n\n double h = 1e-12;\n double y[2] = { 1.0, 0.0 };\n\n int status;\n \n while (t < t1){\n status = gsl_odeiv_evolve_apply (e, c, s,\n\t\t\t\t\t &sys, \n\t\t\t\t\t &t, t1,\n\t\t\t\t\t &h, y);\n if (h>0.001)\n\th=0.001;\n \n \n if (status != GSL_SUCCESS)\n\tbreak;\n \n }\n\t\n d1=y[0]*(t);\n\n gsl_odeiv_evolve_free (e);\n gsl_odeiv_control_free (c);\n gsl_odeiv_step_free (s);\n\n return d1;\n}\n\n\n\n\ndouble z_lastscattering(struct cosmo mycosmo){\n /*\n z_lastscattering(cosmo):\n Returns z_LS from Hu & White, DampingTail paper.\n */\n double wm = mycosmo.wm;\n double wb = mycosmo.wb;\n double b1 = 0.0783*pow(wb,(-0.238))/(1+39.5*pow(wb,0.763));\n double b2 = 0.560/(1+21.1*pow(wb,1.81));\n double zls= 1048.*(1+0.00124*pow(wb,(-0.738)))*(1+b1*pow(wm,b2));\n return zls;\n}\n\ndouble soundhorizon(struct cosmo mycosmo){\n /*\n soundhorizon(cosmo):\n A fit to the sound horizon, in Mpc, from Hu & Sugiyama (1995), Eq. B6\n */\n double wm = mycosmo.wm;\n double wb = mycosmo.wb;\n double wg = 2.4888e-5*pow4(Tcmb/2.73);\n double r0 = 0.75*wb/wg;\n double zeq= 5464.0*(wm/0.135)/pow4(Tcmb/2.725)/(1+0.6851)-1.0;\n double req= r0/(1.+zeq);\n double zLS= z_lastscattering(mycosmo);\n double rls= r0/(1+zLS);\n double tmp= (sqrt(1.+rls)+sqrt(rls+req))/(1.+sqrt(req));\n tmp= 3997.0*sqrt(wg/wm/wb)*log(tmp);\n return(tmp);\n}\n\ndouble distls(struct cosmo mycosmo){\n /*\n distls(cosmo):\n Returns the distance to LS, in Mpc.\n */\n double zLS = z_lastscattering(mycosmo);\n double dLS = ang_dist(mycosmo,1./(1.+zLS))/mycosmo.hub;\n return(dLS);\n}\n\n\ndouble solvehh(double dLS,struct cosmo mycosmo){\n /*\n solvehh(dLS,cosmo):\n Solves for h given the other cosmological parameters and the distance\n to last scattering (in Mpc).\n */\n struct cosmo hmin = mycosmo;\n hmin.hub = 0.3;\n // printf(\"min_cosmo: %g %g %g %g %g\\n\",hmin.hub,hmin.w0,hmin.wa,hmin.wm,hmin.wb);\n double ymin = distls(hmin)-dLS;\n // printf(\"ymin: %g\\n\",ymin);\n struct cosmo hmax = mycosmo;\n hmax.hub = 1.0;\n double ymax = distls(hmax)-dLS;\n // printf(\"ymax: %g\\n\",ymax);\n double ymid;\n struct cosmo hmid = mycosmo;\n while (fabs(hmax.hub-hmin.hub)>1e-3){\n hmid.hub = (hmax.hub+hmin.hub)/2.0;\n ymid = distls(hmid)-dLS;\n if (ymin*ymid<0){\n\thmax = hmid;\n\tymax = ymid;\n } else {\n hmin = hmid;\n ymin = ymid;\n }\n }\n // printf(\"hubble from CMB: %g\\n\",hmid.hub);\n return hmid.hub;\n}\n\n//void getH0fromCMB(double *xstar, double myh, double *rs, double *z_lss, double *d_lss, double *h_CMB, int *writeout, char *fname){\nvoid getH0fromCMB(double *xstar, double *stuff){\n\n FILE *fp;\n\n struct cosmo mycosmo={ 0.72, xstar[3], 0, xstar[1], xstar[0]};\n\n\n\n double rs=soundhorizon(mycosmo);\n stuff[0] = rs;\n\n double z_lss=z_lastscattering(mycosmo);\n stuff[1] = z_lss;\n \n double d_lss=302.4*rs/PI;\n stuff[2] = d_lss;\n\n double hubble_cmb= solvehh(d_lss,mycosmo);\n stuff[3] = hubble_cmb;\n \n}\n\n// Linker function for use with Fortran\n\nvoid geth0fromcmb_(double *xstar, double *stuff){\n void getH0fromCMB();\n getH0fromCMB(xstar,stuff);\n}\n", "meta": {"hexsha": "894c34d77c9320f73d5255a7491a3184d7bf5d86", "size": 5592, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmosis-standard-library/structure/FrankenEmu/hubble.c", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/FrankenEmu/hubble.c", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/FrankenEmu/hubble.c", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 22.1904761905, "max_line_length": 184, "alphanum_fraction": 0.6334048641, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48691106404577766}} {"text": "/*******************************************************************\nFUNCTION NAME: interpolate - performs the interpolation to calculate\n the pixel value e.g. during resampling\n\nINPUT: interpolation - interpolation method (nearest neighbor, bilinear, sinc)\n inbuf - input image buffer\n nLines - number of lines (image buffer)\n nSamples - number of samples per line (image buffer)\n xLine - line of interest\n xSample - sample position within line\n weighting - weighting function to be applied (Kaiser, Hamming)\n nKernel - kernel size for sinc function\n*******************************************************************/\n#include \n#include \n\n#include \n#include \n#include \"asf.h\"\n#include \"asf_raster.h\"\n#include \"float_image.h\"\n\n#define SQR(X) ((X)*(X))\n\n// Some parameters and weights for bicubic interpolation\n#define CUBE(X) ((X)*(X)*(X))\n#define P(X) ( X > 0 ? X : 0 )\n\n// For sinc interpolation, the goal is to weight source values using a\n// sinc function. We want to position the peak of the sinc at the\n// point of interest. The sinc filter itself will interpolate a small\n// number of point, perhaps 8 or 16, for example. In order to achieve\n// the desired location of the peak, we want to introduce a shift in\n// the sinc function computed. However, we don't want to recompute\n// the sinc function for every point to be interpolated! The solution\n// is to precompute an array of slightly shifted sinc functions, and\n// then choose the appropriate one for the point we are interpolating.\n// For example, if we have known values for 1 and 2, and we want to\n// interpolate a value for 1.2, we choose the (1.2 - 1.0) * (2 - 1) *\n// NUM_SINCS sinc function to evaluate the result.\n#define NUM_SINCS 512 // Number of sinc functions to compute.\n\n// For convenience using buffered image functions\n#define GET_PIXEL(x, y) float_image_get_pixel (inbuf, x, y)\n#define SET_PIXEL(x, y, value) float_image_set_pixel (inbuf, x, y, value)\n\n// Fetch pixel ii, jj from inbuf, where inbuf is taken to be an image\n// nSamples wide and nLines high. If ii, jj is outside the image, a\n// \"reflected\" value is returned. For example, these two calls will\n// return the same pixel:\n//\n// get_pixel_with_reflection (inbuf, sample_count, line_count, -1, -2) \n// get_pixel_with_reflection (inbuf, sample_count, line_count, 1, 2);\n//\n// If the reflected indicies are still outside the image, an exception\n// is triggered.\n\n//static float\n//get_pixel_with_reflection (float *inbuf, int nSamples, int nLines, int sample,\n//\t\t\t int line)\n//{\n// int ii = sample;\t\t// Convenience alias.\n// int jj = line;\t\t// Convenience alias.\n// // Handle reflection at image edges.\n// if ( G_UNLIKELY (ii < 0) ) { \n// ii = -ii; \n// }\n// else if ( G_UNLIKELY (ii >= nSamples) ) { \n// ii = ii - (ii - nSamples + 1) - 1; \n// }\n// if ( G_UNLIKELY (jj < 0) ) { \n// jj = -jj; \n// }\n// else if ( G_UNLIKELY (jj >= nLines) ) { \n// jj = jj - (jj - nLines + 1) - 1; \n// }\n// // Now we better be in the image.\n// assert (ii >= 0 && ii < nSamples);\n// assert (jj >= 0 && jj < nLines);\n//\n// return inbuf[nSamples * jj + ii];\n//}\n\nvoid samples2coefficients(FloatImage *inbuf, char dimension)\n{\n int ii, kk;\n float z = sqrt(3.0) - 2.0;\n float lambda = (1.0 - z) * (1.0 - 1.0/z);\n float value;\n\n // Apply overall gain\n for (ii=0; iisize_x; ii++)\n for (kk=0; kksize_y; kk++) {\n value = GET_PIXEL(ii,kk) * lambda;\n SET_PIXEL(ii,kk,value);\n }\n\n for (kk=0; kksize_y; kk++) {\n // Causal initialization (first pixel of line)\n \n }\n\n // Causal recursion\n \n // Anticausal initialization\n \n // Anticausal recursion\n \n\n}\n\nfloat interpolate(interpolate_type_t interpolation, FloatImage *inbuf, float yLine, \n\t\t float xSample, weighting_type_t weighting, int sinc_points)\n{\n int ix, iy, ii, kk, ll, xI[4], yI[4];\n float a00, a10, a01, a11;\n float value, dx, dy, wx[4], wy[4], w;\n \n /* Get closed pixel position to start from */\n\n switch ( interpolation ) \n {\n case NEAREST:\n ix = (int) (xSample + 0.5);\n iy = (int) (yLine + 0.5);\n value = GET_PIXEL(ix,iy);\n break;\n\n case BILINEAR:\n assert (xSample >= 0.0);\n assert (yLine >= 0.0);\n assert (xSample <= inbuf->size_x - 1);\n assert (yLine <= inbuf->size_y - 1);\n ix = floor(xSample);\n iy = floor(yLine);\n \n a00 = GET_PIXEL(ix,iy);\n a10 = GET_PIXEL(ix+1,iy) - GET_PIXEL(ix,iy);\n a01 = GET_PIXEL(ix,iy+1) - GET_PIXEL(ix,iy);\n a11 = GET_PIXEL(ix,iy) - GET_PIXEL(ix+1,iy) - GET_PIXEL(ix,iy+1) \n\t+ GET_PIXEL(ix+1,iy+1);\n value = (a00 + a10 * (xSample - ix) + a01 * (yLine - iy) \n\t + a11 * (xSample - ix) * (yLine - iy));\n break;\n\n case BICUBIC:\n assert (xSample >= 0.0);\n assert (yLine >= 0.0);\n assert (xSample <= inbuf->size_x - 1);\n assert (yLine <= inbuf->size_y - 1);\n ix = floor(xSample);\n iy = floor(yLine);\n dx = xSample - ix;\n dy = yLine - iy;\n \n // Calculating weights\n for (ii=-1; ii<=2; ii++) {\n\twx[ii+1] = 1.0/6.0 * (CUBE(P(ii-dx+2)) - 4*CUBE(P(ii-dx+1)) \n\t\t\t + 6*CUBE(P(ii-dx)) - 4*CUBE(P(ii-dx-1)));\n\twy[ii+1] = 1.0/6.0 * (CUBE(P(dy-ii+2)) - 4*CUBE(P(dy-ii+1)) \n\t\t\t + 6*CUBE(P(dy-ii)) - 4*CUBE(P(dy-ii-1)));\n }\n \n // Get the interpolated pixel value\n value = 0.0;\n for (ii=-1; ii<=2; ii++)\n\tfor (kk=-1; kk<=2; kk++)\n\t value += GET_PIXEL(ix+ii,iy+kk) * wx[ii+1] * wy[kk+1];\n \n break;\n \n case SPLINES:\n // Determine B-Spline coefficients.\n // This is a essentially a pre-filtering applied to the entire image \n // that converts the image from a sample representation into a \n // representation based on B-spline coefficients. \n // Without this step the result would look blurry at the end.\n\n // Convert samples to coefficients in x direction\n samples2coefficients(inbuf, 'x');\n\n // Convert samples to coefficients in y direction\n samples2coefficients(inbuf, 'y');\n\n // Calculate interpolation indices\n ii = (int)floor(xSample) - 1;\n kk = (int)floor(yLine) - 1;\n for (ll=0; ll<=3; ll++) {\n\txI[ll] = ii++;\n\tyI[ll] = kk++;\n }\n\n // Calculate interpolation weights\n w = xSample - (float)xI[1];\n wx[3] = (1.0/6.0)*CUBE(xSample);\n wx[0] = (1.0/6.0) + (1.0/2.0)*w*(w-1.0) - wx[3];\n wx[2] = w + wx[0] - 2.0*wx[3];\n wx[1] = 1.0 - wx[0] - wx[2] - wx[3];\n w = yLine - (float)yI[1];\n wy[3] = (1.0/6.0)*CUBE(xSample);\n wy[0] = (1.0/6.0) + (1.0/2.0)*w*(w-1.0) - wy[3];\n wy[2] = w + wy[0] - 2.0*wy[3];\n wy[1] = 1.0 - wy[0] - wy[2] - wy[3];\n\n // Get interpolation value\n value = 0.0;\n for (kk=0; kk<=3; kk++) {\n\tw = 0.0;\n\tfor (ii=0; ii<=3; ii++)\n\t w += wx[ii] * 1;\n\tvalue += wy[kk] * w;\n }\n break;\n case SINC:\n break;\n default:\n assert (FALSE);\n break;\n }\n\n return value;\n}\n", "meta": {"hexsha": "e832c1fe1dbf79b5d67a2ca40c8bea7404425406", "size": 7113, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_raster/interpolate.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/libasf_raster/interpolate.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/libasf_raster/interpolate.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.8968609865, "max_line_length": 84, "alphanum_fraction": 0.5755658653, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4868415923200341}} {"text": "/* This module contains the routine rotCurveSpline, which takes a\n tabulated rotaiton curve and calculates a B-spline fit to it and\n its derivatives. */\n\n#include \n#include \n#include \n#include \n#include \n#include \"rotCurveSpline.h\"\n\nstruct dpsidr_params {\n gsl_bspline_workspace *wksp;\n#ifdef GSL1\n gsl_bspline_deriv_workspace *dwksp;\n#endif\n gsl_vector *B, *coef;\n gsl_matrix *dB, *cov;\n};\n\ndouble dpsidr(double r, void *params) {\n double vphi, err;\n struct dpsidr_params *p = (struct dpsidr_params *) params;\n\n#ifdef GSL1\n gsl_bspline_deriv_eval(log(r), 2, p->dB, p->wksp, p->dwksp);\n#else\n gsl_bspline_deriv_eval(log(r), 2, p->dB, p->wksp);\n#endif\n gsl_matrix_get_col(p->B, p->dB, 0);\n gsl_multifit_linear_est(p->B, p->coef, p->cov, &vphi, &err);\n return(-vphi*vphi/r);\n}\n\nvoid \nrotCurveSpline(const double *rTab, const double *vTab,\n\t const unsigned long nTab,\n\t const unsigned long bspline_degree,\n\t const unsigned long bspline_breakpoints,\n\t const double *r, const unsigned long nr, \n\t double *vphi, double *psi,\n\t double *beta) {\n\n gsl_vector *xInput, *vInput, *coef, *B, *bkpt_vec;\n gsl_matrix *dB, *cov, *pred;\n gsl_bspline_workspace *wksp;\n#ifdef GSL1\n gsl_bspline_deriv_workspace *dwksp;\n#endif\n gsl_multifit_linear_workspace *mw;\n gsl_integration_workspace *intwksp;\n gsl_function dpsidr_func;\n struct dpsidr_params params;\n double x0, x1, v0, bkpt_sum_target, sum, x, Bij, chisq;\n double dvphidlogr, err, psiInt;\n unsigned long bspline_ncoef, i, j, ptr;\n\n /* Safety check: make sure we have enough data points for the choice\n of degree and breakpoints */\n bspline_ncoef = bspline_breakpoints + bspline_degree - 2;\n if (bspline_ncoef > nTab) {\n fprintf(stderr, \"Error: %lu data points for %lu coefficients; ndata must be >= ncoef = nbreakpoints + degree - 2\\n\", nTab, bspline_ncoef);\n exit(1);\n }\n\n /* Initialize the GSL vectors to hold the data table */\n xInput = gsl_vector_alloc(nTab);\n vInput = gsl_vector_alloc(nTab);\n for (i=0; i0; i--) {\n gsl_integration_qag(&dpsidr_func, r[i], r[i-1],\n\t\t\t1e-6*vphi[i]*vphi[i]*\n\t\t\t(r[i+1]-r[i]),\n\t\t\t1e-6, 4096, 6, intwksp, &psiInt, &err);\n psi[i-1] = psi[i] - psiInt;\n }\n\n /* Free memory */\n gsl_matrix_free(pred);\n gsl_vector_free(bkpt_vec);\n gsl_vector_free(xInput);\n gsl_vector_free(vInput);\n gsl_multifit_linear_free(mw);\n gsl_vector_free(coef);\n gsl_vector_free(B);\n gsl_matrix_free(dB);\n gsl_matrix_free(cov);\n gsl_bspline_free(wksp);\n#ifdef GSL1\n gsl_bspline_deriv_free(dwksp);\n#endif\n gsl_integration_workspace_free(intwksp);\n}\n", "meta": {"hexsha": "e54d595667b1eab08e36adf67c3ad0f5d33075a6", "size": 7292, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 32.4088888889, "max_line_length": 142, "alphanum_fraction": 0.6801974767, "num_tokens": 2316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.48668621873174894}} {"text": "#include \n#include \n#include \n\nvoid integral_recur ( int nmin, int nmax, double vals[]);\n\nvoid integral_recur (int nmin, int nmax, double vals[])\n{\n double IN = 0;\n int i = nmax - 1;\n vals [nmax] = IN;\n while ( i >= nmin)\n {\n vals[i] = (IN + exp (-1.))/((double) i);\n i = i - 1;\n }\n}\n\n", "meta": {"hexsha": "e559e3267f0bf0779a78e50c9cf0fa8a409ef63a", "size": 357, "ext": "c", "lang": "C", "max_stars_repo_path": "integral_recur.c", "max_stars_repo_name": "Paulther/hw7", "max_stars_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integral_recur.c", "max_issues_repo_name": "Paulther/hw7", "max_issues_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integral_recur.c", "max_forks_repo_name": "Paulther/hw7", "max_forks_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7894736842, "max_line_length": 57, "alphanum_fraction": 0.5434173669, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.48645101928408624}} {"text": "/////////////////\n//example25.5.c\n/////////////////\n#include \n#include \n#include \n#include \n#include \n\ntypedef struct{\n double *a; //y=a[0]x[0]+a[1]x[1]+...a[ka]y[ka]+b[0]u[0]+b[1]u[1]+...+b[kb]u[kb]\n // double *a; //y[t+1]=a[0]y[t]+a[1]y[t-1]+...a[ka]y[t-ka]+b[0]u[t]+b[1]u[t-1]+...+b[kb]u[t-kb]\n double *b;\n double *x;\n double *u;\n int k,kx,ku;\n double xmax;\n double umax;\n double y;\n int _dim;\n double *_y;\n double *_y_err;\n // double *_dydt_in;\n // double *_dydt_out;\n double h;\n double _t;\n} LINEAR;\n\n//#define dim_linear 4\n//int linearfunc (double t, const double y[], double f[], void *params)\n//{\n// LINEAR *c = (LINEAR *)params;\n// f[0] = y[1];\n// f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n// f[2] = y[3]; \n// f[3] = (c->F+c->T*sin(y[0]))/c->M;\n// return GSL_SUCCESS;\n//}\n////////////////\n#define square(x) ((x)*(x))\nLINEAR linear;\nint PLANT_NO=1;\nint initialize()\n{\n if(PLANT_NO==1){\n linear.kx=1;\n linear.ku=1;\n linear.k=linear.kx+linear.ku;\n linear.a=(double*)malloc(sizeof(double)*linear.k);\n linear.b=&linear.a[linear.kx];\n linear.x=(double*)malloc(sizeof(double)*linear.k+1);\n linear.u=&linear.x[linear.kx];\n \n linear.a[0]=0.9;\n linear.b[0]=1;\n }\n else if(PLANT_NO==2){\n linear.kx=3;\n linear.ku=1;\n linear.k=linear.kx+linear.ku;\n linear.a=(double*)malloc(sizeof(double)*linear.k);\n linear.b=&linear.a[linear.kx];\n linear.x=(double*)malloc(sizeof(double)*linear.k+1);\n linear.u=&linear.x[linear.kx];\n \n linear.a[0]=1;\n linear.a[1]=1;\n linear.a[2]=1;\n linear.b[0]=1;\n }\n linear.umax=6.0;//check// linear.Fmax=30;//check\n int i;for(i=0;i0) AP_u_max=linear.umax=_AP_umax;\n else AP_u_max=linear.umax;\n\n AP_u_min=-AP_u_max;\n rr=AP_r=_AP_r;//10\n rr_kyoyou=_rr_kyoyou;\n C_MODE=11;\n#else\n linear.h=0.01;\n#endif\n linear._t=0;\n // int i;for(i=0;ilinear.umax) linear.u[0]=linear.umax; \n else if(uu<-linear.umax) linear.u[0]=-linear.umax;\n else linear.u[0]=uu;\n // current output\n linear.y=0;\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\n#define SEQUENCE_COUNT 8\n#define SEQUENCE_MAX 7\n\n/* Bader-Deuflhard extrapolation sequence */\nstatic const int bd_sequence[SEQUENCE_COUNT] =\n { 2, 6, 10, 14, 22, 34, 50, 70 };\n\ntypedef struct\n{\n gsl_matrix *d; /* workspace for extrapolation */\n gsl_matrix *a_mat; /* workspace for linear system matrix */\n gsl_permutation *p_vec; /* workspace for LU permutation */\n\n double x[SEQUENCE_MAX]; /* workspace for extrapolation */\n\n /* state info */\n size_t k_current;\n size_t k_choice;\n double h_next;\n double eps;\n\n /* workspace for extrapolation step */\n double *yp;\n double *y_save;\n double *yerr_save;\n double *y_extrap_save;\n double *y_extrap_sequence;\n double *extrap_work;\n double *dfdt;\n double *y_temp;\n double *delta_temp;\n double *weight;\n gsl_matrix *dfdy;\n\n /* workspace for the basic stepper */\n double *rhs_temp;\n double *delta;\n\n /* order of last step */\n size_t order;\n}\nbsimp_state_t;\n\n/* Compute weighting factor */\n\nstatic void\ncompute_weights (const double y[], double w[], size_t dim)\n{\n size_t i;\n for (i = 0; i < dim; i++)\n {\n double u = fabs(y[i]);\n w[i] = (u > 0.0) ? u : 1.0;\n }\n}\n\n/* Calculate a choice for the \"order\" of the method, using the\n * Deuflhard criteria. \n */\n\nstatic size_t\nbsimp_deuf_kchoice (double eps, size_t dimension)\n{\n const double safety_f = 0.25;\n const double small_eps = safety_f * eps;\n\n double a_work[SEQUENCE_COUNT];\n double alpha[SEQUENCE_MAX][SEQUENCE_MAX];\n\n int i, k;\n\n a_work[0] = bd_sequence[0] + 1.0;\n\n for (k = 0; k < SEQUENCE_MAX; k++)\n {\n a_work[k + 1] = a_work[k] + bd_sequence[k + 1];\n }\n\n for (i = 0; i < SEQUENCE_MAX; i++)\n {\n alpha[i][i] = 1.0;\n for (k = 0; k < i; k++)\n {\n const double tmp1 = a_work[k + 1] - a_work[i + 1];\n const double tmp2 = (a_work[i + 1] - a_work[0] + 1.0) * (2 * k + 1);\n alpha[k][i] = pow (small_eps, tmp1 / tmp2);\n }\n }\n\n a_work[0] += dimension;\n\n for (k = 0; k < SEQUENCE_MAX; k++)\n {\n a_work[k + 1] = a_work[k] + bd_sequence[k + 1];\n }\n\n for (k = 0; k < SEQUENCE_MAX - 1; k++)\n {\n if (a_work[k + 2] > a_work[k + 1] * alpha[k][k + 1])\n break;\n }\n\n return k;\n}\n\nstatic void\npoly_extrap (gsl_matrix * d,\n const double x[],\n const unsigned int i_step,\n const double x_i,\n const double y_i[],\n double y_0[], double y_0_err[], double work[], const size_t dim)\n{\n size_t j, k;\n\n DBL_MEMCPY (y_0_err, y_i, dim);\n DBL_MEMCPY (y_0, y_i, dim);\n\n if (i_step == 0)\n {\n for (j = 0; j < dim; j++)\n {\n gsl_matrix_set (d, 0, j, y_i[j]);\n }\n }\n else\n {\n DBL_MEMCPY (work, y_i, dim);\n\n for (k = 0; k < i_step; k++)\n {\n double delta = 1.0 / (x[i_step - k - 1] - x_i);\n const double f1 = delta * x_i;\n const double f2 = delta * x[i_step - k - 1];\n\n for (j = 0; j < dim; j++)\n {\n const double q_kj = gsl_matrix_get (d, k, j);\n gsl_matrix_set (d, k, j, y_0_err[j]);\n delta = work[j] - q_kj;\n y_0_err[j] = f1 * delta;\n work[j] = f2 * delta;\n y_0[j] += y_0_err[j];\n }\n }\n\n for (j = 0; j < dim; j++)\n {\n gsl_matrix_set (d, i_step, j, y_0_err[j]);\n }\n }\n}\n\n/* Basic implicit Bulirsch-Stoer step. Divide the step h_total into\n * n_step smaller steps and do the Bader-Deuflhard semi-implicit\n * iteration. */\n\nstatic int\nbsimp_step_local (void *vstate,\n size_t dim,\n const double t0,\n const double h_total,\n const unsigned int n_step,\n const double y[],\n const double yp[],\n const double dfdt[],\n const gsl_matrix * dfdy,\n double y_out[], \n const gsl_odeiv_system * sys)\n{\n bsimp_state_t *state = (bsimp_state_t *) vstate;\n\n gsl_matrix *const a_mat = state->a_mat;\n gsl_permutation *const p_vec = state->p_vec;\n\n double *const delta = state->delta;\n double *const y_temp = state->y_temp;\n double *const delta_temp = state->delta_temp;\n double *const rhs_temp = state->rhs_temp;\n double *const w = state->weight;\n\n gsl_vector_view y_temp_vec = gsl_vector_view_array (y_temp, dim);\n gsl_vector_view delta_temp_vec = gsl_vector_view_array (delta_temp, dim);\n gsl_vector_view rhs_temp_vec = gsl_vector_view_array (rhs_temp, dim);\n\n const double h = h_total / n_step;\n double t = t0 + h;\n\n double sum;\n\n /* This is the factor sigma referred to in equation 3.4 of the\n paper. A relative change in y exceeding sigma indicates a\n runaway behavior. According to the authors suitable values for\n sigma are >>1. I have chosen a value of 100*dim. BJG */\n\n const double max_sum = 100.0 * dim;\n\n int signum, status;\n size_t i, j;\n size_t n_inter;\n\n /* Calculate the matrix for the linear system. */\n for (i = 0; i < dim; i++)\n {\n for (j = 0; j < dim; j++)\n {\n gsl_matrix_set (a_mat, i, j, -h * gsl_matrix_get (dfdy, i, j));\n }\n gsl_matrix_set (a_mat, i, i, gsl_matrix_get (a_mat, i, i) + 1.0);\n }\n\n /* LU decomposition for the linear system. */\n\n gsl_linalg_LU_decomp (a_mat, p_vec, &signum);\n\n /* Compute weighting factors */\n\n compute_weights (y, w, dim);\n\n /* Initial step. */\n\n for (i = 0; i < dim; i++)\n {\n y_temp[i] = h * (yp[i] + h * dfdt[i]);\n }\n\n gsl_linalg_LU_solve (a_mat, p_vec, &y_temp_vec.vector, &delta_temp_vec.vector);\n\n sum = 0.0;\n\n for (i = 0; i < dim; i++)\n {\n const double di = delta_temp[i];\n delta[i] = di;\n y_temp[i] = y[i] + di;\n sum += fabs(di) / w[i];\n }\n\n if (sum > max_sum) \n {\n return GSL_EFAILED ;\n }\n\n /* Intermediate steps. */\n\n status = GSL_ODEIV_FN_EVAL (sys, t, y_temp, y_out);\n\n if (status)\n {\n return status;\n }\n\n for (n_inter = 1; n_inter < n_step; n_inter++)\n {\n for (i = 0; i < dim; i++)\n {\n rhs_temp[i] = h * y_out[i] - delta[i];\n }\n\n gsl_linalg_LU_solve (a_mat, p_vec, &rhs_temp_vec.vector, &delta_temp_vec.vector);\n\n sum = 0.0;\n\n for (i = 0; i < dim; i++)\n {\n delta[i] += 2.0 * delta_temp[i];\n y_temp[i] += delta[i];\n sum += fabs(delta[i]) / w[i];\n }\n\n if (sum > max_sum) \n {\n return GSL_EFAILED ;\n }\n\n t += h;\n\n status = GSL_ODEIV_FN_EVAL (sys, t, y_temp, y_out);\n\n if (status)\n {\n return status;\n }\n }\n\n\n /* Final step. */\n\n for (i = 0; i < dim; i++)\n {\n rhs_temp[i] = h * y_out[i] - delta[i];\n }\n\n gsl_linalg_LU_solve (a_mat, p_vec, &rhs_temp_vec.vector, &delta_temp_vec.vector);\n\n sum = 0.0;\n\n for (i = 0; i < dim; i++)\n {\n y_out[i] = y_temp[i] + delta_temp[i];\n sum += fabs(delta_temp[i]) / w[i];\n }\n\n if (sum > max_sum) \n {\n return GSL_EFAILED ;\n }\n\n return GSL_SUCCESS;\n}\n\n\nstatic void *\nbsimp_alloc (size_t dim)\n{\n bsimp_state_t *state = (bsimp_state_t *) malloc (sizeof (bsimp_state_t));\n\n state->d = gsl_matrix_alloc (SEQUENCE_MAX, dim);\n state->a_mat = gsl_matrix_alloc (dim, dim);\n state->p_vec = gsl_permutation_alloc (dim);\n\n state->yp = (double *) malloc (dim * sizeof (double));\n state->y_save = (double *) malloc (dim * sizeof (double));\n state->yerr_save = (double *) malloc (dim * sizeof (double));\n state->y_extrap_save = (double *) malloc (dim * sizeof (double));\n state->y_extrap_sequence = (double *) malloc (dim * sizeof (double));\n state->extrap_work = (double *) malloc (dim * sizeof (double));\n state->dfdt = (double *) malloc (dim * sizeof (double));\n state->y_temp = (double *) malloc (dim * sizeof (double));\n state->delta_temp = (double *) malloc (dim * sizeof(double));\n state->weight = (double *) malloc (dim * sizeof(double));\n\n state->dfdy = gsl_matrix_alloc (dim, dim);\n\n state->rhs_temp = (double *) malloc (dim * sizeof(double));\n state->delta = (double *) malloc (dim * sizeof (double));\n\n {\n size_t k_choice = bsimp_deuf_kchoice (GSL_SQRT_DBL_EPSILON, dim); /*FIXME: choice of epsilon? */\n state->k_choice = k_choice;\n state->k_current = k_choice;\n state->order = 2 * k_choice;\n }\n\n state->h_next = -GSL_SQRT_DBL_MAX;\n\n return state;\n}\n\n/* Perform the basic semi-implicit extrapolation\n * step, of size h, at a Deuflhard determined order.\n */\nstatic int\nbsimp_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], \n const gsl_odeiv_system * sys)\n{\n bsimp_state_t *state = (bsimp_state_t *) vstate;\n\n double *const x = state->x;\n double *const yp = state->yp;\n double *const y_save = state->y_save;\n double *const yerr_save = state->yerr_save;\n double *const y_extrap_sequence = state->y_extrap_sequence;\n double *const y_extrap_save = state->y_extrap_save;\n double *const extrap_work = state->extrap_work;\n double *const dfdt = state->dfdt;\n gsl_matrix *d = state->d;\n gsl_matrix *dfdy = state->dfdy;\n\n const double t_local = t;\n size_t i, k;\n\n if (h + t_local == t_local)\n {\n return GSL_EUNDRFLW; /* FIXME: error condition */\n }\n\n DBL_MEMCPY (y_extrap_save, y, dim);\n\n /* Save inputs */\n DBL_MEMCPY (y_save, y, dim);\n DBL_MEMCPY (yerr_save, yerr, dim);\n \n /* Evaluate the derivative. */\n if (dydt_in != NULL)\n {\n DBL_MEMCPY (yp, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t_local, y, yp);\n\n if (s != GSL_SUCCESS)\n\t{\n return s;\n\t}\n }\n\n /* Evaluate the Jacobian for the system. */\n {\n int s = GSL_ODEIV_JA_EVAL (sys, t_local, y, dfdy->data, dfdt);\n \n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Make a series of refined extrapolations,\n * up to the specified maximum order, which\n * was calculated based on the Deuflhard\n * criterion upon state initialization. */\n for (k = 0; k <= state->k_current; k++)\n {\n const unsigned int N = bd_sequence[k];\n const double r = (h / N);\n const double x_k = r * r;\n\n int status = bsimp_step_local (state,\n dim, t_local, h, N,\n y_extrap_save, yp,\n dfdt, dfdy,\n y_extrap_sequence, \n sys);\n\n if (status == GSL_EFAILED)\n {\n /* If the local step fails, set the error to infinity in\n order to force a reduction in the step size */\n\t \n for (i = 0; i < dim; i++)\n {\n yerr[i] = GSL_POSINF;\n }\n\n break;\n }\n \n else if (status != GSL_SUCCESS)\n\t{\n\t return status;\n\t}\n \n x[k] = x_k;\n\n poly_extrap (d, x, k, x_k, y_extrap_sequence, y, yerr, extrap_work, dim);\n }\n\n /* Evaluate dydt_out[]. */\n\n if (dydt_out != NULL)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);\n\n if (s != GSL_SUCCESS)\n {\n DBL_MEMCPY (y, y_save, dim);\n DBL_MEMCPY (yerr, yerr_save, dim);\n return s;\n }\n }\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nbsimp_order (void *vstate)\n{\n bsimp_state_t *state = (bsimp_state_t *) vstate;\n return state->order;\n}\n\nstatic int\nbsimp_reset (void *vstate, size_t dim)\n{\n bsimp_state_t *state = (bsimp_state_t *) vstate;\n\n state->h_next = 0;\n\n DBL_ZERO_MEMSET (state->yp, dim);\n\n return GSL_SUCCESS;\n}\n\n\nstatic void\nbsimp_free (void * vstate)\n{\n bsimp_state_t *state = (bsimp_state_t *) vstate;\n\n free (state->delta);\n free (state->rhs_temp);\n\n gsl_matrix_free (state->dfdy);\n\n free (state->weight);\n free (state->delta_temp);\n free (state->y_temp);\n free (state->dfdt);\n free (state->extrap_work);\n free (state->y_extrap_sequence);\n free (state->y_extrap_save);\n free (state->y_save);\n free (state->yerr_save);\n free (state->yp);\n\n gsl_permutation_free (state->p_vec);\n gsl_matrix_free (state->a_mat);\n gsl_matrix_free (state->d);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type bsimp_type = { \n \"bsimp\", /* name */\n 1, /* can use dydt_in */\n 1, /* gives exact dydt_out */\n &bsimp_alloc,\n &bsimp_apply,\n &bsimp_reset,\n &bsimp_order,\n &bsimp_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_bsimp = &bsimp_type;\n", "meta": {"hexsha": "235519505192c1f1f58e1c857062788e1b9e2b85", "size": 13802, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/bsimp.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/ode-initval/bsimp.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/ode-initval/bsimp.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.2992957746, "max_line_length": 100, "alphanum_fraction": 0.5753513983, "num_tokens": 4082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.4859305035674216}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName)\n{\n FILE *fp = fopen(input_fileName, \"r\");\n fscanf(fp, \"%*[^\\n]\\n\");\n\n for (int ii = 0; ii < N_kw; ii++)\n fscanf(fp, \"%d,\", &((*index)[ii]));\n fscanf(fp, \"%*[^\\n]\\n\");\n\n int tmp;\n for (int ii = 0; ii < N_kw; ii++)\n {\n for (int jj = 0; jj < N_kw; jj++)\n {\n fscanf(fp, \"%d,\", &tmp);\n (*matrix)[ii*N_kw + jj] = (int) (tmp * scaling);\n }\n fscanf(fp, \"%*[^\\n]\\n\");\n }\n fclose(fp);\n}\n\n\nvoid pad_matrix(int** matrix_padded, int** matrix, int N_kw, int N_doc, double sec_budget, int fixed_padding)\n{\n // Initialising RNG\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 // perform padding on the keywords\n int ii, jj;\n #pragma omp parallel for private(ii)\n for (int ii = 0; ii < N_kw; ii++)\n (*matrix_padded)[ii*N_kw + ii] = 2 * (*matrix)[ii*N_kw + ii] + fixed_padding + (int) gsl_ran_laplace(r, 2.0/sec_budget);\n\n // perform padding\n #pragma omp parallel for private(ii, jj)\n for (ii = 0; ii < N_kw; ii++)\n {\n for (jj = 0; jj < N_kw; jj++)\n {\n if (ii > jj)\n {\n int n1 = (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + ii];\n int n2 = (*matrix_padded)[jj*N_kw + jj] - (*matrix)[jj*N_kw + jj];\n int x1 = gsl_ran_hypergeometric(r, n1, 2*N_doc-n1, (*matrix_padded)[jj*N_kw + jj]);\n int x2 = gsl_ran_hypergeometric(r, n2, 2*N_doc-n2, (*matrix_padded)[ii*N_kw + ii]);\n\n (*matrix_padded)[ii*N_kw + jj] = (*matrix)[ii*N_kw + jj] + x1 + x2;\n (*matrix_padded)[jj*N_kw + ii] = (*matrix_padded)[ii*N_kw + jj];\n }\n }\n }\n gsl_rng_free(r);\n}\n \n\n\nvoid observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw)\n{\n // perform observed count generation\n for (int ii = 0; ii < N_kw; ii++)\n for (int jj = 0; jj < N_kw; jj++)\n gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj]));\n}\n\n\nvoid permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, gsl_matrix* matrix_obs, int** matrix, int fixed_padding, int N_kw, int N_obs, int N_doc, double sec_budget)\n{\n double N1_lower, N1_upper, N2_lower, N2_upper;\n int check = -1;\n int count = 0;\n *idx1 = rand() % N_obs;\n *idx2 = -1;\n int idx_old = (*permutation)[*idx1];\n int idx_new = 0;\n\n do {\n idx_new = rand() % N_kw;\n count++;\n\n if ((*permutation_inv)[idx_new] >= 0)\n {\n *idx2 = (*permutation_inv)[idx_new];\n N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding;\n N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding;\n\n N2_lower = 2 * (*matrix)[idx_old*N_kw + idx_old] - 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) - 4 / sec_budget + fixed_padding;\n N2_upper = 2 * (*matrix)[idx_old*N_kw + idx_old] + 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) + 4 / sec_budget + fixed_padding;\n\n if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper))\n if ((gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower) && (gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower))\n check = 1;\n }\n else\n {\n *idx2 = -1;\n N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding;\n N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding;\n\n if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper))\n check = 1;\n\n }\n \n } while ((check < 0) && (count < 200));\n\n if (count == 200)\n *idx2 = *idx1;\n\n if (*idx1 != *idx2)\n {\n (*permutation_tmp)[*idx1] = idx_new;\n if ((*permutation_inv)[idx_new] >= 0)\n {\n *idx2 = (*permutation_inv)[idx_new];\n (*permutation_tmp)[*idx2] = idx_old;\n }\n }\n}", "meta": {"hexsha": "9de18facd8d7817fa83e5103486b1c9611911eb7", "size": 4985, "ext": "c", "lang": "C", "max_stars_repo_path": "DP-EMM/util.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DP-EMM/util.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DP-EMM/util.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.4812030075, "max_line_length": 222, "alphanum_fraction": 0.5564694082, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.48508944636784634}} {"text": "#include \n#include \n#include \n#include \n#ifndef CRANESUB\nchar *fn1=\"crane1io.dat\";\nchar *fn2=\"crane2io.dat\";\nFILE *fp;\n#endif//#ifndef CRANESUB\ntypedef struct{\n double g;//gravity\n double M;//mass of the car\n double m;//mass of the load\n double r;//length of the rope\n double C;//damping coefficient\n\n double F;//input force\n double T;//tension to the rope\n\n double x,x0;//x position of the load\n double y,y0;//y position of the load\n double X;//X position of the car\n double a;//angle (theta)\n\n double dx,dx0;\n double dy,dy0;\n double dX,dX0;\n double dr;\n double da,da0;\n\n double ddx;\n double ddy;\n double ddX;\n double ddr;\n double dda;\n double dXmax;\n double ddXmax;\n double Fmax;//Force\n\n double h;\n int nh;\n double _h;\n int _dim;\n double *_y;\n double *_y_err;\n double *_dydt_in;\n double *_dydt_out;\n const gsl_odeiv_step_type *_T;\n gsl_odeiv_step *_s;\n gsl_odeiv_system _sys;\n double _t;\n // int *initialize;\n int (*cranefunc)();\n double (*plant)();\n //int (*p) (int num); /* 関数ポインタpを宣言 */\n} CRANE;\n\n#define dim_crane 4\n//double ddXn;//for check\nint crane1func (double t, const double y[], double f[], void *params)\n{\n CRANE *c = (CRANE *)params;\n //y[0]=crane->p, y[1]=crane->dp, y[2]=crane->X, y[3]=crane->dX\n f[0] = y[1];\n f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n f[2] = y[3]; \n f[3] = c->ddX;\n // if(fabs(t-(int)t)<1e6) fprintf(stderr,\"check t=%g f=%g,%g,%g,%g\\n \",t,f[0],f[1],f[2],f[3]);\n // if(fabs(t-(int)(t+0.5))<1e8) fprintf(stderr,\"check t=%g y=%g,%g,%g,%g\\n \",t,y[0],y[1],y[2],y[3]);\n// if(ddXn>0){\n// fprintf(stderr,\"t=%g check?? ddXn=%g=?=%g\\n\",t,ddXn,c->ddX);\n// }\n// double dd=fabs(t-(int)(t+0.5)); if(t>5 && dd<1e-12){\n// fprintf(stderr,\"check t=%g c->ddX=%g, t=%g, it=%d.dd=%g\\n \",t,c->ddX,t,(int)(t+0.5),dd);\n// }\n return GSL_SUCCESS;\n}\n////////////////\n//#define square(x) ((x)*(x))\ndouble square(double x){return((x)*(x));}\n//double plant(double uu)\ndouble plant1(double uu,CRANE *crane)\n{\n // fprintf(stderr,\"check uu=%g, \",uu);\n if(uu>crane->ddXmax) uu=crane->ddXmax; \n else if(uu<-crane->ddXmax) uu=-crane->ddXmax; \n // fprintf(stderr,\"->%g, \\n\",uu);\n int n;\n for(n=0;nnh;n++){\n crane->ddX=uu;//crane->ddX=(uuddXmax)?uu:crane->ddXmax;\n// if(ddXn>0){\n// fprintf(stderr,\"ddXn=%g=?=%g\\n\",ddXn,crane->ddX);\n// }\n if(crane->dX>=crane->dXmax && crane->ddX>0) crane->ddX=0;\n else if(crane->dX<=-crane->dXmax && crane->ddX<0) crane->ddX=0;\n int status = gsl_odeiv_step_apply (crane->_s, crane->_t, crane->_h, \n\t\t\t\t crane->_y, crane->_y_err, \n\t\t\t\t crane->_dydt_in, \n\t\t\t\t crane->_dydt_out, \n\t\t\t\t &crane->_sys);\n if (status != GSL_SUCCESS) {fprintf(stderr,\"### failure of plant calc.\\n\"); break;}\n \n int i;for(i=0;i_dydt_in[i]=crane->_dydt_out[i];\n crane->_t+=crane->_h;\n crane->a =crane->_y[0];\n crane->da =crane->_y[1];\n crane->X =crane->_y[2];\n crane->dX =crane->_y[3];\n crane->x =crane->X+crane->r * sin(crane->a); //output y\n crane->y =crane->r*cos(crane->a);\n\n crane->dx=(crane->x-crane->x0)/crane->_h;\n crane->dy=(crane->y-crane->y0)/crane->_h;\n crane->ddx=(crane->dx-crane->dx0)/crane->_h;\n crane->ddy=(crane->dy-crane->dy0)/crane->_h;\n crane->T=crane->m*sqrt(square(crane->ddx)+square(crane->ddy-crane->g));\n crane->F=crane->M*crane->ddX-crane->T*sin(crane->a);\n crane->dda=(crane->da-crane->da0)/crane->_h;\n crane->x0=crane->x;\n crane->y0=crane->y;\n crane->dx0=crane->dx;\n crane->dy0=crane->dy;\n crane->da0=crane->da;\n }\n#ifndef CRANESUB\n fprintf(fp,\"%.7e %.7e %.7e\", crane->_t,crane->_y[0],crane->_y[1]);//crane->a,crane->da\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->X,crane->dX,crane->ddX);\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->x,crane->dx,crane->ddx);\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->y,crane->dy,crane->ddy);\n fprintf(fp,\" %.7e %.7e\" ,crane->T,crane->F);\n fprintf(fp,\"\\n\");\n#endif //#ifndef CRANESUB\n return(crane->x);//crane->x in [0,AP_y=10?] ==> rt in [0,1]\n}\nint initialize1(CRANE *crane)\n{\n crane->cranefunc=crane1func;\n crane->plant=plant1;\n crane->g=9.8;\n crane->M=100;\n crane->m=20;//10;//20\n crane->r=5;//5;\n crane->C=1;//5;\n\n crane->dr=crane->ddr=0;\n crane->x0=0;\n crane->y0=crane->r;\n crane->dx0=crane->dy0=crane->da0=0;\n crane->dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//??\n crane->ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//??\n crane->Fmax=30.0;//check// crane->Fmax=30;//check\n#ifdef CRANESUB\n crane->h=AP_tS;\n crane->m=_crane_m;\n crane->r=_crane_r;\n crane->dXmax=_crane_dXmax;\n if(_AP_umax>0) AP_u_max=crane->ddXmax=_AP_umax;\n else AP_u_max=crane->ddXmax;\n AP_u_min=-AP_u_max;\n // starttime=0;\n // totaltime=50;\n rr=AP_r=_AP_r;//10\n rr_kyoyou=_rr_kyoyou;\n // p=(double *)malloc(buffsize*sizeof(double));\n C_MODE=11;\n // iteration=_iteration;\n#else\n crane->h=0.01;\n#endif\n crane->nh=10;\n crane->_h=crane->h/crane->nh;//0.001\n crane->_dim=4;\n if(crane->_y==NULL){\n crane->_y=(double*)malloc(crane->_dim*sizeof(double));\n crane->_y_err=(double*)malloc(crane->_dim*sizeof(double));\n crane->_dydt_in=(double*)malloc(crane->_dim*sizeof(double));\n crane->_dydt_out=(double*)malloc(crane->_dim*sizeof(double));\n }\n crane->_T= gsl_odeiv_step_rk4;\n crane->_s= gsl_odeiv_step_alloc (crane->_T, crane->_dim);\n crane->_sys= (gsl_odeiv_system){crane1func, NULL, crane->_dim, crane};\n // crane->_sys= (gsl_odeiv_system){crane1func, NULL, crane->_dim, &crane};\n // crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, &crane};\n //initialize variables\n crane->_t=crane->_y[0]=crane->_y[1]=crane->_y[2]=crane->_y[3]=0;\n int i;for(i=0;i_dim;i++) crane->_dydt_in[i]=0;\n GSL_ODEIV_FN_EVAL(&(crane->_sys), crane->_t, crane->_y, crane->_dydt_in);\n// crane->a =crane->_y[0];\n// crane->da =crane->_y[1];\n// crane->X =crane->_y[2];\n// crane->dX =crane->_y[3];\n// crane->x =crane->X+crane->r * sin(crane->a); //output y\n// crane->y =crane->r*cos(crane->a);\n// crane->dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//??\n// crane->ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//??\n return(0);\n}//endof initialize1\n\n#ifndef CRANESUB\nint main1(int argc,char **argv)\n{\n ////////////////////////////////////////////////////\n /// method 1 ///\n /// input ddX ///\n /// output a,x,y,F ///\n ////////////////////////////////////////////////////\n // double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1;\n double t0=5; //stationary \n double t1=5.0+t0;//accelerate(speed up)\n double t2=2.0+t1;//free run\n double t3=5.0+t2;//decelerate(slow down)\n double t4=20+t3; //free run\n CRANE crane[1];\n// int (*initialize)();\n// if(1==1){\n// initialize=initialize1;\n// }\n// (*initialize)(crane);\n crane->_y=NULL;\n initialize1(crane);\n int M=(t4/crane->h)+1;\n // ddX=(double*)malloc(sizeof(double)*M);\n double *ddX=(double*)malloc(sizeof(double)*M);\n // double *F =(double*)malloc(sizeof(double)*M);\n double Vmax=1;//dX/dt=1[m/s]\n int n;\n double t;\n ////////////////////////////////////////////////////\n /// set ddX ///\n ////////////////////////////////////////////////////\n int n0 =t0/crane->h+0.5, n4=t4/crane->h+0.5;\n for(t=0;th){\n n=t/crane->h;\n if(t<=t0) ddX[n]=0; //zero\n else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate\n else if(t<=t2) ddX[n]=0; //free move\n else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate\n else ddX[n]=0; //free move\n }\n ////////////////////////////////////////////////////\n /// Solve by the Runge Kutta Method of GSL ///\n ////////////////////////////////////////////////////\n // char *fn=\"crane1io.dat\";\n fp=fopen(fn1,\"w\");\n fprintf(fp,\"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\\n\",crane->h,n0,n4,crane->M,crane->m,crane->r,crane->C);\n // double dx0=0,dy0=0,da0=0;\n // for(n=0;nh){\n n=t/crane->h;\n// ddXn=ddX[n];if(n>500 && n<510){\n// fprintf(stderr,\"check n=%d,t=%g ddX=%g\\n\",n,t,ddX[n]);\n// }\n // (*(crane->plant))(ddX[n],crane);\n plant1(ddX[n],crane);\n }\n fclose(fp);\n fprintf(stdout,\"Results are stored in '%s'.\\n\",fn1);\n\n gsl_odeiv_step_free (crane->_s);\n return 0;\n}//endof main1\n#endif//endof #ifndef CRANESUB\n/////////////////////////\nint crane2func (double t, const double y[], double f[], void *params)\n{\n CRANE *c = (CRANE *)params;\n //y[0]=crane->p, y[1]=crane->da, y[2]=crane->X, y[3]=crane->dX\n f[0] = y[1];\n f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n f[2] = y[3]; \n // f[3] = c->ddX;\n f[3] = (c->F+c->T*sin(y[0]))/c->M;\n return GSL_SUCCESS;\n}//endof crane2func\n\ndouble plant2(double uu,CRANE *crane)\n{\n // crane->F=uu;\n if(uu>crane->Fmax) uu=crane->Fmax; \n else if(uu<-crane->Fmax) uu=-crane->Fmax; \n int n;\n for(n=0;nnh;n++){\n crane->F=uu;//\n if(crane->dX>=crane->dXmax && crane->F>0) crane->F=0;\n else if(crane->dX<=-crane->dXmax && crane->F<0) crane->F=0;\n int status = gsl_odeiv_step_apply (crane->_s, crane->_t, crane->_h, \n\t\t\t\t crane->_y, crane->_y_err, \n\t\t\t\t crane->_dydt_in, \n\t\t\t\t crane->_dydt_out, \n\t\t\t\t &crane->_sys);\n if (status != GSL_SUCCESS) break;\n \n int i;for(i=0;i_dydt_in[i]=crane->_dydt_out[i];\n crane->_t+=crane->_h;\n\n crane->a =crane->_y[0];\n crane->da =crane->_y[1];\n crane->X =crane->_y[2];\n crane->dX =crane->_y[3];\n\n crane->x =crane->X+crane->r * sin(crane->a);\n crane->y =crane->r*cos(crane->a);\n crane->dx=(crane->x-crane->x0)/crane->_h;\n crane->dy=(crane->y-crane->y0)/crane->_h;\n crane->ddx=(crane->dx-crane->dx0)/crane->_h;\n crane->ddy=(crane->dy-crane->dy0)/crane->_h;\n crane->T=crane->m*sqrt(square(crane->ddx)+square(crane->ddy-crane->g));\n crane->ddX=(crane->dX-crane->dX0)/crane->_h;\n // crane->F=crane->M*crane->ddX-crane->T*sin(crane->a);\n crane->dda=(crane->da-crane->da0)/crane->_h;\n /* crane->dda=(-2*crane->dr*crane->da-crane->g*sin(crane->a)-ddX[n]*cos(crane->a))/crane->r; */\n crane->x0=crane->x;\n crane->y0=crane->y;\n crane->dx0=crane->dx;\n crane->dy0=crane->dy;\n crane->da0=crane->da;\n crane->dX0=crane->dX;\n }\n#ifndef CRANESUB\n fprintf(fp,\"%.7e %.7e %.7e\", crane->_t,crane->_y[0],crane->_y[1]);//crane->a,crane->da\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->X,crane->dX,crane->ddX);\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->x,crane->dx,crane->ddx);\n fprintf(fp,\" %.7e %.7e %.7e\" ,crane->y,crane->dy,crane->ddy);\n fprintf(fp,\" %.7e %.7e\" ,crane->T,crane->F);\n fprintf(fp,\"\\n\");\n#endif\n return(crane->x);\n // return(crane->X);\n}//endof plant2\nint initialize2(CRANE *crane)\n{\n crane->cranefunc=crane2func;\n crane->plant=plant2;\n crane->Fmax=20.0;//check// crane->Fmax=30;//check\n // crane->dXmax=1.0;\n crane->dXmax=1.0;\n crane->ddXmax=0.2;\n crane->g=9.8;\n crane->M=100;\n crane->m=20;//10;//10;//20\n crane->r=5;//5;\n crane->C=1;//5;\n crane->dr=crane->ddr=0;\n crane->x0=0;\n crane->y0=crane->r;\n crane->dX0=crane->dx0=crane->dy0=crane->da0=0;\n#ifdef CRANESUB\n // crane->Fmax=_crane_Fmax;//check// crane->Fmax=30;//check\n crane->m=_crane_m;\n crane->r=_crane_r;\n crane->h=AP_tS;\n crane->dXmax=_crane_dXmax;\n if(_AP_umax>0) AP_u_max=crane->Fmax=_AP_umax;\n else AP_u_max=crane->Fmax;\n AP_u_min=-AP_u_max;\n // starttime=0;\n // totaltime=100;// totaltime=40;\n // totaltime=50;// totaltime=40;\n // int kmax=totaltime/AP_tS;\n // _rr=(double*)malloc(kmax*sizeof(double));\n rr=AP_r=_AP_r;//10\n // int k;for(k=0;kh=0.01;\n#endif\n crane->nh=10;\n crane->F=crane->a=crane->da=crane->dda=0;\n crane->T=crane->m*crane->g;\n crane->_h=crane->h/crane->nh;//0.001\n crane->_dim=4;\n {// if(crane->_y==NULL){\n crane->_y=(double*)malloc(crane->_dim*sizeof(double));\n crane->_y_err=(double*)malloc(crane->_dim*sizeof(double));\n crane->_dydt_in=(double*)malloc(crane->_dim*sizeof(double));\n crane->_dydt_out=(double*)malloc(crane->_dim*sizeof(double));\n }\n crane->_T= gsl_odeiv_step_rk4;\n crane->_s= gsl_odeiv_step_alloc (crane->_T, crane->_dim);\n crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, crane};\n // crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, &crane};\n crane->_t=crane->_y[0]=crane->_y[1]=crane->_y[2]=crane->_y[3]=0;\n int i;for(i=0;i_dim;i++) crane->_dydt_in[i]=0;\n GSL_ODEIV_FN_EVAL(&(crane->_sys), crane->_t, crane->_y, crane->_dydt_in);\n return(0);\n}\n#ifndef CRANESUB\nint main2(int argc, char** argv)\n{\n // CRANE crane;\n CRANE crane[1];\n crane->g=9.8;\n crane->M=100;\n crane->m=20;\n crane->r=5;\n crane->dr=crane->ddr=0;\n ////////////////////////////////////////////////////\n /// method 2 ///\n /// input F ///\n /// output p,x,y,X,... ///\n ////////////////////////////////////////////////////\n double h;//,hh=0.1;\n //result for different h\n /*gnuplot\n set style data lines;n=1;\n n=n+1;plot \"crane1io.dat\" using 1:n, \"crane2io.dat\" using 1:n;print \"n=\",n\n #strange at n=9(ddx),12(ddy),13(T)\n */\n ////////////////////////////////////////////////////\n /// read F ///\n ////////////////////////////////////////////////////\n // char *fn1=\"crane1io.dat\";\n FILE *fp1=fopen(fn1,\"r\");\n int n4;\n#define buffsize 512\n char buff[buffsize];\n int n0;\n if(fgets(buff,buffsize,fp1)!=NULL)\n sscanf(buff,\"#%lf%d%d%lf%lf%lf%lf\",&h,&n0,&n4,&crane->M,&crane->m,&crane->r,&crane->C);\n crane->h=h;\n double t4=n4*h;\n double *F =(double*)malloc(sizeof(double)*(n4+1));\n // int M=n4+1;double *F =(double*)malloc(sizeof(double)*M);\n // double *ddX=(double*)malloc(sizeof(double)*M);\n \n int n;\n double t;\n // double dx0=0,dy0=0,dX0=0,da0=0;\n // double x0=0,y0=crane->r;\n\n if(fgets(buff,buffsize,fp1)!=NULL); //?? fgets(buff,buffsize,fp1);\n for(n=0;n_y=NULL;\n initialize2(crane);\n fp=fopen(fn2,\"w\");\n for(t=0;th){\n n=t/crane->h;\n plant2(F[n],crane);\n // (*(crane->plant))(F[n],crane);\n }\n fclose(fp);\n fprintf(stdout,\"Results are stored in '%s'.\\n\",fn2);\n\n gsl_odeiv_step_free (crane->_s);\n return 0;\n}//main2\n#endif //#ifndef CRANESUB\n\n#ifndef CRANESUB\nint main(int argc,char **argv)\n{\n if(argc<2){\n fprintf(stderr,\"Usage:%s [1|2]\\n\",argv[0]);\n return(1);\n }\n if(argv[1][0]!='2') main1(argc,argv);\n else main2(argc,argv);\n return(0);\n}\n#endif //#ifndef CRANESUB\n", "meta": {"hexsha": "45e470f3d848d9f2e5b0fb974e293ee1a0b15abe", "size": 15515, "ext": "c", "lang": "C", "max_stars_repo_path": "1021/mspc/crane.c", "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1021/mspc/crane.c", "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1021/mspc/crane.c", "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "avg_line_length": 32.5945378151, "max_line_length": 116, "alphanum_fraction": 0.5547534644, "num_tokens": 6047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48499253507419854}} {"text": "#include \"pyactpol.h\"\n#include \n\n/* sync.c\n *\n * scan-synchronous mode fitting and removal.\n */\n\n\nstatic int fit_poly(float *x, double *y, int n, int order, int samp,\n double *fit);\nstatic int fit_sine(double *t, double *y, int n, double f,\n double *fit, double *coeff);\n\n\n/* Find the amplitude and phase of the synchronous signal in a set of\n * detectors together with the phase of the azimuth scan.\n *\n * az should already have the mean removed. ctime should start at 0\n * to minimize rounding errors. nwin should be the number of samples\n * to use for the amplitude fit; i.e. an round number of azimuth scans.\n */\n\nstatic int mbSyncFit(double* az, double* ctime,\n\t\t float* data, int ndata,\n\t\t int *dets, int ndets,\n\t\t float *sync_amp, float* sync_phase,\n\t\t float *sync_rms,\n\t\t float *phaseAz,\n\t\t float f,\n\t\t int order, int samp, int nT)\n{\n int n, nwin;\n double sampRate, thetaAz;\n\n // Calculate size of data window to do analysis\n sampRate = (double)ndata / (ctime[ndata-1] - ctime[0]);\n nwin = floor( (double)nT / f * sampRate );\n if (nwin > ndata) {\n nwin = ndata;\n }\n\n double *fit_az = malloc(nwin * sizeof(double));\n double *coeff_az = malloc(2 * sizeof(double));\n\n // Obtain phase of azimuth scan\n if (fit_sine(ctime, az, nwin, f, fit_az, coeff_az) != 0)\n return 1;\n if (coeff_az[0] > 0) thetaAz = atan(coeff_az[1]/coeff_az[0]);\n else thetaAz = atan(coeff_az[1]/coeff_az[0]) + M_PI;\n *phaseAz = thetaAz;\n\n free(fit_az);\n free(coeff_az);\n\n float *tcopy = malloc(nwin * sizeof(float));\n for (int j=0; j 0) theta = atan(coeff_syn[1]/coeff_syn[0]);\n else theta = atan(coeff_syn[1]/coeff_syn[0]) + M_PI;\n sync_amp[n] = A;\n sync_phase[n] = theta;\n \n // Find fit RMS error\n rms = 0.0;\n for (i = 0; i < nwin; i++)\n\t rms += (y[i] - fit_syn[i])*(y[i] - fit_syn[i]);\n sync_rms[n] = sqrt(rms/nwin);\n } /* pragma omp for */\n\n free(y);\n free(fit_1f);\n free(fit_syn);\n free(coeff_syn);\n } /* pragma omp parallel */\n\n\n return 0;\n}\n\n/// Fit sinusoidal of a given frequency to data.\n/// \\param t Independent variable (time).\n/// \\param y Dependent variable (data).\n/// \\param n Number of elements in data.\n/// \\param f Frequency of the sinusoid.\n/// \\param fit Vector of fitted data (sinusoid).\n/// \\param coeff Coefficients of sinusoid (A*cos(th) + B*sin(th)).\nstatic int fit_sine(double *t, double *y, int n, double f, \n\t double *fit, double *coeff) {\n int k;\n\n double temp_c, temp_s;\n double cos2, sin2, sincos, ycos, ysin;\n\n cos2 = sin2 = sincos = ycos = ysin = 0.0; \n for (k = 0; k < n; k++) {\n temp_c = cos(2*M_PI*f*t[k]);\n temp_s = sin(2*M_PI*f*t[k]);\n cos2 += temp_c*temp_c;\n sin2 += temp_s*temp_s;\n sincos += temp_s*temp_c;\n ycos += y[k]*temp_c;\n ysin += y[k]*temp_s;\n }\n\n coeff[0] = (sin2*ycos - sincos*ysin) / (cos2*sin2 - sincos*sincos);\n coeff[1] = (cos2*ysin - sincos*ycos) / (cos2*sin2 - sincos*sincos);\n\n // Evaluate result\n for (k = 0; k < n; k++) {\n fit[k] = cos(2*M_PI*f*t[k])*coeff[0] + sin(2*M_PI*f*t[k])*coeff[1];\n }\n\n return 0;\n}\n\n\n/// Fit polynomial to data to remove common mode.\n/// \\param x Independent variable.\n/// \\param y Dependent variable (data).\n/// \\param n Number of elements in data.\n/// \\param order Order of polinomial to fit.\n/// \\param samp Number of samples to take from data to do the fit.\n/// \\param fit vector with evaluated polynomial\n\nstatic int fit_poly(float *x, double *y, int n, int order, int samp, \n double *fit) {\n int i, j, k;\n int N;\n double *coeff;\n double **A, *pows;\n double temp;\n\n gsl_vector *g_Ab = gsl_vector_calloc(order+1);\n gsl_matrix *g_AA = gsl_matrix_alloc(order+1,order+1);\n gsl_vector *g_x = gsl_vector_alloc(order+1);\n gsl_permutation *g_p = gsl_permutation_alloc(order+1);\n int signum = 0;\n\n int status = 1; // failure.\n\n if (order <= 0) {\n print_error(\"Invalid 'order=%i' in fit_poly\\n\", order);\n return 1;\n }\n\n // Initializa Matrices and Vectors\n coeff = malloc((order+1) * sizeof(double));\n N = n/samp;\n if (N < order) {\n print_error(\"Fitting 'order=%i' with 'N=%i' data points in fit_poly\\n\", order, N);\n return 1;\n }\n A = (double **)malloc((order+1) * sizeof(double *));\n A[0] = (double *)malloc(N * (order+1) * sizeof(double));\n for (i = 0; i < order+1; i++){\n A[i] = A[0] + N * i;\n for( j = 0; j < N; j++ ) A[i][j] = 0.0;\n }\n \n pows = (double *)malloc((2*order+1) * sizeof(double));\n for (i = 0; i < 2*order+1; i++)\n pows[i] = 0.0;\n\n // Generate A matrix\n for (i = 0; i < order+1; i++)\n for (k = 0; k < N; k++) {\n A[i][k] = 1.0;\n for (j = 0; j < i; j++)\n A[i][k] *= x[k*samp + samp/2];\n }\n\n // Generate AA as transpose(A)*A\n for (i = 2*order; i > 0; i -= 2) {\n for (k = 0; k < N; k++) {\n pows[i] += A[i/2][k]*A[i/2][k];\n pows[i-1] += A[i/2][k]*A[i/2-1][k];\n }\n }\n for (k = 0; k < N; k++)\n pows[0]++;\n \n for (i = 0; i < order+1; i++)\n for (j = 0; j < order+1; j++)\n g_AA->data[i*g_AA->tda+j] = pows[i+j];\n\t\n/* for (i = 0; i < order+1; i++) {\n\tfor (j = 0; j <= i; j++) {\n\t for (k = 0; k < N; k++)\n\t\tAA[i][j] += A[j][k]*A[i][k];\n\t}\n }*/\n\n // Generate Ab as transpose(A)*y\n for (i = 0; i < order+1; i++) {\n for (k = 0; k < N; k++) {\n temp = 0.0;\n for (j = 0; j < samp; j++)\n temp += y[k*samp + j];\n g_Ab->data[i] += A[i][k] * temp / (float)samp;\n }\n }\n\n // Solve system\n if ((status = gsl_linalg_LU_decomp(g_AA, g_p, &signum))!=0)\n goto exit_now;\n if ((status = gsl_linalg_LU_solve(g_AA, g_p, g_Ab, g_x))!=0)\n goto exit_now;\n\n // Copy out...\n for (i = 0; i < order+1; i++)\n coeff[i] = g_x->data[i];\n \n // Evaluate result\n for (k = 0; k < n; k++) {\n fit[k] = 0.0;\n for (i = 0; i < order+1; i++) {\n temp = 1.0;\n for (j = 0; j < i; j++)\n temp *= x[k];\n fit[k] += temp * coeff[i];\n }\n }\n\n/*\n for (k = 0; k < n; k++)\n\tfit[k] = 0.0;\n for (i = 0; i < order+1; i++)\n\tfor (k = 0; k < n; k++)\n\t fit[k] += A[i][k] * Ab[i];\n*/\n\n status = 0;\n\nexit_now:\n free(A[0]);\n \n free(A);\n free(pows);\n free(coeff);\n\n gsl_vector_free(g_Ab);\n gsl_vector_free(g_x);\n gsl_matrix_free(g_AA);\n gsl_permutation_free(g_p);\n\n return status;\n}\n\t\n\nPyDoc_STRVAR(get_sync_amps__doc__,\n\t \"get_sync_amps(data, dets, az, ctime)\\n\"\n\t \"\\n\"\n\t \"The arrays must be C-ordered with dimensions like:\\n\"\n\t \" data [ *,n_data] (float)\\n\"\n\t \" dets [n_det] \t (int)\\n\"\n \" az [n_data] \t (double)\\n\"\n\t \" ctime[n_data] \t (double)\\n\"\n\t \"\\n\"\n\t \"Returns (az_phase, amps_cos, amps_sin).\"\n );\n\nstatic PyObject *get_sync_amps(PyObject *self, PyObject *args)\n{\n PyArrayObject *data_array;\n PyArrayObject *dets_array;\n PyArrayObject *az_array;\n PyArrayObject *ctime_array;\n double scan_freq;\n int order, samp, nT;\n\n if (!PyArg_ParseTuple(args, \"O!O!O!O!diii\",\n &PyArray_Type, &data_array,\n &PyArray_Type, &dets_array,\n &PyArray_Type, &az_array,\n &PyArray_Type, &ctime_array,\n\t\t\t &scan_freq,\n\t\t\t &order,\n\t\t\t &samp,\n\t\t\t &nT\n ))\n po_raise(\"invalid arguments.\");\n\n // Types and ordering\n ASSERT_CARRAY_TYPE_NDIM(data_array, NPY_FLOAT32, 2);\n ASSERT_CARRAY_TYPE_NDIM(dets_array, NPY_INT32, 1);\n ASSERT_CARRAY_TYPE_NDIM(az_array, NPY_FLOAT64, 1);\n ASSERT_CARRAY_TYPE_NDIM(ctime_array, NPY_FLOAT64, 1);\n\n int ndata = PyArray_DIMS(data_array)[1];\n int ndet = PyArray_DIMS(dets_array)[0];\n\n po_assert(PyArray_DIMS(az_array)[0] == ndata);\n po_assert(PyArray_DIMS(ctime_array)[0] == ndata);\n\n float *data = PyArray_DATA(data_array);\n double *az = PyArray_DATA(az_array);\n double *ctime = PyArray_DATA(ctime_array);\n int *dets = PyArray_DATA(dets_array);\n\n // We've been so thorough, it would be a shame to segfault now.\n for (int i=0; i= 0 &&\n\t\t dets[i] < PyArray_DIMS(data_array)[0]);\n\n // And, places for the results.\n npy_intp ndet_ = ndet;\n PyArrayObject *amp_array = (PyArrayObject*)\n\t PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32);\n PyArrayObject *phase_array = (PyArrayObject*)\n\t PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32);\n PyArrayObject *rms_array = (PyArrayObject*)\n\t PyArray_SimpleNew(1, &ndet_, NPY_FLOAT32);\n \n float phaseAz = -1.;\n mbSyncFit(az, ctime,\n\t data, ndata,\n\t dets, ndet,\n\t PyArray_DATA(amp_array),\n\t PyArray_DATA(phase_array),\n\t PyArray_DATA(rms_array),\n\t &phaseAz,\n\t scan_freq, order, samp, nT);\n\n return Py_BuildValue(\"NNNf\",\n\t\t\t amp_array,\n\t\t\t phase_array,\n\t\t\t rms_array,\n\t\t\t phaseAz);\n}\n\nPyMethodDef pyactpol_sync_methods[] = {\n {\"get_sync_amps\", get_sync_amps, METH_VARARGS, \n get_sync_amps__doc__},\n {NULL, NULL, 0, NULL} /* Sentinel */\n};\n\n\n", "meta": {"hexsha": "68703dc560dc6753eb9f380ec7dd5f356a9f4e44", "size": 9995, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sync.c", "max_stars_repo_name": "ACTCollaboration/moby2", "max_stars_repo_head_hexsha": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-23T15:59:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:04:35.000Z", "max_issues_repo_path": "src/sync.c", "max_issues_repo_name": "ACTCollaboration/moby2", "max_issues_repo_head_hexsha": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-08T15:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T15:10:46.000Z", "max_forks_repo_path": "src/sync.c", "max_forks_repo_name": "ACTCollaboration/moby2", "max_forks_repo_head_hexsha": "b0f6bd6add7170999eb964d18f16d795520426e9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.160326087, "max_line_length": 89, "alphanum_fraction": 0.5695847924, "num_tokens": 3330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.48498538410497744}} {"text": "/* movstat/medacc.c\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * Original copyright notice:\n * Copyright (c) 2011 ashelly.myopenid.com under \n */\n \n#include \n#include \n#include \n#include \n#include \n#include \n \n#define ItemLess(a,b) ((a)<(b))\n#define ItemMean(a,b) (((a)+(b))/2)\n \n#define minCt(m) (((m)->ct-1)/2) /* count of items in minheap */\n#define maxCt(m) (((m)->ct)/2) /* count of items in maxheap */\n\ntypedef double medacc_type_t;\n\ntypedef struct\n{\n int n; /* window size */\n int idx; /* position in circular queue */\n int ct; /* count of items in queue */\n medacc_type_t *data; /* circular queue of values, size k */\n int *pos; /* index into `heap` for each value, size 2*k */\n int *heap; /* max/median/min heap holding indices into `data` */\n} medacc_state_t;\n\nstatic size_t medacc_size(const size_t n);\nstatic int medacc_init(const size_t n, void * vstate);\nstatic int medacc_insert(const medacc_type_t x, void * vstate);\nstatic int medacc_delete(void * vstate);\nstatic int medacc_get(void * params, medacc_type_t * result, const void * vstate);\n\nstatic int mmless(const medacc_state_t * state, const int i, const int j);\nstatic int mmexchange(medacc_state_t * state, const int i, const int j);\nstatic int mmCmpExch(medacc_state_t * state, const int i, const int j);\nstatic void minSortDown(medacc_state_t * state, int i);\nstatic void maxSortDown(medacc_state_t * state, int i);\nstatic int minSortUp(medacc_state_t * state, int i);\nstatic int maxSortUp(medacc_state_t * state, int i);\n\nstatic size_t\nmedacc_size(const size_t n)\n{\n size_t size = 0;\n\n size += sizeof(medacc_state_t);\n size += n * sizeof(medacc_type_t);\n size += 2 * n * sizeof(int);\n\n return size;\n}\n\nstatic int\nmedacc_init(const size_t n, void * vstate)\n{\n medacc_state_t * state = (medacc_state_t *) vstate;\n int k = (int) n;\n\n state->n = n;\n state->ct = 0;\n state->idx = 0;\n\n state->data = (medacc_type_t *) ((unsigned char *) vstate + sizeof(medacc_state_t));\n state->pos = (int *) ((unsigned char *) state->data + n * sizeof(medacc_type_t));\n state->heap = state->pos + n + (n/2); /* points to middle of storage */\n\n /* set up initial heap fill pattern: median,max,min,max,... */\n while (k--)\n {\n state->pos[k] = ((k + 1)/2) * ((k & 1) ? -1 : 1);\n state->heap[state->pos[k]] = k;\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nmedacc_insert(const medacc_type_t x, void * vstate)\n{\n medacc_state_t * state = (medacc_state_t *) vstate;\n int isNew = (state->ct < (int) state->n);\n int p = state->pos[state->idx];\n medacc_type_t old = state->data[state->idx];\n\n state->data[state->idx] = x;\n state->idx = (state->idx + 1) % state->n;\n state->ct += isNew;\n\n if (p > 0) /* new item is in minHeap */\n {\n if (!isNew && ItemLess(old, x))\n minSortDown(state, p * 2);\n else if (minSortUp(state, p))\n maxSortDown(state, -1);\n }\n else if (p < 0) /* new item is in maxHeap */\n {\n if (!isNew && ItemLess(x, old))\n maxSortDown(state, p * 2);\n else if (maxSortUp(state, p))\n minSortDown(state, 1);\n }\n else /* new item is at median */\n {\n if (maxCt(state))\n maxSortDown(state, -1);\n\n if (minCt(state))\n minSortDown(state, 1);\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nmedacc_delete(void * vstate)\n{\n medacc_state_t * state = (medacc_state_t *) vstate;\n\n if (state->ct > 0)\n {\n int p = state->pos[(state->idx - state->ct + state->n) % state->n];\n\n if (p > 0) /* oldest item is in minHeap */\n {\n mmexchange(state, p, minCt(state));\n --(state->ct);\n minSortDown(state, 2 * p);\n }\n else if (p < 0) /* oldest item is in maxHeap */\n {\n mmexchange(state, p, maxCt(state));\n --(state->ct);\n maxSortDown(state, 2 * p);\n }\n else if (p == 0) /* oldest item is at median */\n {\n }\n }\n\n return GSL_SUCCESS;\n}\n\n/* returns median (or average of 2 when item count is even) */\nstatic int\nmedacc_get(void * params, medacc_type_t * result, const void * vstate)\n{\n const medacc_state_t * state = (const medacc_state_t *) vstate;\n medacc_type_t median = state->data[state->heap[0]];\n\n (void) params;\n\n if ((state->ct & 1) == 0)\n median = ItemMean(median, state->data[state->heap[-1]]);\n\n *result = median;\n\n return GSL_SUCCESS;\n}\n\n/* returns 1 if heap[i] < heap[j] */\nstatic int\nmmless(const medacc_state_t * state, const int i, const int j)\n{\n return ItemLess(state->data[state->heap[i]], state->data[state->heap[j]]);\n}\n \n/* swaps items i and j in heap, maintains indexes */\nstatic int\nmmexchange(medacc_state_t * state, const int i, const int j)\n{\n int t = state->heap[i];\n state->heap[i] = state->heap[j];\n state->heap[j] = t;\n state->pos[state->heap[i]] = i;\n state->pos[state->heap[j]] = j;\n return 1;\n}\n \n/* swaps items i and j if i < j; returns true if swapped */\nstatic int\nmmCmpExch(medacc_state_t * state, const int i, const int j)\n{\n return (mmless(state, i, j) && mmexchange(state , i, j));\n}\n \n/* maintains minheap property for all items below i/2. */\nstatic void\nminSortDown(medacc_state_t * state, int i)\n{\n for (; i <= minCt(state); i *= 2)\n {\n if (i > 1 && i < minCt(state) && mmless(state, i + 1, i))\n ++i;\n\n if (!mmCmpExch(state, i, i / 2))\n break;\n }\n}\n \n/* maintains maxheap property for all items below i/2. (negative indexes) */\nstatic void\nmaxSortDown(medacc_state_t * state, int i)\n{\n for (; i >= -maxCt(state); i *= 2)\n {\n if (i < -1 && i > -maxCt(state) && mmless(state, i, i - 1))\n --i;\n\n if (!mmCmpExch(state, i / 2, i))\n break;\n }\n}\n \n/* maintains minheap property for all items above i, including median\n returns true if median changed */\nstatic int\nminSortUp(medacc_state_t * state, int i)\n{\n while (i > 0 && mmCmpExch(state, i, i / 2))\n i /= 2;\n\n return (i == 0);\n}\n \n/* maintains maxheap property for all items above i, including median\n returns true if median changed */\nstatic int\nmaxSortUp(medacc_state_t * state, int i)\n{\n while (i<0 && mmCmpExch(state, i / 2, i))\n i /= 2;\n\n return (i == 0);\n}\n\nstatic const gsl_movstat_accum median_accum_type =\n{\n medacc_size,\n medacc_init,\n medacc_insert,\n NULL, /* XXX FIXME */\n medacc_get\n};\n\nconst gsl_movstat_accum *gsl_movstat_accum_median = &median_accum_type;\n", "meta": {"hexsha": "b1eec0349e3233056cd8d70c68b07a0848c885c4", "size": 7286, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/movstat/medacc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/movstat/medacc.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/medacc.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.1865671642, "max_line_length": 97, "alphanum_fraction": 0.6248970629, "num_tokens": 2170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.48498537329720626}} {"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\n#include \n\n#include \"DMxV.h\"\n\nvoid usageDMxDM(){\n\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"Usage: MM-Suite DMxDM [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, \"\\nPerformance options:\\n\\n\");\n\tfprintf(stderr, \" -t INT Number of threads to use in OpenBLAS. Default: 1\\n\");\n\tfprintf(stderr, \"\\n\");\n\n}\n\nint DMxDM(int argc, char *argv[]) {\n\t\n\tint \t\t\tret_code = 1;\n\tint \t\t\toption;\n\t\n\tunsigned long \t\t*IA;\n\tunsigned long \t\t*JA;\n\tdouble \t\t\t*valuesA;\n\t\n\tunsigned long \t\tMA;\n\tunsigned long \t\tNA;\n\tunsigned long long \tnzA;\n\t\n\t\n\tunsigned long \t\t*IB;\n\tunsigned long \t\t*JB;\n\tdouble \t\t\t*valuesB;\n\t\n\tunsigned long \t\tMB;\n\tunsigned long \t\tNB;\n\tunsigned long long \tnzB;\n\t\n\tchar\t\t\t*outputFileName = NULL;\n\t\n\tchar\t\t\t*inputMatrixFileA = NULL;\n\tchar\t\t\t*inputMatrixFileB= NULL;\n\t\n\tint\t\t\tinputFormatRow = 0;\n\t\n\tint\t\t\tnumThreads = 1;\n\t\n\twhile ((option = getopt(argc, argv,\"ro:t:\")) >= 0) {\n\t\tswitch (option) {\n\t\t\tcase 'o' : \n\t\t\t\t//free(outputFileName);\n\t\t\t\t\n\t\t\t\toutputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);\n\t\t\t\tstrcpy(outputFileName,optarg);\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'r':\n\t\t\t\tinputFormatRow = 1;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase 't':\n\t\t\t\tnumThreads = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault: break;\n\t\t}\n\t\n\t}\n\t\n\tif ((optind + 2 > argc) || (optind + 3 <= argc)) {\n\t\tusageDMxDM();\n\t\treturn 0;\n\t}\n\t\n\topenblas_set_num_threads(numThreads);\n\t\n\tif(outputFileName == NULL) {\n\t\toutputFileName = (char *) malloc(sizeof(char)*7);\n\t\tsprintf(outputFileName,\"stdout\");\n\t}\n\t\n\tinputMatrixFileA = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);\n\tinputMatrixFileB = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);\n\t\n\tstrcpy(inputMatrixFileA,argv[optind]);\n\tstrcpy(inputMatrixFileB,argv[optind+1]);\n\t\n\t//Read matrices\n\tif(inputFormatRow){\n\t\n\t\tif(!readDenseCoordinateMatrixRowLine(inputMatrixFileA,&IA,&JA,&valuesA,&MA,&NA,&nzA)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif(!readDenseCoordinateMatrixRowLine(inputMatrixFileB,&IB,&JB,&valuesB,&MB,&NB,&nzB)){\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(inputMatrixFileA,&IA,&JA,&valuesA,&MA,&NA,&nzA)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif(!readDenseCoordinateMatrix(inputMatrixFileB,&IB,&JB,&valuesB,&MB,&NB,&nzB)){\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\t/*\n\tvoid cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA,\n const enum CBLAS_TRANSPOSE TransB, const int M, const int N,\n const int K, const double alpha, const double *A,\n const int lda, const double *B, const int ldb,\n const double beta, double *C, const int ldc);\n */\n \n double *result=(double *) malloc(MA * NB * sizeof(double));\n \n\t//cblas_dgemv(CblasColMajor,CblasNoTrans,M,N,1.0,values,N,vectorValues,1,0.0,result,1);\n\tcblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, MA, NB, NA, 1.0,valuesA,NA,valuesB,NB,0.0,result,NB);\n\t\n\tif(inputFormatRow){\n\t\twriteDenseCoordinateMatrixRowLine(outputFileName, result,MA,NB,MA * NB);\n\t}\n\telse{\n\t\twriteDenseCoordinateMatrix(outputFileName, result,MA,NB,MA * NB);\n\t}\n\t\n\t\n\t\n\treturn ret_code;\n}\n\n", "meta": {"hexsha": "c56ecc5c6c29f706c32bd4aed538127352c93568", "size": 4392, "ext": "c", "lang": "C", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxDM.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/DMxDM.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/DMxDM.c", "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7804878049, "max_line_length": 107, "alphanum_fraction": 0.6557377049, "num_tokens": 1243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710087, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.4848514270154424}} {"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace units::detail {\n\nstruct decimal_fp {\n double significant;\n std::intmax_t exponent;\n};\n\n[[nodiscard]] constexpr decimal_fp to_decimal(double v) noexcept\n{\n if (v == 0) {\n return {.significant = 0.0, .exponent = 0};\n }\n\n double significant = abs(v);\n std::intmax_t exponent = 0;\n\n while (significant < 1) {\n significant *= 10.0;\n --exponent;\n }\n\n while (significant >= 10) {\n significant /= 10.0;\n ++exponent;\n }\n\n if (v < 0) {\n significant = -significant;\n }\n\n return {.significant = significant, .exponent = exponent};\n}\n\n/* approximate natural log as https://math.stackexchange.com/a/977836\n far slower than std::log but works at compile time with similar accuracy\n */\n[[nodiscard]] constexpr double constexpr_log(double v) noexcept\n{\n Expects(v > 0);\n\n // lookup table to speed up convergence for all significant values\n // significant values of 7 and greater benefit mostly as they now converge in 5 terms compared to O(10)-O(100)\n // required without the table\n //\n // using python:\n // >>> import math\n // >>> for i in range(1, 100):\n // ... print(f\"/* log({i:>2d}) = */ {math.log(i):.16f},\")\n constexpr std::array log_table{\n /* log( 1) = */ 0.0000000000000000,\n /* log( 2) = */ 0.6931471805599453,\n /* log( 3) = */ 1.0986122886681098,\n /* log( 4) = */ 1.3862943611198906,\n /* log( 5) = */ 1.6094379124341003,\n /* log( 6) = */ 1.7917594692280550,\n /* log( 7) = */ 1.9459101490553132,\n /* log( 8) = */ 2.0794415416798357,\n /* log( 9) = */ 2.1972245773362196,\n /* log(10) = */ 2.3025850929940459,\n /* log(11) = */ 2.3978952727983707,\n /* log(12) = */ 2.4849066497880004,\n /* log(13) = */ 2.5649493574615367,\n /* log(14) = */ 2.6390573296152584,\n /* log(15) = */ 2.7080502011022101,\n /* log(16) = */ 2.7725887222397811,\n /* log(17) = */ 2.8332133440562162,\n /* log(18) = */ 2.8903717578961645,\n /* log(19) = */ 2.9444389791664403,\n /* log(20) = */ 2.9957322735539909,\n /* log(21) = */ 3.0445224377234230,\n /* log(22) = */ 3.0910424533583161,\n /* log(23) = */ 3.1354942159291497,\n /* log(24) = */ 3.1780538303479458,\n /* log(25) = */ 3.2188758248682006,\n /* log(26) = */ 3.2580965380214821,\n /* log(27) = */ 3.2958368660043291,\n /* log(28) = */ 3.3322045101752038,\n /* log(29) = */ 3.3672958299864741,\n /* log(30) = */ 3.4011973816621555,\n /* log(31) = */ 3.4339872044851463,\n /* log(32) = */ 3.4657359027997265,\n /* log(33) = */ 3.4965075614664802,\n /* log(34) = */ 3.5263605246161616,\n /* log(35) = */ 3.5553480614894135,\n /* log(36) = */ 3.5835189384561099,\n /* log(37) = */ 3.6109179126442243,\n /* log(38) = */ 3.6375861597263857,\n /* log(39) = */ 3.6635616461296463,\n /* log(40) = */ 3.6888794541139363,\n /* log(41) = */ 3.7135720667043080,\n /* log(42) = */ 3.7376696182833684,\n /* log(43) = */ 3.7612001156935624,\n /* log(44) = */ 3.7841896339182610,\n /* log(45) = */ 3.8066624897703196,\n /* log(46) = */ 3.8286413964890951,\n /* log(47) = */ 3.8501476017100584,\n /* log(48) = */ 3.8712010109078911,\n /* log(49) = */ 3.8918202981106265,\n /* log(50) = */ 3.9120230054281460,\n /* log(51) = */ 3.9318256327243257,\n /* log(52) = */ 3.9512437185814275,\n /* log(53) = */ 3.9702919135521220,\n /* log(54) = */ 3.9889840465642745,\n /* log(55) = */ 4.0073331852324712,\n /* log(56) = */ 4.0253516907351496,\n /* log(57) = */ 4.0430512678345503,\n /* log(58) = */ 4.0604430105464191,\n /* log(59) = */ 4.0775374439057197,\n /* log(60) = */ 4.0943445622221004,\n /* log(61) = */ 4.1108738641733114,\n /* log(62) = */ 4.1271343850450917,\n /* log(63) = */ 4.1431347263915326,\n /* log(64) = */ 4.1588830833596715,\n /* log(65) = */ 4.1743872698956368,\n /* log(66) = */ 4.1896547420264252,\n /* log(67) = */ 4.2046926193909657,\n /* log(68) = */ 4.2195077051761070,\n /* log(69) = */ 4.2341065045972597,\n /* log(70) = */ 4.2484952420493594,\n /* log(71) = */ 4.2626798770413155,\n /* log(72) = */ 4.2766661190160553,\n /* log(73) = */ 4.2904594411483910,\n /* log(74) = */ 4.3040650932041702,\n /* log(75) = */ 4.3174881135363101,\n /* log(76) = */ 4.3307333402863311,\n /* log(77) = */ 4.3438054218536841,\n /* log(78) = */ 4.3567088266895917,\n /* log(79) = */ 4.3694478524670215,\n /* log(80) = */ 4.3820266346738812,\n /* log(81) = */ 4.3944491546724391,\n /* log(82) = */ 4.4067192472642533,\n /* log(83) = */ 4.4188406077965983,\n /* log(84) = */ 4.4308167988433134,\n /* log(85) = */ 4.4426512564903167,\n /* log(86) = */ 4.4543472962535073,\n /* log(87) = */ 4.4659081186545837,\n /* log(88) = */ 4.4773368144782069,\n /* log(89) = */ 4.4886363697321396,\n /* log(90) = */ 4.4998096703302650,\n /* log(91) = */ 4.5108595065168497,\n /* log(92) = */ 4.5217885770490405,\n /* log(93) = */ 4.5325994931532563,\n /* log(94) = */ 4.5432947822700038,\n /* log(95) = */ 4.5538768916005408,\n /* log(96) = */ 4.5643481914678361,\n /* log(97) = */ 4.5747109785033828,\n /* log(98) = */ 4.5849674786705723,\n /* log(99) = */ 4.5951198501345898,\n };\n decimal_fp x = to_decimal(v);\n\n // dividing the significant by nearest lower value in [1.0, 1.1, 1.2, ..., 9.9] will greatly improve convergence\n x.significant *= 10;\n const auto isignificant = static_cast(x.significant);\n x.significant /= static_cast(isignificant);\n const double result = static_cast(x.exponent - 1) * log_table[9] + log_table[isignificant - 1];\n\n // 1.0 <= significant < 1.1 converges rapidly\n const double y = (x.significant - 1) / (x.significant + 1);\n const double y_squared = y * y;\n double sum = 0;\n // 5 terms are needed for convergence to machine precision in the worst case scenario\n for (int k = 4; k > 0; --k) {\n sum = y_squared * (1 / (2 * static_cast(k) + 1) + sum);\n }\n sum = 2 * y * (1 + sum); // k = 0 term\n return result + sum;\n}\n\n/* approximate e^x as Taylor series e^x = 1 + x/1! + x^2/2! + x^3/3! +... where N is the order of the Taylor series\n use https://math.stackexchange.com/a/1988927 to improve convergence for large values\n\n larger Factor values improve convergence for all values but reduce the precision\n*/\ntemplate\n requires gt_zero\n[[nodiscard]] constexpr double constexpr_exp(double v) noexcept\n{\n if constexpr (N == 0) {\n return 1.0;\n } else {\n constexpr auto coefficients = []() {\n std::array coeffs;\n std::size_t factorial = 1;\n for (std::size_t i = 0; i < N; ++i) {\n factorial *= i + 1;\n coeffs[i] = 1.0 / static_cast(factorial);\n }\n return coeffs;\n }();\n\n const double x = v / static_cast(Factor);\n double result = 0;\n for (auto i = static_cast(N - 1); i >= 0; --i) {\n result = x * (coefficients[static_cast(i)] + result);\n }\n\n // for factors of power of 2 this should be replaced by log2(Factor) multiplications by the compiler\n return pow_impl(1 + result);\n }\n}\n\n// default template arguments provide reasonable precision even for fairly large exponents\n// see constexpr_exp for template arguments\ntemplate\n[[nodiscard]] constexpr double constexpr_pow(double v, double exponent) noexcept\n{\n const double x = exponent * constexpr_log(v);\n return constexpr_exp(x);\n}\n\n} // namespace units::detail\n", "meta": {"hexsha": "53e4fdf46b79ae0f6000c31fe5fb0c158f6ef171", "size": 9017, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/units/bits/constexpr_math.h", "max_stars_repo_name": "go2sh/units", "max_stars_repo_head_hexsha": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "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/include/units/bits/constexpr_math.h", "max_issues_repo_name": "go2sh/units", "max_issues_repo_head_hexsha": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "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/include/units/bits/constexpr_math.h", "max_forks_repo_name": "go2sh/units", "max_forks_repo_head_hexsha": "112cce1c6521831ec0b0f996c4958432cf5cfb13", "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.2603305785, "max_line_length": 115, "alphanum_fraction": 0.6089608517, "num_tokens": 3087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.4848514094951986}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#define DECORRCRITS 1\r\n#define SET 1\r\n\r\nint pcl_ran_mvgaussian(gsl_rng *rseed, gsl_vector *mean, gsl_matrix *Sigma, gsl_vector *output)\r\n{\r\n int i;\r\n gsl_linalg_cholesky_decomp(Sigma);\r\n for (i = 0; i < output->size; i++){\r\n gsl_vector_set (output, i , gsl_ran_gaussian(rseed,1)); \r\n }\r\n gsl_blas_dtrmv (CblasLower, CblasNoTrans, CblasNonUnit, Sigma, output);\r\n gsl_blas_daxpy (1.0,mean, output);\r\n return 0;\r\n} \r\n\r\nunsigned long int random_seed()\r\n{\r\n\r\n unsigned int seed;\r\n FILE *devrandom;\r\n if ((devrandom = fopen(\"/dev/random\",\"r\")) == NULL) {\r\n fprintf(stderr,\"Cannot open /dev/random, setting seed to 0\\n\");\r\n seed = 0;\r\n } else {\r\n fread(&seed,sizeof(seed),1,devrandom);\r\n fclose(devrandom);\r\n }\r\n\r\n return(seed);\r\n\r\n}\r\n\r\ndouble ran_inv_gamma(const gsl_rng * r, double a, double b){\r\n return(1/gsl_ran_gamma(r, a, 1/b));\r\n}\r\n\r\ndouble ran_trunc_norm_upper(const gsl_rng * r, double mu, double sigma, double a){\r\n double u = gsl_rng_uniform_pos(r);\r\n double v = gsl_cdf_ugaussian_P((-a+mu)/sigma);\r\n return(-sigma * gsl_cdf_ugaussian_Pinv(u*v)+mu);\r\n}\r\n\r\ndouble ran_trunc_norm_lower(const gsl_rng * r, double mu, double sigma, double a){\r\n double u = gsl_rng_uniform_pos(r);\r\n double v = gsl_cdf_ugaussian_P((a-mu)/sigma);\r\n return(sigma * gsl_cdf_ugaussian_Pinv(u*v)+mu);\r\n}\r\n\r\n\r\ndouble ran_trunc_norm_both(const gsl_rng * r, double mu, double sigma, double a, double b){\r\n double low = gsl_cdf_ugaussian_P((a-mu)/sigma);\r\n double high = gsl_cdf_ugaussian_P((b-mu)/sigma);\r\n double u = gsl_ran_flat(r,low,high);\r\n return(sigma * gsl_cdf_ugaussian_Pinv(u)+mu);\r\n}\r\n\r\nint main(int argc, char *argv[]){\r\n \r\n unsigned long int seed;\r\n seed = random_seed();\r\n int ITERS,iter,i,j,k,K,I,J,nRespCat;\r\n char *fnEstimates,*fnChains,*fnInput;\r\n int yij,sij;\r\n int errs=0;\r\n char *name;\r\n\r\n double a,b,e,f,sigDecorr,mu_crits,sd_crits;\r\n double sig2mu,mumu;\r\n\r\n ////This is all data and prior entry code.\r\n\r\n if(argc<9){\r\n fprintf(stderr,\"Arguments needed: #iterations nRespCat sig2_mu a b e f sigDecorr [analysis.name] [input.file]\\n\");\r\n fprintf(stderr,\"\\n****Not enough arguments.\\n\\n\");\r\n return(1);\r\n }\r\n if(argc>9){\r\n name=argv[9];\r\n }else{\r\n name=\"analysis\";\r\n }\r\n\r\n ITERS=atoi(argv[1]);\r\n nRespCat=atoi(argv[2]);\r\n sig2mu=atof(argv[3]); \r\n a=atof(argv[4]);\r\n b=atof(argv[5]);\r\n e=atof(argv[6]);\r\n f=atof(argv[7]);\r\n sigDecorr=atof(argv[8]);\r\n\r\n //confirm and check command line arguments.\r\n printf(\"Name : %s\\n\",name);\r\n printf(\"nRespCat = %i\\n\",nRespCat);\r\n printf(\"sig2mu = %.2f\\n\",sig2mu);\r\n printf(\"a = %.2f\\n\",a);\r\n printf(\"b = %.2f\\n\",b);\r\n printf(\"e = %.2f\\n\",e);\r\n printf(\"f = %.2f\\n\",f); \r\n printf(\"sigDecorr= %.2f\\n\",sigDecorr);\r\n \r\n\r\n if(nRespCat<=0){printf(\"\\n*****nRespCat must be greater than 0.\\n\");errs++;}\r\n if(sig2mu<=0){printf(\"\\n*****sig2mu must be greater than 0.\\n\");errs++;}\r\n if(a<=0){printf(\"\\n*****a must be greater than 0.\\n\");errs++;}\r\n if(b<=0){printf(\"\\n*****b must be greater than 0.\\n\");errs++;}\r\n if(e<=0){printf(\"\\n*****e must be greater than 0.\\n\");errs++;}\r\n if(f<=0){printf(\"\\n*****f must be greater than 0.\\n\");errs++;}\r\n if(sigDecorr<=0){printf(\"\\n*****sigDecorr must be greater than 0.\\n\");errs++;}\r\n\r\n if(errs>0){printf(\"Exiting...\\n\\n\");exit(1);}\r\n\r\n asprintf(&fnEstimates,\"%s.est\",name);\r\n asprintf(&fnChains,\"%s.chn\",name);\r\n\r\n if(argc>10){\r\n fnInput=argv[10];\r\n }else{\r\n asprintf(&fnInput,\"%s.dat\",name);\r\n }\r\n\r\n K=nRespCat-1;\r\n\r\n\r\n //open files.\r\n FILE *CHAINS;\r\n if ((CHAINS = fopen(fnChains,\"w\")) == NULL) {\r\n fprintf(stderr,\"\\n****Cannot open chain output file!\\n\\n\");\r\n return(1);\r\n }\r\n\r\n FILE *ESTIMATES;\r\n if ((ESTIMATES = fopen(fnEstimates,\"w\")) == NULL) {\r\n fprintf(stderr,\"\\n****Cannot open estimate output file!\\n\\n\");\r\n fclose(CHAINS);\r\n return(1);\r\n }\r\n\r\n FILE *INPUT;\r\n if ((INPUT = fopen(fnInput,\"r\")) == NULL) {\r\n fprintf(stderr,\"\\n****Cannot open input file %s!\\n\\n\",fnInput);\r\n fclose(CHAINS);\r\n fclose(ESTIMATES);\r\n return(1);\r\n }\r\n \r\n //Now that we have opened the files, get the data.\r\n \r\n i=0;\r\n int newline=0,spaces=0;\r\n int got;\r\n while(!newline&&!feof(INPUT)){\r\n i++;\r\n got=fgetc(INPUT);\r\n //printf(\"Character %i: %i %c\\n\",i,got,got);\r\n if(got==32) spaces++;\r\n if(got==10) newline=1;\r\n }\r\n rewind(INPUT);\r\n\r\n if(!newline){\r\n printf(\"Could not determine number of conditions!\\n\");\r\n exit(1);\r\n }\r\n J=(spaces+1)/2;\r\n\r\n i=0;\r\n int totsig=0;\r\n int totnoi=0;\r\n\r\n printf(\"Reading data...\\n\");\r\n while(!feof(INPUT)){\r\n for(j=0;j=nRespCat)||(sij!=0&&sij!=1)){\r\n printf(\"\\n****Invalid data for participant %i, item %i: (yij=%i,sij=%i)\\n\\n\",i+1,j+1,yij,sij);\r\n fclose(CHAINS);\r\n fclose(ESTIMATES);\r\n fclose(INPUT);\r\n return(1);\r\n }\r\n if(yij!=-1){\r\n\ttotsig+=sij; \r\n\ttotnoi+=1-sij;\r\n }\r\n }\r\n i++;\r\n }\r\n rewind(INPUT);\r\n\r\n I=i;\r\n\r\n //printf(\"Read %d subjects and %d items, with %d total signal trials.\\n\",I,J,totsig);\r\n\r\n //initialize matrices\r\n \r\n printf(\"Reserving memory for matrices...\\n\");\r\n int Ys[totsig],Yn[totnoi],Subs[totsig],Subn[totnoi];\r\n gsl_vector *Ws,*Wn,*Ts,*Tn,*WsMean,*WnMean,*WsDev,*TsMean,*TnMean;\r\n gsl_matrix *Xs,*Xn,*Ss,*Sn,*TpSs,*TpSn,*XstXs,*XntXn,*Vs,*Vn;\r\n Xs = gsl_matrix_calloc(totsig, I+J+1);\r\n Xn = gsl_matrix_calloc(totnoi, I+J+1);\r\n XstXs = gsl_matrix_calloc(I+J+1, I+J+1);\r\n XntXn = gsl_matrix_calloc(I+J+1, I+J+1);\r\n Vs = gsl_matrix_calloc(I+J+1, I+J+1);\r\n Vn = gsl_matrix_calloc(I+J+1, I+J+1);\r\n gsl_matrix *Vn0 = gsl_matrix_calloc(I+J+1, I+J+1);\r\n gsl_matrix *Vs0 = gsl_matrix_calloc(I+J+1, I+J+1);\r\n Ws = gsl_vector_calloc(totsig);\r\n Wn = gsl_vector_calloc(totnoi); \r\n Ts = gsl_vector_calloc(I+J+1);\r\n Tn = gsl_vector_calloc(I+J+1);\r\n WsMean = gsl_vector_calloc(totsig);\r\n WnMean = gsl_vector_calloc(totnoi); \r\n WsDev = gsl_vector_calloc(totsig);\r\n TsMean= gsl_vector_calloc(I+J+1);\r\n TnMean= gsl_vector_calloc(I+J+1);\r\n gsl_vector *TsMean0= gsl_vector_calloc(I+J+1);\r\n gsl_vector *TnMean0= gsl_vector_calloc(I+J+1);\r\n \r\n\r\n\r\n gsl_vector *isAlph = gsl_vector_calloc(I+J+1);\r\n gsl_vector *isBeta = gsl_vector_calloc(I+J+1);\r\n \r\n TpSs = gsl_matrix_calloc(I+J+1,I+J+1);\r\n TpSn = gsl_matrix_calloc(I+J+1,I+J+1);\r\n gsl_matrix_set_identity(TpSs);\r\n gsl_matrix_set_identity(TpSn);\r\n\r\n Ss = gsl_matrix_calloc(totsig, totsig);\r\n gsl_matrix_set_identity(Ss);\r\n Sn = gsl_matrix_calloc(totnoi, totnoi);\r\n gsl_matrix_set_identity(Sn);\r\n \r\n gsl_permutation *gslPerm = gsl_permutation_alloc(I+J+1); \r\n gsl_permutation_init(gslPerm);\r\n \r\n gsl_matrix_set(TpSs,0,0,1.0/sig2mu);\r\n gsl_matrix_set(TpSn,0,0,1.0/sig2mu);\r\n\r\n \r\n //end initialize matrices\r\n\r\n printf(\"Creating design matrix...\\n\");\r\n int y[I][J],s[I][J],sigindex=0,noiindex=0;\r\n i=0;\r\n while(!feof(INPUT)){\r\n for(j=0;jmaxw[Subs[i]][0]) { maxw[Subs[i]][0]=gsl_vector_get(Ws,i);}\r\n }else if( Ys[i]==K ){\r\n \tgsl_vector_set(Ws,i,ran_trunc_norm_upper(r, gsl_vector_get(WsMean,i), sqrt(sig2), crits[Subs[i]][K-1]));\r\n\tif(gsl_vector_get(Ws,i)maxw[Subs[i]][Ys[i]]) { maxw[Subs[i]][Ys[i]]=gsl_vector_get(Ws,i);}\r\n\tif(gsl_vector_get(Ws,i)maxw[Subn[i]][0]) { maxw[Subn[i]][0]=gsl_vector_get(Wn,i);}\r\n }else if( Yn[i]==K ){\r\n \tgsl_vector_set(Wn,i,ran_trunc_norm_upper(r, gsl_vector_get(WnMean,i), sqrt(sig2N), crits[Subn[i]][K-1]));\r\n\tif(gsl_vector_get(Wn,i)maxw[Subn[i]][Yn[i]]) { maxw[Subn[i]][Yn[i]]=gsl_vector_get(Wn,i);}\r\n\tif(gsl_vector_get(Wn,i)I){\r\n\tgsl_matrix_set(TpSs,i,i,1.0/sig2beta1);\r\n\tgsl_matrix_set(TpSn,i,i,1.0/sig2beta0);\r\n }else if(i>0){\t\r\n \tgsl_matrix_set(TpSs,i,i,1.0/sig2alph1);\r\n\tgsl_matrix_set(TpSn,i,i,1.0/sig2alph0);\r\n }\r\n //printf(\"i: %d | %f\\n\",i,gsl_matrix_get(TpSs,i,i));\r\n }\r\n \r\n \r\n \r\n gsl_matrix_memcpy(Vs,TpSs);\r\n gsl_matrix_memcpy(Vn,TpSn);\r\n \r\n gsl_matrix_scale(Vs,sig2);\r\n gsl_matrix_scale(Vn,sig2N);\r\n gsl_matrix_add(Vn,XntXn);\r\n gsl_matrix_add(Vs,XstXs);\r\n gsl_matrix_scale(Vs,1.0/sig2);\r\n gsl_matrix_scale(Vn,1.0/sig2N);\r\n\r\n //for(i=0;i<(I+J+1);i++){\r\n // for(j=0;j<(I+J+1);j++){\r\n //\tprintf(\"%f \",gsl_matrix_get(Vs,i,j));\r\n // }\r\n // printf(\"\\n\");\r\n //}\r\n\r\n\r\n gsl_linalg_LU_decomp(Vn,gslPerm,&i);\r\n gsl_linalg_LU_invert(Vn,gslPerm,Vn0);\r\n \r\n gsl_linalg_LU_decomp(Vs,gslPerm,&i);\r\n gsl_linalg_LU_invert(Vs,gslPerm,Vs0);\r\n\r\n //for(i=0;i<(I+J+1);i++){\r\n // for(j=0;j<(I+J+1);j++){\r\n //\tprintf(\"%f \",gsl_matrix_get(Vs0,i,j));\r\n // }\r\n // printf(\"\\n\");\r\n //}\r\n\r\n \r\n\r\n //sample parameter vectors\r\n \r\n gsl_blas_dgemv(CblasTrans,1.0/sig2,Xs,Ws,0,TsMean);\r\n gsl_blas_dgemv(CblasNoTrans,1,Vs0,TsMean,0,TsMean0);\r\n\r\n gsl_blas_dgemv(CblasTrans,1.0/sig2N,Xn,Wn,0,TnMean);\r\n gsl_blas_dgemv(CblasNoTrans,1,Vn0,TnMean,0,TnMean0);\r\n\r\n pcl_ran_mvgaussian(r, TsMean0, Vs0, Ts);\r\n pcl_ran_mvgaussian(r, TnMean0, Vn0, Tn);\r\n\r\n \r\n gsl_vector_fwrite(CHAINS,Ts);\r\n gsl_vector_fwrite(CHAINS,Tn);\r\n \r\n\r\n //Sample variances of parameters\r\n sumAlp20=0;\r\n sumAlp21=0;\r\n sumBet20=0;\r\n sumBet21=0;\r\n for(i=0;i<(I+J+1);i++){\r\n if(i>I){\r\n\tsumBet20+=pow(gsl_vector_get(Tn,i),2);\r\n\tsumBet21+=pow(gsl_vector_get(Ts,i),2);\r\n }else if(i>0){\t\r\n\tsumAlp20+=pow(gsl_vector_get(Tn,i),2);\r\n\tsumAlp21+=pow(gsl_vector_get(Ts,i),2);\r\n }\r\n }\r\n //printf(\"%f\\n\",sumBet20);\r\n \r\n //sample sigma^2\r\n sig2alph0=ran_inv_gamma(r, e+.5*I,f+(.5*sumAlp20));\r\n sig2alph1=ran_inv_gamma(r, e+.5*I,f+(.5*sumAlp21));\r\n sig2beta0=ran_inv_gamma(r, e+.5*J,f+(.5*sumBet20));\r\n sig2beta1=ran_inv_gamma(r, e+.5*J,f+(.5*sumBet21));\r\n\r\n //printf(\"IG: %f %f\\n\",a0+.5*totSignal,(1.0)*b0+(.5*sumWSqr));\r\n //sig2=1.3;\r\n fwrite(&sig2alph0,sizeof(double),1,CHAINS);\r\n fwrite(&sig2alph1,sizeof(double),1,CHAINS);\r\n fwrite(&sig2beta0,sizeof(double),1,CHAINS);\r\n fwrite(&sig2beta1,sizeof(double),1,CHAINS);\r\n\r\n gsl_blas_dgemv(CblasNoTrans,1,Xs,Ts,0,WsMean);\r\n gsl_blas_dgemv(CblasNoTrans,1,Xn,Tn,0,WnMean); \r\n\r\n //gsl_vector_fprintf(stderr,WsMean,\"%f\");\r\n //printf(\"\\n\\n\");\r\n //gsl_vector_fprintf(stderr,WnMean,\"%f\");\r\n //printf(\"\\n\\n\");\r\n //gsl_vector_fprintf(stderr,WsMean,\"%g\");\r\n\r\n \r\n //printf(\"\\ns2=%f\\n%f %f,%f %f\\n\",sig2,sumwN[i]/(1.0*(J-nSignal[i])),1.0/sqrt(1.0*(J-nSignal[i])),sumwS[i]/(1.0*nSignal[i]),sqrt(sig2/(1.0*(nSignal[i]))));\r\n\r\n //sample criteria\r\n for(i=0;i0 && critCand[i][k]1)?1:bDecorr[i]);\r\n\t //printf(\"BDECORR: m%d i%d bdecorr %f\\n\",iter,i,bDecorr[i]);\r\n\t if(accDecorr[i]){\r\n\t decorrRate+=1/(1.0*I*ITERS);\r\n\t \r\n\t for(k=0;k c d s\n **/\n#endif\n\n#include \"bblas_common.h\"\n#include \n#include \n\n\n\n#define COMPLEX\n\n/**\n * bblas_zgemm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty} +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_zgemm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, Bm, Bn, M, K, N, ldc;\n int max_work_size = max(test->maxK,max(test->maxM, test->maxN));\n double Anorm, Bnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n BBLAS_Complex64_t alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n BBLAS_Complex64_t **C_diff;\n C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_zcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t M = test->M[batch_iter];\n\t K = test->K[batch_iter];\n\t N = test->N[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->transA[batch_iter] == BblasNoTrans) {\n\t\tAm = M; An = K;\n\t } else {\n\t\tAm = K; An = M;\n\t }\n\t if (test->transB[batch_iter] == BblasNoTrans) {\n\t\tBm = K; Bn = N;\n\t } else {\n\t\tBm = N; Bn = K;\n\t }\n\n\t /*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tM = test->M[first_index];\n\tK = test->K[first_index];\n\tldc = test->ldc[first_index];\n\tN = test->N[first_index];\n\n\tif (test->transA[first_index] == BblasNoTrans) {\n\t Am = M; An = K;\n\t} else {\n\t Am = K; An = M;\n\t}\n\tif (test->transB[first_index] == BblasNoTrans) {\n\t Bm = K; Bn = N;\n\t} else {\n\t Bm = N; Bn = K;\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t\t/*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', M, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the relative error */\n\t result = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);\n\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_zstarmm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty} +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_zstarmm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, Bm, Bn, N, ldc;\n int max_work_size = max(test->maxM, test->maxN);\n double Anorm, Bnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n BBLAS_Complex64_t alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n BBLAS_Complex64_t **C_diff;\n C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_zcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAm = test->M[batch_iter];\n\t } else {\n\t\tAm = test->N[batch_iter];\n\t }\n\t Bm = test->ldb[batch_iter];\n\t Bn = test->N[batch_iter];\n\t /*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t result = Rnorm / ((N*cabs(test->alpha[batch_iter])*Anorm*Bnorm + cabs(test->beta[batch_iter])*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tN = test->N[first_index];\n\tldc = test->ldc[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t Am = test->M[first_index];\n\t} else {\n\t Am = test->N[first_index];\n\t}\n\tBm = test->ldb[first_index];\n\tBn = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t /*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, Am, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the relative error */\n\t result = Rnorm / ((N*cabs(test->alpha[first_index])*Anorm*Bnorm + cabs(test->beta[first_index])*test->Cinitnorm[batch_iter])*eps);\n\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_zstark_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|A\\|_1 +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_zstark_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, N, K, ldc;\n char u;\n int max_work_size = max(test->maxK, test->maxN);\n double Anorm, ATnorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n double alpha_norm, beta_norm;\n BBLAS_Complex64_t alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n BBLAS_Complex64_t **C_diff;\n C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_zcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t K = test->K[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->trans[batch_iter] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t } else {\n\t\tAm = K; An = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t\tu = 'L';\n\t }else\n\t {\n\t\tu = 'U';\n\t }\n\t /*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t /*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the one norm of A */\n\t ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t if (test->routine == BBLAS_HERK)\n\t {\n\t\tbeta_norm = cabs(test->beta_herk[batch_iter]);\n\t\talpha_norm = cabs(test->alpha_herk[batch_iter]);\n\t }else{\n\t\tbeta_norm = cabs(test->beta[batch_iter]);\n\t\talpha_norm = cabs(test->alpha[batch_iter]);\n\t }\n\n\t result = Rnorm / ((K*alpha_norm*Anorm*ATnorm + beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\t N = test->N[first_index];\n\t K = test->K[first_index];\n\t ldc = test->ldc[first_index];\n\n\t if (test->trans[first_index] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t } else {\n\t\tAm = K; An = N;\n\t }\n\t if(test->uplo[first_index] == BblasLower )\n\t {\n\t\tu = 'L';\n\t }else\n\t {\n\t\tu = 'U';\n\t }\n\n\t for( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t {\n\t\t/*Compute the error C - C_finial */\n\t\tcblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\tRnorm = LAPACKE_zlanhe_work(LAPACK_COL_MAJOR, 'I', u, N, C_diff[batch_iter], ldc, work);\n\n\t\t/*Compute the infinity norm of A */\n\t\tAnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the one norm of A */\n\t\tATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\tif (test->routine == BBLAS_HERK)\n\t\t{\n\t\t beta_norm = cabs(test->beta_herk[first_index]);\n\t\t alpha_norm = cabs(test->alpha_herk[first_index]);\n\t\t}else{\n\t\t beta_norm = cabs(test->beta[first_index]);\n\t\t alpha_norm = cabs(test->alpha[first_index]);\n\t\t}\n\n\t\t/*Compute the relative error */\n\t\tresult = Rnorm / ((K*alpha_norm*Anorm*ATnorm +\n\t\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t\tswitch(test->target)\n\t\t{\n\t\t case BBLAS_MKL:\n\t\t\ttest->mkl_error[batch_iter] = result;\n\t\t\tbreak;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\t case BBLAS_OTHER:\n\t\t\ttest->other_error[batch_iter] = result;\n\t\t\tbreak;\n\t\t default:\n\t\t\tprintf(\"In bblas_zcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t }\n }else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_zstar2k_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((K|\\alpha|\\|A\\|_{\\infty}\\|B\\|_1 +\n * K|\\alpha|\\|B\\|_{\\infty}\\|A\\|_1 +\n * |\\beta|\\|C_{\\mathrm{init}}\\|_{\\infty})\\epsilon).@f]\n *\n **/\n\nvoid bblas_zstar2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, Bn, Bm, N, K, ldc;\n int max_work_size = max(test->maxK, test->maxN);\n double Anorm, Bnorm, ATnorm, BTnorm, Rnorm, result;\n double beta_norm;\n double eps = LAPACKE_dlamch_work('e');\n BBLAS_Complex64_t alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n /*Temporary buffer to save (test-arrayC -C_final) */\n BBLAS_Complex64_t **C_diff;\n C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n /*Make a copy of test->arrayC in C_diff */\n bblas_zcopy_Cinit(test, C_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t K = test->K[batch_iter];\n\t ldc = test->ldc[batch_iter];\n\n\t if (test->trans[batch_iter] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t\tBn = K;\n\t } else {\n\t\tAm = K; An = N;\n\t\tBn = N;\n\t }\n\t Bm = test->ldb[batch_iter];\n\n\t /*Compute the error C - C_finial */\n\t cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t /*Compute the infinity norm of A */\n\t Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the one norm of A */\n\t ATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm of B */\n\t Bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t /*Compute the one norm of B */\n\t BTnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t if(test->routine == BBLAS_HER2K)\n\t {\n\t\tbeta_norm = cabs(test->beta_herk[batch_iter]);\n\t }else\n\t {\n\t\tbeta_norm = cabs(test->beta[batch_iter]);\n\t }\n\n\t result = Rnorm / ((K*cabs(test->alpha[batch_iter])*Anorm*BTnorm +\n\t\t\t K*cabs(test->alpha[batch_iter])*Bnorm*ATnorm +\n\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n\n }else if( test->batch_opts == BBLAS_FIXED ) //fixed size\n {\n\tN = test->N[first_index];\n\tK = test->K[first_index];\n\tldc = test->ldc[first_index];\n\n\tif (test->trans[first_index] == BblasNoTrans) {\n\t\tAm = N; An = K;\n\t\tBn = K;\n\t} else {\n\t Am = K; An = N;\n\t Bn = N;\n\t}\n\tBm = test->ldb[first_index];\n\n\n\t for( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t {\n\t\t/*Compute the error C - C_finial */\n\t\tcblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t\tRnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldc, N, C_diff[batch_iter], ldc, work);\n\n\t\t/*Compute the infinity norm of A */\n\t\tAnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the one norm of A */\n\t\tATnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Am, An, test->arrayA[batch_iter], Am, work);\n\n\t\t/*Compute the infinity norm of B */\n\t\tBnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t\t/*Compute the one norm of B */\n\t\tBTnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'O', Bm, Bn, test->arrayB[batch_iter], Bm, work);\n\n\t\tif(test->routine == BBLAS_HER2K)\n\t\t{\n\t\t beta_norm = cabs(test->beta_herk[first_index]);\n\t\t}else\n\t\t{\n\t\t beta_norm = cabs(test->beta[first_index]);\n\t\t}\n\n\t\t/*Compute the relative error */\n\t\tresult = Rnorm / ((K*cabs(test->alpha[first_index])*Anorm*BTnorm +\n\t\t\t\t K*cabs(test->alpha[first_index])*Bnorm*ATnorm +\n\t\t\t\t beta_norm*test->Cinitnorm[batch_iter])*eps);\n\n\n\t\tswitch(test->target)\n\t\t{\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t\t}\n\t }\n }else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n/*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(C_diff[index]);\n }\n free(C_diff);\n free(work);\n}\n\n\n/**\n * bblas_ztrmm_tolerance computes the forward error\n * @f[\\|C - C_{\\mathrm{seq}}\\|_{\\infty}/((|\\alpha|\\|A\\|_{\\infty}\\|B\\|_{\\infty}N\\epsilon).@f]\n *\n **/\n\nvoid bblas_ztrmm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **B_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, ldb, N, M;\n int max_work_size = max(test->maxK, test->maxN);\n char u, diag;\n double Anorm, Rnorm, result;\n double eps = LAPACKE_dlamch_work('e');\n BBLAS_Complex64_t alpha =-1;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n\n\n /*Temporary buffer to save (test-arrayB -B_final) */\n BBLAS_Complex64_t **B_diff;\n B_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n /*Make a copy of test->arrayB in B_diff */\n bblas_zcopy_Binit(test, B_diff);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t M = test->M[batch_iter];\n\t ldb = test->ldb[batch_iter];\n\n\t Am = test->lda[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAn = M;\n\t }else\n\t {\n\t\tAn = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t u = 'L';\n\t }else\n\t {\n\t u = 'U';\n\t }\n\n\t if(test->diag[batch_iter] == BblasUnit )\n\t {\n\t\tdiag = 'U';\n\t }else\n\t {\n\t\tdiag = 'N';\n\t }\n\n\t /*Compute the error B - B_finial */\n\t cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\t \n\t\tresult = Rnorm/(N*cabs(test->alpha[batch_iter])*Anorm*test->Binitnorm[batch_iter]*eps);\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\n\t}\n }else if( test->batch_opts == BBLAS_FIXED )\n {\n\n\tN = test->N[first_index];\n\tM = test->M[first_index];\n\tldb = test->ldb[first_index];\n\n\tAm = test->lda[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t An = M;\n\t}else\n\t{\n\t An = N;\n\t}\n\n\tif(test->uplo[first_index] == BblasLower )\n\t{\n\t u = 'L';\n\t}else\n\t{\n\t u = 'U';\n\t}\n\n\tif(test->diag[first_index] == BblasUnit )\n\t{\n\t diag = 'U';\n\t}else\n\t{\n\t diag = 'N';\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t /*Compute the error B - B_finial */\n\t cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the error */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, B_diff[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t result = Rnorm/(N*cabs(test->alpha[first_index])*Anorm*test->Binitnorm[batch_iter]*eps);\n\n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }\n else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n /*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(B_diff[index]);\n }\n free(B_diff);\n free(work);\n}\n\n/**\n * bblas_ztrsm_tolerance computes the backward error\n * @f[\\|\\alpha B - AX \\|_{\\infty}/((\\|A\\|_{\\infty}\\|X\\| + |\\alpha|\\|B\\|_{\\infty})N\\epsilon).@f]\n *\n **/\n\nvoid bblas_ztrsm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **B_final)\n{\n /*Local variables */\n int batch_count = test->batch_count;\n int batch_iter, first_index = 0;\n int Am, An, ldb, N, M;\n int max_work_size = max(test->maxK, test->maxN);\n char u, diag;\n double Anorm, Rnorm, result, Xnorm;\n double eps = LAPACKE_dlamch_work('e');\n BBLAS_Complex64_t alpha;\n double *work = (double *)malloc(max_work_size*sizeof(double));\n\n\n\n /*Variable to save the residual alphaB -AX */\n BBLAS_Complex64_t **residual;\n residual = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n /*Make a copy of test->arrayB (X) in residual */\n bblas_zcopy_Binit(test, residual);\n\n /*Variable size */\n if( test->batch_opts == BBLAS_VARIABLE )\n {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t N = test->N[batch_iter];\n\t M = test->M[batch_iter];\n\t ldb = test->ldb[batch_iter];\n\n\t Am = test->lda[batch_iter];\n\n\t if(test->side[batch_iter] == BblasLeft )\n\t {\n\t\tAn = M;\n\t }else\n\t {\n\t\tAn = N;\n\t }\n\n\t if(test->uplo[batch_iter] == BblasLower )\n\t {\n\t u = 'L';\n\t }else\n\t {\n\t u = 'U';\n\t }\n\n\t if(test->diag[batch_iter] == BblasUnit )\n\t {\n\t\tdiag = 'U';\n\t }else\n\t {\n\t\tdiag = 'N';\n\t }\n\n\t /*Compute residual <- AX (ztrmm) */\n\t alpha = 1;\n\t cblas_ztrmm(BblasColMajor, test->side[batch_iter], test->uplo[batch_iter], test->transA[batch_iter],\n\t\t\ttest->diag[batch_iter], M, N, CBLAS_SADDR(alpha), test->arrayA[batch_iter],\n\t\t\ttest->lda[batch_iter], residual[batch_iter], ldb);\n\n\t /*Compute Binit = alpha Binit */\n\t for (int index=0; index < ldb*N; index++)\n\t {\n\t\ttest->Binit[batch_iter][index] = test->alpha[batch_iter]*test->Binit[batch_iter][index];\n\t }\n\n\t /*Compute the residual <- alpha B - Ax */\n\t alpha= -1;\n\t cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);\n\t\t/*Compute the infinity norm associated with the residual */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm associated with X (B) */\n\t Xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);\n\n\t result = Rnorm/(Anorm*Xnorm*N*eps);\n\t \n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\n\t}\n }else if( test->batch_opts == BBLAS_FIXED )\n {\n\n\tN = test->N[first_index];\n\tM = test->M[first_index];\n\tldb = test->ldb[first_index];\n\n\tAm = test->lda[first_index];\n\n\tif(test->side[first_index] == BblasLeft )\n\t{\n\t An = M;\n\t}else\n\t{\n\t An = N;\n\t}\n\n\tif(test->uplo[first_index] == BblasLower )\n\t{\n\t u = 'L';\n\t}else\n\t{\n\t u = 'U';\n\t}\n\n\tif(test->diag[first_index] == BblasUnit )\n\t{\n\t diag = 'U';\n\t}else\n\t{\n\t diag = 'N';\n\t}\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\n\t /*Compute residual <- AX (ztrmm) */\n\t alpha = 1;\n\t cblas_ztrmm(BblasColMajor, test->side[first_index], test->uplo[first_index], test->transA[first_index],\n\t\t\ttest->diag[first_index], M, N, CBLAS_SADDR(alpha), (const BBLAS_Complex64_t*) test->arrayA[batch_iter],\n\t\t\ttest->lda[first_index], residual[batch_iter], ldb);\n\n\t /*Compute Binit = alpha Binit */\n\t for (int index=0; index < ldb*N; index++)\n\t {\n\t\ttest->Binit[batch_iter][index] = test->alpha[first_index]*test->Binit[batch_iter][index];\n\t }\n\n\t /*Compute the residual <- alpha B - Ax */\n\t alpha = -1;\n\t cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), test->Binit[batch_iter], 1, residual[batch_iter], 1);\n\n\t\t/*Compute the infinity norm associated with the residual */\n\t Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, residual[batch_iter], ldb, work);\n\n\t /*Infinity norm of the triangular matrix A */\n\t Anorm = LAPACKE_zlantr_work(LAPACK_COL_MAJOR, 'I', u, diag, Am,\n\t\t\t\t\tAn, test->arrayA[batch_iter], Am, work);\n\n\t /*Compute the infinity norm associated with X (B) */\n\t Xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'I', ldb, N, test->arrayB[batch_iter], ldb, work);\n\n\t result = Rnorm/(Anorm*Xnorm*N*eps);\n\t \n\t /*Compute the relative error */\n\t switch(test->target)\n\t {\n\t\tcase BBLAS_MKL:\n\t\t test->mkl_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t test->device_error[batch_iter] = result;\n\t\t break;\n\n\t\tcase BBLAS_OTHER:\n\t\t test->other_error[batch_iter] = result;\n\t\t break;\n\t\tdefault:\n\t\t printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t exit(EXIT_FAILURE);\n\t }\n\t}\n }\n else\n {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n }\n\n /*Free allocated memory */\n for(int index =0; index < batch_count; index++)\n {\n\tfree(residual[index]);\n }\n free(residual);\n free(work);\n}\n\n\n/**\n * Calls bblas_zstar2k_tolerance.\n **/\n#ifdef COMPLEX\nvoid bblas_zher2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstar2k_tolerance(test, C_final);\n\n}\n#endif\n/**\n * Calls bblas_zstar2k_tolerance.\n **/\n\nvoid bblas_zsyr2k_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstar2k_tolerance(test, C_final);\n}\n\n/**\n * Calls bblas_zstark_tolerance.\n **/\n\n#ifdef COMPLEX\nvoid bblas_zherk_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstark_tolerance(test, C_final);\n}\n#endif\n/**\n * Calls bblas_zstark_tolerance.\n **/\n\nvoid bblas_zsyrk_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstark_tolerance(test, C_final);\n}\n\n/**\n * Calls bblas_zstarmm_tolerance.\n **/\n\n#ifdef COMPLEX\nvoid bblas_zhemm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstarmm_tolerance(test, C_final);\n}\n#endif\n/**\n * Calls bblas_zstamm_tolerance.\n **/\n\nvoid bblas_zsymm_tolerance(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n bblas_zstarmm_tolerance(test, C_final);\n}\n", "meta": {"hexsha": "524a5bdeee117d354c65151ee8bfdcc656a321c2", "size": 30044, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/bblas_zaccuracy.c", "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/bblas_zaccuracy.c", "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/bblas_zaccuracy.c", "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7295373665, "max_line_length": 135, "alphanum_fraction": 0.63273865, "num_tokens": 9434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311906630568, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4846469063591605}} {"text": "/************************************************************************//**\n* @file time_evolution.c\n*\n* This file contains code to advance the solutions one step forward in time\n*\n* *****************************************************************************/\n\n#include \n#include \n#include \n#include \"ChannelsAndJunctions.h\"\n#include \"MeshAttributes.h\"\n#include \"mathfunctions.h\"\n#include \"oneTimeStep.h\"\n\n/* @cond GLOBAL_VARIABLES */\nextern const double g;\n/* @endcond */\n\n/***************************************************************************//**\n*\n* Function to advance a channel structure one step forward in time using 2-stage\n* RKDG scheme\n* @param[in] Chan channel structure that we are currently working on\n* @param[in] time current time of the simulation\n* @param[in] dt size of the time step\n* @param[in] channelNumber identity (number) of the channel structure that we\n* are currently working on\n*\n* *********************************************************************************/\nvoid oneTimeStep (struct channel *Chan, double time, double dt, int channelNumber)\n{\n\tint TotalNumNodes = 2*Chan->NumNodes;\n\tdouble RHSA[TotalNumNodes];\n\tdouble RHSQ[TotalNumNodes];\n\n\t// Calculate wet/dry status of elements\n\t#ifdef WDON\n\twetDryStatus1D(Chan);\n\t#endif\n\n\t// store A and Q \n\tgsl_vector *A = gsl_vector_alloc(TotalNumNodes);\n\tgsl_vector *Q = gsl_vector_alloc(TotalNumNodes);\n\tfor (int i=0; i < TotalNumNodes; ++i) \n\t{\n\t\tgsl_vector_set(A,i,(*Chan).A[i]);\n\t\tgsl_vector_set(Q,i,(*Chan).Q[i]);\n\t}\n\n\t/******** For debugging print out RHSA and RHSQ)************/\n\t#ifdef DEBUG\n\tprintf(\"Intial A and Q:\\n\");\n\tgsl_vector_fprintf(stdout, A, \"%1.16f\");\n\tprintf(\"\\n\");\n\tgsl_vector_fprintf(stdout, Q, \"%1.16f\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***********************************************************/\n\t\n\t// Intermediate RK step\n\tcomputeL(Chan, time, channelNumber, RHSA, RHSQ);\n\t\n\tgsl_vector *gRHSA = gsl_vector_alloc(TotalNumNodes);\n\tgsl_vector *gRHSQ = gsl_vector_alloc(TotalNumNodes);\n\tfor (int i=0; iA[i] = gsl_vector_get(A_1,i);\n\t\tChan->Q[i] = gsl_vector_get(Q_1,i);\n\t}\n\n\t// Apply minmod slope limiter on w_1\n\tminmod(Chan);\n\n\t#ifdef WDON\n\t// apply the positive-depth operaton on w_1\n\tPDop1D(Chan);\n\n\t// Caculate wet/dry status again\n\twetDryStatus1D(Chan);\n\t\n\t#endif \n\t\n//\tinternal_BC();\n\tboundary_conditions();\n\n\tfor (int i = 0; iA[i]);\n\t\tgsl_vector_set(Q_1,i,Chan->Q[i]);\n\t}\n\t\n\t/******** For debugging print out A and Q************/\n/*\t#ifdef DEBUG\n\tprintf(\"A and Q after first minmod\\n\");\n\tgsl_vector_fprintf(stdout, A_1, \"%e\");\n\tprintf(\"\\n\");\n\tgsl_vector_fprintf(stdout, Q_1, \"%e\");\n\tprintf(\"\\n\");\n\t#endif\n*/\t/***********************************************************/\n\n\t// Compute w\n\tcomputeL(Chan, time, channelNumber, RHSA, RHSQ);\n\n\tfor (int i=0; iA[i] = gsl_vector_get(A_1,i);\n\t\tChan->Q[i] = gsl_vector_get(Q_1,i);\n\t}\n\n\t/******** For debugging print out A and Q)************/\n\t#ifdef DEBUG\n\tprintf(\"A and Q after second computeL:\\n\");\n\tgsl_vector_fprintf(stdout, A_1, \"%1.16f\");\n\tprintf(\"\\n\");\n\tgsl_vector_fprintf(stdout, Q_1, \"%1.16f\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***********************************************************/\n\n\t// Apply minmod slope limiter to w\n\tminmod(Chan);\n\t\n\t#ifdef WDON\n\tPDop1D(Chan);\n\t#endif\n\n\tgsl_vector_free(A);\n\tgsl_vector_free(Q);\n\tgsl_vector_free(A_1);\n\tgsl_vector_free(Q_1);\n\tgsl_vector_free(gRHSA);\n\tgsl_vector_free(gRHSQ);\n\n\tboundary_conditions();\n}\n\n/***************************************************************************//**\n*\n* Function to advance a junction structure one step forward in time using 2-stage\n* RKDG scheme\n* @param[in] junc the junction tructure that we are currently working on\n* @param[in] time current time of the simulation\n* @param[in] dt size of the time step\n*\n* *********************************************************************************/\n\nvoid oneTimeStep2D (struct junction *junc, double time, double dt)\n{\n\n\tint NumEl = junc->NumEl;\n\tint NumEdges = 3*NumEl;\n\tdouble RHSZeta[NumEdges], RHSQx[NumEdges], RHSQy[NumEdges];\n\n\t#ifdef WDON\n\twetDryStatus2D(junc);\n\t#endif\n\n\t// store H, Qx, Qy \n\tgsl_vector *zeta = gsl_vector_alloc(NumEdges);\n\tgsl_vector *Qx = gsl_vector_alloc(NumEdges);\n\tgsl_vector *Qy = gsl_vector_alloc(NumEdges);\n\n\t\n\tint j = 0;\n\tfor (int i=0; i < NumEl; ++i) {\n\t\tfor (int k=0; k < 3; ++k){\n\t\t\tgsl_vector_set(zeta,j,junc->zeta[index(i,k,3)]);\n\t\t\tgsl_vector_set(Qx,j, junc->Qx[index(i,k,3)]);\n\t\t\tgsl_vector_set(Qy,j, junc->Qy[index(i,k,3)]);\n\t\t\t++j;\n\t\t}\n\t}\n\n\t/************ print out zeta, Qx and Qy for debugging ********************/\n\t#ifdef DEBUG\n\tprintf(\"Initial values:\\n zeta \\n\");\n\tgsl_vector_fprintf(stdout,zeta,\"%e\");\n\tprintf(\"\\n Qx \\n\");\n\tgsl_vector_fprintf(stdout,Qx,\"%e\");\n\tprintf(\"\\n Qy \\n\");\n\tgsl_vector_fprintf(stdout,Qy,\"%e\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***************************************************************************/\n\n\t// Intermediate RK step\n\tcompute2DL(junc, time, RHSZeta, RHSQx, RHSQy);\n\n\tgsl_vector *gRHSZeta = gsl_vector_alloc(NumEdges);\n\tgsl_vector *gRHSQx = gsl_vector_alloc(NumEdges);\n\tgsl_vector *gRHSQy = gsl_vector_alloc(NumEdges);\t\n\n\tj = 0;\n\tfor (int i=0; i < NumEl; ++i) {\n\t\tfor (int k=0; k < 3; ++k){\n\t\t\tgsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]);\n\t\t\tgsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]);\n\t\t\tgsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]);\n\t\t\t++j;\n\t\t}\n\t}\n\n\t/************ print out RHSZeta, RHSQx and RHSQy for debugging ********************/\n\t#ifdef DEBUG\n\tprintf(\"After first computeL:\\n RHSZeta \\n\");\n\tgsl_vector_fprintf(stdout,RHSZeta,\"%e\");\n\tprintf(\"\\n RHSQx \\n\");\n\tgsl_vector_fprintf(stdout,RHSQx,\"%e\");\n\tprintf(\"\\n RHSQy \\n\");\n\tgsl_vector_fprintf(stdout,RHSQy,\"%e\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***************************************************************************/\n\n\t// w_1 = w + dt*L; \n\tgsl_vector *zeta_1 = gsl_vector_alloc(NumEdges);\n\tgsl_vector *Qx_1 = gsl_vector_alloc(NumEdges);\n\tgsl_vector *Qy_1 = gsl_vector_alloc(NumEdges);\n\tfor (int i=0; izeta[index(i,k,3)] = gsl_vector_get(zeta_1,j);\n\t\t\tjunc->Qx[index(i,k,3)] = gsl_vector_get(Qx_1,j);\n\t\t\tjunc->Qy[index(i,k,3)] = gsl_vector_get(Qy_1,j);\n\t\t\t++j;\n\t\t}\n\t}\n\n\t// Apply minmod slope limiter on w_1\n\tSlopeLimiter(junc);\n//\tinternal_BC();\n\n\t#ifdef WDON\n\tPDop2D(junc);\n\twetDryStatus2D(junc);\n\t#endif\n\n\tj = 0;\t\t\t\n\tfor (int i=0; izeta[index(i,k,3)]);\n\t\t\tgsl_vector_set(Qx_1,j,junc->Qx[index(i,k,3)]);\n\t\t\tgsl_vector_set(Qy_1,j,junc->Qy[index(i,k,3)]);\n\t\t\t++j;\n\t\t}\n\t}\n\t\n\t/************ print out zeta, Qx and Qy for debugging ********************/\n\t#ifdef DEBUG\n\tprintf(\"After first slope limiting:\\n zeta \\n\");\n\tgsl_vector_fprintf(stdout,zeta_1,\"%e\");\n\tprintf(\"\\n Qx \\n\");\n\tgsl_vector_fprintf(stdout,Qx_1,\"%e\");\n\tprintf(\"\\n Qy \\n\");\n\tgsl_vector_fprintf(stdout,Qy_1,\"%e\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***************************************************************************/\n\t\n\t// w_1 = w_1 + w;\n\tgsl_vector_add(zeta_1,zeta);\n\tgsl_vector_add(Qx_1, Qx);\n\tgsl_vector_add(Qy_1,Qy);\n\n\t// Compute w\n\tcompute2DL(junc, time, RHSZeta, RHSQx, RHSQy);\n\n\tj = 0;\n\tfor (int i=0; i < NumEl; ++i) {\n\t\tfor (int k=0; k < 3; ++k){\n\t\t\tgsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]);\n\t\t\tgsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]);\n\t\t\tgsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]);\n\t\t\t++j;\n\t\t}\n\t}\n\n\t/************ print out zeta, Qx and Qy for debugging ********************/\n\t#ifdef DEBUG\n\tprintf(\"After second computeL:\\n RHSZeta \\n\");\n\tgsl_vector_fprintf(stdout,RHSZeta,\"%e\");\n\tprintf(\"\\n RHSQx \\n\");\n\tgsl_vector_fprintf(stdout,RHSQx,\"%e\");\n\tprintf(\"\\n RHSQy \\n\");\n\tgsl_vector_fprintf(stdout,RHSQy,\"%e\");\n\tprintf(\"\\n\");\n\t#endif\n\t/***************************************************************************/\n\n\tgsl_vector_scale(zeta_1,0.5);\n\tgsl_vector_scale(Qx_1,0.5);\n\tgsl_vector_scale(Qy_1,0.5);\n\tgsl_vector_scale(gRHSZeta,dt/2);\n\tgsl_vector_scale(gRHSQx,dt/2);\n\tgsl_vector_scale(gRHSQy,dt/2);\n\n\tgsl_vector_add(zeta_1,gRHSZeta);\n\tgsl_vector_add(Qx_1,gRHSQx);\n\tgsl_vector_add(Qy_1,gRHSQy);\n\n\tj = 0;\n\tfor (int i=0; izeta[index(i,k,3)] = gsl_vector_get(zeta_1,j);\n\t\t\tjunc->Qx[index(i,k,3)] = gsl_vector_get(Qx_1,j);\n\t\t\tjunc->Qy[index(i,k,3)] = gsl_vector_get(Qy_1,j);\n\t\t\t++j;\n\t\t}\n\t}\t\n\t\n\t// Apply minmod slope limiter to w\n\tSlopeLimiter(junc);\n\n\t#ifdef WDON\n\tPDop2D(junc);\n\t#endif\n\n\tgsl_vector_free(zeta);\n\tgsl_vector_free(Qx);\n\tgsl_vector_free(Qy);\n\tgsl_vector_free(zeta_1);\n\tgsl_vector_free(Qx_1);\n\tgsl_vector_free(Qy_1);\n\tgsl_vector_free(gRHSZeta);\n\tgsl_vector_free(gRHSQx);\n\tgsl_vector_free(gRHSQy);\n\n}\n\n/*******************************************************************//**\n*\n* Function to evolve the channels as well as the junctions through time\n* until the final simulation time. It also outputs the data at a certain\n* time\n*\n* *********************************************************************/\nvoid time_evolution(double FinalTime)\n{\n\t\t\n\t//Output initial conditions \n\tFILE* file1;\n\tFILE* file2;\n\t\n\tfor (int i=0; iNumNodes;\t\n\t\t\n\t\tfor (int j = 0; jb[j];\n\t\t\tz = ChannelList[i]->z[j];\n\t\t\tdouble x_val = ChannelList[i]->x[j];\n\t\t\tdouble y_val = ChannelList[i]->y[j];\n\t\t\tfor (int k=0; k<2; ++k)\n\t\t\t{\n\t\t\n\t\t\t\tdouble A = ChannelList[i]->A[index(j,k,2)]; \n\t\t\t\tdouble Q = ChannelList[i]->Q[index(j,k,2)];\n\t\t\t\tdouble H = A/B;\n\t\t\t\tdouble zeta = H - z;\n\t\t\t\tfprintf(file1, \"%e\\t%e\\t%e\\t%e\\n\", x_val, y_val, -z, H);\n\t\t\t\tfprintf(file2, \"%e\\t%e\\t%e\\t%e\\n\", x_val, y_val, -z, Q);\n\t\t\t}\n\t\t}\n\t\tfclose(file1);\n\t\tfclose(file2);\n\t}\n\n\t// output the file with x y and z information for the elements\n/*\tFILE *juncMesh;\n\tfor (int i=0; i NumEl;\n\t\tint NumNodes = JunctionList[i]->NumNodes;\n\t\tint NumEdges = JunctionList[i]->TotalNumEdges;\n\t\t\n\t\tfprintf(juncMesh, \"NodeNum \\t x \\t\\t y \\t\\t z\\n\");\n\t\tfor (int j = 0; j < NumNodes; ++j)\n\t\t{\n\t\t\tdouble xcor = JunctionList[i]->x[j];\n\t\t\tdouble ycor = JunctionList[i]->y[j];\n\t\t\tdouble zcor = JunctionList[i]->z[j];\n\t\t\tfprintf(juncMesh, \"%d\\t%e\\t%e\\t%e\\n\",j+1, xcor, ycor, zcor);\n\t\t}\n\n\t\n\t\tfprintf(juncMesh, \"\\n EltoVert \\n\");\n\t\tfor (int j = 0; j < NumEl; ++j)\n\t\t{\n\t\t\tint n1 = JunctionList[i]->EltoVert[j*3]+1;\n\t\t\tint n2 = JunctionList[i]->EltoVert[j*3+1]+1;\n\t\t\tint n3 = JunctionList[i]->EltoVert[j*3+2]+1;\n\t\t\tfprintf(juncMesh, \"%d\\t3\\t%d\\t%d\\t%d\\n\", j+1, n1, n2,n3);\n\n\t\t} \n\n\t\tfprintf(juncMesh, \"\\n EdgtoVert \\n\");\n\t\tfor (int j =0; j < NumEdges; ++j)\n\t\t{\n\t\t\tint n1 = JunctionList[i]->EdgtoVert[j*2]+1;\n\t\t\tint n2 = JunctionList[i]->EdgtoVert[j*2+1]+1;\n\t\t\tfprintf(juncMesh, \"%d\\t%d\\n\",n1,n2);\n\n\t\t}\n\n\t\tfprintf(juncMesh, \"\\n EdgtoEls \\n\");\n\t\tfor (int j =0; j < NumEdges; ++j)\n\t\t{\n\t\t\tint n1 = JunctionList[i]->EdgtoEls[j*2];\n\t\t\tint n2 = JunctionList[i]->EdgtoEls[j*2+1];\n\t\t\tfprintf(juncMesh, \"%d\\t%d\\n\",n1,n2);\n\n\t\t}\n\n\t\tfclose(juncMesh);\n\t\t\n\t}\n*/\n\tboundary_conditions();\n\t\n\tdouble time = 0;\n\tdouble dt = 1e-5;\n\tint Nstep = 0;\n\tint fileNumber = 1;\n\t\n\tdouble minLength = 99999999;\t\n\tfor (int i = 0; i < NumChannels; ++i)\n\t{\n\t\tminLength = fmin(minLength, ChannelList[i]->mindh);\n\t}\n\n\tfor (int i = 0; i < NumJunctions; ++i)\n\t{\n\t\tminLength = fmin(minLength, JunctionList[i]->minEdgLength);\n\t}\n\n\twhile (time < FinalTime)\n\t{\n\t\ttime = time + dt;\n\t\tprintf(\"dt = %e\\n\", dt);\n\t\tprintf(\"time = %e\\n\", time);\t\n\t\n\t\tdouble maxLambda = 0;\n\n\t\t// step forward in time\n\t\tfor(int i=0; imax_lambda);\n\t\t\n\t\t}\n\n\n\t\tinternal_BC();\n\t\n\t\tfor(int i=0; imax_lambda);\n\t\t}\n\t\tinternal_BC();\n\n\t\tboundary_conditions();\n\n\t\t/********* Output data every twentienth step *************/\t\t\n\t\tNstep = Nstep + 1;\n\t\tint NstepinOneSec = floor(1./dt);\n\t\tif (Nstep%5000== 0 || time == FinalTime)\n\t\t//if (Nstep% NstepinOneSec == 0)\n\t\t{\n\t\t\n\t\t\t//Files for the channels \n\t\t\tFILE* file1;\n\t\t\tFILE* file2;\n\t\t\t\n\t\t\tfor (int i=0; iNumNodes;\t\t\t\n\n\t\t\t\tfor (int j = 0; jb[j];\n\t\t\t\t\tz = ChannelList[i]->z[j];\n\t\t\t\t\tdouble x_val = ChannelList[i]->x[j];\n\t\t\t\t\tdouble y_val = ChannelList[i]->y[j];\n\t\n\t\t\t\t\tint k;\n\t\t\t\t\tfor (k=0; k<2; ++k)\n\t\t\t\t\t{\n\t\t\t\n\t\t\t\t\t\tdouble A = ChannelList[i]->A[index(j,k,2)]; \n\t\t\t\t\t\tdouble Q = ChannelList[i]->Q[index(j,k,2)];\n\t\t\t\t\t\tdouble H = A/B;\n\t\t\t\t\t\tdouble zeta = H - z;\n\t\t\t\t\t\tfprintf(file1, \"%e\\t%e\\t%e\\t%e\\n\", x_val, y_val, -z, H);\n\t\t\t\t\t\tfprintf(file2, \"%e\\t%e\\t%e\\t%e\\n\", x_val, y_val, -z, Q);\n\t\t\t\t\t}\n\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\tfclose(file1);\n\t\t\t\tfclose(file2);\n\t\t\t}\n\t\n\t\t\tFILE* file3;\n\t\t\tFILE* file4;\n\t\t\tFILE* file5;\n\n\t\t\tfor (int i=0; iNumEl; ++j)\n\t\t\t\t{\n\t\t\t\t\tfor(k=0; k<3; ++k)\t\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble zeta = JunctionList[i]->zeta[index(j,k,3)];\n\t\t\t\t\t\tdouble Qx = JunctionList[i]->Qx[index(j,k,3)];\n\t\t\t\t\t\tdouble Qy = JunctionList[i]->Qy[index(j,k,3)];\n\t\t\t\t\t\tdouble z1 = JunctionList[i]->z[JunctionList[i]->EltoVert[j*3+k]];\n\t\t\t\t\t\tdouble z2 = JunctionList[i]->z[JunctionList[i]->EltoVert[j*3+(k+1)%3]];\n\t\t\t\t\t\tdouble z = 0.5*(z1+z2);\n\t\t\t\t\t\tdouble height = zeta + z;\n\t\t\t\t\t\tfprintf(file3, \"%1.15f\\t\\t\",height);\n\t\t\t\t\t\tfprintf(file4, \"%1.15f\\t\\t\",Qx);\n\t\t\t\t\t\tfprintf(file5, \"%1.15f\\t\\t\",Qy);\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(file3, \"\\n\");\n\t\t\t\t\tfprintf(file4, \"\\n\");\n\t\t\t\t\tfprintf(file5, \"\\n\");\n\t\t\t\t}\n\t\t\t\tfclose(file3);\n\t\t\t\tfclose(file4);\n\t\t\t\tfclose(file5);\n\t\t\t}\n\t\t\t\t\n\t\t\t++fileNumber;\n\t\t}\n\t\t\t\n\t\t\n\t\t/**************** Set next time step ****************/\n\n\t\t \n\t\t// set next time step\n\t\t//printf(\"max_lambda = %e\\n\", maxlambda);\n\t\t//printf(\"mindx = %e\\n\", mindx);\n\t\tdt = 0.4*minLength/maxLambda;\n\t\tif ((time + dt) > FinalTime)\n\t\t\tdt = FinalTime - time;\n\n\t}\n}\n", "meta": {"hexsha": "44c7209daca174f848aa9d2bfeaeaa20cda3c352", "size": 18016, "ext": "c", "lang": "C", "max_stars_repo_path": "ChanNet/time_evolution.c", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "ChanNet/time_evolution.c", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "ChanNet/time_evolution.c", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 25.9223021583, "max_line_length": 85, "alphanum_fraction": 0.5779307282, "num_tokens": 5903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.48441416276480076}} {"text": "#include \n#include \n#include \n\nint\nmain (void)\n{\n double x = 1, oldsum = 0, sum = 0; \n int i = 0;\n\n gsl_ieee_env_setup (); /* read GSL_IEEE_MODE */\n\n do \n {\n i++;\n \n oldsum = sum;\n sum += x;\n x = x / i;\n \n printf (\"i=%2d sum=%.18f error=%g\\n\",\n i, sum, sum - M_E);\n\n if (i > 30)\n break;\n } \n while (sum != oldsum);\n\n return 0;\n}\n", "meta": {"hexsha": "04f837db288132d5a51f226134678fd5263bd851", "size": 450, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ieeeround.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieeeround.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieeeround.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 14.5161290323, "max_line_length": 49, "alphanum_fraction": 0.4644444444, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.4843329644813887}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\ndouble f (double px, void * par) {\n\n double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2;\n\n struct my_f_params { double x; double y; double z; double v;};\n struct my_f_params * params = (struct my_f_params *)par;\n\n double T2 = (params->x);\n double es = (params->y);\n double eF = (params->z);\n double py = (params->v);\n\n \n double xi,argument;\n double sx=2.*sin(px/2.),sy=2.*sin(py/2.);\n\n double data[] = { ed , 0. , tpd*sx , -tpd*sy,\n 0., es , tsp*sx , tsp*sy,\n tpd*sx, tsp*sx, ep , -tpp*sx*sy,\n -tpd*sy, tsp*sy, -tpp*sx*sy, ep };\n\n gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4);\n gsl_vector *eval = gsl_vector_alloc (4);\n gsl_matrix *evec = gsl_matrix_alloc (4, 4);\n gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4);\n gsl_eigen_symmv (&m.matrix, eval, evec, w);\n gsl_eigen_symmv_free (w);\n gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n\n double e = gsl_vector_get (eval, 2);\n gsl_vector_view evec_i = gsl_matrix_column (evec, 2);\n xi = gsl_vector_get(&evec_i.vector,0)*gsl_vector_get(&evec_i.vector,1);\n\n gsl_vector_free (eval);\n gsl_matrix_free (evec);\n\n double eeF=e-eF;\n if ( eeF == 0 )\n argument=1./T2;\n else\n argument=(tanh(eeF/T2))/eeF;\n argument*=xi*xi;\n\n\treturn argument;\n}\n\n\ndouble g(double py, void * p)\n{\n struct my_f_params { double a; double b; double c; };\n struct my_f_params * params = (struct my_f_params *)p;\n\n double T2 = (params->a);\n double es = (params->b);\n double eF = (params->c);\n\n //printf(\"%g %g %g\\n\",a,b,c);\n struct your_f_params { double x; double y; double z; double v; };\n\n struct your_f_params parametri = { T2, es , eF , py };\n\n double result, error;\n gsl_integration_workspace * w = gsl_integration_workspace_alloc (5000000);\n gsl_function F;\n\n\n F.function = &f;\n F.params = ¶metri;\n\n\n gsl_integration_qags (&F, 0, 2*M_PI, 0, 1e-7, 5000000, w, &result, &error);\n gsl_integration_workspace_free (w);\n\nreturn result;\n}\n\n\ndouble dvoenintegral(double T2, double es, double eF)\n{\n double dvoenintegral, error;\n struct my_f_params { double a; double b; double c; };\n\n gsl_integration_workspace * v = gsl_integration_workspace_alloc (5000000);\n\n gsl_function F;\n struct my_f_params params = {T2, es , eF};\n\n F.function = &g;\n F.params = ¶ms;\n\n gsl_integration_qags (&F, 0, 2*M_PI, 0, 1e-7, 5000000, v, &dvoenintegral, &error);\n gsl_integration_workspace_free (v);\n\nreturn (dvoenintegral)/(2*M_PI*M_PI);\n}\n\n\ndouble optim(double L, void * pp)\n{\n\n struct my_f_params { double a; double b; double c; };\n struct my_f_params * params = (struct my_f_params *)pp;\n\n double Jsd = (params->a);\n double es = (params->b);\n double eF = (params->c);\n \n double TT=2.*exp(-L);\n double tmp=dvoenintegral(TT,es,eF);\n\nreturn Jsd*tmp-1;\n}\n\ndouble nameri_nula( double Jsd, double es, double eF)\n{\n int status;\n double Kelvin=1/11604.;\n struct my_f_params { double a; double b; double c; };\n struct my_f_params params = { Jsd, es , eF};\n int iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double r = 0;\n double x_lo = 1E-6, x_hi = 7;\n gsl_function F;\n\n F.function = &optim;\n F.params = ¶ms;\n\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc (T);\n gsl_root_fsolver_set (s, &F, x_lo, x_hi);\n\n //printf (\"using %s method\\n\", gsl_root_fsolver_name (s));\n\n //printf (\"%5s [%9s, %9s] %9s %10s\\n\", \"iter\", \"lower\", \"upper\", \"root\", \"err\");\n\n do\n {\n iter++;\n status = gsl_root_fsolver_iterate (s);\n r = gsl_root_fsolver_root (s);\n x_lo = gsl_root_fsolver_x_lower (s);\n x_hi = gsl_root_fsolver_x_upper (s);\n status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001);\n\n //if (status == GSL_SUCCESS)\n //printf (\"Converged:\\n\");\n\n //printf (\"%5d [%.7f, %.7f] %.7f %+.7f\\n\", iter, x_lo, x_hi, r, x_hi - x_lo);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n\t//printf(\"T_c=%g\\n\",exp(-r)/Kelvin);\n\n gsl_root_fsolver_free (s);\n\n return (2*exp(-r)/Kelvin);\n}\n\ndouble granichni_tochki(double a, double b,double es)\n{\n\n double sx=2.*sin(a/2.);\n double sy=2.*sin(b/2.);\n\n double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2;\n \n double data[] = { ed , 0. , tpd*sx , -tpd*sy,\n 0., es , tsp*sx , tsp*sy,\n tpd*sx, tsp*sx, ep , -tpp*sx*sy,\n -tpd*sy, tsp*sy, -tpp*sx*sy, ep };\n\n gsl_matrix_view m = gsl_matrix_view_array (data, 4, 4);\n gsl_vector *eval = gsl_vector_alloc (4);\n gsl_matrix *evec = gsl_matrix_alloc (4, 4);\n gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (4);\n gsl_eigen_symmv (&m.matrix, eval, evec, w);\n gsl_eigen_symmv_free (w);\n gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_VAL_ASC);\n\n gsl_vector_free (eval);\n gsl_matrix_free (evec);\n\n return ( gsl_vector_get (eval, 2) );\n}\n\ndouble pd(double e, double es)\n{\n double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2;\n double A,B,C,xd,eep,eed,ees,ppd;\n\neep=e-ep;\need=e-ed;\nees=e-es;\n\nA=16.*(4.*tpd*tpd*tsp*tsp + 2.*tsp*tsp*tpp*eed-2.*tpd*tpd*tpp*ees-tpp*tpp*eed*ees);\nB=-4.*eep*(tsp*tsp*eed+tpd*tpd*ees);\nC=ees*eep*eep*eed;\nxd=(-B+sqrt(B*B-A*C))/A;\n//printf(\"xd=%g\\n\",xd);\nppd=2*asin(sqrt(xd));\n//printf(\"xd=%g ppd=%g e=%g es=%g\\n\",xd,ppd,e,es);\nreturn ppd;\n}\n\n\n\ndouble fermi(double px, void * p) \n{\n struct my_f_params { double a; double b; };\n struct my_f_params * params = (struct my_f_params *)p;\n\n\n double eF = (params->a);\n double es = (params->b);\n \n\n\n double A,B,C,eep,eed,ees,e,F;\n double ep=-.9, ed=.0, tsp=1.63, tpd=1.13, tpp=.2;\n\n e=eF;\neep=e-ep;\need=e-ed;\nees=e-es;\n\n\nA=16.*(4.*tpd*tpd*tsp*tsp + 2.*tsp*tsp*tpp*eed-2.*tpd*tpd*tpp*ees-tpp*tpp*eed*ees);\nB=-4.*eep*(tsp*tsp*eed+tpd*tpd*ees);\nC=ees*eep*eep*eed;\n\ndouble x=sin(px/2.)*sin(px/2.);\nF=(px-2*asin(sqrt(- (C+B*x)/(A*x+B) )));\n\nreturn F;\n}\n\n\n\ndouble ffactor( double eF , double es )\n{\n double res, error;\n struct my_f_params { double a; double b; };\n\n gsl_integration_workspace * v = gsl_integration_workspace_alloc (1000);\n\n gsl_function F;\n struct my_f_params params = {eF , es};\n\n F.function = &fermi;\n F.params = ¶ms;\n\n gsl_integration_qag (&F, pd(eF,es) , M_PI , 0, 1e-7, 1000, 6 , v, &res, &error);\n gsl_integration_workspace_free (v);\n\n\nreturn (8*res)/(4*M_PI*M_PI) ;\n}\n\ndouble ffactornula( double eF , void * p )\n{\n double res, error;\n double es = *(double *) p;\n\n struct my_f_params { double a; double b; };\n\n gsl_integration_workspace * v = gsl_integration_workspace_alloc (100000);\n\n gsl_function F;\n struct my_f_params params = {eF , es};\n\n F.function = &fermi;\n F.params = ¶ms;\n\n gsl_integration_qags (&F, pd(eF,es) , M_PI , 0, 1e-7, 100000, v, &res, &error);\n gsl_integration_workspace_free (v);\n\n\nreturn (8*res)/(4*M_PI*M_PI) - 0.66;\n}\n\ndouble ferminula( double evhs, double etop, double es)\n{\n int status;\n\n int iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double r = 0;\n double x_lo = evhs+1E-7, x_hi = etop-1E-7;\n gsl_function F;\n\n F.function = &ffactornula;\n F.params = &es;\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc (T);\n gsl_root_fsolver_set (s, &F, x_lo, x_hi);\n\n //printf (\"using %s method\\n\", gsl_root_fsolver_name (s));\n\n //printf (\"%5s [%9s, %9s] %9s %10s\\n\", \"iter\", \"lower\", \"upper\", \"root\", \"err\");\n\n do\n {\n iter++;\n status = gsl_root_fsolver_iterate (s);\n r = gsl_root_fsolver_root (s);\n x_lo = gsl_root_fsolver_x_lower (s);\n x_hi = gsl_root_fsolver_x_upper (s);\n status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001);\n\n //if (status == GSL_SUCCESS)\n //printf (\"Converged:\\n\");\n\n //printf (\"%5d [%.7f, %.7f] %.7f %+.7f\\n\", iter, x_lo, x_hi, r, x_hi - x_lo);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n\t\n gsl_root_fsolver_free (s);\n\n return r;\n}\n\nint main(void)\n{\n double Kelvin=1/11604.;\n double es=6.0, eF=1.301531002,tsp=1.63,ep=-.9,tpd=1.13;\n double Jsd,Tc,evhs,etop,s,ss;\n //double tmp;\n/*\n Jsd=1/dvoenintegral(90*Kelvin,es,eF);\n printf (\"Jsd= %g\\n\",Jsd);\n Tc=nameri_nula(Jsd,es,eF);\n printf (\"Tc= %g\\n\",Tc);\n evhs=granichni_tochki(0,M_PI,es);\n printf(\"evhs=%g\\n\",evhs);\n etop=granichni_tochki(M_PI,M_PI,es);\n printf(\"etop=%g\\n\",etop);\n ff=ffactor(evhs, es);\n printf(\"filling factor(evhs)=%g\\n\",ff);\n printf(\"%g\\n\",ferminula(evhs,etop,es));\n*/\n Jsd=1/dvoenintegral(90*Kelvin,es,eF);\n\n for(es=5;es<8.5;es+=0.1)\n {\n evhs=granichni_tochki(0,M_PI,es);\n etop=granichni_tochki(M_PI,M_PI,es);\n eF=ferminula(evhs,etop,es);\n Tc=nameri_nula(Jsd,es,eF);\n //s=((es-eF)*(eF-ep))/(4*tsp*tsp);\n ss=((es-eF)*(eF-ep))/(4*tsp*tpd);\n //printf(\"Tc=%g es=%g eF=%g\\n\",Tc,es,eF);\n printf(\"%g %g\\n\",ss,log(Tc));\n //printf(\"%g %g\\n\",1/(2*(1+s)),Tc );\n }\n\n\n return 0;\n}\n", "meta": {"hexsha": "7f2abe896ad24908a93952b40123ce2237a656c4", "size": 10691, "ext": "c", "lang": "C", "max_stars_repo_path": "Tc_r.c", "max_stars_repo_name": "zlatan/Superconductivity", "max_stars_repo_head_hexsha": "968c055802abcfa179fae72b0b73d3b1c82c829b", "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": "Tc_r.c", "max_issues_repo_name": "zlatan/Superconductivity", "max_issues_repo_head_hexsha": "968c055802abcfa179fae72b0b73d3b1c82c829b", "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": "Tc_r.c", "max_forks_repo_name": "zlatan/Superconductivity", "max_forks_repo_head_hexsha": "968c055802abcfa179fae72b0b73d3b1c82c829b", "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.5093333333, "max_line_length": 98, "alphanum_fraction": 0.5263305584, "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4842841902248766}} {"text": "//Gets line spectral frequencies (LSFs).\n//from the autoregressive (AR) coefficients along cols or rows of X.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"cmp_ascend.c\"\n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint ar2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);\nint ar2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);\nint ar2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);\nint ar2lsf_z (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);\n\n\nint ar2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)\n{\n const float z = 0.0f, o = 1.0f;\n const int P = (dim==0) ? R : C;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = P+1, n = P+1, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n float *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];\n int r, c;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in ar2lsf_s: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in ar2lsf_s: ncols X must be positive\\n\"); return 1; }\n if (P<1) { fprintf(stderr,\"error in ar2lsf_s: P (length of polynomial coeffs including a0=1) must be positive\\n\"); return 1; }\n\n //Allocate\n if (!(poly=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(prev=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wr=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wi=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(compan=(float *)malloc((size_t)(n*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0)\n {\n for (c=0; c10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; poly[r] += prev[r] + prev[r]; }\n cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);\n info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in ar2lsf_s: lapacke decomposition failed\\n\"); return 1; }\n for (r=0; r10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; }\n qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);\n if (iscolmajor) { cblas_scopy(P,&omegas[n+1],1,&Y[c*P],1); }\n else { cblas_scopy(P,&omegas[n+1],1,&Y[c],C); }\n }\n }\n else if (dim==1)\n {\n for (r=0; r10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; poly[c] += prev[c] + prev[c]; }\n cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(P,&o,0,&compan[1],n+1); cblas_scopy(n,poly,1,compan,n);\n info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in ar2lsf_s: lapacke decomposition failed\\n\"); return 1; }\n for (c=0; c10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; }\n qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);\n if (iscolmajor) { cblas_scopy(P,&omegas[n+1],1,&Y[r],R); }\n else { cblas_scopy(P,&omegas[n+1],1,&Y[r*P],1); }\n }\n }\n else\n {\n fprintf(stderr,\"error in ar2lsf_s: dim must be 0 or 1.\\n\"); return 1;\n }\n\n //Exit\n free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);\n return 0;\n}\n\n\nint ar2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim)\n{\n const double z = 0.0, o = 1.0;\n const int P = (dim==0) ? R : C;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = P+1, n = P+1, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n double *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];\n int r, c;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in ar2lsf_d: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in ar2lsf_d: ncols X must be positive\\n\"); return 1; }\n if (P<1) { fprintf(stderr,\"error in ar2lsf_d: P (length of polynomial coeffs including a0=1) must be positive\\n\"); return 1; }\n\n //Allocate\n if (!(poly=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(prev=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(omegas=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wr=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wi=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(compan=(double *)malloc((size_t)(n*n)*sizeof(double)))) { fprintf(stderr,\"error in ar2lsf_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0)\n {\n for (c=0; c10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; poly[r] += prev[r] + prev[r]; }\n cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);\n info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in ar2lsf_d: lapacke decomposition failed\\n\"); return 1; }\n for (r=0; r10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; }\n qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);\n if (iscolmajor) { cblas_dcopy(P,&omegas[n+1],1,&Y[c*P],1); }\n else { cblas_dcopy(P,&omegas[n+1],1,&Y[c],C); }\n }\n }\n else if (dim==1)\n {\n for (r=0; r10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; poly[c] += prev[c] + prev[c]; }\n cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(P,&o,0,&compan[1],n+1); cblas_dcopy(n,poly,1,compan,n);\n info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in ar2lsf_d: lapacke decomposition failed\\n\"); return 1; }\n for (c=0; c10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; }\n qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);\n if (iscolmajor) { cblas_dcopy(P,&omegas[n+1],1,&Y[r],R); }\n else { cblas_dcopy(P,&omegas[n+1],1,&Y[r*P],1); }\n }\n }\n else\n {\n fprintf(stderr,\"error in ar2lsf_d: dim must be 0 or 1.\\n\"); return 1;\n }\n\n //Exit\n free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);\n return 0;\n}\n\n\nint ar2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)\n{\n const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f};\n const int P = (dim==0) ? R : C;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = P, n = P, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n float *poly, *prev, *omegas, *compan, *wc, zz[2];\n int r, c;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in ar2lsf_c: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in ar2lsf_c: ncols X must be positive\\n\"); return 1; }\n if (P<1) { fprintf(stderr,\"error in ar2lsf_c: P (length of polynomial coeffs including a0=1) must be positive\\n\"); return 1; }\n\n //Allocate\n if (!(poly=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(prev=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wc=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(compan=(float *)malloc((size_t)(4*n*n)*sizeof(float)))) { fprintf(stderr,\"error in ar2lsf_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0)\n {\n for (c=0; c\r\n#include \r\n#include \r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct\r\n {\r\n const char *name;\r\n size_t size;\r\n int (*set) (void *state, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper);\r\n int (*iterate) (void *state, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper);\r\n }\r\ngsl_min_fminimizer_type;\r\n\r\ntypedef struct\r\n {\r\n const gsl_min_fminimizer_type * type;\r\n gsl_function * function ;\r\n double x_minimum ;\r\n double x_lower ;\r\n double x_upper ;\r\n double f_minimum, f_lower, f_upper;\r\n void *state;\r\n }\r\ngsl_min_fminimizer;\r\n\r\nGSL_FUN gsl_min_fminimizer *\r\ngsl_min_fminimizer_alloc (const gsl_min_fminimizer_type * T) ;\r\n \r\nGSL_FUN void gsl_min_fminimizer_free (gsl_min_fminimizer * s);\r\n\r\nGSL_FUN int gsl_min_fminimizer_set (gsl_min_fminimizer * s, \r\n gsl_function * f, double x_minimum, \r\n double x_lower, double x_upper);\r\n\r\nGSL_FUN int gsl_min_fminimizer_set_with_values (gsl_min_fminimizer * s, \r\n gsl_function * f, \r\n double x_minimum, double f_minimum,\r\n double x_lower, double f_lower,\r\n double x_upper, double f_upper);\r\n\r\nGSL_FUN int gsl_min_fminimizer_iterate (gsl_min_fminimizer * s);\r\n\r\nGSL_FUN const char * gsl_min_fminimizer_name (const gsl_min_fminimizer * s);\r\n\r\nGSL_FUN double gsl_min_fminimizer_x_minimum (const gsl_min_fminimizer * s);\r\nGSL_FUN double gsl_min_fminimizer_x_lower (const gsl_min_fminimizer * s);\r\nGSL_FUN double gsl_min_fminimizer_x_upper (const gsl_min_fminimizer * s);\r\nGSL_FUN double gsl_min_fminimizer_f_minimum (const gsl_min_fminimizer * s);\r\nGSL_FUN double gsl_min_fminimizer_f_lower (const gsl_min_fminimizer * s);\r\nGSL_FUN double gsl_min_fminimizer_f_upper (const gsl_min_fminimizer * s);\r\n\r\n/* Deprecated, use x_minimum instead */\r\nGSL_FUN double gsl_min_fminimizer_minimum (const gsl_min_fminimizer * s);\r\n\r\nGSL_FUN int\r\ngsl_min_test_interval (double x_lower, double x_upper, double epsabs, double epsrel);\r\n\r\nGSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_goldensection;\r\nGSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_brent;\r\nGSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_quad_golden;\r\n\r\ntypedef\r\nint (*gsl_min_bracketing_function)(gsl_function *f,\r\n double *x_minimum,double * f_minimum,\r\n double *x_lower, double * f_lower,\r\n double *x_upper, double * f_upper,\r\n size_t eval_max);\r\n\r\nGSL_FUN int \r\ngsl_min_find_bracket(gsl_function *f,double *x_minimum,double * f_minimum,\r\n double *x_lower, double * f_lower,\r\n double *x_upper, double * f_upper,\r\n size_t eval_max);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MIN_H__ */\r\n", "meta": {"hexsha": "73dce773028d52d91d8673e377e3636562736185", "size": 4513, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_min.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_min.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_min.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": 36.9918032787, "max_line_length": 164, "alphanum_fraction": 0.672723244, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.48413285519773985}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define qh_QHimport\n#include \n\nvoid print_summary(qhT *qh);\ndouble findDelaunay(qhT *qh, int dim, coordT *TargetCoord);\ndouble findNearestVertices(qhT *qh, int dim, coordT *TargetCoord);\ndouble findNearestCentrum(qhT *qh, int dim, coordT *TargetCoord);\n\nvoid obtain_convex_h_qhull(int n_data, double *ef2cvh, int *x, double *y, int NCatDim, int *nCat_min, int *nCat_max, double *E0, char *qhullflags) {\n \n int i, j, k, l, nid, Ndim;\n double tmp;\n \n Ndim = NCatDim - 1; // because nV is dependent on other nCats\n printf(\"Convex hull is created using qhull.\\n\");\n printf(\"Input data\\n\");\n printf(\"---------------------------\\n\");\n printf(\" nL nN nM nC nV Ef\\n\");\n for (i=0;ierrexit);\n if (!exitcode) {\n /* Trap Qhull errors in findDelaunay(). Without the setjmp(), Qhull\n will exit() after reporting an error */\n qh->NOerrexit= False;\n for (i=0;iNOerrexit= True;\n }\n qh_freeqhull(qh, !qh_ALL); /* free long memory */\n qh_memfreeshort(qh, &curlong, &totlong); /* free short memory and memory allocator */\n if (curlong || totlong)\n fprintf(errfile, \"qhull internal warning (user_eg, #2): did not free %d bytes of long memory (%d pieces)\\n\", totlong, curlong);\n}\n\nvoid print_summary(qhT *qh) {\n facetT *facet;\n vertexT *vertex;\n int k;\n \n printf(\"\\n%d facets with normals:\\n\", qh->num_facets);\n FORALLfacets {\n for (k=0; k < qh->hull_dim; k++) {\n printf(\"%6.2g \", facet->normal[k]);\n// printf(\"\", facet->vertices);\n }\n printf(\"\\n\");\n }\n printf(\"\\n%d vertices:\\n\",qh->num_vertices);\n FORALLvertices {\n qh_printvertex(qh, qh->fout, vertex);\n }\n}\n\ndouble findDelaunay(qhT *qh, int dim, coordT *TargetCoord) {\n int j, k;\n coordT tmppoint[ 100];\n boolT isoutside;\n realT bestdist;\n facetT *facet;\n vertexT *vertex, **vertexp;\n \n for (k= 0; k < dim; k++)\n tmppoint[k]= TargetCoord[k];\n qh_setdelaunay(qh, dim+1, 1, tmppoint);\n facet= qh_findbestfacet(qh, tmppoint, qh_ALL, &bestdist, &isoutside);\n if (facet->tricoplanar) {\n fprintf(stderr, \"findDelaunay: not implemented for triangulated, non-simplicial Delaunay regions (tricoplanar facet, f%d).\\n\",\n facet->id);\n qh_errexit(qh, qh_ERRqhull, facet, NULL);\n }\n \n for (k= 0; k < dim-1; k++)\n printf(\"% .3f \",tmppoint[k]);\n printf(\"% .3f, \",tmppoint[dim-1]);\n printf(\"facet id: %d\\n\",facet->id);\n/* FOREACHvertex_(facet->vertices) {\n for (k=0; k < dim; k++)\n printf(\"%5.3f \", vertex->point[k]);\n printf(\"vertex id: %d, point id: %d\\n\", vertex->id, qh_pointid(qh, vertex->point));\n }*/\n FOREACHvertex_(facet->vertices) {\n printf(\"vertex id: %d, point id: %d\\n\", vertex->id, qh_pointid(qh, vertex->point));\n }\n \n gsl_matrix * A = gsl_matrix_alloc (dim,dim);\n gsl_matrix * V = gsl_matrix_alloc (dim,dim);\n gsl_vector * S = gsl_vector_alloc (dim);\n gsl_vector * work = gsl_vector_alloc (dim);\n gsl_vector * b = gsl_vector_alloc (dim);\n gsl_vector * x = gsl_vector_alloc (dim);\n \n j= 0;\n FOREACHvertex_(facet->vertices) {\n for (k= 0; k < dim; k++)\n gsl_matrix_set (A,k,j, vertex->point[k]);\n gsl_vector_set(b,j,tmppoint[j]);\n j++;\n }\n double ef[dim];\n // dismiss the last row corresponding to Ef\n // & apply the constriction on the coefficients sum_x_i = 1\n for (k= 0; k < dim; k++) {\n ef[k] = gsl_matrix_get (A,dim-1,k);\n gsl_matrix_set (A,dim-1,k,1.0);\n }\n gsl_vector_set(b,dim-1,2.0);\n\n gsl_linalg_SV_decomp(A, V, S, work);\n gsl_linalg_SV_solve (A, V, S, b, x);\n \n double ef_cvh = 0.0;\n for (k= 0; k < dim; k++)\n ef_cvh += gsl_vector_get(x,k)*ef[k];\n\n gsl_matrix_free(A);\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n gsl_vector_free(b);\n gsl_vector_free(x);\n\n return(TargetCoord[dim-1]-ef_cvh);\n}\n\ndouble findNearestVertices(qhT *qh, int dim, coordT *TargetCoord) {\n int i, j, k;\n int nid;\n double ef_cvh;\n double tmp;\n double tmppoint[dim];\n boolT isoutside;\n realT bestdist;\n facetT *facet;\n vertexT *vertex, **vertexp;\n \n nid = qh->num_vertices;\n for (k= 0; k < dim; k++)\n tmppoint[k]= TargetCoord[k];\n \n double verticespoint[nid][dim];\n j = 0;\n FORALLvertices {\n for (k= 0; k < dim; k++)\n verticespoint[j][k] = vertex->point[k];\n j++;\n }\n \n double dij2[nid];\n int ids[nid];\n for (j= 0; j< nid; j++) {\n tmp = 0.0;\n for (k= 0; k < dim-1; k++) { //ef is excluded for configurational coordinate\n tmp += pow(verticespoint[j][k] - tmppoint[k],2);\n }\n dij2[j] = tmp;\n ids[j] = j;\n }\n sort_array_ids(dij2,ids,nid);\n \n gsl_matrix * A = gsl_matrix_alloc (dim,dim);\n gsl_matrix * V = gsl_matrix_alloc (dim,dim);\n gsl_vector * S = gsl_vector_alloc (dim);\n gsl_vector * work = gsl_vector_alloc (dim);\n gsl_vector * b = gsl_vector_alloc (dim);\n gsl_vector * x = gsl_vector_alloc (dim);\n\n if (dij2[0]==0.0)\n ef_cvh = 0.0;\n else {\n for (j= 0; j< dim; j++) {\n for (k= 0; k < dim; k++)\n gsl_matrix_set (A,k,j,verticespoint[ids[j]][k]);\n gsl_vector_set(b,j,tmppoint[j]);\n }\n for (k= 0; k < dim; k++) { //dismiss the last row corresponding to ef\n gsl_matrix_set (A,dim-1,k,1.0);\n }\n gsl_vector_set(b,dim-1,2.0); //dismiss the last row corresponding to ef\n gsl_linalg_SV_decomp(A, V, S, work);\n gsl_linalg_SV_solve (A, V, S, b, x);\n tmp = 0.0;\n for (j= 0; j< dim; j++)\n tmp += gsl_vector_get(x,j)*verticespoint[ids[j]][dim-1];\n ef_cvh = tmppoint[dim-1]-tmp;\n }\n \n gsl_matrix_free(A);\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n gsl_vector_free(b);\n gsl_vector_free(x);\n \n return(ef_cvh);\n}\n\ndouble findNearestCentrum(qhT *qh, int dim, coordT *TargetCoord) {\n int i, j, k;\n int nf, nv;\n double ef_cvh;\n double tmp;\n double tmppoint[dim];\n boolT isoutside;\n realT bestdist;\n facetT *facet;\n vertexT *vertex, **vertexp;\n pointT *centrum;\n \n nf = qh->num_facets;\n nv = qh->num_vertices;\n \n for (k= 0; k < dim; k++)\n tmppoint[k]= TargetCoord[k];\n \n double facet_normal[nf][dim];\n double facet_center[nf][dim];\n int facet_id[nf];\n int num_lowerhullfacets;\n \n j = 0;\n FORALLfacets {\n if (facet->normal[dim-1] < 0.0) {//is the slope in ef direction negative?\n for (k= 0; k < dim; k++) {\n facet_normal[j][k] = facet->normal[k];\n if (qh->CENTERtype == qh_AScentrum)\n centrum= facet->center;\n else\n centrum= qh_getcentrum(qh, facet);\n facet_center[j][k] = centrum[k];\n facet_id[j] = facet->id;\n }\n j++;\n }\n }\n num_lowerhullfacets = j;\n \n double dij2[num_lowerhullfacets];\n int ids[num_lowerhullfacets];\n for (j= 0; j< num_lowerhullfacets; j++) {\n tmp = 0.0;\n for (k= 0; k < dim-1; k++) { //ef is excluded for configurational coordinate\n tmp += pow(facet_center[j][k] - tmppoint[k],2);\n }\n dij2[j] = tmp;\n ids[j] = j;\n }\n sort_array_ids(dij2,ids,num_lowerhullfacets);\n \n int projectedfacet = facet_id[ids[0]];\n double vertices_point[dim][dim];\n FORALLfacets {\n if (facet->id == projectedfacet) {\n j = 0;\n FOREACHvertex_(facet->vertices) {\n for (k=0; k < dim; k++)\n vertices_point[j][k] = vertex->point[k];\n j++;\n }\n }\n }\n \n gsl_matrix * A = gsl_matrix_alloc (dim,dim);\n gsl_matrix * V = gsl_matrix_alloc (dim,dim);\n gsl_vector * S = gsl_vector_alloc (dim);\n gsl_vector * work = gsl_vector_alloc (dim);\n gsl_vector * b = gsl_vector_alloc (dim);\n gsl_vector * x = gsl_vector_alloc (dim);\n \n for (j= 0; j< dim; j++) {\n for (k= 0; k < dim; k++)\n gsl_matrix_set (A,k,j,vertices_point[j][k]);\n gsl_vector_set(b,j,tmppoint[j]);\n }\n for (k= 0; k < dim; k++) { //dismiss the last row corresponding to ef\n gsl_matrix_set (A,dim-1,k,1.0);\n }\n gsl_vector_set(b,dim-1,1.0); //dismiss the last row corresponding to ef\n \n printf(\"A:\\n\");\n for (j= 0; j< dim; j++) {\n for (k= 0; k < dim; k++)\n printf(\"%g \", gsl_matrix_get (A,j,k));\n printf(\"\\n\");\n }\n printf(\"b:\\n\");\n for (j= 0; j< dim; j++)\n printf(\"%g\\n\", gsl_vector_get(b,j));\n \n gsl_linalg_SV_decomp(A, V, S, work);\n gsl_linalg_SV_solve (A, V, S, b, x);\n printf(\"solution:\\n\");\n for (j= 0; j< dim; j++)\n printf(\"%g\\n\", gsl_vector_get(x,j));\n // need to check if the components of x is in [0,2]\n for (j= 0; j< dim; j++) {\n tmp = gsl_vector_get(x,j);\n if (tmp < -0.1 || tmp > 1.0) {\n printf(\"\\n%d-component of x is %f, out of range\\n\", j, tmp);\n exit(-1);\n }\n }\n tmp = 0.0;\n for (j= 0; j< dim; j++)\n tmp += gsl_vector_get(x,j)*vertices_point[j][dim-1];\n ef_cvh = tmppoint[dim-1]-tmp;\n \n gsl_matrix_free(A);\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n gsl_vector_free(b);\n gsl_vector_free(x);\n \n return(ef_cvh);\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "2699eb7c3df4abd88f9a995b864e885f75e19e3e", "size": 12816, "ext": "c", "lang": "C", "max_stars_repo_path": "src_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_stars_repo_name": "eunseok-lee/spin_atom_CE3", "max_stars_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "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_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_issues_repo_name": "eunseok-lee/spin_atom_CE3", "max_issues_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "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_data_to_corr_mat3/obtain_convex_h_qhull.old.c", "max_forks_repo_name": "eunseok-lee/spin_atom_CE3", "max_forks_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3636363636, "max_line_length": 148, "alphanum_fraction": 0.549937578, "num_tokens": 3950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.48406609026365593}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"ccl.h\"\n#include \"ccl_params.h\"\n#include \"ccl_redshifts.h\"\n\n// ---- LSST redshift distributions & current specs -----\n// ---- Consider spline for input dN/dz - pending\n\n/*------ ROUTINE: ccl_create_photoz_info ------\nINPUT: void * params, (double *) pz_func (double, double, void *)\nTASK: create a structure amalgamating the user-input information on the photo-z model.\nThe structure holds a pointer to the function which returns the probability of getting a certain z_ph (first double) \ngiven a z_spec (second double), and a pointer to the parameters which get passed to that function (other than z_ph and z_sp); */\npz_info* ccl_create_photoz_info(void * params,\n\t\t\t\t\t double (*pz_func)(double, double,void*, int*))\n{\n pz_info * this_info = malloc(sizeof(pz_info));\n this_info ->your_pz_params = params;\n this_info -> your_pz_func = pz_func;\n \n return this_info;\n}\n\n/*------ ROUTINE: ccl_photoz -----\nINPUT: double z_ph, void *params\nTASK: Returns the value of p(z_photo, z). Change this function to \n change the way true-z and photo-z's are related.\n This has to be in a form that gsl can integrate.\n*/\n// struct of parameters to pass to photo_z\nstruct pz_params{\n double z_true; // Gives the true redshift at which to evaluate \n pz_info * pz_information; //Calls the photo-z scatter model\n int *status;\n};\n\nstatic double ccl_photoz(double z_ph, void * params)\n{\n struct pz_params * p = (struct pz_params *) params;\n pz_info * user_stuff = (pz_info*) p->pz_information; \n double z_s = p->z_true;\t\n \n return (user_stuff->your_pz_func)(z_ph, z_s, user_stuff->your_pz_params,p->status);\n}\n\n// Gaussian photo-z function\ndouble gaussian_pz(double z_ph, double z_s, void* params, int *status){\n double sigma_z0 = *((double*) params);\n\n double sigma_z = sigma_z0 * (1. + z_s);\n return exp(- (z_ph - z_s)*(z_ph - z_s) / (2.*sigma_z*sigma_z)) \\\n / (sqrt(2.*M_PI) *sigma_z);\n}\n\n/*------ ROUTINE: ccl_specs_create_gaussian_photoz_info ------\nINPUT: void * user_pz_params, (double *) user_pz_func (double, double, void *)\nTASK: Convenience function for creating a Gaussian photo-z model with error\nsigma(z) = sigma_z0 (1 + z). */\n\npz_info* ccl_create_gaussian_photoz_info(double sigma_z0){\n \n // Allocate memory so that this value persists\n double* sigma_z0_copy = malloc(sizeof(double));\n *sigma_z0_copy = sigma_z0;\n \n // Construct pz_info struct\n pz_info * this_info = malloc(sizeof(pz_info));\n this_info->your_pz_params = sigma_z0_copy;\n this_info->your_pz_func = &gaussian_pz;\n return this_info;\n}\n\n/* ------ ROUTINE: ccl_free_photoz_info -------\nINPUT: pz_info my_photoz_info\nTASK: free memory holding the structure containing user-input photoz information */\n\nvoid ccl_free_photoz_info(pz_info *my_photoz_info)\n{\n free(my_photoz_info);\n}\n\n/*------ ROUTINE: ccl_create_dNdz_info ------\nINPUT: void * params, (double *) dNdz_func (double, void *, int*)\nTASK: create a structure amalgamating the information on an analytic true dNdz model.\nThe structure holds a pointer to the function which returns the analytic dNdz \n* and a pointer to the parameters which get passed to that function (other than z); */\ndNdz_info* ccl_create_dNdz_info(void * params, double(*dNdz_func)(double,void*,int*))\n{\n dNdz_info * this_info = malloc(sizeof(dNdz_info));\n this_info ->your_dN_params = params;\n this_info -> your_dN_func = dNdz_func;\n \n return this_info;\n}\n\n/*------ ROUTINE: dNdz_smail ----------\n * INPUT: z, params (containing: alpha, beta, z0), status\n * OUTPUT: Analytic Smail et al. type dNdz (NOT normalized) */\n\ndouble dNdz_smail(double z, void* params, int *status){\n double alpha = ((smail_params*) params)->alpha;\n double beta = ((smail_params*) params)->beta;\n double z0 = ((smail_params*) params)->z0;\n\n return pow(z, alpha) * exp(- pow(z/z0, beta) );\n}\n\n/*------ ROUTINE: ccl_create_smail_dNdz_info ------\nINPUT: alpha, beta, z0\nTASK: Convenience function for creating an analytic dNdz wrt true z\n* of the 'smail' form: dNdz ~ z^alpha exp(- (z/z0)^beta) */\n\ndNdz_info* ccl_create_Smail_dNdz_info(double alpha, double beta, double z0){\n \n // Allocate a smail type parmaeter structure\n smail_params * smail_par = malloc(sizeof(smail_params));\n smail_par->alpha = alpha;\n smail_par->beta = beta;\n smail_par->z0 = z0;\n \n // Construct dNdz_info struct\n dNdz_info * this_info = malloc(sizeof(dNdz_info));\n this_info->your_dN_params = smail_par;\n this_info->your_dN_func = &dNdz_smail;\n return this_info;\n}\n\n/*------ ROUTINE: ccl_dNdz -----\nINPUT: double z, void *params\nTASK: Returns the value of dNdz(z). Change this function to \n change the way true-z and photo-z's are related.\n This has to be in a form that gsl can integrate.\n*/\n\nstatic double ccl_dNdz(double z, dNdz_info* params, int* status)\n{ \n\t\t\n return (params->your_dN_func)(z, params->your_dN_params, status);\n}\n\n/* ------ ROUTINE: ccl_free_dNdz_info -------\nINPUT: dNdz_info my_dNdz_info\nTASK: free memory holding the structure containing dNdz information */\n\nvoid ccl_free_dNdz_info(dNdz_info *my_dNdz_info)\n{\n free(my_dNdz_info);\n}\n\n/*------ ROUTINE: ccl_specs_norm_integrand -----\nINPUT: double z_ph, void *params\nTASK: Returns the integrand which is integrated to get the normalization of \n dNdz in a given photometric redshift bin (the denominator from dNdz_sources_tomog). \n This has to be an separate function that gsl can integrate.\n*/\n\n// struct of parameters to pass to norm_integrand\nstruct norm_params {\n double bin_zmin_;\n double bin_zmax_;\n pz_info * pz_information;\n dNdz_info * dN_information;\n int *status;\n};\n\nstatic double ccl_norm_integrand(double z, void* params)\n{\t\n\t\n // This is a struct that contains a true redshift and a pointer to the information about the photo_z model\n struct pz_params pz_val_p; // parameters for the photoz pdf wrt true-z\n \n double pz_int=0; // pointer to the value of the integral over the photoz model\n struct norm_params *p = (struct norm_params *) params; // parameters of the current function (because of form required for gsl integration)\n \n double z_min = p->bin_zmin_;\n double z_max = p->bin_zmax_;\n \n // Check whether ccl_splines and ccl_gsl exist; exit gracefully if they \n // can't be loaded\n if(ccl_splines==NULL || ccl_gsl==NULL) ccl_cosmology_read_config();\n if(ccl_splines==NULL || ccl_gsl==NULL) {\n ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, \n \"ccl_redshift.c: Failed to read config file.\");\n return NAN;\n }\n \n // Set up parameters for the pz part of the intermediary integral.\n pz_val_p.z_true = z;\n pz_val_p.status = p->status;\n pz_val_p.pz_information = p-> pz_information;\n \n // Do the intermediary integral over the model relating photo-z to true-z\t\n gsl_integration_cquad_workspace * workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n gsl_function F;\n F.function = ccl_photoz;\n F.params = &pz_val_p;\n int gslstatus = gsl_integration_cquad(&F, z_min, z_max, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&pz_int, NULL, NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_redshifts.c: ccl_specs_norm_integrand():\");\n *p->status|= gslstatus;\n }\n gsl_integration_cquad_workspace_free(workspace);\n \n return ccl_dNdz(z, p->dN_information, p->status) * pz_int ;\n}\n\n/*------ ROUTINE: ccl_specs_dNdz_tomog -----\nINPUT: double z, , double bin_zmin, double bin_zmax, dNdz function pointer, sigma_z function pointer\n tomographic boundaries are [bin_zmin,bin_zmax]\nTASK: dNdz in a particular tomographic bin, \n convolved with a photo-z model (defined by the user), and normalized.\n returns a status integer 0 if called with an allowable type of dNdz, non-zero otherwise\n (this is different from the regular status handling procedure because we don't pass a cosmology to this function)\n*/\nvoid ccl_dNdz_tomog(double z, double bin_zmin, double bin_zmax, \n pz_info * photo_info, dNdz_info * dN_info, double *tomoout, int *status)\n{\t\n // This uses equation 33 of Joachimi & Schneider 2009, arxiv:0905.0393\n double numerator_integrand=0, denom_integrand=0, dNdz_t;\n // This struct contains a spec redshift and a pointer to a photoz information struct.\n struct pz_params pz_p_val; //parameters for the integral over the photoz's\n struct norm_params norm_p_val;\t\n \n // Check whether ccl_splines and ccl_gsl exist; exit gracefully if they \n // can't be loaded\n if(ccl_splines==NULL || ccl_gsl==NULL) ccl_cosmology_read_config();\n if(ccl_splines==NULL || ccl_gsl==NULL) {\n ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE, \n \"ccl_redshifts.c: Failed to read config file.\");\n *status = CCL_ERROR_MISSING_CONFIG_FILE;\n return;\n }\n \n // Set up the parameters to pass to the normalising integral (of type struct norm_params\n norm_p_val.bin_zmin_=bin_zmin;\n norm_p_val.bin_zmax_=bin_zmax;\n norm_p_val.pz_information = photo_info;\t\n norm_p_val.status = status;\n norm_p_val.dN_information = dN_info;\n \n dNdz_t = ccl_dNdz(z, dN_info, status);\n \n // Set up the parameters for the integral over the photo z function in the numerator (of type struct pz_params)\n pz_p_val.z_true = z;\n pz_p_val.status = status;\n pz_p_val.pz_information = photo_info; // pointer to user information\n \n // Integrate over the assumed pdf of photo-z wrt true-z in this bin (this goes in the numerator of the result):\n gsl_integration_cquad_workspace * workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n gsl_function F;\n F.function = ccl_photoz;\n F.params = &pz_p_val;\n int gslstatus = gsl_integration_cquad(&F, bin_zmin, bin_zmax, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&numerator_integrand, NULL, NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_redshifts.c: ccl_norm_integrand():\");\n *status |= gslstatus;\n } \n gsl_integration_cquad_workspace_free(workspace);\t\n \n // Now get the denominator, which normalizes dNdz over the photometric bin\n workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n F.function = ccl_norm_integrand;\n F.params = &norm_p_val;\n gslstatus = gsl_integration_cquad(&F, Z_MIN_SOURCES, Z_MAX_SOURCES, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&denom_integrand, NULL, NULL);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_redshifts.c: ccl_norm_integrand():\");\n *status |= gslstatus;\n }\n \n gsl_integration_cquad_workspace_free(workspace);\n if (*status) {\n *status = CCL_ERROR_INTEG;\n return;\n }\n *tomoout = dNdz_t * numerator_integrand / denom_integrand;\n\n}\n", "meta": {"hexsha": "e606751253fa10ded06683c9487fd3846209cf69", "size": 10839, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_redshifts.c", "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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_redshifts.c", "max_issues_repo_name": "vrastil/CCL", "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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_redshifts.c", "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "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": 38.0315789474, "max_line_length": 147, "alphanum_fraction": 0.7208229541, "num_tokens": 3022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4838375517300927}} {"text": "/* multifit/gsl_multifit.h\n * \n * Copyright (C) 2000, 2007, 2010 Brian Gough\n * Copyright (C) 2013, Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MULTIFIT_H__\n#define __GSL_MULTIFIT_H__\n\n#include \n#include \n#include \n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct \n{\n size_t nmax; /* maximum number of observations */\n size_t pmax; /* maximum number of parameters */\n size_t n; /* number of observations in current SVD decomposition */\n size_t p; /* number of parameters in current SVD decomposition */\n gsl_matrix * A; /* least squares matrix for SVD, n-by-p */\n gsl_matrix * Q;\n gsl_matrix * QSI;\n gsl_vector * S;\n gsl_vector * t;\n gsl_vector * xt;\n gsl_vector * D;\n double rcond; /* reciprocal condition number */\n} \ngsl_multifit_linear_workspace;\n\ngsl_multifit_linear_workspace *\ngsl_multifit_linear_alloc (const size_t n, const size_t p);\n\nvoid\ngsl_multifit_linear_free (gsl_multifit_linear_workspace * w);\n\nint\ngsl_multifit_linear (const gsl_matrix * X,\n const gsl_vector * y,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_tsvd (const gsl_matrix * X,\n const gsl_vector * y,\n const double tol,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n size_t * rank,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_svd (const gsl_matrix * X,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_bsvd (const gsl_matrix * X,\n gsl_multifit_linear_workspace * work);\n\nsize_t\ngsl_multifit_linear_rank(const double tol, const gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_solve (const double lambda,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_vector * c,\n double *rnorm,\n double *snorm,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_applyW(const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * WX,\n gsl_vector * Wy);\n\nint\ngsl_multifit_linear_stdform1 (const gsl_vector * L,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_wstdform1 (const gsl_vector * L,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * tau);\n\nint\ngsl_multifit_linear_stdform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_matrix * M,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_wstdform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_matrix * M,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_genform1 (const gsl_vector * L,\n const gsl_vector * cs,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_genform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * y,\n const gsl_vector * cs,\n const gsl_matrix * M,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_wgenform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n const gsl_vector * cs,\n const gsl_matrix * M,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_lreg (const double smin, const double smax,\n gsl_vector * reg_param);\n\nint\ngsl_multifit_linear_lcurve (const gsl_vector * y,\n gsl_vector * reg_param,\n gsl_vector * rho, gsl_vector * eta,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_lcorner(const gsl_vector *rho,\n const gsl_vector *eta,\n size_t *idx);\n\nint\ngsl_multifit_linear_lcorner2(const gsl_vector *reg_param,\n const gsl_vector *eta,\n size_t *idx);\n\nint\ngsl_multifit_linear_Lk(const size_t p, const size_t k, gsl_matrix *L);\n\nint\ngsl_multifit_linear_Lsobolev(const size_t p, const size_t kmax,\n const gsl_vector *alpha, gsl_matrix *L,\n gsl_multifit_linear_workspace *work);\n\nint\ngsl_multifit_wlinear (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_wlinear_tsvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n const double tol,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n size_t * rank,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_wlinear_svd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, \n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_wlinear_usvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, \n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_est (const gsl_vector * x,\n const gsl_vector * c,\n const gsl_matrix * cov, double *y, double *y_err);\n\ndouble\ngsl_multifit_linear_rcond (const gsl_multifit_linear_workspace * w);\n\nint\ngsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y,\n const gsl_vector *c, gsl_vector *r);\n\n/* gcv.c */\nint\ngsl_multifit_linear_gcv_init(const gsl_vector * y,\n gsl_vector * reg_param,\n gsl_vector * UTy,\n double * delta0,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_gcv_curve(const gsl_vector * reg_param,\n const gsl_vector * UTy,\n const double delta0,\n gsl_vector * G,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_gcv_min(const gsl_vector * reg_param,\n const gsl_vector * UTy,\n const gsl_vector * G,\n const double delta0,\n double * lambda,\n gsl_multifit_linear_workspace * work);\n\ndouble\ngsl_multifit_linear_gcv_calc(const double lambda,\n const gsl_vector * UTy,\n const double delta0,\n gsl_multifit_linear_workspace * work);\n\nint\ngsl_multifit_linear_gcv(const gsl_vector * y,\n gsl_vector * reg_param,\n gsl_vector * G,\n double * lambda,\n double * G_lambda,\n gsl_multifit_linear_workspace * work);\n\ntypedef struct\n{\n const char * name; /* method name */\n int (*wfun)(const gsl_vector *r, gsl_vector *w);\n int (*psi_deriv)(const gsl_vector *r, gsl_vector *dpsi);\n double tuning_default; /* default tuning constant */\n} gsl_multifit_robust_type;\n\ntypedef struct\n{\n double sigma_ols; /* OLS estimate of sigma */\n double sigma_mad; /* MAD estimate of sigma */\n double sigma_rob; /* robust estimate of sigma */\n double sigma; /* final estimate of sigma */\n double Rsq; /* R^2 coefficient of determination */\n double adj_Rsq; /* degree of freedom adjusted R^2 */\n double rmse; /* root mean squared error */\n double sse; /* residual sum of squares */\n size_t dof; /* degrees of freedom */\n size_t numit; /* number of iterations */\n gsl_vector *weights; /* final weights */\n gsl_vector *r; /* final residuals y - X c */\n} gsl_multifit_robust_stats;\n\ntypedef struct\n{\n size_t n; /* number of observations */\n size_t p; /* number of parameters */\n size_t numit; /* number of iterations */\n size_t maxiter; /* maximum iterations */\n const gsl_multifit_robust_type *type;\n double tune; /* tuning parameter */\n\n gsl_vector *r; /* residuals at current iteration */\n gsl_vector *weights; /* weights at current iteration */\n gsl_vector *c_prev; /* coefficients from previous iteration */\n gsl_vector *resfac; /* multiplicative factors for residuals */\n\n gsl_vector *psi; /* psi(r) */\n gsl_vector *dpsi; /* psi'(r) */\n\n gsl_matrix *QSI; /* Q S^{-1} of original matrix X */\n gsl_vector *D; /* balancing parameters of original matrix X */\n\n gsl_vector *workn; /* workspace of length n */\n\n gsl_multifit_robust_stats stats; /* various statistics */\n\n gsl_multifit_linear_workspace *multifit_p;\n} gsl_multifit_robust_workspace;\n\n/* available types */\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_default;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_bisquare;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_cauchy;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_fair;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_huber;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_ols;\nGSL_VAR const gsl_multifit_robust_type * gsl_multifit_robust_welsch;\n\ngsl_multifit_robust_workspace *gsl_multifit_robust_alloc(const gsl_multifit_robust_type *T,\n const size_t n, const size_t p);\nvoid gsl_multifit_robust_free(gsl_multifit_robust_workspace *w);\nint gsl_multifit_robust_tune(const double tune,\n gsl_multifit_robust_workspace *w);\nint gsl_multifit_robust_maxiter(const size_t maxiter,\n gsl_multifit_robust_workspace *w);\nconst char *gsl_multifit_robust_name(const gsl_multifit_robust_workspace *w);\ngsl_multifit_robust_stats gsl_multifit_robust_statistics(const gsl_multifit_robust_workspace *w);\nint gsl_multifit_robust_weights(const gsl_vector *r, gsl_vector *wts,\n gsl_multifit_robust_workspace *w);\nint gsl_multifit_robust(const gsl_matrix * X, const gsl_vector * y,\n gsl_vector * c, gsl_matrix *cov,\n gsl_multifit_robust_workspace *w);\nint gsl_multifit_robust_est(const gsl_vector * x, const gsl_vector * c,\n const gsl_matrix * cov, double *y, double *y_err);\nint gsl_multifit_robust_residuals(const gsl_matrix * X,\n const gsl_vector * y,\n const gsl_vector * c, gsl_vector * r,\n gsl_multifit_robust_workspace * w);\n\n__END_DECLS\n\n#endif /* __GSL_MULTIFIT_H__ */\n", "meta": {"hexsha": "65feec5022b55a16db78592b8fb451b5d2d2ad88", "size": 14549, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multifit.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multifit.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_multifit.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 38.186351706, "max_line_length": 97, "alphanum_fraction": 0.5507595024, "num_tokens": 3087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48353106727368267}} {"text": "//Roots of polynomial using compan matrix, as in Matlab/Octave.\n//This does roots for each vector X.\n//The roots are from an eig using LAPACKE,\n//and are tested to match Octave, except sometimes for sorting order.\n\n//For the complex case with non-contiguous vecs in X and Y,\n//the answers are correct except for a mysterious sign change.\n\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint poly2roots_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim);\nint poly2roots_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim);\nint poly2roots_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim);\nint poly2roots_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim);\n\n\nint poly2roots_s (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim)\n{\n if (dim>3u) { fprintf(stderr,\"error in poly2roots_s: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N==0u || Lx<2u) {}\n else if (Lx==2u)\n {\n if (Lx==N) { *Y = -*(X+1); *++Y = 0.0f; }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, ++X, ++Y) { ++X; *Y = -*X; *++Y = 0.0f; }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B)\n {\n for (size_t b=B; b>0u; --b, ++X, ++Y) { *Y = -*(X+K); *++Y = 0.0f; }\n }\n }\n }\n }\n else\n {\n const size_t Ly = Lx - 1u;\n float x0;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n float *compan, *wr, *wi, zz[1];\n if (!(wr=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in poly2roots_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wi=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,\"error in poly2roots_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(compan=(float *)calloc((size_t)(n*n),sizeof(float)))) { fprintf(stderr,\"error in poly2roots_s: problem with calloc. \"); perror(\"calloc\"); return 1; }\n\n if (Lx==N)\n {\n ++compan;\n for (size_t l=Ly; l>0u; --l, compan+=Lx) { *compan = 1.0f; }\n compan -= Lx*Ly + 1u;\n x0 = -*X++;\n for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_s: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v)\n {\n for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0f; }\n compan -= Lx;\n for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0f; }\n *compan-- = 1.0f;\n x0 = -*X++;\n for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_s: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(Ly-1u))\n {\n for (size_t b=B; b>0u; --b, X-=K*Lx-1u, Y-=2u*K*Ly-2u)\n {\n for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0f; }\n compan -= Lx;\n for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0f; }\n *compan-- = 1.0f;\n x0 = -*X; X += K;\n for (size_t l=Ly; l>0u; --l, X+=K, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_s: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l, Y+=2u*K-1u) { *Y = *wr++; *++Y = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n }\n }\n }\n\n free(compan); free(wr); free(wi);\n }\n\n return 0;\n}\n\n\nint poly2roots_d (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim)\n{\n if (dim>3u) { fprintf(stderr,\"error in poly2roots_d: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N==0u || Lx<2u) {}\n else if (Lx==2u)\n {\n if (Lx==N) { *Y = -*(X+1); *++Y = 0.0; }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, ++X, ++Y) { ++X; *Y = -*X; *++Y = 0.0; }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B)\n {\n for (size_t b=B; b>0u; --b, ++X, ++Y) { *Y = -*(X+K); *++Y = 0.0; }\n }\n }\n }\n }\n else\n {\n const size_t Ly = Lx - 1u;\n double x0;\n\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n double *compan, *wr, *wi, zz[1];\n if (!(wr=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in poly2roots_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(wi=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,\"error in poly2roots_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(compan=(double *)calloc((size_t)(n*n),sizeof(double)))) { fprintf(stderr,\"error in poly2roots_d: problem with calloc. \"); perror(\"calloc\"); return 1; }\n\n if (Lx==N)\n {\n ++compan;\n for (size_t l=Ly; l>0u; --l, compan+=Lx) { *compan = 1.0; }\n compan -= Lx*Ly + 1u;\n x0 = -*X++;\n for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_d: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v)\n {\n for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0; }\n compan -= Lx;\n for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0; }\n *compan-- = 1.0;\n x0 = -*X++;\n for (size_t l=Ly; l>0u; --l, ++X, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_d: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l) { *Y++ = *wr++; *Y++ = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B*(Lx-1u), Y+=2u*B*(Ly-1u))\n {\n for (size_t b=B; b>0u; --b, X-=K*Lx-1u, Y-=2u*K*Ly-2u)\n {\n for (size_t l=Ly*Ly; l>0u; --l, ++compan) { *compan = 0.0; }\n compan -= Lx;\n for (size_t l=Ly; l>2u; --l, compan-=Lx) { *compan = 1.0; }\n *compan-- = 1.0;\n x0 = -*X; X += K;\n for (size_t l=Ly; l>0u; --l, X+=K, compan+=Ly) { *compan = *X / x0; }\n compan -= Ly*Ly;\n info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig\n if (info) { fprintf(stderr,\"error in poly2roots_d: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l, Y+=2u*K-1u) { *Y = *wr++; *++Y = *wi++; }\n wr -= Ly; wi -= Ly;\n }\n }\n }\n }\n\n free(compan); free(wr); free(wi);\n }\n\n return 0;\n}\n\n\nint poly2roots_c (float *Y, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim)\n{\n if (dim>3u) { fprintf(stderr,\"error in poly2roots_c: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N==0u || Lx<2u) {}\n else\n {\n const size_t Ly = Lx - 1u;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n float *compan, zz[2], scr, sci;\n if (!(compan=(float *)calloc((size_t)(4*n*n),sizeof(float)))) { fprintf(stderr,\"error in poly2roots_c: problem with calloc. \"); perror(\"calloc\"); return 1; }\n\n if (Lx==N)\n {\n compan += 2;\n for (size_t l=Ly; l>0u; --l, compan+=2u*Lx) { *compan = 1.0f; }\n compan -= 2u*Lx*Ly + 2u;\n scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2;\n for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)Y,(lapack_complex_float *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_c: lapacke decomposition failed\\n\"); return 1; }\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, Y+=2u*Ly)\n {\n if (Ly>1u)\n {\n for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0f; }\n compan -= 2u*Lx;\n for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0f; }\n *compan = 1.0f; compan -= 2;\n }\n scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2;\n for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)Y,(lapack_complex_float *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_c: lapacke decomposition failed\\n\"); return 1; }\n }\n }\n else\n {\n float *roots;\n if (!(roots=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,\"error in poly2roots_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n \n for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(Ly-1u))\n {\n for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*Ly-2u)\n {\n if (Ly>1u)\n {\n for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0f; }\n compan -= 2u*Lx;\n for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0f; }\n *compan = 1.0f; compan -= 2;\n }\n scr = 1.0f/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2u*K;\n for (size_t l=Ly; l>0u; --l, X+=2u*K, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)roots,(lapack_complex_float *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_c: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l, ++roots, Y+=2u*K-1u) { *Y++ = *roots++; *Y = *roots; }\n roots -= 2u*Ly;\n }\n }\n free(roots);\n }\n }\n free(compan);\n }\n\n return 0;\n}\n\n\nint poly2roots_z (double *Y, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim)\n{\n if (dim>3u) { fprintf(stderr,\"error in poly2roots_z: dim must be in [0 3]\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t Lx = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N==0u || Lx<2u) {}\n else\n {\n const size_t Ly = Lx - 1u;\n const int job = 'E', compz = 'N'; //eigenvalues only\n const lapack_int ldh = (int)Ly, n = (int)Ly, ldz = 1;\n const lapack_int ilo = 1, ihi = n; //avoids balancing\n lapack_int info;\n double *compan, zz[2], scr, sci;\n if (!(compan=(double *)calloc((size_t)(4*n*n),sizeof(double)))) { fprintf(stderr,\"error in poly2roots_z: problem with calloc. \"); perror(\"calloc\"); return 1; }\n\n if (Lx==N)\n {\n compan += 2;\n for (size_t l=Ly; l>0u; --l, compan+=2u*Lx) { *compan = 1.0; }\n compan -= 2u*Lx*Ly + 2u;\n scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2;\n for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)Y,(lapack_complex_double *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_z: lapacke decomposition failed\\n\"); return 1; }\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/Lx, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, Y+=2u*Ly)\n {\n if (Ly>1u)\n {\n for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0; }\n compan -= 2u*Lx;\n for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0; }\n *compan = 1.0; compan -= 2;\n }\n scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2;\n for (size_t l=Ly; l>0u; --l, X+=2, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)Y,(lapack_complex_double *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_z: lapacke decomposition failed\\n\"); return 1; }\n }\n }\n else\n {\n double *roots;\n if (!(roots=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,\"error in poly2roots_z: problem with malloc. \"); perror(\"malloc\"); return 1; }\n \n for (size_t g=G; g>0u; --g, X+=2u*B*(Lx-1u), Y+=2u*B*(Ly-1u))\n {\n for (size_t b=B; b>0u; --b, X-=2u*K*Lx-2u, Y-=2u*K*Ly-2u)\n {\n if (Ly>1u)\n {\n for (size_t l=0u; l<2u*Ly*Ly; ++l, ++compan) { *compan = 0.0; }\n compan -= 2u*Lx;\n for (size_t l=Ly; l>2u; --l, compan-=2u*Lx) { *compan = 1.0; }\n *compan = 1.0; compan -= 2;\n }\n scr = 1.0/(*X**X+*(X+1)**(X+1)); sci = *(X+1)*scr; scr *= -*X;\n X += 2u*K;\n for (size_t l=Ly; l>0u; --l, X+=2u*K, compan+=2u*Ly-1u)\n {\n *compan = *X*scr - *(X+1)*sci;\n *++compan = *X*sci + *(X+1)*scr;\n }\n compan -= 2u*Ly*Ly;\n info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)roots,(lapack_complex_double *)zz,ldz);\n if (info) { fprintf(stderr,\"error in poly2roots_z: lapacke decomposition failed\\n\"); return 1; }\n for (size_t l=Ly; l>0u; --l, ++roots, Y+=2u*K-1u) { *Y++ = *roots++; *Y = *roots; }\n roots -= 2u*Ly;\n }\n }\n free(roots);\n }\n }\n free(compan);\n }\n\n return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "572dba8276291fb9c1efc30465ce9db26c15cd67", "size": 20770, "ext": "c", "lang": "C", "max_stars_repo_path": "c/poly2roots.c", "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_issues_repo_path": "c/poly2roots.c", "max_issues_repo_name": "erikedwards4/dsp", "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "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/poly2roots.c", "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "avg_line_length": 46.0532150776, "max_line_length": 183, "alphanum_fraction": 0.4350987, "num_tokens": 6872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4834921172987905}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName)\n{\n FILE *fp = fopen(input_fileName, \"r\");\n fscanf(fp, \"%*[^\\n]\\n\");\n\n for (int ii = 0; ii < N_kw; ii++)\n fscanf(fp, \"%d,\", &((*index)[ii]));\n fscanf(fp, \"%*[^\\n]\\n\");\n\n int tmp;\n for (int ii = 0; ii < N_kw; ii++)\n {\n for (int jj = 0; jj < N_kw; jj++)\n {\n fscanf(fp, \"%d,\", &tmp);\n (*matrix)[ii*N_kw + jj] = (int) (tmp * scaling);\n }\n fscanf(fp, \"%*[^\\n]\\n\");\n }\n fclose(fp);\n}\n\n\nvoid pad_matrix(int** matrix_padded, int** matrix, double lambda, int N_kw, int N_doc)\n{\n // Initialising RNG\n const gsl_rng_type * T;\n gsl_rng *r1, *r2;\n gsl_rng_env_setup();\n r1 = gsl_rng_alloc(gsl_rng_default);\n r2 = gsl_rng_alloc (gsl_rng_taus);\n\n // perform padding\n int ii, jj;\n\n int max_resp_len = 0;\n for (ii = 0; ii < N_kw; ii++)\n if ((*matrix)[ii*N_kw + ii] > max_resp_len)\n max_resp_len = (*matrix)[ii*N_kw + ii];\n\n #pragma omp parallel for private(ii)\n for (ii = 0; ii < N_kw; ii++)\n (*matrix_padded)[ii*N_kw + ii] = (int) (lambda * (max_resp_len)) + gsl_rng_uniform_int(r2, max_resp_len+1);\n\n #pragma omp parallel for private(ii, jj)\n for (ii = 0; ii < N_kw; ii++)\n {\n for (jj = 0; jj < N_kw; jj++)\n {\n if (ii > jj)\n {\n int n1, n2, n3;\n n3 = 0;\n if ((*matrix_padded)[ii*N_kw + ii] > (*matrix)[ii*N_kw + ii])\n {\n n1 = (*matrix)[ii*N_kw + jj];\n n3 += gsl_ran_hypergeometric(r1, (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + ii], N_doc, (*matrix_padded)[jj*N_kw + jj]);\n }\n else\n n1 = gsl_ran_hypergeometric(r1, (*matrix)[ii*N_kw + jj], (*matrix)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj], (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj]);\n \n if ((*matrix_padded)[jj*N_kw + jj] > (*matrix)[jj*N_kw + jj])\n {\n n2 = n1;\n n3 += gsl_ran_hypergeometric(r1, (*matrix_padded)[jj*N_kw + jj] - (*matrix)[jj*N_kw + jj], N_doc, (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj]);\n }\n else\n n2 = gsl_ran_hypergeometric(r1, n1, (*matrix)[jj*N_kw + jj] - n1, (*matrix_padded)[jj*N_kw + jj]);\n\n (*matrix_padded)[ii*N_kw + jj] = n2 + n3;\n (*matrix_padded)[jj*N_kw + ii] = n2 + n3;\n }\n }\n }\n gsl_rng_free(r1);\n gsl_rng_free(r2);\n}\n \n\n\nvoid observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw)\n{\n // perform observed count generation\n for (int ii = 0; ii < N_kw; ii++)\n for (int jj = 0; jj < N_kw; jj++)\n gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj]));\n}\n\n\nvoid permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, int N_kw, int N_obs)\n{\n int count = 0;\n *idx1 = rand() % N_obs;\n *idx2 = -1;\n int idx_old = (*permutation)[*idx1];\n int idx_new = rand() % N_kw;\n\n (*permutation_tmp)[*idx1] = idx_new;\n if ((*permutation_inv)[idx_new] >= 0)\n {\n *idx2 = (*permutation_inv)[idx_new];\n (*permutation_tmp)[*idx2] = idx_old;\n }\n}\n\n", "meta": {"hexsha": "c51cc4f72e45f9a04a4ff0b9220f83e46857a247", "size": 3614, "ext": "c", "lang": "C", "max_stars_repo_path": "PRT-EMM/util.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "PRT-EMM/util.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "PRT-EMM/util.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.1551724138, "max_line_length": 186, "alphanum_fraction": 0.5182623132, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.48321667980414956}} {"text": "#ifndef SPECTRALFUNCTIONS\n#define SPECTRALFUNCTIONS\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"Constants.h\"\n#include \"NuclearUtilities.h\"\n\nnamespace bsg {\n\n/**\n * Namespace containing all correction factors to the allowed beta spectrum shape\n * as described by Hayen et al., Rev. Mod. Phys. 90 (2018) 015008\n */\nnamespace SpectralFunctions {\n/// type of beta decay, negative or positive\nenum BetaType { BETA_PLUS = -1, BETA_MINUS = 1 };\nenum DecayType { FERMI, GAMOW_TELLER, MIXED };\n\n// the different corrections\ndouble PhaseSpace(double W, double W0, int motherSpinParity,\n int daughterSpinParity);\n/**\n * @brief Fermi function\n * @param W total energy in units of electron mass\n * @param Z the proton number of the daughter\n * @param R the nuclear radius of the daughter\n * @param betaType the BetaType of the transition\n * @return the value\n *\n * The point charge Fermi function @f$ F_0(Z, W) @f$\n * \\f[ F_0(Z,W) = 2(\\gamma+1) \\Gamma(2\\gamma+1)^{-2} (2pR)^{2(\\gamma-1)}\n *e^{\\pi\\alpha Z W /p} |\\Gamma(\\gamma + i \\alpha Z W /p) |^2\\f]\n * the last factor \\f$ |\\Gamma(\\gamma + i \\alpha Z W /p) |^2 \\f$ is calculated\n *using GSL. The GSL function returns the magnitude and phase, and here, as we\n *are interested in the absolute value of the result we just use the\n *magnitude.\n * The calculation of the 2nd factor \\f$ \\Gamma(2\\gamma+1)^{-2} \\f$ and the\n *last factor \\f$ |\\Gamma(\\gamma + i \\alpha Z W /p) |^2 \\f$ is combined, i.e.\n * \\f[ \\ln\\frac{a^2}{b^2} = 2\\ln\\frac{a}{b} = 2(\\ln a - \\ln b) \\f]\n *\n */\ndouble FermiFunction(double W, int Z, double R, int betaType);\n\n/**\n * @brief C correction\n * @param W total energy in units of electron mass\n * @param W0 the total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param betaType the BetaType of the transition\n * @param decayType the DecayType of the transition\n * @param gA the axial vector coupling constant\n * @param gP the induced pseudoscalar coupling constant\n * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$)\n * @param fb the b form factor as per Holstein\n * @param fd the d form factor as per Holstein\n * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism\n * @param addCI boolean to decide whether or not to include the isovector correction to the shape part of C\n * @param NSShape string, says which charge distribution to use in the C correction\n * @param hoFit the fitted A value for the Modified Gaussian distribution\n * @param spsi NuclearStructure::SingleParticleState object denoting the initial nucleon state\n * @param spsf NuclearStructure::SingleParticleState object denoting the final nucleon state\n *\n * The C correction describing effects of finite nuclear size and induced currents when the connection\n to the NME library has been made and actual single-particle wave functions will be used in C_I\n */\ndouble CCorrection(double W, double W0, int Z, int A, double R, int betaType,\n int decayType, double gA, double gP, double fc1, double fb,\n double fd, double ratioM121, bool addCI, std::string NSShape,\n double hoFit, nme::NuclearStructure::SingleParticleState& spsi, nme::NuclearStructure::SingleParticleState& spsf);\n\n/**\n * @brief C correction\n * @param W total energy in units of electron mass\n * @param W0 the total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param betaType the BetaType of the transition\n * @param decayType the DecayType of the transition\n * @param gA the axial vector coupling constant\n * @param gP the induced pseudoscalar coupling constant\n * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$)\n * @param fb the b form factor as per Holstein\n * @param fd the d form factor as per Holstein\n * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism\n * @param addCI boolean to decide whether or not to include the isovector correction to the shape part of C\n * @param NSShape string, says which charge distribution to use in the C correction\n * @param hoFit the fitted A value for the Modified Gaussian distribution\n *\n * The C correction describing effects of finite nuclear size and induced currents.\n */\ndouble CCorrection(double W, double W0, int Z, int A, double R, int betaType,\n int decayType, double gA, double gP, double fc1, double fb,\n double fd, double ratioM121, bool addCI, std::string NSShape,\n double hoFit);\n/**\n * @brief C correction\n * @param W total energy in units of electron mass\n * @param W0 the total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param betaType the BetaType of the transition\n * @param hoFit the fitted A value for the Modified Gaussian distribution\n * @param decayType the DecayType of the transition\n * @param gA the axial vector coupling constant\n * @param gP the induced pseudoscalar coupling constant\n * @param fc1 the c1 form factor as per Holstein (@f$ g_A M_{GT} @f$)\n * @param fb the b form factor as per Holstein\n * @param fd the d form factor as per Holstein\n * @param ratioM121 the ratio of the @f$^AM_{121}@f$ and @f$ ^AM_{101}@f$ matrix elements in the Behrens-Buehring formalism\n * @param NSShape string, says which charge distribution to use in the C correction\n * @param hoFit the fitted A value for the Modified Gaussian distribution\n * @return the value\n *\n * The C correction describing effects of finite nuclear size and induced currents.\n Return the shape and nuclear-sensitive parts separately in a tuple.\n */\nstd::tuple CCorrectionComponents(double W, double W0, int Z, int A, double R, int betaType,\n int decayType, double gA, double gP, double fc1, double fb, double fd, double ratioM121,\n std::string NSShape, double hoFit);\n\n/**\n * Isovector correction to the charge density-calculated C correction\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param betaType BetaType of the transition\n * @param decayType DecayType of the transition\n */\ndouble CICorrection(double W, double W0, int Z, int A, double R, int betaType);\n\n/**\n * Isovector correction to the charge density-calculated C correction\n * Gets called when connection with NME is turned on, thereby using actual\n * single particle wave functions from a (deformed) Woods-Saxon potential\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy i units of the electron rest mass\n * @param Z proton number\n * @param R nuclear radius in natural units\n * @betaType beta type of the transition\n * @param spsi NuclearStructure::SingleParticleState object denoting the initial state\n * @param spsf NuclearStructure::SingleParticleState object denoting the final state\n */\ndouble CICorrection(double W, double W0, double Z, double R, int betaType,\n nme::NuclearStructure::SingleParticleState& spsi, nme::NuclearStructure::SingleParticleState& spsf);\n\n/**\n * Relativistic matrix element correction to the vector pahe \"black hole girl\" right now, and how she's being given too much credit for her role in the historic first image of a black hole. Because this is too important, I want to set the record straight.\n\nOnce Katie Bouman became the \"face\" of the black hole photo, and articles began to call her \"the woman behind the black hole photo\", an assortment of people that I'm strongly inclined to callrt of the C correction\n * as per Wilkinson.\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param betaType BetaType of the transition\n * @param decayType DecayType of the transition\n */\ndouble RelativisticCorrection(double W, double W0, int Z, int A, double R,\n int betaType, int decayType);\n\n/**\n * Deformation correction to L0\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param R nuclear radius in natural units\n * @param beta2 quadrupole deformation\n * @param betaType BetaType of the transition\n * @param aPos array of fitted constants for beta+ decay\n * @param aNeg array of fitted constants for beta- decay\n */\ndouble DeformationCorrection(double W, double W0, int Z, double R, double beta2,\n int betaType, double aPos[], double aNeg[]);\n\n/**\n * Electrostatic finite size correction to the point charge Fermi function\n * written as @f$L_0(Z, W) @f$\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param r radius in natural units\n * @param betaType BetaType of the transition\n * @param aPos array of fitted constants for beta+ decay\n * @param aNeg array of fitted constants for beta- decay\n */\ndouble L0Correction(double W, int Z, double r, int betaType, double aPos[],\n double aNeg[]);\n\n/**\n * Correction to L0 by moving from a uniformly charged sphere to a more elaborate nuclear shape\n *\n * @param W electron total energy in units of its rest mass\n * @param Z proton number\n * @param R nuclear radius in natural units\n * @param betaType BetaType of the transition\n * @param ESShape string denoting the name of the base shape. Currently only Fermi is implemented\n * @param v vector representing the first 3 terms in an even-r power expansion of the base shape\n * @param vp vector representing the first 3 terms in an even-r power expansion of the new shape\n */\ndouble UCorrection(double W, int Z, double R, int betaType, std::string ESShape, std::vector& v, std::vector& vp);\n\n/**\n * Correction to L0 by calculating @f$ \\frac{L_0'}{L_0} @f$ using a power expansion of the potentials\n *\n * @param W electron total energy in units of its rest mass\n * @param Z proton number\n * @param R nuclear radius in natural units\n * @param betaType BetaType of the transition\n * @param v vector representing the first 3 terms in an even-r power expansion of the base shape\n * @param vp vector representing the first 3 terms in an even-r power expansion of the new shape\n * @see UCorrection\n */\ndouble UCorrection(double W, int Z, double R, int betaType, std::vector& v, std::vector& vp);\n\n/**\n * Electromagnetic correction to the Fermi function due to the change in the\n * electromagnetic field of the recoiling nucleus compared to it standing still\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param betaType BetaType of the transition\n * @param decayType decsay type of the transition\n * @double mixingRatio mixing ratio of Fermi versus Gamow-Teller\n */\ndouble QCorrection(double W, double W0, int Z, int A, int betaType,\n int decayType, double mixingRatio);\n\n/**\n * The radiative correction up to order @f$ \\alpha^3Z^2 @f$ as per Sirlin\n *\n * @param W total electron energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param R nuclear radius in natural units\n * @param betaType BetaType of the transition\n * @param gA axial vector coupling constant @f$ g_A @f$\n * @param gM nucleon isovector moment @f$ g_M = 4.706 @f$\n *\n * The first order correction is \\f$ \\delta_1=\\frac{\\alpha}{2\\pi}g(W_0,W) \\f$,\n *where \\f$ g \\f$ is defined by Sirlin (1967).\n * \\f{eqnarray*} g(W_0,W) = & 3 \\ln{\\frac{m_p}{m_e}} - \\frac{3}{4} +\n *\\frac{4}{\\beta}\\rm{Spence}{\\frac{2\\beta}{1+\\beta}} + 4 \\left(\n *\\frac{\\tanh^{-1}{\\beta}}{\\beta}-1 \\right) \\\\\n * & \\times \\left[ \\frac{W_0-W}{3W} - \\frac{3}{2} + \\ln{2(W_0-W)} \\right] \\\\\n * & + \\frac{\\tanh^{-1}{\\beta}}{\\beta} \\left[ 2(1+\\beta^2) +\n *\\frac{(W_0-W)^2}{6W^2} -4\\tanh^{-1}{\\beta}\\right]\n * \\f}\n *\n * where \\f$ \\tanh^{-1} \\f$ is the inverse hyperbolic tangent function, \\f$\n *\\beta = \\sqrt{W^2-1} \\f$ and the Spence function is defined elsewhere.\n * @see Spence()\n */\ndouble RadiativeCorrection(double W, double W0, int Z, double R, int betaType,\n double gA, double gM);\n\n/**\n * Radiative correction to the neutrino spectrum by Sirlin and Marciano\n *\n * @param Wv neutrino total energy in units of the electron rest mass\n */\ndouble NeutrinoRadiativeCorrection(double Wv);\n\n/**\n * Kinematic recoil correction to the beta spectrum due to the enlargement of the phase space\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param A mass number\n * @param decayType decsay type of the transition\n * @double mixingRatio mixing ratio of Fermi versus Gamow-Teller\n */\ndouble RecoilCorrection(double W, double W0, int A, int decayType,\n double mixingRatio);\n\n/**\n * Correction due to atomic screening calculated using the Salvat potential\n *\n * @param W electron total energy in units of its rest mass\n * @param Z proton number\n * @param betaType the BetaType of the transition\n */\ndouble AtomicScreeningCorrection(double W, int Z, int betaType);\n\n/**\n * The atomic exchange correction where an electron decays into a bound state of the daughter atom\n * and its corresponding interference with the direct process\n *\n * @param W electron total energy in units of its rest mass\n * @param exPars array containing the 9 fit parameters required for the analytical parametrisation\n */\ndouble AtomicExchangeCorrection(double W, double exPars[9]);\n\n/**\n * Correction due to the mismatch between initial and final atomic states, causing the\n * endpoint of the transition to get smaller\n *\n * @param W electron total energy in units of its rest mass\n * @param W0 total endpoint energy in units of the electron rest mass\n * @param Z proton number\n * @param A mass number\n * @param betaType BetaType of the transition\n */\ndouble AtomicMismatchCorrection(double W, double W0, int Z, int A,\n int betaType);\n\n/**\n * @brief Spence function\n * @param x\n * @return -gs_sf_dilog(x)\n *\n * The Spence function is included here because the Wilkinson article refers\n *to it. It's value is actually equal (with a sign change) to the DiLogarithm,\n *which is used from GSL.\n * \\f[ \\rm{Spence} = \\int_0^x\\frac{\\ln{(1-t)}}{t}\\mathrm{d}t \\equiv -\n *\\sum_{k=1}^{k=\\infty}\\frac{x^k}{k^2} \\equiv -\\mathrm{Li}_2(x) \\f]\n */\ndouble Spence(double x);\n}\n}\n\n#endif // SPECTRALFUNCTIONS\n", "meta": {"hexsha": "772f9387dcacd0e346a28cc4dd135465d03f2bdd", "size": 15207, "ext": "h", "lang": "C", "max_stars_repo_path": "source/bsg/include/SpectralFunctions.h", "max_stars_repo_name": "MorisRand/BSG", "max_stars_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-02T02:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T09:54:30.000Z", "max_issues_repo_path": "source/bsg/include/SpectralFunctions.h", "max_issues_repo_name": "MorisRand/BSG", "max_issues_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T09:07:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-07T16:49:10.000Z", "max_forks_repo_path": "source/bsg/include/SpectralFunctions.h", "max_forks_repo_name": "MorisRand/BSG", "max_forks_repo_head_hexsha": "d02d9c6b6bb5dddffbf55bfa5762cda0ec97ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T16:49:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T00:55:59.000Z", "avg_line_length": 44.4649122807, "max_line_length": 255, "alphanum_fraction": 0.7169724469, "num_tokens": 3973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.48293719894450593}} {"text": "/* specfunc/bessel_Kn.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"bessel.h\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* [Abramowitz+Stegun, 9.6.11]\n * assumes n >= 1\n */\nstatic\nint\nbessel_Kn_scaled_small_x(const int n, const double x, gsl_sf_result * result)\n{\n int k;\n double y = 0.25 * x * x;\n double ln_x_2 = log(0.5*x);\n double ex = exp(x);\n gsl_sf_result ln_nm1_fact;\n double k_term;\n double term1, sum1, ln_pre1;\n double term2, sum2, pre2;\n\n gsl_sf_lnfact_e((unsigned int)(n-1), &ln_nm1_fact);\n\n ln_pre1 = -n*ln_x_2 + ln_nm1_fact.val;\n if(ln_pre1 > GSL_LOG_DBL_MAX - 3.0) GSL_ERROR (\"error\", GSL_EOVRFLW);\n\n sum1 = 1.0;\n k_term = 1.0;\n for(k=1; k<=n-1; k++) {\n k_term *= -y/(k * (n-k));\n sum1 += k_term;\n }\n term1 = 0.5 * exp(ln_pre1) * sum1;\n\n pre2 = 0.5 * exp(n*ln_x_2);\n if(pre2 > 0.0) {\n const int KMAX = 20;\n gsl_sf_result psi_n;\n gsl_sf_result npk_fact;\n double yk = 1.0;\n double k_fact = 1.0;\n double psi_kp1 = -M_EULER;\n double psi_npkp1;\n gsl_sf_psi_int_e(n, &psi_n);\n gsl_sf_fact_e((unsigned int)n, &npk_fact);\n psi_npkp1 = psi_n.val + 1.0/n;\n sum2 = (psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/npk_fact.val;\n for(k=1; kval = ex * (term1 + term2);\n result->err = ex * GSL_DBL_EPSILON * (fabs(ln_pre1)*fabs(term1) + fabs(term2));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result)\n{\n n = abs(n); /* K(-n, z) = K(n, z) */\n\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n return gsl_sf_bessel_K0_scaled_e(x, result);\n }\n else if(n == 1) {\n return gsl_sf_bessel_K1_scaled_e(x, result);\n }\n else if(x <= 5.0) {\n return bessel_Kn_scaled_small_x(n, x, result);\n }\n else if(GSL_ROOT3_DBL_EPSILON * x > 0.25 * (n*n + 1)) {\n return gsl_sf_bessel_Knu_scaled_asympx_e((double)n, x, result);\n }\n else if(GSL_MIN(0.29/(n*n), 0.5/(n*n + x*x)) < GSL_ROOT3_DBL_EPSILON) {\n return gsl_sf_bessel_Knu_scaled_asymp_unif_e((double)n, x, result);\n }\n else {\n /* Upward recurrence. [Gradshteyn + Ryzhik, 8.471.1] */\n double two_over_x = 2.0/x;\n gsl_sf_result r_b_jm1;\n gsl_sf_result r_b_j;\n int stat_0 = gsl_sf_bessel_K0_scaled_e(x, &r_b_jm1);\n int stat_1 = gsl_sf_bessel_K1_scaled_e(x, &r_b_j);\n double b_jm1 = r_b_jm1.val;\n double b_j = r_b_j.val;\n double b_jp1;\n int j;\n\n for(j=1; jval = b_j;\n result->err = n * (fabs(b_j) * (fabs(r_b_jm1.err/r_b_jm1.val) + fabs(r_b_j.err/r_b_j.val)));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n return GSL_ERROR_SELECT_2(stat_0, stat_1);\n }\n}\n\n\nint gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result)\n{\n const int status = gsl_sf_bessel_Kn_scaled_e(n, x, result);\n const double ex = exp(-x);\n result->val *= ex;\n result->err *= ex;\n result->err += x * GSL_DBL_EPSILON * fabs(result->val);\n return status;\n}\n\n\nint gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array)\n{\n /* CHECK_POINTER(result_array) */\n\n if(nmin < 0 || nmax < nmin || x <= 0.0) {\n int j;\n for(j=0; j<=nmax-nmin; j++) result_array[j] = 0.0;\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(nmax == 0) {\n gsl_sf_result b;\n int stat = gsl_sf_bessel_K0_scaled_e(x, &b);\n result_array[0] = b.val;\n return stat;\n }\n else {\n double two_over_x = 2.0/x;\n gsl_sf_result r_Knm1;\n gsl_sf_result r_Kn;\n int stat_0 = gsl_sf_bessel_Kn_scaled_e(nmin, x, &r_Knm1);\n int stat_1 = gsl_sf_bessel_Kn_scaled_e(nmin+1, x, &r_Kn);\n int stat = GSL_ERROR_SELECT_2(stat_0, stat_1);\n double Knp1;\n double Kn = r_Kn.val;\n double Knm1 = r_Knm1.val;\n int n;\n\n for(n=nmin+1; n<=nmax+1; n++) {\n if(Knm1 < GSL_DBL_MAX) {\n result_array[n-1-nmin] = Knm1;\n Knp1 = Knm1 + n * two_over_x * Kn;\n Knm1 = Kn;\n Kn = Knp1;\n }\n else {\n /* Overflow. Set the rest of the elements to\n * zero and bug out.\n * FIXME: Note: this relies on the convention\n * that the test x < DBL_MIN fails for x not\n * a number. This may be only an IEEE convention,\n * so the portability is unclear.\n */\n int j;\n for(j=n; j<=nmax+1; j++) result_array[j-1-nmin] = 0.0;\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n }\n\n return stat;\n }\n}\n\n\nint\ngsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array)\n{\n int status = gsl_sf_bessel_Kn_scaled_array(nmin, nmax, x, result_array);\n double ex = exp(-x);\n int i;\n for(i=0; i<=nmax-nmin; i++) result_array[i] *= ex;\n return status;\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_Kn_scaled(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Kn_scaled_e(n, x, &result));\n}\n\ndouble gsl_sf_bessel_Kn(const int n, const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_Kn_e(n, x, &result));\n}\n", "meta": {"hexsha": "2ccf460d11a5635dd951bdfa2e67347311d51676", "size": 6590, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_Kn.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Kn.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_Kn.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": 27.3443983402, "max_line_length": 104, "alphanum_fraction": 0.6182094082, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.48282627390846033}} {"text": "/**\n * @file iftCommon.h\n * @brief Common definitions and functions to remaining modules.\n */\n\n#ifndef IFT_COMMON_H\n#define IFT_COMMON_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __linux\n#include \n#include \n#endif\n\n\n#if !defined(__APPLE__)\n #include \n#endif\n#if defined(__linux)\n#endif\n\n#include \"iftBasicDataTypes.h\"\n#include \"iftMemory.h\"\n#include \"iftDialog.h\"\n#include \"iftString.h\"\n\n/**\n * Common definitions\n */\n\n#ifndef PI\n#define PI IFT_PI\n#endif\n\ntypedef enum ift_axis_order {\n XYZ, XZY, YXZ, YZX, ZXY, ZYX\n} iftAxisOrder;\n\n#define IFT_RANDOM_SEED (unsigned int) 213344\n#define IFT_MAXWEIGHT 4095.0\n#define IFT_AXIS_X 0\n#define IFT_AXIS_Y 1\n#define IFT_AXIS_Z 2\n#define IFT_PI 3.14159265358979323846\n#define IFT_INTERIOR 0\n#define IFT_EXTERIOR 1\n#define IFT_BOTH 2\n#define IFT_WHITE 0\n#define IFT_GRAY 1\n#define IFT_BLACK 2\n#define IFT_NIL -1\n#define IFT_INCREASING 1\n#define IFT_DECREASING 0\n#define IFT_EPSILON 1E-07\n\n#ifndef FALSE\n#define FALSE 0\n#endif\n#ifndef TRUE\n#define TRUE 1\n#endif\n\n\n/**\n * Common operations\n */\n\n#ifndef iftMax\n#define iftMax(x,y) (((x) > (y))?(x):(y))\n#endif\n\n#ifndef iftMin\n#define iftMin(x,y) (((x) < (y))?(x):(y))\n#endif\n\n#define iftRound(x) ((x < 0)?(int)(x-0.5):(int)(x+0.5))\n#define iftSign(x) ((x >= 0)?1:-1)\n\n/** @brief Euclidean Distance between voxels or points */\n#define iftPointDistance(u,v) (sqrtf((u.x-v.x)*(u.x-v.x)+(u.y-v.y)*(u.y-v.y)+(u.z-v.z)*(u.z-v.z)))\n\n/** @brief Euclidean Distance between voxels or porints */\n#define iftVoxelDistance(u,v) iftPointDistance(u,v)\n\n/** @brief Computes the Squared Distance between two voxels or points */\n#define iftSquaredVoxelDistance(u,v) ((u.x-v.x)*(u.x-v.x)+(u.y-v.y)*(u.y-v.y)+(u.z-v.z)*(u.z-v.z))\n\n/* @brief Computes the Smooth Euclidean Distances from a pre-computed Squared Euclidean distance among 26-neighbors\n * @param squared_dist The pre-computed Squared Euclidean Distance among 26-neighbors. The details are in N. Kiryati and G. Sze kely, \"Estimating shortest paths and minimal distances on digitized three-dimensional surfaces,\" Pattern Recognition, vol. 26, pp. 1623-1637, 1993.\n * @return The resulting Smooth Euclidean Distance\n */\n#define iftSmoothEuclideanDistance(squared_dist) ((fabs(squared_dist-1)<1.0e-6)? 0.9016 : (fabs(squared_dist-2)<1.0e-6)? 1.289 : 1.615 )\n\n/**\n * @brief Converts a Point to a Voxel\n * @author Samuel\n * @date May 24, 2016\n */\n#define iftPointToVoxel(point) ((iftVoxel) {(int) (point).x, (int) (point).y, (int) (point).z})\n\n/**\n * @brief Converts a Voxel to a Point\n * @author Samuel\n * @date May 24, 2016\n */\n#define iftVoxelToPoint(v) ((iftPoint) {(v).x, (v).y, (v).z})\n\n#define iftImageCenter(img) ((iftVoxel){((img)->xsize - 1)/2, ((img)->ysize - 1)/2, ((img)->zsize - 1)/2})\n\n\n/** @brief Constant used to align memory */\n#define IFT_MEMORY_ALIGNMENT 16\n\n/**\n * @brief Init the GPU devices.\n * @warning If not called, the GPU devices will be started in the first call for a GPU function.\n * @author Peixinho\n */\nvoid iftStartGPU();\n\n/**\n * @brief Stop the GPU devices.\n * @author Peixinho\n */\nvoid iftStopGPU();\n\n/**\n * @brief Checks if the long positive number is prime or not.\n * @author Samuel Martins\n * @date Jan 17th, 2016\n * @note Based on https://en.wikipedia.org/wiki/Primality_test\n */\nbool iftIsPrime(long n);\n\n/**\n * @brief Computes a fast power for small integer exponents.\n * @param base\n * @param b\n * @return Returns base^b\n * @author Peixinho\n * @date May, 2016\n * @warning The funcion is faster upto b=10, after that the regular function pow is called.\n */\ndouble iftFastPow(double base, unsigned b);\n\n/**\n * @brief Prints a Float array on stdout of lentgh .\n */\nvoid iftPrintFloatArray(float* v, int n);\n\n/**\n * @brief Prints a Double array on stdout of lentgh .\n */\nvoid iftPrintDoubleArray(double* v, int n);\n\n/**\n * @brief Prints an Integer array on stdout of lentgh .\n */\nvoid iftPrintIntArray(int* v, int n);\n\n/**\n * @brief Returns a random integer number between low and high.\n */\nint iftRandomInteger (int low, int high);\n\n/**\n * @brief Randomly selects nelems of the set [low, high]\n */\nint *iftRandomIntegers (int low, int high, int nelems);\n\n/**\n * @brief Randomly selects a normal distributed (N(0,1)) float number\n */\nfloat iftRandomNormalFloat(void);\n\n/**\n * @brief Returns initial time\n */\ntimer *iftTic(void);\n\n/**\n * @brief Returns final time\n */\ntimer *iftToc(void);\n\n/**\n * @brief Prints the computational time from tstart to tend, as obtained by iftTic() and iftToc() functions.\n */\nvoid iftPrintCompTime(timer *tstart, timer *tend, const char *msg, ...);\n\n/**\n * @brief Computes the difference in ms from the initial time to the final time.\n *\n * @param tic The initial time.\n * @param toc The final time.\n *\n * @return The computed time difference in milliseconds.\n *\n * @warning The memory allocated for and is freed inside this function.\n */\nfloat iftCompTime(timer *tic, timer *toc);\n\n\n/**\n * @brief Returns a string with the formatted time: days hours mins secs ms.\n *\n * @author Samuel\n *\n * Given a time in ms, this function returns a formatted time: days hours mins secs ms.\n * The runtime in MILISECONDS can be obtained with the function iftCompTime(timer *tic, timer *toc).\n *\n * @param runtime Time in ms.\n * @return The formatted time.\n */\nchar *iftFormattedTime(float runtime);\n\n\n/**\n * @brief Prints the runtime in the following format: days hours mins secs ms.\n *\n * @author Samuel Martins\n * @date October 23, 2015\n * @sa iftFormattedTime()\n *\n * Given a time in ms, this function prints the runtime following the format: days hours mins secs ms.\n * The runtime in MILISECONDS can be obtained with the function iftCompTime(timer *tic, timer *toc).\n *\n * @param runtime Time in ms.\n */\nvoid iftPrintFormattedTime(float runtime);\n\n\n/**\n * @brief Writes a timer to a given file, using the following format %s: %f, where %s is the\n * given information corresponding to the time and %f is the current time in milliseconds.\n *\n * @param tic is freed by the function.\n */\nvoid iftWriteTimerToFile(const char *filename, const char *information, timer *tic);\n\n/**\n * @brief Generates seed for rand(), used in iftRandomInteger.\n */\nvoid iftRandomSeed(unsigned int);\n\n/**\n * @brief Returns the factorial of a number or NIL in case of overflow\n */\nlong double iftFactorial(int n);\n\n/**\n * @brief Returns the limit to avoid overflow in factorial computation\n */\nint iftFactorialLimit(void);\n\n\nvoid iftUnitNorm(float *feats, int nelems);\nvoid iftNormalizeFeatures(float *feats, int nelems);\n\nfloat iftSquaredFeatDistance(float *A, float *B, int n);\nfloat iftFeatDistance(float *A, float *B, int n);\n\n/**\n * @brief Computes the Manhattan Distance between two arrays of float considering the sinal, ie.,\n * wihout the module between the feature difference: dist = (b[0]-a[0]) + (b[1]-a[1]) + ...\n */\nfloat iftSignedManhattanDistance(float *A, float *B, int n);\n\n/**\n * @brief Computes the log(val) in the specified base.\n * @author Peixinho\n */\ndouble iftLog(double val, double base);\n\n\n/**\n * @brief Returns the Central Voxel from the Bounding Box\n * @author Samuel Martins\n * @date Mar 15, 2016\n * @ingroup Geometry\n */\niftVoxel iftCenterFromBoundingBox(iftBoundingBox bb);\n\n\n/**\n * @brief Vector operations defined as macros so that iftVoxels, iftVectors, and iftPoints may be used interchangeably.\n */\n/**\n * @brief Subtracts point vec1 from vec2 (it works for iftVectors/iftVoxels/iftPoints).\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorSub(vec1, vec2) {(vec1).x - (vec2).x, (vec1).y - (vec2).y, (vec1).z - (vec2).z}\n/**\n * @brief Adds points vec1 and vec2 (it works for iftVectors/iftVoxels/iftPoints).\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorSum(vec1, vec2) {(vec1).x + (vec2).x, (vec1).y + (vec2).y, (vec1).z + (vec2).z}\n/**\n * @brief Computes the cross product between two voxels, points, or vectors.\n *\n * @author Thiago Vallin Spina (changed the macro function's name)\n * @date Mar 04, 2016\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorCrossProd(a, b) {(a).y*(b).z - (a).z*(b).y, (a).z*(b).x - (a).x*(b).z, (a).x*(b).y - (a).y*(b).x}\n/**\n * @brief Computes the inner product between two voxels, points, or vectors.\n *\n * @author Thiago Vallin Spina (changed the macro function's name)\n * @date Mar 04, 2016\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorInnerProduct(a, b) (((a).x*(b).x + (a).y*(b).y + (a).z*(b).z))\n\n/**\n * @brief Computes the Vector Magnitude from a voxel or point\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n */\n#define iftVectorMagnitude(v) (sqrtf(iftVectorInnerProduct((v),(v))))\n\n\n/**\n * @brief Returns the XY angle of a 2D vector\n * @author Peixinho\n * @date April, 2016\n * @ingroup Geometry\n */\n#define iftVectorXYAngle(v) ( (atan2(v.y, v.x)+IFT_PI) * (180.0/IFT_PI) )\n\n/**\n * @brief Rounds a vector to integer coordinates.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorRound(vec1) {iftRound((vec1).x), iftRound((vec1).y), iftRound((vec1).z)}\n/**\n * @brief Multiplies a vector by an scalar.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorScalarProd(vec, s) {(vec).x*(s), (vec).y*(s), (vec).z*(s)}\n/**\n * @brief Adds an scalar to a vector.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\n#define iftVectorScalarSum(vec, s) {(vec).x+(s), (vec).y+(s), (vec).z+(s)}\n/**\n * @brief Divides a vector by an scalar.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @return The vector divided by the scalar, or the vector itself if the scalar is close to 0.0\n *\n * @warning The result must be cast as an iftVoxel, iftVector, or iftPoint.\n */\niftVector iftVectorScalarDiv(iftVector vec, double s);\n/**\n * @brief Verifies if a vector has coordinates (0, 0, 0).\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\n#define iftIsNullVector(vec) (iftAlmostZero((vec).x) && iftAlmostZero((vec).y) && iftAlmostZero((vec).z))\n/**\n * @brief Verifies if three points, voxels, or vectors are collinear.\n *\n * This is achieved by testing if the cross product between the vectors P1->P2 and P1->P3 is Null (0,0,0).\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\n#define iftCollinearPoints(P1, P2, P3) (iftIsNullVector((iftVector)iftVectorCrossProd((iftVector)iftVectorSub((P2), (P1)), (iftVector)iftVectorSub((P3), (P1)))))\n\n/**\n * @brief Tests if two iftVoxels are equal\n *\n * @author Thiago Vallin Spina\n * @date Apr 19, 2016\n *\n * @param u1 The first voxel\n * @param u2 The second voxel\n * @return True if their coordinates are the same\n */\nbool iftVoxelsAreEqual(iftVoxel u1, iftVoxel u2);\n\n/**\n * @brief Computes the mean voxel\n *\n * @author Thiago Vallin Spina\n * @date May 1, 2016\n *\n * @param u1 The first voxel\n * @param u2 The second voxel\n * @return The mean voxel (u1 + u2) / 2\n */\niftVoxel iftMeanVoxel(iftVoxel u1, iftVoxel u2);\n\n/**\n * @brief Tests if two iftPoints/iftVectors are equal\n *\n * @author Thiago Vallin Spina\n * @date Apr 19, 2016\n *\n * @param u1 The first point/vector\n * @param u2 The second point/vector\n * @return True if their coordinates are (almost) the same\n */\n#define iftVectorsAreEqual(u1, u2) (iftAlmostZero((u1).x-(u2).x) && iftAlmostZero((u1).y-(u2).y) && \\\n iftAlmostZero((u1).z-(u2).z))\n\n\n/**\n * @brief Normalizes a vector if its norm is greater than 0.0, otherwise returns the vector itself.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\niftVector iftNormalizeVector(iftVector v);\n\n/**\n * @brief Projects vector U onto vector V.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n *\n * @warning If vector V has norm close to 0.0 the function issues and iftError.\n */\niftVector iftProjectVector(iftVector U, iftVector V);\n\n\n/**\n * @brief Returns the distance between P0 and the line from P1 to P2, whose size is P1P2\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\ndouble iftVoxelLineDist2D(iftVoxel P0, iftVoxel P1, iftVoxel P2, double P1P2);\n\n/**\n * @brief Given the vector from P1 to P0, returns the voxel projected on the line between P1 and P2.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\niftVoxel iftClosestVoxelOnLine2D(iftVoxel P0, iftVoxel P1, iftVoxel P2);\n\n/**\n * @brief Returns the position of P0 with respect to the line from P1 to P2.\n *\n * Negative values indicate left side, 0 indicates on the line,\n * and positive values indicate right side.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n * @ingroup Geometry\n */\nint iftVoxelLinePosition2D(iftVoxel P0, iftVoxel P1, iftVoxel P2);\n\n\n/**\n * @brief Computes the circle's area given a radius.\n *\n * @author Thiago Vallin Spina\n * @date Mar 04, 2016\n *\n * @ingroup Geometry\n */\nstatic inline double iftCircleArea(double r) {\n return (r*r)*IFT_PI;\n}\n\n/* @brief Gets rid of the carriage return and the line feed characteres introduced by DOS systems when reading\n * strings from ASCII files.\n *\n * @author Alexandre Xavier Falcao\n *\n * @param line The string in which all carriage return characters are removed.\n */\nvoid iftRemoveCarriageReturn(char *line);\n\n/**\n * @brief Evaluates the sigmoid function, with x = value.\n *\n * @param alfa Controls the decay of the function.\n * @author Renzo Phellan\n */\nfloat iftSigmoidalValue(float value, float alfa);\n\nvoid iftVerifyToken(FILE *fp, char *token, char *function);\nvoid iftReadIntValue(FILE *fp, int *value, char *token, char *function);\nvoid iftReadIntValues(FILE *fp, int **value, int nvalues, char *token, char *function);\nvoid iftWriteIntValue(FILE *fp, int value, char *token);\nvoid iftWriteIntValues(FILE *fp, int *value, int nvalues, char *token);\nvoid iftReadFloatValue(FILE *fp, float *value, char *token, char *function);\nvoid iftReadFloatValues(FILE *fp, float **value, int nvalues, char *token, char *function);\nvoid iftWriteFloatValue(FILE *fp, float value, char *token);\nvoid iftWriteFloatValues(FILE *fp, float *value, int nvalues, char *token);\nvoid iftReadDoubleValue(FILE *fp, double *value, char *token, char *function);\nvoid iftReadDoubleValues(FILE *fp, double **value, int nvalues, char *token, char *function);\nvoid iftWriteDoubleValue(FILE *fp, double value, char *token);\nvoid iftWriteDoubleValues(FILE *fp, double *value, int nvalues, char *token);\nvoid iftSkipComments(FILE *fp);\n\n\n/* These functions are currently used to communicate with numpy */\nvoid iftWriteRawIntArray(char *filename, int *array, int n);\nint* iftReadRawIntArray(char *filename, int n);\n\n/**\n * @brief Computes the mean value of a float array.\n */\nfloat iftMean(float *x, int n);\n/**\n * @brief Computes the variance of a float array.\n */\nfloat iftVar(float *x, int n);\n/**\n * @brief Computes the covariance of float arrays.\n */\nfloat iftCov(float *x, float *y, int n);\n\n/**\n * @brief Tests if a real (float/double) number is zero. It should be used for comparisons if two floats are equal.\n *\n * @author Thiago Vallin Spina\n */\nint iftAlmostZero(double x);\n/**\n * @brief Computes the mod operation of by . If the mod value is negative, it is placed within [0,n-1].\n */\nint iftSafeMod(int a, int n);\n\n\n/**\n * @brief Gets an Integer Array with the Unique Elements from an Input Array.\n *\n * Ex: Given the array = [1, 2, 3, 4, 4, 3, 2, 1], with size n = 8, the resulting array of unique elements will be:\n * [1, 2, 3, 4]\n *\n * @param array Input Int Array to be scanned.\n * @param n Number of Elements from the Input Int Array.\n * @return An Integer Array with the Unique Elements from array.\n */\niftIntArray *iftIntArrayUnique(const int *array, int n);\n\n\n/**\n * @brief Counts the Number of Unique Elements from an array.\n *\n * @param array Integer Array whose Number of Unique Elements will be counted.\n * @param n Array Size.\n * @return The number of Unique Elements.\n */\nint iftCountUniqueIntElems(const int *array, int n);\n\n\n/**\n * @brief This function finds the most suitable normalization value to be used during image color/feature conversion/normalization.\n *\n * It is afunction of the most common number of bits in imaging sensors. It assumes that these values are in {1, 8, 10,\n * 12, 16, 24, 32} bits per voxel.\n *\n * @author Alexandre Xavier Falcao.\n *\n * @param maxval The maximum value of an image, for instance.\n */\nint iftNormalizationValue(int maxval);\n\n/**\n * @brief Converts a number in radians to degrees.\n *\n * @author Thiago Vallin Spina\n */\nstatic inline double iftDegrees(double rad) {\n return rad * 180.0 / IFT_PI;\n}\n\n/**\n * @brief Converts a number in degrees to radians.\n *\n * @author Thiago Vallin Spina\n */\nstatic inline double iftRadians(double deg) {\n return deg * IFT_PI / 180.0;\n}\n\n/**\n * @brief Converts a negative radian number to positive.\n *\n * @author Thiago Vallin Spina\n */\nstatic inline double iftNegativeToPositiveRadians(double rad) {\n return (rad < 0) ? 2 * IFT_PI + rad : rad;\n}\n\n/**\n * @brief Converts a negative degree number to positive.\n *\n * @author Thiago Vallin Spina\n */\nstatic inline double iftNegativeToPositiveDegrees(double deg) {\n return (deg < 0) ? 360.0+deg : deg;\n}\n\n/**\n * @brief Compute the index of the element in vector x with minimum value\n *\n * @param x Float vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftArgmin(const int *x, int n);\n\n/**\n * @brief Compute the index of the element in vector x with maximum value\n *\n * @param x Float vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftArgmax(const int *x, int n);\n\n/**\n * @brief Compute the index of the element in vector x with minimum value\n *\n * @param x Float vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftFArgmin(const float *x, int n);\n\n/**\n * @brief Compute the index of the element in vector x with maximum value\n *\n * @param x Float vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftFArgmax(const float *x, int n);\n\n/**\n * @brief Compute the index of the element in vector x with minimum value\n *\n * @param x Double vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftDArgmin(const double *x, int n);\n\n/**\n * @brief Compute the index of the element in vector x with maximum value\n *\n * @param x Double vector.\n * @param n Size of the vectors.\n * @return index.\n*/\nint iftDArgmax(const double *x, int n);\n\n\n/**\n * @brief Finds the index of in array and returns it.\n *\n * @author Peixinho\n *\n * @param x Unsorted array of elements.\n * @param n The size of the array.\n * @param elem The elem to be found.\n *\n * @return The element's index in or NIL if not found\n */\nint iftFindIntArrayElementIndex(int *x, int n, int elem);\n\n\n/**\n * @brief Compute the Gaussian Probability Density Function for a set of values.\n * @author Samuel Martins\n * @date May 12, 2016\n *\n * @param vals Array of Values to compute the Gaussian PDF.\n * @param n_vals Number of values.\n * @param mean Mean used to compute the Gaussian PDF.\n * @param stdev Standard Deviation used to compute the Gaussian PDF.\n * @return Array of probabilities, one for each input value.\n */\ndouble *iftGaussPDF(double *vals, size_t n_vals, double mean, double stdev);\n\n\n/**\n * @brief Compute the Cumulative Density of the (Gaussian) PDF (Normal Distribution) in a Random Variable with value x.\n * @author Samuel Martins\n * @date May 12, 2016\n *\n * It gives the Area under the Probability Density Function (Normal Distribution) from minus infinity to x. \\n\n * Then, it also describes the probability that a random variable X takes on a value less than or\n * equal to a number x. \\n\n *\n * @param x Value from the Random Variable to compute the CDF.\n * @param mean Mean used to compute the Gaussian PDF.\n * @param stdev Standard Deviation used to compute the Gaussian PDF.\n * @return The area under the PDF from minus to x.\n */\ndouble iftCDF(double x, double mean, double stdev);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "c3c8ed3a7450801acac310db25c67a87ef2d2b89", "size": 21139, "ext": "h", "lang": "C", "max_stars_repo_path": "include/iftCommon.h", "max_stars_repo_name": "Fabio-Kubo/processamento-imagens", "max_stars_repo_head_hexsha": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/iftCommon.h", "max_issues_repo_name": "Fabio-Kubo/processamento-imagens", "max_issues_repo_head_hexsha": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/iftCommon.h", "max_forks_repo_name": "Fabio-Kubo/processamento-imagens", "max_forks_repo_head_hexsha": "800a5b150c69cc008ecff6528710f1c6abf63b6f", "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.3821243523, "max_line_length": 275, "alphanum_fraction": 0.6921803302, "num_tokens": 6140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.48276100132462796}} {"text": "/*\nCopyright 2010-2011, D. E. Shaw Research.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions, and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions, and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n* Neither the name of D. E. Shaw Research nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#include \n#include \n#include \"random123/philox.h\"\n#include \"random123/threefry.h\"\n#include \"random123/gsl_microrng.h\"\n\n/* Compute pi, using the gsl_ran_flat distribution with\n an underlying threefry4x64 counter-based rng (cbrng).\n We can call cbrng 8 times between calls to cbrng_reset */\n\nGSL_MICRORNG(cbrng, threefry4x64); /* creates gsl_rng_cbrng */\n\n#include \"pi_check.h\"\n\nint main(int argc, char **argv){\n unsigned long hits = 0, tries = 0;\n gsl_rng *r;\n (void)argc; (void)argv; /* unused */\n\n threefry4x64_ctr_t c = {{0}};\n threefry4x64_key_t k = {{0}};\n r = gsl_rng_alloc(gsl_rng_cbrng);\n printf(\"%lu uniforms from %s\\n\", NTRIES, gsl_rng_name(r));\n while (tries < NTRIES) {\n double x, y;\n c.v[0]++; /* increment the counter */\n cbrng_reset(r, c, k); /* reset the rng to the new counter */\n x = gsl_ran_flat (r, -1.0, 1.0);\n y = gsl_ran_flat (r, -1.0, 1.0);\n if( x*x + y*y < 1.0 )\n hits++;\n\t tries++;\n }\n gsl_rng_free (r);\n return pi_check(hits, tries);\n}\n", "meta": {"hexsha": "68478a8edd219c22d8513bbe5910e8d1d1359ef3", "size": 2616, "ext": "c", "lang": "C", "max_stars_repo_path": "random123/examples/pi_gsl.c", "max_stars_repo_name": "kabicm/arbor", "max_stars_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "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": "random123/examples/pi_gsl.c", "max_issues_repo_name": "kabicm/arbor", "max_issues_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "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": "random123/examples/pi_gsl.c", "max_forks_repo_name": "kabicm/arbor", "max_forks_repo_head_hexsha": "cfab5fd6a2e6a211c097659c96dcc098ee806e68", "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": 38.4705882353, "max_line_length": 72, "alphanum_fraction": 0.7182721713, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.48276098524556976}} {"text": "#ifndef UTIL_H\n#define UTIL_H\n\n#define PRECISION 2\n#define MAX_LINE_LENGTH 9046\n#define USE_CBLAS\n#define USE_LAPACK\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef USE_CBLAS\n#include \n#endif\n\n#ifdef USE_LAPACK\n#include \n#endif\n\n/******************************************************************************\n * LOGGING\n ******************************************************************************/\n\n/* DEBUG */\n#ifdef NDEBUG\n#define DEBUG(M, ...)\n#else\n#define DEBUG(M, ...) \\\n fprintf(stderr, \"[DEBUG] %s:%d: \" M \"\\n\", __func__, __LINE__, ##__VA_ARGS__)\n#endif\n\n/* LOG */\n#define LOG_ERROR(M, ...) \\\n fprintf(stderr, \"[ERROR] [%s] \" M \"\\n\", __func__, ##__VA_ARGS__)\n#define LOG_WARN(M, ...) fprintf(stderr, \"[WARN] \" M \"\\n\", ##__VA_ARGS__)\n#define LOG_INFO(M, ...) fprintf(stderr, \"[INFO] \" M \"\\n\", ##__VA_ARGS__)\n\n/* FATAL */\n#define FATAL(M, ...) \\\n fprintf(stderr, \"[FATAL] \" M \"\\n\", ##__VA_ARGS__); \\\n exit(-1);\n\n/* CHECK */\n#define CHECK(A, M, ...) \\\n if (!(A)) { \\\n log_err(M, ##__VA_ARGS__); \\\n goto error; \\\n }\n\n/******************************************************************************\n * DATA\n ******************************************************************************/\n\n#if PRECISION == 1\ntypedef float real_t;\n#elif PRECISION == 2\ntypedef double real_t;\n#else\n#error \"Precision not defined!\"\n#endif\n\nchar *malloc_string(const char *s);\nint dsv_rows(const char *fp);\nint dsv_cols(const char *fp, const char delim);\nchar **dsv_fields(const char *fp, const char delim, int *nb_fields);\nreal_t **dsv_data(const char *fp, const char delim, int *nb_rows, int *nb_cols);\nreal_t **csv_data(const char *fp, int *nb_rows, int *nb_cols);\nint **load_iarrays(const char *csv_path, int *nb_arrays);\nreal_t **load_darrays(const char *csv_path, int *nb_arrays);\nreal_t *load_vector(const char *file_path);\n\n/******************************************************************************\n * MATHS\n ******************************************************************************/\n\n#define UNUSED(expr) \\\n do { \\\n (void)(expr); \\\n } while (0)\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n#define MIN(x, y) ((x) < (y) ? (x) : (y))\n#define MAX(x, y) ((x) > (y) ? (x) : (y))\n#define SIGN(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a))\n\nfloat randf(float a, float b);\nreal_t deg2rad(const real_t d);\nreal_t rad2deg(const real_t r);\nint fltcmp(const real_t x, const real_t y);\nreal_t pythag(const real_t a, const real_t b);\nreal_t lerp(const real_t a, const real_t b, const real_t t);\nvoid lerp3(const real_t *a, const real_t *b, const real_t t, real_t *x);\nreal_t sinc(const real_t x);\n\n/******************************************************************************\n * LINEAR ALGEBRA\n ******************************************************************************/\n\nvoid print_matrix(const char *prefix, const real_t *data, const size_t m,\n const size_t n);\nvoid print_vector(const char *prefix, const real_t *data, const size_t length);\n\nvoid eye(real_t *A, const size_t m, const size_t n);\nvoid ones(real_t *A, const size_t m, const size_t n);\nvoid zeros(real_t *A, const size_t m, const size_t n);\n\nreal_t *mat_new(const size_t m, const size_t n);\nint mat_cmp(const real_t *A, const real_t *B, const size_t m, const size_t n);\nint mat_equals(const real_t *A, const real_t *B, const size_t m, const size_t n,\n const real_t tol);\nint mat_save(const char *save_path, const real_t *A, const int m, const int n);\nreal_t *mat_load(const char *save_path, int *nb_rows, int *nb_cols);\nvoid mat_set(real_t *A, const size_t stride, const size_t i, const size_t j,\n const real_t val);\nreal_t mat_val(const real_t *A, const size_t stride, const size_t i,\n const size_t j);\nvoid mat_copy(const real_t *src, const int m, const int n, real_t *dest);\nvoid mat_block_get(const real_t *A, const size_t stride, const size_t rs,\n const size_t cs, const size_t re, const size_t ce,\n real_t *block);\nvoid mat_block_set(real_t *A, const size_t stride, const size_t rs,\n const size_t cs, const size_t re, const size_t ce,\n const real_t *block);\nvoid mat_diag_get(const real_t *A, const int m, const int n, real_t *d);\nvoid mat_diag_set(real_t *A, const int m, const int n, const real_t *d);\nvoid mat_triu(const real_t *A, const size_t n, real_t *U);\nvoid mat_tril(const real_t *A, const size_t n, real_t *L);\nreal_t mat_trace(const real_t *A, const size_t m, const size_t n);\nvoid mat_transpose(const real_t *A, size_t m, size_t n, real_t *A_t);\nvoid mat_add(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);\nvoid mat_sub(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);\nvoid mat_scale(real_t *A, const size_t m, const size_t n, const real_t scale);\n\nreal_t *vec_new(const size_t length);\nvoid vec_copy(const real_t *src, const size_t length, real_t *dest);\nint vec_equals(const real_t *x, const real_t *y, const size_t length);\nvoid vec_add(const real_t *x, const real_t *y, real_t *z, size_t length);\nvoid vec_sub(const real_t *x, const real_t *y, real_t *z, size_t length);\nvoid vec_scale(real_t *x, const size_t length, const real_t scale);\nreal_t vec_norm(const real_t *x, const size_t length);\n\nvoid dot(const real_t *A, const size_t A_m, const size_t A_n, const real_t *B,\n const size_t B_m, const size_t B_n, real_t *C);\nvoid skew(const real_t x[3], real_t A[3 * 3]);\nvoid fwdsubs(const real_t *L, const real_t *b, real_t *y, const size_t n);\nvoid bwdsubs(const real_t *U, const real_t *y, real_t *x, const size_t n);\nint check_jacobian(const char *jac_name, const real_t *fdiff, const real_t *jac,\n const size_t m, const size_t n, const real_t tol,\n const int print);\n\n#ifdef USE_CBLAS\nvoid cblas_dot(const real_t *A, const size_t A_m, const size_t A_n,\n const real_t *B, const size_t B_m, const size_t B_n, real_t *C);\n#endif\n\n/******************************************************************************\n * SVD\n ******************************************************************************/\n\nint svd(real_t *A, int m, int n, real_t *U, real_t *s, real_t *V_t);\nint svdcomp(real_t *A, int m, int n, real_t *w, real_t *V);\nint pinv(real_t *A, const int m, const int n, real_t *A_inv);\n\n#ifdef USE_LAPACK\n\n#endif\n\n/******************************************************************************\n * CHOL\n ******************************************************************************/\n\nvoid chol(const real_t *A, const size_t n, real_t *L);\nvoid chol_solve(const real_t *A, const real_t *b, real_t *x, const size_t n);\n\n#ifdef USE_LAPACK\nvoid lapack_chol_solve(const real_t *A, const real_t *b, real_t *x,\n const size_t n);\n#endif\n\n/******************************************************************************\n * TIME\n ******************************************************************************/\n\ntypedef uint64_t timestamp_t;\n\nstruct timespec tic();\nfloat toc(struct timespec *tic);\nfloat mtoc(struct timespec *tic);\nfloat time_now();\n\n/******************************************************************************\n * TRANSFORMS\n ******************************************************************************/\n\nvoid tf(const real_t params[7], real_t T[4 * 4]);\nvoid tf_params(const real_t T[4 * 4], real_t params[7]);\nvoid tf_rot_set(real_t T[4 * 4], const real_t C[3 * 3]);\nvoid tf_trans_set(real_t T[4 * 4], const real_t r[3]);\nvoid tf_trans_get(const real_t T[4 * 4], real_t r[3]);\nvoid tf_rot_get(const real_t T[4 * 4], real_t C[3 * 3]);\nvoid tf_quat_get(const real_t T[4 * 4], real_t q[4]);\nvoid tf_inv(const real_t T[4 * 4], real_t T_inv[4 * 4]);\nvoid tf_point(const real_t T[4 * 4], const real_t p[3], real_t retval[3]);\nvoid tf_hpoint(const real_t T[4 * 4], const real_t p[4], real_t retval[4]);\nvoid tf_perturb_rot(real_t T[4 * 4], const real_t step_size, const int i);\nvoid tf_perturb_trans(real_t T[4 * 4], const real_t step_size, const int i);\nvoid rvec2rot(const real_t *rvec, const real_t eps, real_t *R);\nvoid euler321(const real_t euler[3], real_t C[3 * 3]);\nvoid rot2quat(const real_t C[3 * 3], real_t q[4]);\nvoid quat2euler(const real_t q[4], real_t euler[3]);\nvoid quat2rot(const real_t q[4], real_t C[3 * 3]);\nvoid quat_lmul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_rmul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_mul(const real_t p[4], const real_t q[4], real_t r[4]);\nvoid quat_delta(const real_t dalpha[3], real_t dq[4]);\n\n/******************************************************************************\n * IMAGE\n ******************************************************************************/\n\ntypedef struct image_t {\n int width;\n int height;\n uint8_t *data;\n} image_t;\n\nvoid image_init(image_t *img, uint8_t *data, int width, int height);\n\n/******************************************************************************\n * CV\n ******************************************************************************/\n\n/******************************** RADTAN **************************************/\n\nvoid radtan4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);\nvoid radtan4_point_jacobian(const real_t params[4], const real_t p[2],\n real_t J_point[2 * 2]);\nvoid radtan4_params_jacobian(const real_t params[4], const real_t p[2],\n real_t J_param[2 * 4]);\n\n/********************************* EQUI ***************************************/\n\nvoid equi4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);\nvoid equi4_point_jacobian(const real_t params[4], const real_t p[2],\n real_t J_point[2 * 2]);\nvoid equi4_params_jacobian(const real_t params[4], const real_t p[2],\n real_t J_param[2 * 4]);\n\n/******************************** PINHOLE *************************************/\n\nreal_t pinhole_focal(const int image_width, const real_t fov);\nint pinhole_project(const real_t params[4], const real_t p_C[3], real_t x[2]);\n\nvoid pinhole_point_jacobian(const real_t params[4], real_t J_point[2 * 3]);\nvoid pinhole_params_jacobian(const real_t params[4], const real_t x[2],\n real_t J[2 * 4]);\n\n/**************************** PINHOLE-RADTAN4 *********************************/\n\nvoid pinhole_radtan4_project(const real_t params[8], const real_t p_C[3],\n real_t x[2]);\nvoid pinhole_radtan4_project_jacobian(const real_t params[8],\n const real_t p_C[3], real_t J[2 * 3]);\nvoid pinhole_radtan4_params_jacobian(const real_t params[8],\n const real_t p_C[3], real_t J[2 * 8]);\n\n/***************************** PINHOLE-EQUI4 **********************************/\n\nvoid pinhole_equi4_project(const real_t params[8], const real_t p_C[3],\n real_t x[2]);\nvoid pinhole_equi4_project_jacobian(const real_t params[8], const real_t p_C[3],\n real_t J[2 * 3]);\nvoid pinhole_equi4_params_jacobian(const real_t params[8], const real_t p_C[3],\n real_t J[2 * 8]);\n\n#endif // ZERO_H\n", "meta": {"hexsha": "0b7993c7e2f9a76f8394d22e469bcea7e2f4ce42", "size": 11779, "ext": "h", "lang": "C", "max_stars_repo_path": "ba/c/util.h", "max_stars_repo_name": "daoran/ba", "max_stars_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-04-26T02:40:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T10:22:00.000Z", "max_issues_repo_path": "ba/c/util.h", "max_issues_repo_name": "daoran/ba", "max_issues_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ba/c/util.h", "max_forks_repo_name": "daoran/ba", "max_forks_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T07:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T04:22:32.000Z", "avg_line_length": 41.1853146853, "max_line_length": 80, "alphanum_fraction": 0.536038713, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.4823363371992143}} {"text": "/*\n * Copyright 2008-2016 Jan Gasthaus\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** \n * Functions for computing and tabulating the generalized stirling numbers \n * of type (-1,-d,0). \n *\n */\n\n#ifndef STIRLING_H_\n#define STIRLING_H_\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace gatsby { namespace libplump {\n\ntypedef std::vector d_vec;\ntypedef std::vector d_vec_vec;\n\n/**\n * computes log(exp(a) + exp(b)) while avoiding numerical\n * instabilities.\n */\ninline double fast_logsumexp(double a, double b) {\n if (a>b) {\n return log(1+exp(b-a)) + a;\n } else {\n return log(1+exp(a-b)) + b;\n }\n}\n\n/**\n * computes log(exp(a) - exp(b)) while avoiding numerical\n * instabilities.\n */\ninline double fast_logminusexp(double a, double b) {\n if (a>b) {\n return log(1-exp(b-a)) + a;\n } else {\n return log(1-exp(a-b)) + b;\n }\n}\n\n/**\n * Compute S_d(c,t) recursively by directly applying the recursion\n * S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)\n *\n * This does a _lot_ of duplicate work and should only be used for debugging!\n */\ndouble gen_stirling_recursive(double d, int c, int t);\n\n\n/**\n * Compute S_d(c,t) recursively in log space by directly applying the recursion\n * S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)\n *\n * This does a _lot_ of duplicate work and should only be used for debugging!\n */\ndouble log_gen_stirling_recursive(double d, int c, int t);\n\n\n/**\n * Compute S_d(c,t) directly in log space using the recursion\n * S_d(c,t) = S_d(c-1,t-1) + (c-1 - t*d)S_d(c-1,t)\n */\ndouble log_gen_stirling_direct(double d, int c, int t);\n\n\ndouble log_gen_stirling_ratio(double d, int c, int t);\n\n\nd_vec_vec log_gen_stirling_table(double d, int c);\n\n\nvoid log_gen_stirling_table_extend(double d, int c, d_vec_vec& table);\n\n\ndouble log_get_stirling_from_table(d_vec_vec& table, int c, int t);\n\n\nclass stirling_generator_recompute_log {\n public:\n stirling_generator_recompute_log(double d, int c, int t);\n\n double ratio(int c, int t);\n\n static std::string statsToString();\n\n private:\n double d;\n};\n\n\nclass stirling_generator_fast_log {\n\n public:\n stirling_generator_fast_log(double d, int c, int t);\n\n double get(int c, int t);\n\n double ratio(int c, int t);\n\n static std::string statsToString();\n\n private:\n void incC();\n void decC();\n\n double d;\n int current_c;\n d_vec row, col, prev_col;\n};\n\n/**\n * Class to encapsulate the generation of ratios of stirling numbers\n * for removing customers from restaurants.\n * \n * One of these objects should be constructed for each restaurant, \n * providing the current number of tables, and the total number of customers.\n */\nclass stirling_generator_full_log {\n public:\n stirling_generator_full_log(double d, int c, int t);\n\n double ratio(int c, int t);\n \n double getLog(int c, int t);\n\n static std::string statsToString();\n\n private:\n\n static int global_c_max, num_ratio_calls, num_extends, num_construct;\n\n d_vec_vec table;\n int c_max;\n double d;\n};\n\ninline double log_get_stirling_from_table(d_vec_vec& table, int c, int t) {\n // c and t must be non-negative\n assert(c >= 0 && t>= 0);\n\n if ((c == 1 && t == 1) || (c == 0 && t == 0))\n return 0;\n if (c == 0 || t == 0)\n return -INFINITY;\n if (t > c)\n return -INFINITY;\n if(c == t)\n return 0;\n if (t > (int)table.size() || (c - t) > (int)table[t-1].size()) {\n std::cout<< c << \", \" << t << std::endl;\n }\n return table[t-1][c-t-1];\n}\n\n\ninline double log_stirling_asymptotic(double d, int c, int t) {\n return gsl_sf_lngamma(c) \n - gsl_sf_lngamma(1 - d) \n - gsl_sf_lngamma(t)\n - (t-1) * log(d)\n - d * log(c);\n}\n\n// class log_gen_stirling_table {\n// private:\n// std::vector > table;\n// size_t c_cur, t_cur;\n// \n// /*\n// * Grow the arrays to the required size.\n// */\n// void _grow(size_t c_max, size_t t_max) {\n// for(int i=t_cur;i tmp(c_cur,0);\n// table.push_back(std::vector());\n// }\n// }\n// \n// /*\n// * Tabulate up to the specified limits\n// */\n// void _tabulate(size_t c_max, size_t t_max) {\n// for t in xrange(1,max_t):\n// for c in xrange(t,max_c):\n// a[c,t] = a[c-1,t-1] + (c-1-d*t)*a[c-1,t]\n// \n// }\n// \n// public:\n// double d;\n// gen_stirling_table(double d) : d(d), c_cur(0), t_cur(0) {}\n// \n// };\n\n\n\n\n\n\n}} // namespace gatsby::libplump\n\n\n#endif /* STIRLING_H_ */\n", "meta": {"hexsha": "616b2cfcc2314f3ba7a0a87faab731593c08c07f", "size": 5210, "ext": "h", "lang": "C", "max_stars_repo_path": "src/libplump/stirling.h", "max_stars_repo_name": "jgasthaus/libPLUMP", "max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z", "max_issues_repo_path": "src/libplump/stirling.h", "max_issues_repo_name": "jgasthaus/libPLUMP", "max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "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/libplump/stirling.h", "max_forks_repo_name": "jgasthaus/libPLUMP", "max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z", "avg_line_length": 23.1555555556, "max_line_length": 79, "alphanum_fraction": 0.6216890595, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4821161664058099}} {"text": "/**\n *\n * @file core_clarfy.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 Azzam Haidar\n * @date 2011-05-15\n * @generated c Tue Jan 7 11:44:49 2014\n *\n **/\n#include \n#include \n#include \"common.h\"\n\n#undef REAL\n#define COMPLEX\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n * CORE_clarfy applies an elementary reflector, or Householder matrix, H,\n * to a N-by-N hermitian matrix C, from both the left and the right.\n *\n * H is represented in the form\n *\n * H = I - tau * v * v'\n *\n * where tau is a scalar and v is a vector.\n *\n * If tau is zero, then H is taken to be the unit matrix.\n *\n *******************************************************************************\n *\n * @param[in] N\n * The number of rows and columns of the matrix C. N >= 0.\n *\n * @param[in,out] A\n * COMPLEX*16 array, dimension (LDA, N)\n * On entry, the Hermetian matrix A.\n * On exit, A is overwritten by H * A * H'.\n *\n * @param[in] LDA\n * The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[in] V\n * The vector V that contains the Householder reflectors.\n *\n * @param[in] TAU\n * The value tau.\n *\n * @param[out] WORK\n * Workspace.\n *\n ******************************************************************************/\nvoid\nCORE_clarfy(int N,\n PLASMA_Complex32_t *A, int LDA,\n const PLASMA_Complex32_t *V,\n const PLASMA_Complex32_t *TAU,\n PLASMA_Complex32_t *WORK)\n{\n static PLASMA_Complex32_t zzero = 0.0;\n static PLASMA_Complex32_t zmone = -1.0;\n\n int j;\n PLASMA_Complex32_t dtmp;\n\n /* Compute dtmp = X'*V */\n /* X = AVtau */\n cblas_chemv(CblasColMajor, CblasLower,\n N, CBLAS_SADDR(*TAU), A, LDA,\n V, 1, CBLAS_SADDR(zzero), WORK, 1);\n\n /* cblas_cdotc_sub(N, WORK, 1, V, 1, &dtmp);*/\n dtmp = 0.;\n for (j = 0; j < N ; j++)\n dtmp = dtmp + conjf(WORK[j]) * V[j];\n\n /* Compute 1/2 X'*V*t = 1/2*dtmp*tau */\n dtmp = -dtmp * 0.5 * (*TAU);\n\n /* Compute W=X-1/2VX'Vt = X - dtmp*V */\n cblas_caxpy(N, CBLAS_SADDR(dtmp),\n V, 1, WORK, 1);\n\n /*\n * Performs the symmetric rank 2 operation\n * A := alpha*x*y' + alpha*y*x' + A\n */\n cblas_cher2(CblasColMajor, CblasLower, N,\n CBLAS_SADDR(zmone), WORK, 1,\n V, 1,\n A, LDA);\n\n return;\n}\n#undef COMPLEX\n", "meta": {"hexsha": "163fa798388111f620a6074d59f137a221032261", "size": 2702, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_clarfy.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_clarfy.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_clarfy.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": 26.2330097087, "max_line_length": 80, "alphanum_fraction": 0.5025906736, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.48205555738088035}} {"text": "//This takes the output of window_univar, and applies the 1D FFT to each row or col.\n//The input dim is which dim to take the 1D FFT along (0->along cols, 1->along rows).\n//The output Y is power (real-valued), i.e. the FFT squared, Y = X*conj(X) element-wise.\n//The size of Y must be FxC if dim==0, and RxF if dim==1, where F = nfft/2 + 1.\n\n//I tried parallel versions with OpenMP, but much slower (have to make fftw_plan P times!).\n\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint fft_squared_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft);\nint fft_squared_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft);\n\n\nint fft_squared_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int nfft)\n{\n const float z = 0.0f;\n const int F = nfft/2 + 1;\n int r, c, f;\n float *X1, *Y1;\n fftwf_plan plan;\n //struct timespec tic, toc;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in fft_squared_s: R (nrows X) must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in fft_squared_s: C (ncols X) must be positive\\n\"); return 1; }\n if (nfft= R (winlength)\\n\"); return 1; }\n if (nfft= C (winlength)\\n\"); return 1; }\n\n //Initialize fftwf\n X1 = fftwf_alloc_real((size_t)nfft);\n Y1 = fftwf_alloc_real((size_t)nfft);\n plan = fftwf_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);\n if (!plan) { fprintf(stderr,\"error in fft_squared_s: problem creating fftw plan\\n\"); return 1; }\n cblas_scopy(nfft-R,&z,0,&X1[R],1); //zero-pad\n\n if (dim==0u)\n {\n if (iscolmajor)\n {\n //clock_gettime(CLOCK_REALTIME,&tic);\n for (c=0; c= R (winlength)\\n\"); return 1; }\n if (nfft= C (winlength)\\n\"); return 1; }\n\n\n //Initialize fftw\n X1 = fftw_alloc_real((size_t)nfft);\n Y1 = fftw_alloc_real((size_t)nfft);\n plan = fftw_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);\n if (!plan) { fprintf(stderr,\"error in fft_squared_d: problem creating fftw plan\\n\"); return 1; }\n cblas_dcopy(nfft,&z,0,&X1[0],1); //zero-pad\n\n if (dim==0u)\n {\n if (iscolmajor)\n {\n for (c=0; c\n#include \n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint add_delta_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\nint add_delta_deltas_d (double *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\n\n\nint add_delta_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N)\n{\n const float z = 0.0f;\n const int No = R*C/3;\n int r, c, n;\n float sc = 1.0f;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in add_delta_deltas_s: R (nrows X) must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in add_delta_deltas_s: C (ncols X) must be positive\\n\"); return 1; }\n if (N<1) { fprintf(stderr,\"error in add_delta_deltas_s: N (delta winlength) must be positive\\n\"); return 1; }\n if (dim==0 && C%3!=0) { fprintf(stderr,\"error in add_delta_deltas_s: for dim==0, C (ncols X) must be divisible by 3\\n\"); return 1; }\n if (dim==1 && R%3!=0) { fprintf(stderr,\"error in add_delta_deltas_s: for dim==1, R (nrows X) must be divisible by 3\\n\"); return 1; }\n\n //Get sc (normalizer)\n for (n=2; n<=N; n++) { sc += n*n; }\n sc = 0.5f/sc;\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n cblas_scopy(2*No,&z,0,&X[No],1);\n for (c=0; c\n#include \n#include \n#include \n\n\n/*****************************************************************************\n * backward_recurse\n *\n * Purpose:\n ****************************************************************************/\nstatic void backward_recurse_c(double aa, double qq, double xx, double *ff,\n double *gx, int even_odd, int ni)\n{\n int ii, nn;\n double g1;\n\n\n g1 = *gx;\n ff[ni] = xx;\n\n if (even_odd == 0)\n {\n for (ii=0; ii GSL_SF_MATHIEU_COEFF)\n return GSL_FAILURE;\n \n /* Handle the trivial case where q = 0. */\n if (qq == 0.0)\n {\n for (ii=0; ii GSL_SF_MATHIEU_COEFF)\n return GSL_FAILURE;\n \n /* Handle the trivial case where q = 0. */\n if (qq == 0.0)\n {\n for (ii=0; ii\n\n\n\nint main( int argc, char *argv[] )\n{\n\n Vec a,b,c;\n DM packer;\n PetscErrorCode ierr;\n PetscInt i[4] = {0,1,2,3};\n PetscReal v[4] = {1.5,2.5,3.5,4.5};\n PetscReal w[4] = {5.5,6.5,7.5,8.5};\n\n // initialize Petsc ...\n ierr = PetscInitialize(&argc, &argv, NULL, \"\");CHKERRQ(ierr);\n\n ierr= VecCreate(PETSC_COMM_WORLD, &a); CHKERRQ(ierr);\n ierr= VecCreate(PETSC_COMM_WORLD, &b); CHKERRQ(ierr);\n\n ierr= VecSetSizes(a,PETSC_DECIDE,4); CHKERRQ(ierr);\n ierr = VecSetFromOptions(a); CHKERRQ(ierr);\n ierr= VecSetValues(a,4,i,v,INSERT_VALUES);CHKERRQ(ierr);\n ierr= VecAssemblyBegin(a);CHKERRQ(ierr);\n ierr = VecAssemblyEnd(a);CHKERRQ(ierr);\n ierr = VecView(a,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);\n\n ierr= VecSetSizes(b,PETSC_DECIDE,4); CHKERRQ(ierr);\n ierr = VecSetFromOptions(b); CHKERRQ(ierr);\n ierr= VecSetValues(b,4,i,w,INSERT_VALUES);CHKERRQ(ierr);\n ierr= VecAssemblyBegin(b);CHKERRQ(ierr);\n ierr = VecAssemblyEnd(b);CHKERRQ(ierr);\n ierr = VecView(b,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);\n\n\n\n\n ierr = PetscFinalize();exit(ierr);\n\n\n\n\n}", "meta": {"hexsha": "0d87c0476290454ea28b83c7b138f818ffab5d76", "size": 1173, "ext": "c", "lang": "C", "max_stars_repo_path": "test_vec.c", "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "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": "test_vec.c", "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "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": "test_vec.c", "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9574468085, "max_line_length": 65, "alphanum_fraction": 0.6555839727, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4815397372863182}} {"text": "\n/*\n* -----------------------------------------------------------------\n* ODE Solver Library --- ode_lib.c\n* Version: 1.6180\n* Date: Jan 4, 2011\n* ----------------------------------------------------------------- \n* Programmer: Americo Barbosa da Cunha Junior\n* americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n* Copyright (c) 2010 by Americo Barbosa da Cunha Junior\n*\n* This program is free software: you can redistribute it and/or\n* modify it under the terms of the GNU General Public License as\n* published by the Free Software Foundation, either version 3 of\n* the License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* A copy of the GNU General Public License is available in\n* LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n* This is the implementation file of a library\n* with ODE solution tools.\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../include/ode_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n* uround\n*\n* This function computes the machine unit roundoff\n* defined as the smallest u such that 1.0 + u > 1.0\n*\n* Output:\n* uround - machine unit roundoff\n*\n* last update: May 20, 2009\n*------------------------------------------------------------\n*/\n\ndouble uround(void)\n{\n double u = 1.0;\n double comp = 0.0;\n\n while(comp != 1.0)\n {\n\tu *= 0.5;\n\tcomp = 1.0 + u;\n }\n \n return 2.0*u;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* wnorm\n*\n* This function computes v1 and v2 vector weight norm\n* defined as\n* wnorm = sqrt( (1/n)*(sum (v1[i]*v2[i])^2) )\n*\n* Input:\n* n - vectors dimension\n* v - vector 1\n* v - vector 2\n*\n* Output:\n* wnorm - weight norm\n*\n* last update: May 20, 2009\n*------------------------------------------------------------\n*/\n\ndouble wnorm(int n,double *v1,double *v2)\n{\n int i;\n double wnorm = 0.0;\n \n for ( i = 0; i < n; i++ )\n\twnorm += v1[i]*v1[i]*v2[i]*v2[i];\n \n return sqrt( wnorm / (double)n );\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* ewset\n*\n* This function creates a error weight vector\n* defined as ewv[i] = rtol*abs(v[i]) + atol\n*\n* Input:\n* n - vector dimension\n* v - vector\n* atol - absolute tolerance\n* rtol - relative tolerance\n*\n* Output:\n* ewv - error weight vector\n*\n* last update: May 22, 2009\n*------------------------------------------------------------\n*/\n\nvoid ewtset(int n,double *v,double atol,double rtol,double *ewt)\n{\n int i;\n \n for ( i = 0; i < n; i++ )\n ewt[i] = rtol*fabs(v[i]) + atol;\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*------------------------------------------------------------\n* jacobian\n*\n* This function computes the jacobian matrix of ydot = f(y,t)\n* defiend as Jij = dfi/dyj\n*\n* Input:\n* n - vector dimension\n* f_data - pointer to external data\n* Fy - reaction mapping\n* y - composition vector\n* t - time step\n* atol - absolute tolerance\n* rtol - relative tolerance\n*\n* Output:\n* J - jacobian matrix\n* success or error\n*\n* last update: Oct 7, 2009\n------------------------------------------------------------*/\n\nint jacobian(CVRhsFn f,void *f_data,gsl_vector *Fy,gsl_vector *y,\n double t,double atol,double rtol,gsl_matrix *J)\n{\n unsigned int i, j, N1, N2;\n double roundoff, min_inc_mult;\n double fnorm, minInc, inc, inc_inv, yjsaved, srur;\n double *yd_data = NULL;\n double *Fyd_data = NULL;\n N_Vector yd = NULL;\n N_Vector Fyd = NULL;\n gsl_vector *ewt = NULL;\n \n \n min_inc_mult = 1.0e3;\n \n /* vectors dimensions */\n N1 = y->size;\n N2 = Fy->size;\n \n /* error weight vector */\n ewt = gsl_vector_calloc(N1);\n \n /* computing the unit roundoff */\n roundoff = uround();\n \n /* memory allocation and startup of yd and Fyd */\n yd = N_VNew_Serial(N1);\n Fyd = N_VNew_Serial(N2);\n if ( yd == NULL || Fyd == NULL )\n return GSL_ENOMEM;\n \n /* obtaining yd and Fyd compoments */\n yd_data = NV_DATA_S(yd);\n Fyd_data = NV_DATA_S(Fyd);\n \n /* setting yd equal y vector */\n for ( i = 0; i < N1; i++ )\n yd_data[i] = y->data[i];\n \n /* setting Fyd equal the null vector */\n for ( i = 0; i < N2; i++ )\n Fyd_data[i] = 0.0;\n \n /* defing error weight vector */\n ewtset(N1,y->data,atol,rtol,ewt->data);\n \n /* computing weight norm */\n fnorm = wnorm(N2,Fy->data,ewt->data);\n \n /* square root of the machine roundoff */\n srur = sqrt(roundoff);\n \n /* computing disturbance parameter */\n minInc = (fnorm != 0.0) ?\n\t (min_inc_mult*fabs(t)*roundoff*((double)N1)*fnorm) : 1.0;\n \n for ( j = 0; j < N1; j++ )\n {\n /* saving y[j] value */\n yjsaved = yd_data[j];\n \n /* disturbance */\n inc = GSL_MAX(srur*fabs(yjsaved),minInc/ewt->data[j]);\n \t\n \t/* disturbing y */\n yd_data[j] += inc;\n\t\n /* computing Fy disturbed */\n f(t,yd,Fyd,f_data);\n\t\n\t/* restoring yd[j] original value */\n yd_data[j] = yjsaved;\n\t\n\t/* computing the step */\n inc_inv = 1.0/inc;\n \n /* computing jacobian matrix column j */\n \tfor ( i = 0; i < N2; i++ )\n J->data[i*J->tda+j] = inc_inv*(Fyd_data[i] - Fy->data[i]);\n }\n \n /* releasing allocated memory */\n N_VDestroy_Serial(yd);\n N_VDestroy_Serial(Fyd);\n gsl_vector_free(ewt);\n yd = NULL;\n Fyd = NULL;\n yd_data = NULL;\n Fyd_data = NULL;\n ewt = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*------------------------------------------------------------\n* gradient\n*\n* This function computes the gradient matrix of R(phi)\n* defiend as: Aij = d R_i/d phi_j\n*\n* Input:\n* f - right hand side function\n* f_data - pointer to external data\n* t0 - initial time\n* delta_t - time step\n* atol - absolute tolerance\n* rtol - relative tolerance\n* phi - composition vector\n* Rphi - reac tion mapping\n*\n* Output:\n* A - gradient matrix\n* success or error\n*\n* last update: Feb 19, 2010\n------------------------------------------------------------*/\n\nint gradient(CVRhsFn f,void *f_data,void *cvode_mem,double t0,double delta_t,\n double atol,double rtol,gsl_vector *phi,gsl_vector *Rphi,gsl_matrix *A)\n{\n unsigned int i, j, flag;\n double inc, inc_inv, phijsaved, srur;\n gsl_vector *Rphid = NULL;\n \n /* memory allocation for Rphid */\n Rphid = gsl_vector_calloc(Rphi->size);\n \n /* square root of 1.0e6 times the machine roundoff */\n srur = sqrt(1.0e6*DBL_EPSILON);\n \n for ( j = 0; j < phi->size; j++ )\n {\n /* saving phi_j value */\n phijsaved = phi->data[j];\n \n /* disturbance */\n inc = phijsaved*srur + srur;\n \t\n \t/* disturbing phi_j */\n phi->data[j] += inc;\n\t\n /* computing R(phi) disturbed */\n\tflag = odesolver_reinit(f,f_data,t0,atol,rtol,phi,cvode_mem);\n if ( flag != GSL_SUCCESS )\n return flag;\n \n\tflag = odesolver(cvode_mem,delta_t,Rphid);\n if ( flag != GSL_SUCCESS )\n return flag;\n\t\n\t/* restoring phi_j original value */\n phi->data[j] = phijsaved;\n\t\n\t/* computing the step */\n inc_inv = 1.0/inc;\n \n /* computing gradient matrix column j */\n \tfor ( i = 0; i < Rphi->size; i++ )\n A->data[i*A->tda+j] = inc_inv*(Rphid->data[i] - Rphi->data[i]);\n }\n \n \n /* releasing allocated memory */\n gsl_vector_free(Rphid);\n Rphid = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* linear_approx\n*\n* This function computes the linear approximation\n* for a vector function F(x) near the point x0.\n* \n* F(x) = F(x0) + DF(x0)*(x-x0) + O(|x-x0|^2)\n* \n* Input:\n* x - vector x\n* x0 - vector x0\n* Fx0 - function at x0\n* DFx0 - jacobian matrix at x0\n*\n* Output:\n* Fx - linear approximation for F(x)\n*\n* last update: Jun 9, 2009\n*------------------------------------------------------------\n*/\n\nvoid linear_approx(gsl_vector *x,gsl_vector *x0,\n gsl_vector *Fx0,gsl_matrix *DFx0,gsl_vector *Fx)\n{\n gsl_vector *aux = NULL;\n \n /* memory allocation */\n aux = gsl_vector_alloc(x0->size);\n\n /* aux := x */\n gsl_vector_memcpy(aux,x);\n \n /* aux := x - x0 */\n gsl_vector_sub(aux,x0);\n \n /* Fx := F(x0) */\n gsl_vector_memcpy(Fx,Fx0);\n \n /* Fx := F(x0) + DF(x0)*(x-x0) */\n gsl_blas_dgemv(CblasNoTrans,1.0,DFx0,aux,1.0,Fx);\n \n /* releasing allocated memory */\n gsl_vector_free(aux);\n aux = NULL;\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver_init\n*\n* This function initiates the ODE solver workspace.\n*\n* Input:\n* f - right hand side function\n* f_data - right hand side function data\n* t0 - initial time\n* mxsteps - max # of solver iterations\n* atol - absolute tolerance\n* rtol - relative tolerance\n* x - initial condition\n* cvode_mem - ODE solver workspace\n*\n* Output:\n* success or error\n*\n* last update: Jan 4, 2011\n*------------------------------------------------------------\n*/\n\nint odesolver_init(CVRhsFn f,void *f_data,double t0,int mxsteps,\n\t\t double atol,double rtol,gsl_vector *x,void *cvode_mem)\n{\n int maxnef = 100;\n int flag = CV_SUCCESS;\n N_Vector y0 = NULL;\n \n /* memory allocation and startup of y0 */\n y0 = N_VMake_Serial(x->size,x->data);\n if ( y0 == NULL )\n\treturn GSL_ENOMEM;\n \n /* memory allocation for CVODE */\n flag = CVodeMalloc(cvode_mem,f,t0,y0,CV_SS,rtol,&atol);\n if( flag != CV_SUCCESS )\n \treturn GSL_ENOMEM;\n \n /* setting user data for right hand side function */\n flag = CVodeSetFdata(cvode_mem,f_data);\n if( flag != CV_SUCCESS )\n return flag;\n\n /* setting max # of steps to be taken by the solver */\n flag = CVodeSetMaxNumSteps(cvode_mem,mxsteps);\n if( flag != CV_SUCCESS )\n return flag; \n\n /* setting max # of error test failures permitted */\n flag = CVodeSetMaxErrTestFails(cvode_mem,maxnef);\n if( flag != CV_SUCCESS )\n return flag;\n\n /* setting dense linear solver */\n flag = CVDense(cvode_mem,x->size);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* releasing allocated memory */\n N_VDestroy_Serial(y0);\n y0 = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver_reinit\n*\n* This function reinitiates the ODE solver workspace.\n*\n* Input:\n* f - right hand side function\n* f_data - right hand side function data\n* t0 - initial time\n* atol - absolute tolerance\n* rtol - relative tolerance\n* x - initial condition\n* cvode_mem - ODE solver workspace\n*\n* Output:\n* success or error\n*\n* last update: Oct 31, 2009\n*------------------------------------------------------------\n*/\n\nint odesolver_reinit(CVRhsFn f,void *f_data,double t0,\n\t\t double atol,double rtol,gsl_vector *x,void *cvode_mem)\n{\n int flag = CV_SUCCESS;\n N_Vector y0 = NULL;\n \n /* memory allocation and startup of y0 */\n y0 = N_VMake_Serial(x->size,x->data);\n if ( y0 == NULL )\n\treturn GSL_ENOMEM;\n \n /* restarting CVODE workspace */\n flag = CVodeReInit(cvode_mem,f,t0,y0,CV_SS,rtol,&atol);\n if( flag != CV_SUCCESS )\n \treturn flag;\n \n /* setting user data for right hand side function */\n flag = CVodeSetFdata(cvode_mem,f_data);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* releasing allocated memory */\n N_VDestroy_Serial(y0);\n y0 = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* odesolver\n*\n* This function performs the direct integration of the\n* governing equations.\n*\n* Input:\n* cvode_mem - ODE solver workspace\n* tf - final time\n* Fx - solution vector\n*\n* Output:\n* success or error\n*\n* last update: Oct 31, 2009\n*------------------------------------------------------------\n*/\n\nint odesolver(void *cvode_mem,double tf,gsl_vector *Fx)\n{\n double t;\n int flag = CV_SUCCESS;\n N_Vector y = NULL;\n \n /* memory allocation and startup of y */\n y = N_VMake_Serial(Fx->size,Fx->data);\n if ( y == NULL )\n\treturn GSL_ENOMEM;\n \n /* calling CVode solver */\n flag = CVode(cvode_mem,tf,y,&t,CV_NORMAL);\n if( flag != CV_SUCCESS )\n return flag;\n \n /* releasing allocated memory */\n N_VDestroy_Serial(y);\n y = NULL;\n\n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "d1aaa7a82107ad637395a3966dc3600f8f28c03f", "size": 13852, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-1.0/src/ode_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-1.0/src/ode_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-1.0/src/ode_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 24.3873239437, "max_line_length": 77, "alphanum_fraction": 0.5010828761, "num_tokens": 3690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.4813012978151567}} {"text": "/* eigen/gensymm.c\n * \n * Copyright (C) 2007 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module computes the eigenvalues of a real generalized\n * symmetric-definite eigensystem A x = \\lambda B x, where A and\n * B are symmetric, and B is positive-definite.\n */\n\n/*\ngsl_eigen_gensymm_alloc()\n\nAllocate a workspace for solving the generalized symmetric-definite\neigenvalue problem. The size of this workspace is O(2n).\n\nInputs: n - size of matrices\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_gensymm_workspace *\ngsl_eigen_gensymm_alloc(const size_t n)\n{\n gsl_eigen_gensymm_workspace *w;\n\n if (n == 0)\n {\n GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n GSL_EINVAL);\n }\n\n w = (gsl_eigen_gensymm_workspace *) calloc (1, sizeof (gsl_eigen_gensymm_workspace));\n\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->size = n;\n\n w->symm_workspace_p = gsl_eigen_symm_alloc(n);\n if (!w->symm_workspace_p)\n {\n gsl_eigen_gensymm_free(w);\n GSL_ERROR_NULL(\"failed to allocate space for symm workspace\", GSL_ENOMEM);\n }\n\n return (w);\n} /* gsl_eigen_gensymm_alloc() */\n\n/*\ngsl_eigen_gensymm_free()\n Free workspace w\n*/\n\nvoid\ngsl_eigen_gensymm_free (gsl_eigen_gensymm_workspace * w)\n{\n RETURN_IF_NULL (w);\n\n if (w->symm_workspace_p)\n gsl_eigen_symm_free(w->symm_workspace_p);\n\n free(w);\n} /* gsl_eigen_gensymm_free() */\n\n/*\ngsl_eigen_gensymm()\n\nSolve the generalized symmetric-definite eigenvalue problem\n\nA x = \\lambda B x\n\nfor the eigenvalues \\lambda.\n\nInputs: A - real symmetric matrix\n B - real symmetric and positive definite matrix\n eval - where to store eigenvalues\n w - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_gensymm (gsl_matrix * A, gsl_matrix * B, gsl_vector * eval,\n gsl_eigen_gensymm_workspace * w)\n{\n const size_t N = A->size1;\n\n /* check matrix and vector sizes */\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n }\n else if ((N != B->size1) || (N != B->size2))\n {\n GSL_ERROR (\"B matrix dimensions must match A\", GSL_EBADLEN);\n }\n else if (eval->size != N)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else if (w->size != N)\n {\n GSL_ERROR (\"matrix size does not match workspace\", GSL_EBADLEN);\n }\n else\n {\n int s;\n\n /* compute Cholesky factorization of B */\n s = gsl_linalg_cholesky_decomp(B);\n if (s != GSL_SUCCESS)\n return s; /* B is not positive definite */\n\n /* transform to standard symmetric eigenvalue problem */\n gsl_eigen_gensymm_standardize(A, B);\n\n s = gsl_eigen_symm(A, eval, w->symm_workspace_p);\n\n return s;\n }\n} /* gsl_eigen_gensymm() */\n\n/*\ngsl_eigen_gensymm_standardize()\n Reduce the generalized symmetric-definite eigenproblem to\nthe standard symmetric eigenproblem by computing\n\nC = L^{-1} A L^{-t}\n\nwhere L L^t is the Cholesky decomposition of B\n\nInputs: A - (input/output) real symmetric matrix\n B - real symmetric, positive definite matrix in Cholesky form\n\nReturn: success\n\nNotes: A is overwritten by L^{-1} A L^{-t}\n*/\n\nint\ngsl_eigen_gensymm_standardize(gsl_matrix *A, const gsl_matrix *B)\n{\n const size_t N = A->size1;\n size_t i;\n double a, b, c;\n\n for (i = 0; i < N; ++i)\n {\n /* update lower triangle of A(i:n, i:n) */\n\n a = gsl_matrix_get(A, i, i);\n b = gsl_matrix_get(B, i, i);\n a /= b * b;\n gsl_matrix_set(A, i, i, a);\n\n if (i < N - 1)\n {\n gsl_vector_view ai = gsl_matrix_subcolumn(A, i, i + 1, N - i - 1);\n gsl_matrix_view ma =\n gsl_matrix_submatrix(A, i + 1, i + 1, N - i - 1, N - i - 1);\n gsl_vector_const_view bi =\n gsl_matrix_const_subcolumn(B, i, i + 1, N - i - 1);\n gsl_matrix_const_view mb =\n gsl_matrix_const_submatrix(B, i + 1, i + 1, N - i - 1, N - i - 1);\n\n gsl_blas_dscal(1.0 / b, &ai.vector);\n\n c = -0.5 * a;\n gsl_blas_daxpy(c, &bi.vector, &ai.vector);\n\n gsl_blas_dsyr2(CblasLower, -1.0, &ai.vector, &bi.vector, &ma.matrix);\n\n gsl_blas_daxpy(c, &bi.vector, &ai.vector);\n\n gsl_blas_dtrsv(CblasLower,\n CblasNoTrans,\n CblasNonUnit,\n &mb.matrix,\n &ai.vector);\n }\n }\n\n return GSL_SUCCESS;\n} /* gsl_eigen_gensymm_standardize() */\n", "meta": {"hexsha": "112dd1f7e47b1a04d35ce2dc5860c9e0d30b2fcf", "size": 5441, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/eigen/gensymm.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/eigen/gensymm.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/eigen/gensymm.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": 25.4252336449, "max_line_length": 87, "alphanum_fraction": 0.6408748392, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695627, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.481241101049938}} {"text": "#include \n#include \n\ndouble A[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };\n\ndouble x[] = { 1.0, -1.0, 2.0 };\ndouble y[] = { -1.0, 0.0, 2.0 };\n\nint main() {\n int i;\n cblas_dgemv(CblasRowMajor, CblasNoTrans, 3, 3, 2.5, A, 3, x, 1, 1.2, y, 1);\n for (i = 0; i < 3; ++i) { printf(\"%6.1f\\n\", y[i]); }\n\n return 0;\n}\n", "meta": {"hexsha": "dccb6a35fc8f11a42a6c244b9da3b0c66d49b83f", "size": 339, "ext": "c", "lang": "C", "max_stars_repo_path": "src_book0/ex10/list1022/list1022.c", "max_stars_repo_name": "julnamoo/practice-linux", "max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z", "max_issues_repo_path": "src_book0/ex10/list1022/list1022.c", "max_issues_repo_name": "julnamoo/practice-linux", "max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_issues_repo_licenses": ["FSFAP"], "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_book0/ex10/list1022/list1022.c", "max_forks_repo_name": "julnamoo/practice-linux", "max_forks_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1875, "max_line_length": 77, "alphanum_fraction": 0.4808259587, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.48034376828387393}} {"text": "/* gsl_histogram_maxval.c\n * Copyright (C) 2000 Simone Piccardi\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 * File gsl_histogram_maxval.c: \n * Routine to find maximum and minumum content of a hisogram. \n * Need GSL library and header.\n * Contains the routines:\n * gsl_histogram_max_val find max content values\n * gsl_histogram_min_val find min content values\n * gsl_histogram_bin_max find coordinates of max contents bin\n * gsl_histogram_bin_min find coordinates of min contents bin\n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include \n#include \n#include \n\ndouble\ngsl_histogram_max_val (const gsl_histogram * h)\n{\n const size_t n = h->n;\n size_t i;\n double max = h->bin[0];\n for (i = 0; i < n; i++)\n {\n if (h->bin[i] > max)\n {\n max = h->bin[i];\n }\n }\n return max;\n}\n\nsize_t\ngsl_histogram_max_bin (const gsl_histogram * h)\n{\n size_t i;\n size_t imax = 0;\n double max = h->bin[0];\n for (i = 0; i < h->n; i++)\n {\n if (h->bin[i] > max)\n {\n max = h->bin[i];\n imax = i;\n }\n }\n return imax;\n}\n\ndouble\ngsl_histogram_min_val (const gsl_histogram * h)\n{\n size_t i;\n double min = h->bin[0];\n for (i = 0; i < h->n; i++)\n {\n if (h->bin[i] < min)\n {\n min = h->bin[i];\n }\n }\n return min;\n}\n\nsize_t\ngsl_histogram_min_bin (const gsl_histogram * h)\n{\n size_t i;\n size_t imin = 0;\n double min = h->bin[0];\n for (i = 0; i < h->n; i++)\n {\n if (h->bin[i] < min)\n {\n min = h->bin[i];\n imin = i;\n }\n }\n return imin;\n}\n", "meta": {"hexsha": "a914c1ce29cca5e81c54b00ed7a0a27e31dbd587", "size": 2430, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/maxval.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/maxval.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/maxval.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.0594059406, "max_line_length": 74, "alphanum_fraction": 0.5893004115, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.4802555501742017}} {"text": "/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* Set of C routines to use FFTW1.3 library\r\n* 2D- FFT's for any size\r\n*\r\n*\r\n* JLP\r\n* Version 12/12/2006 (from my BORLAND version)\r\n*--------------------------------------------------------*/\r\n#include \r\n#include \r\n#include \"jlp_fftw.h\"\r\n#include \"jlp_num_rename.h\"\r\n\r\n/* JLP2001: To be compatible with \"matlab\" \r\n* I should not normalize by sqrt(nx*ny): */\r\n/*\r\n#define NORMALIZE_SQRT\r\n*/\r\n\r\n/* Content of jlp_fftw.h: \r\n#include \r\n\r\nint FFTW_1D_Y_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, \r\n INT4 *direct);\r\nint fftw_1D_Y_float(float *re, float *im, int nx, int ny, int direct);\r\nint FFTW_1D_Y_DBLE(double *re, double *im, INT4 *nx, INT4 *ny, INT4 *idim, \r\n INT4 *direct);\r\nint fftw_1D_Y_double(double *re, double *im, int nx, int ny, int direct);\r\nint FFTW_2D_DBLE(double *re, double *im, int *nx, int *ny, int *direct);\r\nint fftw_2D_double(double *re, double *im, int nx, int ny, int direct);\r\nint FFTW_2D_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, \r\n INT4 *kod);\r\nint fftw_2D_float(float *re, float *im, int nx, int ny, int direct);\r\nint fftw_setup(int nx, int ny);\r\nint FFTW_SETUP(int *nx, int *ny);\r\nint fftw_fast(FFTW_COMPLEX *image, int nx, int ny, int direct);\r\nint fftw_shutdown();\r\n*/\r\n\r\n/* Static variables: */\r\nstatic fftwnd_plan plan_fwd, plan_bkwd;\r\n\r\n/*\r\n#define MAIN_TEST\r\n*/\r\n\r\n#ifdef MAIN_TEST\r\nmain()\r\n{\r\nregister int i;\r\nint nx = 9, ny = 8;\r\ndouble re[128], im[128];\r\nFFTW_COMPLEX* image;\r\nchar s[80];\r\n\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = i;\r\n im[i] = -i;\r\n }\r\n\r\nfftw_2D_double(re, im, nx, ny, 1);\r\nfftw_2D_double(re, im, nx, ny, -1);\r\n\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n printf(\" i=%d re=%f im=%f \\n\", i, re[i], im[i]);\r\n }\r\n\r\nprintf(\" Now going to fast fft...\");\r\ngets(s);\r\n\r\nnx = 388; ny = 128;\r\nimage = (FFTW_COMPLEX *) malloc(nx * ny * sizeof(FFTW_COMPLEX));\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n c_re(image[i]) = i;\r\n c_im(image[i]) = -i;\r\n }\r\n printf(\"OK, I go on, with nx=%d ny=%d\",nx,ny);\r\n\r\nfftw_setup(nx, ny);\r\nfftw_fast(image, nx, ny, 1);\r\nfftw_fast(image, nx, ny, -1);\r\nfftw_shutdown();\r\nfor(i = 0; i < 200; i++)\r\n {\r\n printf(\" i=%d re=%f im=%f \\n\", i, c_re(image[i]), c_im(image[i]));\r\n }\r\n\r\ngets(s);\r\nfree(image);\r\n}\r\n#endif\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* Interface with Fortran routines (with arrays of first dimension = idim)\r\n* kod=1, or 2 direct\r\n* kod=-1, or -2 inverse\r\n* kod=-2, or 2: power spectrum, and phase\r\n*--------------------------------------------------------------*/\r\nint FFTW_2D_FLT(float *re, float *im, INT4 *nx, INT4 *ny, INT4 *idim, \r\n INT4 *kod)\r\n{\r\nint nx1, ny1, direct, status;\r\nif(*idim != *nx)\r\n {printf(\"FFTW_2D/Fatal error idim=%d while nx=%d \\n\", *idim, *nx);\r\n exit(-1);\r\n }\r\nif(*kod != 1 && *kod != -1)\r\n {printf(\"FFTW_2D/Fatal error kod=%d (option not yet implemented)\\n\", *kod);\r\n exit(-1);\r\n }\r\nnx1 = *nx; ny1 = *ny; direct = *kod;\r\nstatus = fftw_2D_float(re, im, nx1, ny1, direct);\r\nreturn(status);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* Interface with Fortran routines\r\n* kod=1, or 2 direct\r\n* kod=-1, or -2 inverse\r\n* kod=-2, or 2: power spectrum, and phase\r\n* --------------------------------------------------------------*/\r\nint FFTW_1D_Y_DBLE(double *re, double *im, INT4 *nx, INT4 *ny, \r\n INT4 *idim, INT4 *kod)\r\n{\r\nint nx1, ny1, direct, status;\r\nif(*idim != *nx)\r\n {printf(\"FFTW_1D_Y/Fatal error idim=%d while nx=%d \\n\", *idim, *nx);\r\n exit(-1);\r\n }\r\nif(*kod != 1 && *kod != -1)\r\n {printf(\"FFTW_1D_Y/Fatal error kod=%d (option not yet implemented)\\n\", *kod);\r\n exit(-1);\r\n }\r\nnx1 = *nx; ny1 = *ny; direct = *kod;\r\nprintf(\"FFTW_1D_Y/ nx1=%d ny1=%d direct=%d\\n\",nx1,ny1,direct);\r\nstatus = fftw_1D_Y_double(re, im, nx1, ny1, direct);\r\nreturn(status);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* Interface with Fortran routines\r\n* kod=1, or 2 direct\r\n* kod=-1, or -2 inverse\r\n* kod=-2, or 2: power spectrum, and phase\r\n* --------------------------------------------------------------*/\r\nint FFTW_1D_Y_FLT(float *re, float *im, INT4 *nx, INT4 *ny, \r\n INT4 *idim, INT4 *kod)\r\n{\r\nint nx1, ny1, direct, status;\r\n\r\n#ifndef TOTO_\r\ndouble sum;\r\nregister int i;\r\n#endif\r\n\r\nif(*idim != *nx)\r\n {printf(\"FFTW_1D_Y_FLT/Fatal error idim=%d while nx=%d \\n\", *idim, *nx);\r\n exit(-1);\r\n }\r\nif(*kod != 1 && *kod != -1)\r\n {printf(\"FFTW_1D_Y_FLT/Fatal error kod=%d (option not yet implemented)\\n\", *kod);\r\n exit(-1);\r\n }\r\nnx1 = *nx; ny1 = *ny; direct = *kod;\r\n#ifdef DEBUG\r\nprintf(\"FFTW_1D_Y_FLT/ nx1=%d ny1=%d direct=%d (fftw)\\n\",nx1,ny1,direct);\r\n#endif\r\n\r\n#ifndef TOTO_\r\nsum =0;\r\nfor(i=0; i < ny1; i++) sum += re[nx1/2 + i * nx1];\r\nprintf(\" Sum of central line = %e and sum/sqrt(ny)=%e \\n\",\r\n sum,sum/sqrt((double)ny1));\r\n#endif\r\n\r\nstatus = fftw_1D_Y_float(re, im, nx1, ny1, direct);\r\n\r\n/* JLP99: to check that FFT is correct: */\r\n/* Not recentred yet !! */\r\n#ifndef TOTO_\r\nfor(i=0; i <= 2; i++)\r\nprintf(\"re,im [ixc,%d]: %e %e \\n\",i,\r\n re[nx1/2 + i*nx1],im[nx1/2 + i*nx1]);\r\n#endif\r\n\r\nreturn(status);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 2D FFT routine for double precision arrays\r\n* direct = 1 : direct or forward\r\n* direct = -1 : reverse or backward\r\n* (FORTRAN version)\r\n* --------------------------------------------------------------*/\r\nint FFTW_2D_DBLE(double *re, double *im, int *nx, int *ny, int *direct)\r\n{\r\nint status;\r\nstatus = fftw_2D_double(re, im, *nx, *ny, *direct);\r\nreturn(status);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 2D FFT routine for double precision arrays\r\n* direct = 1 : direct or forward\r\n* direct = -1 : reverse or backward\r\n*\r\n* --------------------------------------------------------------*/\r\nint fftw_2D_double(double *re, double *im, int nx, int ny, int direct)\r\n{\r\nregister int i;\r\ndouble norm;\r\nint isize;\r\nfftwnd_plan plan;\r\nfftw_direction dir;\r\nFFTW_COMPLEX* in_out;\r\n\r\nisize = nx * ny;\r\nin_out = (FFTW_COMPLEX *) malloc(isize * sizeof(FFTW_COMPLEX));\r\n\r\n/* Transfer to complex array structure: */\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n c_re(in_out[i]) = re[i];\r\n c_im(in_out[i]) = im[i];\r\n }\r\n\r\n/* direct = 1 : forward\r\n direct = -1 : backward\r\n*/\r\ndir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD;\r\n/* Warning: inversion nx-ny here: */\r\nplan = fftw2d_create_plan(ny, nx, dir, \r\n FFTW_ESTIMATE | FFTW_IN_PLACE);\r\nif(plan == NULL)\r\n{printf(\"FFTW_2D_DBLE: fatal error creating plan\\n\"); exit(-1);}\r\n\r\n/* Compute the FFT: */\r\n fftwnd(plan, 1, in_out, 1, 0, 0, 0, 0);\r\n\r\n/* Transfer back to original arrays (and normalize by sqrt(nx * ny): */\r\n#ifdef NORMALIZE_SQRT \r\nnorm = nx * ny; norm = sqrt(norm);\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]) /norm;\r\n im[i] = c_im(in_out[i]) /norm;\r\n }\r\n#else\r\nif(direct == 1)\r\n {\r\n for(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]);\r\n im[i] = c_im(in_out[i]);\r\n }\r\n }\r\nelse\r\n {\r\n norm = nx * ny;\r\n for(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]) /norm;\r\n im[i] = c_im(in_out[i]) /norm;\r\n }\r\n }\r\n#endif\r\n\r\nfree(in_out);\r\n\r\n/* Delete plan: */\r\n fftwnd_destroy_plan(plan);\r\n\r\nreturn(0);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 2D FFT routine for single precision arrays (for which idim=nx)\r\n* (well suited to C arrays since nx=idim...)\r\n* direct = 1 : direct or forward\r\n* direct = -1 : reverse or backward\r\n* --------------------------------------------------------------*/\r\nint fftw_2D_float(float *re, float *im, int nx, int ny, int direct)\r\n{\r\nregister int i;\r\ndouble norm;\r\nint isize;\r\nfftwnd_plan plan;\r\nfftw_direction dir;\r\nFFTW_COMPLEX* in_out;\r\n\r\nisize = nx * ny;\r\nin_out = (FFTW_COMPLEX *) malloc(isize * sizeof(FFTW_COMPLEX));\r\n\r\n/* Transfer to complex array structure: */\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n c_re(in_out[i]) = re[i];\r\n c_im(in_out[i]) = im[i];\r\n }\r\n\r\n/* direct = 1 : forward\r\n direct = -1 : backward\r\n*/\r\ndir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD;\r\n/* Warning: inversion nx-ny here: */\r\nplan = fftw2d_create_plan(ny, nx, dir, \r\n FFTW_ESTIMATE | FFTW_IN_PLACE);\r\nif(plan == NULL)\r\n{printf(\"fftw_2D_float: fatal error creating plan\\n\"); exit(-1);}\r\n\r\n/* Compute the FFT: */\r\n fftwnd(plan, 1, in_out, 1, 0, 0, 0, 0);\r\n\r\n/* Transfer back to original arrays (and normalize by sqrt(nx * ny): */\r\n#ifdef NORMALIZE_SQRT \r\nnorm = nx * ny; norm = sqrt(norm);\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]) /norm;\r\n im[i] = c_im(in_out[i]) /norm;\r\n }\r\n#else\r\nif(direct == 1)\r\n {\r\n for(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]);\r\n im[i] = c_im(in_out[i]);\r\n }\r\n }\r\nelse\r\n {\r\n norm = nx * ny;\r\n for(i = 0; i < nx * ny; i++)\r\n {\r\n re[i] = c_re(in_out[i]) /norm;\r\n im[i] = c_im(in_out[i]) /norm;\r\n }\r\n }\r\n#endif\r\n\r\nfree(in_out);\r\n\r\n/* Delete plan: */\r\n fftwnd_destroy_plan(plan);\r\n\r\nreturn(0);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 1D FFT routine for single precision arrays\r\n* along the columns (for spectroscopic mode)\r\n* direct = 1 : direct or forward\r\n* direct = -1 : reverse or backward\r\n*\r\n* --------------------------------------------------------------*/\r\nint fftw_1D_Y_float(float *re, float *im, int nx, int ny, int direct)\r\n{\r\nregister int i, j;\r\ndouble norm;\r\nfftw_plan plan;\r\nfftw_direction dir;\r\nFFTW_COMPLEX* in_out;\r\n\r\nin_out = (FFTW_COMPLEX *) malloc(ny * sizeof(FFTW_COMPLEX));\r\nif(in_out == NULL)\r\n{printf(\"fftw_1D_Y_float: fatal error allocating memory\\n\"); exit(-1);}\r\n\r\n\r\n/* direct = 1 : forward\r\n direct = -1 : backward\r\n*/\r\ndir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD;\r\nplan = fftw_create_plan(ny, dir, FFTW_ESTIMATE | FFTW_IN_PLACE);\r\nif(plan == NULL)\r\n{printf(\"fftw_1D_Y_float: fatal error creating plan\\n\"); exit(-1);}\r\n\r\nfor(i = 0; i < nx; i++)\r\n{\r\n/* Transfer to complex array structure: */\r\n for(j = 0; j < ny; j++)\r\n {\r\n c_re(in_out[j]) = re[i + j * nx];\r\n c_im(in_out[j]) = im[i + j * nx];\r\n }\r\n\r\n/* Compute the FFT: */\r\n fftw(plan, 1, in_out, 1, 0, 0, 0, 0);\r\n\r\n/* Transfer back to original arrays (and normalize by sqrt(ny): */\r\n#ifdef NORMALIZE_SQRT \r\nnorm = sqrt((double)ny);\r\nfor(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]) /norm;\r\n im[i + j * nx] = c_im(in_out[j]) /norm;\r\n }\r\n#else\r\nif(direct == 1)\r\n {\r\n for(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]);\r\n im[i + j * nx] = c_im(in_out[j]);\r\n }\r\n }\r\nelse\r\n {\r\n norm = (double)ny;\r\n for(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]) /norm;\r\n im[i + j * nx] = c_im(in_out[j]) /norm;\r\n }\r\n }\r\n#endif\r\n/* End of loop on i (from 0 to nx-1) */\r\n}\r\n\r\nfree(in_out);\r\n\r\n/* Delete plan: */\r\n fftw_destroy_plan(plan);\r\n\r\nreturn(0);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 1D FFT routine for double precision arrays\r\n* along the columns (for spectroscopic mode)\r\n* direct = 1 : direct or forward\r\n* direct = -1 : reverse or backward\r\n*\r\n* --------------------------------------------------------------*/\r\nint fftw_1D_Y_double(double *re, double *im, int nx, int ny, int direct)\r\n{\r\nregister int i, j;\r\ndouble norm;\r\nfftw_plan plan;\r\nfftw_direction dir;\r\nFFTW_COMPLEX* in_out;\r\n\r\nin_out = (FFTW_COMPLEX *) malloc(ny * sizeof(FFTW_COMPLEX));\r\n\r\n/* direct = 1 : forward\r\n direct = -1 : backward\r\n*/\r\ndir = (direct == 1) ? FFTW_FORWARD : FFTW_BACKWARD;\r\nplan = fftw_create_plan(ny, dir, FFTW_ESTIMATE | FFTW_IN_PLACE);\r\nif(plan == NULL)\r\n{printf(\"fftw_1D_Y: fatal error creating plan\\n\"); exit(-1);}\r\n\r\nfor(i = 0; i < nx; i++)\r\n{\r\n/* Transfer to complex array structure: */\r\n for(j = 0; j < ny; j++)\r\n {\r\n c_re(in_out[j]) = re[i + j * nx];\r\n c_im(in_out[j]) = im[i + j * nx];\r\n }\r\n\r\n/* Compute the FFT: */\r\n fftw(plan, 1, in_out, 1, 0, 0, 0, 0);\r\n\r\n/* Transfer back to original arrays (and normalize by sqrt(ny): */\r\n#ifdef NORMALIZE_SQRT \r\nnorm = sqrt((double)ny);\r\nfor(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]) /norm;\r\n im[i + j * nx] = c_im(in_out[j]) /norm;\r\n }\r\n#else\r\nif(direct == 1)\r\n {\r\n for(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]);\r\n im[i + j * nx] = c_im(in_out[j]);\r\n }\r\n }\r\nelse\r\n {\r\n norm = (double)ny;\r\n for(j = 0; j < ny; j++)\r\n {\r\n re[i + j * nx] = c_re(in_out[j]) /norm;\r\n im[i + j * nx] = c_im(in_out[j]) /norm;\r\n }\r\n }\r\n#endif\r\n/* End of loop on i (from 0 to nx-1) */\r\n}\r\n\r\nfree(in_out);\r\n\r\n/* Delete plan: */\r\n fftw_destroy_plan(plan);\r\n\r\nreturn(0);\r\n}\r\n/****************************************************************\r\n* Fortran interface to fftw_setup\r\n****************************************************************/\r\nint FFTW_FSETUP(int *nx, int *ny)\r\n{\r\nfftw_setup(*nx, *ny);\r\nreturn(0);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n// fftw_setup, to initialize FFTW routines\r\n// Create forward and backward plans\r\n//\r\n// --------------------------------------------------------------*/\r\nint fftw_setup(int nx, int ny)\r\n{\r\nchar fwd_name[60], bkwd_name[60];\r\nFILE *fp_wisd;\r\nint ToOutput;\r\n\r\n/********************** With \"forward\" ***************************/\r\n#ifdef BORLAND\r\nsprintf(fwd_name,\"c:\\\\tc\\\\fftw13\\\\jlp\\\\fwd_%d.wis\",nx);\r\n#else\r\nsprintf(fwd_name,\"/d/fftw/fwd_%d%d.wis\",nx,ny);\r\n#endif\r\n\r\n/* Check if wisdom file already exits: */\r\nprintf(\"fftw_setup/Read wisdom file: %s\\n\",fwd_name);\r\nif((fp_wisd = fopen(fwd_name,\"r\")) == NULL) \r\n {\r\n printf(\"fftw_setup/Failure to open wisdom file: %s\\n\",fwd_name);\r\n ToOutput = 1;\r\n }\r\nelse\r\n {\r\n ToOutput = 0;\r\n if(fftw_import_wisdom_from_file(fp_wisd) == FFTW_FAILURE) ToOutput = 1;\r\n fclose(fp_wisd);\r\n }\r\n\r\n/* Create \"plan\" for fftw (speed is wanted for subsequent FFT's) */\r\n/* Warning: inversion nx-ny here: */\r\nplan_fwd = fftw2d_create_plan(ny, nx, FFTW_FORWARD,\r\n FFTW_MEASURE | FFTW_IN_PLACE | FFTW_USE_WISDOM);\r\n\r\n/* Output wisdom file if needed: */\r\nif(ToOutput)\r\n {\r\n printf(\"fftw_setup/Write wisdom file: %s\\n\",fwd_name);\r\n if((fp_wisd = fopen(fwd_name,\"w\")) != NULL) \r\n fftw_export_wisdom_to_file(fp_wisd);\r\n fclose(fp_wisd);\r\n }\r\n\r\n/********************** With \"backward\" ***************************/\r\n#ifdef BORLAND\r\nsprintf(bkwd_name,\"c:\\\\tc\\\\fftw13\\\\jlp\\\\bk_%d%d.wis\",nx,ny);\r\n#else\r\nsprintf(bkwd_name,\"/d/fftw/bk_%d%d.wis\",nx,ny);\r\n#endif\r\n\r\n/* Check if wisdom file already exits: */\r\nprintf(\"fftw_setup/Read wisdom file: %s\\n\",bkwd_name);\r\nif((fp_wisd = fopen(bkwd_name,\"r\")) == NULL) \r\n {\r\n printf(\"fftw_setup/Failure to open wisdom file: %s\\n\",bkwd_name);\r\n ToOutput = 1;\r\n } \r\nelse\r\n {\r\n ToOutput = 0;\r\n if(fftw_import_wisdom_from_file(fp_wisd) == FFTW_FAILURE) ToOutput = 1;\r\n fclose(fp_wisd);\r\n }\r\n\r\n/* Create \"plan\" for fftw (speed is wanted for subsequent FFT's) */\r\n/* Warning: inversion nx-ny here: */\r\nplan_bkwd = fftw2d_create_plan(ny, nx, FFTW_BACKWARD,\r\n FFTW_MEASURE | FFTW_IN_PLACE | FFTW_USE_WISDOM);\r\n\r\n/* Output wisdom file if needed: */\r\nif(ToOutput)\r\n {\r\n printf(\"fftw_setup/Write wisdom file: %s\\n\",bkwd_name);\r\n if((fp_wisd = fopen(bkwd_name,\"w\")) != NULL) \r\n fftw_export_wisdom_to_file(fp_wisd);\r\n fclose(fp_wisd);\r\n }\r\n\r\nreturn(0);\r\n}\r\n/*************************************************************\r\n*\r\n**************************************************************/\r\nint FFTW_SHUTDOWN()\r\n{\r\n/* Delete plans: */\r\n fftwnd_destroy_plan(plan_fwd);\r\n fftwnd_destroy_plan(plan_bkwd);\r\nreturn(0);\r\n}\r\n/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n* 2D FFT routine for double precision fftw_complex arrays\r\n* direction = 1 : forward\r\n* direction = -1 : backward\r\n* Should be called after fftw_setup and before fftw_shutdown\r\n* --------------------------------------------------------------*/\r\nint fftw_fast(FFTW_COMPLEX *image, int nx, int ny, int dir)\r\n{\r\nregister int i;\r\ndouble norm;\r\n\r\n/* Compute the FFT: */\r\nif(dir == 1)\r\n fftwnd(plan_fwd, 1, image, 1, 0, 0, 0, 0);\r\nelse\r\n fftwnd(plan_bkwd, 1, image, 1, 0, 0, 0, 0);\r\n\r\n/* Normalize by sqrt(nx * ny): */\r\n#ifdef NORMALIZE_SQRT \r\nnorm = nx * ny; norm = sqrt(norm);\r\nfor(i = 0; i < nx * ny; i++)\r\n {\r\n c_re(image[i]) /= norm;\r\n c_im(image[i]) /= norm;\r\n }\r\n#else\r\nif(dir == -1)\r\n {\r\n norm = (double)(nx * ny);\r\n for(i = 0; i < nx * ny; i++)\r\n {\r\n c_re(image[i]) /= norm;\r\n c_im(image[i]) /= norm;\r\n }\r\n }\r\n#endif\r\n\r\nreturn(0);\r\n}\r\n\r\n", "meta": {"hexsha": "7fc57d430fd78b544776447f62828d4db5c609ec", "size": 16698, "ext": "c", "lang": "C", "max_stars_repo_path": "jlp_numeric/old/fft_num_old/fftw_set.c", "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "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": "jlp_numeric/old/fft_num_old/fftw_set.c", "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "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": "jlp_numeric/old/fft_num_old/fftw_set.c", "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "avg_line_length": 26.1724137931, "max_line_length": 83, "alphanum_fraction": 0.5200622829, "num_tokens": 5158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4798921374025703}} {"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_4_2.c\n * \\brief Source file to optimize Runge-Kutta 4 steps 2nd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_4_2.h\"\n\n#define DEBUG_RK_4_2 0 ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 4 steps 2nd order Runge-Kutta \n * method.\n */\nint\nrk_tb_4_2 (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t4 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n b21 (tb) = r[2];\n t3 (tb) = r[3];\n b31 (tb) = r[4];\n b32 (tb) = r[5];\n b41 (tb) = r[6];\n b42 (tb) = r[7];\n b43 (tb) = (0.5L - b41 (tb) * t1 (tb) - b42 (tb) * t2 (tb)) / t3 (tb);\n if (isnan (b43 (tb)))\n return 0;\n rk_b_4 (tb);\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 2nd order, 3rd order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_4_2t (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb, *r;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2t: start\\n\");\n#endif\n tb = optimize->coefficient;\n r = optimize->random_data;\n t4 (tb) = 1.L;\n t1 (tb) = r[0];\n t2 (tb) = r[1];\n b21 (tb) = r[2];\n t3 (tb) = r[3];\n b31 (tb) = r[4];\n b32 (tb) = r[5];\n b41 (tb) = r[6];\n b42 (tb) = (1.L / 3.L - 0.5L * t3 (tb)\n - b41 (tb) * t1 (tb) * (t1 (tb) - t3 (tb)))\n / (t2 (tb) * (t2 (tb) - t3 (tb)));\n if (isnan (b42 (tb)))\n return 0;\n b43 (tb) = (0.5L - b41 (tb) * t1 (tb) - b42 (tb) * t2 (tb)) / t3 (tb);\n if (isnan (b43 (tb)))\n return 0;\n rk_b_4 (tb);\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2t: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 1st-2nd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_4_2p (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2p: start\\n\");\n#endif\n if (!rk_tb_4_2 (optimize))\n return 0;\n tb = optimize->coefficient;\n e41 (tb) = e42 (tb) = 0.L;\n rk_e_4 (tb);\n#if DEBUG_RK_4_2\n rk_print_e (optimize, \"rk_tb_4_2p\", stderr);\n fprintf (stderr, \"rk_tb_4_2p: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 1st-2nd order, 1st-3rd order\n * in equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_4_2tp (Optimize * optimize) ///< Optimize struct.\n{\n long double *tb;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_tb_4_2tp: start\\n\");\n#endif\n if (!rk_tb_4_2t (optimize))\n return 0;\n tb = optimize->coefficient;\n e41 (tb) = e42 (tb) = 0.L;\n rk_e_4 (tb);\n#if DEBUG_RK_4_2\n rk_print_tb (optimize, \"rk_tb_4_2tp\", stderr);\n fprintf (stderr, \"rk_tb_4_2pt: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 2nd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_2 (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_objective_tb_4_2: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b40 (tb) < 0.L)\n o += b40 (tb);\n if (b43 (tb) < 0.L)\n o += b43 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_objective_tb_4_2: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_4_2: end\\n\");\n#endif\n return o;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 2nd order, 3rd\n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_2t (RK * rk) ///< RK struct.\n{\n long double *tb;\n long double o;\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_objective_tb_4_2t: start\\n\");\n#endif\n tb = rk->tb->coefficient;\n o = fminl (0.L, b20 (tb));\n if (b30 (tb) < 0.L)\n o += b30 (tb);\n if (b40 (tb) < 0.L)\n o += b40 (tb);\n if (b42 (tb) < 0.L)\n o += b42 (tb);\n if (b43 (tb) < 0.L)\n o += b43 (tb);\n if (o < 0.L)\n {\n o = 40.L - o;\n goto end;\n }\n o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n if (rk->strong)\n {\n rk_bucle_ac (rk);\n o = fminl (o, *rk->ac0->optimal);\n }\nend:\n#if DEBUG_RK_4_2\n fprintf (stderr, \"rk_objective_tb_4_2t: optimal=%Lg\\n\", o);\n fprintf (stderr, \"rk_objective_tb_4_2t: end\\n\");\n#endif\n return o;\n}\n", "meta": {"hexsha": "6aadac489054525052d1e29ae27056ea84786647", "size": 6274, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_4_2.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rk_4_2.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_4_2.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5040650407, "max_line_length": 80, "alphanum_fraction": 0.6381893529, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.4795285733154741}} {"text": "#include \n#include \n \nint main (void)\n{\n double x, y;\n x = 5.0;\n y = gsl_sf_bessel_J0 (x);\n printf (\"J0(%g) = %.18e\\n\", x, y);\n return 0;\n}", "meta": {"hexsha": "6d5bcfc2ce756db844005e1c700415aa3396ae4c", "size": 178, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gpdream/modules/Merlin/src/test.c", "max_stars_repo_name": "kevintee/Predicting-Gene-Networks", "max_stars_repo_head_hexsha": "bf415f2b11cd7289b13ab900752cf1f856ce4b47", "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/gpdream/modules/Merlin/src/test.c", "max_issues_repo_name": "kevintee/Predicting-Gene-Networks", "max_issues_repo_head_hexsha": "bf415f2b11cd7289b13ab900752cf1f856ce4b47", "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/gpdream/modules/Merlin/src/test.c", "max_forks_repo_name": "kevintee/Predicting-Gene-Networks", "max_forks_repo_head_hexsha": "bf415f2b11cd7289b13ab900752cf1f856ce4b47", "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": 16.1818181818, "max_line_length": 36, "alphanum_fraction": 0.5561797753, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47929886501828944}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"LNAbundance.h\"\n\nstatic int verbose = FALSE;\n\nstatic int nLines = 9;\n\nstatic char *usage[] = {\"LNAbundance - \\n\",\n \"Required parameters:\\n\",\n\t\t\t\" -a abundance data\\n\",\n\t\t\t\" -in filename parameter file \\n\",\n \"Optional:\\n\",\n\t\t\t\" -b integer length of sample file to ignore\\n\",\n\t\t\t\" -s integer sampling frequency\\n\",\n\t\t\t\" -seed long seed random number generator\\n\",\n\t\t\t\" -v verbose\\n\"};\n\nvoid updateExpectations(double* adExpect, int nMax, double dMDash, double dV, int nS, t_Data *ptData)\n{\n int i = 0;\n\n for(i = 1; i <= nMax; i++){\n int nA = i;\n double dLog = 0.0, dP = 0.0;\n \n if(nA < MAX_QUAD){\n dLog = logLikelihoodQuad(nA, dMDash, dV);\n }\n else{\n dLog = logLikelihoodRampal(nA, dMDash, dV);\n }\n\n dP = exp(dLog);\n\n adExpect[i - 1]+= dP*nS;\n }\n}\n\n\nint main(int argc, char* argv[]){\n t_Params tParams;\n t_LNParams* atLNParams;\n int i = 0, nSamples = 0, nMax = 0; \n t_Data tData;\n double* adExpect = NULL;\n\n gsl_set_error_handler_off();\n\n getCommandLineParams(&tParams, argc, argv);\n\n /*allocate memory for samples*/\n atLNParams = (t_LNParams *) malloc(MAX_SAMPLES*sizeof(t_LNParams));\n if(!atLNParams)\n goto memoryError;\n \n /*read in Monte-Carlo samples*/\n readSamples(&tParams, atLNParams, &nSamples);\n\n readAbundanceData(tParams.szAbundFile, &tData);\n\n nMax = tData.aanAbund[tData.nNA - 1][0];\n nMax = floor(pow(2.0,ceil(log((double) nMax)/log(2.0)) + 2.0) + 1.0e-7);\n\n adExpect = (double *) malloc(sizeof(double)*nMax);\n\n for(i = 0; i < nMax; i++){\n adExpect[i] = 0.0;\n }\n\n for(i = 0; i < nSamples; i++){\n updateExpectations(adExpect, nMax, \n\t\t atLNParams[i].dMDash, \n\t\t atLNParams[i].dV, \n\t\t atLNParams[i].nS, \n\t\t &tData);\n }\n\n for(i = 1; i <= nMax; i++){\n printf(\"%d %f\\n\",i,adExpect[i - 1]/((double) nSamples));\n }\n\n free(adExpect);\n exit(EXIT_SUCCESS);\n \n memoryError:\n fprintf(stderr, \"Failed to allocate memory in main aborting ...\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nint intCompare(const void *pvA, const void *pvB)\n{\n int* pnA = (int *) pvA, *pnB = (int *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nint doubleCompare(const void *pvA, const void *pvB)\n{\n double* pnA = (double *) pvA, *pnB = (double *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nvoid writeUsage(FILE* ofp)\n{\n int i = 0;\n char *line;\n\n for(i = 0; i < nLines; i++){\n line = usage[i];\n fputs(line,ofp);\n }\n}\n\nchar *extractParameter(int argc, char **argv, char *param,int when)\n{\n int i = 0;\n\n while((i < argc) && (strcmp(param,argv[i]))){\n i++;\n }\n\n if(i < argc - 1){\n return(argv[i + 1]);\n }\n\n if((i == argc - 1) && (when == OPTION)){\n return \"\";\n }\n\n if(when == ALWAYS){\n fprintf(stdout,\"Can't find asked option %s\\n\",param);\n }\n\n return (char *) NULL;\n}\n\nvoid getCommandLineParams(t_Params *ptParams,int argc,char *argv[])\n{\n char *szTemp = NULL;\n char *cError = NULL;\n\n /*get parameter file name*/\n ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS); \n if(ptParams->szInputFile == NULL)\n goto error;\n\n /*get abundance file name*/\n ptParams->szAbundFile = extractParameter(argc,argv, ABUND_FILE,ALWAYS); \n if(ptParams->szAbundFile == NULL)\n goto error;\n\n\n /*get long seed*/\n szTemp = extractParameter(argc,argv,SEED,OPTION); \n if(szTemp != NULL){\n ptParams->lSeed = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->lSeed = 0;\n }\n\n /*get burn*/\n szTemp = extractParameter(argc, argv, BURN, OPTION); \n if(szTemp != NULL){\n ptParams->nBurn = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nBurn = DEF_BURN;\n }\n\n /*get long seed*/\n szTemp = extractParameter(argc, argv, SAMPLE, OPTION); \n if(szTemp != NULL){\n ptParams->nSample = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nSample = DEF_SAMPLE;\n }\n \n /*verbosity*/\n szTemp = extractParameter(argc, argv, VERBOSE, OPTION);\n if(szTemp != NULL){\n verbose = TRUE;\n }\n\n return;\n\n error:\n writeUsage(stdout);\n exit(EXIT_FAILURE);\n}\n\nvoid readSamples(t_Params *ptParams, t_LNParams *atLNParams, int *pnSamples)\n{\n int nSamples = 0;\n char *szInputFile = ptParams->szInputFile;\n char szLine[MAX_LINE_LENGTH];\n FILE *ifp = NULL;\n\n ifp = fopen(szInputFile, \"r\");\n\n if(ifp){\n while(fgets(szLine, MAX_LINE_LENGTH, ifp)){\n char *szTok = NULL, *szBrk = NULL, *pcError = NULL;\n int nTime = 0;\n\n /*remove trailing new line*/\n szBrk = strpbrk(szLine, \"\\n\"); (*szBrk) = '\\0';\n \n szTok = strtok(szLine, DELIM);\n\n nTime = strtol(szTok, &pcError, 10);\n if(*pcError != '\\0') goto fileFormatError;\n\n if(nTime > ptParams->nBurn && nTime % ptParams->nSample == 0){\n\t\n\tszTok = strtok(NULL,DELIM);\n\tatLNParams[nSamples].dMDash = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatLNParams[nSamples].dV = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatLNParams[nSamples].nS = strtol(szTok, &pcError, 10);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tnSamples++;\n }\n }\n\n fclose(ifp);\n }\n else{\n fprintf(stderr, \"Failed to open file %s aborting\\n\", szInputFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n (*pnSamples) = nSamples;\n return;\n\n fileFormatError:\n fprintf(stderr, \"Incorrectly formatted input file aborting\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\ndouble f1(double x, void *pvParams)\n{\n t_LNParams *ptLNParams = (t_LNParams *) pvParams;\n double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;\n double dTemp = (x - dMDash);\n double dExp = x*((double) n) - exp(x) - 0.5*((dTemp*dTemp)/dV);\n double dRet = exp(dExp);\n\n return dRet;\n}\n\n\ndouble logLikelihoodRampal(int n, double dMDash, double dV)\n{\n double dN = (double) n;\n double dLogLik = 0.0, dTemp = gsl_pow_int(log(dN) - dMDash,2), dTemp3 = gsl_pow_int(log(dN) - dMDash,3); \n\n dLogLik = -0.5*log(2.0*M_PI*dV) - log(dN) - (dTemp/(2.0*dV));\n\n dLogLik += log(1.0 + 1.0/(2.0*dN*dV)*(dTemp/dV + log(dN) - dMDash - 1.0) \n\t\t + 1.0/(6.0*dN*dN*dV*dV*dV)*(3.0*dV*dV - (3.0*dV - 2.0*dV*dV)*(dMDash - log(dN)) \n\t\t - 3.0*dV*dTemp + dTemp3));\n\n return dLogLik;\n}\n\ndouble logLikelihoodQuad(int n, double dMDash, double dV)\n{\n gsl_integration_workspace *ptGSLWS = \n gsl_integration_workspace_alloc(1000);\n double dLogFac1 = 0.0, dLogFacN = 0.0;\n double dResult = 0.0, dError = 0.0, dPrecision = 0.0;\n gsl_function tGSLF;\n t_LNParams tLNParams;\n double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;\n\n tLNParams.n = n; tLNParams.dMDash = dMDash; tLNParams.dV = dV;\n\n tGSLF.function = &f1;\n tGSLF.params = (void *) &tLNParams;\n\n dLogFac1 = log(2.0*M_PI*dV);\n \n if(n < 50){\n dLogFacN = gsl_sf_fact(n);\n dLogFacN = log(dLogFacN);\n }\n else{\n dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);\n }\n\n if(dEst > dV){\n double dMax = 0.0;\n double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);\n double dVar = 0.0;\n\n solveF(0.0, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);\n\n dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));\n\n dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;\n }\n else{\n double dMax = 0.0;\n double dLower = dEst - dV;\n double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);\n double dVar = 0.0;\n\n solveF(dLower, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);\n\n dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));\n\n dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;\n }\n \n if(n < 10){\n dPrecision = HI_PRECISION;\n }\n else{\n dPrecision = LO_PRECISION;\n }\n\n gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);\n \n gsl_integration_workspace_free(ptGSLWS);\n\n return log(dResult) - dLogFacN -0.5*dLogFac1;\n}\n\ndouble derivExponent(double x, void *pvParams)\n{\n t_LNParams *ptLNParams = (t_LNParams *) pvParams;\n double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;\n double dTemp = (x - dMDash)/dV, dRet = 0.0;\n\n dRet = ((double) n) - exp(x) - dTemp;\n\n return dRet;\n}\n\nint solveF(double x_lo, double x_hi, double (*f)(double, void*), \n\t void* params, double tol, double *xsolve)\n{\n int status, iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double r = 0;\n gsl_function F;\n \n F.function = f;\n F.params = params;\n \n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc (T);\n gsl_root_fsolver_set (s, &F, x_lo, x_hi);\n \n do{\n iter++;\n status = gsl_root_fsolver_iterate (s);\n r = gsl_root_fsolver_root (s);\n x_lo = gsl_root_fsolver_x_lower (s);\n x_hi = gsl_root_fsolver_x_upper (s);\n \n status = gsl_root_test_interval (x_lo, x_hi, 0, tol); \n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n (*xsolve) = gsl_root_fsolver_root (s);\n gsl_root_fsolver_free (s);\n \n return status;\n}\n\n\nvoid readAbundanceData(const char *szFile, t_Data *ptData)\n{\n int **aanAbund = NULL;\n int i = 0, nNA = 0, nA = 0, nC = 0;\n int nL = 0, nJ = 0;\n char szLine[MAX_LINE_LENGTH];\n FILE* ifp = NULL;\n\n ifp = fopen(szFile, \"r\");\n\n if(ifp){\n char* szTok = NULL;\n char* pcError = NULL;\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n \n nNA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n goto formatError;\n }\n \n aanAbund = (int **) malloc(nNA*sizeof(int*));\n\n for(i = 0; i < nNA; i++){\n aanAbund[i] = (int *) malloc(sizeof(int)*2);\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n\n nA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n\n szTok = strtok(NULL, DELIM2);\n\n nC = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n \n nL += nC;\n nJ += nC*nA;\n\n aanAbund[i][0] = nA;\n aanAbund[i][1] = nC; \n }\n }\n else{\n fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n ptData->nJ = nJ;\n ptData->nL = nL;\n ptData->aanAbund = aanAbund;\n ptData->nNA = nNA;\n return;\n\n formatError:\n fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n", "meta": {"hexsha": "0700d4362e761e306e9ca66b40d58656a620b6ea", "size": 11041, "ext": "c", "lang": "C", "max_stars_repo_path": "LNAbundance/LNAbundance.c", "max_stars_repo_name": "chrisquince/DiversityEstimates", "max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z", "max_issues_repo_path": "LNAbundance/LNAbundance.c", "max_issues_repo_name": "chrisquince/DiversityEstimates", "max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "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": "LNAbundance/LNAbundance.c", "max_forks_repo_name": "chrisquince/DiversityEstimates", "max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "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.5326530612, "max_line_length": 108, "alphanum_fraction": 0.598134227, "num_tokens": 3810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4792970488641266}} {"text": "#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../core_allvars.h\"\n\n#define LUV_LOOKUPTABLE_MASS 1e6\n\nint32_t init_UVlookup(void)\n{\n\n // For calcUVmag == 1 we must explicitly track the stellar ages of a galaxy.\n // Then we determine the UV magnitude using the age of the stellar population.\n\n // Using STARBURST99 it was determined that the 1600A Luminosty depends on the mass\n // of stars formed and the time since the starburst. Furthermore, the UV luminosity linearly with the mass of stars formed.\n // That is, a starburst that forms 6.0e11Msun worth of stars will exhibit 10 times the UV luminosity as a starburst that forms 6.0e10Msun worth of stars.\n\n // So if we read in a table that contains the number of ionizing photons emitted from a starburst for a 6.0e10Msun episode, then we can scale our values to this lookup table\n // using log10 LUV(Msun, t) = (log10 M* - 6.0) + log10 LUV(6.0, t).\n\n#define MAXBINS 10000\n\n char fname[MAX_STRING_LEN];\n FILE *LUVtable;\n int32_t num_lines = 0;\n float t, lambda, LUV, norm_spec;\n\n snprintf(fname, MAX_STRING_LEN - 1, ROOT_DIR \"/extra/LUV_table.txt\");\n LUVtable = fopen(fname, \"r\");\n if (LUVtable == NULL)\n {\n fprintf(stderr, \"Could not open file %s\\n\", fname);\n return EXIT_FAILURE;\n }\n\n stars_LUV = calloc(MAXBINS, sizeof(*(stars_LUV)));\n if (stars_LUV == NULL)\n {\n fprintf(stderr, \"Could not allocate memory for the UV luminosity bins for the tracking of stellar populations.\\n\");\n return EXIT_FAILURE;\n }\n\n while (fscanf(LUVtable, \"%f %f %f %f\", &t, &lambda, &LUV, &norm_spec) == 4)\n {\n\n stars_LUV[num_lines] = LUV;\n\n ++num_lines;\n if (num_lines == MAXBINS - 1)\n {\n fprintf(stderr, \"Exceeding the maximum bins for the tracking of stellar populations.\\n\");\n return EXIT_FAILURE;\n }\n }\n fclose(LUVtable);\n\n // Check that the Nion lookup table had enough datapoints to cover the time we're tracking the ages for.\n if (t / 1.0e6 < STELLAR_TRACKING_TIME)\n {\n fprintf(stderr, \"The final time specified in the UV luminosity lookup table is %.4f Myr. However we specified to track stellar ages over %d Myr.\\n\", t / 1.0e6, STELLAR_TRACKING_TIME);\n fprintf(stderr, \"Either update the UV luminosity lookup table or reduce the value of STELLAR_TRACKING_TIME in `core_allvars.h`.\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n#undef MAXBINS\n}\n\n/*\nCalculates the UV Luminosity (i.e., at 1600A) for a given galaxy at a specified snapshot.\n\n**Important** See Units.\n\nParameters\n----------\n\ng: struct GALAXY pointer. See `core_allvars.h` for the struct architecture.\n Pointer to the galaxy that we are calculating UV luminosity.\n\n*LUV: Float Pointer.\n Pointer that will store the UV luminosity.\n\nReturns\n----------\n\nEXIT_SUCCESS or EXIT_FAILURE.\n If the UV luminosity is negative, EXIT_FAILURE is returned. Otherwise EXIT_SUCCESS is returned.\n\nPointer Updates\n----------\n\n*LUV.\n\nUnits\n----------\n\nThe UV luminosty is returned in units of 1.0e50 erg s^-1 A^-1\n*/\n\nint32_t calc_LUV(struct GALAXY *g, float *LUV)\n{\n\n double t;\n int32_t i, lookup_idx;\n\n // We ran STARBURST99 for a single mass and scale our results.\n // First convert the mass to internal code units.\n const double code_LUV_lookuptable_mass = LUV_LOOKUPTABLE_MASS*1.0e-10*Hubble_h;\n\n *LUV = 0.0;\n\n // Then go through the previous 100Myr worth of SF and sum up the UV luminosity.\n for (i = 0; i < StellarTracking_Len - 1; ++i)\n {\n if (g->Stellar_Stars[i] < 1e-10)\n continue;\n\n t = (i + 1) * TimeResolutionStellar; // (i + 1) because 0th entry will be at TimeResolutionSN.\n lookup_idx = t; // Find the index in the lookup table.\n\n *LUV += exp10(log10(g->Stellar_Stars[i] / code_LUV_lookuptable_mass) + stars_LUV[lookup_idx] - 50.0);\n //printf(\"t %.4f\\tlookup_idx %d\\tg->Stellar_Stars[i] %.4e\\tstars_LUV[lookup_idx] %.4e\\tRunningTotal %.4e\\n\", t, lookup_idx, g->Stellar_Stars[i], stars_LUV[lookup_idx], *LUV);\n }\n\n // The units of LUV are 1.0e50 erg s^-1 A^-1. Hence a negative value is not allowed.\n if (*LUV < 0.0)\n {\n fprintf(stderr, \"Got an LUV value of %.4e. This MUST be a positive value.\\nPrinting out information for every element used to calculate LUV.\\n\", *LUV);\n\n // Print out information for every element of the array so we can try identify the problem.\n for (i = 0; i < StellarTracking_Len; ++i)\n {\n t = (i + 1) * TimeResolutionStellar; // (i + 1) because 0th entry will be at TimeResolutionSN.\n lookup_idx = (t / 0.1); // Find the index in the lookup table.\n\n double total = 0.0;\n total += exp10(log10(g->Stellar_Stars[i] / code_LUV_lookuptable_mass) + stars_LUV[lookup_idx] - 50.0);\n printf(\"t %.4f\\tlookup_idx %d\\tg->Stellar_Stars[i] %.4e\\tstars_LUV[lookup_idx] %.4e\\tRunningTotal %.4e\\n\", t, lookup_idx, g->Stellar_Stars[i], stars_LUV[lookup_idx], total);\n }\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "2021fa795c7ac6bbe27e754d9ce299f042c2cbd3", "size": 5122, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sage/UVmag/UVmag.c", "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_issues_repo_path": "src/sage/UVmag/UVmag.c", "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_forks_repo_path": "src/sage/UVmag/UVmag.c", "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8333333333, "max_line_length": 187, "alphanum_fraction": 0.6944552909, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.47903947997842444}} {"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2018 Mateusz Pusz\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace units::detail {\n\ntemplate\n requires gt_zero\n[[nodiscard]] constexpr std::intmax_t iroot_impl(std::intmax_t v, F const& pow_function) noexcept\n{\n if constexpr (N == 1) {\n return v;\n } else {\n gsl_Expects(v >= 0);\n if (v == 0) {\n return 0;\n }\n\n constexpr double exponent = 1.0 / static_cast(N);\n const auto root = static_cast(pow_function(static_cast(v), exponent));\n\n // integer roots may be truncated down by 1 or in even rarer cases up by 1 due to finite precision of pow and\n // exponent, check both cases\n if (v == pow_impl(root + 1)) {\n return root + 1;\n }\n if (v < pow_impl(root)) {\n return root - 1;\n }\n return root;\n }\n}\n\n// maximum v is std::numeric_limits::max() which is the worst case for exp convergence\n// ExpOrder = 12 and Factor = 64 give a precision of about O(1e-15) for a wide range of 1 / N exponents\n// Factor = 32 needs quite a few more terms to converge\n// https://godbolt.org/z/odWq1o\ntemplate\n requires gt_zero\n[[nodiscard]] constexpr std::intmax_t iroot_compile(std::intmax_t v) noexcept\n{\n return iroot_impl(v, [](double x, double exponent) { return constexpr_pow(x, exponent); });\n}\n\ntemplate\n requires gt_zero\n[[nodiscard]] std::intmax_t iroot_runtime(std::intmax_t v) noexcept\n{\n return iroot_impl(v, [](double x, [[maybe_unused]] double exponent) {\n if constexpr (N == 2) {\n return std::sqrt(x);\n } else if constexpr (N == 3) {\n return std::cbrt(x);\n } else {\n return std::pow(x, exponent);\n }\n });\n}\n\ntemplate\n requires gt_zero\n[[nodiscard]] constexpr std::intmax_t iroot(std::intmax_t v) noexcept\n{\n // compile time version is much slower, use faster version at runtime\n if (std::is_constant_evaluated()) {\n return iroot_compile(v);\n }\n\n return iroot_runtime(v);\n}\n\n} // namespace units::detail\n", "meta": {"hexsha": "e718ef8a284f3238a9131b55d413b6c0a4db8546", "size": 3404, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/units/bits/root.h", "max_stars_repo_name": "HazardyKnusperkeks/units", "max_stars_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 571.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z", "max_issues_repo_path": "src/core/include/units/bits/root.h", "max_issues_repo_name": "HazardyKnusperkeks/units", "max_issues_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 283.0, "max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z", "max_forks_repo_path": "src/core/include/units/bits/root.h", "max_forks_repo_name": "HazardyKnusperkeks/units", "max_forks_repo_head_hexsha": "1d2b9205383f967e4d21df20ac2fd4168b6ff7a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 70.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z", "avg_line_length": 34.04, "max_line_length": 114, "alphanum_fraction": 0.6994712103, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4790384714472576}} {"text": "//This gets polynomial coeffs for each row/col of X using the Burg method.\n\n//An opt mean0 is added to zero the mean of each row/col of X first.\n//In this case, this is mean0 -> autocov_fft -> sig2ar_burg.\n\n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint sig2ar_burg_s (float *Y, float *V, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0);\nint sig2ar_burg_d (double *Y, double *V, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0);\n\n\nint sig2ar_burg_s (float *Y, float *V, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0)\n{\n if (dim>3) { fprintf(stderr,\"error in sig2ar_burg_s: dim must be in [0 3]\\n\"); return 1; }\n\n const float o = 1.0f;\n const int N = (dim==0) ? R : C;\n int r, c, p, q;\n float m, g, b2, f2;\n float *b, *f, *oldf, *AStmp;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in sig2ar_burg_s: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in sig2ar_burg_s: ncols X must be positive\\n\"); return 1; }\n if (dim==0 && P>=R) { fprintf(stderr,\"error in sig2ar_burg_s: P must be < nrows X for dim==0\\n\"); return 1; }\n if (dim==1 && P>=C) { fprintf(stderr,\"error in sig2ar_burg_s: P must be < ncols X for dim==1\\n\"); return 1; }\n\n //Allocate\n if (!(b=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,\"error in sig2ar_burg_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(f=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,\"error in sig2ar_burg_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(oldf=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,\"error in sig2ar_burg_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(AStmp=(float *)malloc((size_t)(P)*sizeof(float)))) { fprintf(stderr,\"error in sig2ar_burg_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n for (size_t c=0; c1) { for (q=0; q1) { for (q=0; q1) { for (q=0; q1) { for (q=0; q3) { fprintf(stderr,\"error in sig2ar_burg_d: dim must be in [0 3]\\n\"); return 1; }\n\n const double o = 1.0;\n const int N = (dim==0) ? R : C;\n int r, c, p, q;\n double m, g, b2, f2;\n double *b, *f, *oldf, *AStmp;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in sig2ar_burg_d: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in sig2ar_burg_d: ncols X must be positive\\n\"); return 1; }\n if (dim==0 && P>=R) { fprintf(stderr,\"error in sig2ar_burg_d: P must be < nrows X for dim==0\\n\"); return 1; }\n if (dim==1 && P>=C) { fprintf(stderr,\"error in sig2ar_burg_d: P must be < ncols X for dim==1\\n\"); return 1; }\n\n //Allocate\n if (!(b=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,\"error in sig2ar_burg_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(f=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,\"error in sig2ar_burg_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(oldf=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,\"error in sig2ar_burg_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(AStmp=(double *)malloc((size_t)(P)*sizeof(double)))) { fprintf(stderr,\"error in sig2ar_burg_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n for (size_t c=0; c1) { for (q=0; q1) { for (q=0; q1) { for (q=0; q1) { for (q=0; q\n#include \n#include \n#include \n#include \n\nint\ngsl_monte_plain_integrate (const gsl_monte_function * f,\n const double xl[], const double xu[],\n const size_t dim,\n const size_t calls,\n gsl_rng * r,\n gsl_monte_plain_state * state,\n double *result, double *abserr)\n{\n double vol, m = 0, q = 0;\n double *x = state->x;\n size_t n, i;\n\n if (dim != state->dim)\n {\n GSL_ERROR (\"number of dimensions must match allocated size\", GSL_EINVAL);\n }\n\n for (i = 0; i < dim; i++)\n {\n if (xu[i] <= xl[i])\n {\n GSL_ERROR (\"xu must be greater than xl\", GSL_EINVAL);\n }\n\n if (xu[i] - xl[i] > GSL_DBL_MAX)\n {\n GSL_ERROR (\"Range of integration is too large, please rescale\",\n GSL_EINVAL);\n }\n }\n\n /* Compute the volume of the region */\n\n vol = 1;\n\n for (i = 0; i < dim; i++)\n {\n vol *= xu[i] - xl[i];\n }\n\n for (n = 0; n < calls; n++)\n {\n /* Choose a random point in the integration region */\n\n for (i = 0; i < dim; i++)\n {\n x[i] = xl[i] + gsl_rng_uniform_pos (r) * (xu[i] - xl[i]);\n }\n\n {\n double fval = GSL_MONTE_FN_EVAL (f, x);\n\n /* recurrence for mean and variance */\n\n double d = fval - m;\n m += d / (n + 1.0);\n q += d * d * (n / (n + 1.0));\n }\n }\n\n *result = vol * m;\n\n if (calls < 2)\n {\n *abserr = GSL_POSINF;\n }\n else\n {\n *abserr = vol * sqrt (q / (calls * (calls - 1.0)));\n }\n\n return GSL_SUCCESS;\n}\n\ngsl_monte_plain_state *\ngsl_monte_plain_alloc (size_t dim)\n{\n gsl_monte_plain_state *s =\n (gsl_monte_plain_state *) malloc (sizeof (gsl_monte_plain_state));\n\n if (s == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for state struct\",\n GSL_ENOMEM, 0);\n }\n\n s->x = (double *) malloc (dim * sizeof (double));\n\n if (s->x == 0)\n {\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for working vector\",\n GSL_ENOMEM, 0);\n }\n\n s->dim = dim;\n\n return s;\n}\n\n/* Set some default values and whatever */\n\nint\ngsl_monte_plain_init (gsl_monte_plain_state * s)\n{\n size_t i;\n\n for (i = 0; i < s->dim; i++)\n {\n s->x[i] = 0.0;\n }\n\n return GSL_SUCCESS;\n}\n\nvoid\ngsl_monte_plain_free (gsl_monte_plain_state * s)\n{\n free (s->x);\n free (s);\n}\n", "meta": {"hexsha": "cab3ae2c59e7120e8445aaf70fb535ffcfdb7475", "size": 3413, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/monte/plain.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/monte/plain.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/monte/plain.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.4539473684, "max_line_length": 81, "alphanum_fraction": 0.5566949897, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.47885627874628833}} {"text": "#ifndef UTIL_H\n#define UTIL_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_MKL\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#include \"spaND.h\"\n\nnamespace spaND {\n\nbool are_connected(Eigen::VectorXi &a, Eigen::VectorXi &b, SpMat &A);\nbool should_be_disconnected(int lvl1, int lvl2, int sep1, int sep2);\ndouble elapsed(timeval& start, timeval& end);\nvoid swap2perm(Eigen::VectorXi* swap, Eigen::VectorXi* perm);\nbool isperm(const Eigen::VectorXi* perm);\nEigen::VectorXi invperm(const Eigen::VectorXi& perm);\nSpMat symmetric_graph(SpMat& A);\n\ntypedef timeval timer;\ntimer wctime();\n\n/**\n * C <- alpha A * B + beta C\n * C <- alpha A^T * B + beta C\n * C <- alpha A * B^T + beta C\n * C <- alpha A^T * B^T + beta C\n * Gemm\n */\nvoid gemm(Eigen::MatrixXd* A, Eigen::MatrixXd* B, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha, double beta);\n\n/** Return a new\n * C <- alpha A^(/T) * B^(/T)\n **/\nEigen::MatrixXd* gemm_new(Eigen::MatrixXd* A, Eigen::MatrixXd* B, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha);\n\n/**\n * C <- alpha A * A^T + beta C (or A^T * A)\n */\nvoid syrk(Eigen::MatrixXd* A, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, double alpha, double beta);\n\n/** \n * A <- L, L L^T = A\n * Return != 0 if potf failed (not spd)\n */ \nint potf(Eigen::MatrixXd* A);\n\nint ldlt(Eigen::MatrixXd* A, Eigen::MatrixXd* L, Eigen::VectorXd* d, Eigen::VectorXi* p, double* rcond);\n\n/**\n * A <- [L\\U] (lower and upper)\n * p <- swap (NOT a permutation)\n * A[p] = L*U\n * L is unit diagonal\n * U is not\n * Return != 0 if getf failed (singular)\n */\nint getf(Eigen::MatrixXd* A, Eigen::VectorXi* swap);\n\n/**\n * A = P L U Q\n * A <- [L\\U] (lower and upper)\n * L is unit diagonal\n * U is not\n */\nvoid fpgetf(Eigen::MatrixXd* A, Eigen::VectorXi* p, Eigen::VectorXi* q);\n\n/**\n * A = L U\n * breaks down into L & U, and split the diagonal between the two\n * A = L * (D + U') = L * D (I + D^-1 U') = { L * |D|^1/2 } { |D|^1/2 sign(D) (I + D^-1 U') }\n */\nvoid split_LU(Eigen::MatrixXd* A, Eigen::MatrixXd* L, Eigen::MatrixXd* U);\n\n/**\n * Compute an estimated 1-norm condition number of A using its LU or Cholesky factorization\n */\ndouble rcond_1_getf(Eigen::MatrixXd* A_LU, double A_1_norm);\ndouble rcond_1_potf(Eigen::MatrixXd* A_LLT, double A_1_norm);\ndouble rcond_1_trcon(Eigen::MatrixXd* LU, char uplo, char diag);\n\n/**\n * B <- B * L^(-1)\n * B <- B * L^(-T)\n * B <- B * U^(-1)\n * B <- B * U^(-T)\n */\nvoid trsm_right(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * B <- L^(-1) * B\n * B <- L^(-T) * B\n * B <- U^(-1) * B\n * B <- U^(-T) * B\n */\nvoid trsm_left(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * x <- L^(-1) * x\n * x <- L^(-T) * x\n * x <- U^(-1) * x\n * x <- U^(-T) * x\n */\nvoid trsv(Eigen::MatrixXd* L, Segment* x, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);\n\n/**\n * x <- L^T * x\n */\nvoid trmv_trans(Eigen::MatrixXd* L, Segment* x);\n\n/**\n * A <- L^T * A\n */\nvoid trmm_trans(Eigen::MatrixXd* L, Eigen::MatrixXd* A);\n\n/**\n * x2 <- x2 - A21 * x1\n */\nvoid gemv_notrans(Eigen::MatrixXd* A21, Segment* x1, Segment* x2);\n\n/**\n * x2 <- x2 - A12^T * x1\n */\nvoid gemv_trans(Eigen::MatrixXd* A12, Segment* x1, Segment* x2);\n\n/**\n * AP = QR\n */\nvoid geqp3(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau);\n\n/**\n * A = U S VT\n * Compute the full SVD, where if A is mxn, U is mxm, V is nxn, and S is min(M,N)\n * VT is V^T, *not* V.\n */\nvoid gesvd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S, Eigen::MatrixXd* VT);\n\n/**\n * A = U S U^T \n * A <- U\n * Full Symmetric EVD\n */\nvoid syev(Eigen::MatrixXd* A, Eigen::VectorXd* S);\n\n/**\n * x <- Q * x\n */\nvoid ormqr_notrans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);\n\n/**\n * x <- Q^T * x\n * A <- Q^T * A\n */\nvoid ormqr_trans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);\n\n/**\n * A <- A * Q\n * A <- A * Q^T\n * A <- Q * A\n * A <- Q^T * A\n */\nvoid ormqr(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A, char side, char trans);\n\n/**\n * Create the thin Q\n */\nvoid orgqr(Eigen::MatrixXd* v, Eigen::VectorXd* h);\n\n/** \n * Create a square Q\n */\n// void orgqr_fat(Eigen::MatrixXd* v, Eigen::VectorXd* h);\n\n/**\n * A = QR\n */\nvoid geqrf(Eigen::MatrixXd* A, Eigen::VectorXd* tau);\n\nint choose_rank(Eigen::VectorXd& s, double tol);\n\nstd::size_t hashv(std::vector vals);\n\n// Hash function for Eigen matrix and vector.\n// The code is from `hash_combine` function of the Boost library. See\n// http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine .\ntemplate\nstruct matrix_hash : std::unary_function {\n std::size_t operator()(T const& matrix) const {\n // Note that it is oblivious to the storage order of Eigen matrix (column- or\n // row-major). It will give you the same hash value for two different matrices if they\n // are the transpose of each other in different storage order.\n size_t seed = 0;\n for (size_t i = 0; i < matrix.size(); ++i) {\n auto elem = *(matrix.data() + i);\n seed ^= std::hash()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n return seed;\n }\n};\n\nvoid block2dense(Eigen::VectorXi &rowval, Eigen::VectorXi &colptr, Eigen::VectorXd &nnzval, int i, int j, int li, int lj, Eigen::MatrixXd *dst, bool transpose);\n\nEigen::MatrixXd linspace_nd(int n, int dim);\n\n// Returns A[p,p]\nSpMat symm_perm(SpMat &A, Eigen::VectorXi &p);\n\n// Random vector with seed\nEigen::VectorXd random(int size, int seed);\n\nEigen::MatrixXd random(int rows, int cols, int seed);\n\n// Set Eigen::MatrixXd to zero using memset\nvoid setZero(Eigen::MatrixXd* A);\n\n// Print vector\ntemplate\nstd::ostream& operator<<(std::ostream& os, const std::vector& v) {\n for(auto v_ : v) {\n os << v_ << \" \" ;\n }\n os << std::endl;\n return os;\n}\n\n// Range\ntemplate\nstruct ItRange\n{\n public:\n ItRange(const T& begin, const T& end) : begin_(begin), end_(end) {}\n const T& begin() const {\n return this->begin_;\n }\n const T& end() {\n return this->end_;\n }\n private:\n T begin_;\n T end_;\n};\n\n/**\n * Statistics and Logging\n **/\n\nstruct Profile {\n public:\n double elim;\n double scale;\n double spars;\n double merge;\n\n double elim_pivot;\n double elim_panel;\n double elim_schur;\n\n double scale_pivot;\n double scale_panel;\n\n double spars_assmb;\n double spars_spars;\n double spars_scatt;\n\n double merge_alloc;\n double merge_copy;\n\n double potf;\n double ldlt;\n double trsm;\n double gemm;\n double geqp3;\n double geqrf;\n double syev;\n double gesvd;\n double getf;\n\n double buildq;\n double scattq;\n double perma;\n double scatta;\n double assmb;\n double phi;\n\n Profile() :\n elim(0), scale(0), spars(0), merge(0), \n elim_pivot(0), elim_panel(0), elim_schur(0),\n scale_pivot(0), scale_panel(0), \n spars_assmb(0), spars_spars(0), spars_scatt(0),\n merge_alloc(0), merge_copy(0),\n potf(0), ldlt(0), trsm(0), gemm(0), geqp3(0), geqrf(0), syev(0), gesvd(0), getf(0),\n buildq(0), scattq(0), perma(0), scatta(0), assmb(0), phi(0)\n {}\n};\n\nstruct PivotFlops {\n long rows;\n double time;\n};\n\nstruct PanelFlops {\n long rows;\n long cols;\n double time;\n};\n\nstruct GemmFlops {\n long rows;\n long cols;\n long inner;\n double time;\n};\n\nstruct RRQRFlops {\n long rows;\n long cols;\n double time;\n};\n\nstruct ProfileFlops {\n public:\n std::vector pivot;\n std::vector panel;\n std::vector gemm;\n std::vector rrqr;\n ProfileFlops() {};\n};\n\ntemplate\nstruct Stats {\n private:\n T min;\n T max;\n T sum;\n int count;\n public:\n Stats(): min(std::numeric_limits::max()), max(std::numeric_limits::lowest()), sum(0), count(0) {};\n void addData(T value) {\n this->min = (this->min < value ? this->min : value);\n this->max = (this->max > value ? this->max : value);\n this->sum += value;\n this->count += 1;\n }\n T getMin() const { return this->count == 0 ? 0 : this->min; }\n T getMax() const { return this->count == 0 ? 0 : this->max; }\n double getMean() const { return ((double)this->sum)/((double)this->count); }\n int getCount() const { return this->count; }\n T getSum() const { return this->sum; }\n};\n\nstruct Log {\n public:\n int dofs_nd;\n int dofs_left_nd;\n int dofs_left_elim;\n int dofs_left_spars;\n long long int fact_nnz;\n Stats rank_before;\n Stats rank_after;\n int ignored;\n Stats nbrs;\n\n Stats cond_diag_elim;\n Stats norm_diag_elim;\n Stats cond_U_elim;\n Stats cond_L_elim;\n\n Stats cond_diag_scal;\n Stats norm_diag_scal;\n Stats cond_U_scal;\n Stats cond_L_scal;\n\n double Asym_before_scaling;\n double Asym_after_scaling; \n Stats Anorm_before_lower;\n Stats Anorm_before_upper;\n Stats Anorm_after_lower;\n Stats Anorm_after_upper;\n \n Log() :\n dofs_nd(0),\n dofs_left_nd(0), dofs_left_elim(0), dofs_left_spars(0),\n fact_nnz(0), ignored(0),\n Asym_before_scaling(0), Asym_after_scaling(0)\n {}\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "95b53703ddfb0466422ea81226558e9b07d77080", "size": 10074, "ext": "h", "lang": "C", "max_stars_repo_path": "include/util.h", "max_stars_repo_name": "leopoldcambier/spaND_public", "max_stars_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T21:17:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:56:30.000Z", "max_issues_repo_path": "include/util.h", "max_issues_repo_name": "leopoldcambier/spaND_public", "max_issues_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util.h", "max_forks_repo_name": "leopoldcambier/spaND_public", "max_forks_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-23T12:04:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-23T12:04:28.000Z", "avg_line_length": 24.8128078818, "max_line_length": 160, "alphanum_fraction": 0.5938058368, "num_tokens": 3051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4787211700076092}} {"text": "/* multifit/multiwlinear.c\n * \n * Copyright (C) 2015 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linear_common.c\"\n\nint\ngsl_multifit_wlinear (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n size_t rank;\n int status = gsl_multifit_wlinear_tsvd(X, w, y, GSL_DBL_EPSILON, c, cov, chisq, &rank, work);\n\n return status;\n}\n\nint\ngsl_multifit_wlinear_tsvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n const double tol,\n gsl_vector * c,\n gsl_matrix * cov,\n double * chisq,\n size_t * rank,\n gsl_multifit_linear_workspace * work)\n{\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (y->size != n)\n {\n GSL_ERROR(\"number of observations in y does not match matrix\",\n GSL_EBADLEN);\n }\n else if (w->size != n)\n {\n GSL_ERROR(\"number of weights in w does not match matrix\",\n GSL_EBADLEN);\n }\n else if (p != c->size)\n {\n GSL_ERROR (\"number of parameters c does not match matrix\",\n GSL_EBADLEN);\n }\n else if (tol <= 0)\n {\n GSL_ERROR (\"tolerance must be positive\", GSL_EINVAL);\n }\n else\n {\n int status;\n double rnorm, snorm;\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);\n\n /* compute A = sqrt(W) X, b = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);\n if (status)\n return status;\n\n /* compute SVD of A */\n status = gsl_multifit_linear_bsvd(&A.matrix, work);\n if (status)\n return status;\n\n status = multifit_linear_solve(X, &b.vector, tol, 0.0, rank,\n c, &rnorm, &snorm, work);\n if (status)\n return status;\n\n *chisq = rnorm * rnorm;\n\n /* variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */\n {\n const size_t p = X->size2;\n size_t i, j;\n gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p);\n gsl_vector_view D = gsl_vector_subvector(work->D, 0, p);\n\n for (i = 0; i < p; i++)\n {\n gsl_vector_view row_i = gsl_matrix_row (&QSI.matrix, i);\n double d_i = gsl_vector_get (&D.vector, i);\n\n for (j = i; j < p; j++)\n {\n gsl_vector_view row_j = gsl_matrix_row (&QSI.matrix, j);\n double d_j = gsl_vector_get (&D.vector, j);\n double s;\n\n gsl_blas_ddot (&row_i.vector, &row_j.vector, &s);\n\n gsl_matrix_set (cov, i, j, s / (d_i * d_j));\n gsl_matrix_set (cov, j, i, s / (d_i * d_j));\n }\n }\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_multifit_wlinear_svd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n int status = gsl_multifit_wlinear_tsvd(X, w, y, tol, c, cov, chisq, rank, work);\n return status;\n}\n\nint\ngsl_multifit_wlinear_usvd (const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n double tol,\n size_t * rank,\n gsl_vector * c,\n gsl_matrix * cov,\n double *chisq, gsl_multifit_linear_workspace * work)\n{\n /* FIXME: this call does actually perform balancing, but this function is deprecated anyway */\n int status = gsl_multifit_wlinear_tsvd(X, w, y, tol, c, cov, chisq, rank, work);\n return status;\n}\n", "meta": {"hexsha": "1f10684f203d90aac4ec57ed48519023d3b446d6", "size": 5118, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/multiwlinear.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/multifit/multiwlinear.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/multifit/multiwlinear.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.1886792453, "max_line_length": 96, "alphanum_fraction": 0.544353263, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4781708904379278}} {"text": "#include \"gemm.h\"\n#if defined(USE_BLAS)\n#include \n#else\n// see https://github.com/pjreddie/darknet/blob/master/src/gemm.c\n\nstatic void gemm_nn(int M, int N, int K, float ALPHA,\n float *A, int lda,\n float *B, int ldb,\n float *C, int ldc)\n{\n int i;\n #pragma omp parallel for\n for (i = 0; i < M; ++i)\n {\n int j, k;\n for (k = 0; k < K; ++k)\n {\n float A_PART = ALPHA * A[i * lda + k];\n for (j = 0; j < N; ++j)\n {\n C[i * ldc + j] += A_PART * B[k * ldb + j];\n }\n }\n }\n}\n\nstatic void gemm_nt(int M, int N, int K, float ALPHA,\n float *A, int lda,\n float *B, int ldb,\n float *C, int ldc)\n{\n int i;\n #pragma omp parallel for\n for (i = 0; i < M; ++i)\n {\n int j, k;\n for (j = 0; j < N; ++j)\n {\n float sum = 0;\n for (k = 0; k < K; ++k)\n {\n sum += ALPHA * A[i * lda + k] * B[j * ldb + k];\n }\n C[i * ldc + j] += sum;\n }\n }\n}\n\nstatic void gemm_tn(int M, int N, int K, float ALPHA,\n float *A, int lda,\n float *B, int ldb,\n float *C, int ldc)\n{\n int i;\n #pragma omp parallel for\n for (i = 0; i < M; ++i)\n {\n int j, k;\n for (k = 0; k < K; ++k)\n {\n float A_PART = ALPHA * A[k * lda + i];\n for (j = 0; j < N; ++j)\n {\n C[i * ldc + j] += A_PART * B[k * ldb + j];\n }\n }\n }\n}\n\nstatic void gemm_tt(int M, int N, int K, float ALPHA,\n float *A, int lda,\n float *B, int ldb,\n float *C, int ldc)\n{\n int i;\n #pragma omp parallel for\n for (i = 0; i < M; ++i)\n {\n int j, k;\n for (j = 0; j < N; ++j)\n {\n float sum = 0;\n for (k = 0; k < K; ++k)\n {\n sum += ALPHA * A[i + k * lda] * B[k + j * ldb];\n }\n C[i * ldc + j] += sum;\n }\n }\n}\n#endif\n\nvoid gemm(int TA, int TB, int M, int N, int K, float ALPHA,\n data_val_t **A, int offa, int lda,\n data_val_t **B, int offb, int ldb,\n float BETA,\n data_val_t **C, int offc, int ldc)\n{\n#if defined(USE_BLAS)\n cblas_sgemm(\n CblasRowMajor,\n TA ? CblasTrans : CblasNoTrans,\n TB ? CblasTrans : CblasNoTrans,\n M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, BETA, *C + offc, ldc);\n#else\n int i, j;\n for (i = 0; i < M; ++i)\n {\n for (j = 0; j < N; ++j)\n {\n (*C + offc)[i * ldc + j] *= BETA;\n }\n }\n if (!TA && !TB)\n gemm_nn(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc);\n else if (TA && !TB)\n gemm_tn(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc);\n else if (!TA && TB)\n gemm_nt(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc);\n else\n gemm_tt(M, N, K, ALPHA, *A + offa, lda, *B + offb, ldb, *C + offc, ldc);\n#endif\n}\n", "meta": {"hexsha": "709666ac616b354fa5dd876dd41a07c4e8d21926", "size": 3179, "ext": "c", "lang": "C", "max_stars_repo_path": "core/gemm.c", "max_stars_repo_name": "yang-le/cnet", "max_stars_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T13:57:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-05T05:07:24.000Z", "max_issues_repo_path": "core/gemm.c", "max_issues_repo_name": "yang-le/cnet", "max_issues_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-28T14:40:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-01T14:52:50.000Z", "max_forks_repo_path": "core/gemm.c", "max_forks_repo_name": "yang-le/cnet", "max_forks_repo_head_hexsha": "cc946f7d891248442009f62061c144c3e9f70f9c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.432, "max_line_length": 80, "alphanum_fraction": 0.3916325889, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4780356432825999}} {"text": "/* ----------------------------------------------------------------------------\n JAM_AXI_VEL_WMMT\n \n Calculates weighted first moments.\n \n INPUTS\n xp : projected x' [pc]\n yp : projected y' [pc]\n nxy : number of x' and y' values given\n incl : inclination [radians]\n lum : projected luminous MGE\n pot : projected potential MGE\n beta : velocity anisotropy (1 - vz^2 / vr^2)\n kappa : rotation parameter\n \n NOTES\n * Based on janis1_weighted_first_moment IDL code by Michele Cappellari.\n \n Laura L Watkins [lauralwatkins@gmail.com]\n \n This code is released under a BSD 2-clause license.\n If you use this code for your research, please cite:\n Watkins et al. 2013, MNRAS, 436, 2598\n \"Discrete dynamical models of omega Centauri\"\n http://adsabs.harvard.edu/abs/2013MNRAS.436.2598W\n---------------------------------------------------------------------------- */\n\n#include \n#include \n#include \n#include \n#include \n#include \"jam.h\"\n#include \"../mge/mge.h\"\n#include \"../tools/tools.h\"\n\n\ndouble** jam_axi_vel_wmmt( double *xp, double *yp, int nxy, double incl, \\\n struct multigaussexp *lum, struct multigaussexp *pot, \\\n double *beta, double *kappa, int *gslFlag_vel ) {\n \n struct params_losint lp;\n struct multigaussexp ilum, ipot;\n double *bani, *s2l, *q2l, *s2q2l, *s2p, *e2p;\n double *iz0, *iz1;\n double lim, result, error, si, ci, trpig, **sb_mu1;\n int i;\n size_t neval;\n int status = 0, *gslFlag;\n int TadejaVar = 0; gslFlag = &TadejaVar;\n \n // ---------------------------------\n \n // MGE parameters for inner integrand function\n \n // convert from projected MGEs to intrinsic MGEs\n ilum = mge_deproject( lum, incl );\n ipot = mge_deproject( pot, incl );\n \n // calculate useful quantities\n bani = (double *) malloc( ilum.ntotal * sizeof( double ) );\n s2l = (double *) malloc( ilum.ntotal * sizeof( double ) );\n q2l = (double *) malloc( ilum.ntotal * sizeof( double ) );\n s2q2l = (double *) malloc( ilum.ntotal * sizeof( double ) );\n s2p = (double *) malloc( ipot.ntotal * sizeof( double ) );\n e2p = (double *) malloc( ipot.ntotal * sizeof( double ) );\n \n for ( i = 0; i < ilum.ntotal; i++ ) {\n bani[i] = 1. / ( 1. - beta[i] );\n s2l[i] = pow( ilum.sigma[i], 2 );\n q2l[i] = pow( ilum.q[i], 2 );\n s2q2l[i] = s2l[i] * q2l[i];\n }\n \n for ( i = 0; i < ipot.ntotal; i++ ) {\n s2p[i] = pow( ipot.sigma[i], 2 );\n e2p[i] = 1. - pow( ipot.q[i], 2 );\n }\n \n // parameters for integrand function\n lp.incl = incl;\n lp.lum = &ilum;\n lp.pot = &ipot;\n lp.bani = bani;\n lp.s2l = s2l;\n lp.q2l = q2l;\n lp.s2q2l = s2q2l;\n lp.s2p = s2p;\n lp.e2p = e2p;\n lp.kappa = kappa;\n lp.gslFlag_losint = gslFlag;\n \n // ---------------------------------\n \n // set up integration\n gsl_integration_workspace *w = gsl_integration_workspace_alloc( 1000 );\n gsl_integration_cquad_workspace *ww = gsl_integration_cquad_workspace_alloc(1000);\n gsl_function F;\n F.function = &jam_axi_vel_losint;\n\n // trig angles\n si = sin( incl );\n ci = cos( incl );\n \n // outer limit of integration\n lim = 4. * maximum( ilum.sigma, ilum.ntotal );\n \n iz0 = (double *) malloc( nxy * sizeof( double ) );\n iz1 = (double *) malloc( nxy * sizeof( double ) );\n for ( i = 0; i < nxy; i++ ) {\n \n // parameters for integrand function\n lp.xp = xp[i];\n lp.yp = yp[i];\n \n // do z^0 integral\n lp.zpow = 0.;\n F.function = &jam_axi_vel_losint;\n F.params = &lp;\n gsl_integration_cquad(&F, -lim, lim, 0., 1e-4, ww, &result,\n &error, &neval);\n iz0[i] = result;\n \n // do z^1 integral\n lp.zpow = 1.;\n F.function = &jam_axi_vel_losint;\n F.params = &lp;\n gsl_set_error_handler_off(); \n status += gsl_integration_qag( &F, -lim, lim, 1., 1., 1000, 2, w,\n &result, &error ); \n /* uncomment these two lines for testing\n int test = 1;// Tadeja\n status += test; // Tadeja\n */\n if (status > 0 && *gslFlag<20) { // the limiting value is very arbitrary\n *gslFlag_vel += 1; }\n\n if (status > 0 && *gslFlag>=20) { // the limiting value is very arbitrary so that the values do not exceed allowed size for integers\n *gslFlag_vel -= 1; }\n *gslFlag_vel += *gslFlag; // if there was an integration error in losint\n\n if ( fabs( result ) > 1e-6 ) {\n gsl_integration_cquad(&F, -lim, lim, 0., 1e-3, ww, &result,\n &error, &neval);\n }\n iz1[i] = result;\n }\n \n // tidy up\n gsl_integration_workspace_free( w );\n gsl_integration_cquad_workspace_free(ww);\n \n // ---------------------------------\n \n sb_mu1 = (double **) malloc( nxy * sizeof( double* ) );\n for ( i = 0; i < nxy; i++ ) \\\n sb_mu1[i] = (double *) malloc( 3 * sizeof( double ) );\n \n // calculate for each velocity component\n trpig = 2. * sqrt( M_PI * G );\n for ( i = 0; i < nxy; i++ ) {\n sb_mu1[i][0] = trpig * ( yp[i] * ci * iz0[i] - si * iz1[i] );\n sb_mu1[i][1] = -trpig * xp[i] * ci * iz0[i];\n sb_mu1[i][2] = trpig * xp[i] * si * iz0[i];\n }\n \n // ---------------------------------\n \n free( bani );\n free( s2l );\n free( q2l );\n free( s2q2l );\n free( s2p );\n free( e2p );\n \n free( iz0 );\n free( iz1 );\n \n return sb_mu1;\n \n}\n", "meta": {"hexsha": "9c3f175ada10b110e4df101e405dac262bbb4ef7", "size": 5660, "ext": "c", "lang": "C", "max_stars_repo_path": "src/jam/jam_axi_vel_wmmt.c", "max_stars_repo_name": "tadejaversic/cjam", "max_stars_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/jam/jam_axi_vel_wmmt.c", "max_issues_repo_name": "tadejaversic/cjam", "max_issues_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "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/jam/jam_axi_vel_wmmt.c", "max_forks_repo_name": "tadejaversic/cjam", "max_forks_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0989010989, "max_line_length": 140, "alphanum_fraction": 0.521024735, "num_tokens": 1763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.47789137583271313}} {"text": "#ifndef __CNN_FC_H__\n#define __CNN_FC_H__\n\n#include \n\n#include \"cnn_types.h\"\n\n#ifdef CNN_WITH_CUDA\n#include \n#include \n\n#include \"cnn_init.h\"\n#endif\n\nstatic inline void cnn_forward_fc(union CNN_LAYER* layerRef,\n struct CNN_CONFIG* cfgRef, int layerIndex)\n{\n#ifdef CNN_WITH_CUDA\n float alpha = 1.0;\n float beta = 0.0;\n\n struct CNN_LAYER_FC* layerPtr = &layerRef[layerIndex].fc;\n\n struct CNN_MAT* wPtr = &layerPtr->weight;\n struct CNN_MAT* outData = &layerPtr->outMat.data;\n struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;\n\n // Weight matrix multiplication\n cnn_assert_cublas(cublasSgemm( //\n cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_N, //\n outData->cols, cfgRef->batch, preOutData->cols, //\n &alpha, //\n wPtr->mat, wPtr->cols, //\n preOutData->mat, preOutData->cols, //\n &beta, //\n outData->mat, outData->cols));\n\n // Add bias\n beta = 1.0;\n cnn_assert_cudnn(cudnnAddTensor(cnnInit.cudnnHandle, //\n &alpha, //\n layerPtr->biasTen, layerPtr->bias.mat, //\n &beta, //\n layerPtr->dstTen, outData->mat));\n#else\n // Weight matrix multiplication\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n layerRef[layerIndex - 1].outMat.data.rows,\n layerRef[layerIndex].outMat.data.cols,\n layerRef[layerIndex - 1].outMat.data.cols, 1.0,\n layerRef[layerIndex - 1].outMat.data.mat,\n layerRef[layerIndex - 1].outMat.data.cols,\n layerRef[layerIndex].fc.weight.mat,\n layerRef[layerIndex].fc.weight.cols, 0.0,\n layerRef[layerIndex].outMat.data.mat,\n layerRef[layerIndex].outMat.data.cols);\n\n // Add bias\n for (int j = 0; j < cfgRef->batch; j++)\n {\n int dstIndex = j * layerRef[layerIndex].outMat.data.cols;\n cblas_saxpy(layerRef[layerIndex].fc.bias.cols, 1.0,\n layerRef[layerIndex].fc.bias.mat, 1,\n &layerRef[layerIndex].outMat.data.mat[dstIndex], 1);\n }\n#endif\n}\n\nstatic inline void cnn_backward_fc(union CNN_LAYER* layerRef,\n struct CNN_CONFIG* cfgRef, int layerIndex)\n{\n#ifdef CNN_WITH_CUDA\n float alpha = 1.0;\n float beta = 1.0;\n\n struct CNN_LAYER_FC* layerPtr = &layerRef[layerIndex].fc;\n\n struct CNN_MAT* wPtr = &layerPtr->weight;\n struct CNN_MAT* outData = &layerPtr->outMat.data;\n struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;\n\n // Sum weight gradient matrix\n cnn_assert_cublas( //\n cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_N, CUBLAS_OP_T, //\n wPtr->cols, wPtr->rows, cfgRef->batch, //\n &alpha, //\n outData->grad, outData->cols, //\n preOutData->mat, preOutData->cols, //\n &beta, //\n wPtr->grad, wPtr->cols));\n\n // Sum bias gradient matrix\n if (cfgRef->batch > 1)\n {\n cnn_assert_cudnn(\n cudnnReduceTensor(cnnInit.cudnnHandle, layerPtr->reduDesc,\n layerPtr->indData, layerPtr->indSize, //\n cnnInit.wsData, cnnInit.wsSize, //\n &alpha, //\n layerPtr->dstTen, outData->grad, //\n &beta, //\n layerPtr->biasTen, layerPtr->bias.grad));\n }\n else\n {\n cnn_assert_cublas( //\n cublasSaxpy(cnnInit.blasHandle, layerPtr->bias.cols, //\n &alpha, //\n outData->grad, 1, //\n layerPtr->bias.grad, 1));\n }\n#else\n // Sum weight gradient matrix\n cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans,\n layerRef[layerIndex].fc.weight.rows,\n layerRef[layerIndex].fc.weight.cols, cfgRef->batch, 1.0,\n layerRef[layerIndex - 1].outMat.data.mat,\n layerRef[layerIndex - 1].outMat.data.cols,\n layerRef[layerIndex].outMat.data.grad,\n layerRef[layerIndex].outMat.data.cols, 1.0,\n layerRef[layerIndex].fc.weight.grad,\n layerRef[layerIndex].fc.weight.cols);\n\n // Sum bias gradient matrix\n for (int j = 0; j < cfgRef->batch; j++)\n {\n int srcShift = j * layerRef[layerIndex].outMat.data.cols;\n cblas_saxpy(layerRef[layerIndex].fc.bias.cols, 1.0,\n &layerRef[layerIndex].outMat.data.grad[srcShift], 1,\n layerRef[layerIndex].fc.bias.grad, 1);\n }\n#endif\n\n // Find layer gradient\n if (layerIndex > 1)\n {\n#ifdef CNN_WITH_CUDA\n beta = 0.0;\n cnn_assert_cublas( //\n cublasSgemm(cnnInit.blasHandle, CUBLAS_OP_T, CUBLAS_OP_N, //\n wPtr->rows, cfgRef->batch, wPtr->cols, //\n &alpha, //\n wPtr->mat, wPtr->cols, //\n outData->grad, outData->cols, //\n &beta, //\n preOutData->grad, preOutData->cols));\n#else\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,\n layerRef[layerIndex - 1].outMat.data.rows,\n layerRef[layerIndex - 1].outMat.data.cols,\n layerRef[layerIndex].outMat.data.cols, 1.0,\n layerRef[layerIndex].outMat.data.grad,\n layerRef[layerIndex].outMat.data.cols,\n layerRef[layerIndex].fc.weight.mat,\n layerRef[layerIndex].fc.weight.cols, 0.0,\n layerRef[layerIndex - 1].outMat.data.grad,\n layerRef[layerIndex - 1].outMat.data.cols);\n#endif\n }\n}\n\n#endif\n", "meta": {"hexsha": "23386098bc4bdffd4ffdd51c73acd759d22341c5", "size": 6701, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cnn_fc.h", "max_stars_repo_name": "jamesljlster/cnn", "max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z", "max_issues_repo_path": "src/cnn_fc.h", "max_issues_repo_name": "jamesljlster/cnn", "max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "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/cnn_fc.h", "max_forks_repo_name": "jamesljlster/cnn", "max_forks_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "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": 41.1104294479, "max_line_length": 78, "alphanum_fraction": 0.4829129981, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4776974935356108}} {"text": "//This involves multiplication of two vectors. \n\n\n#include \n#include \n\n void vector_mul(double* a, double *b, double *c, size_t size)\n{\n\tint i;\n \tgsl_vector * a_vec = gsl_vector_alloc (size);\n\tgsl_vector * b_vec = gsl_vector_alloc (size);\n\tgsl_vector * c_vec = gsl_vector_alloc (size);\n \tfor (i = 0; i < size; i++)\n {\n \tgsl_vector_set (a_vec, i, a[i]);\n\t\tgsl_vector_set (b_vec, i, b[i]);\n }\n\tgsl_vector_mul(a_vec,b_vec);\n\tgsl_vector_memcpy(c_vec, a_vec);\n \tfor (i = 0; i < size; i++) /* OUT OF RANGE ERROR */\n {\n\t\tc[i] = gsl_vector_get (c_vec, i);\n \tprintf (\"v_%d = %g\\n\", i, gsl_vector_get (c_vec, i));\n }\n\n \tgsl_vector_free (a_vec);\n\tgsl_vector_free (b_vec);\n\tgsl_vector_free (c_vec);\n}\n\n/*\n//The main function has been provided solely for the sake of testing the function. It will be removed when the problem set is formally passed on.\nint main (void)\n{\n\tdouble a[5] = {1.0, 2.0, 3.0, 4.0, 5.0};\n\tdouble b[5] = {0.1, 0.2, 0.3, 0.4, 0.5};\t\n\tdouble *c;\n\tvector_mul(a, b, c, 5);\n\treturn 0;\n}*/\n", "meta": {"hexsha": "96cd57c10c58d765a04399ca70667391c73670cf", "size": 1047, "ext": "c", "lang": "C", "max_stars_repo_path": "Resources/Include/p4.c", "max_stars_repo_name": "RITUait/OpenModelica", "max_stars_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-03T04:23:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:23:39.000Z", "max_issues_repo_path": "TestSample/Resources/Include/p4.c", "max_issues_repo_name": "RITUait/OpenModelica", "max_issues_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "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": "TestSample/Resources/Include/p4.c", "max_forks_repo_name": "RITUait/OpenModelica", "max_forks_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e", "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.5365853659, "max_line_length": 145, "alphanum_fraction": 0.6332378223, "num_tokens": 356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47766026536265915}} {"text": "#define _XOPEN_SOURCE 600\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"fileio.h\"\n#include \"likelihood.h\"\n#include \"master_tasks.h\"\n#include \"mutation.h\"\n#include \"radix.h\"\n#include \"randomisation.h\"\n#include \"resampling.h\"\n#include \"typedefs.h\"\n\nstatic const int ALG = 6;\nstatic const int MASTER = 0;\n\nint \nmain (\n int argc, \n char *argv[]) \n{\n\n struct Process process;\n struct Estimates estimates;\n int pair_rank, src;\n int do_resampling;\n long *inds;\n double *w, *x, *x_resamp;\n double total_w = 1;\n double my_normal_weight;\n double w_pair[2];\n double rsamp_time=0;\n double rsamp_start=0;\n double comm_time=0;\n double comm_start;\n double comm_time2=0;\n double *output;\n double weight_time = 0;\n double mutation_time = 0.0;\n double init_time = 0.0;\n unsigned int cnts[2];\n short counts[2];\n short n_resamp;\n \n const gsl_rng_type * T;\n double timer_start;\n\n // Parse commandline arguments\n int run_idx = 0;\n if ( argc > 1 )\n run_idx = atoi( argv[ 1 ] );\n\n long N = 1000;\n if ( argc > 2 )\n N = atol( argv[ 2 ] );\n\n int state_dim;\n if ( argc > 3 ) \n state_dim = atoi( argv[ 3 ] );\n else {\n perror(\"State dimesion must be provided\");\n return -1;\n }\n\n double epc_threshold;\n if (argc > 4 ) {\n epc_threshold = atof( argv[ 4 ] );\n } else {\n perror(\"Reampling threshold must be provided\");\n return -1;\n }\n\n // Initialize the MPI environment\n MPI_Init(NULL, NULL);\n \n gsl_rng_env_setup();\n T = gsl_rng_default;\n gsl_rng *rgen;\n rgen = gsl_rng_alloc( T );\n \n // Get the number of processes\n int world_size;\n MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n \n // Get the rank of the process\n int world_rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n // Start the timer\n struct timespec start_time;\n clock_gettime(CLOCK_REALTIME, &start_time);\n \n MPI_Barrier( MPI_COMM_WORLD );\n timer_start = MPI_Wtime();\n\n long data_length;\n process = readProcessFile( state_dim );\n data_length = (int)process.n;\n \n // Construct the communication hypercube\n MPI_Comm nthCube;\n int hc_rank;\n int nDim;\n constructHypercube( world_size, &nthCube, &hc_rank, &nDim );\n int S = nDim;\n\n //---------------\n // Initialisation\n //---------------\n x = malloc( sizeof( double ) * N * state_dim ); \n w = malloc( sizeof( double ) * N );\n\n inds = malloc( sizeof( long ) * N );\n x_resamp = malloc( sizeof( double ) * N * state_dim );\n \n // Initial distribution setup\n setupInitialSeed( world_rank, rgen );\n\n // Create initial sample\n createInitialSample( x, N, rgen, state_dim );\n \n // Setup the randomisation\n set_resamplingseed( world_rank );\n\n int output_dim = 2 + state_dim + 2 * world_size + world_size * state_dim;\n if ( world_rank == MASTER )\n output = malloc( sizeof( double ) * output_dim * data_length );\n \n my_normal_weight = 1.0 / world_size;\n \n MPI_Barrier( MPI_COMM_WORLD );\n init_time += MPI_Wtime() - timer_start;\n\n // main loop\n for( long n = 0; n < data_length; n++ ) {\n\n // ------------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n timer_start = MPI_Wtime();\n\n evaluateLikelihoods( x, process, state_dim, data_length, N, n, w, \n\t\t\t my_normal_weight ); \n \n MPI_Barrier( MPI_COMM_WORLD );\n weight_time += MPI_Wtime() - timer_start ;\n\n // Compute the relevant estimates for THIS filter only\n estimates = estimateOutput( w, x, world_rank, N, run_idx, state_dim );\n \n // Combine the results of all filters\n combineEstimates( world_rank, state_dim, estimates, output, n, \n\t\t output_dim, world_size, &total_w, &my_normal_weight, \n\t\t &do_resampling, epc_threshold);\n \n // -----------------------------\n // RESAMPLING\n // -----------------------------\n\n // Resampling within processors\n\n MPI_Barrier( MPI_COMM_WORLD );\n rsamp_start = MPI_Wtime();\n \n serial_multinomial_resample_sng_noutk( N, w, inds, N );\n \n for ( long i = 0; i < N; i++)\n for ( int d = 0; d < state_dim; d++ ) \n\tx_resamp[ state_dim * i + d ] = x[ state_dim * inds[ i ] + d ];\n\n for ( long i = 0; i < N; i++)\n for ( int d = 0; d < state_dim ; d++ ) \n\tx[ state_dim * i + d ] = x_resamp[ state_dim * i + d ];\n \n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n rsamp_time += MPI_Wtime() - rsamp_start;\n comm_start = MPI_Wtime();\n \n if ( do_resampling ) {\n\n // ---------------------------\n // START THE RADIX INTERACTION\n // ---------------------------\n \n for ( int s = 0; s < S ; s++ ) {\n \n\t// Determine the process you need to communicate with\n\tMPI_Cart_shift( nthCube, s, 1, &src, &pair_rank );\n\t\n\t// The lower ranking process in the pair gets the filter weights and\n\t// does the island level resampling \n\tif ( hc_rank < pair_rank ) {\n\t \n\t MPI_Recv( w_pair + 1, 1, MPI_DOUBLE, pair_rank, 0, nthCube, \n\t\t MPI_STATUS_IGNORE );\n\t \n\t // The lower ranking filter must send its weight to the paired filter \n\t // so that the paired filter can update its weight\n\t MPI_Send( &my_normal_weight, 1, MPI_DOUBLE, pair_rank, 1, nthCube ); \n\t \n\t w_pair[ 0 ] = my_normal_weight;\n\t \n\t // Generate a binomial random variate indicating how many samples \n\t // are drawn from each of the paired processes.\n\t gsl_ran_multinomial( rgen , ( size_t ) 2, ( unsigned int ) ( 2 ), w_pair, \n\t\t\t cnts );\n\n\t counts[ 0 ] = ( short ) cnts[ 0 ];\n\t counts[ 1 ] = ( short ) cnts[ 1 ]; \n\t \n\t // Send the resampling counts to the paired process\n\t MPI_Send( counts + 1 , 1, MPI_SHORT, pair_rank, 3, nthCube );\n\t \n\t n_resamp = counts[ 0 ];\n\t \n\t} else { \n\t \n\t // Send my weight to the lower ranking filter in the pair\n\t MPI_Send(&my_normal_weight, 1, MPI_DOUBLE, pair_rank, 0, nthCube );\n\t \n\t // Receive the weight of the paired filter\n\t MPI_Recv( w_pair, 1, MPI_DOUBLE, pair_rank, 1, nthCube, MPI_STATUS_IGNORE );\n\t \n\t // Receive the duplicate count ( 0 or 1 )\n\t MPI_Recv( &n_resamp, 1, MPI_SHORT, pair_rank, 3, nthCube, MPI_STATUS_IGNORE );\n\t \n\t w_pair[ 1 ] = my_normal_weight;\n\t \n\t}\n\t\n\t// ----------------------------------------------------------------------------- \n\tMPI_Barrier( MPI_COMM_WORLD );\n\tcomm_time2 += MPI_Wtime() - comm_start;\n\tcomm_start = MPI_Wtime();\n\t\n\t// Balance the resampled particle counts\n\tif ( n_resamp > 1 ) {\n\t \n\t // Send the surplus particles, i.e. the last n_resamp - N of the \n\t // resampled particles\n\t MPI_Send( x, N * state_dim , MPI_DOUBLE, pair_rank, 2, nthCube );\n\t \n\t} else if ( n_resamp < 1 ) { \n\t \n\t // Receive compensation for shortage\n\t MPI_Recv( x, N * state_dim, MPI_DOUBLE, pair_rank, 2, nthCube, \n\t\t MPI_STATUS_IGNORE );\n\t \n\t}\n\t\n\tmy_normal_weight = ( w_pair[ 0 ] + w_pair[ 1 ] ) / (double ) 2;\n }\n\n }\n \n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n comm_time += MPI_Wtime() - comm_start;\n timer_start = MPI_Wtime();\n\n mutation(N, x, state_dim, rgen);\n \n // -----------------------------------------------------------------------------\n MPI_Barrier( MPI_COMM_WORLD );\n mutation_time += MPI_Wtime() - timer_start ;\n\n }\n \n\n struct timespec end_time;\n clock_gettime(CLOCK_REALTIME, &end_time);\n \n createOutput( ALG, world_rank, output, data_length, world_size,\n\t\trun_idx, N, state_dim, start_time, end_time, comm_time, rsamp_time,\n\t\tcomm_time2, weight_time, mutation_time, init_time, \n\t\t(int)( atof( argv[ 4 ] ) * 100 ) );\n \n // Finalize the MPI environment.\n MPI_Finalize();\n \n return 0;\n}\n", "meta": {"hexsha": "aa857326d592b833b71d88626808d7feb31024a0", "size": 7756, "ext": "c", "lang": "C", "max_stars_repo_path": "src/airpf1.c", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "src/airpf1.c", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/airpf1.c", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7448275862, "max_line_length": 85, "alphanum_fraction": 0.5946364105, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.47742642497014287}} {"text": "// ******************** Functions for segSiteHMM\n\n\n#include \"stdio.h\"\n#include \"math.h\"\n#include \"segSites.h\"\n#include \"../hmm/popGenTools.h\"\n#include \"../hmm/numerical.h\"\n#include \"assert.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n//core function for probs\ndouble my_h(double q, void * p){\n struct my_f_params * params = (struct my_f_params *) p;\n double beta = params->beta;\n int i = params->i;\n int n = params->n;\n\t\n return ((1.0 - exp(-2.0 * beta * (1.0 - q))) / (1.0 - exp(-2.0 * beta))) \\\n * (2.0 / (q * (1.0 - q))) * gsl_ran_binomial_pdf(i, q, n);\n}\n\n\n\n/* integral of f over allele freq -- returns Prob(Segsite | mu, beta) */\ndouble my_H(gsl_vector *pVector, void * p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_f_params fParams;\n gsl_function f;\n gsl_integration_workspace * w;\n double result,error;\n \n if (gsl_vector_get(pVector, 0) == 0){\n return gsl_vector_get(pVector, 1) / params->i;\n }\n else{\n w = gsl_integration_workspace_alloc (100000);\n fParams.beta = gsl_vector_get(pVector, 0);\n fParams.i = params->i;\n fParams.n = params->n;\n f.function = &(my_h);\n f.params = &fParams;\n gsl_integration_qags(&f,0.0,1.0,1e-5,1e-5, 100000,w, &result,&error);\n gsl_integration_workspace_free(w);\n return result * gsl_vector_get(pVector,1); \n }\n}\n\n/* siteProbMatrix- fills up a matrix of log siteProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\n variable sampleSizes (2 to max), columns represent freqs (0 to max -1), freq 0 is for monomorphic sites */\nvoid siteProbMatrix(gsl_matrix *probs, gsl_vector *pVector, int maxSampleSize, gsl_vector *sampleSizeVector){\n struct my_snpProb_params FParams;\n int i, j;\n double tot, prob;\n \n //check & init probs\n assert(probs->size1 == maxSampleSize + 1 && probs->size2 == maxSampleSize);\n gsl_matrix_set_zero(probs);\n \n //go through sampleSizes\n for(i = 2; i <= maxSampleSize; i++){\n //have sample size i?\n if (gsl_vector_get(sampleSizeVector, i)){\n //set tot to zero for p{monomorphic}\n tot = 0;\n //go through freqs\n for(j = 1; j < maxSampleSize; j++){\n\t//calc prob\n\tprob = 0;\n\tFParams.i = j;\n\tFParams.n = i;\n\t//need to impose constraint that p{SegSite = 0 | theta < 0}\n\tif(gsl_vector_get(pVector,1) < 0){\n\t prob = 0;\n\t}\n\telse{\n\t prob = my_H(pVector, &FParams);\n\t}\n\tgsl_matrix_set(probs, i, j, log(prob));\n\ttot += prob;\n }\n //set p{monomorphic}\n gsl_matrix_set(probs,i, 0, log(1.0 - tot));\n }\n }\n}\n\ndouble weightedLikLookSites(gsl_vector *pVector, void * p){\n struct my_jointLik_params * params = (struct my_jointLik_params *) p;\n gsl_matrix *probs;\n double lik;\n int i;\n\t\n //make prob matrix (log space)\n probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize);\n siteProbMatrix(probs, pVector, params->maxSampleSize, params->sampleSizeVector);\n\n //tally likelihood\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);\n }\n gsl_matrix_free(probs);\n return -lik;\n}\n// weightedLikLookSites2State -- for use in 2 state HMM\ndouble weightedLikLookSites2State(gsl_vector *pVector, void * p){\n struct my_jointLik_params * params = (struct my_jointLik_params *) p;\n gsl_matrix *probs, *probsN;\n gsl_vector *npVector;\n double lik;\n int i;\n \n //setup neutral params\n npVector = gsl_vector_alloc(2);\n gsl_vector_set(npVector,0,0);\n gsl_vector_set(npVector,1,gsl_vector_get(pVector,1));\n\n //alloc & make probs and probsN matrix (log space)\n probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize);\n siteProbMatrix(probs, pVector, params->maxSampleSize, params->sampleSizeVector);\n probsN = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize);\n siteProbMatrix(probsN,npVector, params->maxSampleSize, params->sampleSizeVector);\n\n //tally likelihood\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);\n lik += gsl_matrix_get(probsN,params->data[i].n,params->data[i].i) * (1.0 - gsl_vector_get(params->weights,i));\n }\n gsl_matrix_free(probs);\n gsl_matrix_free(probsN);\n gsl_vector_free(npVector);\n return -lik;\n}\n\n\ngsl_vector *jointMLEst(double *lik, void * p){\n size_t np = 2;\n struct my_jointLik_params * params = (struct my_jointLik_params *) p;\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;\n gsl_multimin_fminimizer *s = NULL;\n gsl_multimin_function minex_func;\n gsl_vector *ss, *x, *results;\n\n size_t iter = 0, i;\n int status;\n double size;\n\n /* Initial vertex size vector */\n ss = gsl_vector_alloc (np);\n //initialize results vector\n results = gsl_vector_alloc (np);\n /* Set all step sizes to 1 */\n gsl_vector_set_all (ss, 0.01);\n \n /* Starting point */\n x = gsl_vector_alloc (np);\n gsl_vector_set (x, 0, gsl_vector_get(params->startingPoint,0));\n gsl_vector_set (x, 1, gsl_vector_get(params->startingPoint,1));\n \n /* Initialize method and iterate */\n minex_func.f = &weightedLikLookSites2State;\n minex_func.n = np;\n minex_func.params = params;\n \n s = gsl_multimin_fminimizer_alloc (T, np);\n gsl_multimin_fminimizer_set (s, &minex_func, x, ss);\n\n do\n {\n iter++;\n status = gsl_multimin_fminimizer_iterate(s);\n if (status)\n\tbreak;\n size = gsl_multimin_fminimizer_size (s);\n status = gsl_multimin_test_size (size, 1e-3);\n }\n while (status == GSL_CONTINUE && iter < 500);\n for (i = 0; i < np; i++){\n gsl_vector_set(results,i,gsl_vector_get (s->x, i));\n }\n gsl_vector_free(ss);\n gsl_multimin_fminimizer_free (s);\n return(results);\n}\n\n// weightedLikLookSitesNState -- for use in n state HMM\n// pVector now consists of n parameters, not just two\n// pVector = [theta_hat, beta_hat_1, beta_hat_2,\ndouble weightedLikLookSitesNState(gsl_vector *pVector, void * p){\n struct my_jointLik_params * params = (struct my_jointLik_params *) p;\n gsl_matrix *probs;\n gsl_vector *currentVector;\n double lik;\n int i,j;\n \n //setup neutral params\n currentVector = gsl_vector_alloc(params->nstates);\n gsl_vector_set(currentVector,0,0);\n gsl_vector_set(currentVector,1,gsl_vector_get(pVector,0));\n\n //make prob matrix (log space)\n probs = gsl_matrix_alloc(params->maxSampleSize + 1, params->maxSampleSize);\n siteProbMatrix(probs, currentVector, params->maxSampleSize, params->sampleSizeVector);\n\n //tally likelihood due to neutral\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(params->posts,0,i);\n }\n //go through states tallying lik\n for (i = 1; i < params->nstates; i++){\n gsl_vector_set(currentVector,0,gsl_vector_get(pVector,i));\n gsl_vector_set(currentVector,1,gsl_vector_get(pVector,0));\n siteProbMatrix(probs,currentVector, params->maxSampleSize, params->sampleSizeVector);\n for(j = 0; j < params->snpNumber; j++){\n lik += gsl_matrix_get(probs,params->data[j].n,params->data[j].i) * gsl_matrix_get(params->posts,i,j);\n }\n }\n gsl_matrix_free(probs);\n gsl_vector_free(currentVector);\n return -lik;\n}\n\n//N state version\nvoid jointMLEstNState(gsl_vector *results, double *lik, void * p){\n struct my_jointLik_params * params = (struct my_jointLik_params *) p;\n size_t np = params->nstates;\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;\n gsl_multimin_fminimizer *s = NULL;\n gsl_multimin_function minex_func;\n gsl_vector *ss, *x;\n\n size_t iter = 0, i;\n int status,j;\n double size;\n \n //check results vector\n assert(results->size == np);\n \n /* Initial vertex size vector */\n ss = gsl_vector_alloc (np);\n \n /* Set all step sizes to 1 */\n gsl_vector_set_all (ss, 0.01);\n \n /* Starting point */\n x = gsl_vector_alloc (np);\n for(j = 0; j < np; j++){\n gsl_vector_set (x, j, gsl_vector_get(params->startingPoint,j));\n }\n \n /* Initialize method and iterate */\n minex_func.f = &weightedLikLookSitesNState;\n minex_func.n = np;\n minex_func.params = params;\n \n s = gsl_multimin_fminimizer_alloc (T, np);\n gsl_multimin_fminimizer_set (s, &minex_func, x, ss);\n\n do\n {\n iter++;\n status = gsl_multimin_fminimizer_iterate(s);\n if (status)\n\tbreak;\n size = gsl_multimin_fminimizer_size (s);\n status = gsl_multimin_test_size (size, 1e-5);\n }\n while (status == GSL_CONTINUE && iter < 500);\n for (i = 0; i < np; i++){\n gsl_vector_set(results,i,gsl_vector_get (s->x, i));\n }\n gsl_vector_free(x);\n gsl_vector_free(ss);\n gsl_multimin_fminimizer_free (s);\n}\n\n", "meta": {"hexsha": "b74ef992c0720c4e0d1549a349cb5cb0cad94780", "size": 8904, "ext": "c", "lang": "C", "max_stars_repo_path": "segSiteHMM/segSites.c", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "segSiteHMM/segSites.c", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "segSiteHMM/segSites.c", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5979381443, "max_line_length": 115, "alphanum_fraction": 0.6850853549, "num_tokens": 2699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4773199662224855}} {"text": "/* specfunc/hyperg_2F0.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\n#include \"error.h\"\n#include \"hyperg.h\"\n\nint\ngsl_sf_hyperg_2F0_e(const double a, const double b, const double x, gsl_sf_result * result)\n{\n if(x < 0.0) {\n /* Use \"definition\" 2F0(a,b,x) = (-1/x)^a U(a,1+a-b,-1/x).\n */\n gsl_sf_result U;\n double pre = pow(-1.0/x, a);\n int stat_U = gsl_sf_hyperg_U_e(a, 1.0+a-b, -1.0/x, &U);\n result->val = pre * U.val;\n result->err = GSL_DBL_EPSILON * fabs(result->val) + pre * U.err;\n return stat_U;\n }\n else if(x == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else {\n /* Use asymptotic series. ??\n */\n /* return hyperg_2F0_series(a, b, x, -1, result, &prec); */\n DOMAIN_ERROR(result);\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_hyperg_2F0(const double a, const double b, const double x)\n{\n EVAL_RESULT(gsl_sf_hyperg_2F0_e(a, b, x, &result));\n}\n", "meta": {"hexsha": "022b5cb58afe5a33651aa2c697d30ba36f59bd33", "size": 1883, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/hyperg_2F0.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/hyperg_2F0.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/hyperg_2F0.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": 29.421875, "max_line_length": 91, "alphanum_fraction": 0.6553372278, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.47720310766580465}} {"text": "/*\n** centrality maps using spectral coherence\n**\n** get cross-periodogram via multiplication of FFTs\n**\n** Ref: T. Subba Rao,\n** On the Cross Periodogram of a Stationary Gaussian Vector Process,\n** The Annals of Mathematical Statistics, Vol. 38, No. 2 (Apr., 1967),\n** pp. 593-597. (2239172.pdf)\n**\n** Implementation follows SAS, see\n** http://www.tau.ac.il/cc/pages/docs/sas8/ets/chap17/\n**\n** G.Lohmann, September 2009\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#define PI 3.14159265\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n/* re-implementation of cblas_sspmv, cblas_sspmv causes problems */\nvoid my_sspmv(float *A,float *x,float *y,int n)\n{\n size_t i,j,k,kk;\n float tmp1=0,tmp2=0;\n \n for (j=0; j= wx) return 0;\n else return 0.5*(1.0 + cos((PI*x)/wx));\n}\n\nint GetFFtIndex(int n,double tr,double wavelength)\n{\n int k0;\n double nx,cycle;\n\n nx = (double)n;\n cycle = wavelength / tr;\n k0 = (int)(nx/cycle + 0.5);\n return k0;\n}\n\n\ndouble *Weights(int n,int k0,int p)\n{\n int k;\n double *w=NULL;\n double kx,wx,sum;\n \n w = (double *) VCalloc(n,sizeof(double));\n wx = (double) p;\n kx = 0;\n for (k=0; ksize1;\n nx = (double)n;\n kx = 0;\n for (k=0; ksize1; \n nx = 1;\n kx = 0;\n for (k=0; k= tablecos->size1) VError(\" k= %d\",k);\n if (k >= tablesin->size1) VError(\" k= %d\",k);\n sum1 = sum2 = 0;\n /* w = 2.0*PI*kx/nx; */\n ix = 0;\n for (i=0; i 0) fprintf(stderr,\" %6d %3d %3d %3d %f\\n\",i,c,r,b,ev[i]); */\n VPixel(dest,b,r,c,VFloat) = ev[i];\n }\n return dest;\n}\n\n\n\nVAttrList VSpectralECM(VAttrList list,VImage mask,VDouble wavelength,VShort nlags,\n\t\t VShort first,VShort length,VShort type)\n{\n int b,r,c,j,k,kk,k0,n,p;\n size_t i;\n size_t m,nvox;\n int last;\n gsl_matrix *matcos=NULL,*matsin=NULL;\n float *A=NULL,*ev=NULL;\n float tr=-1,xtr=-1;\n double *in,*xsin=NULL,*xcos=NULL,*w=NULL;\n double nx,u,sumx,freq=0;\n gsl_matrix *tablecos=NULL,*tablesin=NULL;\n double pi = 2.0*acos(0);\n\n\n /* get image dimensions */\n int nrows=0,ncols=0,nt=0;\n int nslices = VAttrListNumImages(list);\n VImage *src = VAttrListGetImages(list,nslices);\n VImageDimensions(src,nslices,&nt,&nrows,&ncols);\n size_t ntimesteps = nt;\n\n if (VImageNRows(mask) != nrows) \n VError(\" inconsistent image dims, mask has %d rows, image has %d rows\",VImageNRows(mask),nrows);\n if (VImageNColumns(mask) != ncols) \n VError(\" inconsistent image dims, mask has %d columns, image has %d columns\",VImageNColumns(mask),ncols);\n if (VImageNBands(mask) != nslices) \n VError(\" inconsistent image dims, mask has %d slices, image has %d slices\",VImageNBands(mask),nslices);\n\n\n /* get time steps to include */\n if (first < 0) first = 0;\n if (length <= 0) length = ntimesteps;\n last = first + length -1;\n if (last >= ntimesteps) last = ntimesteps-1;\n\n n = last - first + 1;\n if (n < 2) VError(\" not enough timesteps, nt= %d\",n);\n nx = (double)n;\n \n\n /* \n ** get freq range \n */\n if (VGetAttr (VImageAttrList (src[0]), \"repetition_time\", NULL,\n\t\tVFloatRepn, (VPointer) & xtr) == VAttrFound) {\n tr = (xtr/1000.0);\n }\n if (tr <= 0) VError(\" illegal tr: %f\",tr);\n\n k0 = GetFFtIndex((int)n,tr,wavelength); \n freq = 1.0/wavelength;\n fprintf(stderr,\" TR= %g secs, wavelength= %g secs, freq= %.3f Hz, k0= %d\\n\",\n\t tr,wavelength,freq,k0);\n if (k0 < 1 || k0 >= n/2) VError(\" illegal freq, index must be in [1,%d]\\n\",n/2);\n\n\n /* weights */\n if (nlags < 0)\n p = n/15; /* default */\n else\n p = (int)nlags;\n if (p < 3) VError(\" nlags too small, %d\",p);\n w = Weights((int)n,k0,p);\n\n\n\n /* count number of voxels */\n nvox = 0;\n for (b=0; b= n) kk = n-k;\n u = 2.0*(xcos[kk]*xcos[kk] + xsin[kk]*xsin[kk])/nx;\n sumx += w[ABS(k)]*u;\n }\n xmap[i] = sumx;\n \n for (k=0; k= n) kk = n-k;\n\n\tc1 = gsl_matrix_get(matcos,i,kk);\n\ts1 = gsl_matrix_get(matsin,i,kk);\n\n\tc2 = gsl_matrix_get(matcos,j,kk);\n\ts2 = gsl_matrix_get(matsin,j,kk);\n\t\n\tre = 2.0*(c1*c2 + s1*s2)/nx;\n\tim = 2.0*(c1*s2 - s1*c2)/nx;\n\n\tcs += w[ABS(k)] * re;\n\tqs += w[ABS(k)] * im;\n }\n \n if (type == 0) { /* spectral coherence */\n\tif (x*y > TINY) {\n\t v = (cs*cs + qs*qs) / (x*y);\n\t v = sqrt(v);\n\t}\n\telse v = -1;\n }\n else { /* phase sync */\n\tv = atan2(qs,cs)/pi;\n\t/* v = 1.0 - ABS(v); */\n\tv = cos(v);\n }\n if (v < TINY) v = TINY; /* make matrix irreducible */\n\n kij=j+i*(i+1)/2;\n A[kij] = v;\n }\n }\n \n /* free space */\n gsl_matrix_free(matcos);\n gsl_matrix_free(matsin);\n\n\n /*\n ** eigenvector centrality\n */\n ev = (float *) VCalloc(nvox,sizeof(float));\n EigenvectorCentrality(A,ev,nvox);\n /* DegreeCentrality(A,ev,nvox); */\n VImage dest0 = WriteOutput(src[0],map,nslices,nrows,ncols,ev,nvox);\n VSetAttr(VImageAttrList(dest0),\"name\",NULL,VStringRepn,\"eigenvector_centrality\");\n VAttrList out_list = VCreateAttrList();\n VAppendAttr(out_list,\"image\",NULL,VImageRepn,dest0);\n return out_list;\n}\n\n\nVDictEntry TYPDict[] = {\n { \"freq\", 0 },\n { \"sync\", 1 },\n { NULL }\n};\n\nint main (int argc,char *argv[])\n{ \n static VDouble wavelength = 10;\n static VShort nlags = 10;\n static VShort first = 0;\n static VShort length = 0;\n static VShort type = 0;\n static VString mask_filename = \"\";\n static VShort nproc = 0;\n static VOptionDescRec options[] = {\n {\"wavelength\", VDoubleRepn,1,(VPointer) &wavelength,VRequiredOpt,NULL,\"wavelength in secs\"},\n {\"first\",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,\"first timestep to use\"},\n {\"length\",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,\"length of time series to use\"},\n {\"mask\",VStringRepn,1,(VPointer) &mask_filename,VRequiredOpt,NULL,\"mask\"},\n {\"nlags\",VShortRepn,1,(VPointer) &nlags,VOptionalOpt,NULL,\n \"num lags in cross-corr, use 0 to get default value\"},\n {\"type\",VShortRepn,1,(VPointer) &type,VOptionalOpt,TYPDict,\"frequency or phase coherence\"},\n {\"j\",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,\"Number of processors to use, '0' to use all\"}\n };\n FILE *in_file,*out_file;\n VString in_filename=NULL;\n char *prg = \"vspectralecm\";\n\n\n /* parse command line */\n VParseFilterCmdZ (VNumber (options),options,argc,argv,&in_file,&out_file,&in_filename);\n if (type > 2) VError(\" illegal type\");\n\n\n \n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\"using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n\n /* read mask */\n VAttrList listm = VReadAttrList(mask_filename,0L,TRUE,FALSE);\n VImage mask = VReadImage(listm);\n if (mask == NULL) VError(\" no ROI mask found\");\n\n\n /* read functional data */\n VAttrList list = VReadAttrListZ(in_file,in_filename,0L,TRUE,FALSE);\n if (list == NULL) VError(\" error reading input file %s\",in_file);\n VAttrList geolist = VGetGeoInfo(list);\n\n\n /*\n ** process\n */\n VAttrList out_list = VSpectralECM(list,mask,wavelength,nlags,first,length,type);\n\n\n /* update geoinfo, 4D to 3D */\n if (geolist != NULL) {\n double *D = VGetGeoDim(geolist,NULL);\n D[0] = 3; /* 3D */\n D[4] = 1; /* just one timestep */\n VSetGeoDim(geolist,D);\n VSetGeoInfo(geolist,out_list);\n }\n\n VHistory(VNumber(options),options,prg,&list,&out_list);\n if (! VWriteFile (out_file, out_list)) exit (1);\n fprintf (stderr, \"%s: done.\\n\", argv[0]);\n return 0;\n}\n", "meta": {"hexsha": "0e4a6d0dea077dcff91ee782914aa14f17207c7c", "size": 13585, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nets/vspectralecm/vspectralecm.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/nets/vspectralecm/vspectralecm.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/nets/vspectralecm/vspectralecm.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 24.0442477876, "max_line_length": 109, "alphanum_fraction": 0.5814501288, "num_tokens": 4916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47687359225932796}} {"text": "/* eigen/eigen_sort.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, Modified: B. Gough. */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/* The eigen_sort below is not very good, but it is simple and\n * self-contained. We can always implement an improved sort later. */\n\nint\ngsl_eigen_symmv_sort (gsl_vector * eval, gsl_matrix * evec, \n gsl_eigen_sort_t sort_type)\n{\n if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (eval->size != evec->size1)\n {\n GSL_ERROR (\"eigenvalues must match eigenvector matrix\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = eval->size;\n size_t i;\n\n for (i = 0; i < N - 1; i++)\n {\n size_t j;\n size_t k = i;\n\n double ek = gsl_vector_get (eval, i);\n\n /* search for something to swap */\n for (j = i + 1; j < N; j++)\n {\n int test;\n const double ej = gsl_vector_get (eval, j);\n\n switch (sort_type)\n { \n case GSL_EIGEN_SORT_VAL_ASC:\n test = (ej < ek);\n break;\n case GSL_EIGEN_SORT_VAL_DESC:\n test = (ej > ek);\n break;\n case GSL_EIGEN_SORT_ABS_ASC:\n test = (fabs (ej) < fabs (ek));\n break;\n case GSL_EIGEN_SORT_ABS_DESC:\n test = (fabs (ej) > fabs (ek));\n break;\n default:\n GSL_ERROR (\"unrecognized sort type\", GSL_EINVAL);\n }\n\n if (test)\n {\n k = j;\n ek = ej;\n }\n }\n\n if (k != i)\n {\n /* swap eigenvalues */\n gsl_vector_swap_elements (eval, i, k);\n\n /* swap eigenvectors */\n gsl_matrix_swap_columns (evec, i, k);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_eigen_hermv_sort (gsl_vector * eval, gsl_matrix_complex * evec, \n gsl_eigen_sort_t sort_type)\n{\n if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (eval->size != evec->size1)\n {\n GSL_ERROR (\"eigenvalues must match eigenvector matrix\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = eval->size;\n size_t i;\n\n for (i = 0; i < N - 1; i++)\n {\n size_t j;\n size_t k = i;\n\n double ek = gsl_vector_get (eval, i);\n\n /* search for something to swap */\n for (j = i + 1; j < N; j++)\n {\n int test;\n const double ej = gsl_vector_get (eval, j);\n\n switch (sort_type)\n { \n case GSL_EIGEN_SORT_VAL_ASC:\n test = (ej < ek);\n break;\n case GSL_EIGEN_SORT_VAL_DESC:\n test = (ej > ek);\n break;\n case GSL_EIGEN_SORT_ABS_ASC:\n test = (fabs (ej) < fabs (ek));\n break;\n case GSL_EIGEN_SORT_ABS_DESC:\n test = (fabs (ej) > fabs (ek));\n break;\n default:\n GSL_ERROR (\"unrecognized sort type\", GSL_EINVAL);\n }\n\n if (test)\n {\n k = j;\n ek = ej;\n }\n }\n\n if (k != i)\n {\n /* swap eigenvalues */\n gsl_vector_swap_elements (eval, i, k);\n\n /* swap eigenvectors */\n gsl_matrix_complex_swap_columns (evec, i, k);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_eigen_nonsymmv_sort (gsl_vector_complex * eval,\n gsl_matrix_complex * evec, \n gsl_eigen_sort_t sort_type)\n{\n if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (eval->size != evec->size1)\n {\n GSL_ERROR (\"eigenvalues must match eigenvector matrix\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = eval->size;\n size_t i;\n\n for (i = 0; i < N - 1; i++)\n {\n size_t j;\n size_t k = i;\n\n gsl_complex ek = gsl_vector_complex_get (eval, i);\n\n /* search for something to swap */\n for (j = i + 1; j < N; j++)\n {\n int test;\n const gsl_complex ej = gsl_vector_complex_get (eval, j);\n\n switch (sort_type)\n { \n case GSL_EIGEN_SORT_ABS_ASC:\n test = (gsl_complex_abs (ej) < gsl_complex_abs (ek));\n break;\n case GSL_EIGEN_SORT_ABS_DESC:\n test = (gsl_complex_abs (ej) > gsl_complex_abs (ek));\n break;\n case GSL_EIGEN_SORT_VAL_ASC:\n case GSL_EIGEN_SORT_VAL_DESC:\n default:\n GSL_ERROR (\"invalid sort type\", GSL_EINVAL);\n }\n\n if (test)\n {\n k = j;\n ek = ej;\n }\n }\n\n if (k != i)\n {\n /* swap eigenvalues */\n gsl_vector_complex_swap_elements (eval, i, k);\n\n /* swap eigenvectors */\n gsl_matrix_complex_swap_columns (evec, i, k);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "d0755d9355dfe8f7cf60d7345632c7a919385f30", "size": 6482, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/sort.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/sort.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/sort.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.4661016949, "max_line_length": 81, "alphanum_fraction": 0.4853440296, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.476838900783656}} {"text": "/* ode-initval/rk2.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/* Runge-Kutta 2(3), Euler-Cauchy */\n\n/* Author: G. Jungman\n */\n\n/* Reference: Abramowitz & Stegun, section 25.5. Runge-Kutta 2nd (25.5.7)\n and 3rd (25.5.8) order methods */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\ntypedef struct\n{\n double *k1;\n double *k2;\n double *k3;\n double *ytmp;\n}\nrk2_state_t;\n\nstatic void *\nrk2_alloc (size_t dim)\n{\n rk2_state_t *state = (rk2_state_t *) malloc (sizeof (rk2_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rk2_state\", GSL_ENOMEM);\n }\n\n state->k1 = (double *) malloc (dim * sizeof (double));\n\n if (state->k1 == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k1\", GSL_ENOMEM);\n }\n\n state->k2 = (double *) malloc (dim * sizeof (double));\n\n if (state->k2 == 0)\n {\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2\", GSL_ENOMEM);\n }\n\n state->k3 = (double *) malloc (dim * sizeof (double));\n \n if (state->k3 == 0)\n {\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->k3);\n free (state->k2);\n free (state->k1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\nstatic int\nrk2_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], \n const gsl_odeiv_system * sys)\n{\n rk2_state_t *state = (rk2_state_t *) vstate;\n\n size_t i;\n\n double *const k1 = state->k1;\n double *const k2 = state->k2;\n double *const k3 = state->k3;\n double *const ytmp = state->ytmp;\n\n /* k1 step */\n /* k1 = f(t,y) */\n\n if (dydt_in != NULL)\n {\n DBL_MEMCPY (k1, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1);\n\n if (s != GSL_SUCCESS)\n\t{\n\t return s;\n\t}\n }\n\n /* k2 step */\n /* k2 = f(t + 0.5*h, y + 0.5*k1) */\n\n for (i = 0; i < dim; i++)\n {\n ytmp[i] = y[i] + 0.5 * h * k1[i];\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k2);\n\n if (s != GSL_SUCCESS)\n {\n\treturn s;\n }\n }\n\n /* k3 step */\n /* for 3rd order estimates, is used for error estimation\n k3 = f(t + h, y - k1 + 2*k2) */\n \n for (i = 0; i < dim; i++)\n {\n ytmp[i] = y[i] + h * (-k1[i] + 2.0 * k2[i]);\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k3);\n\n if (s != GSL_SUCCESS)\n {\n\treturn s;\n }\n }\n\n /* final sum */\n \n for (i = 0; i < dim; i++)\n {\n /* Save original values if derivative evaluation below fails */\n ytmp[i] = y[i];\n\n {\n\tconst double ksum3 = (k1[i] + 4.0 * k2[i] + k3[i]) / 6.0;\n\ty[i] += h * ksum3;\n }\n }\n \n /* Derivatives at output */\n\n if (dydt_out != NULL)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);\n \n if (s != GSL_SUCCESS)\n\t{\n\t /* Restore original values */\n\t DBL_MEMCPY (y, ytmp, dim);\n\t \n\t return s;\n\t}\n }\n\n /* Error estimation */\n\n for (i = 0; i < dim; i++)\n {\n const double ksum3 = (k1[i] + 4.0 * k2[i] + k3[i]) / 6.0;\n yerr[i] = h * (k2[i] - ksum3);\n }\n \n return GSL_SUCCESS;\n}\n\nstatic int\nrk2_reset (void *vstate, size_t dim)\n{\n rk2_state_t *state = (rk2_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->k1, dim);\n DBL_ZERO_MEMSET (state->k2, dim);\n DBL_ZERO_MEMSET (state->k3, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrk2_order (void *vstate)\n{\n rk2_state_t *state = (rk2_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 2;\n}\n\nstatic void\nrk2_free (void *vstate)\n{\n rk2_state_t *state = (rk2_state_t *) vstate;\n free (state->k1);\n free (state->k2);\n free (state->k3);\n free (state->ytmp);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type rk2_type = { \"rk2\", /* name */\n 1, /* can use dydt_in */\n 1, /* gives exact dydt_out */\n &rk2_alloc,\n &rk2_apply,\n &rk2_reset,\n &rk2_order,\n &rk2_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_rk2 = &rk2_type;\n", "meta": {"hexsha": "e7696d1146f08bef6144280fd929fa2b75698a84", "size": 5234, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/rk2.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/ode-initval/rk2.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/ode-initval/rk2.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.8525896414, "max_line_length": 81, "alphanum_fraction": 0.5747038594, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.47639804760735743}} {"text": "#ifndef _linalg_h_included_\n#define _linalg_h_included_\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nextern \"C\" {\n\textern void dgetrf_(int *,int *,double *,int *,double *,int *);\n\textern void dgetri_(int *,double *,int *,double *,double *,int *,int *);\n\textern void dpotrf_(char *,int *,double *,int *,int *);\n\textern void dpotri_(char *,int *,double *,int *,int *);\n};\n\nusing namespace boost;\nusing namespace boost::numeric;\nusing namespace jsc::util;\n\nclass linalg {\n\tpublic:\n\t\tstatic void invert_matrix(const ublas::matrix & A,\n\t\t\t\tublas::matrix & inv) {\n\t\t\tinvert_matrix_gsl_lu(A, inv);\n\t\t\t// invert_matrix_lapack_lu(A, inv);\n\t\t\t// invert_matrix_lapack_cholesky(A, inv);\n\t\t\tunsigned long K = A.size1() + 1;\n\t\t\tublas::matrix rst(K-1, K-1);\n\t\t\tublas::matrix ident = ublas::identity_matrix(K-1);\n\t\t\taxpy_prod(A, inv, rst);\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tif (abs(rst(p,q) - ident(p,q)) > 1E-5) {\n\t\t\t\t\t\tL_(debug) << \"A*(invA)[\" << p << \",\" << q\n\t\t\t\t\t\t\t<< \"] = \" << rst(p,q);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tprivate:\n\t\tstatic void invert_matrix_gsl_lu(const ublas::matrix & A,\n\t\t\t\tublas::matrix & inv) {\n\t\t\tunsigned long K = A.size1() + 1;\n\n\t\t\tgsl_matrix* m = gsl_matrix_alloc(K - 1, K - 1);\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tgsl_matrix_set(m, p, q, A(p,q));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgsl_matrix* inverse = gsl_matrix_alloc(K - 1, K - 1);\n\t\t\tgsl_permutation*perm = gsl_permutation_alloc(K-1);\n\t\t\tint s=0;\n\t\t\tgsl_linalg_LU_decomp(m, perm, &s);\n\t\t\tgsl_linalg_LU_invert(m, perm, inverse);\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tinv(p,q) = gsl_matrix_get(inverse, p, q);\n\t\t\t\t}\n\t\t\t}\n\t\t\tgsl_permutation_free(perm);\n\t\t\tgsl_matrix_free(inverse);\n\t\t\tgsl_matrix_free(m);\n\t\t}\n\n\t\tstatic void invert_matrix_lapack_lu(const ublas::matrix & A,\n\t\t\t\tublas::matrix & inv) {\n\t\t\tunsigned long K = A.size1() + 1;\n\n\t\t\tdouble * m = (double *)malloc((K - 1)*(K - 1)*sizeof(double));\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tm[p + q*(K-1)] = A(p,q);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdouble * ipiv = (double *)malloc((K - 1)*sizeof(double));\n\t\t\tint N = K - 1;\n\t\t\tint lda = N;\n\t\t\tint info;\n\t\t\tdgetrf_(&N, &N, &m[0], &lda, &ipiv[0], &info);\n\t\t\tassert(info == 0);\n\n\t\t\tdouble * work = (double *)malloc((K - 1)*sizeof(double));\n\t\t\tint lwork = N;\n\t\t\tdgetri_(&N, &m[0], &lda, &ipiv[0], &work[0], &lwork, &info);\n\t\t\tassert(info == 0);\n\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tinv(p,q) = m[p + q*(K-1)];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfree(m);\n\t\t\tfree(ipiv);\n\t\t\tfree(work);\n\t\t}\n\n\t\tstatic void invert_matrix_lapack_cholesky(const ublas::matrix & A,\n\t\t\t\tublas::matrix & inv) {\n\t\t\tunsigned long K = A.size1() + 1;\n\n\t\t\tdouble * m = (double *)malloc((K - 1)*(K - 1)*sizeof(double));\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tm[p + q*(K-1)] = A(p,q);\n\t\t\t\t}\n\t\t\t}\n\t\t\tint N = K - 1;\n\t\t\tint lda = N;\n\t\t\tint info;\n\t\t\tchar UPLO = 'U';\n\t\t\tdpotrf_(&UPLO, &N, &m[0], &lda, &info);\n\t\t\tassert(info == 0);\n\t\t\tdpotrf_(&UPLO, &N, &m[0], &lda, &info);\n\t\t\tassert(info == 0);\n\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tinv(p,q) = m[p + q*(K-1)];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfree(m);\n\t\t}\n};\n\n#endif\n", "meta": {"hexsha": "07ae432e7194a122ebf6eec0de5cf0f7800f6007", "size": 3715, "ext": "h", "lang": "C", "max_stars_repo_path": "common/linalg.h", "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_issues_repo_path": "common/linalg.h", "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "common/linalg.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "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.3161764706, "max_line_length": 76, "alphanum_fraction": 0.5615074024, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4760142830590473}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\ndouble get_k0_fftlog(int N, double mu, double q, double r0, double L, double k0guess);\nvoid um_fftlog(int m, double mu, double q, double k0, double r0, double L, double *realpart, double *imagpart);\n\nvoid compute_discrete_spherical_fft(double *data, int N, double r0, double L, double q, double *result, double *k0)\n{\n double mu,rn,kn,tmp[2],um[2],k0guess;\n int i,m;\n static int initFlag = 1;\n static double *rin;\n static fftw_complex *out;\n static fftw_plan pf,pb;\n\n if(initFlag)\n {\n initFlag = 0;\n\n rin = (double*)fftw_malloc(sizeof(double)*N);\n out = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*(N/2+1));\n pf = fftw_plan_dft_r2c_1d(N,rin,out,FFTW_MEASURE);\n pb = fftw_plan_dft_c2r_1d(N,out,rin,FFTW_MEASURE);\n }\n\n for(i=0;i= N/2)\n\tm = i-N;\n else\n\tm = i;\n\n um_fftlog(m,mu,q,*k0,r0,L,&(um[0]),&(um[1]));\n if(m == N/2 || m == -N/2)\n\tum[1] = 0.0;\n\n tmp[0] = out[i][0]*um[0] - out[i][1]*um[1];\n tmp[1] = out[i][1]*um[0] + out[i][0]*um[1];\n\n out[i][0] = tmp[0];\n out[i][1] = tmp[1];\n }\n\n fftw_execute(pb);\n\n for(i=0;i\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define TSSIZE 10\n#define WL 10000\n\ntypedef struct tagInterpolant{\n gsl_matrix *Bs;\n int *nodes;\n}Interpolant;\n\n/* function to create an orthonormal basis set from a training set of models */\ndouble *create_basis(double weight, double tolerance, gsl_matrix *TS, size_t *nbases);\n\n/* function to create the empirical interpolant */\n//void create_interpolant(gsl_matrix *RB, gsl_matrix **Bs, int **idxarray);\nInterpolant *create_interpolant(gsl_matrix *RB);\n\n/* define function to project model vector onto the training set of models */\nvoid project_onto_basis(double dt, gsl_matrix *RB, gsl_matrix *TS, gsl_matrix *projections, gsl_matrix *projection_coefficients, int idx);\n\n/* dot product of two vectors, but with one multiplied by the weighting factor */\ndouble weighted_dot_product(double weight, gsl_vector *a, gsl_vector *b);\n\n/* normalise a vector */\nvoid normalise(double weight, gsl_vector *a);\n\n/* get the B_matrix */\ngsl_matrix *B_matrix(gsl_matrix *V, gsl_matrix *RB);\n\nvoid print_shape(gsl_matrix *a);\n\n/* create ROQ weights for interpolant to calculate the data dot model terms */\ngsl_vector *create_data_model_weights(gsl_matrix *B, double *data);\n\n/* calculate ROQ version of the data model dot product (where the model\n vector is the model just computed at the interpolant points) */\ndouble roq_data_dot_model(gsl_vector *weights, double *model);\n\n/* create ROQ weights for interpolant to calculate the model dot model terms */\ngsl_matrix *create_model_model_weights(gsl_matrix *B);\n\n/* calculate ROQ version of the model model dot product (where the model\n vector is the model just computed at the interpolant points) */\ndouble roq_model_dot_model(gsl_matrix *weights, double *model);\n\n\ndouble *create_basis(double weight, double tolerance, gsl_matrix *TS, size_t *nbases){\n double *RB = NULL;\n\n gsl_matrix *projections; /* projections of the basis onto the training set */\n gsl_matrix *residual;\n gsl_matrix *projection_coeffs;\n gsl_vector *projection_errors;\n gsl_vector_view resrow;\n\n double sigma = 1.;\n size_t dlength = TS->size2, nts = TS->size1;\n size_t mindex = 0, k=0;\n int idx = 0;\n\n /* allocate reduced basis (initially just one model vector in length).\n Here we have RB just as a double array, rather than a gsl_matrix,\n as there is no realloc functions for GSL matrices. When wanting to\n use RB as a GSL matrix we will have to use matrix views. */\n RB = calloc(dlength, sizeof(double)); \n\n gsl_matrix_view RBview = gsl_matrix_view_array(RB, 1, dlength);\n gsl_vector *firstrow = gsl_vector_calloc(dlength);\n gsl_matrix_get_row(firstrow, TS, 0);\n gsl_matrix_set_row(&RBview.matrix, 0, firstrow);\n gsl_vector_free(firstrow);\n\n projection_errors = gsl_vector_calloc(dlength);\n residual = gsl_matrix_calloc(nts, dlength);\n projections = gsl_matrix_calloc(nts, dlength);\n projection_coeffs = gsl_matrix_calloc(nts, nts);\n\n /* create reduced basis set using greedy binning Algorithm 1 of http://arxiv.org/abs/1308.3565 */\n while ( sigma >= tolerance ){\n if ( idx > nts-1 ){\n fprintf(stderr, \"Not enough training models (%zu) to produce orthonormal basis given the tolerance of %le\\n\", nts, tolerance);\n return NULL;\n }\n\n project_onto_basis(weight, &RBview.matrix, TS, projections, projection_coeffs, idx);\n\n gsl_matrix_memcpy(residual, TS); /* copy training set into residual */\n\n /* get residuals by subtracting projections from training set */\n gsl_matrix_sub(residual, projections);\n\n /* get projection errors */\n for( k=0; k < nts; k++ ){\n double err;\n\n resrow = gsl_matrix_row(residual, k);\n err = weighted_dot_product(weight, &resrow.vector, &resrow.vector);\n\n gsl_vector_set(projection_errors, k, err);\n }\n\n sigma = fabs(gsl_vector_max(projection_errors));\n\n if ( sigma > 1e-5 ){ fprintf(stderr, \"%.12lf\\t%d\\n\", sigma, idx); }\n else { fprintf(stderr, \"%.12le\\t%d\\n\", sigma, idx); }\n\n if ( sigma < tolerance ) { break; }\n\n /* get index of training set with the largest projection errors */\n mindex = gsl_vector_max_index( projection_errors );\n\n gsl_vector *next_basis = gsl_vector_calloc(dlength);\n gsl_vector_view proj_basis = gsl_matrix_row(projections, mindex);\n gsl_matrix_get_row(next_basis, TS, mindex);\n gsl_vector_sub(next_basis, &proj_basis.vector);\n\n /* normalise vector */\n normalise(weight, next_basis);\n\n idx++;\n\n /* expand reduced basis */\n RB = realloc(RB, sizeof(double)*dlength*(idx+1));\n\n /* add on next basis */\n RBview = gsl_matrix_view_array(RB, idx+1, dlength);\n gsl_matrix_set_row(&RBview.matrix, idx, next_basis);\n\n gsl_vector_free(next_basis);\n }\n\n *nbases = (size_t)idx;\n\n gsl_matrix_free(projection_coeffs);\n gsl_matrix_free(residual);\n gsl_matrix_free(TS);\n\n return RB;\n}\n\nvoid project_onto_basis(double dt, gsl_matrix *RB, gsl_matrix *TS, gsl_matrix *projections, gsl_matrix *projection_coefficients, int idx){\n size_t row = 0;\n \n gsl_vector_view basis = gsl_matrix_row(RB, idx);\n\n for ( row=0; row < TS->size1; row++ ){\n double prod;\n gsl_vector_view proj = gsl_matrix_row(projections, row);\n gsl_vector *basisscale = gsl_vector_calloc(TS->size2);\n\n gsl_vector_view model = gsl_matrix_row(TS, row); /* get model from training set */\n\n prod = weighted_dot_product(dt, &basis.vector, &model.vector);\n \n gsl_matrix_set(projection_coefficients, idx, row, prod);\n gsl_vector_memcpy(basisscale, &basis.vector); \n gsl_vector_scale(basisscale, prod);\n gsl_vector_add(&proj.vector, basisscale);\n gsl_vector_free(basisscale);\n }\n}\n\ndouble weighted_dot_product(double weight, gsl_vector *a, gsl_vector *b){\n double dp;\n gsl_vector *weighted = gsl_vector_calloc(a->size);\n gsl_vector_memcpy(weighted, a);\n \n /* multiply vector by weight */\n gsl_vector_scale(weighted, weight);\n\n /* get dot product */\n gsl_blas_ddot(weighted, b, &dp);\n \n gsl_vector_free(weighted);\n\n return dp;\n}\n\nvoid normalise(double weight, gsl_vector *a){\n double norm = gsl_blas_dnrm2(a); /* use GSL normalisation calculation function */\n\n gsl_vector_scale(a, 1./(norm*sqrt(weight)));\n}\n\ngsl_matrix *B_matrix(gsl_matrix *V, gsl_matrix *RB){\n /* get inverse of V */\n size_t n = V->size1;\n gsl_matrix *invV = gsl_matrix_alloc(n, n);\n int signum;\n \n /* use LU decomposition to get inverse */\n gsl_matrix *LU = gsl_matrix_alloc(n, n);\n gsl_matrix_memcpy(LU, V);\n\n gsl_permutation *p = gsl_permutation_alloc(n);\n gsl_linalg_LU_decomp(LU, p, &signum);\n gsl_linalg_LU_invert(LU, p, invV);\n gsl_permutation_free(p);\n gsl_matrix_free(LU);\n\n /* get B matrix */\n gsl_matrix_view subRB = gsl_matrix_submatrix(RB, 0, 0, n, RB->size2);\n gsl_matrix *B = gsl_matrix_alloc(n, RB->size2);\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, invV, &subRB.matrix, 0., B); \n\n gsl_matrix_free(invV);\n return B;\n}\n\nvoid print_shape(gsl_matrix *a){\n fprintf(stderr, \"Matrix is %zu x %zu\\n\", a->size1, a->size2);\n}\n\ngsl_vector *create_data_model_weights(gsl_matrix *B, double *data){\n gsl_vector_view dataview = gsl_vector_view_array(data, B->size2);\n\n /* create weights */\n gsl_vector *weights = gsl_vector_alloc(B->size1);\n\n gsl_blas_dgemv(CblasNoTrans, 1.0, B, &dataview.vector, 0., weights);\n\n return weights;\n}\n\ndouble roq_data_dot_model(gsl_vector *weights, double *model){\n double d_dot_m = 0.;\n gsl_vector_view modelview = gsl_vector_view_array(model, weights->size);\n \n gsl_blas_ddot(weights, &modelview.vector, &d_dot_m);\n\n return d_dot_m;\n}\n\ngsl_matrix *create_model_model_weights(gsl_matrix *B){\n gsl_matrix *weights = gsl_matrix_alloc(B->size1, B->size1);\n size_t i=0, j=0;\n double ressum = 0.;\n\n for ( i=0; isize1; i++ ){\n for ( j=0; jsize1; j++ ){\n gsl_vector_view Bi = gsl_matrix_row(B, i);\n gsl_vector_view Bj = gsl_matrix_row(B, j);\n gsl_blas_ddot(&Bi.vector, &Bj.vector, &ressum);\n gsl_matrix_set(weights, i, j, ressum);\n }\n }\n\n return weights;\n}\n\ndouble roq_model_dot_model(gsl_matrix *weights, double *model){\n gsl_vector *ws = gsl_vector_alloc(weights->size1);\n gsl_vector_view modelview = gsl_vector_view_array(model, weights->size1);\n double m_dot_m = 0.; \n\n gsl_blas_dgemv(CblasTrans, 1.0, weights, &modelview.vector, 0., ws);\n gsl_blas_ddot(ws, &modelview.vector, &m_dot_m);\n\n return m_dot_m;\n}\n\nInterpolant *create_interpolant(gsl_matrix *RB){\n /* now find the empirical interopolant and interpolation nodes using Algorithm 2\n of http://arxiv.org/abs/1308.3565 */\n size_t RBsize = RB->size1; /* reduced basis size (no. of reduced bases) */\n size_t dlength = RB->size2; /* length of each base */\n size_t i=1, j=0, k=0;\n double *V = malloc(sizeof(double));\n gsl_matrix_view Vview;\n \n Interpolant *interp = malloc(sizeof(Interpolant));\n \n int idmax = 0, newidx = 0;\n\n /* get index of maximum absolute value of first basis */\n gsl_vector_view firstbasis = gsl_matrix_row(RB, 0);\n idmax = (int)gsl_blas_idamax(&firstbasis.vector); /* function gets index of maximum absolute value */\n\n interp->nodes = malloc(RBsize*sizeof(int));\n \n interp->nodes[0] = idmax;\n\n fprintf(stderr, \"first index = %d\\n\", interp->nodes[0]); \n \n for ( i=1; inodes[k]));\n }\n }\n\n /* get B matrix */\n gsl_matrix *B = B_matrix(&Vview.matrix, RB);\n\n /* make empirical interpolant of basis */\n gsl_vector *interpolant = gsl_vector_calloc(dlength);\n gsl_vector *subbasis = gsl_vector_calloc(i);\n gsl_vector_view subview = gsl_matrix_row(RB, i);\n\n for ( k=0; knodes[k]));\n }\n\n gsl_blas_dgemv(CblasTrans, 1.0, B, subbasis, 0., interpolant); \n\n /* get residuals of interpolant */\n gsl_vector_sub(interpolant, &subview.vector);\n\n newidx = (int)gsl_blas_idamax(interpolant);\n\n interp->nodes[i] = newidx;\n\n fprintf(stderr, \"%zu: idx[%d]\\n\", i, interp->nodes[i]);\n\n gsl_vector_free(subbasis);\n gsl_matrix_free(B);\n gsl_vector_free(interpolant);\n\n /* reallocate memory for V */\n V = realloc(V, (i+1)*(i+1)*sizeof(double));\n }\n\n /* NOTE: the above works and produces identical results to the ipython notebook */\n\n /* get final B vector with all the indices */\n Vview = gsl_matrix_view_array(V, RBsize, RBsize);\n for( j=0; jnodes[k]));\n }\n }\n\n interp->Bs = B_matrix(&Vview.matrix, RB);\n\n free(V); \n\n return interp;\n}\n\nint main(){\n gsl_matrix *TS; /* the training set of waveforms */\n\n size_t TSsize; /* the size of the training set (number of waveforms) */\n size_t wl; /* the length of each waveform */\n size_t k = 0, j = 0, i = 0, nbases = 0;\n\n double *RB = NULL; /* the reduced basis set */\n Interpolant *interp = NULL;\n \n gsl_vector *times;\n\n double tolerance = 1e-12, sigma = 1.; /* tolerance for reduced basis generation loop */\n\n double dt = 60.; /* model time steps */\n\n TSsize = TSSIZE;\n wl = WL;\n\n /* allocate memory for training set */\n TS = gsl_matrix_calloc(TSsize, wl);\n\n double fmin = -0.0001, fmax = 0.0001, f0 = 0., m0 = 0.;\n times = gsl_vector_alloc(wl);\n\n /* set up training set */\n for ( k=0; k < TSsize; k++ ){\n f0 = fmin + (double)k*(fmax-fmin)/((double)TSsize-1.);\n\n for ( j=0; j < wl; j++ ){\n double tv = dt*(double)j;\n m0 = sin(2.*M_PI*f0*tv);\n gsl_vector_set(times, j, tv);\n gsl_matrix_set(TS, k, j, m0);\n }\n\n gsl_vector_view rowview = gsl_matrix_row(TS, k);\n normalise(dt, &rowview.vector);\n }\n\n if ( (RB = create_basis(dt, tolerance, TS, &nbases)) == NULL){\n fprintf(stderr, \"Error... problem producing basis\\n\");\n return 1;\n }\n \n gsl_matrix_view RBview = gsl_matrix_view_array(RB, nbases, wl);\n\n fprintf(stderr, \"%zu, %zu x %zu\\n\", nbases, RBview.matrix.size1, RBview.matrix.size2); \n\n //FILE *fp = fopen(\"test_vector.txt\", \"w\");\n //gsl_vector_view testview = gsl_matrix_row(&RBview.matrix, RBview.matrix.size1-1);\n //gsl_vector_fprintf(fp, &testview.vector, \"%le\");\n //fclose(fp);\n\n /* NOTE: the above appears to be correct and gives identical values to those in the ipython notebook */\n\n interp = create_interpolant(&RBview.matrix); \n \n /* do some timing tests */\n\n /* create the model dot model weights */\n gsl_matrix *mmw = create_model_model_weights(interp->Bs);\n\n double randf0 = -0.00004; /* a random frequency to create a model */\n\n double *modelfull = calloc(wl, sizeof(double));\n double *modelreduced = calloc(nbases, sizeof(double));\n double *timesred = calloc(nbases, sizeof(double));\n\n /* create model */\n for ( i=0; inodes[i])); }\n\n gsl_vector_view mfview = gsl_vector_view_array(modelfull, wl);\n\n struct timespec t1, t2, t3, t4;\n double dt1, dt2;\n\n /* get the model model term with the full model */\n double mmfull, mmred;\n clock_gettime(CLOCK_MONOTONIC, &t1);\n gsl_blas_ddot(&mfview.vector, &mfview.vector, &mmfull);\n clock_gettime(CLOCK_MONOTONIC, &t2);\n \n clock_gettime(CLOCK_MONOTONIC, &t3);\n mmred = roq_model_dot_model(mmw, modelreduced);\n clock_gettime(CLOCK_MONOTONIC, &t4);\n\n dt1 = (double)((t2.tv_sec + t2.tv_nsec*1.e-9) - (t1.tv_sec + t1.tv_nsec*1.e-9));\n dt2 = (double)((t4.tv_sec + t4.tv_nsec*1.e-9) - (t3.tv_sec + t3.tv_nsec*1.e-9));\n fprintf(stderr, \"M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\\n\", mmfull, dt1, mmred, dt2, dt1/dt2);\n\n /* get the data dot model terms by generating some random data */\n const gsl_rng_type *T;\n gsl_rng * r;\n \n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc(T);\n\n double *data = calloc(wl, sizeof(double));\n for ( i=0; iBs, data);\n gsl_vector_view dataview = gsl_vector_view_array(data, wl);\n \n double dmfull, dmred;\n clock_gettime(CLOCK_MONOTONIC, &t1);\n gsl_blas_ddot(&dataview.vector, &mfview.vector, &dmfull);\n clock_gettime(CLOCK_MONOTONIC, &t2);\n \n clock_gettime(CLOCK_MONOTONIC, &t3);\n dmred = roq_data_dot_model(dmw, modelreduced);\n clock_gettime(CLOCK_MONOTONIC, &t4);\n \n dt1 = (double)((t2.tv_sec + t2.tv_nsec*1.e-9) - (t1.tv_sec + t1.tv_nsec*1.e-9));\n dt2 = (double)((t4.tv_sec + t4.tv_nsec*1.e-9) - (t3.tv_sec + t3.tv_nsec*1.e-9));\n fprintf(stderr, \"D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\\n\", dmfull, dt1, dmred, dt2, dt1/dt2);\n\n /* check difference in log likelihoods */\n double Lfull, Lred;\n \n Lfull = mmfull - 2.*dmfull;\n Lred = mmred - 2.*dmred;\n \n fprintf(stderr, \"Fractional difference in log likelihoods = %lf%%\\n\", 100.*fabs(Lfull-Lred)/fabs(Lfull));\n \n return 0;\n}\n", "meta": {"hexsha": "bd536ce9d2cb09d9b8085a5827e34f873d132388", "size": 15330, "ext": "c", "lang": "C", "max_stars_repo_path": "ROQ/roq_test.c", "max_stars_repo_name": "mattpitkin/random_scripts", "max_stars_repo_head_hexsha": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "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": "ROQ/roq_test.c", "max_issues_repo_name": "mattpitkin/random_scripts", "max_issues_repo_head_hexsha": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "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": "ROQ/roq_test.c", "max_forks_repo_name": "mattpitkin/random_scripts", "max_forks_repo_head_hexsha": "8fcfc1d25d8ca7ef66778b7b30be564962e3add3", "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.7391304348, "max_line_length": 141, "alphanum_fraction": 0.6866927593, "num_tokens": 4518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4758567318345002}} {"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#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\nint gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_prob(const int n, const double x);\r\nint gsl_sf_hermite_prob_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_prob_deriv(const int m, const int n, const double x);\r\nint gsl_sf_hermite_e(const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite(const int n, const double x);\r\nint gsl_sf_hermite_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_deriv(const int m, const int n, const double x);\r\nint gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_func(const int n, const double x);\r\nint gsl_sf_hermite_func_fast_e(const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_func_fast(const int n, const double x);\r\nint gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_prob_array_deriv(const int m, const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_prob_deriv_array(const int mmax, const int n, const double x, double * result_array);\r\nint gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_prob_series(const int n, const double x, const double * a);\r\nint gsl_sf_hermite_array(const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_array_deriv(const int m, const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_deriv_array(const int mmax, const int n, const double x, double * result_array);\r\nint gsl_sf_hermite_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_series(const int n, const double x, const double * a);\r\nint gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_func_series(const int n, const double x, const double * a);\r\nint gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_func_der(const int m, const int n, const double x);\r\nint gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_prob_zero(const int n, const int s);\r\nint gsl_sf_hermite_zero_e(const int n, const int s, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_zero(const int n, const int s);\r\nint gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_func_zero(const int n, const int s);\r\n\r\n#ifndef GSL_DISABLE_DEPRECATED\r\n\r\nint gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_phys(const int n, const double x);\r\nint gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_phys_der(const int m, const int n, const double x);\r\nint gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_phys_series(const int n, const double x, const double * a);\r\nint gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array);\r\nint gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result);\r\ndouble gsl_sf_hermite_phys_zero(const int n, const int s);\r\n\r\nint gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array);\r\nint gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array);\r\nint gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result);\r\ndouble 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": "1d7088a0aa5b10682acb8100afd4d5978fc8c78a", "size": 5538, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_sf_hermite.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "gsl-2.6/gsl/gsl_sf_hermite.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "gsl-2.6/gsl/gsl_sf_hermite.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": 55.9393939394, "max_line_length": 105, "alphanum_fraction": 0.7455760202, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.47565406210773614}} {"text": "/* ============================================================ *\n * lensing_3rd.h\t\t\t\t\t\t*\n * Martin Kilbinger, Liping Fu 2010.\t\t\t\t*\n * ============================================================ */\n\n#ifndef __LENSING_3RD_H\n#define __LENSING_3RD_H\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmo.h\"\n#include \"nofz.h\"\n#include \"lensing.h\"\n#include \"errorlist.h\"\n#include \"maths_base.h\"\n\n\n#define tenoverseven 1.428571428571\n#define fouroverseven 0.571428571429\n\n\n/* Minimum scale factor where a non-linear scale can be defined. *\n * See {a,b,c}scocou.\t\t\t\t\t\t */\n#define A_NL_MIN 0.02\n\n#define s2_min 0.1\n#define s2_max 1.0e6\n#define N_s2 50\n#define epsilon0 1.0e-2\n#define N_EFF_MIN -2.0\n\n\n/* more ce_xyz in smith2.h */\n#define lensing_3rd_base -2400\n#define lensing_3rd_wrongmode -1 + lensing_3rd_base\n#define lensing_3rd_rootbracket -4 + lensing_3rd_base\n#define lensing_3rd_slc -5 + lensing_3rd_base\n\ntypedef enum {fgauss=0, fpoly=1, ftophat=2, fdelta=3, fxip=4, fxim=5, fall=6} filter_t;\n\ntypedef enum {PT=0, SCOCOU=1, GM12} bispmode_t;\n#define sbispmode_t(i) ( \\\n i==PT ? \"PT\" : \\\n i==SCOCOU ? \"scocou01\" : \\\n i==GM12 ? \"GM12\" : \\\n \"\")\n#define Nbispmode_t 3\n\n/* Intrinsic 3rd-order alignment model */\ntypedef enum {ia_3rd_none, ia_3rd_S08} ia_3rd_t;\n#define sia_3rd_t(i) ( \\\n i==ia_3rd_none ? \"none\" : \\\n i==ia_3rd_S08 ? \"S08\" : \\\n \"\")\n#define Nia_3rd_t 2\n\n/* Bit-coded IA terms */\ntypedef enum {ia_3rd_undef, ia_GGI_GII_III, ia_only_GGI, ia_only_GII, ia_only_III} ia_3rd_terms_t;\n#define sia_3rd_terms_t(i) ( \\\n i==ia_3rd_undef ? \"undef\" : \\\n i==ia_GGI_GII_III ? \"GGI_GII_III\" : \\\n i==ia_only_GGI ? \"only_GGI\" : \\\n i==ia_only_GII ? \"only_GII\" : \\\n i==ia_only_III ? \"only_III\" : \\\n \"\")\n#define Nia_3rd_terms_t 5\n\n/* Source-lens clustering */\ntypedef enum {slc_none, slc_FK13} slc_t;\n#define sslc_t(i) ( \\\n i==slc_none ? \"none\" : \\\n i==slc_FK13 ? \"slc_FK13\" : \\\n \"\")\n#define Nslc_t 2\n\ntypedef enum {kkk=0, kkg=1, kgg=2, ggg=3} bispfield_t;\n\ntypedef struct {\n\n /* Lensing, including basic cosmology and redshift distribution)(s) */\n cosmo_lens *lens;\n\n /* Intrinsic alignment parameters */\n ia_3rd_t ia;\n ia_3rd_terms_t ia_terms;\n double A_GGI, theta_GGI, A_GII, theta_GII;\n\n /* Source-lens clustering */\n slc_t slc;\n double b_slc, gamma_slc;\n\n /* ============================================================ *\n * Precomputed stuff (at the moment only one redshift-bin). *\n * ============================================================ */\n\n interTable *k_NL, *n_eff;\n double scale_NL_amin;\n interTable2D **B_kappa[3];\n\n bispmode_t bispmode;\n\n} cosmo_3rd;\n\n\ntypedef struct {\n double r1, r2;\n cosmo_3rd *self;\n} cosmo3ANDdoubleANDdouble;\n\ntypedef struct {\n double r1, r2;\n cosmo_3rd *self;\n int i, n_bin[3];\n} cosmo3ANDtomo;\n\ntypedef struct {\n cosmo_3rd *self;\n double R[3];\n filter_t wfilter;\n int n_bin[3];\n int m;\n error **err;\n} cosmo3ANDmorestuff;\n\ntypedef struct {\n cosmo_3rd *self;\n error **err;\n double a1, a2, f1, f2, R;\n} cosmo3SLC;\n\ncosmo_3rd *init_parameters_3rd(double OMEGAM, double OMEGAV, double W0_DE, double W1_DE,\n\t\t\t double *W_POLY_DE, int N_POLY_DE,\n\t\t\t double H100, double OMEGAB, double OMEGANUMASS,\n\t\t\t double NEFFNUMASS, double NORM, double NSPEC,\n\t\t\t int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,\n\t\t\t nonlinear_t NONLINEAR, transfer_t TRANSFER,\n\t\t\t growth_t GROWTH, de_param_t DEPARAM,\n\t\t\t norm_t normmode,\n\t\t\t ia_t IA, ia_terms_t IA_TERMS, double A_IA,\n\t\t\t bispmode_t BISPMODE,\n\t\t\t ia_3rd_t IA_3RD, ia_3rd_terms_t IA_3RD_TERMS, double A_GGI, double theta_GGI,\n\t\t\t double A_GII, double theta_GII,\n\t\t\t slc_t slc, double b_slc, double gamma_slc,\n\t\t\t error **err);\n\nvoid consistency_parameters_3rd(const cosmo_3rd *self, error **err);\ncosmo_3rd *copy_parameters_3rd_only(cosmo_3rd *source, error **err);\nvoid updateFrom_3rd(cosmo_3rd *avant, cosmo_3rd *apres, error **err);\ncosmo_3rd *set_cosmological_parameters_to_default_lens_3rd(error **err);\nvoid read_cosmological_parameters_lens_3rd(cosmo_3rd **self, FILE *F, error **err);\nvoid free_parameters_3rd(cosmo_3rd **self);\nvoid dump_param_3rd(cosmo_3rd* self, FILE *F, error **err);\n\ndouble dcub(double a);\ndouble n_eff_one(cosmo *self, double k, error **err);\ndouble n_eff(cosmo_3rd *, double, int, error **);\ndouble Q3(double, error **err);\ndouble temp_NL(double, double, cosmo *, error **);\ndouble scale_NL(cosmo_3rd *, double, error **);\n\ndouble ascocou(cosmo_3rd *, double, double, error **);\ndouble bscocou(cosmo_3rd *, double, double, error **);\ndouble cscocou(cosmo_3rd *, double, double, error **);\n\ndouble int_for_B_kappa_bar0(double a, void *intpar, error **err);\ndouble int_for_B_kappa_bar1(double a, void *intpar, error **err);\ndouble int_for_B_kappa_bar2(double a, void *intpar, error **err);\ndouble int_for_B_kappa_bar3(double a, void *intpar, error **err);\n\ndouble F2eff(cosmo_3rd *, double a, double k1, double k2, double cosphi, error **);\ndouble F2bar(int, double, double, error **);\ndouble F2(int, double, double, error **);\ndouble F2cos(int, double, error **err);\n\ndouble Q_123(cosmo_3rd *, double, double, double, double, error **);\ndouble bb(cosmo_3rd *, double, double, double, int i_bin, int j_bin, int k_bin, error **);\ndouble B_kappa_bar(cosmo_3rd *self, double s1, double s2, int abc, int i_bin, int j_bin, int k_bin, error **err);\n\ndouble hept_rtbis(double (*func)(double,double,cosmo*,error**), double, double,\n\t\t double, double, cosmo *, error **);\ndouble B_delta(cosmo_3rd *self, double k1, double k2, double cosbeta, double a,\n\t error **err);\n\ndouble Uhat_one(double x, filter_t wfilter);\ndouble Uhat(double eta, filter_t wfilter);\nvoid permute3(double *x, int offset);\ndouble int_for_map3_3d(double x[], size_t dim, void *intpar);\ndouble map3_perm(cosmo_3rd *self, double R[3], int i_bin, int j_bin, int k_bin, filter_t wfilter, error **err);\ndouble map3(cosmo_3rd *self, double R[3], int i_bin, int j_bin, int k_bin, filter_t wfilter, error **err);\n\ndouble int_for_E_GGI(cosmo_lens *self, double zs1, double zs2, double zl, error **err);\ndouble E_GGI(cosmo_lens *self, error **err);\ndouble map3_GGI(cosmo_3rd *self, double theta, error **err);\n\ndouble int_for_E_GII(cosmo_lens *self, double zs, double zl, error **err);\ndouble E_GII(cosmo_lens *self, error **err);\ndouble map3_GII(cosmo_3rd *self, double theta, error **err);\n\ndouble map3_SLC_t1(cosmo_3rd *self, double R, int n_bin, error **err);\ndouble bias_SLC(cosmo_3rd *self, double a, error **err);\ndouble int_for_Q_mc(double x[], size_t dim, void *intpar);\ndouble Q_mc(cosmo_3rd *self, double a1, double a2, double f1, double f2, double R, double *abserr,\n\t double *chisqr, error **err);\n\n\ndouble lensing_signal_3rd(cosmo_3rd *self, double theta[3], int i_bin, int j_bin, int k_bin, error **err);\nvoid fill_dmm_map3gauss_diag(cosmo_3rd *self, double *data_minus_model, int start, const double *data,\n\t\t\t int Nzbin, int Ntheta, double *theta, error **err);\nvoid fill_dmm_map3gauss(cosmo_3rd *self, double *data_minus_model, int start, const double *data,\n\t\t\tint Ntheta, double *theta, error **err);\ndouble chi2_lensing_3rd(cosmo_3rd *self, datcov *dc, const cosebi_info_t *cosebi_info, error **err);\n\n\n\n#endif\n\n", "meta": {"hexsha": "264522a192a250af440419e90dc812f9995b008d", "size": 7590, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nicaea_2.5/Cosmo/include/lensing_3rd.h", "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_issues_repo_path": "src/nicaea_2.5/Cosmo/include/lensing_3rd.h", "max_issues_repo_name": "danielgruen/ccv", "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "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/nicaea_2.5/Cosmo/include/lensing_3rd.h", "max_forks_repo_name": "danielgruen/ccv", "max_forks_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "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.2894736842, "max_line_length": 113, "alphanum_fraction": 0.6777338603, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.47560960322837964}} {"text": "//gcc -g meanpreds.c -o meanpreds\n#include \n#include \n#include \n#include \n#include \"my_misc.c\"\n#define isnum(c) (((c>='0') && (c<='9'))||(c=='-')||(c=='+')||(c==' '))\n//static char pr[1024];\n#include \n#include \n//#include \n#include \n//#include \"my_misc.c\"\n//#define GSL 1\n#undef GSL\n#define GSL 1\n//#define GSL 0\nint GSLtag;\nvoid least_gsl_error_handler( const char * reason,\n\t\t\t const char * file,\n\t\t\t int line,\n\t\t\t int gsl_errno)\n{\n // printf(\"%s:%d: %s (gsl_error: %s)\\n\", \n //\t file, line, reason, gsl_strerror(gsl_errno));\n printf(\"%s:%d: %s (gsl_error %d)\\n\", \n\t file, line, reason,gsl_errno);\n GSLtag=1;\n}\ndouble VarY;\nvoid calc_Ainvb(double *M, double *A_data, double *b_data, int nx, int ndata,int nxmarume)\n{\n /* b= A M --> M= Ainv b\n b in R^{ndata x 1}\n A in R^{ndata x nx} (ndata>nx)\n M in R^{nx x 1}\n */\n int i;\n gsl_vector *S;\n gsl_vector *work;\n gsl_vector *x;\n gsl_vector *b;\n gsl_matrix *V;\n gsl_matrix *A;\n if(ndata<=0){\n M[0]=1;\n for(i=1;idata=b_data;\n A->data=A_data; \n // for(i=0;idata[i],b->data[i],i); }\n \n V = gsl_matrix_alloc (nx,nx); \n S = gsl_vector_alloc (nx); \n work = gsl_vector_alloc(nx); \n x = gsl_vector_alloc(nx); \n \n gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0;\n \n#if GSL == 1\n gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh\n#elif GSL == 2\n gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh\n#elif GSL == 3\n {//faster\n gsl_matrix *X;\n X = gsl_matrix_alloc (nx,nx); \n gsl_linalg_SV_decomp_mod (A, X, V, S, work); \n gsl_matrix_free(X);\n }\n#endif\n // for(i=nxmarume;i40) break;\n // fprintf(stdout,\"S->data[%d]=%e;\",i,S->data[i]);\n fprintf(stdout,\"(%d)%e\",i,S->data[i]);\n }\n fprintf(stdout,\"\\n\");\n VarY=0;\n if(GSLtag==1){\n fprintf(stderr,\"\\nEigenValue=\");for(i=0;idata[i]); fprintf(stderr,\"\\n\");\n for(i=0;i=0){//Principal Component Analysis\n\tfor(i=nxmarume;idata[i]=0;\n\tfor(i=0;idata[i];\n\tgsl_linalg_SV_solve(A,V,S,b,x);\n\tfor(i=0;i10) break;\n\t//\tyhat=b_data[i];\n\t//\tfor(j=0;j=0;i--){\n\t if(S->data[i]>1e-20){\n\t ii++;\n\t VarY+=S->data[i];\n\t if(ii>=im) break;\n\t }\n\t}\n\tint j;\n\n\tdouble M0=-V->data[i];\n\tfor(j=1;jdata[j*nx+i]/M0;\n\t}\n//\tdouble M0=-V->data[i*nx];\n//\tfor(j=1;jdata[i*nx+j]/M0;\n//\t}\n\n }\n }\n gsl_vector_free(S);\n gsl_vector_free(work);\n gsl_vector_free(x);\n gsl_matrix_free(V);\n gsl_matrix_free(A);\n gsl_vector_free(b);\n }\n}\nvoid calc_AtinvbMCA(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume)\n{ \n /* b= A M --> M= Ainv b\n b in R^{ndata x 1}\n A=At in R^{ndata x nx} \n M in R^{nx x 1}\n */\n int nx1=nx+1,i,j,jnx1;\n gsl_matrix *A =gsl_matrix_alloc(ndata,nx1);\n for(j=0;jdata[jnx1]=b_data[j];\n for(i=0;idata[jnx1+i+1]=At_data[i*ndata+j];\n }\n }\n calc_Ainvb(M, (double *)(A->data), b_data, nx1, ndata, -nxmarume);\n \n gsl_matrix_free(A);\n}\nvoid calc_Atinvb(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume)\n{ \n /* b= A M --> M= Ainv b\n b in R^{ndata x 1}\n A=At in R^{ndata x nx} \n M in R^{nx x 1}\n */\n gsl_matrix *At =gsl_matrix_alloc(nx,ndata);\n gsl_matrix *A =gsl_matrix_alloc(ndata,nx);\n At->data=At_data;\n gsl_matrix_transpose_memcpy(A, At);\n calc_Ainvb(M, (double *)(A->data), b_data, nx, ndata, nxmarume);\n gsl_matrix_free(A);\n gsl_matrix_free(At);\n}\nvoid calc_yp(double *y, double *a_data, int nx, int ndata,int nxmarume)\n{//M[i]=Ainv b\n int i, l,j;\n double sumS=0,sumSj=0;\n gsl_vector *S;\n gsl_vector *work;\n gsl_vector *x;\n // gsl_vector *b;\n gsl_matrix *V;\n gsl_matrix *A;\n A =gsl_matrix_alloc(ndata,nx);\n A->data=a_data; \n // b =gsl_vector_alloc(ndata);\n // b->data=b_data;\n V = gsl_matrix_alloc (nx,nx); \n S = gsl_vector_alloc (nx); \n work = gsl_vector_alloc(nx); \n x = gsl_vector_alloc(nx); \n \n gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0;\n \n#if GSL == 1\n gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh\n#elif GSL == 2\n gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh\n#elif GSL == 3\n {//faster\n gsl_matrix *X;\n X = gsl_matrix_alloc (nx,nx); \n gsl_linalg_SV_decomp_mod (A, X, V, S, work); \n gsl_matrix_free(X);\n }\n#endif\n // for(i=nxmarume;i=0){\n for(i=0;idata[l]*A->data[i*nx+l]*V->data[j*nx+l];\n\t y[i]+=gsl_vector_get(S,l)*gsl_matrix_get(A,i,l)*gsl_matrix_get(V,j,l);\n\t}\n }\n y[i]/=nx;\n if(i<5){\n\tsumSj+=gsl_vector_get(S,i);\n\tfprintf(stderr,\"[%d]y=%e, s=%e, CumulativeProp=%f=%f/%f\\n\",i,y[i],gsl_vector_get(S,i),sumSj/sumS,sumSj,sumS);\n }\n }\n }\n else{\n int ll=0;\n for(i=0;i=-nxmarume) break;\n }\n y[i]/=nx;\n if(i<5){\n\tsumSj+=gsl_vector_get(S,i);\n\tif(i<5) fprintf(stderr,\"[%d]y=%e, s=%e, CumulativeProp=%f=%f/%f\\n\",i,y[i],gsl_vector_get(S,i),sumSj/sumS,sumSj,sumS);\n }\n }\n }\n gsl_vector_free(S);\n gsl_vector_free(work);\n gsl_vector_free(x);\n gsl_matrix_free(V);\n}\n\n////For Maximizing the Entropy of the training data\n////For Minimizing the minus of the Entropy of the training data\n//Lagrange Method\nint\nmy_df_Entropy(const gsl_vector *v, void *params, gsl_vector *df)\n{\n double **dp = (double **)params;\n int nd=(int)((double)*dp[0]);\n int nl=(int)((double)*dp[1]);\n double *y=(double *)dp[2];\n double *f=(double *)dp[3];\n int sgn=(int)((double)*dp[4]);\n double *yp=(double*)malloc(sizeof(double)*nd);\n double *e2=(double*)malloc(sizeof(double)*nd);\n double *e =(double*)malloc(sizeof(double)*nd);\n double *dHdp=(double*)malloc(sizeof(double)*nd);\n double *dpde2=(double*)malloc(sizeof(double)*nd*nd);\n double E2,lognd=log(nd),pi;\n int i,j,k,l;\n\n E2=0;\n for(i=0;idata[j])*f[j*nd+i];\n e[i]=(y[i]-yp[i]);\n e2[i]=e[i]*e[i];\n E2+=e2[i];\n }\n for(i=0;idata[l]=0;\n for(i=0;idata[l]+=dHdp[i]*dpde2[i*nd+k]*(2.*e[k]*(-2.*v->data[l]*f[l*nd+k]));\n\t//\tdf->data[l]+=dHdp[i]*dpde2[i*nd+k]*(-2.*e[k]*f[l*nd+k]);\n }\n df->data[l]+= 2.*v->data[nl]*v->data[l]*sgn;//for Penalty\n // df->data[l]-= 2.*v->data[nl]*v->data[l];//for Penalty\n // df->data[l] = C0*(-2.*e[i]*f[l*nd+i])/E0 +C1*df->data[l];//for H=C0*E2/E0+C1*Entropy\n }\n // dfnorm+=square(df->data[l]);\n // fprintf(stdout,\"%.4f \",df->data[l]);\n }\n //Lagrange for sumv=1. v->data[nd]=lambda \n double sumv=0;//for Lagrange\n for(j=0;jdata[j]);//for Lagrange\n df->data[nl]=(sumv-1.)*sgn;//for Lagrange L=H+lambda*(sum c_l-1)\n // df->data[nl]=1.-sumv;//for Lagrange L=H-lambda*(sum c_l-1)\n // fprintf(stdout,\";dfnorm=%.4e\\n\",dfnorm);\n free(yp);\n free(e);\n free(e2);\n return GSL_SUCCESS;\n}\nint\ngsl_print_state (size_t iter, gsl_multiroot_fsolver * s, void *params)\n{\n double **dp = (double **)params;\n int nd=(int)((double)*dp[0]);\n int nl=(int)((double)*dp[1]);\n double *y=(double *)dp[2];\n double *f=(double *)dp[3];\n double *yp=(double*)malloc(sizeof(double)*nd);\n double *e2=(double*)malloc(sizeof(double)*nd);\n double *e =(double*)malloc(sizeof(double)*nd);\n double E2,pi;\n int i,j;\n \n E2=0;\n for(i=0;ix, j))*f[j*nd+i];\n e[i]=(y[i]-yp[i]);\n e2[i]=e[i]*e[i];\n E2+=e2[i];\n }\n double H=0;//\n for(i=0;ix, 0)),\n\t gsl_vector_get (s->x, nl),\n\t gsl_vector_get (s->f, 0),\n\t gsl_vector_get (s->f, nl));\n return 0;\n}\n\n//////For Maximizing the Entropy of the training data\n//////For Minimizing the minus of the Entropy of the training data\n//double\n//my_f_Entropy(const gsl_vector *v, void *params)\n//{\n// //params\n// /*\n// e_i=y_i- sum_l v[l] f[l][i] (l=0:nx-1)\n// p_i= e_i^2/ sum_j e_j^2\n// H= sum_i p_i log(p_i);\n//\n// */\n// double **dp = (double **)params;\n// int nd=(int)((double)*dp[0]);\n// int nl=(int)((double)*dp[1]);\n// double *y=(double *)dp[2];\n// double *f=(double *)dp[3];\n// double C0=(double)*dp[4];\n//// double C1=(double)*dp[5];\n//// double E0=(double)*dp[6];\n// double *e2=(double*)malloc(sizeof(double)*nd);\n// double E2;\n// double H,ypi,pi;\n// int i,j;\n// E2=0;\n// for(i=0;idata[j])*f[j*nd+i];\n// e2[i]=square(ypi-y[i]);\n// E2+=e2[i];\n// }\n// H=0;\n// for(i=0;idata[nd]=lambda \n// double sumv=0;//for Lagrange\n// for(j=0;jdata[j]);//for Lagrange\n// // if(C0*(sumv-1.)<0) C0*=-1;\n// // H+=v->data[nl]*(sumv-1.);//for Lagrange \n// fprintf(stderr,\"H=%f,sumv=%e\",H,sumv);\n// H+=C0*(sumv-1.);//for Penalty method\n// /////\n// free(e2);\n// return H;\n//}\n//\n///* The gradient of f, df = (df/dx, df/dy). */\n//void\n//my_df_Entropy(const gsl_vector *v, void *params,\n// gsl_vector *df)\n//{\n// double **dp = (double **)params;\n// int nd=(int)((double)*dp[0]);\n// int nl=(int)((double)*dp[1]);\n// double *y=(double *)dp[2];\n// double *f=(double *)dp[3];\n// double C0=(double)*dp[4];\n// // double C1=(double)*dp[5];\n// // double E0=(double)*dp[6];\n// double *yp=(double*)malloc(sizeof(double)*nd);\n// double *e2=(double*)malloc(sizeof(double)*nd);\n// double *e =(double*)malloc(sizeof(double)*nd);\n// double *dHdp=(double*)malloc(sizeof(double)*nd);\n// double *dpde2=(double*)malloc(sizeof(double)*nd*nd);\n// double E2,lognd=log(nd),pi;\n// int i,j,k,l;\n//// {\n//// double sumv;\n//// for(j=0;jdata[j]);//for Lagrange\n//// if(C0*(sumv-1.)<0) C0*=-1;\n//// }\n// E2=0;\n// for(i=0;idata[j])*f[j*nd+i];\n// e[i]=(y[i]-yp[i]);\n// e2[i]=e[i]*e[i];\n// E2+=e2[i];\n// }\n// for(i=0;idata[l]=0;\n// for(i=0;idata[l]+=dHdp[i]*dpde2[i*nd+k]*(2.*e[k]*(-2.*v->data[l]*f[l*nd+k]));\n//\t//\tdf->data[l]+=dHdp[i]*dpde2[i*nd+k]*(-2.*e[k]*f[l*nd+k]);\n// }\n// df->data[l]+= 2.*C0*v->data[l];//for Penalty\n// // df->data[l] = C0*(-2.*e[i]*f[l*nd+i])/E0 +C1*df->data[l];//for H=C0*E2/E0+C1*Entropy\n// }\n// dfnorm+=square(df->data[l]);\n// // fprintf(stdout,\"%.4f \",df->data[l]);\n// }\n// //Lagrange for sumv=1. v->data[nd]=lambda \n// // double sumv=0;//for Lagrange\n// // for(j=0;jdata[j]);//for Lagrange\n// // df->data[nl]=sumv-1.;//for Lagrange\n//\n// fprintf(stdout,\";dfnorm=%.4e\\n\",dfnorm);\n// free(yp);\n// free(e);\n// free(e2);\n//}\n//\n///* Compute both f and df together. */\n//void\n//my_fdf_Entropy(const gsl_vector *x, void *params,\n//\tdouble *f, gsl_vector *df)\n//{\n// *f = my_f_Entropy(x, params);\n// my_df_Entropy(x, params, df);\n//}\n\n////\ntypedef struct{\n int r1;\n int r2;\n double r3;\n int nr;\n double r12;\n double *r;\n double ymin;\n double ymax;\n} RESOLUTION;\n#define ZERO 1e-20\nint init_res(RESOLUTION *res)\n{\n int i;\n char buff[32];\n if(res->r2==0) return(-1);\n if(fabs(res->ymax-res->ymin)r2=0;\n return(-1);\n }\n if(res->r3<-ZERO){//negrect resolution for the meanpred\n res->r2=0;\n return(-1);\n }\n res->r12=(double)res->r1/res->r2;\n // res->nr=(res->ymax-res->ymin)/res->r12;\n res->nr=(res->ymax-res->ymin)/res->r12+0.5;//??\n // res->r12=(res->ymax-res->ymin)/res->nr;//for ymin and ymax more reliable than r1 and r2 for ijcnn06\n res->r=(double*)malloc(sizeof(double)*(res->nr+1));\n if(fabs(res->r3)>ZERO){\n for(i=0;i<=res->nr;i++){\n sprintf(buff,\"%.10le\",((int)((i*res->r12+res->ymin)/res->r3+0.5))*res->r3);//r3\u001b$B7e$G;Mr[i]);\n }\n }\n else{\n for(i=0;i<=res->nr;i++){\n sprintf(buff,\"%.10le\",(double)i*res->r12+res->ymin);\n sscanf(buff,\"%lf\",&res->r[i]);\n }\n }\n return(0);\n}\ndouble y_res(double y,RESOLUTION *res)\n{\n int ii;\n if(res->r2==0) return(y);\n // ii=(int)((y-ymin)/r12+0.5);//4sha5nyu\n ii=floor((y-res->ymin)/res->r12+0.5);//4sha5nyu\n if(yymin) return((double)res->r[0]);\n if(y>res->ymax) return((double)res->r[res->nr]);\n return((double)res->r[ii]);\n}\n#define buffsize 1024\nint main(int argc, char **argv)\n{\n int i,j,l;\n FILE *fp;\n char buff[buffsize];\n double *yp,_yp;\n double *y,_y,*yr,_yr;\n int *n,_n; \n int num=0,num0=0;\n // char *fnpredict=\"predict+.dat\";\n // char *fnloss=\"loss+.dat\";\n int intmode=0, j0=1,nfiles=argc-1;\n char fn_is[256],fn_pred[256],fn_pred0[256],fn_prob[256];\n double _is,_mseis,_n_msetrain,_msetrain,_n_cells2,_nCells1,_n_mse,_mse,_msetrainis;\n double *prob,*sigma2,meansigma2,probtotal;\n FILE *fp0;\n int bayesmode=0; //0 (for flat probability) or 1 (for probatility decaying according to MSE).\n double bayesopt1=0;//for adjusting probability (1 for same probatility)\n double bayesopt2=0;//0 for original L, 1 for L_derivative requiring nfiles>=3.\n double bayesopt3=0;//??\n double bayesopt4=0;//??\n // double *ds;\n // int *s;\n double Lvar,Lvarval,Lval,LD=0,_LD;//\n double skew,kurtosis,entropy,skew2,skewa;//skew=3rd moment, kurtosis=4th moment\n double m2,m3,m4,m5,m6,m3a,m5a;//5th moment, 6th moment\n double m3p,m3m;//m3plus,m3minus\n int nm3p,nm3m;\n double mcov;//mean covariance\n double Lvar0;\n double Ltrain,LtrainE,H0;\n double *var,*vv;\n int *cc,ccmax=0;\n double _var,_vv,_cc;\n double *kyorix2,_kyorix2,_e2;\n int LDmode=2;\n RESOLUTION res={0,0,0,};\n double *yp00;\n int nop=0;\n if(argc<2){\n fprintf(stderr,\"Usage: %s [ib::[:]] ... \\n\",argv[0]);\n fprintf(stderr,\":1 for intmode, 0 for real.\\n\");\n fprintf(stderr,\":0 simple ensemble.?\\n\");\n fprintf(stderr,\":1 for bayes mode1 exp.\\n\");\n fprintf(stderr,\":2 for bayes mode2 YpInvY.\\n\");\n fprintf(stderr,\":-1 for reading from probfile.\\n\");\n fprintf(stderr,\"res::::.\\n\");\n fprintf(stderr,\"Old Usage: %s [:] ... \\n\",argv[0]);\n fprintf(stderr,\"par:paramfile.\\n\");\n exit(1);\n }\n // fprintf(stderr,\"last arg[%d]='%s'\\n\",argc,argv[argc-1]);\n int parfile=0;\n //\n for(i=1;i=100){}//end of bayesmode>=100\n else{//bayesmode <100\n if(bayesmode==0){//same probability\n probtotal=nfiles;\n for(j=0;j=0) sgn=1; else sgn=-1;\n\t par[0]=(double *)&nd;\n\t par[1]=&nl;\n\t par[2]=&yt[0];\n\t par[3]=&yp01[j*num0];\n\t par[4]=&sgn;\n\t const gsl_multiroot_fsolver_type *T;\n\t gsl_multiroot_fsolver *s;\n\t gsl_multiroot_function df = {&my_df_Entropy, nl1, &par};\n\t gsl_vector *x = gsl_vector_alloc (nl1); //&ww[(l*nmean+j)*nfiles];\n\t for(i=0;i<=nl;i++) gsl_vector_set (x, i, sqrt(1./nl));\n\t gsl_vector_set (x, nl, 0.0);//Good!?\n\t T = gsl_multiroot_fsolver_hybrids;\n\t s = gsl_multiroot_fsolver_alloc (T, nl1);\n\t gsl_multiroot_fsolver_set (s, &df, x);\n\t gsl_print_state (iter, s, par);\n\t do {\n\t\titer++;\n\t\tstatus = gsl_multiroot_fsolver_iterate (s);\n\t\tgsl_print_state (iter, s, par);\n\t\t/* check if solver is stuck */\n\t\tif (status) {\n\t\t printf (\"Minimum not found (ERR=%d)? See /usr/include/gsl/gsl_errno.h for details.\",status);\n\t\t if (status==GSL_EBADFUNC) {printf (\"Encountered a singular point.\\n\");}\n\t\t else if (status==GSL_EBADFUNC) {printf (\"Noprogress.\\n\");}\n\t\t else if (status==GSL_ENOPROGJ) {printf (\" ERR=%d:Jacobian is not improving the solution.\\n\",GSL_ENOPROGJ);}\n\t\t break;}//break at Sucess or failure ?\n\t\t//\t\tstatus = gsl_multiroot_test_residual (s->f, 1e-7);\n\t\tstatus = gsl_multiroot_test_residual (s->f, 1./nl);\n\t } while (status == GSL_CONTINUE && iter < itermax);\n\t for(i=0;ix, i));\n\t gsl_multiroot_fsolver_free (s);\n\t gsl_vector_free (x);\n\t double sumw=0;\n\t fprintf(stderr,\"w[%d,%d]:\",j,l);\n\t for(i=0;i=2) Lvar0 /=((num0+ZERO)*(nfiles2)*(nfiles2-1));//estimated variance of ensemble prediction\n else Lvar0 /=(num0+ZERO); //average of unbiased estimator\n Ltrain/=(num0+ZERO);\n LtrainE/=(nfiles*num0+ZERO);\n // free(yp01);//??why bat result if active?\n#define Ltrain4Entropy\n#ifdef Ltrain4Entropy\n {\n\tdouble pn,E2sum=Ltrain*num0;//Entropy\n\tH0=0;\n\tfor(i=0;i=m_LD && j=m_LD && j0)?(err2_):(-err2_);//?\n\t m3j+=(err2_*=err);//skewj+=(errn=err2*err);//m3j\n\t if(err>0){\n\t nm3pj++;\n\t m3pj+=err2_;//err^3\n\t }\n\t else if(err<0){\n\t nm3mj++;\n\t m3mj+=err2_;//err^3\n\t }\n\t m4j+=(err2_*=err);//kurtosis+=(errn=errn*err);//m4j\n\t m5j+=(err2_*=err);\n\t m6j+=(err2_*=err);\n\t //Lvar += square(yp[i]-yp00[(j+m_LD)*num+i]);\n\t //Lvar += square(yp[i]-yp00[(j+m_LD)*num+i]);\n\t //Lvar += exp(square(yp[i]-yp00[(j+m_LD)*num+i]));//???060530\n\t Lvarval += square(yp00[(j+m_LD)*num+i]-y[i]);\n\t {//mean covariance\n\t int l;\n\t for(l=0;l1900) fprintf(stderr,\"[%d]Lval=%9.3e,yp=%.3e,y=%.3e\\n\",i,Lval/num,yp[i],y[i]);\n\t}//closing for(i=0;i=2) Lvar /=((num)*(nfiles2)*(nfiles2-1.));//estimated variance of ensemble prediction\n\t//if(nfiles2>=2) Lvar /=num2;//estimated variance of ensemble prediction\n\t//else Lvar/=(num);\n\tfor(i=0;i\n\nnamespace blas {\n\n\ninline void gemm(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* B, bool transposeB, int rowsB, int colsB, double alpha = 1.0, double beta = 0.0)\n{\n\tcblas_dgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB);\n}\n\ninline void gemm(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* B, bool transposeB, int rowsB, int colsB, float alpha = 1.0f, float beta = 0.0f)\n{\n\tcblas_sgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB);\n}\n\ninline void gemv(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* x, double alpha = 1.0, double beta = 0.0)\n{\n\tcblas_dgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1);\n}\n\ninline void gemv(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* x, float alpha = 1.0, float beta = 0.0)\n{\n\tcblas_sgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1);\n}\n\ninline void ger(double* Y, const double * A, int rowsA, const double* X, int rowsX, double alpha = 1.0)\n{\n\tcblas_dger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX);\n}\n\ninline void ger(float* Y, const float * A, int rowsA, const float* X, int rowsX, float alpha = 1.0)\n{\n\tcblas_sger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX);\n}\n\ninline double norm2(double* X, int n, int stride = 1)\n{\n\treturn cblas_dnrm2(n, X, stride);\n}\n\ninline float norm2(float* X, int n, int stride = 1)\n{\n\treturn cblas_snrm2(n, X, stride);\n}\n\ninline void scale(float alpha, float* X, int n, int stride = 1)\n{\n\treturn cblas_sscal(n, alpha, X, stride);\n}\n\ninline void scale(double alpha, double* X, int n, int stride = 1)\n{\n\treturn cblas_dscal(n, alpha, X, stride);\n}\n}\n\n#endif\n", "meta": {"hexsha": "802ab2e719c1a7366b3a29fbdb7b2378ff18110f", "size": 3568, "ext": "h", "lang": "C", "max_stars_repo_path": "neural_network/blas_wrapper.h", "max_stars_repo_name": "klindworth/disparity_estimation", "max_stars_repo_head_hexsha": "74759d35f7635ff725629a1ae555d313f3e9fb29", "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": "neural_network/blas_wrapper.h", "max_issues_repo_name": "klindworth/disparity_estimation", "max_issues_repo_head_hexsha": "74759d35f7635ff725629a1ae555d313f3e9fb29", "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": "neural_network/blas_wrapper.h", "max_forks_repo_name": "klindworth/disparity_estimation", "max_forks_repo_head_hexsha": "74759d35f7635ff725629a1ae555d313f3e9fb29", "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": 41.488372093, "max_line_length": 256, "alphanum_fraction": 0.740470852, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4752375861458337}} {"text": "/*\n * SPDX-License-Identifier: BSD-3-Clause\n * \n * example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c : \n * Example of SPH Density Calculation using a \n * naive implementation of the main density loop, \n * no neighbours earch, and Array of Structs (AoS) \n * data layout, OpenMP parallelization and SIMD \n * directives on the kernel and density calculation.\n * This incorporates strip mining and exchange to \n * implement cache blocking and support performance \n * for large number of particles that would otherwise\n * be lost. \n *\n * (C) Copyright 2021 José Hugo Elsas\n * Author: José Hugo Elsas \n *\n * Command Line Options: \n * -runs : Set the number of repetitions (runs) for\n * calculating the density. The value of\n * the density is based on the last \n * iteration.\n * Default value: 1\n * -run_seed : Flag to set an alternative seed use for\n * for the PRNG. Instead of feeding seed\n * to the PRNG directly, it feeds \n * seed + iteration, as to generate different\n * configurations for each iteration. \n * Default value: 0 - (possible 0/1)\n * -seed : Set the seed to use for the SPH particles \n * uniform position generation in the box\n * Default value: 123123123\n *\n * -N : Set the number of SPH particles to be used\n * Default value: 1e5 = 100,000\n * -h : Set the value of the smoothing kernel \n * parameter h, which corresponds to half\n * of the support of the kernel. \n * Default value: 0.05\n *\n * -Nx : Set the number of Cells in the X direction\n * Default value: 10\n * -Ny : Set the number of Cells in the Y direction\n * Default value: 10\n * -Nz : Set the number of Cells in the Z direction\n * Default value: 10\n * \n * -Xmin : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 0.0\n * -Ymin : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 0.0\n * \n * -Xmax : Set the lower bound in the X direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Ymax : Set the lower bound in the Y direction for \n * the Cell Linked List box \n * Default value: 1.0\n * -Zmax : Set the lower bound in the Z direction for \n * the Cell Linked List box \n * Default value: 1.0\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n#include \"sph_utils.h\"\n\n#ifndef M_PI\n#define M_PI (3.14159265358979323846)\n#endif\n\n#define COMPUTE_BLOCKS 1\n\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n linkedListBox *box, SPHparticle *lsph, double *times);\n\nint compute_density_3d_naive_omp_simd_tiled(int N,double h,SPHparticle *lsph);\n\ndouble w_bspline_3d_constant(double h);\n\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q);\n\nint main(int argc, char **argv){\n bool run_seed = false; // By default the behavior is is to use the same seed\n int err, runs = 1; // By default the main loop only runs once\n long int seed = 123123123; // The default seed is 123123123\n int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000\n double h=0.05; // The default kernel smoothing length is h = 0.05\n linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method\n SPHparticle *lsph; // Uninitialized array of SPH particles\n\n box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain\n\n // allow for command line customization of the run\n arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options\n // line arguments and override default values\n lsph = (SPHparticle*)malloc(N*sizeof(SPHparticle)); // Create an array of N particles\n \n double times[runs*COMPUTE_BLOCKS];\n\n for(int run=0;run : index (or value) or the present iteration\n * run_seed : boolean defining whether to use run index for seed or not\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * seed : seed for GSL PRNG generator to generate particle positions\n * box : Box of linked list cells, encapsulating the 3d domain\n * lsph : Array (pointer) of SPH particles to be updated\n * times : Array to store the computation timings to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n * times : Times is updated by reference\n */\nint main_loop(int run, bool run_seed, int64_t N, double h, long int seed, \n linkedListBox *box, SPHparticle *lsph, double *times)\n{\n int err;\n \n if(run_seed)\n err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);\n else\n err = gen_unif_rdn_pos_box(N,seed,box,lsph);\n\n if(err)\n fprintf(stderr,\"error in gen_unif_rdn_pos\\n\");\n\n // ------------------------------------------------------ //\n\n double t0,t1;\n\n t0 = omp_get_wtime();\n \n compute_density_3d_naive_omp_simd_tiled(N,h,lsph); // Compute the density for all particles\n\n t1 = omp_get_wtime();\n\n // ------------------------------------------------------ //\n\n times[COMPUTE_BLOCKS*run+0] = t1-t0; // Only one component to measure time\n\n return 0;\n}\n\n/*\n * Function compute_density_3d_naive_omp_simd_tiled:\n * Computes the SPH density from the particles implementing a strip mine and exchange\n * strategy to re-use data in cache over the direct loop. It executes calculations \n * in parallel for the outer-most loop using openMP and SIMD in inner-most loop, \n * though SIMD only for limited success. \n * \n * Reference: https://en.wikipedia.org/wiki/Loop_nest_optimization\n * \n * Arguments:\n * N : Number of SPH particles to be used in the run\n * h : Smoothing Length for the Smoothing Kernel w_bspline\n * lsph : Array (pointer) of SPH particles to be updated\n * Returns:\n * 0 : error code returned\n * lsph : SPH particle array is updated in the rho field by reference\n */\nint compute_density_3d_naive_omp_simd_tiled(int N,double h,SPHparticle *lsph){\n const double inv_h = 1./h; // Pre-invert the smoothing distance \n const double kernel_constant = w_bspline_3d_constant(h); // Pre-compute the 3d normalization constant\n const int64_t STRIP = 500; // Setting the size of the strip or block \n\n #pragma omp parallel for // Run the iteration in Parallel\n for(int64_t ii=0;ii : Smoothing Length for the Smoothing Kernel w_bspline\n * Returns:\n * 3d bspline normalization density \n */\ndouble w_bspline_3d_constant(double h){ \n return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel\n}\n\n/*\n * Function w_bspline_3d_simd:\n * Returns the un-normalized value of the cubic b-spline SPH smoothing kernel\n * \n * Arguments:\n * q : Distance between particles normalized by the smoothing length h\n * Returns:\n * wq : Unnormalized value of the kernel\n * \n * Observation: \n * Why not else if(q<2.)? \n * Because if you use \"else if\", the compiler refuses to vectorize, \n * This results in a large slowdown, as of 2.5x slower for example_04\n */\n#pragma omp declare simd\ndouble w_bspline_3d_simd(double q){ // Use as input the normalized distance\n double wq = 0.0;\n double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline\n double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline\n \n if(q<2.) // If the distance is below 2\n wq = wq2; // Use the 2nd polynomial for the spline\n\n if(q<1.) // If the distance is below 1\n wq = wq1; // Use the 1nd polynomial for the spline\n \n return wq; // return which ever value corresponds to the distance\n}", "meta": {"hexsha": "d3d0ab813325548102a67f495216220069ea5d40", "size": 13063, "ext": "c", "lang": "C", "max_stars_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c", "max_stars_repo_name": "jhelsas/sphalerite", "max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c", "max_issues_repo_name": "jhelsas/sphalerite", "max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AoS/exec/example_04-ArrayOfStructs-Naive-Omp-SIMD-Tiled.c", "max_forks_repo_name": "jhelsas/sphalerite", "max_forks_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6748251748, "max_line_length": 126, "alphanum_fraction": 0.5627344408, "num_tokens": 3142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.4751173908470659}} {"text": "/*\n** LISA, 2nd level using design matrix\n**\n** G.Lohmann, July 2018\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n#define SQR(x) ((x)*(x))\n\nextern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);\nextern gsl_matrix *XRead2ndLevel(VString);\nextern double t2z(double t,double df);\n\n\ndouble EstimateVariance(gsl_matrix *XInv,gsl_vector *con)\n{\n int nbeta = XInv->size1;\n double var=0;\n\n gsl_matrix *bcov = gsl_matrix_calloc(nbeta,nbeta);\n gsl_blas_dgemm(CblasNoTrans,CblasTrans,1.0,XInv,XInv,0.0,bcov);\n\n gsl_vector *tmp = gsl_vector_alloc(nbeta);\n gsl_blas_dgemv(CblasTrans,1.0,bcov,con,0.0,tmp);\n gsl_blas_ddot (tmp,con,&var);\n double sigma = sqrt(var);\n gsl_matrix_free(bcov);\n gsl_vector_free(tmp);\n\n return sigma;\n}\n\n\n/* \n** get effective degrees of freedom \n*/\ndouble DoF(gsl_matrix *X,gsl_matrix *XInv,double *xtrace)\n{\n int i,nimages = X->size1;\n\n gsl_matrix *R = gsl_matrix_calloc (nimages,nimages);\n gsl_matrix *P = gsl_matrix_calloc (nimages,nimages);\n gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,X,XInv,0.0,P);\n gsl_matrix_set_identity(R);\n gsl_matrix_sub(R,P);\n\n double trace = 0;\n for (i=0; isize1;\n VFillImage(dest,VAllBands,0);\n\n\n /* permutation or sign switching applied to design matrix */\n gsl_matrix *XP = gsl_matrix_calloc(X->size1,X->size2);\n gsl_matrix_memcpy(XP,X);\n\n if (signswitch >= 0) { /* sign switching (one-sample test) */\n for (i=0; isize1; i++) {\n if (signtable[i] < 0) {\n\tu = gsl_matrix_get(X,i,signswitch);\n\tgsl_matrix_set(XP,i,signswitch,-u);\n }\n }\n }\n\n else { /* permutations */\n for (i=0; isize1; i++) {\n ip = permtable[i];\n for (j=0; jsize2; j++) {\n\tif (permflag[j] > 0) { /* do not permute columns containing nuisance covariates */\n\t u = gsl_matrix_get(X,i,j);\n\t gsl_matrix_set(XP,ip,j,u);\n\t}\n }\n }\n }\n\n \n /* pseudo inverse */\n gsl_matrix *XInv = PseudoInv(XP,NULL);\n\n\n /* get DoF and variance */\n double trace = 0;\n double df = DoF(XP,XInv,&trace);\n double sigma = EstimateVariance(XInv,contrast);\n if (df < tiny) VError(\" Zero degrees of freedom\");\n if (sigma < tiny) VError(\" No variance in design/contrast\");\n\n\n /* main loop */\n gsl_set_error_handler_off();\n gsl_vector *y = gsl_vector_alloc (nimages);\n gsl_vector *yz = gsl_vector_alloc (nimages);\n gsl_vector *beta = gsl_vector_alloc (X->size2);\n\n for (b=0; bdata[j] = VGetPixel(src[j],b,r,c);\n\t if (fabs(y->data[j]) > 0) nonzero++;\n\t}\n\tif (nonzero < nimages-2) continue;\n\n\n\t/* compute beta's */\n\tgsl_blas_dgemv(CblasNoTrans,1.0,XInv,y,0.0,beta);\n\n\n\t/* residuals */\n\tgsl_blas_dgemv(CblasNoTrans,1.0,XP,beta,0.0,yz);\n\terr = 0;\n\tfor (j=0; jdata[j] - yz->data[j];\n\t err += d*d;\n\t}\n\t\n\n\t/* get z-value */\n\tt = z = sum = 0;\n\tgsl_blas_ddot (beta,contrast,&sum);\n\tif (fabs(sum) < tiny) continue;\n\tvar = err / trace;\n\ttsigma = sqrt(var) * sigma;\n\tif (tsigma > tiny) {\n\t t = sum / tsigma;\n\t z = t2z(t,df);\n\t if (sum < 0) z = -z;\n\t}\n\tVPixel(dest,b,r,c,VFloat) = z;\n }\n }\n }\n\n gsl_vector_free(y);\n gsl_vector_free(yz);\n gsl_vector_free(beta);\n gsl_matrix_free(XP);\n gsl_matrix_free(XInv);\n}\n", "meta": {"hexsha": "032eed4adffa69d01d0d649e8dfacda50efa746a", "size": 4322, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_2ndlevel/2ndLevel.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.8677248677, "max_line_length": 128, "alphanum_fraction": 0.6402128644, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4747515618798562}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"util.h\"\n\n\n\nint main(int argc, char *argv[]) {\n char* input_fileName1 = argv[1];\n char* input_fileName2 = argv[2];\n int N_doc_bg = atoi(argv[3]);\n int N_kw = atoi(argv[4]);\n int N_obs = atoi(argv[5]);\n int N_iter = atoi(argv[6]);\n int m = atoi(argv[7]);\n double p = 0.89;\n double q = atof(argv[8]);\n char* output_fileName = argv[9];\n int N_doc = 480000/2;\n\n\n int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw);\n int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* true_index = (int*) malloc(sizeof(int) * N_kw);\n int* permutation = (int*) malloc(sizeof(int) * N_obs);\n gsl_matrix* matrix_obs;\n\n // Setup\n for (int round = 0; round < 10; round++)\n {\n char input_fileName1_extend[40];\n char input_fileName2_extend[40];\n sprintf(input_fileName1_extend, \"%s%d\", input_fileName1, round);\n sprintf(input_fileName2_extend, \"%s%d\", input_fileName2, round);\n\n struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);\n read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);\n gettimeofday(&tv2, NULL);\n printf(\"Reading done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n for (int iter = 0; iter < 10; iter++)\n {\n printf(\"Run %d\\n\", iter);\n matrix_obs = gsl_matrix_alloc(N_obs, N_obs);\n\n gettimeofday(&tv1, NULL);\n pad_matrix(&matrix_padded, &matrix, m, p, q, N_obs, N_doc);\n gettimeofday(&tv2, NULL);\n printf(\"Padding done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n gettimeofday(&tv1, NULL);\n observe_matrix(matrix_obs, &matrix_padded, N_obs);\n gettimeofday(&tv2, NULL);\n printf(\"Observed matrix generated: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n // Permute observed matrix randomly and attack\n \n gettimeofday(&tv1, NULL);\n attack(matrix_obs, &matrix_bg, &permutation, m, p, q, N_kw, N_obs, N_doc, N_iter);\n gettimeofday(&tv2, NULL);\n printf(\"Main attack done: %f.\\n\", (double) ((tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)) / N_iter);\n fflush(stdout);\n\n //for (int ii = 0; ii < 20; ii++)\n // printf(\"%d, %d, %d, %d, %d\\n\", permutation[ii], true_index[ii], matrix[ii*N_obs+ii], matrix_bg[true_index[ii]*N_kw+true_index[ii]], matrix_bg[permutation[ii]*N_kw+permutation[ii]]);\n\n char output_fileName_full[40];\n sprintf(output_fileName_full, \"%s%d-%d\", output_fileName, round, iter);\n print_result(output_fileName_full, &permutation, &true_index, N_obs);\n //sprintf(output_fileName_full, \"%s-%d-full\", output_fileName, iter);\n //print_full_result(output_fileName_full, permutation_matrix, N_kw);\n }\n }\n\n free(matrix);\n free(matrix_bg);\n free(matrix_padded);\n gsl_matrix_free(matrix_obs);\n return(0);\n}\n\n\ndouble log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int m, double p, double q, int N_kw, int N_doc)\n{\n int idx1_m = (*permutation)[idx1];\n int idx2_m = (*permutation)[idx2];\n\n double score = 0.0;\n if (idx1 == idx2)\n {\n int N1 = m * (*matrix)[idx1_m*N_kw + idx2_m];\n double N1_mean = p * N1;\n double N1_var = p * (1-p) * N1 + (m * N_doc - N1) * N1 * 1.0 / N_doc / m;\n\n int N2 = m * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n double N2_mean = q * N2;\n double N2_var = q * (1-q) * N2 + (m * N_doc - N2) * N2 * 1.0 / N_doc / m;\n\n double N3_var = 1.0 * m / N_doc * (*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n\n int k = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n \n score = gsl_cdf_gaussian_P(floor(k - N1_mean - N2_mean) + 0.5, sqrt(N1_var + N2_var + N3_var));\n score -= gsl_cdf_gaussian_P(floor(k - N1_mean - N2_mean) - 0.5, sqrt(N1_var + N2_var + N3_var));\n }\n\n\n else\n {\n int N1 = m * (*matrix)[idx1_m*N_kw + idx2_m];\n double N1_mean = p * p * N1;\n double N1_var = p * p * (1-p) * (1-p)* N1;\n\n int N2 = m * ((*matrix)[idx1_m*N_kw + idx1_m] + (*matrix)[idx2_m*N_kw + idx2_m] - 2*(*matrix)[idx1_m*N_kw + idx2_m]);\n double N2_mean = p * q * N2;\n double N2_var = p * q * (1-p) * (1-q) * N2;\n\n int N3 = m * N_doc - N1 - N2;\n double N3_mean = q * q * N3;\n double N3_var = q * q * (1-q) * (1-q) * N3;\n\n double N4_var = 1.0 * m / N_doc * (*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n\n int M = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n\n score = gsl_cdf_gaussian_P(floor(M - N1_mean - N2_mean - N3_mean) + 0.5, sqrt(N1_var + N2_var + N3_var + N4_var));\n score -= gsl_cdf_gaussian_P(floor(M - N1_mean - N2_mean - N3_mean) - 0.5, sqrt(N1_var + N2_var + N3_var + N4_var));\n }\n\n if (score == 0)\n return(-500.0);\n return(log(score));\n}\n\n\n\n\nvoid attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int m, double p, double q, int N_kw, int N_obs, int N_doc, int N_iter)\n{\n // Initialise data structures\n double* score_matrix = (double*) malloc(sizeof(double) * N_kw * N_kw);\n double* score_row1 = (double*) malloc(sizeof(double) * N_kw);\n double* score_row2 = (double*) malloc(sizeof(double) * N_kw);\n\n int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);\n int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);\n\n // Initialising RNG\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 struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n\n solution_initial(permutation, matrix_obs, matrix, m, p, q, N_kw, N_obs, N_doc);\n\n for (int ii = 0; ii < N_obs; ii++)\n permutation_tmp[ii] = (*permutation)[ii];\n for (int ii = 0; ii < N_kw; ii++)\n permutation_inv[ii] = -1;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_inv[permutation_tmp[ii]] = ii;\n\n // Compute initial score\n #pragma omp parallel for shared(score_matrix, matrix_obs, matrix)\n for (int ii = 0; ii < N_obs * N_obs; ii++)\n score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, m, p, q, N_kw, N_doc);\n gettimeofday(&tv2, NULL);\n printf(\"Initial score computed: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n \n // Iterations of simulated annealing\n double temp = (double) N_kw;\n int N_stuck = 0;\n for (int iter = 0; iter < N_iter; iter++)\n {\n /* Status code */\n\t if (iter % (N_iter / 10) == 0)\n {\n gettimeofday(&tv1, NULL);\n printf(\"Iteration: %d, %d, %d.\\n\", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));\n fflush(stdout);\n gettimeofday(&tv2, NULL);\n }\n\n\t if (N_stuck >= (N_iter / 20))\n iter = N_iter;\n\n int idx1, idx2;\n permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, matrix_obs, matrix, m, p, q, N_kw, N_obs, N_doc);\n if (idx1 == idx2)\n {\n N_stuck++;\n continue;\n }\n\n int ii = 0;\n #pragma omp parallel for shared(score_row1)\n for (ii = 0; ii < N_obs; ii++)\n score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, m, p, q, N_kw, N_doc);\n\n if (idx2 >= 0)\n #pragma omp parallel for shared(score_row2)\n for (ii = 0; ii < N_obs; ii++)\n score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, m, p, q, N_kw, N_doc);\n\n double score_diff = 0;\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx1*N_obs + ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx2*N_obs + ii];\n }\n\n // compute difference in score, with exponentiation\n score_diff = score_diff / temp;\n \n if (score_diff < -40)\n score_diff = 0;\n else if (score_diff > 0)\n score_diff = 1.01;\n else\n score_diff = exp(score_diff);\n\n if (gsl_ran_flat(r, 0, 1) < score_diff)\n {\n // Update the scores\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx1*N_obs + ii] = score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx1] = score_row1[ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx2*N_obs + ii] = score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx2] = score_row2[ii];\n }\n\n // Update the permutation\n permutation_inv[(*permutation)[idx1]] = -1;\n (*permutation)[idx1] = permutation_tmp[idx1];\n permutation_inv[permutation_tmp[idx1]] = idx1;\n if (idx2 >= 0)\n {\n (*permutation)[idx2] = permutation_tmp[idx2];\n permutation_inv[permutation_tmp[idx2]] = idx2;\n }\n N_stuck = 0;\n }\n else\n {\n // Update the permutation\n permutation_tmp[idx1] = (*permutation)[idx1];\n if (idx2 >= 0)\n permutation_tmp[idx2] = (*permutation)[idx2];\n N_stuck += 1;\n }\n\n temp *= 0.995;\n }\n\n free(score_matrix);\n free(score_row1);\n free(score_row2);\n gsl_rng_free(r);\n}\n\n\n\nvoid print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n int count2 = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n fprintf(fp, \"%d\\n\", count);\n fclose(fp);\n printf(\"Success: %d/%d.\\n\", count, N_obs);\n}\n\n\n\nvoid print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n fprintf(fp, \"%d\\n\", count);\n fclose(fp);\n}", "meta": {"hexsha": "31fd86512611923e8739731be2727105d4670c8d", "size": 11253, "ext": "c", "lang": "C", "max_stars_repo_path": "DPAP-SE/attack_mp.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DPAP-SE/attack_mp.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DPAP-SE/attack_mp.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.165625, "max_line_length": 198, "alphanum_fraction": 0.5585177286, "num_tokens": 3366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4744670949077991}} {"text": "\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern void gsl_sort_vector(gsl_vector *);\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n\nvoid WriteTest(gsl_matrix *data)\n{\n FILE *fp=0;\n VAttrList alist;\n VImage tmp;\n double u;\n int i,j;\n\n tmp = VCreateImage(1,data->size1,data->size2,VFloatRepn);\n for (i = 0; i < data->size1; i++) {\n for (j = 0; j < data->size2; j++) {\n u = gsl_matrix_get(data,i,j);\n VPixel(tmp,0,i,j,VFloat) = u;\n }\n }\n alist = VCreateAttrList();\n VAppendAttr(alist,\"image\",NULL,VImageRepn,tmp);\n fp = fopen(\"qtest.v\",\"w\");\n VWriteFile (fp,alist);\n fclose(fp);\n exit(0);\n}\n\n\ndouble \nestimateSigma(gsl_matrix *data)\n{\n int i,j,i2,j2,n,nn;\n gsl_vector *vec=NULL;\n double median=0,med0,u,xmax,tiny=1.0e-6;\n\n i2 = data->size1/2;\n j2 = data->size2/2;\n\n nn = 3 * (i2+1) * (j2+1);\n vec = gsl_vector_calloc(nn);\n\n\n /*\n ** first pass, median, no absolute values\n */\n xmax = VRepnMaxValue(VDoubleRepn);\n gsl_vector_set_all(vec,xmax);\n\n n = 0;\n for (i=0; isize2; j++) {\n u = gsl_matrix_get(data,i,j);\n if (ABS(u) > tiny) gsl_vector_set(vec,n++,u);\n }\n }\n\n for (i=i2; isize1; i++) {\n for (j=0; j tiny) gsl_vector_set(vec,n++,u);\n }\n }\n\n for (i=i2; isize1; i++) {\n for (j=j2; jsize2; j++) {\n u = gsl_matrix_get(data,i,j);\n if (ABS(u) > tiny) gsl_vector_set(vec,n++,u);\n }\n }\n \n gsl_sort_vector(vec);\n u = (double)n/2.0;\n nn = (int)u;\n med0 = 0.5*(gsl_vector_get(vec,nn) + gsl_vector_get(vec,nn+1));\n\n /*\n ** median, 2nd pass\n */\n xmax = VRepnMaxValue(VDoubleRepn);\n gsl_vector_set_all(vec,xmax);\n\n n = 0;\n for (i=0; isize2; j++) {\n u = gsl_matrix_get(data,i,j);\n if (ABS(u) <= tiny) continue;\n u = ABS(u - med0);\n gsl_vector_set(vec,n++,u);\n }\n }\n\n for (i=i2; isize1; i++) {\n for (j=0; jsize1; i++) {\n for (j=j2; jsize2; j++) {\n u = gsl_matrix_get(data,i,j);\n if (ABS(u) <= tiny) continue;\n u = ABS(u - med0);\n gsl_vector_set(vec,n++,u);\n }\n }\n \n gsl_sort_vector(vec);\n u = (double)n/2.0;\n nn = (int)u;\n median = 0.5*(gsl_vector_get(vec,nn) + gsl_vector_get(vec,nn+1));\n\n return (median/0.455);\n}\n\n\n\n\ndouble sgn(double x)\n{\n if (x < 0) return -1;\n else if (x > 0) return 1;\n else return 0;\n}\n\nvoid \nFiltering(gsl_matrix *data, int type, double intensity, double sigma)\n{\n int i,j,n;\n double d,dd,alpha;\n\n n = data->size1;\n\n double tau = sigma * intensity * sqrt(2 * log10((double) (n*n)));\n\n for (i=0; i < data->size1; i++) {\n for (j=0; j < data->size2; j++) {\n d = gsl_matrix_get(data,i,j);\n\n\n /* Wiener-Filter */\n if (type == 0) {\n\talpha = ((d * d) - intensity * (sigma * sigma)) / (d * d);\n\tif (alpha < 0) alpha = 0;\n\td *= alpha;\n }\n\n /* Soft-Threshold */\n else if (type == 1) {\n\tif (ABS(d) < tau)\n\t dd = 0;\n\telse\n\t dd = sgn(d) * (ABS(d) - tau);\n\td = dd;\n }\n\n /* Hard-Threshold */\n else if (type == 2) {\n\tif (ABS(d) < tau) d = 0;\n }\n\n gsl_matrix_set(data,i,j,d);\n }\n }\n}\n\nvoid\nShift(gsl_matrix *data,gsl_matrix *shiftdata,int ishift,int jshift)\n{\n int i,j,ii,jj,n;\n double u;\n\n gsl_matrix_set_zero(shiftdata);\n\n n = data->size1; \n for (i=0; i= n) continue;\n for (j=0; j= n) continue;\n u = gsl_matrix_get(data,i,j);\n gsl_matrix_set(shiftdata,ii,jj,u);\n }\n }\n}\n\n\nvoid\nAddShift(gsl_matrix *data,gsl_matrix *shiftdata,int ishift,int jshift)\n{\n int i,j,ii,jj,n;\n double u,v;\n n = data->size1;\n \n for (i=0; i= n) continue;\n for (j=0; j= n) continue;\n u = gsl_matrix_get(data,i,j);\n v = gsl_matrix_get(shiftdata,ii,jj);\n u = u+v;\n gsl_matrix_set(data,i,j,u);\n }\n }\n}\n\n\nVImage\nVWavelets(VImage src,VImage dest,int filtertype,int wtype,int nshift,double level)\n{\n static gsl_wavelet_workspace *work=NULL;\n static gsl_wavelet *w=NULL;\n static gsl_matrix *data=NULL,*tmp=NULL,*shiftdata=NULL;\n int nslices,nrows,ncols,i,j,slice,n,size,dim;\n double u,sum1,sum2,nx,mean,sig,sigma=0,avesig;\n extern VFloat VGetPixelValue (VImage,int);\n\n\n /*\n ** read image info\n */\n nslices = VImageNBands(src);\n nrows = VImageNRows(src);\n ncols = VImageNColumns(src);\n\n if (dest == NULL)\n dest = VCreateImage(nslices,nrows,ncols,VPixelRepn(src));\n VCopyImageAttrs (src, dest);\n VFillImage(dest,VAllBands,0);\n \n size = nrows;\n if (nrows < ncols) size = ncols;\n n = (int) ceil(log10((double) size) / log10(2.0));\n dim = (int) pow(2.0, (double) n);\n\n\n /*\n ** ini wavelets transform\n */\n if (work == NULL) {\n\n switch (wtype) {\n case 0:\n w = gsl_wavelet_alloc (gsl_wavelet_haar_centered,2);\n break;\n case 1:\n w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,4);\n break;\n case 2:\n w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,6);\n break;\n case 3:\n w = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered,8);\n break;\n case 4:\n w = gsl_wavelet_alloc (gsl_wavelet_bspline_centered,103);\n break;\n case 5:\n w = gsl_wavelet_alloc (gsl_wavelet_bspline_centered,202);\n break;\n default: \n VError(\"illegal wavelet type\");\n }\n\n work = gsl_wavelet_workspace_alloc (dim);\n data = gsl_matrix_calloc(dim,dim);\n shiftdata = gsl_matrix_calloc(dim,dim);\n tmp = gsl_matrix_calloc(dim,dim);\n }\n \n\n avesig = 0;\n for (slice=0; slice VPixelMaxValue(dest)) u = VPixelMaxValue(dest);\n\tVSetPixel(dest,slice,i,j,u);\n }\n }\n }\n avesig /= (double)nslices;\n /* fprintf(stderr,\" kappa: %f\\n\",sqrt(avesig) * 1.75); */\n\n /*\n gsl_matrix_free(shiftdata);\n gsl_matrix_free(tmp);\n gsl_wavelet_free (w);\n gsl_wavelet_workspace_free (work);\n free (data);\n */\n return dest;\n}\n\n\nVDictEntry WDict[] = {\n { \"haar\", 0 },\n { \"daub4\", 1 },\n { \"daub6\", 2 },\n { \"daub8\", 3 },\n { \"bspline103\", 4 },\n { \"bspline202\", 5 },\n { NULL }\n};\n\n\nint main (int argc,char *argv[])\n{ \n static VShort ftype = 0;\n static VShort wtype = 0;\n static VShort nshift = 1;\n static VDouble level = 0.5;\n static VOptionDescRec options[] = {\n {\"wavelet\",VShortRepn,1,(VPointer) &wtype,VOptionalOpt,WDict,\"wavelet type\"},\n {\"filter\",VShortRepn,1,(VPointer) &ftype,VOptionalOpt,NULL,\"filter type\"},\n {\"shift\",VShortRepn,1,(VPointer) &nshift,VOptionalOpt,NULL,\"shift window size\"},\n {\"level\",VDoubleRepn,1,(VPointer) &level,VOptionalOpt,NULL,\"level\"}\n };\n FILE *in_file,*out_file;\n VAttrList list=NULL;\n VAttrListPosn posn;\n VImage src=NULL,dest=NULL;\n int n=0,nimages=0;\n char *prg=GetLipsiaName(\"vdenoise\");\n fprintf (stderr, \"%s\\n\", prg);\n\n\n VParseFilterCmd (VNumber (options),options,argc,argv,&in_file,&out_file);\n\n\n if (! (list = VReadFile (in_file, NULL))) exit (1);\n fclose(in_file);\n\n nimages = 0;\n for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n if (VGetAttrRepn (& posn) == VImageRepn) nimages++;\n }\n\n n = 0;\n for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n if (VGetAttrRepn (& posn) != VImageRepn) continue;\n VGetAttrValue (& posn, NULL,VImageRepn, & src);\n fprintf(stderr,\" image %4d of %d\\r\",n,nimages);\n dest = VWavelets(src,dest,(int)ftype,(int)wtype,(int)nshift,level);\n src = VCopyImage(dest,src,VAllBands);\n VSetAttrValue (& posn, NULL,VImageRepn,src);\n n++;\n }\n if (src == NULL) VError(\" no input image found\");\n\n\n VHistory(VNumber(options),options,prg,&list,&list);\n if (! VWriteFile (out_file, list)) exit (1);\n fprintf (stderr, \"%s: done.\\n\", argv[0]);\n return 0;\n}\n", "meta": {"hexsha": "895c682901d9eccb2f520bca1331c6952f067709", "size": 10049, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prep/vdenoise/vdenoise.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/prep/vdenoise/vdenoise.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/prep/vdenoise/vdenoise.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.2815964523, "max_line_length": 84, "alphanum_fraction": 0.5890138322, "num_tokens": 3477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4744670949077991}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n//Structure containing info about a model parameter\ntypedef struct {\n int index;\n double value;\n} LSS_param;\n\n//Structure defining one of the tracers being correlated\n//Note that each LSS tracer contains many redshift bins\n//(whereas a CCL_ClTracer corresponds to a single bin)\ntypedef struct {\n int n_bins; //Number of redshift bins\n\n int *num_z; //Number of z-values for the n(z) of each bin (dims -> [nbins])\n double **z_nz_arr; //z-values for the n(z) of each bin (dims -> [nbins,num_z])\n double **n_nz_arr; //n(z) of each bin (dims -> [nbins,num_z])\n\n int n_nodes_b; //Number of nodes defining b(z)\n double *z_bz_arr; //Redshift values for each node (dims -> [n_nodes_b])\n LSS_param *b_bz_arr; //Bias values for each node (dims -> [n_nodes_b])\n int interp_scheme_b; //Interpolation scheme for b(z)\n\n //Add similar stuff for magnification bias, 2nd-order bias etc.,\n\n //Add similar stuff for photo-z uncertainties?\n\n //Flags describing theoretical calculation\n int flag_w_rsd; //Include RSDs?\n int flag_w_mag; //Include magnification?\n int non_linear_type; //Scheme for non-linearities?\n\n //Array of CCL_ClTracers for each redshift bin (stored here to avoid recomputation?)\n CCL_ClTracer *t; // (dims -> [n_bins])\n} LSS_tracer_info;\n\n\n//Structure containing info needed to compute the LSS likelihood\ntypedef struct {\n //Cosmological parameters\n LSS_param par_Oc;\n LSS_param par_Ob;\n LSS_param par_Ok;\n LSS_param par_h;\n LSS_param par_s8;\n LSS_param par_ns;\n LSS_param par_w0;\n LSS_param par_wa;\n\n //Tracers to correlate\n LSS_tracer_info *tr1;\n LSS_tracer_info *tr2;\n\n //Probably a lot of stuff missing here\n //...\n} LSS_likelihood_workspace;\n\n//Structure defining a set of power spectra\ntypedef struct {\n //Number of bins for each tracer\n int nbin_1;\n int nbin_2;\n\n //Number of bandpowers for each cross-power spectrum\n int **n_bpw; // (dim -> [nbin_1,nbin_2])\n //Effective ell for each bandpower\n double ***l_bpw; // (dim -> [nbin_1,nbin_2,n_bpw[nbin_1,nbin_2]])\n //Effective C_ell for each bandpower\n gsl_vector *cl_bpw; // (flattened [nbin_1,nbin_2,n_bpw[nbin_1,nbin_2]])\n //This will probably have to be more general, with a weight-per-ell\n //array for each bandpower (e.g. to account for pseudo-Cl binning).\n} LSS_2pt_Cell;\n\n//Something like the above should be defined for the precision matrix,\n//or it could be read directly into a 2D matrix\n\n\n//////////\n// Functions defined in lss_cell_io.c\n//\n//Read power spectrum\nLSS_2pt_Cell *lss_read_cell(char *fname);\n//Write power spectrum\nvoid lss_write_cell(char *fname,LSS_2pt_Cell *cl);\n//Read precision matrix\ngsl_matrix *lss_read_precision(char *fname);\n//Write precision matrix\nvoid lss_write_precision(char *fname,gsl_matrix *prec,LSS_2pt_Cell *cl);\n//Destructor\nvoid lss_free_cell(LSS_2pt_Cell *cl);\n\n//////////\n// Functions defined in lss_tracers.c\n//\n//Creates new tracer\nLSS_tracer_info *lss_tracer_new(int n_bins,\n\t\t\t\tint *num_z,double **z_nz_arr,double **n_nz_arr,\n\t\t\t\tint n_nodes_b,double *z_bz_arr,double *b_bz_arr,\n\t\t\t\tint flag_w_rsd,int flag_w_mag,int non_linear_type);\n//Destructor\nvoid lss_tracer_free(LSS_tracer_info *tr);\n\n//////////\n// Functions defined in lss_cell_th.c\n//\n//Compute theory power spectrum (and return as gsl_vector)\ngsl_vector *lss_cell_theory(ccl_cosmology *cosmo,LSS_likelihood_workspace *w,LSS_2pt_Cell *cl);\n\n//////////\n// Functions defined in lss_cell_like.c\n//\n//Computes likelihood for a set of cosmological and nuisance parameters (encoded in params)\ndouble lss_likelihood(int n_par,double *params,LSS_2pt_Cell *data,gsl_matrix *prec,LSS_likelihood_workspace *w);\n//Creates a new LSS_likelihood_workspace\nLSS_likelihood_workspace *lss_like_workspace_new(ccl_cosmology *cosmo,LSS_tracer_info *tr1,LSS_tracer_info *tr2);\n//Destructor\nvoid lss_like_workspace_free(LSS_likelihood_workspace *w);\n", "meta": {"hexsha": "f5b428ef12635459e3ad2b13f6f0c97faa448222", "size": 4011, "ext": "h", "lang": "C", "max_stars_repo_path": "C_old/include/lss_common.h", "max_stars_repo_name": "LSSTDESC/LSSLike", "max_stars_repo_head_hexsha": "49f4654dbe08eacb377cdfb6e8f1131f1bbd0349", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T20:57:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-04T20:57:17.000Z", "max_issues_repo_path": "C_old/include/lss_common.h", "max_issues_repo_name": "LSSTDESC/LSSLike", "max_issues_repo_head_hexsha": "49f4654dbe08eacb377cdfb6e8f1131f1bbd0349", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T03:40:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T18:09:32.000Z", "max_forks_repo_path": "C_old/include/lss_common.h", "max_forks_repo_name": "LSSTDESC/LSSLike", "max_forks_repo_head_hexsha": "49f4654dbe08eacb377cdfb6e8f1131f1bbd0349", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T19:13:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:38:31.000Z", "avg_line_length": 32.3467741935, "max_line_length": 113, "alphanum_fraction": 0.7417102967, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.47426669564747587}} {"text": "/*\n * Command-line numerical polynomial equation solver using the GNU Scientific Library (GSL).\n * GSL is available from: \"http://www.gnu.org/software/gsl/\".\n *\n * Copyright (C) 2008-2011 George Gesslein II\n \nThis library is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nThe chief copyright holder can be contacted at gesslein@mathomatic.org, or\nGeorge Gesslein II, P.O. Box 224, Lansing, NY 14882-0224 USA.\n \n */\n\n/*\n * To compile:\n\n./compile.roots\n\n * or\n\ngcc -O3 -Wall -o roots roots.c -lgsl -lgslcblas\n\n * This program nicely solves any degree polynomial\n * with real coefficients by calling the\n * GSL function gsl_poly_complex_solve().\n * This file is also useful for testing\n * and as an example of using the GSL from C.\n * The results are double precision floating point values\n * that are sometimes accurate to 14 digits.\n * Complex numbers are output if successful.\n * Here is an example of it solving a cubic polynomial:\n\n$ roots 1 1 1 1 \nThe 3 approximate floating point solutions of:\n+x^3 +x^2 +x +1 = 0\nare:\n\nx = +0 +1*i\nx = +0 -1*i\nx = -1\n$ \n\nTry this for a large amount of error:\nroots -1 -1 1 1\n\nProof the GSL isn't perfect.\n\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define EPSILON\t0.00000000000005\t/* a good value for doubles */\n#define HELP\t1\t\t\t/* display helpful text */\n\nvoid\tdisplay_root(int i);\n\nchar\t*prog_name = \"roots\";\t\t/* name of this program */\ndouble\t*a, *z;\t\t\t\t/* input and output arrays, respectively */\nint\tprecision = DBL_DIG - 1;\t/* display precision, it is not useful to set this higher than 15 */\n\nvoid\nusage(void)\n{\n printf(\"\\n%s version 1.0 - numerical polynomial equation solver\\n\", prog_name);\n printf(\"Uses the GNU Scientific Library (GSL).\\n\");\n printf(\"\\nSolves polynomial = 0 when given all real coefficients of the polynomial.\\n\");\n printf(\"Double precision floating point math is used, accurate to about 14 digits.\\n\");\n printf(\"\\nUsage: %s highest-power-coefficient ... constant-term\\n\", prog_name);\n printf(\"\\nThe coefficients must be decimal, floating point, real numbers.\\n\");\n printf(\"For example, if 4 real numbers are given, there will be 3 complex number\\n\");\n printf(\"results or \\\"roots\\\" that are all valid solutions to polynomial = 0.\\n\");\n}\n\nint\nmain(int argc, char **argv)\n{\n int i, highest_power;\n char *cp, *arg;\n gsl_poly_complex_workspace *w;\n\n if (argc <= 1) {\n fprintf(stderr, \"%s: The polynomial coefficients must be specified on the command line.\\n\", prog_name);\n usage();\n exit(2);\n }\n\n highest_power = argc - 2;\n a = calloc(highest_power + 1, sizeof(double)); /* allocate real double input array */\n z = calloc(2 * highest_power, sizeof(double)); /* allocate complex double output array */\n\n/* parse the command line into the coefficient array a[] */\n for (i = 0; i < argc - 1; i++) {\n arg = argv[argc-i-1];\n errno = 0;\n a[i] = strtod(arg, &cp);\n if (arg == cp || *cp) {\n fprintf(stderr, \"%s: Argument \\\"%s\\\" is not a floating point number.\\n\", prog_name, arg);\n usage();\n exit(2);\n }\n if (errno) {\n fprintf(stderr, \"%s: Argument \\\"%s\\\" is out of range.\\n\", prog_name, arg);\n exit(2);\n }\n }\n\n#if\tHELP\n/* nicely display the actual polynomial equation we are solving */\n printf(\"The %d approximate floating point solutions of:\\n\", highest_power);\n for (i = highest_power; i >= 0; i--) {\n if (a[i]) {\n if (i && a[i] == 1.0) {\n\tprintf(\"+x\");\n } else {\n printf(\"%+.*g\", precision, a[i]);\n if (i) {\n\t printf(\"*x\");\n }\n }\n if (i > 1) {\n printf(\"^%d\", i);\n }\n printf(\" \");\n }\n }\n printf(\"= 0\\nare:\\n\\n\");\n#endif\n\n/* solve the polynomial equation */\n w = gsl_poly_complex_workspace_alloc(highest_power + 1);\n if (gsl_poly_complex_solve(a, highest_power + 1, w, z) != GSL_SUCCESS) {\n fprintf(stderr, \"%s: GSL approximation failed.\\n\", prog_name);\n exit(1);\n }\n gsl_poly_complex_workspace_free(w);\n\n/* display all solutions */\n for (i = 0; i < highest_power; i++) {\n#ifdef\tEPSILON /* zero out relatively very small values (which are floating point error) */\n if (fabs(z[2*i] * EPSILON) > fabs(z[2*i+1]))\n z[2*i+1] = 0.0;\n else if (fabs(z[2*i+1] * EPSILON) > fabs(z[2*i]))\n z[2*i] = 0.0;\n#endif\n#if\tHELP\n printf(\"x = \");\n#endif\n display_root(i);\n printf(\"\\n\");\n }\n\n exit(0);\n}\n\nvoid\ndisplay_root(int i)\n{\n printf(\"%+.*g\", precision, z[2*i]);\t\t/* output real part */\n if (z[2*i+1])\n printf(\" %+.*g*i\", precision, z[2*i+1]);\t/* output imaginary part */\n}\n", "meta": {"hexsha": "5fde8edbcf030f824fb60c31ad0d3fa019e04f61", "size": 5275, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/mathomatic-master/examples/roots.c", "max_stars_repo_name": "josephlewis42/beancounter", "max_stars_repo_head_hexsha": "10ae79fc0f99134a3696de9eaa67a7ec0bd2d9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T00:43:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T03:41:53.000Z", "max_issues_repo_path": "lib/mathomatic-master/examples/roots.c", "max_issues_repo_name": "josephlewis42/beancounter", "max_issues_repo_head_hexsha": "10ae79fc0f99134a3696de9eaa67a7ec0bd2d9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-04-22T19:26:37.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-11T23:03:41.000Z", "max_forks_repo_path": "lib/mathomatic-master/examples/roots.c", "max_forks_repo_name": "josephlewis42/beancounter", "max_forks_repo_head_hexsha": "10ae79fc0f99134a3696de9eaa67a7ec0bd2d9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T00:52:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-12T04:39:02.000Z", "avg_line_length": 29.1436464088, "max_line_length": 107, "alphanum_fraction": 0.6580094787, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.47424889813424687}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"util.h\"\n\n\n\nint main(int argc, char *argv[]) {\n char* input_fileName1 = argv[1];\n char* input_fileName2 = argv[2];\n int N_doc_bg = atoi(argv[3]);\n int N_kw = atoi(argv[4]);\n int N_obs = atoi(argv[5]);\n int N_iter = atoi(argv[6]);\n double lambda = atof(argv[7]);\n char* output_fileName = argv[8];\n int N_doc = 480000/2;\n\n int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* matrix_bgi = (int*) malloc(sizeof(int) * N_kw * N_kw);\n int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* true_index = (int*) malloc(sizeof(int) * N_kw);\n int* permutation = (int*) malloc(sizeof(int) * N_obs);\n gsl_matrix* matrix_obs;\n\n\n for (int round = 0; round < 10; round++)\n {\n char input_fileName1_extend[40];\n char input_fileName2_extend[40];\n sprintf(input_fileName1_extend, \"%s%d\", input_fileName1, round);\n sprintf(input_fileName2_extend, \"%s%d\", input_fileName2, round);\n\n // Setup\n struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n read_matrix(&true_index, &matrix_bgi, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);\n read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);\n gettimeofday(&tv2, NULL);\n printf(\"Reading done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n for (int iter = 0; iter < 10; iter++)\n {\n printf(\"Run %d\\n\", iter);\n matrix_obs = gsl_matrix_alloc(N_obs, N_obs);\n\n gettimeofday(&tv1, NULL);\n pad_matrix(&matrix_padded, &matrix, lambda, N_obs, N_doc);\n gettimeofday(&tv2, NULL);\n printf(\"Padding done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n gettimeofday(&tv1, NULL);\n observe_matrix(matrix_obs, &matrix_padded, N_obs);\n gettimeofday(&tv2, NULL);\n printf(\"Observed matrix generated: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n \n gettimeofday(&tv1, NULL);\n attack(matrix_obs, &matrix_bgi, &permutation, N_kw, N_obs, N_doc, N_iter);\n gettimeofday(&tv2, NULL);\n printf(\"Main attack done: %d.\\n\", (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n char output_fileName_full[40];\n sprintf(output_fileName_full, \"%s%d-%d\", output_fileName, round, iter);\n print_result(output_fileName_full, &permutation, &true_index, N_obs);\n //sprintf(output_fileName_full, \"%s%d-%d-full\", output_fileName, round, iter);\n //print_full_result(output_fileName_full, &permutation, &true_index, N_obs);\n }\n }\n\n free(matrix);\n free(matrix_padded);\n gsl_matrix_free(matrix_obs);\n return(0);\n}\n\n\ndouble log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc)\n{\n if (idx1 == idx2)\n return(0.0);\n\n int idx1_m = (*permutation)[idx1];\n int idx2_m = (*permutation)[idx2];\n\n double mean1, mean2, mean3;\n mean3 = 0;\n double var = 0;\n\n if (gsl_matrix_get(matrix_obs, idx1, idx1) > (*matrix)[idx1_m*N_kw + idx1_m])\n {\n mean1 = (*matrix)[idx1_m*N_kw + idx2_m];\n double x1, x2;\n x1 = gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx1_m];\n x2 = gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx1_m*N_kw + idx2_m];\n mean3 = x1 / N_doc * x2;\n var += x1 / N_doc * x2 * (N_doc - x2) / N_doc;\n }\n else\n {\n mean1 = (*matrix)[idx1_m*N_kw + idx2_m] * gsl_matrix_get(matrix_obs, idx1, idx1) / (*matrix)[idx1_m*N_kw + idx1_m];\n var += mean1 / (*matrix)[idx1_m*N_kw + idx1_m] * ((*matrix)[idx1_m*N_kw + idx1_m] - gsl_matrix_get(matrix_obs, idx1, idx1));\n }\n\n\n if (gsl_matrix_get(matrix_obs, idx2, idx2) > (*matrix)[idx2_m*N_kw + idx2_m])\n {\n mean2 = mean1;\n double x1, x2;\n x1 = gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx2_m*N_kw + idx2_m];\n x2 = gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx2_m];\n mean3 += x1 / N_doc * x2;\n var += x1 / N_doc * x2 * (N_doc - x2) / N_doc;\n }\n else\n {\n mean2 = mean1 * gsl_matrix_get(matrix_obs, idx2, idx2) / (*matrix)[idx2_m*N_kw + idx2_m];\n var += mean2 / (*matrix)[idx2_m*N_kw + idx2_m] * ((*matrix)[idx2_m*N_kw + idx2_m] - gsl_matrix_get(matrix_obs, idx2, idx2));\n }\n\n var += 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx2_m*N_kw + idx2_m]);\n\n double score = gsl_ran_gaussian_pdf(mean2 + mean3 - gsl_matrix_get(matrix_obs, idx1, idx2), sqrt(var));\n \n if (score == 0)\n return(-500.0);\n return(log(score));\n}\n\n\n\n\n\nvoid attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, int N_iter)\n{\n // Initialise data structures\n double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs);\n double* score_row1 = (double*) malloc(sizeof(double) * N_obs);\n double* score_row2 = (double*) malloc(sizeof(double) * N_obs);\n\n int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);\n int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);\n\n\n // Initialise permutations\n for (int ii = 0; ii < N_obs; ii++)\n (*permutation)[ii] = ii;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_tmp[ii] = ii;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_inv[ii] = ii;\n for (int ii = N_obs; ii < N_kw; ii++)\n permutation_inv[ii] = -1;\n\n // Initialising RNG\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 struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n\n // Compute initial score\n #pragma omp parallel for shared(score_matrix, matrix_obs, matrix)\n for (int ii = 0; ii < N_obs * N_obs; ii++)\n score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc);\n gettimeofday(&tv2, NULL);\n printf(\"Initial score computed: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n \n // Iterations of simulated annealing\n double temp = (double) N_kw;\n int N_stuck = 0;\n for (int iter = 0; iter < N_iter; iter++)\n {\n\t /* Status code */\n\t if (iter % (N_iter / 10) == 0)\n {\n gettimeofday(&tv1, NULL);\n printf(\"Iteration: %d, %d, %d.\\n\", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));\n fflush(stdout);\n gettimeofday(&tv2, NULL);\n }\n\n if (N_stuck >= 20000)\n iter = N_iter;\n\n\t /* Main code */\n int idx1, idx2;\n permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, N_kw, N_obs);\n\n int ii = 0;\n #pragma omp parallel for shared(score_row1)\n for (ii = 0; ii < N_obs; ii++)\n score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc);\n\n if (idx2 >= 0)\n #pragma omp parallel for shared(score_row2)\n for (ii = 0; ii < N_obs; ii++)\n score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc);\n\n double score_diff = 0;\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx1*N_obs + ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx2*N_obs + ii];\n }\n\n // compute difference in score, with exponentiation\n score_diff = score_diff / temp;\n \n if (score_diff < -40)\n score_diff = 0;\n else if (score_diff > 0)\n score_diff = 1.01;\n else\n score_diff = exp(score_diff);\n\n if (gsl_ran_flat(r, 0, 1) < score_diff)\n {\n // Update the scores\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx1*N_obs + ii] = score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx1] = score_row1[ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx2*N_obs + ii] = score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx2] = score_row2[ii];\n }\n\n // Update the permutation\n permutation_inv[(*permutation)[idx1]] = -1;\n (*permutation)[idx1] = permutation_tmp[idx1];\n permutation_inv[permutation_tmp[idx1]] = idx1;\n if (idx2 >= 0)\n {\n (*permutation)[idx2] = permutation_tmp[idx2];\n permutation_inv[permutation_tmp[idx2]] = idx2;\n }\n N_stuck = 0;\n }\n else\n {\n // Update the permutation\n permutation_tmp[idx1] = (*permutation)[idx1];\n if (idx2 >= 0)\n permutation_tmp[idx2] = (*permutation)[idx2];\n N_stuck += 1;\n }\n\n temp *= 0.995;\n }\n\n free(score_matrix);\n free(score_row1);\n free(score_row2);\n gsl_rng_free(r);\n}\n\n\n\nvoid print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n fprintf(fp, \"%d\\n\", count);\n fclose(fp);\n printf(\"Success: %d/%d.\\n\", count, N_obs);\n}\n\n\n\nvoid print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n fprintf(fp, \"%d, %d\\n\", (*permutation)[ii], (*true_index)[ii]);\n fclose(fp);\n}", "meta": {"hexsha": "480104b7a3a4ff9457f06d19c842150a97b53a9d", "size": 10489, "ext": "c", "lang": "C", "max_stars_repo_path": "PRT-EMM/attack_mp.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "PRT-EMM/attack_mp.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "PRT-EMM/attack_mp.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.1661237785, "max_line_length": 140, "alphanum_fraction": 0.5669749261, "num_tokens": 3059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.47410842469692055}} {"text": "/* randist/beta.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/* The beta distribution has the form\n\n p(x) dx = (Gamma(a + b)/(Gamma(a) Gamma(b))) x^(a-1) (1-x)^(b-1) dx\n\n The method used here is the one described in Knuth */\n\ndouble\ngsl_ran_beta (const gsl_rng * r, const double a, const double b)\n{\n if ( (a <= 1.0) && (b <= 1.0) )\n {\n double U, V, X, Y;\n while (1)\n {\n U = gsl_rng_uniform_pos(r);\n V = gsl_rng_uniform_pos(r);\n X = pow(U, 1.0/a);\n Y = pow(V, 1.0/b);\n if ((X + Y ) <= 1.0)\n {\n if (X + Y > 0)\n {\n return X/ (X + Y);\n }\n else\n {\n double logX = log(U)/a;\n double logY = log(V)/b;\n double logM = logX > logY ? logX: logY;\n logX -= logM;\n logY -= logM;\n return exp(logX - log(exp(logX) + exp(logY)));\n }\n }\n }\n }\n else\n {\n double x1 = gsl_ran_gamma (r, a, 1.0);\n double x2 = gsl_ran_gamma (r, b, 1.0);\n return x1 / (x1 + x2);\n }\n}\n\ndouble\ngsl_ran_beta_pdf (const double x, const double a, const double b)\n{\n if (x < 0 || x > 1)\n {\n return 0 ;\n }\n else \n {\n double p;\n\n double gab = gsl_sf_lngamma (a + b);\n double ga = gsl_sf_lngamma (a);\n double gb = gsl_sf_lngamma (b);\n \n if (x == 0.0 || x == 1.0) \n {\n\t if (a > 1.0 && b > 1.0)\n\t {\n\t p = 0.0;\n\t }\n\t else\n\t {\n\t p = exp (gab - ga - gb) * pow (x, a - 1) * pow (1 - x, b - 1);\n\t }\n }\n else\n {\n p = exp (gab - ga - gb + log(x) * (a - 1) + log1p(-x) * (b - 1));\n }\n\n return p;\n }\n}\n", "meta": {"hexsha": "03826f1e036b3b0cd92195a3d926b8b7d407db4f", "size": 2709, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/beta.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/randist/beta.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/beta.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.8, "max_line_length": 81, "alphanum_fraction": 0.511627907, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.47359841295178984}} {"text": "/* rng/ran2.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n\n/* This is an implementation of the algorithm used in Numerical\n Recipe's ran2 generator. It is a L'Ecuyer combined recursive\n generator with a 32-element shuffle-box.\n\n As far as I can tell, in general the effects of adding a shuffle\n box cannot be proven theoretically, so the period of this generator\n is unknown. \n\n The period of the underlying combined generator is O(2^60). */\n\nstatic inline unsigned long int ran2_get (void *vstate);\nstatic double ran2_get_double (void *vstate);\nstatic void ran2_set (void *state, unsigned long int s);\n\nstatic const long int m1 = 2147483563, a1 = 40014, q1 = 53668, r1 = 12211;\nstatic const long int m2 = 2147483399, a2 = 40692, q2 = 52774, r2 = 3791;\n\n#define N_SHUFFLE 32\n#define N_DIV (1 + 2147483562/N_SHUFFLE)\n\ntypedef struct\n {\n unsigned long int x;\n unsigned long int y;\n unsigned long int n;\n unsigned long int shuffle[N_SHUFFLE];\n }\nran2_state_t;\n\nstatic inline unsigned long int\nran2_get (void *vstate)\n{\n ran2_state_t *state = (ran2_state_t *) vstate;\n\n const unsigned long int x = state->x;\n const unsigned long int y = state->y;\n\n long int h1 = x / q1;\n long int t1 = a1 * (x - h1 * q1) - h1 * r1;\n\n long int h2 = y / q2;\n long int t2 = a2 * (y - h2 * q2) - h2 * r2;\n\n if (t1 < 0)\n t1 += m1;\n\n if (t2 < 0)\n t2 += m2;\n\n state->x = t1;\n state->y = t2;\n\n {\n unsigned long int j = state->n / N_DIV;\n long int delta = state->shuffle[j] - t2;\n if (delta < 1)\n delta += m1 - 1;\n state->n = delta;\n state->shuffle[j] = t1;\n }\n\n return state->n;\n}\n\nstatic double\nran2_get_double (void *vstate)\n{\n float x_max = 1 - 1.2e-7f ; /* Numerical Recipes version of 1-FLT_EPS */\n\n float x = ran2_get (vstate) / 2147483563.0f ;\n \n if (x > x_max) \n return x_max ;\n \n return x ;\n}\n\nstatic void\nran2_set (void *vstate, unsigned long int s)\n{\n ran2_state_t *state = (ran2_state_t *) vstate;\n int i;\n\n if (s == 0)\n s = 1;\t/* default seed is 1 */\n\n state->y = s;\n\n for (i = 0; i < 8; i++)\n {\n long int h = s / q1;\n long int t = a1 * (s - h * q1) - h * r1;\n if (t < 0)\n\tt += m1;\n s = t;\n }\n\n for (i = N_SHUFFLE - 1; i >= 0; i--)\n {\n long int h = s / q1;\n long int t = a1 * (s - h * q1) - h * r1;\n if (t < 0)\n\tt += m1;\n s = t;\n state->shuffle[i] = s;\n }\n\n state->x = s;\n state->n = s;\n\n return;\n}\n\nstatic const gsl_rng_type ran2_type =\n{\"ran2\",\t\t\t/* name */\n 2147483562,\t\t\t/* RAND_MAX */\n 1,\t\t\t\t/* RAND_MIN */\n sizeof (ran2_state_t),\n &ran2_set,\n &ran2_get,\n &ran2_get_double};\n\nconst gsl_rng_type *gsl_rng_ran2 = &ran2_type;\n", "meta": {"hexsha": "d6555ec624638777bbfc246830993c68e953f56f", "size": 3463, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ran2.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ran2.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/ran2.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.5578231293, "max_line_length": 74, "alphanum_fraction": 0.6312445856, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4735663178916123}} {"text": "/* ode-initval/test_odeiv.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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"gsl_odeiv.h\"\n\nint rhs_linear (double t, const double y[], double f[], void *params);\nint jac_linear (double t, const double y[], double *dfdy, double dfdt[],\n void *params);\nint rhs_sin (double t, const double y[], double f[], void *params);\nint jac_sin (double t, const double y[], double *dfdy, double dfdt[],\n void *params);\nint rhs_exp (double t, const double y[], double f[], void *params);\nint jac_exp (double t, const double y[], double *dfdy, double dfdt[],\n void *params);\nint rhs_stiff (double t, const double y[], double f[], void *params);\nint jac_stiff (double t, const double y[], double *dfdy, double dfdt[],\n void *params);\nvoid test_stepper_linear (const gsl_odeiv_step_type * T, double h,\n double base_prec);\nvoid test_stepper_sin (const gsl_odeiv_step_type * T, double h, double base_prec);\nvoid test_stepper_exp (const gsl_odeiv_step_type * T, double h, double base_prec);\nvoid test_stepper_stiff (const gsl_odeiv_step_type * T, double h, double base_prec);\nvoid test_evolve_system_flat (gsl_odeiv_step * step,\n const gsl_odeiv_system * sys,\n double t0, double t1, double hstart,\n double y[], double yfin[],\n double err_target, const char *desc);\n\nvoid test_evolve_system (const gsl_odeiv_step_type * T,\n const gsl_odeiv_system * sys,\n double t0, double t1, double hstart,\n double y[], double yfin[],\n double err_target, const char *desc);\n\nvoid test_evolve_exp (const gsl_odeiv_step_type * T, double h, double err);\nvoid test_evolve_sin (const gsl_odeiv_step_type * T, double h, double err);\nvoid test_evolve_stiff1 (const gsl_odeiv_step_type * T, double h, double err);\nvoid test_evolve_stiff5 (const gsl_odeiv_step_type * T, double h, double err);\n\n/* RHS for a + b t */\n\nint\nrhs_linear (double t, const double y[], double f[], void *params)\n{\n f[0] = 0.0;\n f[1] = y[0];\n return GSL_SUCCESS;\n}\n\nint\njac_linear (double t, const double y[], double *dfdy, double dfdt[],\n\t void *params)\n{\n gsl_matrix dfdy_mat;\n dfdy_mat.size1 = 2;\n dfdy_mat.size2 = 2;\n dfdy_mat.tda = 2;\n dfdy_mat.data = dfdy;\n dfdy_mat.block = 0;\n gsl_matrix_set (&dfdy_mat, 0, 0, 0.0);\n gsl_matrix_set (&dfdy_mat, 0, 1, 0.0);\n gsl_matrix_set (&dfdy_mat, 1, 0, 1.0);\n gsl_matrix_set (&dfdy_mat, 1, 1, 0.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\ngsl_odeiv_system rhs_func_lin = {\n rhs_linear,\n jac_linear,\n 2,\n 0\n};\n\n\n/* RHS for sin(t),cos(t) */\n\nint\nrhs_sin (double t, const double y[], double f[], void *params)\n{\n f[0] = -y[1];\n f[1] = y[0];\n return GSL_SUCCESS;\n}\n\nint\njac_sin (double t, const double y[], double *dfdy, double dfdt[],\n\t void *params)\n{\n gsl_matrix dfdy_mat;\n dfdy_mat.data = dfdy;\n dfdy_mat.size1 = 2;\n dfdy_mat.size2 = 2;\n dfdy_mat.tda = 2;\n dfdy_mat.block = 0;\n gsl_matrix_set (&dfdy_mat, 0, 0, 0.0);\n gsl_matrix_set (&dfdy_mat, 0, 1, -1.0);\n gsl_matrix_set (&dfdy_mat, 1, 0, 1.0);\n gsl_matrix_set (&dfdy_mat, 1, 1, 0.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\ngsl_odeiv_system rhs_func_sin = {\n rhs_sin,\n jac_sin,\n 2,\n 0\n};\n\n\n/* RHS for a exp(t)+ b exp(-t) */\n\nint\nrhs_exp (double t, const double y[], double f[], void *params)\n{\n f[0] = y[1];\n f[1] = y[0];\n return GSL_SUCCESS;\n}\n\nint\njac_exp (double t, const double y[], double *dfdy, double dfdt[],\n\t void *params)\n{\n gsl_matrix dfdy_mat;\n dfdy_mat.data = dfdy;\n dfdy_mat.size1 = 2;\n dfdy_mat.size2 = 2;\n dfdy_mat.tda = 2;\n dfdy_mat.block = 0;\n gsl_matrix_set (&dfdy_mat, 0, 0, 0.0);\n gsl_matrix_set (&dfdy_mat, 0, 1, 1.0);\n gsl_matrix_set (&dfdy_mat, 1, 0, 1.0);\n gsl_matrix_set (&dfdy_mat, 1, 1, 0.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\ngsl_odeiv_system rhs_func_exp = {\n rhs_exp,\n jac_exp,\n 2,\n 0\n};\n\n\n/* RHS for stiff example */\n\nint\nrhs_stiff (double t, const double y[], double f[], void *params)\n{\n f[0] = 998.0 * y[0] + 1998.0 * y[1];\n f[1] = -999.0 * y[0] - 1999.0 * y[1];\n return GSL_SUCCESS;\n}\n\nint\njac_stiff (double t, const double y[], double *dfdy, double dfdt[],\n\t void *params)\n{\n gsl_matrix dfdy_mat;\n dfdy_mat.data = dfdy;\n dfdy_mat.size1 = 2;\n dfdy_mat.size2 = 2;\n dfdy_mat.tda = 2;\n dfdy_mat.block = 0;\n gsl_matrix_set (&dfdy_mat, 0, 0, 998.0);\n gsl_matrix_set (&dfdy_mat, 0, 1, 1998.0);\n gsl_matrix_set (&dfdy_mat, 1, 0, -999.0);\n gsl_matrix_set (&dfdy_mat, 1, 1, -1999.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\ngsl_odeiv_system rhs_func_stiff = {\n rhs_stiff,\n jac_stiff,\n 2,\n 0\n};\n\n\nvoid\ntest_stepper_linear (const gsl_odeiv_step_type * T, double h,\n\t\t double base_prec)\n{\n int s = 0;\n double y[2];\n double yerr[2];\n double t;\n double del;\n double delmax = 0.0;\n int count = 0;\n\n gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2);\n\n y[0] = 1.0;\n y[1] = 0.0;\n\n for (t = 0.0; t < 4.0; t += h)\n {\n gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_lin);\n del = fabs ((y[1] - (t + h)) / y[1]);\n delmax = GSL_MAX_DBL (del, delmax);\n if (del > (count + 1.0) * base_prec)\n\t{\n\t printf (\" LINEAR(%20.17g) %20.17g %20.17g %8.4g\\n\", t + h, y[1],\n\t\t t + h, del);\n\t s++;\n\t}\n count++;\n }\n\n gsl_test (s, \"%s, linear [0,4], max relative error = %g\",\n\t gsl_odeiv_step_name (stepper), delmax);\n\n gsl_odeiv_step_free (stepper);\n}\n\n\nvoid\ntest_stepper_sin (const gsl_odeiv_step_type * T, double h, double base_prec)\n{\n int s = 0;\n double y[2];\n double yerr[2];\n double t;\n double del;\n double delmax = 0.0;\n int count = 0;\n\n gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2);\n\n y[0] = 1.0;\n y[1] = 0.0;\n\n for (t = 0.0; t < M_PI; t += h)\n {\n int stat;\n double sin_th = sin (t + h);\n gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_sin);\n del = fabs ((y[1] - sin_th) / sin_th);\n delmax = GSL_MAX_DBL (del, delmax);\n {\n\tif (t < 0.5 * M_PI)\n\t {\n\t stat = (del > (count + 1.0) * base_prec);\n\t }\n\telse if (t < 0.7 * M_PI)\n\t {\n\t stat = (del > 1.0e+04 * base_prec);\n\t }\n\telse if (t < 0.9 * M_PI)\n\t {\n\t stat = (del > 1.0e+06 * base_prec);\n\t }\n\telse\n\t {\n\t stat = (del > 1.0e+09 * base_prec);\n\t }\n\tif (stat != 0)\n\t {\n\t printf (\" SIN(%22.18g) %22.18g %22.18g %10.6g\\n\", t + h, y[1],\n\t\t sin_th, del);\n\t }\n\ts += stat;\n }\n count++;\n }\n if (delmax > 1.0e+09 * base_prec)\n {\n s++;\n printf (\" SIN(0 .. M_PI) delmax = %g\\n\", delmax);\n }\n\n gsl_test (s, \"%s, sine [0,pi], max relative error = %g\",\n\t gsl_odeiv_step_name (stepper), delmax);\n\n delmax = 0.0;\n for (; t < 100.5 * M_PI; t += h)\n {\n gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_sin);\n del = fabs (y[1] - sin (t));\n delmax = GSL_MAX_DBL (del, delmax);\n count++;\n }\n\n if (del > count * 2.0 * base_prec)\n {\n s++;\n printf (\" SIN(%22.18g) %22.18g %22.18g %10.6g\\n\", t + h, y[1],\n\t sin (t), del);\n }\n\n gsl_test (s, \"%s, sine [pi,100.5*pi], max absolute error = %g\",\n\t gsl_odeiv_step_name (stepper), delmax);\n\n gsl_odeiv_step_free (stepper);\n}\n\n\nvoid\ntest_stepper_exp (const gsl_odeiv_step_type * T, double h, double base_prec)\n{\n int s = 0;\n double y[2];\n double yerr[2];\n double t;\n double del, delmax = 0.0;\n int count = 0;\n\n gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2);\n\n y[0] = 1.0;\n y[1] = 1.0;\n\n for (t = 0.0; t < 20.0; t += h)\n {\n double ex = exp (t + h);\n gsl_odeiv_step_apply (stepper, t, h, y, yerr, 0, 0, &rhs_func_exp);\n del = fabs ((y[1] - ex) / y[1]);\n delmax = GSL_MAX_DBL (del, delmax);\n if (del > (count + 1.0) * 2.0 * base_prec)\n\t{\n\t printf (\" EXP(%20.17g) %20.17g %20.17g %8.4g\\n\", t + h, y[1],\n\t\t ex, del);\n\t s++;\n\t}\n count++;\n }\n\n gsl_test (s, \"%s, exponential [0,20], max relative error = %g\",\n\t gsl_odeiv_step_name (stepper), delmax);\n\n gsl_odeiv_step_free (stepper);\n}\n\nvoid\ntest_stepper_stiff (const gsl_odeiv_step_type * T, double h, double base_prec)\n{\n int s = 0;\n double y[2];\n double yerr[2];\n double t;\n double del, delmax = 0.0;\n int count = 0;\n\n gsl_odeiv_step *stepper = gsl_odeiv_step_alloc (T, 2);\n\n y[0] = 1.0;\n y[1] = 0.0;\n\n for (t = 0.0; t < 20.0; t += h)\n {\n gsl_odeiv_step_apply (stepper, t, h, y, yerr, NULL, NULL,\n\t\t\t &rhs_func_stiff);\n\n if (t > 0.04)\n\t{\n\t double arg = t + h;\n\t double e1 = exp (-arg);\n\t double e2 = exp (-1000.0 * arg);\n\t double u = 2.0 * e1 - e2;\n\t /* double v = -e1 + e2; */\n\t del = fabs ((y[0] - u) / y[0]);\n\t delmax = GSL_MAX_DBL (del, delmax);\n\n\t if (del > (count + 1.0) * 100.0 * base_prec)\n\t {\n\t printf (\" STIFF(%20.17g) %20.17g %20.17g %8.4g\\n\", arg,\n\t\t y[0], u, del);\n\t s++;\n\t }\n\t}\n count++;\n }\n\n gsl_test (s, \"%s, stiff [0,20], max relative error = %g\",\n\t gsl_odeiv_step_name (stepper), delmax);\n\n gsl_odeiv_step_free (stepper);\n}\n\nvoid\ntest_evolve_system_flat (gsl_odeiv_step * step,\n\t\t\t const gsl_odeiv_system * sys,\n\t\t\t double t0, double t1, double hstart,\n\t\t\t double y[], double yfin[],\n\t\t\t double err_target, const char *desc)\n{\n int s = 0;\n double frac;\n\n double t = t0;\n double h = hstart;\n\n gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension);\n\n while (t < t1)\n {\n gsl_odeiv_evolve_apply (e, NULL, step, sys, &t, t1, &h, y);\n }\n\n frac = fabs ((y[1] - yfin[1]) / yfin[1]) + fabs ((y[0] - yfin[0]) / yfin[0]);\n\n if (frac > 2.0 * e->count * err_target)\n {\n printf (\"FLAT t = %.5e y0 = %g y1= %g\\n\", t, y[0], y[1]);\n s++;\n }\n\n gsl_test (s, \"%s, %s, evolve, no control, max relative error = %g\",\n\t gsl_odeiv_step_name (step), desc, frac);\n\n gsl_odeiv_evolve_free (e);\n}\n\n\nvoid\ntest_evolve_system (const gsl_odeiv_step_type * T,\n\t\t const gsl_odeiv_system * sys,\n\t\t double t0, double t1, double hstart,\n\t\t double y[], double yfin[],\n\t\t double err_target, const char *desc)\n{\n int s = 0;\n double frac;\n\n double t = t0;\n double h = hstart;\n\n gsl_odeiv_step * step = gsl_odeiv_step_alloc (T, sys->dimension);\n\n gsl_odeiv_control *c =\n gsl_odeiv_control_standard_new (0.0, err_target, 1.0, 1.0);\n gsl_odeiv_evolve *e = gsl_odeiv_evolve_alloc (sys->dimension);\n\n while (t < t1)\n {\n gsl_odeiv_evolve_apply (e, c, step, sys, &t, t1, &h, y);\n /* printf (\"SYS t = %.18e h = %g y0 = %g y1= %g\\n\", t, h, y[0], y[1]); */\n }\n\n frac = fabs ((y[1] - yfin[1]) / yfin[1]) + fabs ((y[0] - yfin[0]) / yfin[0]);\n\n if (frac > 2.0 * e->count * err_target)\n {\n printf (\"SYS t = %.5e h = %g y0 = %g y1= %g\\n\", t, h, y[0], y[1]);\n s++;\n }\n\n gsl_test (s, \"%s, %s, evolve, standard control, relative error = %g\",\n\t gsl_odeiv_step_name (step), desc, frac);\n\n gsl_odeiv_evolve_free (e);\n gsl_odeiv_control_free (c);\n gsl_odeiv_step_free (step);\n}\n\n\nvoid\ntest_evolve_exp (const gsl_odeiv_step_type * T, double h, double err)\n{\n double y[2];\n double yfin[2];\n\n y[0] = 1.0;\n y[1] = 1.0;\n yfin[0] = exp (10.0);\n yfin[1] = yfin[0];\n test_evolve_system (T, &rhs_func_exp, 0.0, 10.0, h, y, yfin, err, \"exp [0,10]\");\n}\n\nvoid\ntest_evolve_sin (const gsl_odeiv_step_type * T, double h, double err)\n{\n double y[2];\n double yfin[2];\n\n y[0] = 1.0;\n y[1] = 0.0;\n yfin[0] = cos (2.0);\n yfin[1] = sin (2.0);\n test_evolve_system (T, &rhs_func_sin, 0.0, 2.0, h, y, yfin, err, \"sine [0,2]\");\n}\n\nvoid\ntest_evolve_stiff1 (const gsl_odeiv_step_type * T, double h, double err)\n{\n double y[2];\n double yfin[2];\n\n y[0] = 1.0;\n y[1] = 0.0;\n {\n double arg = 1.0;\n double e1 = exp (-arg);\n double e2 = exp (-1000.0 * arg);\n yfin[0] = 2.0 * e1 - e2;\n yfin[1] = -e1 + e2;\n }\n test_evolve_system (T, &rhs_func_stiff, 0.0, 1.0, h, y, yfin, err,\n \"stiff [0,1]\");\n}\n\nvoid\ntest_evolve_stiff5 (const gsl_odeiv_step_type * T, double h, double err)\n{\n double y[2];\n double yfin[2];\n\n y[0] = 1.0;\n y[1] = 0.0;\n {\n double arg = 5.0;\n double e1 = exp (-arg);\n double e2 = exp (-1000.0 * arg);\n yfin[0] = 2.0 * e1 - e2;\n yfin[1] = -e1 + e2;\n }\n test_evolve_system (T, &rhs_func_stiff, 0.0, 5.0, h, y, yfin, err,\n \"stiff [0,5]\");\n}\n\n\n\nint\nmain (void)\n{\n int i;\n\n struct ptype\n {\n const gsl_odeiv_step_type *type;\n double h;\n }\n p[20];\n\n p[0].type = gsl_odeiv_step_rk2;\n p[0].h = 1.0e-03;\n p[1].type = gsl_odeiv_step_rk2imp;\n p[1].h = 1.0e-03;\n p[2].type = gsl_odeiv_step_rk4;\n p[2].h = 1.0e-03;\n p[3].type = gsl_odeiv_step_rk4imp;\n p[3].h = 1.0e-03;\n p[4].type = gsl_odeiv_step_rkf45;\n p[4].h = 1.0e-03;\n p[5].type = gsl_odeiv_step_rk8pd;\n p[5].h = 1.0e-03;\n p[6].type = gsl_odeiv_step_rkck;\n p[6].h = 1.0e-03;\n p[7].type = gsl_odeiv_step_bsimp;\n p[7].h = 0.1;\n p[8].type = gsl_odeiv_step_gear1;\n p[8].h = 1.0e-03;\n p[9].type = gsl_odeiv_step_gear2;\n p[9].h = 1.0e-03;\n p[10].type = 0;\n\n gsl_ieee_env_setup ();\n\n for (i = 0; p[i].type != 0; i++)\n {\n test_stepper_linear (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON);\n test_stepper_sin (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON);\n test_stepper_exp (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON);\n test_stepper_stiff (p[i].type, p[i].h / 10.0, GSL_SQRT_DBL_EPSILON);\n }\n\n for (i = 0; p[i].type != 0; i++)\n {\n test_evolve_exp (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON);\n test_evolve_sin (p[i].type, p[i].h, GSL_SQRT_DBL_EPSILON);\n test_evolve_stiff1 (p[i].type, p[i].h, 1e-5);\n test_evolve_stiff5 (p[i].type, p[i].h, 1e-5);\n }\n\n exit (gsl_test_summary ());\n}\n", "meta": {"hexsha": "2f0c08cab7ef7a7e0e6bcc37d4d66bfdb561a7c4", "size": 14762, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/ode-initval/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.0423452769, "max_line_length": 84, "alphanum_fraction": 0.588741363, "num_tokens": 5602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.47293823540551894}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"beachball.h\"\n#include \"parmt_config.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#else\n#include \n#include \n#endif\n//#include \"pixmap.h\"\n//#include \"pixmap_png.h\"\n//#include \"pixmap_jpg.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n#ifndef M_PI_2\n#define M_PI_2 1.57079632679489661923\n#endif\n#ifndef MAX\n#define MAX(x,y) (((x) > (y)) ? (x) : (y))\n#endif\n#ifndef MIN\n#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n#endif\n#define PIXMAP_COLORS 3\n\nstatic void vecstrd(const double str, const double dip, double r[3]);\nstatic void strdv(const double r[3], double *str, double *dip);\nstatic void crossp(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n);\nstatic void strdvec(double r[3], double *str, double *dip);\nstatic void rotmat(const int naxis, const double theta,\n double *__restrict__ r,\n double *__restrict__ rt);\nstatic void isItNear(const double *__restrict__ pt, \n double *howClose,\n double *__restrict__ ptold);\nstatic double dot3(const double *__restrict__ x,\n const double *__restrict__ y);\nstatic void gemv3(const double *__restrict__ A, const double *__restrict__ x,\n double *__restrict__ y);\nstatic double transform(const double a, const double b,\n const double c, const double d,\n const double x);\n\n/*\nint beachball_setMomentTensor(const double m11, const double m22,\n const double m33, const double m12,\n const double m13, const double m23,\n const enum cmopad_basis_enum basis,\n struct beachballPlot_struct *beachball)\n{\n struct cmopad_struct cmt;\n double mt[3][3], m9[9], eigs[3];\n int ierr, info;\n bool lexplosion, limplosion;\n memset(&cmt, 0, sizeof(struct cmopad_struct));\n // the edge case is for purely isotropic sources\n lexplosion = false;\n limplosion = false;\n m9[0] = m11;\n m9[1] = m12;\n m9[2] = m13;\n m9[3] = m12;\n m9[4] = m22;\n m9[5] = m23;\n m9[6] = m13;\n m9[7] = m23;\n m9[8] = m33;\n info = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'N', 'L', 3, m9, 3, eigs);\n if (info != 0)\n {\n printf(\"Failed classifying eigenvalues\\n\");\n }\n if ((eigs[0] > 0.0 && eigs[1] > 0.0 && eigs[2] > 0.0))\n { \n //printf(\"Source is pure explosion\\n\"); \n lexplosion = true;\n }\n if ((eigs[0] < 0.0 && eigs[1] < 0.0 && eigs[2] < 0.0))\n { \n printf(\"Source is pure implosion\\n\");\n limplosion = true;\n }\n // copy the input moment tensor\n mt[0][0] = m11;\n mt[1][1] = m22;\n mt[2][2] = m33;\n mt[0][1] = mt[1][0] = m12;\n mt[0][2] = mt[2][0] = m13;\n mt[1][2] = mt[2][1] = m23;\n ierr = cmopad_basis_transformMatrixM33(mt, basis, NED);\n if (ierr != 0)\n {\n printf(\"Error transforming matrix\\n\");\n return -1;\n }\n // decompose the moment tensor\n ierr = cmopad_standardDecomposition(mt, &cmt);\n if (ierr != 0)\n {\n printf(\"Failed initializing moment tensor from strike, dip, rake\\n\");\n return -1;\n }\n // get the principal tension, null, and plunge axes \n ierr = cmopad_MT2PrincipalAxisSystem(0, &cmt);\n if (ierr != 0)\n {\n printf(\"Error computing principal axes\\n\");\n return -1;\n }\n if (lexplosion || limplosion)\n {\n cmt.p_axis[2] = cmt.eigenvalues[0];\n cmt.null_axis[2] = cmt.eigenvalues[1];\n cmt.t_axis[2] = cmt.eigenvalues[2];\n }\n else\n {\n // Convert pressure, null, and tension principal axes to\n // azimuth, plunge, and length\n ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[0],\n cmt.p_axis, cmt.p_axis);\n ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[1],\n cmt.null_axis, cmt.null_axis);\n ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[2],\n cmt.t_axis, cmt.t_axis);\n if (ierr != 0)\n {\n printf(\"Error converting eigenvector to principal axis!\\n\");\n return -1;\n }\n }\n memcpy(&beachball->cmt, &cmt, sizeof(struct cmopad_struct));\n beachball->lhaveMT = true;\n return 0;\n}\n*/\n\nint beachball_writePNG(const char *fileName,\n size_t height, size_t width, unsigned char *bytes)\n{\n FILE *file = NULL;\n png_structp png = NULL;\n png_infop info = NULL;\n png_bytepp rows = NULL;\n int h;\n\n file = fopen(fileName, \"wb\");\n if (file == NULL){printf(\"failed to open file\\n\");}\n png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (png == NULL){printf(\"error making png struct\\n\");}\n info = png_create_info_struct(png); \n if (info == NULL){printf(\"error making png info struct\\n\");}\n png_init_io(png, file);\n png_set_IHDR(png, info, width, height, 8,\n PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n png_write_info(png, info);\n rows = calloc(height, sizeof(png_bytep));\n for (h=0; h<(int) height; h++)\n {\n rows[h] = bytes + (PIXMAP_COLORS*h*(int) width);\n }\n png_write_rows(png, rows, height);\n png_write_end(png, NULL); //info);\n png_destroy_write_struct(&png, &info);\n if (rows != NULL){free(rows);}\n fclose(file);\n return 0;\n}\n\nint beachball_draw(struct beachballPlot_struct beachball)\n{\n const char *fcnm = \"beachball_draw\\0\";\n struct beachBall_struct beachImage;\n unsigned char *image;\n double baz, bdp, bev, paz, pdp, pev, taz, tdp, tev, x, xnorm, y;\n int i, i1, i2, indx, ix, iy, jy, k;\n size_t npixel;\n taz = beachball.tAxis[0];\n tdp = beachball.tAxis[1];\n tev = beachball.tAxis[2];\n baz = beachball.nAxis[0];\n bdp = beachball.nAxis[1];\n bev = beachball.nAxis[2];\n paz = beachball.pAxis[0];\n pdp = beachball.pAxis[1];\n pev = beachball.pAxis[2];\n // normalize the moment tensor for my sanity\n xnorm = MAX(fabs(tev), MAX(fabs(bev), fabs(pev)));\n if (xnorm == 0.0)\n {\n printf(\"%s: Error normalization is zero %f %f %f\\n\", fcnm, tev, bev, pev);\n return -1; \n }\n // compute everything describing the beachball \n memset(&beachImage, 0, sizeof(struct beachBall_struct));\n cliffsNodes_beachBallP(beachball.xc, beachball.yc, beachball.rad,\n taz, tdp, tev,\n baz, bdp, bev,\n paz, pdp, pev,\n beachball.nNodalLine,\n beachball.nFocalSphere,\n beachball.nxPixel, beachball.nyPixel,\n true, true, true,\n &beachImage);\n // draw the image\n npixel = (size_t) (beachball.nxPixel*beachball.nyPixel);\n image = (unsigned char *)\n calloc(PIXMAP_COLORS*npixel, sizeof(unsigned char));\n // Set a white background\n for (indx=0; indx<3*beachball.nxPixel*beachball.nyPixel; indx++)\n {\n image[indx] = 255;\n } \n // Draw the polarity\n if (beachball.lwantPolarity)\n { \n for (i=0; irad = 1.0;\n beachball->xc = 1.5;\n beachball->yc = 1.5;\n beachball->nxPixel = 251;\n beachball->nyPixel = 251;\n beachball->nNodalLine = 3*beachball->nxPixel;\n beachball->nFocalSphere = 4*beachball->nxPixel; \n beachball->lwantPolarity = true;\n beachball->lwantNodalLines = true;\n beachball->lhaveMT = false;\n return 0;\n}\n\nstatic double transform(const double a, const double b,\n const double c, const double d,\n const double x)\n{\n double det, c1, c2, xi;\n det = 1.0/(b - a);\n c1 = det*(b*c - a*d);\n c2 = det*(-c + d);\n xi = c1 + x*c2;\n return xi;\n}\n//============================================================================//\nint cliffsNodes_plotStations(const double xc, const double yc, const double rad,\n const int nstat, \n const double *__restrict__ az, \n const double *__restrict__ toa,\n double *__restrict__ xp, \n double *__restrict__ yp);\n\n/*!\n * @brief Computes the station locations for the given azimuth\n * and take-off angle on a focal sphere with radius rad\n * centered at (xc, yc). This is based on Cliff Frohlich's\n * stnPlt but now processes multiple stations and does no plotting.\n *\n * @param[in] xc x center of focal sphere\n * @param[in] yc y center of focal sphere\n * @param[in] rad radius of sphere\n * @param[in] nstat number of stations\n * @param[in] az source station azimuths (degrees) [nstat]\n * @param[in] toa take off angle (degrees) from source to stations [nstat]\n *\n * @param[out] xp station's x location on focal sphere [nstat]\n * @param[out] yp station's y location on focal sphere [nstat]\n *\n * @author Ben Baker\n *\n * @copyright BSD \n *\n */\nint cliffsNodes_plotStations(const double xc, const double yc, const double rad,\n const int nstat, \n const double *__restrict__ az,\n const double *__restrict__ toa,\n double *__restrict__ xp,\n double *__restrict__ yp)\n{\n const char *fcnm = \"cliffsNodes_plotStations\\0\";\n double azrad, rp, sign, toaN;\n int i;\n const double sqrt2 = 1.4142135623730951;\n const double degrad = M_PI/180.0;\n //------------------------------------------------------------------------//\n //\n // error handling\n if (nstat < 1 || az == NULL || toa == NULL || xp == NULL || yp == NULL)\n {\n if (nstat < 1){printf(\"%s: No stations\\n\", fcnm);}\n if (az == NULL){printf(\"%s: az is NULL\\n\", fcnm);}\n if (toa == NULL){printf(\"%s: toa is NULL\\n\", fcnm);}\n if (xp == NULL){printf(\"%s: xp is NULL\\n\", fcnm);}\n if (yp == NULL){printf(\"%s: yp is NULL\\n\", fcnm);}\n return -1;\n }\n // compute point on focal shere for each station\n for (i=0; i 90.)\n {\n toaN = 180. - toa[i];\n sign =-1.;\n }\n rp = sign*rad*sqrt2*sin(0.5*degrad*toaN);\n azrad = az[i]*degrad;\n xp[i] = xc + rp*sin(azrad);\n yp[i] = yc + rp*cos(azrad);\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Given the azimuth and dip of the tension and pressure eigenvectors\n * in geographic coordinates along with normalized eigenvalues\n * this computes the moment tensort in geographic coordinates as\n * well as the rotation and transpose rotation matrices which rotate\n * from a system where t=1-axis and p=2-axis. This is based on \n * Cliff Frohlich's mtensor.\n *\n * @param[in] taz tension axis azimuth (degrees)\n * @param[in] tdp tension axis dip (degrees)\n * @param[in] paz pressure axis azimuth (degrees)\n * @param[in] pdp pressure axis dip\n * @param[in] tev1 normalized eigenvalue for tension eigenvector\n * @param[in] bev1 normalized eigenvalue for null eigenvector \n * @param[in] pev1 normalized eigenvalue for pressure eigenvector \n *\n * @param[out] mt [3 x 3] moment tensor (column major)\n * @param[out] rm [3 x 3] rotation matrix as described above (column major)\n * @param[out] rmt [3 x 3] transpose rotation matrix described above \n * (column major)\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nvoid cliffsNodes_mtensor(const double taz, const double tdp,\n const double paz, const double pdp,\n const double tev1, const double bev1,\n const double pev1,\n double *__restrict__ mt,\n double *__restrict__ rm,\n double *__restrict__ rmt,\n double *ampMax)\n{ \n double mpt[9], sm1[9], smt1[9], sm2[9], smt2[9], sm3[9],\n smt3[9], work[9], p[3], pnew[3], pxt[3], t[3], pang;\n const double degrad = M_PI/180.0;\n // set up moment tensor in t-p system\n memset(mpt, 0, 9*sizeof(double));\n mpt[0] = tev1;\n mpt[4] = pev1;\n mpt[8] = bev1;\n // condition p-axis so that it really is perpendicular to t-axis\n vecstrd(taz, tdp, t);\n vecstrd(paz, pdp, p);\n crossp(p, t, pxt);\n crossp(t, pxt, p);\n // Step 1: rotate 1-axis about 3-axis so that 1-axis lies along t azimuth\n rotmat(3, taz-90., sm1, smt1);\n // Step 2: rotate 1-axis about 2-axis so that 1-axis liesalong t\n rotmat(2, tdp, sm2, smt2);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, sm2, 3, sm1, 3, 0.0, sm3, 3); \n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, smt1, 3, smt2, 3, 0.0, smt3, 3);\n // in this system, p should lie in 2-3 plane\n cblas_dgemv(CblasColMajor, CblasNoTrans, 3, 3,\n 1.0, sm3, 3, p, 1, 0.0, pnew, 1); \n // Step 3: rotate about 1 axis so that 2 axis lies along p\n pang = atan2(pnew[2], pnew[1])/degrad; //(3.14159/180.)\n rotmat(1, -pang, sm1, smt1);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, sm1, 3, sm3, 3, 0.0, rm, 3); \n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, smt3, 3, smt1, 3, 0.0, rmt, 3);\n // Finally: find moment tensor in space coordinates.\n // This is because Mpt=RM*Mspace*RMT, thus Mspace=RMT*Mpt*RM\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, rmt, 3, mpt, 3, 0.0, work, 3);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,\n 1.0, work, 3, rm, 3, 0.0, mt, 3);\n // ampMax is the absolute maximum amplitude\n *ampMax = MAX(fabs(pev1), MAX(fabs(tev1), fabs(bev1)));\n return;\n}\n//============================================================================//\n/*!\n * @brief Computes the lower-hemisphere projection `beachball' diagram for a\n * focal mechanism. This is based on Cliff Frohlich's bballP and \n * has been translated to C and does no plotting.\n *\n * @param[in] xc plot coordinates (e.g. pixels) of center of\n * beachball\n * @param[in] yc plot coordinates (e.g. pixels) of center of\n * beachball\n * @param[in] rad beachball radius (e.g. pixels)\n * @param[in] taz1 azimuth (degrees) of tension eigenvector\n * @param[in] tdp1 dip (degrees) of tension eigenvector\n * @param[in] tevI eigenvalue corresponding to tension eigenvector\n * (e.g. Newton meters)\n * @param[in] baz1 azimuth (degrees) of null eigenvector\n * @param[in] bdp1 dip (degrees) of null eigenvector\n * @param[in] bevI eigenvalue corresponding to null eigenvector\n * (e.g. Newton meters)\n * @param[in] paz1 azimuth (degrees) of pressure eigenvector\n * @param[in] pdp1 dip (degrees) of pressure eigenvector\n * @param[in] pevI eigenvalue corresponding to pressure eigenvector\n * (e.g. Newton meters)\n * @param[in] nNodalLine number of points to draw in nodal line.\n * @param[in] nFocalSphere number of points to draw in focal sphere.\n * @param[in] nxPixel number of pixels in x when drawing polarity\n * @param[in] nyPixel number of pixels in y when drawing polairty\n * @param[in] lwantNodalLines if true then compute the nodal lines.\n * @param[in] lwantPTBAxes if true then compute the PTB axis points.\n * @param[in] lwantPolarity if true then compute the polarity.\n *\n * @param[out] beachBall container for the pressure, tension and null axes,\n * the nodal lines, and the polarity\n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n * @bug this routine fails if rad is not = 1.\n *\n */\nvoid cliffsNodes_beachBallP(const double xc, const double yc, const double rad,\n const double taz1, const double tdp1,\n const double tevI,\n const double baz1, const double bdp1,\n const double bevI,\n const double paz1, const double pdp1,\n const double pevI,\n const int nNodalLine,\n const int nFocalSphere,\n const int nxPixel, const int nyPixel,\n const bool lwantNodalLines,\n const bool lwantPTBAxes,\n const bool lwantPolarity,\n struct beachBall_struct *beachBall)\n{\n double *xw1, *xw2, *yw1, *yw2;\n double rm[9] __attribute__ ((aligned(64)));\n double rmt[9] __attribute__ ((aligned(64)));\n double tm[9] __attribute__ ((aligned(64)));\n double pt[3] __attribute__ ((aligned(64)));\n double ptnew[3] __attribute__ ((aligned(64)));\n double ax1[3] __attribute__ ((aligned(64)));\n double ax2[3] __attribute__ ((aligned(64)));\n double ax3[3] __attribute__ ((aligned(64)));\n double ptLine1[3] __attribute__ ((aligned(64)));\n double ptLine2[3] __attribute__ ((aligned(64)));\n double ptLine1Old[3] __attribute__ ((aligned(64)));\n double ptLine2Old[3] __attribute__ ((aligned(64)));\n double ampMax, az, baz, bdp, bev, cosPsi, cosTheta, \n dip, dp, dpsi, dx, dy, evI, fclvd, fIso, howClose, rad2,\n rb, rp, rpt, rpt2, rt, paz, pdp, pev, plusMin, psi,\n sinsq, sinPsi, sinTheta, str,\n taz, tdp, tev, theta, x, x0, xpt, y, y0, ypt;\n int *pn1, *pn2, ix, ixy, iy, k, nlines, nnl1, nnl2, npts, nseg,\n nx, ny, penDown, psave1, psave2;\n size_t nwork;\n const double sqrt2 = 1.4142135623730951;\n const double sqrt2i = 1.0/sqrt2;\n const double degrad = M_PI/180.0;\n const double degradi = 180.0/M_PI; \n const double third = 1.0/3.0;\n const double tol = 0.95;\n // null out result\n memset(beachBall, 0, sizeof(struct beachBall_struct));\n // Avoid overwriting memory\n taz = taz1;\n tdp = tdp1;\n baz = baz1;\n bdp = bdp1;\n paz = paz1;\n pdp = pdp1;\n // Step 1: set up axes:\n // - D axis ('dominant' 1-axis - with largest absolute eigenvalue)\n // - M axis ('minor' 3-axis)\n // - B axis ( 2-axis)\n evI = (tevI + bevI + pevI)*third;\n tev = tevI - evI;\n bev = bevI - evI;\n pev = pevI - evI;\n vecstrd(paz, pdp, ax1);\n vecstrd(taz, tdp, ax3);\n fclvd = fabs(bev/pev);\n fIso = evI/pev;\n if (fabs(tev) > fabs(pev))\n {\n vecstrd(taz, tdp, ax1);\n vecstrd(paz, pdp, ax3);\n fclvd = fabs(bev/tev);\n fIso = evI/tev;\n }\n //if (fabs(evI) > .03) \n //{\n // write(6,901) evI\n //}\n crossp(ax1, ax3, ax2);\n strdvec(ax2, &baz, &bdp);\n cliffsNodes_mtensor(taz, tdp, paz, pdp, tevI, bevI, pevI,\n tm, rm, rmt, &Max);\n // Step 2: Now: plot upper half nodal line:\n // point on nodal line is represented by vector pt;\n // pt is defined by two angles \n // - psi is azimuth with respect to 3-axis (M-axis) \n // in 2-3 plane (in B-M plane)\n // - theta is angle with respect to 1 axis.\n // It can be shown (i. e., cliff did it once) that:\n // sin(theta)**2=(2+2*fIso)/(3+(1-2*f)*cos(2*psi))\n // Additionally, a constraint corresponding to Cliff's Rule 1\n // for existance of P nodal planes is applied\n //psi = 0.;\n //dpsi = 2.;\n //npts = nNodalLine1; //1 + (int)(360.0/dpsi + 0.5); //nint((360./dpsi))\n //dpsi = dpsi*degrad;\n psave1 =-1;\n psave2 =-1;\n memset(ptLine1Old, 0, 3*sizeof(double));\n memset(ptLine2Old, 0, 3*sizeof(double));\n if (lwantNodalLines && nNodalLine > 1 &&\n !(tevI > 0.0 && bevI > 0.0 && pevI > 0.0) &&\n !(tevI < 0.0 && bevI < 0.0 && pevI < 0.0))\n {\n npts = nNodalLine;\n psi = 0.0;\n dpsi = 360.0/(double) (nNodalLine - 1);\n dpsi = dpsi*degrad;\n xw1 = (double *) calloc((size_t) npts, sizeof(double));\n yw1 = (double *) calloc((size_t) npts, sizeof(double));\n pn1 = (int *) calloc((size_t) npts+1, sizeof(int));\n xw2 = (double *) calloc((size_t) npts, sizeof(double));\n yw2 = (double *) calloc((size_t) npts, sizeof(double));\n pn2 = (int *) calloc((size_t) npts+1, sizeof(int));\n nnl1 = 0;\n nnl2 = 0;\n for (k=0; k 0 && sinsq <= 1.0)\n {\n theta = asin(sqrt(sinsq));\n cosTheta = cos(theta);\n sinTheta = sin(theta);\n cosPsi = cos(psi);\n sinPsi = sin(psi);\n // upper half nodal line\n ptLine1[0] = cosTheta*ax1[0] \n + sinTheta*(sinPsi*ax2[0] + cosPsi*ax3[0]);\n ptLine1[1] = cosTheta*ax1[1]\n + sinTheta*(sinPsi*ax2[1] + cosPsi*ax3[1]);\n ptLine1[2] = cosTheta*ax1[2]\n + sinTheta*(sinPsi*ax2[2] + cosPsi*ax3[2]);\n // lower half nodal line\n ptLine2[0] =-cosTheta*ax1[0]\n - sinTheta*(sinPsi*ax2[0] + cosPsi*ax3[0]);\n ptLine2[1] =-cosTheta*ax1[1]\n - sinTheta*(sinPsi*ax2[1] + cosPsi*ax3[1]);\n ptLine2[2] =-cosTheta*ax1[2]\n - sinTheta*(sinPsi*ax2[2] + cosPsi*ax3[2]);\n isItNear(ptLine1, &howClose, ptLine1Old);\n // upper half nodal line\n penDown =-1;\n if (ptLine1[2] < 0.0){penDown = 1;}\n if (howClose < tol){penDown =-1;}\n strdv(ptLine1, &str, &dip);\n rpt = rad*sqrt2*sin(0.5*degrad*(90.-dip));\n xpt = xc + rpt*sin(str*degrad);\n ypt = yc + rpt*cos(str*degrad);\n xw1[k] = xpt;\n yw1[k] = ypt;\n if (k == 0){pn1[k] = 3;}\n if (penDown == 1 && psave1 == 1)\n {\n pn1[k] = 2;\n //printf(\"%f %f\\n\", xpt, ypt);\n }\n if (penDown ==-1){pn1[k] = 3;}\n nnl1 = nnl1 + 1;\n psave1 = penDown;\n // lower half nodal line\n penDown =-1;\n if (ptLine2[2] < 0.0){penDown = 1;} \n if (howClose < tol){penDown =-1;}\n strdv(ptLine2, &str, &dip);\n rpt = rad*sqrt2*sin(0.5*degrad*(90.-dip));\n xpt = xc + rpt*sin(str*degrad);\n ypt = yc + rpt*cos(str*degrad);\n xw2[k] = xpt;\n yw2[k] = ypt;\n if (k == 0){pn2[k] = 3;} // pen down\n if (penDown == 1 && psave2 == 1)\n {\n pn2[k] = 2;\n //xptsLine2[k] = xpt;\n //yptsLine2[k] = ypt;\n //penLine2[k] = penDwn;\n }\n if (penDown ==-1){pn2[k] = 3;}\n nnl2 = nnl2 + 1;\n psave2 = penDown;\n }\n } // loop on points\n nwork = (size_t) (MAX(2, 2*nnl1));\n beachBall->xNodalLine1 = (double *) calloc(nwork, sizeof(double));\n beachBall->yNodalLine1 = (double *) calloc(nwork, sizeof(double));\n nwork = (size_t) (nnl1 + 1);\n beachBall->nodalLine1Ptr = (int *) calloc(nwork, sizeof(int));\n nwork = (size_t) (MAX(2, 2*nnl2));\n beachBall->xNodalLine2 = (double *) calloc(nwork, sizeof(double));\n beachBall->yNodalLine2 = (double *) calloc(nwork, sizeof(double));\n nwork = (size_t) (nnl2 + 1);\n beachBall->nodalLine2Ptr = (int *) calloc(nwork, sizeof(int));\n // make sure the lines end\n pn1[nnl1] = 3;\n pn2[nnl2] = 3;\n // compute the nodal line 1 line segments \n nlines = 0;\n nseg = 0;\n for (k=0; kxNodalLine1[2*nlines ] = xw1[k];\n beachBall->xNodalLine1[2*nlines+1] = xw1[k+1]; \n beachBall->yNodalLine1[2*nlines ] = yw1[k];\n beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];\n nlines = nlines + 1;\n }\n // line continues\n if (pn1[k] == 2 && pn1[k+1] == 2)\n {\n beachBall->xNodalLine1[2*nlines ] = xw1[k];\n beachBall->xNodalLine1[2*nlines+1] = xw1[k+1]; \n beachBall->yNodalLine1[2*nlines ] = yw1[k];\n beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];\n nlines = nlines + 1;\n }\n // line ends \n if (pn1[k] == 2 && pn1[k+1] == 3)\n {\n/*\n beachBall->xNodalLine1[2*nlines ] = xw1[k];\n beachBall->xNodalLine1[2*nlines+1] = xw1[k+1]; \n beachBall->yNodalLine1[2*nlines ] = yw1[k];\n beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];\n nlines = nlines + 1;\n*/\n nseg = nseg + 1;\n beachBall->nodalLine1Ptr[nseg] = nlines;\n }\n }\n beachBall->nNodalLineSegs1 = nseg;\n // compute the nodal line 2 line segments \n nlines = 0;\n nseg = 0;\n for (k=0; kxNodalLine2[2*nlines ] = xw2[k];\n beachBall->xNodalLine2[2*nlines+1] = xw2[k+1]; \n beachBall->yNodalLine2[2*nlines ] = yw2[k];\n beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];\n nlines = nlines + 1;\n }\n // line continues\n if (pn2[k] == 2 && pn2[k+1] == 2)\n {\n beachBall->xNodalLine2[2*nlines ] = xw2[k];\n beachBall->xNodalLine2[2*nlines+1] = xw2[k+1]; \n beachBall->yNodalLine2[2*nlines ] = yw2[k];\n beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];\n nlines = nlines + 1;\n }\n // line ends \n if (pn2[k] == 2 && pn2[k+1] == 3)\n {\n beachBall->xNodalLine2[2*nlines ] = xw2[k];\n beachBall->xNodalLine2[2*nlines+1] = xw2[k+1]; \n beachBall->yNodalLine2[2*nlines ] = yw2[k];\n beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];\n nlines = nlines + 1;\n nseg = nseg + 1;\n beachBall->nodalLine2Ptr[nseg] = nlines;\n }\n }\n beachBall->nNodalLineSegs2 = nseg;\n//printf(\"%d %d\\n\", nlines, nseg);\n free(pn1);\n free(pn2);\n free(xw1);\n free(xw2);\n free(yw1);\n free(yw2);\n }\n // Step 4: Plot the, P, T, and B axes\n if (lwantPTBAxes)\n {\n rp = rad*sqrt2*sin(0.5*degrad*(90.-pdp));\n rt = rad*sqrt2*sin(0.5*degrad*(90.-tdp));\n rb = rad*sqrt2*sin(0.5*degrad*(90.-bdp));\n beachBall->xp = xc + rp*sin(paz*degrad);\n beachBall->yp = yc + rp*cos(paz*degrad);\n beachBall->xt = xc + rt*sin(taz*degrad);\n beachBall->yt = yc + rt*cos(taz*degrad);\n beachBall->xb = xc + rb*sin(baz*degrad);\n beachBall->yb = yc + rb*cos(baz*degrad);\n }\n // Step 5: Plot the focal sphere\n if (nFocalSphere > 1)\n {\n beachBall->nFocalSphere = nFocalSphere;\n beachBall->xFocalSphere = (double *)\n calloc((size_t) nFocalSphere, sizeof(double));\n beachBall->yFocalSphere = (double *)\n calloc((size_t) nFocalSphere, sizeof(double));\n dpsi = 2.0*M_PI/(double) (nFocalSphere - 1);\n#ifdef _OPENMP\n #pragma omp simd\n#endif\n for (k=0; kxFocalSphere[k] = xc + rad*sin(psi);\n beachBall->yFocalSphere[k] = yc + rad*cos(psi);\n } \n }\n // Step 6: Plot the + and -\n if (lwantPolarity && nxPixel > 0 && nyPixel > 0)\n {\n // begin in lower left corner\n nx = nxPixel;\n ny = nyPixel;\n dx = 2.0*rad/(double) (nx - 1); \n dy = 2.0*rad/(double) (ny - 1);\n x0 = xc - rad;\n y0 = yc - rad;\n rad2 = rad*rad; // saves a sqrt computation when comparing distances\n xw1 = (double *)calloc((size_t) (nx*ny), sizeof(double));\n yw1 = (double *)calloc((size_t) (nx*ny), sizeof(double));\n pn1 = (int *)calloc((size_t) (nx*ny), sizeof(int)); \n nwork = 0;\n // loop on pixel grid\n for (iy=0; iy 100.0*DBL_EPSILON*ampMax){pn1[k] = 1;}\n } // end check on location\n } // loop on x\n } // loop on y\n // Copy the points to be plotted\n if (nwork > 0)\n {\n beachBall->npolarity = (int) nwork;\n beachBall->xPolarity = (double *)\n calloc((size_t) nwork, sizeof(double));\n beachBall->yPolarity = (double *)\n calloc((size_t) nwork, sizeof(double));\n beachBall->polarity = (int *)\n calloc((size_t) nwork, sizeof(double));\n k = 0; \n for (ixy=0; ixyxPolarity[k] = xw1[ixy];\n beachBall->yPolarity[k] = yw1[ixy];\n beachBall->polarity[k] = pn1[ixy];\n k = k + 1;\n }\n }\n }\n free(pn1);\n free(xw1);\n free(yw1);\n }\n return;\n}\n\nvoid cliffsNodes_free(struct beachBall_struct *beachBall)\n{\n if (beachBall->xNodalLine1 != NULL){free(beachBall->xNodalLine1);}\n if (beachBall->yNodalLine1 != NULL){free(beachBall->yNodalLine1);}\n if (beachBall->xNodalLine2 != NULL){free(beachBall->xNodalLine2);}\n if (beachBall->yNodalLine2 != NULL){free(beachBall->yNodalLine2);}\n if (beachBall->xFocalSphere != NULL){free(beachBall->xFocalSphere);}\n if (beachBall->yFocalSphere != NULL){free(beachBall->yFocalSphere);}\n if (beachBall->xPolarity != NULL){free(beachBall->xPolarity);}\n if (beachBall->yPolarity != NULL){free(beachBall->yPolarity);}\n if (beachBall->polarity != NULL){free(beachBall->polarity);}\n if (beachBall->nodalLine1Ptr != NULL){free(beachBall->nodalLine1Ptr);}\n if (beachBall->nodalLine2Ptr != NULL){free(beachBall->nodalLine2Ptr);}\n memset(beachBall, 0, sizeof(struct beachBall_struct));\n return;\n}\n//============================================================================//\n/*! \n * @brief Finds simple rotation matrix R and transpose R^T for rotation\n * of a vector by angle theta about x, y, or z. This is based on \n * Cliff Rohlich's rotmat.\n *\n * @param[in] naxis rotation axis. if 1 then x. if 2 then y. if 3 then z.\n * @param[in] theta rotation angle (degrees)\n * @param[out] r rotation matrix [3 x 3] in column major format.\n * @param[out] rt tranpsose rotation matrix [3 x 3] in column major format.\n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void rotmat(const int naxis, const double theta,\n double *__restrict__ r,\n double *__restrict__ rt)\n{\n double cosThetar, sinThetar, thetar;\n int i, j;\n const double degrad = M_PI/180.0;\n memset(r, 0, 9*sizeof(double));\n thetar = theta*degrad;\n cosThetar = cos(thetar); \n sinThetar = sin(thetar);\n r[0] = cosThetar;\n r[4] = cosThetar;\n r[8] = cosThetar;\n // naxis = x\n if (naxis == 1)\n {\n r[0] = 1.0; // (1, 1)\n r[5] = sinThetar; // (3, 2)\n r[7] =-sinThetar; // (2, 3)\n }\n // naxis = y\n else if (naxis == 2)\n {\n r[2] = sinThetar; // (3, 1)\n r[4] = 1.0; // (2, 2)\n r[6] =-sinThetar; // (1, 3)\n }\n // naxis = z\n else if (naxis == 3)\n {\n r[1] = sinThetar; // (2, 1)\n r[3] =-sinThetar; // (1, 2)\n r[8] = 1.0; // (3, 3)\n }\n // Compute the transpose \n for (i=0; i<3; i++)\n {\n for (j=0; j<3; j++)\n {\n rt[3*i+j] = r[3*j+i];\n }\n }\n return;\n}\n//============================================================================//\n/*!\n * @brief Find components of downward pointing unit vector pole from the \n * strike and dip angles. This is based on Cliff Frolich's vecstrd.\n *\n * @param[in] str strike angle of pole (degrees)\n * @param[in] dip dip angle of pole (degrees)\n *\n * @param[out] r corresponding unit vector pole (3)\n *\n * @author Ben Baker\n *\n * @copyright BSD\n * \n */\nstatic void vecstrd(const double str, const double dip, double r[3])\n{\n double cosdip, cosstr, diprad, sindip, sinstr, strrad;\n const double degrad = M_PI/180.0;\n // convert to radians\n strrad = str*degrad;\n diprad = dip*degrad;\n // compute cosines and sines\n sinstr = sin(strrad);\n cosstr = cos(strrad);\n cosdip = cos(diprad);\n sindip = sin(diprad);\n // compute (x,y,z) from strike and dip for unit radius \n r[0] = sinstr*cosdip;\n r[1] = cosstr*cosdip;\n r[2] =-sindip;\n return;\n}\n//============================================================================//\nstatic void isItNear(const double *__restrict__ pt,\n double *howClose,\n double *__restrict__ ptold)\n{\n *howClose = dot3(ptold, pt); //cblas_ddot(3, ptold, 1, pt, 1); \n ptold[0] = pt[0];\n ptold[1] = pt[1];\n ptold[2] = pt[2];\n return;\n}\n/*!\n * @brief Finds the strike and dip of downward pointing unit vector. This\n * is based on Cliff Frolich's strdvec.\n *\n * @param[in,out] r on input contains the downward pointing unit\n * vector.\n * if r[2] is > 0 then the unit vector is pointing\n * updward. in this case then on output r3 will\n * be negated.\n *\n * @param[out] str strike angle (degrees) \\f$ s.t. \\phi \\in [0,360] \\f$.\n * @param[out] dip dip angle (degrees) \n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void strdvec(double r[3], double *str, double *dip)\n{\n double rs;\n const double degradi = 180.0/M_PI;\n if (r[2] > 0.0)\n {\n r[0] =-r[0];\n r[1] =-r[1];\n r[2] =-r[2];\n }\n *str = atan2(r[0], r[1])*degradi;\n if (*str < 0.){*str = *str + 360.;}\n rs = sqrt(r[0]*r[0] + r[1]*r[1]);\n *dip=atan2(-r[2], rs)*degradi;\n return;\n}\n/*!\n * @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n.\n * \n * @param[in] u first vector in cross product u x v [3]\n * @param[in] v second vector in cross product u x v [3]\n * \n * @param[out] n normal vector n = u x v [3]\n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void crossp(const double *__restrict__ u,\n const double *__restrict__ v,\n double *__restrict__ n)\n{\n n[0] = u[1]*v[2] - u[2]*v[1];\n n[1] = u[2]*v[0] - u[0]*v[2]; \n n[2] = u[0]*v[1] - u[1]*v[0];\n return;\n}\n/*!\n * @brief Finds strike and dip given components of unit vector. This is\n * based on Cliff Frohlich's strdv.\n *\n * @param[in] r unit vector \n * @param[out] str strike angle (degrees)\n * @param[out] dip dip angle (degrees) s.t. dip down is positive\n *\n * @author Ben Baker\n *\n * @copyright BSD\n *\n */\nstatic void strdv(const double r[3], double *str, double *dip)\n{\n double rs;\n const double degradi = 180.0/M_PI;\n *str = atan2(r[0], r[1])*degradi;\n rs = sqrt(r[0]*r[0] + r[1]*r[1]);\n *dip = atan2(-r[2], rs)*degradi;\n return;\n}\n\n/*!\n * @brief Utility function for computing dot product of length 3 vector\n */\nstatic double dot3(const double *__restrict__ x,\n const double *__restrict__ y)\n{\n double dot;\n dot = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return dot;\n}\n\n/*!\n * @brief Utility function for computing y = Ax for 3 x 3 matrix.\n */\nstatic void gemv3(const double *__restrict__ A, const double *__restrict__ x,\n double *__restrict__ y)\n{\n y[0] = A[0]*x[0] + A[3]*x[1] + A[6]*x[2];\n y[1] = A[1]*x[0] + A[4]*x[1] + A[7]*x[2];\n y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2];\n return;\n}\n", "meta": {"hexsha": "7b36509686211bfc11ac4732d710fc6c8d25ddc0", "size": 45668, "ext": "c", "lang": "C", "max_stars_repo_path": "postprocess/beachball.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "postprocess/beachball.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "postprocess/beachball.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.835956918, "max_line_length": 82, "alphanum_fraction": 0.5041604625, "num_tokens": 13789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924954, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4728991748075799}} {"text": "/*\n** Implementation of LISA algorithm\n** for statistical inference of fMRI images\n**\n** 1st level analysis using GLM (general linear model) with pre-coloring\n**\n** G.Lohmann, April 2017\n*/\n#include \"viaio/Vlib.h\"\n#include \"viaio/file.h\"\n#include \"viaio/mu.h\"\n#include \"viaio/option.h\"\n#include \"viaio/os.h\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n\ntypedef struct TrialStruct {\n int id;\n float onset;\n float duration;\n float height;\n} Trial;\n\nextern void VIsolatedVoxels(VImage src,float threshold);\nextern void VHistogram(gsl_histogram *histogram,VString filename);\nextern void VCheckImage(VImage src);\nextern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);\nextern double ttest1(double *data1,int n);\nextern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);\nextern Trial *ReadDesign(VStringConst designfile,int *numtrials,int *nevents);\nextern gsl_matrix *VCreateDesign(int ntimesteps,int nevents,int,VBoolean,gsl_matrix *);\nextern void VHemoModel(Trial *trial,int ntrials,int nevents,int ntimesteps,double tr,int,VBoolean,gsl_matrix *,gsl_matrix *);\nextern Trial *CopyTrials(Trial *trial,int numtrials);\nextern void VGLM(gsl_matrix *Data,gsl_matrix *X,gsl_matrix *XInv,gsl_vector *con,VImage map,VImage zmap);\nextern Trial *ConcatenateTrials(Trial **trial,int *numtrials,float *run_duration,int dlists,int sumtrials);\n\nextern double VImageVar(VImage src);\nextern void VImageCount(VImage src);\nextern void VBilateralFilter(VImage src,VImage,int radius,double var1,double var2,int);\nextern void VGetHistRange(VImage src,double *hmin,double *hmax);\nextern void VZScale(VImage src,float,float stddev);\nextern float VGetMode(VImage src);\nextern void GlobalMean(gsl_matrix *Data,gsl_matrix *covariates,int column);\nextern gsl_matrix *VReadCovariates(VString cfile,VBoolean normalize);\n\nextern VImage VoxelMap(VAttrList list);\nextern gsl_matrix *VReadImageData(VAttrList *list,int nlists);\nextern void VGetTimeInfos(VAttrList *list,int nlists,double *mtr,float *run_duration);\nextern void VRowNormalize(gsl_matrix *Data);\nextern void CheckTrialLabels(Trial *trial,int numtrials);\nextern void HistoUpdate(VImage,gsl_histogram *);\nextern void PlotDesign(gsl_matrix *X,double tr,VString filename);\n\n\nvoid XCheckImage(VImage src,char *filename)\n{\n VAttrList out_list = VCreateAttrList();\n VAppendAttr(out_list,\"image\",NULL,VImageRepn,src);\n FILE *out_file = fopen(filename,\"w\");\n VWriteFile (out_file, out_list);\n}\n\n\n\n\n/* shuffle each run separately to ensure exchangebility, concatenate individual permtables */\nint **genperm(gsl_rng *rx,int *numtrials,int sumtrials,int dlists,int numperm)\n{\n int i,j,k;\n\n int **permtable = (int **) VCalloc(numperm,sizeof(int *));\n\n gsl_permutation **perm = (gsl_permutation **) VCalloc(dlists,sizeof(gsl_permutation *));\n for (k=0; kdata,numtrials[k],sizeof(size_t));\n for (j=0; jdata[j] + jj;\n }\n jj += numtrials[k];\n }\n }\n\n for (k=0; k 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\" using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n\n\n /* read functional image data */\n int nlists = in_files.number;\n if (nlists < 1) VError(\" no input\");\n\n VAttrList *list = (VAttrList *) VCalloc(nlists,sizeof(VAttrList));\n for (i=0; i 0.01) VError(\" Input files must be 4D (not 3D)\");\n }\n }\n\n\n /* get number og design files */\n int dlists = des_files.number;\n if (dlists != nlists) {\n VError(\" number of input functional files (%d) and design files (%d) do not match\",nlists,dlists);\n }\n\n\n /* apply brain mask or threshold */\n VMultMinval(list,nlists,mask_filename,0.0);\n\n\n /* read data and voxel map */\n double tr=0;\n float *run_duration = (float *) VCalloc(nlists,sizeof(float));\n VGetTimeInfos(list,nlists,&tr,run_duration);\n gsl_matrix *Data = VReadImageData(list,nlists);\n VImage map = VoxelMap(list[0]);\n int nslices = VPixel(map,0,3,0,VShort);\n int nrows = VPixel(map,0,3,1,VShort);\n int ncols = VPixel(map,0,3,2,VShort);\n int ntimesteps = Data->size2;\n\n \n\n /* additional regressors, no task labels, not included in permutations */\n gsl_matrix *ctmp1=NULL;\n gsl_matrix *ctmp2=NULL;\n gsl_matrix *covariates=NULL;\n int cdim = 1;\n int nuisance_dim=0;\n if (strlen(cova_filename) > 1) {\n ctmp1 = VReadCovariates(cova_filename,demean);\n if (ctmp1->size1 != Data->size2) VError(\" num timesteps in covariate file not consistent with data\");\n nuisance_dim = ctmp1->size2;\n }\n if (globalmean) {\n if (ctmp1 != NULL) cdim = ctmp1->size2+1;\n ctmp2 = gsl_matrix_calloc(Data->size2,cdim);\n GlobalMean(Data,ctmp2,(int)(cdim-1));\n }\n if (ctmp1 != NULL && ctmp2 == NULL) covariates = ctmp1;\n if (ctmp2 != NULL) covariates = ctmp2;\n\n\n /* design files with task labels */\n Trial **trial = (Trial **) VCalloc(dlists,sizeof(Trial *));\n int *numtrials = (int *) VCalloc(dlists,sizeof(int *));\n int nevents = 0;\n int sumtrials = 0;\n for (i=0; i nevents) nevents = jj;\n sumtrials += numtrials[i];\n }\n fprintf(stderr,\" Number of trials: %d, number of event types: %d\\n\",sumtrials,nevents);\n Trial *alltrials = ConcatenateTrials(trial,numtrials,run_duration,nlists,sumtrials);\n CheckTrialLabels(alltrials,sumtrials);\n\n\n /* read contrast vector */ \n gsl_vector *cont = gsl_vector_alloc(contrast.number + nuisance_dim);\n gsl_vector_set_zero(cont);\n for (i=0; i < contrast.number; i++) {\n double u = ((VFloat *)contrast.vector)[i];\n gsl_vector_set(cont,i,u);\n }\n\n\n /* alloc initial design matrix X */\n gsl_matrix *X = VCreateDesign(ntimesteps,nevents,(int)hemomodel,firstcol,covariates);\n fprintf(stderr,\" Design file dimensions: %lu x %lu\\n\",X->size1,X->size2);\n \n \n gsl_matrix *XInv = gsl_matrix_calloc(X->size2,X->size1);\n if (X->size2 != cont->size) {\n VError(\" dimension of contrast vector (%ld) does not match design matrix (%ld)\",cont->size-1,X->size2);\n }\n\n /* ini random permutations */\n gsl_rng_env_setup();\n const gsl_rng_type *T = gsl_rng_default;\n gsl_rng *rx = gsl_rng_alloc(T);\n gsl_rng_set(rx,(unsigned long int)seed);\n if (verbose) fprintf(stderr,\" seed: %ld\\n\",(long)seed);\n int **permtable = genperm(rx,numtrials,sumtrials,dlists,(int)numperm);\n\n\n /* estimate null variance to adjust radiometric parameter, use first 30 permutations */\n int nperm=0;\n float stddev = 1.0;\n double meanvar = 0.0;\n if (numperm > 0) {\n int tstperm = 30;\n if (tstperm > numperm) tstperm = numperm;\n VImage zmap = VCreateImage(nslices,nrows,ncols,VFloatRepn);\n double varsum=0,nx=0;\n for (nperm = 0; nperm < tstperm; nperm++) {\n Trial *permtrials = CopyTrials(alltrials,sumtrials);\n int j=0;\n for (j=0; jsize2,X->size1);\n VHemoModel(permtrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);\n VGLM(Data,X,XInv,cont,map,zmap);\n varsum += VImageVar(zmap);\n nx++;\n\n gsl_matrix_free(X);\n gsl_matrix_free(XInv);\n VFree(permtrials);\n }\n meanvar = varsum/nx;\n stddev = (float)(sqrt(meanvar)); /* update stddev */\n VDestroyImage(zmap);\n }\n \n\n /* no permutation */\n VImage zmap1 = VCreateImage(nslices,nrows,ncols,VFloatRepn);\n VCopyImageAttrs (map,zmap1);\n VImage dst1 = VCreateImageLike (zmap1);\n VHemoModel(alltrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);\n if (strlen(plot_filename) > 0) PlotDesign(X,tr,plot_filename);\n VGLM(Data,X,XInv,cont,map,zmap1);\n\n\n if (numperm == 0) {\n double z = VImageVar(zmap1);\n stddev = sqrt(z); /* update stddev */\n }\n float mode=0;\n if (numperm > 0) VZScale(zmap1,mode,stddev);\n VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n\n /* ini histograms */\n double hmin=0,hmax=0;\n VGetHistRange(dst1,&hmin,&hmax);\n size_t nbins = 20000;\n gsl_histogram *hist0 = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);\n gsl_histogram *histz = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (histz,hmin,hmax);\n HistoUpdate(dst1,histz);\n\n\n /* random permutations */\n#pragma omp parallel for shared(Data) schedule(dynamic)\n for (nperm = 0; nperm < numperm; nperm++) {\n if (nperm%5 == 0) fprintf(stderr,\" perm %4d of %d\\r\",nperm,(int)numperm);\n\n /* randomly shuffle trial labels */\n Trial *permtrials = CopyTrials(alltrials,sumtrials);\n int j=0;\n for (j=0; jsize2,X->size1);\n VHemoModel(permtrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);\n\n\n /* GLM */\n VImage zmap = VCreateImageLike(zmap1);\n VGLM(Data,X,XInv,cont,map,zmap);\n VZScale(zmap,mode,stddev);\n gsl_matrix_free(X);\n gsl_matrix_free(XInv);\n VFree(permtrials);\n\n\n /* bilateral filter */\n VImage dst = VCreateImageLike (zmap);\n VBilateralFilter(zmap,dst,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n#pragma omp critical\n {\n HistoUpdate(dst,hist0);\n }\n VDestroyImage(dst);\n VDestroyImage(zmap);\n }\n\n\n /* apply fdr */\n VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);\n if (numperm > 0) {\n FDR(dst1,fdrimage,hist0,histz,(double)alpha);\n if (cleanup && alpha < 1.0) {\n VIsolatedVoxels(fdrimage,(float)(1.0-alpha));\n }\n }\n\n\n\n /*\n ** output\n */\n out_list = VCreateAttrList ();\n VHistory(VNumber(options),options,prg_name,&list[0],&out_list);\n\n /* update geoinfo, 4D to 3D */\n if (geolist != NULL) {\n double *D = VGetGeoDim(geolist,NULL);\n D[0] = 3;\n D[4] = 1;\n VSetGeoDim(geolist,D);\n }\n VSetGeoInfo(geolist,out_list);\n VAppendAttr (out_list,\"image\",NULL,VImageRepn,fdrimage);\n fp = VOpenOutputFile (out_filename, TRUE);\n if (! VWriteFile (fp, out_list)) exit (1);\n fclose(fp);\n\n\n fprintf (stderr, \"\\n%s: done.\\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "bd574ceb52029e2c74c0c42241c1d8d0e9cb54f4", "size": 14878, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.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": 33.3587443946, "max_line_length": 125, "alphanum_fraction": 0.6878612717, "num_tokens": 4577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.47231250057171953}} {"text": "//Normalizes RMS of each vector in X according to dim.\n//See C++ command-line code for more info.\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint rms_scale_s (float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const float sr, const float tau, const float target_dB_SPL, const float max_dB_SPL);\nint rms_scale_d (double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const double sr, const double tau, const double target_dB_SPL, const double max_dB_SPL);\n\n\nint rms_scale_s (float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const float sr, const float tau, const float target_dB_SPL, const float max_dB_SPL)\n{\n if (dim>3u) { fprintf(stderr,\"error in rms_scale_s: dim must be in [0 3]\\n\"); return 1; }\n if (sr<=0.0f) { fprintf(stderr,\"error in rms_scale_s: sr (sample rate) must be positive\\n\"); return 1; }\n if (tau<=0.0f) { fprintf(stderr,\"error in rms_scale_s: tau (time constant) must be positive\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N<2u || L<2u) {}\n else\n {\n const float rms_prctile = 0.9f;\n const float target_RMS = 20e-6f * powf(10.0f, target_dB_SPL/20.0f);\n const float max_RMS = 20e-6f * powf(10.0f, max_dB_SPL/20.0f);\n const float a1 = expf(-1.0f/(sr*tau));\n const float b0 = 1.0f - a1;\n const size_t tranz = (L>5u) ? 5u : 0u; //nsamps to zero in case transient\n const size_t rms_p = (size_t)roundf((1.0f-rms_prctile)*(float)L); //index for rms_prctile\n float rms, scale, scalemx;\n \n float *Y;\n if (!(Y=(float *)malloc(L*sizeof(float)))) { fprintf(stderr,\"error in rms_scale_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (L==N)\n {\n *Y = b0 * *X * *X;\n ++X; ++Y;\n for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient\n Y -= tranz;\n if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_s: problem with LAPACKE function\\n\"); }\n rms = sqrtf(*Y);\n scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f;\n rms = sqrtf(*(Y+rms_p));\n scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f;\n scale = (scale0u; --l) { *--X *= scale; }\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/L, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, X+=L)\n {\n *Y = b0 * *X * *X;\n ++X; ++Y;\n for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient\n Y -= tranz;\n if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_s: problem with LAPACKE function\\n\"); }\n rms = sqrtf(*Y);\n scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f;\n rms = sqrtf(*(Y+rms_p));\n scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f;\n scale = (scale0u; --l) { *--X *= scale; }\n }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B*(L-1u))\n {\n for (size_t b=B; b>0u; --b, ++X)\n {\n *Y = b0 * *X * *X;\n X+=K; ++Y;\n for (size_t l=L-1u; l>0u; --l, X+=K, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0f; } //in case transient\n Y -= tranz;\n if (LAPACKE_slasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_s: problem with LAPACKE function\\n\"); }\n rms = sqrtf(*Y);\n scalemx = (rms>FLT_EPSILON) ? max_RMS/rms : 1.0f;\n rms = sqrtf(*(Y+rms_p));\n scale = (rms>FLT_EPSILON) ? target_RMS/rms : 1.0f;\n scale = (scale0u; --l) { X-=K; *X *= scale; }\n }\n }\n }\n }\n\n free(Y);\n }\n\n return 0;\n}\n\n\nint rms_scale_d (double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const double sr, const double tau, const double target_dB_SPL, const double max_dB_SPL)\n{\n if (dim>3u) { fprintf(stderr,\"error in rms_scale_d: dim must be in [0 3]\\n\"); return 1; }\n if (sr<=0.0) { fprintf(stderr,\"error in rms_scale_d: sr (sample rate) must be positive\\n\"); return 1; }\n if (tau<=0.0) { fprintf(stderr,\"error in rms_scale_d: tau (time constant) must be positive\\n\"); return 1; }\n\n const size_t N = R*C*S*H;\n const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n if (N<2u || L<2u) {}\n else\n {\n const double rms_prctile = 0.9;\n const double target_RMS = 20e-6 * pow(10.0, target_dB_SPL/20.0);\n const double max_RMS = 20e-6 * pow(10.0, max_dB_SPL/20.0);\n const double a1 = exp(-1.0/(sr*tau));\n const double b0 = 1.0 - a1;\n const size_t tranz = (L>5u) ? 5u : 0u; //nsamps to zero in case transient\n const size_t rms_p = (size_t)round((1.0-rms_prctile)*(double)L); //index for rms_prctile\n double rms, scale, scalemx;\n \n double *Y;\n if (!(Y=(double *)malloc(L*sizeof(double)))) { fprintf(stderr,\"error in rms_scale_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (L==N)\n {\n *Y = b0 * *X * *X;\n ++X; ++Y;\n for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient\n Y -= tranz;\n if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_d: problem with LAPACKE function\\n\"); }\n rms = sqrt(*Y);\n scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0;\n rms = sqrt(*(Y+rms_p));\n scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0;\n scale = (scale0u; --l) { *--X *= scale; }\n }\n else\n {\n const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n const size_t B = (iscolmajor && dim==0u) ? C*S*H : K;\n const size_t V = N/L, G = V/B;\n\n if (K==1u && (G==1u || B==1u))\n {\n for (size_t v=V; v>0u; --v, X+=L)\n {\n *Y = b0 * *X * *X;\n ++X; ++Y;\n for (size_t l=L-1u; l>0u; --l, ++X, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient\n Y -= tranz;\n if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_d: problem with LAPACKE function\\n\"); }\n rms = sqrt(*Y);\n scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0;\n rms = sqrt(*(Y+rms_p));\n scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0;\n scale = (scale0u; --l) { *--X *= scale; }\n }\n }\n else\n {\n for (size_t g=G; g>0u; --g, X+=B*(L-1u))\n {\n for (size_t b=B; b>0u; --b, ++X)\n {\n *Y = b0 * *X * *X;\n X+=K; ++Y;\n for (size_t l=L-1u; l>0u; --l, X+=K, ++Y) { *Y = b0**X**X + a1**(Y-1); }\n Y -= L;\n for (size_t l=tranz; l>0u; --l, ++Y) { *Y = 0.0; } //in case transient\n Y -= tranz;\n if (LAPACKE_dlasrt_work('D',(int)L,Y)) { fprintf(stderr,\"error in rms_scale_d: problem with LAPACKE function\\n\"); }\n rms = sqrt(*Y);\n scalemx = (rms>DBL_EPSILON) ? max_RMS/rms : 1.0;\n rms = sqrt(*(Y+rms_p));\n scale = (rms>DBL_EPSILON) ? target_RMS/rms : 1.0;\n scale = (scale0u; --l) { X-=K; *X *= scale; }\n }\n }\n }\n }\n\n free(Y);\n }\n\n return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "684e7f30350a9ed18b2a14755d7c1b24505b59aa", "size": 9670, "ext": "c", "lang": "C", "max_stars_repo_path": "c/rms_scale.c", "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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": "c/rms_scale.c", "max_issues_repo_name": "erikedwards4/aud", "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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/rms_scale.c", "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "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": 44.976744186, "max_line_length": 220, "alphanum_fraction": 0.4607032058, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.47231249406617226}} {"text": "#ifndef _EM_DEFS_H_\n#define _EM_DEFS_H_ 1\n\n#include \n\n#include \n#include \n\n#include \n#include \n\ntypedef std::complex Complex;\n\ntypedef std::tuple TupleII;\n\nconst double PI = 3.14159265358979323846;\nconst double MU = 4 * PI * 1E-7;\nconst Complex II = Complex(0.0, 1.0);\n\nconst double RTOD = 180.0 / PI;\nconst double DTOR = PI / 180.0;\n\nconst double EPS = 1.0E-6;\n\nconst int TX_SIZE = 7;\n\ntypedef Eigen::Vector3d Point;\ntypedef Eigen::Vector3d VectorD;\ntypedef Eigen::Vector3cd VectorZ;\n\ntypedef Eigen::Matrix3d Tensor;\n\nstruct PETScBlockVector {\n Vec re, im;\n};\n\nenum AnisotropicForm { Isotropic = 0, Vertical = 1, Triaxial = 2, Arbitrary = 3 };\n\nenum PolarType { XY_POLAR = -1, YX_POLAR = -2};\n\nenum RefineStrategy { FixedNumber = 0, FixedFraction = 1 };\n\nenum InnerPCType { Mixed = 0, AMS = 1, Direct = 2 };\n\nenum DirectSolverType { MUMPS = 0, SUPERLUDIST = 1 };\n\nenum ObsType {\n F_EX_RI = 111,\n F_EY_RI = 121,\n F_EZ_RI = 131,\n F_HX_RI = 141,\n F_HY_RI = 151,\n F_HZ_RI = 161,\n F_EX_AP = 112,\n F_EY_AP = 122,\n F_EZ_AP = 132,\n F_HX_AP = 142,\n F_HY_AP = 152,\n F_HZ_AP = 162,\n R_XY_AP = 212,\n R_YX_AP = 222,\n Z_XX_RI = 311,\n Z_XY_RI = 321,\n Z_YX_RI = 331,\n Z_YY_RI = 341,\n T_ZX_RI = 351,\n T_ZY_RI = 361,\n Z_XX_AP = 312,\n Z_XY_AP = 322,\n Z_YX_AP = 332,\n Z_YY_AP = 342\n};\n\n#define EM_ERR_USER -1\n\n#endif\n", "meta": {"hexsha": "d12ac0a5dbb900d85d0e4117bad1e59777a29a77", "size": 1391, "ext": "h", "lang": "C", "max_stars_repo_path": "src/em_defs.h", "max_stars_repo_name": "emfem/emfem", "max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z", "max_issues_repo_path": "src/em_defs.h", "max_issues_repo_name": "emfem/emfem", "max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "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/em_defs.h", "max_forks_repo_name": "emfem/emfem", "max_forks_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502", "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.0649350649, "max_line_length": 82, "alphanum_fraction": 0.6685837527, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.47189120078311325}} {"text": "/* linalg/lu.c\n * \n * Copyright (C) 2020 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic int LU_band_decomp_L2 (const size_t M, const size_t lb, const size_t ub,\n gsl_matrix * AB, gsl_vector_uint * ipiv);\n\n/* Factorise a (p,q) banded M x N matrix A into,\n *\n * P A = L U\n *\n * where P is a permutation matrix, L is unit lower triangular and U\n * is upper triangular.\n *\n * L is stored in the strict lower triangular part of the input\n * matrix. The diagonal elements of L are unity and are not stored.\n *\n * U is stored in the diagonal and upper triangular part of the\n * input matrix. \n * \n * P is stored in the permutation p. Column j of P is column k of the\n * identity matrix, where k = permutation->data[j]\n *\n * Inputs: M - number of rows in matrix\n * lb - lower bandwidth\n * ub - upper bandwidth\n * AB - matrix in band storage format, N-by-(2*p + q + 1)\n * piv - pivot vector, size MIN(M, N)\n */\n\nint\ngsl_linalg_LU_band_decomp (const size_t M, const size_t lb, const size_t ub, gsl_matrix * AB, gsl_vector_uint * piv)\n{\n const size_t N = AB->size1;\n const size_t minMN = GSL_MIN(M, N);\n\n if (lb >= M)\n {\n GSL_ERROR (\"lower bandwidth must be less than M\", GSL_EDOM);\n }\n else if (ub >= N)\n {\n GSL_ERROR (\"upper bandwidth must be less than N\", GSL_EDOM);\n }\n else if (AB->size2 != 2*lb + ub + 1)\n {\n GSL_ERROR (\"matrix size inconsistent with bandwidths\", GSL_EBADLEN);\n }\n else if (piv->size != minMN)\n {\n GSL_ERROR (\"pivot vector must have length MIN(M,N)\", GSL_EBADLEN);\n }\n else\n {\n int status;\n\n status = LU_band_decomp_L2 (M, lb, ub, AB, piv);\n\n return status;\n }\n}\n\nint\ngsl_linalg_LU_band_solve (const size_t lb, const size_t ub, const gsl_matrix * LUB,\n const gsl_vector_uint * piv, const gsl_vector * b, gsl_vector * x)\n{\n const size_t N = LUB->size1;\n\n if (N != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else if (N != b->size)\n {\n GSL_ERROR (\"matrix size must match rhs size\", GSL_EBADLEN);\n }\n else if (lb >= N)\n {\n GSL_ERROR (\"lower bandwidth must be less than N\", GSL_EDOM);\n }\n else if (ub >= N)\n {\n GSL_ERROR (\"upper bandwidth must be less than N\", GSL_EDOM);\n }\n else if (LUB->size2 != 2*lb + ub + 1)\n {\n GSL_ERROR (\"matrix size inconsistent with bandwidths\", GSL_EBADLEN);\n }\n else if (piv->size != N)\n {\n GSL_ERROR (\"pivot vector must have length N\", GSL_EBADLEN);\n }\n else\n {\n int status;\n\n gsl_vector_memcpy(x, b);\n\n status = gsl_linalg_LU_band_svx(lb, ub, LUB, piv, x);\n\n return status;\n }\n}\n\nint\ngsl_linalg_LU_band_svx (const size_t lb, const size_t ub, const gsl_matrix * LUB,\n const gsl_vector_uint * piv, gsl_vector * x)\n{\n const size_t N = LUB->size1;\n\n if (N != x->size)\n {\n GSL_ERROR (\"matrix size must match solution/rhs size\", GSL_EBADLEN);\n }\n else if (lb >= N)\n {\n GSL_ERROR (\"lower bandwidth must be less than N\", GSL_EDOM);\n }\n else if (ub >= N)\n {\n GSL_ERROR (\"upper bandwidth must be less than N\", GSL_EDOM);\n }\n else if (LUB->size2 != 2*lb + ub + 1)\n {\n GSL_ERROR (\"matrix size inconsistent with bandwidths\", GSL_EBADLEN);\n }\n else if (piv->size != N)\n {\n GSL_ERROR (\"pivot vector must have length N\", GSL_EBADLEN);\n }\n else\n {\n if (lb > 0)\n {\n size_t j;\n\n for (j = 0; j < N - 1; ++j)\n {\n size_t pj = gsl_vector_uint_get(piv, j);\n double * xj = gsl_vector_ptr(x, j);\n size_t lm = GSL_MIN(lb, N - j - 1);\n gsl_vector_view xv = gsl_vector_subvector(x, j + 1, lm);\n gsl_vector_const_view yv = gsl_matrix_const_subrow(LUB, j, lb + ub + 1, lm);\n\n if (j != pj)\n {\n double xl = gsl_vector_get(x, pj);\n gsl_vector_set(x, pj, *xj);\n *xj = xl;\n }\n\n gsl_blas_daxpy(-(*xj), &yv.vector, &xv.vector);\n }\n }\n\n /* solve U x = b */\n cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit,\n (int) N, (int) (lb + ub), LUB->data, LUB->tda,\n x->data, x->stride);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_LU_band_unpack (const size_t M, const size_t lb, const size_t ub, const gsl_matrix * LUB,\n const gsl_vector_uint * piv, gsl_matrix * L, gsl_matrix * U)\n{\n const size_t N = LUB->size1;\n const size_t minMN = GSL_MIN(M, N);\n\n if (ub >= N)\n {\n GSL_ERROR (\"upper bandwidth must be < N\", GSL_EDOM);\n }\n else if (lb >= M)\n {\n GSL_ERROR (\"lower bandwidth must be < M\", GSL_EDOM);\n }\n else if (LUB->size2 != 2*lb + ub + 1)\n {\n GSL_ERROR (\"matrix size inconsistent with bandwidths\", GSL_EBADLEN);\n }\n else if (piv->size != minMN)\n {\n GSL_ERROR (\"pivot vector must have length MIN(M,N)\", GSL_EBADLEN);\n }\n else if (L->size1 != M || L->size2 != minMN)\n {\n GSL_ERROR (\"L matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (U->size1 != minMN || U->size2 != N)\n {\n GSL_ERROR (\"U matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else\n {\n const size_t ub_U = lb + ub;\n size_t j;\n\n gsl_matrix_set_identity(L);\n gsl_matrix_set_zero(U);\n\n /* compute L */\n if (lb > 0)\n {\n const size_t jstart = (M > N) ? minMN : minMN - 1;\n size_t j;\n\n for (j = jstart; j > 0 && j--; )\n {\n size_t pj = gsl_vector_uint_get(piv, j);\n size_t lm = GSL_MIN(lb, M - j - 1);\n gsl_vector_const_view xv = gsl_matrix_const_subrow(LUB, j, lb + ub + 1, lm);\n gsl_vector_const_view yv = gsl_matrix_const_subrow(L, j, 0, minMN);\n gsl_matrix_view m = gsl_matrix_submatrix(L, j + 1, 0, lm, minMN);\n\n gsl_blas_dger(1.0, &xv.vector, &yv.vector, &m.matrix);\n\n if (j != pj)\n {\n gsl_vector_view Lj = gsl_matrix_row(L, j);\n gsl_vector_view Lpj = gsl_matrix_row(L, pj);\n gsl_blas_dswap(&Lj.vector, &Lpj.vector);\n }\n }\n }\n\n /* fill in U */\n for (j = 0; j <= GSL_MIN(ub_U, N - 1); ++j)\n {\n gsl_vector_const_view src = gsl_matrix_const_subcolumn(LUB, ub_U - j, j, GSL_MIN(M, N - j));\n gsl_vector_view dest = gsl_matrix_superdiagonal(U, j);\n gsl_vector_memcpy(&dest.vector, &src.vector);\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\nLU_band_decomp_L2\n LU decomposition with partial pivoting using Level 2 BLAS\n\nInputs: M - number of rows in matrix\n lb - lower bandwidth\n ub - upper bandwidth\n AB - on input, matrix to be factored; on output, L and U factors\n N-by-(2*p + q + 1)\n ipiv - (output) array containing row swaps\n\nNotes:\n1) Based on LAPACK DGBTF2\n*/\n\nstatic int\nLU_band_decomp_L2 (const size_t M, const size_t lb, const size_t ub,\n gsl_matrix * AB, gsl_vector_uint * ipiv)\n{\n const size_t N = AB->size1;\n const size_t minMN = GSL_MIN(M, N);\n\n if (ipiv->size != minMN)\n {\n GSL_ERROR (\"ipiv length must equal MIN(M,N)\", GSL_EBADLEN);\n }\n else if (lb >= M)\n {\n GSL_ERROR (\"lower bandwidth must be less than M\", GSL_EDOM);\n }\n else if (ub >= N)\n {\n GSL_ERROR (\"upper bandwidth must be less than N\", GSL_EDOM);\n }\n else if (AB->size2 != 2*lb + ub + 1)\n {\n GSL_ERROR (\"matrix size inconsistent with bandwidths\", GSL_EBADLEN);\n }\n else\n {\n const size_t ub_U = lb + ub; /* upper bandwidth of U factor */\n const size_t ldab = AB->size2;\n size_t ju = 0;\n size_t j;\n\n if (lb > 0)\n {\n /* initialize fill-in elements to zero */\n gsl_matrix_view m = gsl_matrix_submatrix(AB, 0, 0, N, lb);\n gsl_matrix_set_zero(&m.matrix);\n }\n \n for (j = 0; j < minMN; ++j)\n {\n size_t lbj = GSL_MIN(lb, M - j - 1); /* subdiagonal elements in column j */\n gsl_vector_view x = gsl_matrix_subrow(AB, j, ub_U, lbj + 1);\n gsl_vector_view y;\n CBLAS_INDEX_t j_pivot = gsl_blas_idamax(&x.vector);\n double * ptr;\n\n gsl_vector_uint_set(ipiv, j, j + j_pivot);\n\n ptr = gsl_matrix_ptr(AB, j, ub_U + j_pivot);\n if (*ptr != 0.0)\n ju = GSL_MAX(ju, GSL_MIN(j + ub + j_pivot, N - 1));\n\n if (j_pivot != 0)\n {\n double *ptr2;\n\n /* swap columns */\n\n x = gsl_vector_view_array_with_stride(ptr, ldab - 1, ju - j + 1);\n\n ptr2 = gsl_matrix_ptr(AB, j, ub_U);\n y = gsl_vector_view_array_with_stride(ptr2, ldab - 1, ju - j + 1);\n\n gsl_blas_dswap(&x.vector, &y.vector);\n }\n\n if (lbj > 0)\n {\n double tmp = gsl_matrix_get(AB, j, ub_U);\n\n x = gsl_matrix_subrow(AB, j, ub_U + 1, lbj);\n gsl_blas_dscal(1.0 / tmp, &x.vector);\n\n if (ju > j)\n {\n gsl_matrix_view m = gsl_matrix_submatrix(AB, j + 1, ub_U, ju - j, lbj);\n\n ptr = gsl_matrix_ptr(AB, j + 1, ub_U - 1);\n y = gsl_vector_view_array_with_stride(ptr, ldab - 1, ju - j);\n\n m.matrix.tda = ldab - 1; /* unskew matrix */\n gsl_blas_dger(-1.0, &y.vector, &x.vector, &m.matrix);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "02805b4987a343d038f39d62a3b4d6a68acb6ce9", "size": 10621, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/lu_band.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/lu_band.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/lu_band.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.783197832, "max_line_length": 116, "alphanum_fraction": 0.56134074, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.47178881326965877}} {"text": "/* eigen/nonsymmv.c\n * \n * Copyright (C) 2006 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module computes the eigenvalues and eigenvectors of a real\n * nonsymmetric matrix.\n * \n * This file contains routines based on original code from LAPACK\n * which is distributed under the modified BSD license. The LAPACK\n * routines used are DTREVC and DLALN2.\n */\n\n#define GSL_NONSYMMV_SMLNUM (2.0 * GSL_DBL_MIN)\n#define GSL_NONSYMMV_BIGNUM ((1.0 - GSL_DBL_EPSILON) / GSL_NONSYMMV_SMLNUM)\n\nstatic void nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,\n gsl_vector_complex *eval,\n gsl_matrix_complex *evec,\n gsl_eigen_nonsymmv_workspace *w);\nstatic void nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,\n gsl_matrix_complex *evec);\n\n/*\ngsl_eigen_nonsymmv_alloc()\n\nAllocate a workspace for solving the nonsymmetric eigenvalue problem.\nThe size of this workspace is O(5n).\n\nInputs: n - size of matrices\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_nonsymmv_workspace *\ngsl_eigen_nonsymmv_alloc(const size_t n)\n{\n gsl_eigen_nonsymmv_workspace *w;\n\n if (n == 0)\n {\n GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n GSL_EINVAL);\n }\n\n w = (gsl_eigen_nonsymmv_workspace *)\n calloc (1, sizeof (gsl_eigen_nonsymmv_workspace));\n\n if (w == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->size = n;\n w->Z = NULL;\n w->nonsymm_workspace_p = gsl_eigen_nonsymm_alloc(n);\n\n if (w->nonsymm_workspace_p == 0)\n {\n gsl_eigen_nonsymmv_free(w);\n GSL_ERROR_NULL (\"failed to allocate space for nonsymm workspace\", GSL_ENOMEM);\n }\n\n /*\n * set parameters to compute the full Schur form T and balance\n * the matrices\n */\n gsl_eigen_nonsymm_params(1, 1, w->nonsymm_workspace_p);\n\n w->work = gsl_vector_alloc(n);\n w->work2 = gsl_vector_alloc(n);\n w->work3 = gsl_vector_alloc(n);\n if (w->work == 0 || w->work2 == 0 || w->work3 == 0)\n {\n gsl_eigen_nonsymmv_free(w);\n GSL_ERROR_NULL (\"failed to allocate space for nonsymmv additional workspace\", GSL_ENOMEM);\n }\n\n return (w);\n} /* gsl_eigen_nonsymmv_alloc() */\n\n/*\ngsl_eigen_nonsymmv_free()\n Free workspace w\n*/\n\nvoid\ngsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w)\n{\n RETURN_IF_NULL (w);\n\n if (w->nonsymm_workspace_p)\n gsl_eigen_nonsymm_free(w->nonsymm_workspace_p);\n\n if (w->work)\n gsl_vector_free(w->work);\n\n if (w->work2)\n gsl_vector_free(w->work2);\n\n if (w->work3)\n gsl_vector_free(w->work3);\n\n free(w);\n} /* gsl_eigen_nonsymmv_free() */\n\n/*\ngsl_eigen_nonsymmv()\n\nSolve the nonsymmetric eigensystem problem\n\nA x = \\lambda x\n\nfor the eigenvalues \\lambda and right eigenvectors x\n\nInputs: A - general real matrix\n eval - where to store eigenvalues\n evec - where to store eigenvectors\n w - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix_complex * evec,\n gsl_eigen_nonsymmv_workspace * w)\n{\n const size_t N = A->size1;\n\n /* check matrix and vector sizes */\n\n if (N != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n }\n else if (eval->size != N)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (evec->size1 != N)\n {\n GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n }\n else\n {\n int s;\n gsl_matrix Z;\n\n /*\n * We need a place to store the Schur vectors, so we will\n * treat evec as a real matrix and store them in the left\n * half - the factor of 2 in the tda corresponds to the\n * complex multiplicity\n */\n Z.size1 = N;\n Z.size2 = N;\n Z.tda = 2 * N;\n Z.data = evec->data;\n Z.block = 0;\n Z.owner = 0;\n\n /* compute eigenvalues, Schur form, and Schur vectors */\n s = gsl_eigen_nonsymm_Z(A, eval, &Z, w->nonsymm_workspace_p);\n\n if (w->Z)\n {\n /*\n * save the Schur vectors in user supplied matrix, since\n * they will be destroyed when computing eigenvectors\n */\n gsl_matrix_memcpy(w->Z, &Z);\n }\n\n /* only compute eigenvectors if we found all eigenvalues */\n if (s == GSL_SUCCESS)\n {\n /* compute eigenvectors */\n nonsymmv_get_right_eigenvectors(A, &Z, eval, evec, w);\n\n /* normalize so that Euclidean norm is 1 */\n nonsymmv_normalize_eigenvectors(eval, evec);\n }\n\n return s;\n }\n} /* gsl_eigen_nonsymmv() */\n\n/*\ngsl_eigen_nonsymmv_Z()\n Compute eigenvalues and eigenvectors of a real nonsymmetric matrix\nand also save the Schur vectors. See comments in gsl_eigen_nonsymm_Z\nfor more information.\n\nInputs: A - real nonsymmetric matrix\n eval - where to store eigenvalues\n evec - where to store eigenvectors\n Z - where to store Schur vectors\n w - nonsymmv workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix_complex * evec, gsl_matrix * Z,\n gsl_eigen_nonsymmv_workspace * w)\n{\n /* check matrix and vector sizes */\n\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix must be square to compute eigenvalues/eigenvectors\", GSL_ENOTSQR);\n }\n else if (eval->size != A->size1)\n {\n GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n }\n else if (evec->size1 != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n }\n else if (evec->size1 != A->size1)\n {\n GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n }\n else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1))\n {\n GSL_ERROR (\"Z matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else\n {\n int s;\n\n w->Z = Z;\n\n s = gsl_eigen_nonsymmv(A, eval, evec, w);\n\n w->Z = NULL;\n\n return s;\n }\n} /* gsl_eigen_nonsymmv_Z() */\n\n/********************************************\n * INTERNAL ROUTINES *\n ********************************************/\n\n/*\nnonsymmv_get_right_eigenvectors()\n Compute the right eigenvectors of the Schur form T and then\nbacktransform them using the Schur vectors to get right eigenvectors of\nthe original matrix.\n\nInputs: T - Schur form\n Z - Schur vectors\n eval - where to store eigenvalues (to ensure that the\n correct eigenvalue is stored in the same position\n as the eigenvectors)\n evec - where to store eigenvectors\n w - nonsymmv workspace\n\nReturn: none\n\nNotes: 1) based on LAPACK routine DTREVC - the algorithm used is\n backsubstitution on the upper quasi triangular system T\n followed by backtransformation by Z to get vectors of the\n original matrix.\n\n 2) The Schur vectors in Z are destroyed and replaced with\n eigenvectors stored with the same storage scheme as DTREVC.\n The eigenvectors are also stored in 'evec'\n\n 3) The matrix T is unchanged on output\n\n 4) Each eigenvector is normalized so that the element of\n largest magnitude has magnitude 1; here the magnitude of\n a complex number (x,y) is taken to be |x| + |y|\n*/\n\nstatic void\nnonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,\n gsl_vector_complex *eval,\n gsl_matrix_complex *evec,\n gsl_eigen_nonsymmv_workspace *w)\n{\n const size_t N = T->size1;\n const double smlnum = GSL_DBL_MIN * N / GSL_DBL_EPSILON;\n const double bignum = (1.0 - GSL_DBL_EPSILON) / smlnum;\n int i; /* looping */\n size_t iu, /* looping */\n ju,\n ii;\n gsl_complex lambda; /* current eigenvalue */\n double lambda_re, /* Re(lambda) */\n lambda_im; /* Im(lambda) */\n gsl_matrix_view Tv, /* temporary views */\n Zv;\n gsl_vector_view y, /* temporary views */\n y2,\n ev,\n ev2;\n double dat[4], /* scratch arrays */\n dat_X[4];\n double scale; /* scale factor */\n double xnorm; /* |X| */\n gsl_vector_complex_view ecol, /* column of evec */\n ecol2;\n int complex_pair; /* complex eigenvalue pair? */\n double smin;\n\n /*\n * Compute 1-norm of each column of upper triangular part of T\n * to control overflow in triangular solver\n */\n\n gsl_vector_set(w->work3, 0, 0.0);\n for (ju = 1; ju < N; ++ju)\n {\n gsl_vector_set(w->work3, ju, 0.0);\n for (iu = 0; iu < ju; ++iu)\n {\n gsl_vector_set(w->work3, ju,\n gsl_vector_get(w->work3, ju) +\n fabs(gsl_matrix_get(T, iu, ju)));\n }\n }\n\n for (i = (int) N - 1; i >= 0; --i)\n {\n iu = (size_t) i;\n\n /* get current eigenvalue and store it in lambda */\n lambda_re = gsl_matrix_get(T, iu, iu);\n\n if (iu != 0 && gsl_matrix_get(T, iu, iu - 1) != 0.0)\n {\n lambda_im = sqrt(fabs(gsl_matrix_get(T, iu, iu - 1))) *\n sqrt(fabs(gsl_matrix_get(T, iu - 1, iu)));\n }\n else\n {\n lambda_im = 0.0;\n }\n\n GSL_SET_COMPLEX(&lambda, lambda_re, lambda_im);\n\n smin = GSL_MAX(GSL_DBL_EPSILON * (fabs(lambda_re) + fabs(lambda_im)),\n smlnum);\n smin = GSL_MAX(smin, GSL_NONSYMMV_SMLNUM);\n\n if (lambda_im == 0.0)\n {\n int k, l;\n gsl_vector_view bv, xv;\n\n /* real eigenvector */\n\n /*\n * The ordering of eigenvalues in 'eval' is arbitrary and\n * does not necessarily follow the Schur form T, so store\n * lambda in the right slot in eval to ensure it corresponds\n * to the eigenvector we are about to compute\n */\n gsl_vector_complex_set(eval, iu, lambda);\n\n /*\n * We need to solve the system:\n *\n * (T(1:iu-1, 1:iu-1) - lambda*I)*X = -T(1:iu-1,iu)\n */\n\n /* construct right hand side */\n for (k = 0; k < i; ++k)\n {\n gsl_vector_set(w->work,\n (size_t) k,\n -gsl_matrix_get(T, (size_t) k, iu));\n }\n\n gsl_vector_set(w->work, iu, 1.0);\n\n for (l = i - 1; l >= 0; --l)\n {\n size_t lu = (size_t) l;\n\n if (lu == 0)\n complex_pair = 0;\n else\n complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;\n\n if (!complex_pair)\n {\n double x;\n\n /*\n * 1-by-1 diagonal block - solve the system:\n *\n * (T_{ll} - lambda)*x = -T_{l(iu)}\n */\n\n Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);\n bv = gsl_vector_view_array(dat, 1);\n gsl_vector_set(&bv.vector, 0,\n gsl_vector_get(w->work, lu));\n xv = gsl_vector_view_array(dat_X, 1);\n\n gsl_schur_solve_equation(1.0,\n &Tv.matrix,\n lambda_re,\n 1.0,\n 1.0,\n &bv.vector,\n &xv.vector,\n &scale,\n &xnorm,\n smin);\n\n /* scale x to avoid overflow */\n x = gsl_vector_get(&xv.vector, 0);\n if (xnorm > 1.0)\n {\n if (gsl_vector_get(w->work3, lu) > bignum / xnorm)\n {\n x /= xnorm;\n scale /= xnorm;\n }\n }\n\n if (scale != 1.0)\n {\n gsl_vector_view wv;\n\n wv = gsl_vector_subvector(w->work, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n }\n\n gsl_vector_set(w->work, lu, x);\n\n if (lu > 0)\n {\n gsl_vector_view v1, v2;\n\n /* update right hand side */\n\n v1 = gsl_matrix_subcolumn(T, lu, 0, lu);\n v2 = gsl_vector_subvector(w->work, 0, lu);\n gsl_blas_daxpy(-x, &v1.vector, &v2.vector);\n } /* if (l > 0) */\n } /* if (!complex_pair) */\n else\n {\n double x11, x21;\n\n /*\n * 2-by-2 diagonal block\n */\n\n Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);\n bv = gsl_vector_view_array(dat, 2);\n gsl_vector_set(&bv.vector, 0,\n gsl_vector_get(w->work, lu - 1));\n gsl_vector_set(&bv.vector, 1,\n gsl_vector_get(w->work, lu));\n xv = gsl_vector_view_array(dat_X, 2);\n\n gsl_schur_solve_equation(1.0,\n &Tv.matrix,\n lambda_re,\n 1.0,\n 1.0,\n &bv.vector,\n &xv.vector,\n &scale,\n &xnorm,\n smin);\n\n /* scale X(1,1) and X(2,1) to avoid overflow */\n x11 = gsl_vector_get(&xv.vector, 0);\n x21 = gsl_vector_get(&xv.vector, 1);\n\n if (xnorm > 1.0)\n {\n double beta;\n\n beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),\n gsl_vector_get(w->work3, lu));\n if (beta > bignum / xnorm)\n {\n x11 /= xnorm;\n x21 /= xnorm;\n scale /= xnorm;\n }\n }\n\n /* scale if necessary */\n if (scale != 1.0)\n {\n gsl_vector_view wv;\n\n wv = gsl_vector_subvector(w->work, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n }\n\n gsl_vector_set(w->work, lu - 1, x11);\n gsl_vector_set(w->work, lu, x21);\n\n /* update right hand side */\n if (lu > 1)\n {\n gsl_vector_view v1, v2;\n\n v1 = gsl_matrix_subcolumn(T, lu - 1, 0, lu - 1);\n v2 = gsl_vector_subvector(w->work, 0, lu - 1);\n gsl_blas_daxpy(-x11, &v1.vector, &v2.vector);\n\n v1 = gsl_matrix_subcolumn(T, lu, 0, lu - 1);\n gsl_blas_daxpy(-x21, &v1.vector, &v2.vector);\n }\n\n --l;\n } /* if (complex_pair) */\n } /* for (l = i - 1; l >= 0; --l) */\n\n /*\n * At this point, w->work is an eigenvector of the\n * Schur form T. To get an eigenvector of the original\n * matrix, we multiply on the left by Z, the matrix of\n * Schur vectors\n */\n\n ecol = gsl_matrix_complex_column(evec, iu);\n y = gsl_matrix_column(Z, iu);\n\n if (iu > 0)\n {\n gsl_vector_view x;\n\n Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu);\n\n x = gsl_vector_subvector(w->work, 0, iu);\n\n /* compute Z * w->work and store it in Z(:,iu) */\n gsl_blas_dgemv(CblasNoTrans,\n 1.0,\n &Zv.matrix,\n &x.vector,\n gsl_vector_get(w->work, iu),\n &y.vector);\n } /* if (iu > 0) */\n\n /* store eigenvector into evec */\n\n ev = gsl_vector_complex_real(&ecol.vector);\n ev2 = gsl_vector_complex_imag(&ecol.vector);\n\n scale = 0.0;\n for (ii = 0; ii < N; ++ii)\n {\n double a = gsl_vector_get(&y.vector, ii);\n\n /* store real part of eigenvector */\n gsl_vector_set(&ev.vector, ii, a);\n\n /* set imaginary part to 0 */\n gsl_vector_set(&ev2.vector, ii, 0.0);\n\n if (fabs(a) > scale)\n scale = fabs(a);\n }\n\n if (scale != 0.0)\n scale = 1.0 / scale;\n\n /* scale by magnitude of largest element */\n gsl_blas_dscal(scale, &ev.vector);\n } /* if (GSL_IMAG(lambda) == 0.0) */\n else\n {\n gsl_vector_complex_view bv, xv;\n size_t k;\n int l;\n gsl_complex lambda2;\n\n /* complex eigenvector */\n\n /*\n * Store the complex conjugate eigenvalues in the right\n * slots in eval\n */\n GSL_SET_REAL(&lambda2, GSL_REAL(lambda));\n GSL_SET_IMAG(&lambda2, -GSL_IMAG(lambda));\n gsl_vector_complex_set(eval, iu - 1, lambda);\n gsl_vector_complex_set(eval, iu, lambda2);\n\n /*\n * First solve:\n *\n * [ T(i:i+1,i:i+1) - lambda*I ] * X = 0\n */\n\n if (fabs(gsl_matrix_get(T, iu - 1, iu)) >=\n fabs(gsl_matrix_get(T, iu, iu - 1)))\n {\n gsl_vector_set(w->work, iu - 1, 1.0);\n gsl_vector_set(w->work2, iu,\n lambda_im / gsl_matrix_get(T, iu - 1, iu));\n }\n else\n {\n gsl_vector_set(w->work, iu - 1,\n -lambda_im / gsl_matrix_get(T, iu, iu - 1));\n gsl_vector_set(w->work2, iu, 1.0);\n }\n gsl_vector_set(w->work, iu, 0.0);\n gsl_vector_set(w->work2, iu - 1, 0.0);\n\n /* construct right hand side */\n for (k = 0; k < iu - 1; ++k)\n {\n gsl_vector_set(w->work, k,\n -gsl_vector_get(w->work, iu - 1) *\n gsl_matrix_get(T, k, iu - 1));\n gsl_vector_set(w->work2, k,\n -gsl_vector_get(w->work2, iu) *\n gsl_matrix_get(T, k, iu));\n }\n\n /*\n * We must solve the upper quasi-triangular system:\n *\n * [ T(1:i-2,1:i-2) - lambda*I ] * X = s*(work + i*work2)\n */\n\n for (l = i - 2; l >= 0; --l)\n {\n size_t lu = (size_t) l;\n\n if (lu == 0)\n complex_pair = 0;\n else\n complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;\n\n if (!complex_pair)\n {\n gsl_complex bval;\n gsl_complex x;\n\n /*\n * 1-by-1 diagonal block - solve the system:\n *\n * (T_{ll} - lambda)*x = work + i*work2\n */\n\n Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);\n bv = gsl_vector_complex_view_array(dat, 1);\n xv = gsl_vector_complex_view_array(dat_X, 1);\n\n GSL_SET_COMPLEX(&bval,\n gsl_vector_get(w->work, lu),\n gsl_vector_get(w->work2, lu));\n gsl_vector_complex_set(&bv.vector, 0, bval);\n\n gsl_schur_solve_equation_z(1.0,\n &Tv.matrix,\n &lambda,\n 1.0,\n 1.0,\n &bv.vector,\n &xv.vector,\n &scale,\n &xnorm,\n smin);\n\n if (xnorm > 1.0)\n {\n if (gsl_vector_get(w->work3, lu) > bignum / xnorm)\n {\n gsl_blas_zdscal(1.0/xnorm, &xv.vector);\n scale /= xnorm;\n }\n }\n\n /* scale if necessary */\n if (scale != 1.0)\n {\n gsl_vector_view wv;\n\n wv = gsl_vector_subvector(w->work, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n wv = gsl_vector_subvector(w->work2, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n }\n\n x = gsl_vector_complex_get(&xv.vector, 0);\n gsl_vector_set(w->work, lu, GSL_REAL(x));\n gsl_vector_set(w->work2, lu, GSL_IMAG(x));\n\n /* update the right hand side */\n if (lu > 0)\n {\n gsl_vector_view v1, v2;\n\n v1 = gsl_matrix_subcolumn(T, lu, 0, lu);\n v2 = gsl_vector_subvector(w->work, 0, lu);\n gsl_blas_daxpy(-GSL_REAL(x), &v1.vector, &v2.vector);\n\n v2 = gsl_vector_subvector(w->work2, 0, lu);\n gsl_blas_daxpy(-GSL_IMAG(x), &v1.vector, &v2.vector);\n } /* if (lu > 0) */\n } /* if (!complex_pair) */\n else\n {\n gsl_complex b1, b2, x1, x2;\n\n /*\n * 2-by-2 diagonal block - solve the system\n */\n\n Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);\n bv = gsl_vector_complex_view_array(dat, 2);\n xv = gsl_vector_complex_view_array(dat_X, 2);\n\n GSL_SET_COMPLEX(&b1,\n gsl_vector_get(w->work, lu - 1),\n gsl_vector_get(w->work2, lu - 1));\n GSL_SET_COMPLEX(&b2,\n gsl_vector_get(w->work, lu),\n gsl_vector_get(w->work2, lu));\n gsl_vector_complex_set(&bv.vector, 0, b1);\n gsl_vector_complex_set(&bv.vector, 1, b2);\n\n gsl_schur_solve_equation_z(1.0,\n &Tv.matrix,\n &lambda,\n 1.0,\n 1.0,\n &bv.vector,\n &xv.vector,\n &scale,\n &xnorm,\n smin);\n\n x1 = gsl_vector_complex_get(&xv.vector, 0);\n x2 = gsl_vector_complex_get(&xv.vector, 1);\n\n if (xnorm > 1.0)\n {\n double beta;\n\n beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),\n gsl_vector_get(w->work3, lu));\n if (beta > bignum / xnorm)\n {\n gsl_blas_zdscal(1.0/xnorm, &xv.vector);\n scale /= xnorm;\n }\n }\n\n /* scale if necessary */\n if (scale != 1.0)\n {\n gsl_vector_view wv;\n\n wv = gsl_vector_subvector(w->work, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n wv = gsl_vector_subvector(w->work2, 0, iu + 1);\n gsl_blas_dscal(scale, &wv.vector);\n }\n gsl_vector_set(w->work, lu - 1, GSL_REAL(x1));\n gsl_vector_set(w->work, lu, GSL_REAL(x2));\n gsl_vector_set(w->work2, lu - 1, GSL_IMAG(x1));\n gsl_vector_set(w->work2, lu, GSL_IMAG(x2));\n\n /* update right hand side */\n if (lu > 1)\n {\n gsl_vector_view v1, v2, v3, v4;\n\n v1 = gsl_matrix_subcolumn(T, lu - 1, 0, lu - 1);\n v4 = gsl_matrix_subcolumn(T, lu, 0, lu - 1);\n v2 = gsl_vector_subvector(w->work, 0, lu - 1);\n v3 = gsl_vector_subvector(w->work2, 0, lu - 1);\n\n gsl_blas_daxpy(-GSL_REAL(x1), &v1.vector, &v2.vector);\n gsl_blas_daxpy(-GSL_REAL(x2), &v4.vector, &v2.vector);\n gsl_blas_daxpy(-GSL_IMAG(x1), &v1.vector, &v3.vector);\n gsl_blas_daxpy(-GSL_IMAG(x2), &v4.vector, &v3.vector);\n } /* if (lu > 1) */\n\n --l;\n } /* if (complex_pair) */\n } /* for (l = i - 2; l >= 0; --l) */\n\n /*\n * At this point, work + i*work2 is an eigenvector\n * of T - backtransform to get an eigenvector of the\n * original matrix\n */\n\n y = gsl_matrix_column(Z, iu - 1);\n y2 = gsl_matrix_column(Z, iu);\n\n if (iu > 1)\n {\n gsl_vector_view x;\n\n /* compute real part of eigenvectors */\n\n Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu - 1);\n x = gsl_vector_subvector(w->work, 0, iu - 1);\n\n gsl_blas_dgemv(CblasNoTrans,\n 1.0,\n &Zv.matrix,\n &x.vector,\n gsl_vector_get(w->work, iu - 1),\n &y.vector);\n\n\n /* now compute the imaginary part */\n x = gsl_vector_subvector(w->work2, 0, iu - 1);\n\n gsl_blas_dgemv(CblasNoTrans,\n 1.0,\n &Zv.matrix,\n &x.vector,\n gsl_vector_get(w->work2, iu),\n &y2.vector);\n }\n else\n {\n gsl_blas_dscal(gsl_vector_get(w->work, iu - 1), &y.vector);\n gsl_blas_dscal(gsl_vector_get(w->work2, iu), &y2.vector);\n }\n\n /*\n * Now store the eigenvectors into evec - the real parts\n * are Z(:,iu - 1) and the imaginary parts are\n * +/- Z(:,iu)\n */\n\n /* get views of the two eigenvector slots */\n ecol = gsl_matrix_complex_column(evec, iu - 1);\n ecol2 = gsl_matrix_complex_column(evec, iu);\n\n /*\n * save imaginary part first as it may get overwritten\n * when copying the real part due to our storage scheme\n * in Z/evec\n */\n ev = gsl_vector_complex_imag(&ecol.vector);\n ev2 = gsl_vector_complex_imag(&ecol2.vector);\n scale = 0.0;\n for (ii = 0; ii < N; ++ii)\n {\n double a = gsl_vector_get(&y2.vector, ii);\n\n scale = GSL_MAX(scale,\n fabs(a) + fabs(gsl_vector_get(&y.vector, ii)));\n\n gsl_vector_set(&ev.vector, ii, a);\n gsl_vector_set(&ev2.vector, ii, -a);\n }\n\n /* now save the real part */\n ev = gsl_vector_complex_real(&ecol.vector);\n ev2 = gsl_vector_complex_real(&ecol2.vector);\n for (ii = 0; ii < N; ++ii)\n {\n double a = gsl_vector_get(&y.vector, ii);\n\n gsl_vector_set(&ev.vector, ii, a);\n gsl_vector_set(&ev2.vector, ii, a);\n }\n\n if (scale != 0.0)\n scale = 1.0 / scale;\n\n /* scale by largest element magnitude */\n\n gsl_blas_zdscal(scale, &ecol.vector);\n gsl_blas_zdscal(scale, &ecol2.vector);\n\n /*\n * decrement i since we took care of two eigenvalues at\n * the same time\n */\n --i;\n } /* if (GSL_IMAG(lambda) != 0.0) */\n } /* for (i = (int) N - 1; i >= 0; --i) */\n} /* nonsymmv_get_right_eigenvectors() */\n\n/*\nnonsymmv_normalize_eigenvectors()\n Normalize eigenvectors so that their Euclidean norm is 1\n\nInputs: eval - eigenvalues\n evec - eigenvectors\n*/\n\nstatic void\nnonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,\n gsl_matrix_complex *evec)\n{\n const size_t N = evec->size1;\n size_t i; /* looping */\n gsl_complex ei;\n gsl_vector_complex_view vi;\n gsl_vector_view re, im;\n double scale; /* scaling factor */\n\n for (i = 0; i < N; ++i)\n {\n ei = gsl_vector_complex_get(eval, i);\n vi = gsl_matrix_complex_column(evec, i);\n\n re = gsl_vector_complex_real(&vi.vector);\n\n if (GSL_IMAG(ei) == 0.0)\n {\n scale = 1.0 / gsl_blas_dnrm2(&re.vector);\n gsl_blas_dscal(scale, &re.vector);\n }\n else if (GSL_IMAG(ei) > 0.0)\n {\n im = gsl_vector_complex_imag(&vi.vector);\n\n scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector),\n gsl_blas_dnrm2(&im.vector));\n gsl_blas_zdscal(scale, &vi.vector);\n\n vi = gsl_matrix_complex_column(evec, i + 1);\n gsl_blas_zdscal(scale, &vi.vector);\n }\n }\n} /* nonsymmv_normalize_eigenvectors() */\n", "meta": {"hexsha": "9a87a74a0a6262bfc3c5da1f0f9ffa3a37d3b8a0", "size": 31430, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/eigen/nonsymmv.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/eigen/nonsymmv.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/eigen/nonsymmv.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": 32.3353909465, "max_line_length": 96, "alphanum_fraction": 0.4636971047, "num_tokens": 7689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.47169617753214255}} {"text": "/* histogram/pdf2d.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#include \n\n#include \"find.c\"\n\nint\ngsl_histogram2d_pdf_sample (const gsl_histogram2d_pdf * p,\n double r1, double r2,\n double *x, double *y)\n{\n size_t k;\n int status;\n\n/* Wrap the exclusive top of the bin down to the inclusive bottom of\n the bin. Since this is a single point it should not affect the\n distribution. */\n\n if (r2 == 1.0)\n {\n r2 = 0.0;\n }\n if (r1 == 1.0)\n {\n r1 = 0.0;\n }\n\n status = find (p->nx * p->ny, p->sum, r1, &k);\n\n if (status)\n {\n GSL_ERROR (\"cannot find r1 in cumulative pdf\", GSL_EDOM);\n }\n else\n {\n size_t i = k / p->ny;\n size_t j = k - (i * p->ny);\n double delta = (r1 - p->sum[k]) / (p->sum[k + 1] - p->sum[k]);\n *x = p->xrange[i] + delta * (p->xrange[i + 1] - p->xrange[i]);\n *y = p->yrange[j] + r2 * (p->yrange[j + 1] - p->yrange[j]);\n return GSL_SUCCESS;\n }\n}\n\ngsl_histogram2d_pdf *\ngsl_histogram2d_pdf_alloc (const size_t nx, const size_t ny)\n{\n const size_t n = nx * ny;\n\n gsl_histogram2d_pdf *p;\n\n if (n == 0)\n {\n GSL_ERROR_VAL (\"histogram2d pdf length n must be positive integer\",\n GSL_EDOM, 0);\n }\n\n p = (gsl_histogram2d_pdf *) malloc (sizeof (gsl_histogram2d_pdf));\n\n if (p == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for histogram2d pdf struct\",\n GSL_ENOMEM, 0);\n }\n\n p->xrange = (double *) malloc ((nx + 1) * sizeof (double));\n\n if (p->xrange == 0)\n {\n free (p); /* exception in constructor, avoid memory leak */\n\n GSL_ERROR_VAL (\"failed to allocate space for histogram2d pdf xranges\",\n GSL_ENOMEM, 0);\n }\n\n p->yrange = (double *) malloc ((ny + 1) * sizeof (double));\n\n if (p->yrange == 0)\n {\n free (p->xrange);\n free (p); /* exception in constructor, avoid memory leak */\n\n GSL_ERROR_VAL (\"failed to allocate space for histogram2d pdf yranges\",\n GSL_ENOMEM, 0);\n }\n\n p->sum = (double *) malloc ((n + 1) * sizeof (double));\n\n if (p->sum == 0)\n {\n free (p->yrange);\n free (p->xrange);\n free (p); /* exception in constructor, avoid memory leak */\n\n GSL_ERROR_VAL (\"failed to allocate space for histogram2d pdf sums\",\n GSL_ENOMEM, 0);\n }\n\n p->nx = nx;\n p->ny = ny;\n\n return p;\n}\n\nint\ngsl_histogram2d_pdf_init (gsl_histogram2d_pdf * p, const gsl_histogram2d * h)\n{\n size_t i;\n const size_t nx = p->nx;\n const size_t ny = p->ny;\n const size_t n = nx * ny;\n\n if (nx != h->nx || ny != h->ny)\n {\n GSL_ERROR (\"histogram2d size must match pdf size\", GSL_EDOM);\n }\n\n for (i = 0; i < n; i++)\n {\n if (h->bin[i] < 0)\n {\n GSL_ERROR (\"histogram bins must be non-negative to compute\"\n \"a probability distribution\", GSL_EDOM);\n }\n }\n\n for (i = 0; i < nx + 1; i++)\n {\n p->xrange[i] = h->xrange[i];\n }\n\n for (i = 0; i < ny + 1; i++)\n {\n p->yrange[i] = h->yrange[i];\n }\n\n {\n double mean = 0, sum = 0;\n\n for (i = 0; i < n; i++)\n {\n mean += (h->bin[i] - mean) / ((double) (i + 1));\n }\n\n p->sum[0] = 0;\n\n for (i = 0; i < n; i++)\n {\n sum += (h->bin[i] / mean) / n;\n p->sum[i + 1] = sum;\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\nvoid\ngsl_histogram2d_pdf_free (gsl_histogram2d_pdf * p)\n{\n RETURN_IF_NULL (p);\n free (p->xrange);\n free (p->yrange);\n free (p->sum);\n free (p);\n}\n", "meta": {"hexsha": "07cc24d615fead5e7cd508126da61ca0bbdefcea", "size": 4456, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/pdf2d.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/pdf2d.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/pdf2d.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.7021276596, "max_line_length": 81, "alphanum_fraction": 0.5576750449, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.4715138648025148}} {"text": "/// \\file energy.c\n/// \\brief Sort and fill energy levels to obtain occupancy of each level.\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 \"energy.h\"\n#include \n#include \n#include \n#include \n\n\n\n/// \\brief Allocate memory for energy levels structure\nvoid AllocateEnergyLevels(const int m_max, const int num, en_levels_t *levels)\n{\n\tlevels->m_max = m_max;\n\tlevels->num = num;\n\n\tlevels->en = malloc((m_max+1)*num * sizeof(double));\n}\n\n\n/// \\brief Free memory of energy levels structure\nvoid FreeEnergyLevels(en_levels_t *levels)\n{\n\tfree(levels->en);\n\n\tlevels->num = 0;\n\tlevels->m_max = 0;\n}\n\n\n//_______________________________________________________________________________________________________________________\n//\n\n\n/// \\brief Comparison function used for sorting\nstatic int en_occupancy_cmp(const void *e1, const void *e2)\n{\n\tconst en_occupancy_t *a = (en_occupancy_t *)e1;\n\tconst en_occupancy_t *b = (en_occupancy_t *)e2;\n\n\t// sort according to energy\n\tif (a->en < b->en)\n\t{\n\t\treturn -1;\n\t}\n\telse if (a->en > b->en)\n\t{\n\t\treturn 1;\n\t}\n\n\t// should actually never reach this point\n\n\t// compare 'm' quantum numbers\n\tif (a->m < b->m)\n\t{\n\t\treturn -1;\n\t}\n\telse if (a->m > b->m)\n\t{\n\t\treturn 1;\n\t}\n\n\t// compare energy quantum numbers\n\tif (a->n < b->n)\n\t{\n\t\treturn -1;\n\t}\n\telse if (a->n > b->n)\n\t{\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\n\n/// \\brief Get the maximum occupancy of an energy level, depending on 'm' quantum number and whether state is spin-polarized\nstatic inline int GetMaxOccupancy(const int m, const bool spinpol)\n{\n\tint occ = 1;\n\n\tif (m != 0)\n\t{\n\t\tocc *= 2;\n\t}\n\tif (!spinpol)\n\t{\n\t\tocc *= 2;\n\t}\n\n\treturn occ;\n}\n\n\n//_______________________________________________________________________________________________________________________\n//\n\n\n/// \\brief Fermi-Dirac distribution function\nstatic double FermiDirac(const double kBT, const double mu, const double en)\n{\n\treturn 1 / (exp((en - mu)/kBT) + 1);\n}\n\n\n/// \\brief GSL parameters for NumParticleDifference()\ntypedef struct\n{\n\tint nelec;\t\t\t//!< physical number of electrons\n\tint nlevels;\t\t//!< number of energy levels\n\tdouble *en;\t\t\t//!< energies\n\tint *occ;\t\t\t//!< maximum occupancy of each energy level\n\tdouble kBT;\t\t\t//!< k_B T (Boltzmann constant times temperature)\n}\ngsl_FD_params_t;\n\n\n/// \\brief Calculate difference in number of particles given a Fermi-Dirac distribution with chemical potential 'mu'\nstatic double NumParticleDifference(double mu, void *p)\n{\n\tint i;\n\n\tconst gsl_FD_params_t *params = (gsl_FD_params_t *)p;\n\n\tdouble N = 0;\n\tfor (i = 0; i < params->nlevels; i++)\n\t{\n\t\tN += params->occ[i] * FermiDirac(params->kBT, mu, params->en[i]);\n\t}\n\n\treturn N - params->nelec;\n}\n\n\n//_______________________________________________________________________________________________________________________\n///\n/// \\brief Calculate chemical potential 'mu' such that FermiDirac distribution gives exactly 'nelec' electrons\n///\nstatic double CalculateChemicalPotential(const en_levels_t *levels, const int nelec, const bool spinpol, const double kBT)\n{\n\tint m, n, i;\n\n\tconst int maxiter = 128;\n\n\tgsl_FD_params_t params;\n\tparams.nelec = nelec;\n\tparams.nlevels = (levels->m_max+1)*levels->num;\n\tparams.en = malloc(params.nlevels * sizeof(double));\n\tparams.occ = malloc(params.nlevels * sizeof(int));\n\tparams.kBT = kBT;\n\t// fill energy levels and occupancies\n\tfor (m = 0; m <= levels->m_max; m++)\n\t{\n\t\tfor (n = 0; n < levels->num; n++)\n\t\t{\n\t\t\tparams.en [n + m*levels->num] = levels->en[n + m*levels->num];\n\t\t\tparams.occ[n + m*levels->num] = GetMaxOccupancy(m, spinpol);\n\t\t}\n\t}\n\n\t// first interval used in interval bisection method\n\tdouble mu_lo = 0.0;\n\tdouble mu_hi = levels->en[(levels->m_max+1)*levels->num-1];\t\t// use \"last\" energy level as upper bound\n\n\tgsl_function F;\n\tF.function = &NumParticleDifference;\n\tF.params = ¶ms;\n\n\tconst gsl_root_fsolver_type *T = gsl_root_fsolver_brent;\n\tgsl_root_fsolver *s = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &F, mu_lo, mu_hi);\n\n\tdouble mu = 0;\n\tint status = GSL_CONTINUE;\n\tfor (i = 0; i < maxiter && status == GSL_CONTINUE; i++)\n\t{\n\t\tstatus = gsl_root_fsolver_iterate(s);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"CalculateOccupancy() warning: gsl_root_fsolver_iterate() returned with status code %i\\n\", status);\n\t\t}\n\n\t\tmu = gsl_root_fsolver_root(s);\n\t\tmu_lo = gsl_root_fsolver_x_lower(s);\n\t\tmu_hi = gsl_root_fsolver_x_upper(s);\n\t\tstatus = gsl_root_test_interval(mu_lo, mu_hi, 0, 1e-8);\n\t}\n\n\tif (status != GSL_SUCCESS) {\n\t\tfprintf(stderr, \"CalculateOccupancy() warning: not converged after %i iterations, status: %i\\n\", maxiter, status);\n\t}\n\n\t// clean up\n\tfree(params.occ);\n\tfree(params.en);\n\tgsl_root_fsolver_free(s);\n\n\treturn mu;\n}\n\n\n//_______________________________________________________________________________________________________________________\n///\n/// \\brief Calculate occupancy of energy levels\n///\nvoid CalculateOccupancy(const en_levels_t *levels, const int nelec, const bool spinpol, const double kBT, en_occlist_t *occlist)\n{\n\tint i, m, n;\n\n\t// accumulate all energies into one list\n\tocclist->occupancy = malloc((levels->m_max+1)*levels->num * sizeof(en_occupancy_t));\n\n\tif (kBT == 0)\t// zero temperature\n\t{\n\t\tfor (m = 0; m <= levels->m_max; m++)\n\t\t{\n\t\t\tfor (n = 0; n < levels->num; n++)\n\t\t\t{\n\t\t\t\ten_occupancy_t *encur = &occlist->occupancy[n + m*levels->num];\n\t\t\t\tencur->en = levels->en[n + m*levels->num];\n\t\t\t\tencur->m = m;\n\t\t\t\tencur->n = n;\n\t\t\t\tencur->occ = 0;\t\t// initially set to zero\n\t\t\t}\n\t\t}\n\n\t\t// sort energies\n\t\tqsort(occlist->occupancy, (levels->m_max+1)*levels->num, sizeof(en_occupancy_t), en_occupancy_cmp);\n\n\t\t// fill up energy levels\n\t\ten_occupancy_t *encur = occlist->occupancy;\n\t\tocclist->length = 1;\n\t\tfor (i = 0; i < nelec; i++)\n\t\t{\n\t\t\tif (encur->occ >= GetMaxOccupancy(encur->m, spinpol)) {\n\t\t\t\tencur++;\t// use next level\n\t\t\t\tocclist->length++;\n\t\t\t}\n\n\t\t\tencur->occ++;\n\t\t}\n\t}\n\telse\t// k_B T > 0\n\t{\n\t\tassert(kBT > 0);\n\n\t\tconst double mu = CalculateChemicalPotential(levels, nelec, spinpol, kBT);\n\n\t\t// all energy levels have nonzero occupancy since Fermi-Dirac function is strictly positive\n\t\tocclist->length = (levels->m_max+1)*levels->num;\n\t\tfor (m = 0; m <= levels->m_max; m++)\n\t\t{\n\t\t\tfor (n = 0; n < levels->num; n++)\n\t\t\t{\n\t\t\t\ten_occupancy_t *encur = &occlist->occupancy[n + m*levels->num];\n\t\t\t\tencur->en = levels->en[n + m*levels->num];\n\t\t\t\tencur->m = m;\n\t\t\t\tencur->n = n;\n\t\t\t\tencur->occ = GetMaxOccupancy(m, spinpol) * FermiDirac(kBT, mu, encur->en);\n\t\t\t}\n\t\t}\n\n\t\t// sort energies\n\t\tqsort(occlist->occupancy, (levels->m_max+1)*levels->num, sizeof(en_occupancy_t), en_occupancy_cmp);\n\t}\n}\n\n\n\n/// \\brief Free memory of energy level occupancy list\nvoid FreeOccupancy(en_occlist_t *occlist)\n{\n\tfree(occlist->occupancy);\n\tocclist->length = 0;\n}\n", "meta": {"hexsha": "3b572ddebbb19e4b1a58c60db7f909ef1369a97e", "size": 7412, "ext": "c", "lang": "C", "max_stars_repo_path": "src/energy.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/energy.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/energy.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.3835616438, "max_line_length": 128, "alphanum_fraction": 0.6933351322, "num_tokens": 2167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.47133307470744684}} {"text": "/* linalg/ptlq.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * Copyright (C) 2004 Joerg Wensch, modifications for LQ. \n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"apply_givens.c\"\n\n/* The purpose of this package is to speed up QR-decomposition for\n large matrices. Because QR-decomposition is column oriented, but\n GSL uses a row-oriented matrix format, there can considerable\n speedup obtained by computing the LQ-decomposition of the\n transposed matrix instead. This package provides LQ-decomposition\n and related algorithms. */\n\n/* Factorise a general N x M matrix A into\n *\n * P A = L Q\n *\n * where Q is orthogonal (M x M) and L is lower triangular (N x M).\n * When A is rank deficient, r = rank(A) < n, then the permutation is\n * used to ensure that the lower n - r columns of L are zero and the first\n * l rows of Q form an orthonormal basis for the rows of A.\n *\n * Q is stored as a packed set of Householder transformations in the\n * strict upper triangular part of the input matrix.\n *\n * L is stored in the diagonal and lower 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,i+1), m(i,i+2), ... , m(i,M)]\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_PTLQ_decomp (gsl_matrix * A, gsl_vector * tau, gsl_permutation * p, int *signum, gsl_vector * norm)\n{\n const size_t N = A->size1;\n const size_t M = 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_row (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_rows (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 = gsl_matrix_subrow (A, i, 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 +1, i, N - (i+1), M - i);\n gsl_linalg_householder_mh (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, j, i) / 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 = gsl_matrix_subrow (A, j, 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_PTLQ_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 N = A->size1;\n const size_t M = 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 != N || r->size2 !=M)\n {\n GSL_ERROR (\"r must be N x M\", 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_PTLQ_decomp (r, tau, p, signum, norm);\n\n /* FIXME: aliased arguments depends on behavior of unpack routine! */\n\n gsl_linalg_LQ_unpack (r, tau, q, r);\n\n return GSL_SUCCESS;\n}\n\n\n/* Solves the system x^T A = b^T using the P^T L Q factorisation,\n\n z^T L = b^T Q^T \n\n x = P z;\n\n to obtain x. Based on SLATEC code. */\n\nint\ngsl_linalg_PTLQ_solve_T (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->size2 != p->size)\n {\n GSL_ERROR (\"matrix size must match permutation size\", GSL_EBADLEN);\n }\n else if (QR->size2 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (QR->size1 != 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_PTLQ_svx_T (QR, tau, p, x);\n \n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_PTLQ_svx_T (const gsl_matrix * LQ,\n const gsl_vector * tau,\n const gsl_permutation * p,\n gsl_vector * x)\n{\n if (LQ->size1 != LQ->size2)\n {\n GSL_ERROR (\"LQ matrix must be square\", GSL_ENOTSQR);\n }\n else if (LQ->size2 != p->size)\n {\n GSL_ERROR (\"matrix size must match permutation size\", GSL_EBADLEN);\n }\n else if (LQ->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* compute sol = b^T Q^T */\n\n gsl_linalg_LQ_vecQT (LQ, tau, x);\n\n /* Solve L^T x = sol, storing x inplace in sol */\n\n gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_PTLQ_LQsolve_T (const gsl_matrix * Q, const gsl_matrix * L,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * x)\n{\n if (Q->size1 != Q->size2 || L->size1 != L->size2)\n {\n return GSL_ENOTSQR;\n }\n else if (Q->size1 != p->size || Q->size1 != L->size1\n || Q->size1 != b->size)\n {\n return GSL_EBADLEN;\n }\n else\n {\n /* compute b' = Q b */\n\n gsl_blas_dgemv (CblasNoTrans, 1.0, Q, b, 0.0, x);\n\n /* Solve L^T x = b', storing x inplace */\n\n gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, L, 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_PTLQ_Lsolve_T (const gsl_matrix * LQ,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * x)\n{\n if (LQ->size1 != LQ->size2)\n {\n GSL_ERROR (\"LQ matrix must be square\", GSL_ENOTSQR);\n }\n else if (LQ->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LQ->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 L^T x = b, storing x inplace */\n\n gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_PTLQ_Lsvx_T (const gsl_matrix * LQ,\n const gsl_permutation * p,\n gsl_vector * x)\n{\n if (LQ->size1 != LQ->size2)\n {\n GSL_ERROR (\"LQ matrix must be square\", GSL_ENOTSQR);\n }\n else if (LQ->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 L^T x = b, storing x inplace */\n\n gsl_blas_dtrsv (CblasLower, CblasTrans, CblasNonUnit, LQ, x);\n\n gsl_permute_vector_inverse (p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n\n/* Update a P^T L Q factorisation for P A= L Q , A' = A + v u^T,\n PA' = PA + Pv u^T\n\n * P^T L' Q' = P^T LQ + v u^T\n * = P^T (L + (P v) u^T Q^T) Q\n * = P^T (L + (P v) w^T) Q\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 */\n\nint\ngsl_linalg_PTLQ_update (gsl_matrix * Q, gsl_matrix * L,\n const gsl_permutation * p,\n const gsl_vector * v, gsl_vector * w)\n{\n if (Q->size1 != Q->size2 || L->size1 != L->size2)\n {\n return GSL_ENOTSQR;\n }\n else if (L->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 N = Q->size1;\n const size_t M = 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 L, H = J_1^T ... J^T_(n-1) L\n so that H is upper Hessenberg. (12.5.2) */\n\n for (k = M - 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 gsl_linalg_givens (wkm1, wk, &c, &s);\n gsl_linalg_givens_gv (w, k - 1, k, c, s);\n apply_givens_lq (M, N, Q, L, k - 1, k, c, s);\n }\n\n w0 = gsl_vector_get (w, 0);\n\n /* Add in v w^T (Equation 12.5.3) */\n\n for (j = 0; j < N; j++)\n {\n double lj0 = gsl_matrix_get (L, j, 0);\n size_t p_j = gsl_permutation_get (p, j);\n double vj = gsl_vector_get (v, p_j);\n gsl_matrix_set (L, j, 0, lj0 + w0 * vj);\n }\n\n /* Apply Givens transformations L' = 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 (L, k - 1, k - 1);\n double offdiag = gsl_matrix_get (L, k - 1, k );\n\n gsl_linalg_givens (diag, offdiag, &c, &s);\n apply_givens_lq (M, N, Q, L, k - 1, k, c, s);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "8c3e74630803bab6d8d430697663827c7b3c8a57", "size": 13086, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/ptlq.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/linalg/ptlq.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/ptlq.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.8706365503, "max_line_length": 149, "alphanum_fraction": 0.534464313, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.47113388386791333}} {"text": "#include \n#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_conline_run()\n{\n double aicc, chi2, aicc_best;\n double *theta_best_this, *theta_best_var_this;\n\n char fname_mcmc[100];\n \n aicc_best = DBL_MAX;\n theta_best_this = malloc(ntheta_max*sizeof(double));\n theta_best_var_this = malloc(ntheta_max*2*sizeof(double));\n \n printf(\"*******con-line mcmc\\n\");\n if(flag_mcmc==1)\n {\n fprintf(fp_results, \"************AICC************\\n\");\n for(nc = nc_lim_low; nc<=nc_lim_up; nc++)\n {\n printf(\"nc = %d\\n\", nc);\n sprintf(fname_mcmc, \"data/mcmc_%02d.txt\", nc);\n mcmc_conline_init();\n mcmc_sampling(fname_mcmc, &probability_conline);\n mcmc_stats(fname_mcmc);\n aicc = cal_aicc();\n if(aicc < aicc_best)\n {\n aicc_best = aicc;\n nc_best = nc;\n memcpy(theta_best_this, theta_best, ntheta * sizeof(double));\n memcpy(theta_best_var_this, theta_best_var, ntheta * 2 * sizeof(double));\n }\n printf(\"aicc: %d %f\\n\", nc, aicc);\n fprintf(fp_results, \"aicc: %d %f\\n\", nc, aicc);\n }\n }\n else\n {\n printf(\"reading par.txt\\n\");\n nc = nc_best = nc_lim_low;\n sprintf(fname_mcmc, \"data/mcmc_%02d.txt\", nc);\n mcmc_conline_init();\n read_input();\n memcpy(theta_best_this, theta_best, ntheta * sizeof(double));\n memcpy(theta_best_var_this, theta_best_var, ntheta * 2 * sizeof(double));\n }\n printf(\"*******finish mcmc\\n\");\n\n fprintf(fp_results, \"************Best Estimate************\\n\");\n fprintf(fp_results, \"best nc: %d\\n\", nc_best);\n printf(\"best nc: %d\\n\", nc_best);\n \n nc = nc_best;\n memcpy(theta_best, theta_best_this, ntheta * sizeof(double));\n memcpy(theta_best_var, theta_best_var_this, ntheta * 2 * sizeof(double)); \n mcmc_conline_init(); // reset the grid of tau\n\n reconstruct_conline();\n transfer_function(theta_best);\n aicc = cal_aicc();\n chi2 = chi_square();\n line_convolution();\n fprintf(fp_results, \"aicc: %f\\n\", aicc);\n fprintf(fp_results, \"chi2: %f\\n\", chi2);\n\n free(theta_best_this);\n free(theta_best_var_this);\n}\n\nvoid mcmc_conline_init()\n{\n int i, j;\n\n \n#ifdef JAVELIN // only one-tophat is used in JAVELIN\n ntheta = 2 + 3 + 1;\n\n theta_range[0][0] = log(1.0e-6); // sigma in DRW\n theta_range[0][1] = log(10.0); // \n\n theta_range[1][0] = log(1.0e-2); // tau in DRW\n theta_range[1][1] = log(1.0e5);\n\n theta_range[2][0] = (tau_lim_up - tau_lim_low)/1000.0; // width of tophat\n theta_range[2][1] = (tau_lim_up - tau_lim_low)*10.0;\n \n theta_range[3][0] = 0.0; // height of tophat\n theta_range[3][1] = 1.0e3;\n\n theta_range[4][0] = tau_lim_low; //central value of tophat\n theta_range[4][1] = tau_lim_up;\n\n theta_range[5][0] = log(1.0e-5); // systematic error\n theta_range[5][1] = log(1.0e6);\n\n i = 0;\n sigma_input[i++] = 0.01; // sigma\n sigma_input[i++] = 0.01; // taud\n sigma_input[i++] = 0.01; // width\n sigma_input[i++] = 0.1; // fk\n sigma_input[i++] = 0.1; // tauc\n sigma_input[i++] = 0.1;\n\n theta_input[0] = theta_best[0];\n theta_input[1] = theta_best[1];\n theta_input[2] = (tau_lim_up-tau_lim_low)/5.0;\n theta_input[3] = 1.0;\n theta_input[4] = (tau_lim_up-tau_lim_low)/2.0;\n theta_input[5] = log(10.0);\n \n#else\n\n ntheta = nc + 3 + 1;\n// grid of time lag\n for(i=0; i 0.0 ) // check if prob is positive\n {\n prob = -1.0e10;\n printf(\"prob >0!\\n\");\n return prob;\n }\n\n //memcpy(Tmat1, Cmat, n_data*nall_data*sizeof(double));\n lndet_C = lndet_mat3(Cmat, nall_data, &info, &sign_C) + 2.0*nall_data * log(sigma);\n if(info!=0|| sign_C==-1)\n {\n prob = -1.0e10;\n printf(\"lndet_C %f %d!\\n\", lndet_C, sign_C);\n return prob;\n }\n\n //memcpy(Tmat1, ICq, nq*nq*sizeof(double));\n lndet_ICq = lndet_mat3(ICq, nq, &info, &sign_Cq) - 2.0*nq*log(sigma);\n if(info!=0 || sign_Cq==-1 )\n {\n prob = -1.0e10;\n printf(\"lndet_ICq!\\n\");\n return prob;\n }\n \n prob -= 0.5*(lndet_C + lndet_ICq);\n\n prior = 0.0;\n// for sigmad \n if( theta[0] < theta_best_con[0])\n {\n prior += -0.5*pow(theta[0] - theta_best_con[0], 2.0)/pow(theta_best_var_con[0*2], 2.0);\n }\n else\n {\n prior += -0.5*pow(theta[0] - theta_best_con[0], 2.0)/pow(theta_best_var_con[0*2+1], 2.0);\n }\n// for taud\n if( theta[1] < theta_best_con[1])\n {\n prior += -0.5*pow(theta[1] - theta_best_con[1], 2.0)/pow(theta_best_var_con[1*2], 2.0);\n }\n else\n {\n prior += -0.5*pow(theta[1] - theta_best_con[1], 2.0)/pow(theta_best_var_con[1*2+1], 2.0);\n }\n//penalize very large tau or very small tau \n/* if(theta[1] > log(len_con) )\n {\n prior += (log(len_con) - theta[1])/fabs(log(cad_con));\n }\n if(theta[1] < log(cad_con))\n {\n prior += (theta[1] - log(cad_con) ) / fabs(log(cad_con));\n }*/\n \n prob += prior;\n return prob;\n}\n\ndouble cal_aicc()\n{\n double prob, aic, aicc;\n int k, n;\n\n k = nc + 4;\n n = nall_data;\n\n prob = probability_conline_aicc(theta_best);\n\n aic = 2.0*k - 2.0*prob;\n\n aicc = aic + 2.0*k*(k+1.0)/(n - k - 1.0);\n\n //printf(\"aicc: %d %f %f\\n\", nc, aicc, prob);\n return aicc;\n}\n\ndouble probability_conline_aicc(double *theta)\n{\n double prob, lndet_C, lndet_ICq, sigma, taud;\n double *Larr, *ybuf, *Cq, *ICq, *ave, *ysub, *yrec, *yrec_err, *yave;\n int i, nq, info, sign_C, sign_Cq;\n \n taud = exp(theta[1]);\n sigma = exp(theta[0]) * sqrt(taud/2.0);\n\n nq = (flag_detrend + 1)*2;\n Larr = workspace;\n ybuf = Larr + nq*nall_data;\n Cq = ybuf + nall_data;\n ICq = Cq + nq*nq;\n ave = ICq + nq*nq;\n\n ysub = ave + nq;\n yrec = ysub + nall_data;\n yrec_err = yrec + nall_data;\n yave = yrec_err + nall_data;\n\n set_covar_mat(theta);\n\n for(i=0; i 0.0 ) // check if prob is positive\n {\n prob = -1.0e10;\n printf(\"prob >0!\\n\");\n return prob;\n }\n\n //memcpy(Tmat1, Cmat, n_data*nall_data*sizeof(double));\n lndet_C = lndet_mat3(Cmat, nall_data, &info, &sign_C) + 2.0*nall_data * log(sigma);\n if(info!=0|| sign_C==-1)\n {\n prob = -1.0e10;\n printf(\"lndet_C %f %d!\\n\", lndet_C, sign_C);\n return prob;\n }\n\n //memcpy(Tmat1, ICq, nq*nq*sizeof(double));\n lndet_ICq = lndet_mat3(ICq, nq, &info, &sign_Cq) - 2.0*nq*log(sigma);\n if(info!=0 || sign_Cq==-1 )\n {\n prob = -1.0e10;\n printf(\"lndet_ICq!\\n\");\n return prob;\n }\n \n prob -= 0.5*(lndet_C + lndet_ICq);\n \n return prob;\n}\n\ndouble chi_square()\n{\n double chi2, sigma, taud;\n double *Larr, *ybuf, *Cq, *ICq, *ave, *ysub, *yrec, *yrec_err, *yave;\n int i, nq, info;\n \n taud = exp(theta_best[1]);\n sigma = exp(theta_best[0]) * sqrt(taud/2.0);\n \n nq = 2*(flag_detrend + 1);\n\n Larr = workspace;\n ybuf = Larr + nq*nall_data;\n Cq = ybuf + nall_data;\n ICq = Cq + nq*nq;\n ave = ICq + nq*nq;\n\n ysub = ave + nq;\n yrec = ysub + nall_data;\n yrec_err = yrec + nall_data;\n yave = yrec_err + nall_data;\n\n\n set_covar_mat(theta_best);\n\n for(i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n#define MIN(x,y) ((x) < (y) ? (x) : (y))\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n\n\nextern double ttest2(double *data1,double *data2,int n1,int n2);\nextern double xtest2(double *data1,double *data2,int n);\nextern double paired_ttest(double *data1,double *data2,int n);\nextern double welchtest(double *data1,double *data2,int n1,int n2);\nextern void VIsolatedVoxels(VImage src,float threshold);\nextern void VHistogram(gsl_histogram *histogram,VString filename);\nextern void VCheckImage(VImage src);\nextern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);\nextern double ttest1(double *data1,int n);\nextern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);\nextern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);\nextern double VImageVar(VImage src);\nextern void VGetHistRange(VImage src,double *hmin,double *hmax);\nextern void VZScale(VImage src,float mode,float stddev);\nextern float VGetMode(VImage src);\nextern void HistoUpdate(VImage,gsl_histogram *);\n\n\n/* generate permutation table */\nint **genperm(long seed,int n1,int n2,int numperm,int testtype)\n{\n int i,j,n=n1+n2;\n int **table = (int **) VCalloc(numperm,sizeof(int *));\n int *base = (int *) VCalloc(n,sizeof(int));\n for (j=0; j 0) {\n\t data1[k1++] = u;\n\t }\n\t }\n\t if (k1 < min1) continue;\n\n\t k2 = 0;\n\t for (i=0; i 0) {\n\t data2[k2++] = u;\n\t }\n\t }\n\t if (k2 < min2) continue;\n\t}\n\n\n\t/* paired test */\n\tif (testtype == 1) {\n\t k=0;\n\t for (i=0; i 0 && fabs(v) > 0) {\n\t data1[k] = u;\n\t data2[k] = v;\n\t k++;\n\t }\n\t }\n\t if (k < min1) continue;\n\t}\n\n\n\n\t/* t-test */\n\tz = 0;\n\tswitch(testtype) {\n\tcase 0 :\n\t z = ttest2(data1,data2,k1,k2); /* pooled variance */\n\t break;\n\tcase 1 :\n\t z = paired_ttest(data1,data2,k); /* paired */\n\t break;\n\tcase 2 :\n\t z = welchtest(data1,data2,k1,k2); /* unequal variance */\n\t break;\n\tdefault:\n\t VError(\" unknown testtype\");\n\t}\n\tVPixel(dest,b,r,c,VFloat) = z;\n }\n }\n }\n VFree(data);\n VFree(data1);\n VFree(data2);\n}\n\n\nVDictEntry TSTDict[] = {\n { \"pooled\", 0, 0,0,0,0 },\n { \"paired\", 1, 0,0,0,0 },\n { \"welch\", 2, 0,0,0,0 },\n { NULL, 0,0,0,0,0 }\n};\n\n\nint main (int argc, char *argv[])\n{\n static VArgVector in_files1;\n static VArgVector in_files2;\n static VString out_filename=\"\";\n static VString mask_filename=\"\";\n static VFloat alpha = 0.05;\n static VShort testtype = 2; /* default is welch */\n static VShort radius = 2;\n static VFloat rvar = 2.0;\n static VFloat svar = 2.0;\n static VShort numiter = 2;\n static VShort numperm = 5000;\n static VLong seed = 99402622;\n static VBoolean centering = FALSE;\n static VBoolean cleanup = TRUE;\n static VShort nproc = 0;\n static VOptionDescRec options[] = {\n {\"in1\", VStringRepn, 0, & in_files1, VRequiredOpt, NULL,\"Input files 1 (single file per group)\" },\n {\"in2\", VStringRepn, 0, & in_files2, VRequiredOpt, NULL,\"Input files 2 (single file per group)\" },\n {\"out\", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,\"Output file\" },\n {\"alpha\",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,\"FDR significance level\"},\n {\"perm\",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,\"Number of permutations\"},\n {\"mask\", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, \"Mask\"},\n {\"test\",VShortRepn,1,(VPointer) &testtype,VOptionalOpt,TSTDict,\"type of test\"},\n {\"seed\",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,\"Seed for random number generation\"},\n {\"radius\",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,\"Bilateral parameter (radius in voxels)\"},\n {\"rvar\",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,\"Bilateral parameter (radiometric)\"},\n {\"svar\",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,\"Bilateral parameter (spatial)\"},\n {\"filteriterations\",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,\"Bilateral parameter (number of iterations)\"},\n {\"cleanup\",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,\"Whether to apply cleanup\"},\n {\"j\",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,\"Number of processors to use, '0' to use all\"},\n };\n\n FILE *fp=NULL;\n VString in_filename,str1,str2;\n VAttrList list1=NULL,list2=NULL,out_list=NULL,geolist=NULL;\n int i,ngroups1=0,ngroups2=0,npix=0;\n char *prg_name=GetLipsiaName(\"vlisa_grouped_twosample\");\n fprintf (stderr, \"%s\\n\", prg_name);\n\n\n /* parse command line */\n if (! VParseCommand (VNumber (options), options, & argc, argv)) {\n VReportUsage (argv[0], VNumber (options), options, NULL);\n exit (EXIT_FAILURE);\n }\n if (argc > 1) {\n VReportBadArgs (argc, argv);\n exit (EXIT_FAILURE);\n }\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\" using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n /* read mask */\n VImage mask = VReadImageFile(mask_filename);\n if (mask==NULL) VError(\"Error reading mask file %s\",mask_filename);\n\n\n /* number of inputs */\n ngroups1 = in_files1.number;\n ngroups2 = in_files2.number;\n fprintf(stderr,\" ngroups= %d %d\\n\",ngroups1,ngroups2);\n\n\n /* images 1 */\n VImage *src1 = (VImage *) VCalloc(ngroups1,sizeof(VImage));\n for (i = 0; i < ngroups1; i++) {\n in_filename = ((VString *) in_files1.vector)[i];\n list1 = VReadAttrList(in_filename,0L,TRUE,FALSE);\n VMaskMinval(list1,mask,0.0);\n src1[i] = VReadImage(list1);\n if (src1[i] == NULL) VError(\" no input image found\");\n if (VPixelRepn(src1[i]) != VFloatRepn) VError(\" input pixel repn must be float\");\n if (i == 0) npix = VImageNPixels(src1[i]);\n else if (npix != VImageNPixels(src1[i])) VError(\" inconsistent image dimensions\");\n\n /* use geometry info from 1st file */\n if (geolist == NULL) geolist = VGetGeoInfo(list1);\n }\n\n\n /* images 2 */\n VImage *src2 = (VImage *) VCalloc(ngroups2,sizeof(VImage));\n for (i = 0; i < ngroups2; i++) {\n in_filename = ((VString *) in_files2.vector)[i];\n list2 = VReadAttrList(in_filename,0L,TRUE,FALSE);\n VMaskMinval(list2,mask,0.0);\n src2[i] = VReadImage(list2);\n if (src2[i] == NULL) VError(\" no input image found\");\n if (VPixelRepn(src2[i]) != VFloatRepn) VError(\" input pixel repn must be float\");\n if (i == 0) npix = VImageNPixels(src2[i]);\n else if (npix != VImageNPixels(src2[i])) VError(\" inconsistent image dimensions\");\n }\n\n if (testtype == 1) { /* print filenames to terminal */\n for (i = 0; i < ngroups1; i++) {\n str1 = ((VString *) in_files1.vector)[i];\n str2 = ((VString *) in_files2.vector)[i];\n fprintf(stderr,\" %3d: %s %s\\n\",i,str1,str2);\n }\n }\n else {\n fprintf(stderr,\" Group 1:\\n\");\n for (i = 0; i < ngroups1; i++) {\n str1 = ((VString *) in_files1.vector)[i];\n fprintf(stderr,\" %3d: %s\\n\",i,str1);\n }\n fprintf(stderr,\"\\n Group 2:\\n\");\n for (i = 0; i < ngroups2; i++) {\n str2 = ((VString *) in_files2.vector)[i];\n fprintf(stderr,\" %3d: %s\\n\",i,str2);\n }\n }\n\n\n /* random permutations */\n size_t n = ngroups1+ngroups2;\n int nperm=0;\n int **permtable = genperm((long)seed,(int)ngroups1,(int)ngroups2,(int)numperm,(int)testtype);\n int *nopermtable = (int *) VCalloc(n,sizeof(int));\n for (i=0; i 0) {\n int tstperm = 30;\n if (tstperm > numperm) tstperm = numperm;\n double varsum=0,nx=0;\n\n#pragma omp parallel for shared(src1,permtable) schedule(dynamic)\n for (nperm = 0; nperm < tstperm; nperm++) {\n VImage zmap = VCreateImageLike(src1[0]);\n TTest(src1,src2,permtable[nperm],zmap,ngroups1,ngroups2,(int)testtype);\n#pragma omp critical\n {\n\tvarsum += VImageVar(zmap);\n\tnx++;\n }\n VDestroyImage(zmap);\n }\n double meanvar = varsum/nx;\n stddev = sqrt(meanvar);\n }\n\n\n\n /* no permutation */\n VImage dst1 = VCreateImageLike (src1[0]);\n VImage zmap1 = VCreateImageLike(src1[0]);\n VFillImage(zmap1,VAllBands,0);\n TTest(src1,src2,nopermtable,zmap1,ngroups1,ngroups2,(int)testtype);\n\n if (numperm == 0) {\n double z = VImageVar(zmap1);\n stddev = (float)(sqrt(z)); /* update stddev */\n }\n float mode=0;\n if (centering) mode = VGetMode(zmap1);\n if (numperm > 0) VZScale(zmap1,mode,stddev);\n VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n\n /* ini histograms */\n VGetHistRange(dst1,&hmin,&hmax);\n size_t nbins = 20000;\n gsl_histogram *hist0 = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);\n gsl_histogram *histz = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (histz,hmin,hmax);\n HistoUpdate(dst1,histz);\n\n\n#pragma omp parallel for shared(src1,src2,permtable) schedule(dynamic)\n for (nperm = 0; nperm < numperm; nperm++) {\n if (nperm%20 == 0) fprintf(stderr,\" perm %4d of %d\\r\",nperm,(int)numperm);\n\n VImage zmap = VCreateImageLike(src1[0]);\n VImage dst = VCreateImageLike (zmap);\n TTest(src1,src2,permtable[nperm],zmap,ngroups1,ngroups2,(int)testtype);\n\n float mode=0;\n if (centering) mode = VGetMode(zmap);\n VZScale(zmap,mode,stddev);\n VBilateralFilter(zmap,dst,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n\n#pragma omp critical\n {\n HistoUpdate(dst,hist0);\n }\n VDestroyImage(dst);\n VDestroyImage(zmap);\n }\n\n\n /* apply fdr */\n VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);\n if (numperm > 0) {\n FDR(dst1,fdrimage,hist0,histz,(double)alpha);\n if (cleanup && alpha < 1.0) {\n VIsolatedVoxels(fdrimage,(float)(1.0-alpha));\n }\n }\n\n\n /* write output to disk */\n out_list = VCreateAttrList ();\n VHistory(VNumber(options),options,prg_name,&list1,&out_list);\n VSetGeoInfo(geolist,out_list);\n VAppendAttr (out_list,\"image\",NULL,VImageRepn,fdrimage);\n fp = VOpenOutputFile (out_filename, TRUE);\n if (! VWriteFile (fp, out_list)) exit (1);\n fclose(fp);\n fprintf (stderr, \"\\n\");\n fprintf (stderr, \"%s: done.\\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "76cfee874735438ac8f1eb1aad460a1fbd6db2f9", "size": 13010, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_grouped_twosample/vlisa_grouped_twosample.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "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/stats/vlisa_grouped_twosample/vlisa_grouped_twosample.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "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/stats/vlisa_grouped_twosample/vlisa_grouped_twosample.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "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": 29.4343891403, "max_line_length": 121, "alphanum_fraction": 0.6322828593, "num_tokens": 4341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4707929841496716}} {"text": "/*!\n \\file fasttransforms.h\n \\brief fasttransforms.h is the main header file for FastTransforms.\n*/\n#ifndef FASTTRANSFORMS_H\n#define FASTTRANSFORMS_H\n\n#include \n#include \n\ntypedef double ft_complex[2];\n\n#ifdef _OPENMP\n #include \n #define FT_GET_THREAD_NUM() omp_get_thread_num()\n #define FT_GET_NUM_THREADS() omp_get_num_threads()\n #define FT_GET_MAX_THREADS() omp_get_max_threads()\n #define FT_SET_NUM_THREADS(x) omp_set_num_threads(x)\n#else\n #define FT_GET_THREAD_NUM() 0\n #define FT_GET_NUM_THREADS() 1\n #define FT_GET_MAX_THREADS() 1\n #define FT_SET_NUM_THREADS(x)\n#endif\n\n#define FT_CONCAT(prefix, name, suffix) prefix ## name ## suffix\n\nvoid ft_horner(const int n, const double * c, const int incc, const int m, double * x, double * f);\nvoid ft_hornerf(const int n, const float * c, const int incc, const int m, float * x, float * f);\n\nvoid ft_clenshaw(const int n, const double * c, const int incc, const int m, double * x, double * f);\nvoid ft_clenshawf(const int n, const float * c, const int incc, const int m, float * x, float * f);\n\nvoid ft_orthogonal_polynomial_clenshaw(const int n, const double * c, const int incc, const double * A, const double * B, const double * C, const int m, double * x, double * phi0, double * f);\nvoid ft_orthogonal_polynomial_clenshawf(const int n, const float * c, const int incc, const float * A, const float * B, const float * C, const int m, float * x, float * phi0, float * f);\n\nvoid ft_eigen_eval(const int n, const double * c, const int incc, const double * A, const double * B, const double * C, const int m, double * x, const int sign, double * f);\nvoid ft_eigen_evalf(const int n, const float * c, const int incc, const float * A, const float * B, const float * C, const int m, float * x, const int sign, float * f);\nvoid ft_eigen_evall(const int n, const long double * c, const int incc, const long double * A, const long double * B, const long double * C, const int m, long double * x, const int sign, long double * f);\n#if defined(FT_QUADMATH)\n #include \n typedef __float128 quadruple;\n void ft_eigen_evalq(const int n, const quadruple * c, const int incc, const quadruple * A, const quadruple * B, const quadruple * C, const int m, quadruple * x, const int sign, quadruple * f);\n#endif\n\n#define FT_SN (1U << 0)\n#define FT_CN (1U << 1)\n#define FT_DN (1U << 2)\n\n#include \"tdc.h\"\n\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Legendre and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Legendre}} P_\\ell(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x).\n \\f]\n `normleg` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_legendre_to_chebyshevf, \\ref ft_plan_legendre_to_chebyshevl, and \\ref ft_mpfr_plan_legendre_to_chebyshev.\n*/\nft_tb_eigen_FMM * ft_plan_legendre_to_chebyshev(const int normleg, const int normcheb, const int n);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Chebyshev and Legendre polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Legendre}} P_\\ell(x).\n \\f]\n `normcheb` and `normleg` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_chebyshev_to_legendref, \\ref ft_plan_chebyshev_to_legendrel, and \\ref ft_mpfr_plan_chebyshev_to_legendre.\n*/\nft_tb_eigen_FMM * ft_plan_chebyshev_to_legendre(const int normcheb, const int normleg, const int n);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between ultraspherical polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{(1)} C_\\ell^{(\\lambda)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{(2)} C_\\ell^{(\\mu)}(x).\n \\f]\n `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_ultraspherical_to_ultrasphericalf, \\ref ft_plan_ultraspherical_to_ultrasphericall, and \\ref ft_mpfr_plan_ultraspherical_to_ultraspherical.\n*/\nft_tb_eigen_FMM * ft_plan_ultraspherical_to_ultraspherical(const int norm1, const int norm2, const int n, const double lambda, const double mu);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Jacobi polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{(1)} P_\\ell^{(\\alpha,\\beta)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{(2)} P_\\ell^{(\\gamma,\\delta)}(x).\n \\f]\n `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_jacobi_to_jacobif, \\ref ft_plan_jacobi_to_jacobil, and \\ref ft_mpfr_plan_jacobi_to_jacobi.\n*/\nft_tb_eigen_FMM * ft_plan_jacobi_to_jacobi(const int norm1, const int norm2, const int n, const double alpha, const double beta, const double gamma, const double delta);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Laguerre polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{(1)} L_\\ell^{(\\alpha)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{(2)} L_\\ell^{(\\beta)}(x).\n \\f]\n `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_laguerre_to_laguerref, \\ref ft_plan_laguerre_to_laguerrel, and \\ref ft_mpfr_plan_laguerre_to_laguerre.\n*/\nft_tb_eigen_FMM * ft_plan_laguerre_to_laguerre(const int norm1, const int norm2, const int n, const double alpha, const double beta);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Jacobi and ultraspherical polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Jacobi}} P_\\ell^{(\\alpha,\\beta)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{ultraspherical}} C_\\ell^{(\\lambda)}(x).\n \\f]\n `normjac` and `normultra` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_jacobi_to_ultrasphericalf, \\ref ft_plan_jacobi_to_ultrasphericall, and \\ref ft_mpfr_plan_jacobi_to_ultraspherical.\n*/\nft_tb_eigen_FMM * ft_plan_jacobi_to_ultraspherical(const int normjac, const int normultra, const int n, const double alpha, const double beta, const double lambda);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between ultraspherical and Jacobi polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{ultraspherical}} C_\\ell^{(\\lambda)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Jacobi}} P_\\ell^{(\\alpha,\\beta)}(x).\n \\f]\n `normultra` and `normjac` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_ultraspherical_to_jacobif, \\ref ft_plan_ultraspherical_to_jacobil, and \\ref ft_mpfr_plan_ultraspherical_to_jacobi.\n*/\nft_tb_eigen_FMM * ft_plan_ultraspherical_to_jacobi(const int normultra, const int normjac, const int n, const double lambda, const double alpha, const double beta);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Jacobi and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Jacobi}} P_\\ell^{(\\alpha,\\beta)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x).\n \\f]\n `normjac` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_jacobi_to_chebyshevf, \\ref ft_plan_jacobi_to_chebyshevl, and \\ref ft_mpfr_plan_jacobi_to_chebyshev.\n*/\nft_tb_eigen_FMM * ft_plan_jacobi_to_chebyshev(const int normjac, const int normcheb, const int n, const double alpha, const double beta);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Chebyshev and Jacobi polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Jacobi}} P_\\ell^{(\\alpha,\\beta)}(x).\n \\f]\n `normcheb` and `normjac` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_chebyshev_to_jacobif, \\ref ft_plan_chebyshev_to_jacobil, and \\ref ft_mpfr_plan_chebyshev_to_jacobi.\n*/\nft_tb_eigen_FMM * ft_plan_chebyshev_to_jacobi(const int normcheb, const int normjac, const int n, const double alpha, const double beta);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between ultraspherical and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{ultraspherical}} C_\\ell^{(\\lambda)}(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x).\n \\f]\n `normultra` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_ultraspherical_to_chebyshevf, \\ref ft_plan_ultraspherical_to_chebyshevl, and \\ref ft_mpfr_plan_ultraspherical_to_chebyshev.\n*/\nft_tb_eigen_FMM * ft_plan_ultraspherical_to_chebyshev(const int normultra, const int normcheb, const int n, const double lambda);\n/*!\n \\brief Pre-compute a factorization of the connection coefficients between Chebyshev and ultraspherical polynomials in double precision so that ft_bfmv converts between expansions:\n \\f[\n \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{Chebyshev}} T_\\ell(x) = \\sum_{\\ell=0}^{n-1} c_\\ell^{\\mathrm{ultraspherical}} C_\\ell^{(\\lambda)}(x).\n \\f]\n `normcheb` and `normultra` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\\n\n See also \\ref ft_plan_chebyshev_to_ultrasphericalf, \\ref ft_plan_chebyshev_to_ultrasphericall, and \\ref ft_mpfr_plan_chebyshev_to_ultraspherical.\n*/\nft_tb_eigen_FMM * ft_plan_chebyshev_to_ultraspherical(const int normcheb, const int normultra, const int n, const double lambda);\n\nft_btb_eigen_FMM * ft_plan_associated_jacobi_to_jacobi(const int norm1, const int norm2, const int n, const int c, const double alpha, const double beta, const double gamma, const double delta);\nft_btb_eigen_FMM * ft_plan_associated_laguerre_to_laguerre(const int norm1, const int norm2, const int n, const int c, const double alpha, const double beta);\nft_btb_eigen_FMM * ft_plan_associated_hermite_to_hermite(const int norm1, const int norm2, const int n, const int c);\n\n/// A single precision version of \\ref ft_plan_legendre_to_chebyshev.\nft_tb_eigen_FMMf * ft_plan_legendre_to_chebyshevf(const int normleg, const int normcheb, const int n);\n/// A single precision version of \\ref ft_plan_chebyshev_to_legendre.\nft_tb_eigen_FMMf * ft_plan_chebyshev_to_legendref(const int normcheb, const int normleg, const int n);\n/// A single precision version of \\ref ft_plan_ultraspherical_to_ultraspherical.\nft_tb_eigen_FMMf * ft_plan_ultraspherical_to_ultrasphericalf(const int norm1, const int norm2, const int n, const float lambda, const float mu);\n/// A single precision version of \\ref ft_plan_jacobi_to_jacobi.\nft_tb_eigen_FMMf * ft_plan_jacobi_to_jacobif(const int norm1, const int norm2, const int n, const float alpha, const float beta, const float gamma, const float delta);\n/// A single precision version of \\ref ft_plan_laguerre_to_laguerre.\nft_tb_eigen_FMMf * ft_plan_laguerre_to_laguerref(const int norm1, const int norm2, const int n, const float alpha, const float beta);\n/// A single precision version of \\ref ft_plan_jacobi_to_ultraspherical.\nft_tb_eigen_FMMf * ft_plan_jacobi_to_ultrasphericalf(const int normjac, const int normultra, const int n, const float alpha, const float beta, const float lambda);\n/// A single precision version of \\ref ft_plan_ultraspherical_to_jacobi.\nft_tb_eigen_FMMf * ft_plan_ultraspherical_to_jacobif(const int normultra, const int normjac, const int n, const float lambda, const float alpha, const float beta);\n/// A single precision version of \\ref ft_plan_jacobi_to_chebyshev.\nft_tb_eigen_FMMf * ft_plan_jacobi_to_chebyshevf(const int normjac, const int normcheb, const int n, const float alpha, const float beta);\n/// A single precision version of \\ref ft_plan_chebyshev_to_jacobi.\nft_tb_eigen_FMMf * ft_plan_chebyshev_to_jacobif(const int normcheb, const int normjac, const int n, const float alpha, const float beta);\n/// A single precision version of \\ref ft_plan_ultraspherical_to_chebyshev.\nft_tb_eigen_FMMf * ft_plan_ultraspherical_to_chebyshevf(const int normultra, const int normcheb, const int n, const float lambda);\n/// A single precision version of \\ref ft_plan_chebyshev_to_ultraspherical.\nft_tb_eigen_FMMf * ft_plan_chebyshev_to_ultrasphericalf(const int normcheb, const int normultra, const int n, const float lambda);\n\nft_btb_eigen_FMMf * ft_plan_associated_jacobi_to_jacobif(const int norm1, const int norm2, const int n, const int c, const float alpha, const float beta, const float gamma, const float delta);\nft_btb_eigen_FMMf * ft_plan_associated_laguerre_to_laguerref(const int norm1, const int norm2, const int n, const int c, const float alpha, const float beta);\nft_btb_eigen_FMMf * ft_plan_associated_hermite_to_hermitef(const int norm1, const int norm2, const int n, const int c);\n\n/// A long double precision version of \\ref ft_plan_legendre_to_chebyshev.\nft_tb_eigen_FMMl * ft_plan_legendre_to_chebyshevl(const int normleg, const int normcheb, const int n);\n/// A long double precision version of \\ref ft_plan_chebyshev_to_legendre.\nft_tb_eigen_FMMl * ft_plan_chebyshev_to_legendrel(const int normcheb, const int normleg, const int n);\n/// A long double precision version of \\ref ft_plan_ultraspherical_to_ultraspherical.\nft_tb_eigen_FMMl * ft_plan_ultraspherical_to_ultrasphericall(const int norm1, const int norm2, const int n, const long double lambda, const long double mu);\n/// A long double precision version of \\ref ft_plan_jacobi_to_jacobi.\nft_tb_eigen_FMMl * ft_plan_jacobi_to_jacobil(const int norm1, const int norm2, const int n, const long double alpha, const long double beta, const long double gamma, const long double delta);\n/// A long double precision version of \\ref ft_plan_laguerre_to_laguerre.\nft_tb_eigen_FMMl * ft_plan_laguerre_to_laguerrel(const int norm1, const int norm2, const int n, const long double alpha, const long double beta);\n/// A long double precision version of \\ref ft_plan_jacobi_to_ultraspherical.\nft_tb_eigen_FMMl * ft_plan_jacobi_to_ultrasphericall(const int normjac, const int normultra, const int n, const long double alpha, const long double beta, const long double lambda);\n/// A long double precision version of \\ref ft_plan_ultraspherical_to_jacobi.\nft_tb_eigen_FMMl * ft_plan_ultraspherical_to_jacobil(const int normultra, const int normjac, const int n, const long double lambda, const long double alpha, const long double beta);\n/// A long double precision version of \\ref ft_plan_jacobi_to_chebyshev.\nft_tb_eigen_FMMl * ft_plan_jacobi_to_chebyshevl(const int normjac, const int normcheb, const int n, const long double alpha, const long double beta);\n/// A long double precision version of \\ref ft_plan_chebyshev_to_jacobi.\nft_tb_eigen_FMMl * ft_plan_chebyshev_to_jacobil(const int normcheb, const int normjac, const int n, const long double alpha, const long double beta);\n/// A long double precision version of \\ref ft_plan_ultraspherical_to_chebyshev.\nft_tb_eigen_FMMl * ft_plan_ultraspherical_to_chebyshevl(const int normultra, const int normcheb, const int n, const long double lambda);\n/// A long double precision version of \\ref ft_plan_chebyshev_to_ultraspherical.\nft_tb_eigen_FMMl * ft_plan_chebyshev_to_ultrasphericall(const int normcheb, const int normultra, const int n, const long double lambda);\n\nft_btb_eigen_FMMl * ft_plan_associated_jacobi_to_jacobil(const int norm1, const int norm2, const int n, const int c, const long double alpha, const long double beta, const long double gamma, const long double delta);\nft_btb_eigen_FMMl * ft_plan_associated_laguerre_to_laguerrel(const int norm1, const int norm2, const int n, const int c, const long double alpha, const long double beta);\nft_btb_eigen_FMMl * ft_plan_associated_hermite_to_hermitel(const int norm1, const int norm2, const int n, const int c);\n\n#include \n\ntypedef struct {\n mpfr_t * data;\n int n;\n int b;\n} ft_mpfr_triangular_banded;\n\nvoid ft_mpfr_destroy_plan(mpfr_t * A, int n);\nvoid ft_mpfr_trmv(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * x, mpfr_rnd_t rnd);\nvoid ft_mpfr_trsv(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * x, mpfr_rnd_t rnd);\nvoid ft_mpfr_trmm(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * B, int LDB, int N, mpfr_rnd_t rnd);\nvoid ft_mpfr_trsm(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * B, int LDB, int N, mpfr_rnd_t rnd);\n// C -- Julia interoperability. Julia `BigFloat` does not have the same size as `mpfr_t`.\n// So we give all Julia-owned data its own address, and dereference to retrieve the number.\nvoid ft_mpfr_trmv_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** x, mpfr_rnd_t rnd);\nvoid ft_mpfr_trsv_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** x, mpfr_rnd_t rnd);\nvoid ft_mpfr_trmm_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** B, int LDB, int N, mpfr_rnd_t rnd);\nvoid ft_mpfr_trsm_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** B, int LDB, int N, mpfr_rnd_t rnd);\n\n/// A multi-precision version of \\ref ft_plan_legendre_to_chebyshev that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_legendre_to_chebyshev(const int normleg, const int normcheb, const int n, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_chebyshev_to_legendre that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_chebyshev_to_legendre(const int normcheb, const int normleg, const int n, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_ultraspherical_to_ultraspherical that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_ultraspherical_to_ultraspherical(const int norm1, const int norm2, const int n, mpfr_srcptr lambda, mpfr_srcptr mu, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_jacobi_to_jacobi that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_jacobi_to_jacobi(const int norm1, const int norm2, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_srcptr gamma, mpfr_srcptr delta, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_laguerre_to_laguerre that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_laguerre_to_laguerre(const int norm1, const int norm2, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_jacobi_to_ultraspherical that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_jacobi_to_ultraspherical(const int normjac, const int normultra, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_ultraspherical_to_jacobi that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_ultraspherical_to_jacobi(const int normultra, const int normjac, const int n, mpfr_srcptr lambda, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_jacobi_to_chebyshev that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_jacobi_to_chebyshev(const int normjac, const int normcheb, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_chebyshev_to_jacobi that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_chebyshev_to_jacobi(const int normcheb, const int normjac, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_ultraspherical_to_chebyshev that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_ultraspherical_to_chebyshev(const int normultra, const int normcheb, const int n, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd);\n/// A multi-precision version of \\ref ft_plan_chebyshev_to_ultraspherical that returns a dense array of connection coefficients.\nmpfr_t * ft_mpfr_plan_chebyshev_to_ultraspherical(const int normcheb, const int normultra, const int n, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd);\n\n/// Set the number of OpenMP threads.\nvoid ft_set_num_threads(const int n);\n\n/// Data structure to store sines and cosines of Givens rotations.\ntypedef struct ft_rotation_plan_s ft_rotation_plan;\n\n/// Destroy a \\ref ft_rotation_plan.\nvoid ft_destroy_rotation_plan(ft_rotation_plan * RP);\n\nft_rotation_plan * ft_plan_rotsphere(const int n);\n\n/// Convert a single vector of spherical harmonic coefficients in A with stride S from order m2 down to order m1.\nvoid ft_kernel_sph_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n/// Convert a single vector of spherical harmonic coefficients in A with stride S from order m1 up to order m2.\nvoid ft_kernel_sph_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n\nft_rotation_plan * ft_plan_rottriangle(const int n, const double alpha, const double beta, const double gamma);\n\n/// Convert a single vector of triangular harmonic coefficients in A with stride S from order m2 down to order m1.\nvoid ft_kernel_tri_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n/// Convert a single vector of triangular harmonic coefficients in A with stride S from order m1 up to order m2.\nvoid ft_kernel_tri_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n\nft_rotation_plan * ft_plan_rotdisk(const int n, const double alpha, const double beta);\n\n/// Convert a single vector of disk harmonic coefficients in A with stride S from order m2 down to order m1.\nvoid ft_kernel_disk_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n/// Convert a single vector of disk harmonic coefficients in A with stride S from order m1 up to order m2.\nvoid ft_kernel_disk_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n\nft_rotation_plan * ft_plan_rotrectdisk(const int n, const double beta);\n\n/// Convert a single vector of rectangularized disk harmonic coefficients in A with stride S from order m2 down to order m1.\nvoid ft_kernel_rectdisk_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n/// Convert a single vector of rectangularized disk harmonic coefficients in A with stride S from order m1 up to order m2.\nvoid ft_kernel_rectdisk_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S);\n\nvoid ft_kernel_tet_hi2lo(const ft_rotation_plan * RP, const int L, const int m, double * A);\nvoid ft_kernel_tet_lo2hi(const ft_rotation_plan * RP, const int L, const int m, double * A);\n\n/// Data structure to store sines and cosines of Givens rotations for spin-weighted harmonics.\ntypedef struct ft_spin_rotation_plan_s ft_spin_rotation_plan;\n\n/// Destroy a \\ref ft_spin_rotation_plan.\nvoid ft_destroy_spin_rotation_plan(ft_spin_rotation_plan * SRP);\n\nft_spin_rotation_plan * ft_plan_rotspinsphere(const int n, const int s);\n\n/// Convert a single vector of spin-weighted spherical harmonic coefficients in A with stride S from order m down to order m%2.\nvoid ft_kernel_spinsph_hi2lo(const ft_spin_rotation_plan * SRP, const int m, ft_complex * A, const int S);\n/// Convert a single vector of spin-weighted spherical harmonic coefficients in A with stride S from order m%2 up to order m.\nvoid ft_kernel_spinsph_lo2hi(const ft_spin_rotation_plan * SRP, const int m, ft_complex * A, const int S);\n\n\nvoid ft_execute_sph_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M);\nvoid ft_execute_sph_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M);\n\nvoid ft_execute_sphv_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M);\nvoid ft_execute_sphv_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M);\n\nvoid ft_execute_tri_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M);\nvoid ft_execute_tri_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M);\n\nvoid ft_execute_disk_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M);\nvoid ft_execute_disk_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M);\n\nvoid ft_execute_rectdisk_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M);\nvoid ft_execute_rectdisk_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M);\n\nvoid ft_execute_tet_hi2lo(const ft_rotation_plan * RP1, const ft_rotation_plan * RP2, double * A, const int L, const int M);\nvoid ft_execute_tet_lo2hi(const ft_rotation_plan * RP1, const ft_rotation_plan * RP2, double * A, const int L, const int M);\n\nvoid ft_execute_spinsph_hi2lo(const ft_spin_rotation_plan * SRP, ft_complex * A, ft_complex * B, const int M);\nvoid ft_execute_spinsph_lo2hi(const ft_spin_rotation_plan * SRP, ft_complex * A, ft_complex * B, const int M);\n\n/// Data structure to store \\ref ft_rotation_plan \"ft_rotation_plan\"s, arrays to represent 1D orthogonal polynomial transforms and their inverses, and Greek parameters.\ntypedef struct {\n ft_rotation_plan ** RP;\n double * B;\n double ** P;\n double ** Pinv;\n double alpha;\n double beta;\n double gamma;\n double delta;\n int NRP;\n int NP;\n} ft_harmonic_plan;\n\n/// Destroy a \\ref ft_harmonic_plan.\nvoid ft_destroy_harmonic_plan(ft_harmonic_plan * P);\n\n/// Plan a spherical harmonic transform.\nft_harmonic_plan * ft_plan_sph2fourier(const int n);\n\n/// Transform a spherical harmonic expansion to a bivariate Fourier series.\nvoid ft_execute_sph2fourier(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n/// Transform a bivariate Fourier series to a spherical harmonic expansion.\nvoid ft_execute_fourier2sph(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n\nvoid ft_execute_sphv2fourier(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\nvoid ft_execute_fourier2sphv(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n\n/// Plan a triangular harmonic transform.\nft_harmonic_plan * ft_plan_tri2cheb(const int n, const double alpha, const double beta, const double gamma);\n\n/// Transform a triangular harmonic expansion to a bivariate Chebyshev series.\nvoid ft_execute_tri2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n/// Transform a bivariate Chebyshev series to a triangular harmonic expansion.\nvoid ft_execute_cheb2tri(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n\n/// Plan a disk harmonic transform.\nft_harmonic_plan * ft_plan_disk2cxf(const int n, const double alpha, const double beta);\n\n/// Transform a disk harmonic expansion to a Chebyshev--Fourier series.\nvoid ft_execute_disk2cxf(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n/// Transform a Chebyshev--Fourier series to a disk harmonic expansion.\nvoid ft_execute_cxf2disk(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n\n/// Plan a rectangularized disk harmonic transform.\nft_harmonic_plan * ft_plan_rectdisk2cheb(const int n, const double beta);\n\n/// Transform a rectangularized disk harmonic expansion to a Chebyshev series.\nvoid ft_execute_rectdisk2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n/// Transform a Chebyshev series to a rectangularized disk harmonic expansion.\nvoid ft_execute_cheb2rectdisk(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M);\n\n/// Plan a tetrahedral harmonic transform.\nft_harmonic_plan * ft_plan_tet2cheb(const int n, const double alpha, const double beta, const double gamma, const double delta);\n\n/// Transform a tetrahedral harmonic expansion to a trivariate Chebyshev series.\nvoid ft_execute_tet2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int L, const int M);\n/// Transform a trivariate Chebyshev series to a tetrahedral harmonic expansion.\nvoid ft_execute_cheb2tet(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int L, const int M);\n\n/// Data structure to store a \\ref ft_spin_rotation_plan, and various arrays to represent 1D orthogonal polynomial transforms.\ntypedef struct {\n ft_spin_rotation_plan * SRP;\n ft_complex * B;\n ft_complex * P1;\n ft_complex * P2;\n ft_complex * P1inv;\n ft_complex * P2inv;\n int s;\n} ft_spin_harmonic_plan;\n\n/// Destroy a \\ref ft_spin_harmonic_plan.\nvoid ft_destroy_spin_harmonic_plan(ft_spin_harmonic_plan * P);\n\n/// Plan a spin-weighted spherical harmonic transform.\nft_spin_harmonic_plan * ft_plan_spinsph2fourier(const int n, const int s);\n\n/// Transform a spin-weighted spherical harmonic expansion to a bivariate Fourier series.\nvoid ft_execute_spinsph2fourier(const char TRANS, const ft_spin_harmonic_plan * P, ft_complex * A, const int N, const int M);\n/// Transform a bivariate Fourier series to a spin-weighted spherical harmonic expansion.\nvoid ft_execute_fourier2spinsph(const char TRANS, const ft_spin_harmonic_plan * P, ft_complex * A, const int N, const int M);\n\n\nint ft_fftw_init_threads(void);\nvoid ft_fftw_plan_with_nthreads(const int n);\n\ntypedef struct {\n fftw_plan plantheta1;\n fftw_plan plantheta2;\n fftw_plan plantheta3;\n fftw_plan plantheta4;\n fftw_plan planphi;\n double * Y;\n} ft_sphere_fftw_plan;\n\n/// Destroy a \\ref ft_sphere_fftw_plan.\nvoid ft_destroy_sphere_fftw_plan(ft_sphere_fftw_plan * P);\n\nft_sphere_fftw_plan * ft_plan_sph_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]);\n/// Plan FFTW synthesis on the sphere.\nft_sphere_fftw_plan * ft_plan_sph_synthesis(const int N, const int M);\n/// Plan FFTW analysis on the sphere.\nft_sphere_fftw_plan * ft_plan_sph_analysis(const int N, const int M);\nft_sphere_fftw_plan * ft_plan_sphv_synthesis(const int N, const int M);\nft_sphere_fftw_plan * ft_plan_sphv_analysis(const int N, const int M);\n\n/// Execute FFTW synthesis on the sphere.\nvoid ft_execute_sph_synthesis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M);\n/// Execute FFTW analysis on the sphere.\nvoid ft_execute_sph_analysis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M);\n\nvoid ft_execute_sphv_synthesis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M);\nvoid ft_execute_sphv_analysis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M);\n\ntypedef struct {\n fftw_plan planxy;\n} ft_triangle_fftw_plan;\n\n/// Destroy a \\ref ft_triangle_fftw_plan.\nvoid ft_destroy_triangle_fftw_plan(ft_triangle_fftw_plan * P);\n\nft_triangle_fftw_plan * ft_plan_tri_with_kind(const int N, const int M, const fftw_r2r_kind kind0, const fftw_r2r_kind kind1);\n/// Plan FFTW synthesis on the triangle.\nft_triangle_fftw_plan * ft_plan_tri_synthesis(const int N, const int M);\n/// Plan FFTW analysis on the triangle.\nft_triangle_fftw_plan * ft_plan_tri_analysis(const int N, const int M);\n\n/// Execute FFTW synthesis on the triangle.\nvoid ft_execute_tri_synthesis(const char TRANS, const ft_triangle_fftw_plan * P, double * X, const int N, const int M);\n/// Execute FFTW analysis on the triangle.\nvoid ft_execute_tri_analysis(const char TRANS, const ft_triangle_fftw_plan * P, double * X, const int N, const int M);\n\ntypedef struct {\n fftw_plan planxyz;\n} ft_tetrahedron_fftw_plan;\n\nvoid ft_destroy_tetrahedron_fftw_plan(ft_tetrahedron_fftw_plan * P);\n\nft_tetrahedron_fftw_plan * ft_plan_tet_with_kind(const int N, const int L, const int M, const fftw_r2r_kind kind0, const fftw_r2r_kind kind1, const fftw_r2r_kind kind2);\nft_tetrahedron_fftw_plan * ft_plan_tet_synthesis(const int N, const int L, const int M);\nft_tetrahedron_fftw_plan * ft_plan_tet_analysis(const int N, const int L, const int M);\n\nvoid ft_execute_tet_synthesis(const char TRANS, const ft_tetrahedron_fftw_plan * P, double * X, const int N, const int L, const int M);\nvoid ft_execute_tet_analysis(const char TRANS, const ft_tetrahedron_fftw_plan * P, double * X, const int N, const int L, const int M);\n\ntypedef struct {\n fftw_plan planr1;\n fftw_plan planr2;\n fftw_plan planr3;\n fftw_plan planr4;\n fftw_plan plantheta;\n double * Y;\n} ft_disk_fftw_plan;\n\n/// Destroy a \\ref ft_disk_fftw_plan.\nvoid ft_destroy_disk_fftw_plan(ft_disk_fftw_plan * P);\n\nft_disk_fftw_plan * ft_plan_disk_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]);\n/// Plan FFTW synthesis on the disk.\nft_disk_fftw_plan * ft_plan_disk_synthesis(const int N, const int M);\n/// Plan FFTW analysis on the disk.\nft_disk_fftw_plan * ft_plan_disk_analysis(const int N, const int M);\n\n/// Execute FFTW synthesis on the disk.\nvoid ft_execute_disk_synthesis(const char TRANS, const ft_disk_fftw_plan * P, double * X, const int N, const int M);\n/// Execute FFTW analysis on the disk.\nvoid ft_execute_disk_analysis(const char TRANS, const ft_disk_fftw_plan * P, double * X, const int N, const int M);\n\ntypedef struct {\n fftw_plan planx1;\n fftw_plan planx2;\n fftw_plan plany;\n} ft_rectdisk_fftw_plan;\n\n/// Destroy a \\ref ft_rectdisk_fftw_plan.\nvoid ft_destroy_rectdisk_fftw_plan(ft_rectdisk_fftw_plan * P);\n\nft_rectdisk_fftw_plan * ft_plan_rectdisk_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]);\n/// Plan FFTW synthesis on the rectangularized disk.\nft_rectdisk_fftw_plan * ft_plan_rectdisk_synthesis(const int N, const int M);\n/// Plan FFTW analysis on the rectangularized disk.\nft_rectdisk_fftw_plan * ft_plan_rectdisk_analysis(const int N, const int M);\n\n/// Execute FFTW synthesis on the rectangularized disk.\nvoid ft_execute_rectdisk_synthesis(const char TRANS, const ft_rectdisk_fftw_plan * P, double * X, const int N, const int M);\n/// Execute FFTW analysis on the rectangularized disk.\nvoid ft_execute_rectdisk_analysis(const char TRANS, const ft_rectdisk_fftw_plan * P, double * X, const int N, const int M);\n\ntypedef struct {\n fftw_plan plantheta1;\n fftw_plan plantheta2;\n fftw_plan plantheta3;\n fftw_plan plantheta4;\n fftw_plan planphi;\n double * Y;\n int S;\n} ft_spinsphere_fftw_plan;\n\n/// Destroy a \\ref ft_spinsphere_fftw_plan.\nvoid ft_destroy_spinsphere_fftw_plan(ft_spinsphere_fftw_plan * P);\n\nint ft_get_spin_spinsphere_fftw_plan(const ft_spinsphere_fftw_plan * P);\n\nft_spinsphere_fftw_plan * ft_plan_spinsph_with_kind(const int N, const int M, const int S, const fftw_r2r_kind kind[2][1], const int sign);\n/// Plan FFTW synthesis on the sphere with spin.\nft_spinsphere_fftw_plan * ft_plan_spinsph_synthesis(const int N, const int M, const int S);\n/// Plan FFTW analysis on the sphere with spin.\nft_spinsphere_fftw_plan * ft_plan_spinsph_analysis(const int N, const int M, const int S);\n\n/// Execute FFTW synthesis on the sphere with spin.\nvoid ft_execute_spinsph_synthesis(const char TRANS, const ft_spinsphere_fftw_plan * P, ft_complex * X, const int N, const int M);\n/// Execute FFTW analysis on the sphere with spin.\nvoid ft_execute_spinsph_analysis(const char TRANS, const ft_spinsphere_fftw_plan * P, ft_complex * X, const int N, const int M);\n\ntypedef struct {\n ft_banded ** B;\n ft_triangular_banded ** T;\n int n;\n} ft_gradient_plan;\n\nvoid ft_destroy_gradient_plan(ft_gradient_plan * P);\n\nft_gradient_plan * ft_plan_sph_gradient(const int n);\n\nvoid ft_execute_sph_gradient(ft_gradient_plan * P, double * U, double * Ut, double * Up, const int N, const int M);\nvoid ft_execute_sph_curl(ft_gradient_plan * P, double * U, double * Ut, double * Up, const int N, const int M);\n\ntypedef struct {\n ft_triangular_banded ** T;\n ft_banded_qr ** F;\n double * X;\n int n;\n} ft_helmholtzhodge_plan;\n\nvoid ft_destroy_helmholtzhodge_plan(ft_helmholtzhodge_plan * P);\n\nft_helmholtzhodge_plan * ft_plan_sph_helmholtzhodge(const int n);\n\nvoid ft_execute_sph_helmholtzhodge(ft_helmholtzhodge_plan * P, double * U1, double * U2, double * V1, double * V2, const int N, const int M);\n\n/*!\n \\brief A static struct to store an orthogonal matrix \\f$Q \\in \\mathbb{R}^{3\\times3}\\f$, such that \\f$Q^\\top Q = I\\f$.\n \\f$Q\\f$ has column-major storage.\n*/\ntypedef struct {\n double Q[9];\n} ft_orthogonal_transformation;\n\n/*!\n \\brief Every orthogonal matrix \\f$Q \\in \\mathbb{R}^{3\\times3}\\f$ can be decomposed as a product of \\f$ZYZ\\f$ Euler angles and, if necessary, a reflection \\f$R\\f$ about the \\f$xy\\f$-plane.\n \\f[\n Q = ZYZR,\n \\f]\n where the \\f$z\\f$-axis rotations are:\n \\f[\n Z = \\begin{pmatrix} c & -s & 0\\\\ s & c & 0\\\\ 0 & 0 & 1\\end{pmatrix},\n \\f]\n the \\f$y\\f$-axis rotation is:\n \\f[\n Y = \\begin{pmatrix} c & 0 & -s\\\\ 0 & 1 & 0\\\\ s & 0 & c\\end{pmatrix},\n \\f]\n and the potential reflection is:\n \\f[\n R = \\begin{pmatrix} 1 & 0 & 0\\\\ 0 & 1 & 0\\\\ 0 & 0 & \\pm 1\\end{pmatrix}.\n \\f]\n The reflection is stored as an integer `sign` corresponding to the bottom right entry.\n*/\ntypedef struct {\n double s[3];\n double c[3];\n int sign;\n} ft_ZYZR;\n\n/*!\n \\brief A static struct to store a reflection about the plane \\f$w\\cdot x = 0\\f$ in \\f$\\mathbb{R}^3\\f$.\n*/\ntypedef struct {\n double w[3];\n} ft_reflection;\n\nft_ZYZR ft_create_ZYZR(ft_orthogonal_transformation Q);\n\nvoid ft_apply_ZYZR(ft_ZYZR Q, ft_orthogonal_transformation * U);\n\nvoid ft_apply_reflection(ft_reflection Q, ft_orthogonal_transformation * U);\n\nvoid ft_execute_sph_polar_rotation(double * A, const int N, const int M, double s, double c);\n\nvoid ft_execute_sph_polar_reflection(double * A, const int N, const int M);\n\ntypedef struct {\n ft_symmetric_tridiagonal_symmetric_eigen * F11;\n ft_symmetric_tridiagonal_symmetric_eigen * F21;\n ft_symmetric_tridiagonal_symmetric_eigen * F12;\n ft_symmetric_tridiagonal_symmetric_eigen * F22;\n int l;\n} ft_partial_sph_isometry_plan;\n\ntypedef struct {\n ft_partial_sph_isometry_plan ** F;\n int n;\n} ft_sph_isometry_plan;\n\nvoid ft_destroy_partial_sph_isometry_plan(ft_partial_sph_isometry_plan * F);\n\nvoid ft_destroy_sph_isometry_plan(ft_sph_isometry_plan * F);\n\nft_partial_sph_isometry_plan * ft_plan_partial_sph_isometry(const int l);\n\nft_sph_isometry_plan * ft_plan_sph_isometry(const int n);\n\nvoid ft_execute_sph_yz_axis_exchange(ft_sph_isometry_plan * J, double * A, const int N, const int M);\n\nvoid ft_execute_sph_isometry(ft_sph_isometry_plan * J, ft_ZYZR Q, double * A, const int N, const int M);\n\nvoid ft_execute_sph_rotation(ft_sph_isometry_plan * J, const double alpha, const double beta, const double gamma, double * A, const int N, const int M);\n\nvoid ft_execute_sph_reflection(ft_sph_isometry_plan * J, ft_reflection W, double * A, const int N, const int M);\n\nvoid ft_execute_sph_orthogonal_transformation(ft_sph_isometry_plan * J, ft_orthogonal_transformation Q, double * A, const int N, const int M);\n\n#endif // FASTTRANSFORMS_H\n", "meta": {"hexsha": "cf0d6e148be9135f4fa9ec497c817ed98677570d", "size": 39478, "ext": "h", "lang": "C", "max_stars_repo_path": "src/fasttransforms.h", "max_stars_repo_name": "MikaelSlevinsky/FastTransforms", "max_stars_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2018-05-05T04:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T00:27:31.000Z", "max_issues_repo_path": "src/fasttransforms.h", "max_issues_repo_name": "MikaelSlevinsky/FastTransforms", "max_issues_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 51.0, "max_issues_repo_issues_event_min_datetime": "2018-06-28T15:01:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T15:53:04.000Z", "max_forks_repo_path": "src/fasttransforms.h", "max_forks_repo_name": "MikaelSlevinsky/FastTransforms", "max_forks_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-06-11T15:21:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T21:29:14.000Z", "avg_line_length": 60.7353846154, "max_line_length": 216, "alphanum_fraction": 0.7723035615, "num_tokens": 11338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.47052665922990033}} {"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*/\n\n#include \n#include \n#include \n#include \n\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_step_real (gsl_complex a)\n{ \n gsl_complex z;\n\t\n if (GSL_REAL(a) < 0)\n {\n GSL_SET_COMPLEX (&z, 0, 0);\n }\n else\n {\n GSL_SET_COMPLEX (&z, 1, 0);\n }\n \n return z;\n}\n\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_min_real (gsl_complex a, gsl_complex b)\n{\n gsl_complex z;\n double min;\n\t\n /* just consider real parts */\n min = GSL_REAL(a) < GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b);\n GSL_SET_COMPLEX (&z, min, 0);\n\t\n return z;\n}\n\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_max_real (gsl_complex a, gsl_complex b)\n{\n gsl_complex z;\n double max;\n\t\n /* just consider real parts */\n max = GSL_REAL(a) > GSL_REAL(b) ? GSL_REAL(a) : GSL_REAL(b);\n GSL_SET_COMPLEX (&z, max, 0);\n\t\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_carg (gsl_complex a)\n{ \n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, gsl_complex_arg(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_cabs (gsl_complex a)\n{ \n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, gsl_complex_abs(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_cabs2 (gsl_complex a)\n{ \n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, gsl_complex_abs2(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_clogabs (gsl_complex a)\n{ \n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, gsl_complex_logabs(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_erf (gsl_complex a)\n{ \n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, gsl_sf_erf(GSL_REAL(a)), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_arctan2 (gsl_complex a, gsl_complex b)\n{ \n gsl_complex z, p;\n\n if(GSL_REAL(b) != 0.0)\n {\n z = gsl_complex_arctan(gsl_complex_div(a, b));\n if(GSL_REAL(b) < 0.0){\n\tGSL_SET_COMPLEX (&p, M_PI, 0);\n\tif(GSL_REAL(a) >= 0.0)\n\t z = gsl_complex_add(z, p);\n\telse\n\t z = gsl_complex_sub(z, p);\n }\n }\n else\n {\n if(GSL_REAL(a) >= 0.0)\n\t{\n\t GSL_SET_COMPLEX (&z, M_PI/2.0, 0.0);\n\t}\n else\n\t{\n\t GSL_SET_COMPLEX (&z, -M_PI/2.0, 0.0);\n\t}\n }\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_realpart (gsl_complex a)\n{\n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, GSL_REAL(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_imagpart (gsl_complex a)\n{\n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, GSL_IMAG(a), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_round (gsl_complex a)\n{\n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, trunc(GSL_REAL(a)), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_ceiling (gsl_complex a)\n{\n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, ceil(GSL_REAL(a)), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_floor (gsl_complex a)\n{\n gsl_complex z;\n\n GSL_SET_COMPLEX (&z, floor(GSL_REAL(a)), 0);\n\n return z;\n}\n\n/* ------------------------------------------------------ */\nvoid gsl_complex_rand_seed(long a)\n{\n srandom(a);\n}\n\n/* ------------------------------------------------------ */\ngsl_complex gsl_complex_rand (gsl_complex a)\n{\n\n double r = random()/((double) RAND_MAX);\n return gsl_complex_rect(r, 0.0);\n}\n\n", "meta": {"hexsha": "1842fb8a2941a54e1e7ea9e7edcc47e7759c5aa3", "size": 4562, "ext": "c", "lang": "C", "max_stars_repo_path": "liboct_parser/gsl_userdef.c", "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "liboct_parser/gsl_userdef.c", "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_forks_repo_path": "liboct_parser/gsl_userdef.c", "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 21.0230414747, "max_line_length": 69, "alphanum_fraction": 0.5280578694, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.47013090388714635}} {"text": "#include \n#include \"sweeny_dc.h\"\n#include \n#include \n#include \"../src/dyncon.h\"\n#include \n\n\n#define MIN(a,b) a<=b ? a: b\n#define MAX(a,b) a>=b? a:b\nstatic char verbose = 0;\nstatic char equilibration=1;\nstatic char setup=0;\n\nstatic __u32 DX;\nstatic __u32 seed;\nstatic __u32 cutoff;\nstatic __u32 steps;\nstatic double beta;\nstatic double coupling;\nstatic double q;\nstatic double rnd_num;\n\nstatic double v;\nstatic __u32 j=0;\nstatic __s8 dB = 0,dN=0;\nstatic gsl_rng *r;\nstatic Edge *cEdge;\nstatic double rcWeights[4]; // array with precalculated mc weights\nstatic double p_min_del,p_max_del, p_min_ins,p_max_ins;\n\nstatic __u32 *num_bonds, *num_cluster, *size_giant;\nstatic __u64 *sec_cs_moment,*four_cs_moment;\n\n/******************************************************************************\n *****************************************************************************/\nstatic void extract_observables(__u32 i) {\n static __u32 clust_cnt=0;\n static __u64 sum=0,sum_2=0;\n static __u32 maxc=0;\n static s_tree *c;\n num_bonds[i] = nte + te;\n c = levels[0]->head;\n while(c) {\n clust_cnt++;\n sum += pow(c->root->n,2);//*c->root->n;\n sum_2 += pow(c->root->n,4);\n if(c->root->n > maxc)\n maxc = c->root->n;\n c = c->next;\n }\n num_cluster[i] = clust_cnt;\n size_giant[i] = maxc;\n sec_cs_moment[i] = sum;\n four_cs_moment[i] = sum_2;\n sum=sum_2=0;\n maxc = 0;\n clust_cnt=0;\n}\n\n/******************************************************************************\n *****************************************************************************/\n\nstatic inline void mcStep(void) {\n // get a randomly selected edge \n cEdge = &adjMatrix[gsl_rng_uniform_int(r,2*DX*DX)];\n\n\trnd_num = gsl_rng_uniform(r);\n \tif(ACTIVE_EDGE(cEdge)) { //edge is active hence delete it\n\t dB = -1;\n\t if(rnd_num < p_min_del) {\n\t delete_dc(cEdge);\n\t }\n\t else {\n\t if(rnd_num < p_max_del) {\n\t\tdN = delete_dc(cEdge);\n\t\tif(rnd_num >= rcWeights[dB == -1? dN : 2-dN]) \n\t\t insert_dc(cEdge);\n\t }\n\t\n\t }\n\n\t}\n else {\t\n // Insert cedge. If adjacent vertices are already connected, the new \n // edge will be a non-tree edge, i.e. dN = 0\n dB = 1;\n if(rnd_num < p_min_ins) {\n\t insert_dc(cEdge);\n\t}\n\telse {\n\t if(rnd_num < p_max_ins) {\n\t dN = connected_dc_e(cEdge,1) ? 0: -1;\n\t dB = 1;\n\t if(rnd_num < rcWeights[dB == -1? dN : 2-dN])\n\t\tinsert_dc(cEdge);\n\t }\n\n\t}\n }\n\n\n\n\n\n}\n/******************************************************************************\n *****************************************************************************/\nstatic inline void sweep() {\n for(j=0;j<2*DX*DX;j++)mcStep();\n}\n/******************************************************************************\n *****************************************************************************/\nchar init_sweeny_dc(double _q,unsigned int _l,double _beta,double _coupl,\n unsigned int _cutoff,unsigned _tslength,unsigned int rng_seed,\n void *ts_0,void *ts_1,void * ts_2,void *ts_3, void *ts_4) {\n\n q = _q;\n DX = _l;\n beta = _beta;\n coupling = _coupl;\n cutoff = _cutoff;\n steps = _tslength;\n seed = rng_seed;\n num_bonds = (__u32 *)ts_0;\n num_cluster = (__u32 *)ts_1;\n size_giant = (__u32 *)ts_2;\n sec_cs_moment = (__u64 *)ts_3;\n four_cs_moment = (__u64 *)ts_4;\n\n r = gsl_rng_alloc(gsl_rng_mt19937);\n gsl_rng_set(r,seed);\n v = exp(coupling*beta) - 1.; // >0\n rcWeights[0] = pow(v,-1); //db==-1,dN==0\n rcWeights[1] = rcWeights[0]*q; //db==-1,dN=1\n rcWeights[2] = v; //db==1,dN==0\n rcWeights[3] = v*pow(q,-1); //db==1,dN==-1\n p_min_del = MIN(rcWeights[0],rcWeights[1]); \n p_max_del = MAX(rcWeights[0],rcWeights[1]);\n p_min_ins = MIN(rcWeights[2],rcWeights[3]);\n p_max_ins = MAX(rcWeights[2],rcWeights[3]); \n return setup=(r && init_dc(DX));\n\n}\n \n \n/******************************************************************************\n *****************************************************************************/\nvoid destroy_sweeny_dc(void) {\n if(setup) {\n gsl_rng_free(r);\n destroy_dc();\n }\n setup=0;\n}\n/******************************************************************************\n *****************************************************************************/\nchar simulate_sweeny_dc(void) {\n if(!setup) return 0;\n __u32 i;\n for(i=0;i\n#include \n#include \n#include \n\ntypedef struct\n{\n double step;\n double max_step;\n gsl_vector *x1;\n gsl_vector *g1;\n}\nsteepest_descent_state_t;\n\nstatic int\nsteepest_descent_alloc (void *vstate, size_t n)\n{\n steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;\n\n state->x1 = gsl_vector_alloc (n);\n\n if (state->x1 == NULL)\n {\n GSL_ERROR (\"failed to allocate space for x1\", GSL_ENOMEM);\n }\n\n state->g1 = gsl_vector_alloc (n);\n\n if (state->g1 == NULL)\n {\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for g1\", GSL_ENOMEM);\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nsteepest_descent_set (void *vstate, gsl_multimin_function_fdf * fdf,\n const gsl_vector * x, double *f,\n gsl_vector * gradient, double step_size)\n{\n steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;\n\n GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x, f, gradient);\n\n state->step = step_size;\n state->max_step = step_size;\n\n return GSL_SUCCESS;\n}\n\n\nstatic void\nsteepest_descent_free (void *vstate)\n{\n steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;\n\n gsl_vector_free (state->x1);\n gsl_vector_free (state->g1);\n}\n\nstatic int\nsteepest_descent_restart (void *vstate)\n{\n steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;\n\n state->step = state->max_step;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nsteepest_descent_iterate (void *vstate, gsl_multimin_function_fdf * fdf,\n gsl_vector * x, double *f,\n gsl_vector * gradient, gsl_vector * dx)\n{\n steepest_descent_state_t *state = (steepest_descent_state_t *) vstate;\n\n gsl_vector *x1 = state->x1;\n gsl_vector *g1 = state->g1;\n\n double f0 = *f;\n double f1, fm, f_trial;\n double step0 = 0.0, step1, stepm, step_trial, step = state->step;\n size_t iter = 0;\n\n /* compute new trial point at x1= x - step * dir, where dir is the\n normalized gradient */\n\n double gnorm = gsl_blas_dnrm2 (gradient);\n\n gsl_vector_set_zero (dx);\n gsl_blas_daxpy (-step / gnorm, gradient, dx);\n\n gsl_vector_memcpy (x1, x);\n gsl_blas_daxpy (1.0, dx, x1);\n\n /* evaluate function and gradient at new point x1 */\n\n GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x1, &f1, g1);\n\n if (f1 < f0)\n {\n state->step = 2.0 * step;\n\n gsl_vector_memcpy (x, x1);\n gsl_vector_memcpy (gradient, g1);\n\n *f = f1;\n\n return GSL_SUCCESS;\n }\n\n step1 = step;\n\ntrial:\n\n stepm = 0.5 * step1;\n\n gsl_vector_set_zero (dx);\n gsl_blas_daxpy (-stepm / gnorm, gradient, dx);\n \n gsl_vector_memcpy (x1, x);\n gsl_blas_daxpy (1.0, dx, x1);\n\n fm = GSL_MULTIMIN_FN_EVAL_F (fdf, x1);\n printf(\"trying stepm = %.18e fm=%g\\n\", stepm, fm);\n if (fm >= f0)\n {\n /* downhill step failed, reduce step-size and try again */\n f1 = fm;\n step1 = stepm;\n goto trial;\n }\n\n /* We now have a triplet (0,f0) (stepm, fm) (step1, f1) */\n\nminimize:\n iter++;\n\n if ((stepm - step0) > (step1 - stepm))\n {\n step_trial = stepm - 0.38 * (stepm - step0);\n }\n else\n {\n step_trial = stepm + 0.38 * (step1 - stepm);\n }\n \n gsl_vector_set_zero (dx);\n gsl_blas_daxpy (-step_trial / gnorm, gradient, dx);\n \n gsl_vector_memcpy (x1, x);\n gsl_blas_daxpy (1.0, dx, x1);\n \n f_trial = GSL_MULTIMIN_FN_EVAL_F (fdf, x1);\n \n if (f_trial > fm)\n {\n if (step_trial < stepm)\n {\n step0 = step_trial;\n f0 = f_trial;\n }\n else\n {\n step1 = step_trial;\n f1 = f_trial;\n }\n }\n else\n {\n if (step_trial < stepm)\n {\n step1 = stepm;\n f1 = fm;\n }\n else\n {\n step0 = stepm;\n f0 = fm;\n }\n\n stepm = step_trial;\n fm = f_trial;\n }\n\n printf(\"f = %.18e\\n\", fm);\n \n if (iter > 100) \n {\n gsl_vector_set_zero (dx);\n gsl_blas_daxpy (-stepm / gnorm, gradient, dx);\n gsl_blas_daxpy (1.0, dx, x);\n \n GSL_MULTIMIN_FN_EVAL_DF (fdf, x, gradient);\n *f = fm;\n state->step = stepm;\n\n return GSL_SUCCESS;\n }\n\n goto minimize;\n}\n\nstatic const gsl_multimin_fdfminimizer_type steepest_descent_type =\n { \"steepest_descent\", /* name */\n sizeof (steepest_descent_state_t),\n &steepest_descent_alloc,\n &steepest_descent_set,\n &steepest_descent_iterate,\n &steepest_descent_restart,\n &steepest_descent_free\n};\n\nconst gsl_multimin_fdfminimizer_type\n *gsl_multimin_fdfminimizer_steepest_descent = &steepest_descent_type;\n", "meta": {"hexsha": "e7727bdd9e18f734ea588a9816cce8eb2a5c4fa3", "size": 5481, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/sd2.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/multimin/sd2.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/multimin/sd2.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": 22.8375, "max_line_length": 81, "alphanum_fraction": 0.6407589856, "num_tokens": 1671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46960959746625053}} {"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"dnest.h\"\n#include \"model2.h\"\n\nint which_level_update;\nint num_data_points;\nint num_params;\nDNestFptrSet *fptrset_thismodel2;\n\nDataType *data;\nvoid *best_model_thismodel, *best_model_std_thismodel;\n\nvoid model2()\n{ \n int i, argc=0, narg=6;\n char **argv;\n\n argv = malloc(narg*sizeof(char *));\n for(i=0; ifrom_prior = from_prior_thismodel2;\n fptrset_thismodel2->log_likelihoods_cal = log_likelihoods_cal_thismodel2;\n fptrset_thismodel2->log_likelihoods_cal_initial = log_likelihoods_cal_thismodel2;\n fptrset_thismodel2->log_likelihoods_cal_restart = log_likelihoods_cal_thismodel2;\n fptrset_thismodel2->perturb = perturb_thismodel2;\n fptrset_thismodel2->print_particle = print_particle_thismodel2;\n fptrset_thismodel2->restart_action = restart_action_model2;\n \n /* load data */\n if(thistask == 0)\n {\n data_load_thismodel2();\n }\n MPI_Bcast(data, num_data_points*sizeof(DataType), MPI_BYTE, 0, MPI_COMM_WORLD);\n \n /* run dnest */\n dnest(argc, argv, fptrset_thismodel2, num_params, NULL, NULL, NULL, \"./\", \"OPTIONS2\", NULL, NULL);\n \n /* free memory */\n free(data);\n dnest_free_fptrset(fptrset_thismodel2);\n\n for(i=0; i (size_levels - 20)?(size_levels-20):which_level_update;\n if(which_level > 0)\n {\n limit1 = limits[(which_level-1) * num_params *2 + which *2 ];\n limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1];\n width = (limit2 - limit1);\n }\n\n\tif(which == 0)\n\t{\n if(which_level_update == 0)\n {\n width = 1E3;\n }\n\t\tlogH -= -0.5*pow(params[0]/1E3, 2);\n\t\tparams[0] += width*dnest_randh();\n\t\tlogH += -0.5*pow(params[0]/1E3, 2);\n\t}\n\telse if(which == 1)\n\t{\n if(which_level_update == 0)\n {\n width = 1E3;\n }\n\n\t\tlogH -= -0.5*pow(params[1]/1E3, 2);\n\t\tparams[1] += width*dnest_randh();\n\t\tlogH += -0.5*pow(params[1]/1E3, 2);\n\t}\n\telse\n\t{\n if(which_level_update == 0)\n {\n limit1 = -10.0;\n limit2 = 10.0;\n width = 20.0;\n }\n else\n {\n limit1 = log(limit1);\n limit2 = log(limit2);\n width = limit2 - limit1;\n }\n \n\t\t// Usual log-uniform prior trick\n\t\tparams[2] = log(params[2]);\n\t\tparams[2] += width*dnest_randh();\n\t\tdnest_wrap(&(params[2]), -10.0, 10.0);\n\t\tparams[2] = exp(params[2]);\n\t}\n \n return logH;\n}\n/*=======================================================*/\n\nvoid print_particle_thismodel2(FILE *fp, const void *model)\n{\n int i;\n double *params = (double *)model;\n for(i=0; i\n#include \n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint add_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\nint add_deltas_d (double *X, const int iscolmajor, const int R, const int C, const int dim, const int N);\n\n\nint add_deltas_s (float *X, const int iscolmajor, const int R, const int C, const int dim, const int N)\n{\n const float z = 0.0f;\n const int No = R*C/2;\n int r, c, n;\n float sc = 1.0f;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in add_deltas_s: R (nrows X) must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in add_deltas_s: C (ncols X) must be positive\\n\"); return 1; }\n if (N<1) { fprintf(stderr,\"error in add_deltas_s: N (delta winlength) must be positive\\n\"); return 1; }\n if (dim==0 && C%2!=0) { fprintf(stderr,\"error in add_deltas_s: C (ncols X) must be even for dim==0\\n\"); return 1; }\n if (dim==1 && R%2!=0) { fprintf(stderr,\"error in add_deltas_s: R (nrows X) must be even for dim==1\\n\"); return 1; }\n\n //Get sc (normalizer)\n for (n=2; n<=N; n++) { sc += n*n; }\n sc = 0.5f/sc;\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n cblas_scopy(No,&z,0,&X[No],1);\n for (c=0; c\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint lsf2poly_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);\nint lsf2poly_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);\n\n\nint lsf2poly_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)\n{\n const float z = 0.0f, o = 1.0f;\n const int F = (dim==0) ? R : C; //num LSFs\n const int nr = 2*F + 2; //length roots\n const int P = F + 2; //length psym and pasym\n const int Po = P - 1; //num output poly coeffs\n int r, c, p, f;\n float *roots, *psym, *pasym;\n\n //Checks\n if (R<1) { fprintf(stderr,\"error in lsf2poly_s: nrows X must be positive\\n\"); return 1; }\n if (C<1) { fprintf(stderr,\"error in lsf2poly_s: ncols X must be positive\\n\"); return 1; }\n\n //Initialize\n if (!(psym=(float *)malloc((size_t)(2*P)*sizeof(float)))) { fprintf(stderr,\"error in lsf2poly_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(pasym=(float *)malloc((size_t)(2*P)*sizeof(float)))) { fprintf(stderr,\"error in lsf2poly_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(roots=(float *)malloc((size_t)(2*nr)*sizeof(float)))) { fprintf(stderr,\"error in lsf2poly_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n roots[0] = o; roots[nr] = -o; roots[1] = roots[nr+1] = z;\n\n if (dim==0)\n {\n if (iscolmajor)\n {\n //cblas_scopy(C,&o,0,Y,Po);\n for (c=0; c0; p--)\n {\n pasym[2*p] = fmaf(-roots[4*r],pasym[2*p-2],fmaf(roots[4*r+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fmaf(-roots[4*r],pasym[2*p-1],fmaf(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fmaf(-roots[4*r+2],psym[2*p-2],fmaf(roots[4*r+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fmaf(-roots[4*r+2],psym[2*p-1],fmaf(-roots[4*r+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (r=0; r0; p--)\n {\n pasym[2*p] = fmaf(-roots[4*r],pasym[2*p-2],fmaf(roots[4*r+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fmaf(-roots[4*r],pasym[2*p-1],fmaf(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fmaf(-roots[4*r+2],psym[2*p-2],fmaf(roots[4*r+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fmaf(-roots[4*r+2],psym[2*p-1],fmaf(-roots[4*r+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (r=0; r0; p--)\n {\n pasym[2*p] = fmaf(-roots[4*c],pasym[2*p-2],fmaf(roots[4*c+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fmaf(-roots[4*c],pasym[2*p-1],fmaf(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fmaf(-roots[4*c+2],psym[2*p-2],fmaf(roots[4*c+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fmaf(-roots[4*c+2],psym[2*p-1],fmaf(-roots[4*c+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (c=0; c0; p--)\n {\n pasym[2*p] = fmaf(-roots[4*c],pasym[2*p-2],fmaf(roots[4*c+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fmaf(-roots[4*c],pasym[2*p-1],fmaf(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fmaf(-roots[4*c+2],psym[2*p-2],fmaf(roots[4*c+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fmaf(-roots[4*c+2],psym[2*p-1],fmaf(-roots[4*c+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (c=0; c0; p--)\n {\n pasym[2*p] = fma(-roots[4*r],pasym[2*p-2],fma(roots[4*r+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fma(-roots[4*r],pasym[2*p-1],fma(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fma(-roots[4*r+2],psym[2*p-2],fma(roots[4*r+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fma(-roots[4*r+2],psym[2*p-1],fma(-roots[4*r+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (r=0; r0; p--)\n {\n pasym[2*p] = fma(-roots[4*r],pasym[2*p-2],fma(roots[4*r+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fma(-roots[4*r],pasym[2*p-1],fma(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fma(-roots[4*r+2],psym[2*p-2],fma(roots[4*r+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fma(-roots[4*r+2],psym[2*p-1],fma(-roots[4*r+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (r=0; r0; p--)\n {\n pasym[2*p] = fma(-roots[4*c],pasym[2*p-2],fma(roots[4*c+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fma(-roots[4*c],pasym[2*p-1],fma(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fma(-roots[4*c+2],psym[2*p-2],fma(roots[4*c+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fma(-roots[4*c+2],psym[2*p-1],fma(-roots[4*c+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (c=0; c0; p--)\n {\n pasym[2*p] = fma(-roots[4*c],pasym[2*p-2],fma(roots[4*c+1],pasym[2*p-1],pasym[2*p]));\n pasym[2*p+1] = fma(-roots[4*c],pasym[2*p-1],fma(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1]));\n psym[2*p] = fma(-roots[4*c+2],psym[2*p-2],fma(roots[4*c+3],psym[2*p-1],psym[2*p]));\n psym[2*p+1] = fma(-roots[4*c+2],psym[2*p-1],fma(-roots[4*c+3],psym[2*p-2],psym[2*p+1]));\n }\n }\n for (c=0; c\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n/*--------ROUTINE: taper_cl ------\nTASK:n Apply cosine tapering to Cls to reduce aliasing\nINPUT: number of ell bins for Cl, ell vector, C_ell vector, limits for tapering\n e.g., ell_limits=[low_ell_limit_lower,low_ell_limit_upper,high_ell_limit_lower,high_ell_limit_upper]\n*/\nstatic int taper_cl(int n_ell,double *ell,double *cl, double *ell_limits)\n{\n\n for(int i=0;iell_limits[3]) {\n cl[i]=0;//ell outside desirable range\n continue;\n }\n if(ell[i]>=ell_limits[1] && ell[i]<=ell_limits[2])\n continue;//ell within good ell range\n\n if(ell[i]ell_limits[2])//tapering high ell\n cl[i]*=cos((ell[i]-ell_limits[2])/(ell_limits[3]-ell_limits[2])*M_PI/2.);\n }\n\n return 0;\n}\n\n/*--------ROUTINE: ccl_tracer_corr_fftlog ------\nTASK: For a given tracer, get the correlation function\n Following function takes a function to calculate angular cl as well.\n By default above function will call it using ccl_angular_cl\nINPUT: type of tracer, number of theta values to evaluate = NL, theta vector\n */\nstatic void ccl_tracer_corr_fftlog(ccl_cosmology *cosmo,\n int n_ell,double *ell,double *cls,\n int n_theta,double *theta,double *wtheta,\n int corr_type,int do_taper_cl,double *taper_cl_limits,\n int *status) {\n int i;\n double *l_arr,*cl_arr,*th_arr,*wth_arr;\n\n l_arr=ccl_log_spacing(cosmo->spline_params.ELL_MIN_CORR,cosmo->spline_params.ELL_MAX_CORR,cosmo->spline_params.N_ELL_CORR);\n if(l_arr==NULL) {\n *status=CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n cl_arr=malloc(cosmo->spline_params.N_ELL_CORR*sizeof(double));\n if(cl_arr==NULL) {\n free(l_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n\n //Interpolate input Cl into array needed for FFTLog\n ccl_f1d_t *cl_spl=ccl_f1d_t_new(n_ell,ell,cls,cls[0],0,\n\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t ccl_f1d_extrap_logx_logy,\n\t\t\t\t status);\n if(cl_spl==NULL) {\n free(l_arr);\n free(cl_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t \"ccl_correlation.c: ccl_tracer_corr_fftlog \"\n\t\t\t\t \"ran out of memory\\n\");\n return;\n }\n\n for(i=0;ispline_params.N_ELL_CORR;i++)\n cl_arr[i]=ccl_f1d_t_eval(cl_spl,l_arr[i]);\n ccl_f1d_t_free(cl_spl);\n\n if (do_taper_cl)\n taper_cl(cosmo->spline_params.N_ELL_CORR,l_arr,cl_arr,taper_cl_limits);\n\n th_arr=malloc(sizeof(double)*cosmo->spline_params.N_ELL_CORR);\n if(th_arr==NULL) {\n free(l_arr);\n free(cl_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n wth_arr=(double *)malloc(sizeof(double)*cosmo->spline_params.N_ELL_CORR);\n if(wth_arr==NULL) {\n free(l_arr);\n free(cl_arr);\n free(th_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n\n for(i=0;ispline_params.N_ELL_CORR;i++)\n th_arr[i]=0;\n //Although set here to 0, theta is modified by FFTlog to obtain the correlation at ~1/l\n\n int i_bessel=0;\n if(corr_type==CCL_CORR_GG) i_bessel=0;\n if(corr_type==CCL_CORR_GL) i_bessel=2;\n if(corr_type==CCL_CORR_LP) i_bessel=0;\n if(corr_type==CCL_CORR_LM) i_bessel=4;\n ccl_fftlog_ComputeXi2D(i_bessel,0,\n\t\t\t 1, cosmo->spline_params.N_ELL_CORR,l_arr,&cl_arr,\n\t\t\t th_arr,&wth_arr, status);\n\n // Interpolate to output values of theta\n ccl_f1d_t *wth_spl=ccl_f1d_t_new(cosmo->spline_params.N_ELL_CORR,th_arr,\n\t\t\t\t wth_arr,wth_arr[0],0,\n\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t ccl_f1d_extrap_const, status);\n if (wth_spl == NULL) {\n free(l_arr);\n free(cl_arr);\n free(th_arr);\n free(wth_arr);\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n for(i=0;ith;\n\n cl=ccl_f1d_t_eval(p->cl_spl,l);\n\n jbes=gsl_sf_bessel_Jn(p->i_bessel,x);\n\n return l*jbes*cl;\n}\n\nstatic void ccl_tracer_corr_bessel(ccl_cosmology *cosmo,\n int n_ell,double *ell,double *cls,\n int n_theta,double *theta,double *wtheta,\n int corr_type,int *status) {\n corr_int_par cp;\n ccl_f1d_t *cl_spl = NULL;\n cl_spl = ccl_f1d_t_new(n_ell, ell, cls, cls[0], 0,\n\t\t\t ccl_f1d_extrap_const,\n\t\t\t ccl_f1d_extrap_logx_logy, status);\n if(cl_spl == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\\n\");\n return;\n }\n\n int ith, gslstatus;\n double result,eresult;\n gsl_function F;\n gsl_integration_workspace *w = NULL;\n int local_status;\n\n#pragma omp parallel default(none) \\\n shared(cosmo, status, wtheta, n_ell, ell, cls, \\\n\t\t\t corr_type, cl_spl, theta, n_theta)\t\\\n private(w, F, result, eresult, local_status, ith, \\\n\t\t\t gslstatus, cp)\n {\n local_status = *status;\n\n switch(corr_type) {\n case CCL_CORR_GG:\n cp.i_bessel = 0;\n break;\n case CCL_CORR_GL:\n cp.i_bessel = 2;\n break;\n case CCL_CORR_LP:\n cp.i_bessel = 0;\n break;\n case CCL_CORR_LM:\n cp.i_bessel = 4;\n break;\n }\n\n cp.cl_spl = cl_spl;\n\n w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\n if (w == NULL) {\n local_status = CCL_ERROR_MEMORY;\n }\n F.function = &corr_bessel_integrand;\n F.params = &cp;\n\n #pragma omp for schedule(dynamic)\n for(ith=0; ith < n_theta; ith++) {\n if (local_status == 0) {\n cp.th = theta[ith]*M_PI/180;\n //TODO: Split into intervals between first bessel zeros before integrating\n //This will help both speed and accuracy of the integral.\n gslstatus = gsl_integration_qag(&F, 0, cosmo->spline_params.ELL_MAX_CORR, 0,\n cosmo->gsl_params.INTEGRATION_EPSREL, cosmo->gsl_params.N_ITERATION,\n cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS,\n w, &result, &eresult);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_correlation.c: ccl_tracer_corr_bessel():\");\n local_status |= gslstatus;\n }\n wtheta[ith] = result/(2*M_PI);\n }\n }\n\n if (local_status) {\n #pragma omp atomic write\n *status = local_status;\n }\n\n gsl_integration_workspace_free(w);\n }\n ccl_f1d_t_free(cl_spl);\n}\n\n\n/*--------ROUTINE: ccl_compute_legendre_polynomial ------\nTASK: Compute input factor for ccl_tracer_corr_legendre\nINPUT: tracer 1, tracer 2, i_bessel, theta array, n_theta, L_max, output Pl_theta\n */\nstatic void ccl_compute_legendre_polynomial(int corr_type,double theta,int ell_max,double *Pl_theta)\n{\n int i,j;\n double k=0;\n double cth=cos(theta*M_PI/180);\n\n //Initialize Pl_theta\n for (j=0;j<=ell_max;j++)\n Pl_theta[j]=0.;\n\n if(corr_type==CCL_CORR_GG) {\n gsl_sf_legendre_Pl_array(ell_max,cth,Pl_theta);\n for (j=0;j<=ell_max;j++)\n Pl_theta[j]*=(2*j+1);\n }\n else if(corr_type==CCL_CORR_GL) {\n for (j=2;j<=ell_max;j++) {//https://arxiv.org/pdf/1007.4809.pdf\n Pl_theta[j]=gsl_sf_legendre_Plm(j,2,cth);\n Pl_theta[j]*=(2*j+1.)/((j+0.)*(j+1.));\n }\n }\n}\n\n/*--------ROUTINE: ccl_tracer_corr_legendre ------\nTASK: Compute correlation function via Legendre polynomials\nINPUT: cosmology, number of theta bins, theta array, tracer 1, tracer 2, i_bessel, boolean\n for tapering, vector of tapering limits, correlation vector, angular_cl function.\n */\nstatic void ccl_tracer_corr_legendre(ccl_cosmology *cosmo,\n int n_ell,double *ell,double *cls,\n int n_theta,double *theta,double *wtheta,\n int corr_type,int do_taper_cl,double *taper_cl_limits,\n int *status) {\n int i;\n double *l_arr = NULL, *cl_arr = NULL, *Pl_theta = NULL;\n ccl_f1d_t *cl_spl;\n\n if(corr_type==CCL_CORR_LM || corr_type==CCL_CORR_LP){\n *status=CCL_ERROR_NOT_IMPLEMENTED;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: CCL does not support full-sky xi+- calcuations.\\nhttps://arxiv.org/abs/1702.05301 indicates flat-sky to be sufficient.\\n\");\n }\n\n if(*status==0) {\n l_arr=malloc(((int)(cosmo->spline_params.ELL_MAX_CORR)+1)*sizeof(double));\n if(l_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n\n if(*status==0) {\n cl_arr=malloc(((int)(cosmo->spline_params.ELL_MAX_CORR)+1)*sizeof(double));\n if(cl_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n\n if(*status==0) {\n //Interpolate input Cl into\n cl_spl=ccl_f1d_t_new(n_ell,ell,cls,cls[0],0,\n\t\t\t ccl_f1d_extrap_const,\n\t\t\t ccl_f1d_extrap_logx_logy, status);\n if(cl_spl==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n\n if(*status==0) {\n for(i=0;i<=(int)(cosmo->spline_params.ELL_MAX_CORR);i++) {\n double l=(double)i;\n l_arr[i]=l;\n cl_arr[i]=ccl_f1d_t_eval(cl_spl,l);\n }\n ccl_f1d_t_free(cl_spl);\n\n if (do_taper_cl)\n *status=taper_cl((int)(cosmo->spline_params.ELL_MAX_CORR)+1,l_arr,cl_arr,taper_cl_limits);\n }\n\n int local_status, i_L;\n#pragma omp parallel default(none) \\\n shared(cosmo, theta, cl_arr, wtheta, n_theta, status, corr_type) \\\n private(Pl_theta, i, i_L, local_status)\n {\n Pl_theta = NULL;\n local_status = *status;\n\n if (local_status == 0) {\n Pl_theta = malloc(sizeof(double)*((int)(cosmo->spline_params.ELL_MAX_CORR)+1));\n if (Pl_theta == NULL) {\n local_status = CCL_ERROR_MEMORY;\n }\n }\n\n #pragma omp for schedule(dynamic)\n for (int i=0; i < n_theta; i++) {\n if (local_status == 0) {\n wtheta[i] = 0;\n ccl_compute_legendre_polynomial(corr_type, theta[i], (int)(cosmo->spline_params.ELL_MAX_CORR), Pl_theta);\n for (i_L=1; i_L < (int)(cosmo->spline_params.ELL_MAX_CORR); i_L+=1)\n wtheta[i] += cl_arr[i_L]*Pl_theta[i_L];\n wtheta[i] /= (M_PI*4);\n }\n }\n\n if (local_status) {\n #pragma omp atomic write\n *status = local_status;\n }\n\n free(Pl_theta);\n }\n free(l_arr);\n free(cl_arr);\n}\n\n/*--------ROUTINE: ccl_tracer_corr ------\nTASK: For a given tracer, get the correlation function. Do so by running\n ccl_angular_cls. If you already have Cls calculated, go to the next\n function to pass them directly.\nINPUT: cosmology, number of theta values to evaluate = NL, theta vector,\n tracer 1, tracer 2, i_bessel, key for tapering, limits of tapering\n correlation function.\n */\nvoid ccl_correlation(ccl_cosmology *cosmo,\n int n_ell,double *ell,double *cls,\n int n_theta,double *theta,double *wtheta,\n int corr_type,int do_taper_cl,double *taper_cl_limits,int flag_method,\n int *status) {\n switch(flag_method) {\n case CCL_CORR_FFTLOG :\n ccl_tracer_corr_fftlog(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,\n do_taper_cl,taper_cl_limits,status);\n break;\n case CCL_CORR_LGNDRE :\n ccl_tracer_corr_legendre(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,\n do_taper_cl,taper_cl_limits,status);\n break;\n case CCL_CORR_BESSEL :\n ccl_tracer_corr_bessel(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,status);\n break;\n default :\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation. Unknown algorithm\\n\");\n }\n\n}\n\n/*--------ROUTINE: ccl_correlation_3d ------\nTASK: Calculate the 3d-correlation function. Do so by using FFTLog.\n\nINPUT: cosmology, scale factor a,\n number of r values, r values,\n key for tapering, limits of tapering\n\nCorrelation function result will be in array xi\n */\n\nvoid ccl_correlation_3d(ccl_cosmology *cosmo, double a,\n int n_r,double *r,double *xi,\n int do_taper_pk,double *taper_pk_limits,\n int *status) {\n int i,N_ARR;\n double *k_arr,*pk_arr,*r_arr,*xi_arr;\n\n if (!cosmo->computed_nonlin_power) {\n *status = CCL_ERROR_NONLIN_POWER_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_correlation_3d(): non-linear power spctrum has not been computed!\");\n return;\n }\n\n //number of data points for k and pk array\n N_ARR=(int)(cosmo->spline_params.N_K_3DCOR*log10(cosmo->spline_params.K_MAX/cosmo->spline_params.K_MIN));\n\n k_arr=ccl_log_spacing(cosmo->spline_params.K_MIN,cosmo->spline_params.K_MAX,N_ARR);\n if(k_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation_3d ran out of memory\\n\");\n return;\n }\n\n pk_arr=malloc(N_ARR*sizeof(double));\n if(pk_arr==NULL) {\n free(k_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation_3d ran out of memory\\n\");\n return;\n }\n\n for (i=0; icomputed_nonlin_power) {\n *status = CCL_ERROR_NONLIN_POWER_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_correlation_multipole(): non-linear power spctrum has not been computed!\");\n return;\n }\n\n N_ARR = (int)(cosmo->spline_params.N_K_3DCOR * log10(cosmo->spline_params.K_MAX / cosmo->spline_params.K_MIN));\n\n k_arr = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, N_ARR);\n if (k_arr == NULL) {\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n return;\n }\n\n pk_arr = malloc(N_ARR * sizeof(double));\n if (pk_arr == NULL) {\n free(k_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n return;\n }\n\n for (i = 0; i < N_ARR; i++)\n pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status);\n\n s_arr = malloc(sizeof(double) * N_ARR);\n if (s_arr == NULL) {\n free(k_arr);\n free(pk_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n return;\n }\n xi_arr = malloc(sizeof(double) * N_ARR);\n if (xi_arr == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n return;\n }\n xi_arr0 = malloc(sizeof(double) * N_ARR);\n if (xi_arr0 == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n return;\n }\n\n for (i = 0; i < N_ARR; i++) s_arr[i] = 0;\n\n // Calculate multipoles\n\n if (l == 0) {\n ccl_fftlog_ComputeXi3D(0, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status);\n for (i = 0; i < N_ARR; i++)\n xi_arr[i] = (1. + 2. / 3 * beta + 1. / 5 * beta * beta) * xi_arr0[i];\n } else if (l == 2) {\n ccl_fftlog_ComputeXi3D(2, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status);\n for (i = 0; i < N_ARR; i++)\n xi_arr[i] = -(4. / 3 * beta + 4. / 7 * beta * beta) * xi_arr0[i];\n } else if (l == 4) {\n ccl_fftlog_ComputeXi3D(4, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status);\n for (i = 0; i < N_ARR; i++) xi_arr[i] = 8. / 35 * beta * beta * xi_arr0[i];\n } else {\n strcpy(cosmo->status_message, \"unavailable value of l\\n\");\n return;\n }\n\n // Interpolate to output values of s\n ccl_f1d_t *xi_spl = ccl_f1d_t_new(N_ARR, s_arr, xi_arr, xi_arr[0], 0,\n\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t ccl_f1d_extrap_const, status);\n if (xi_spl == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole ran out of memory\\n\");\n }\n for (i = 0; i < n_s; i++) xi[i] = ccl_f1d_t_eval(xi_spl,s[i]);\n ccl_f1d_t_free(xi_spl);\n\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n\n return;\n}\n\n/*--------ROUTINE: ccl_correlation_multipole_spline ------\nTASK: Store multipoles of the redshift-space correlation in global splines\n\nINPUT: cosmology, scale factor a\n\nResult is stored in cosmo->data.rsd_splines[]\n */\n\nvoid ccl_correlation_multipole_spline(ccl_cosmology *cosmo, double a,\n int *status) {\n int i, N_ARR;\n double *k_arr, *pk_arr, *s_arr, *xi_arr, *xi_arr0, *xi_arr2, *xi_arr4;\n\n if (!cosmo->computed_nonlin_power) {\n *status = CCL_ERROR_NONLIN_POWER_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_correlation_multipole_spline(): non-linear power spctrum has not been computed!\");\n return;\n }\n\n N_ARR = (int)(cosmo->spline_params.N_K_3DCOR * log10(cosmo->spline_params.K_MAX / cosmo->spline_params.K_MIN));\n\n k_arr = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, N_ARR);\n if (k_arr == NULL) {\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n pk_arr = malloc(N_ARR * sizeof(double));\n if (pk_arr == NULL) {\n free(k_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n for (i = 0; i < N_ARR; i++)\n pk_arr[i] = ccl_nonlin_matter_power(cosmo, k_arr[i], a, status);\n\n s_arr = malloc(sizeof(double) * N_ARR);\n if (s_arr == NULL) {\n free(k_arr);\n free(pk_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n xi_arr = malloc(sizeof(double) * N_ARR);\n if (xi_arr == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n xi_arr0 = malloc(sizeof(double) * N_ARR);\n if (xi_arr0 == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n xi_arr2 = malloc(sizeof(double) * N_ARR);\n if (xi_arr2 == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n xi_arr4 = malloc(sizeof(double) * N_ARR);\n if (xi_arr4 == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n free(xi_arr2);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n for (i = 0; i < N_ARR; i++) s_arr[i] = 0;\n\n // Calculate multipoles\n ccl_fftlog_ComputeXi3D(0, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr0, status);\n ccl_fftlog_ComputeXi3D(2, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr2, status);\n ccl_fftlog_ComputeXi3D(4, 0, 1, N_ARR, k_arr, &pk_arr, s_arr, &xi_arr4, status);\n\n // free any memory that may have been allocated\n ccl_f1d_t_free(cosmo->data.rsd_splines[0]);\n ccl_f1d_t_free(cosmo->data.rsd_splines[1]);\n ccl_f1d_t_free(cosmo->data.rsd_splines[2]);\n cosmo->data.rsd_splines[0] = NULL;\n cosmo->data.rsd_splines[1] = NULL;\n cosmo->data.rsd_splines[1] = NULL;\n\n // Interpolate to output values of s\n cosmo->data.rsd_splines[0] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr0, xi_arr0[0], 0,\n\t\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t\t ccl_f1d_extrap_const, status);\n if (cosmo->data.rsd_splines[0] == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n free(xi_arr2);\n free(xi_arr4);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n cosmo->data.rsd_splines[1] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr2, xi_arr2[0], 0,\n\t\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t\t ccl_f1d_extrap_const, status);\n if (cosmo->data.rsd_splines[1] == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n free(xi_arr2);\n free(xi_arr4);\n ccl_f1d_t_free(cosmo->data.rsd_splines[0]);\n cosmo->data.rsd_splines[0] = NULL;\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n cosmo->data.rsd_splines[2] = ccl_f1d_t_new(N_ARR, s_arr, xi_arr4, xi_arr4[0], 0,\n\t\t\t\t\t ccl_f1d_extrap_const,\n\t\t\t\t\t ccl_f1d_extrap_const, status);\n if (cosmo->data.rsd_splines[2] == NULL) {\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n free(xi_arr2);\n free(xi_arr4);\n ccl_f1d_t_free(cosmo->data.rsd_splines[0]);\n cosmo->data.rsd_splines[0] = NULL;\n ccl_f1d_t_free(cosmo->data.rsd_splines[1]);\n cosmo->data.rsd_splines[1] = NULL;\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_multipole_spline ran out of \"\n \"memory\\n\");\n return;\n }\n\n // set the scale factor\n cosmo->data.rsd_splines_scalefactor = a;\n\n free(k_arr);\n free(pk_arr);\n free(s_arr);\n free(xi_arr);\n free(xi_arr0);\n free(xi_arr2);\n free(xi_arr4);\n\n return;\n}\n\n/*--------ROUTINE: ccl_correlation_3dRsd ------\nTASK: Calculate the redshift-space correlation function.\n\nINPUT: cosmology, scale factor a, number of s values, s values,\n mu = cosine of galaxy separation angle w.r.t. line of sight,\n beta (= growth rate / bias), key for using spline\n\nCorrelation function result will be in array xi\n */\n\nvoid ccl_correlation_3dRsd(ccl_cosmology *cosmo, double a, int n_s, double *s,\n double mu, double beta, double *xi, int use_spline,\n int *status) {\n int i;\n double *xi_arr0, *xi_arr2, *xi_arr4;\n\n if (!cosmo->computed_nonlin_power) {\n *status = CCL_ERROR_NONLIN_POWER_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_correlation_3dRsd(): non-linear power spctrum has not been computed!\");\n return;\n }\n\n if (use_spline == 0) {\n xi_arr0 = malloc(sizeof(double) * n_s);\n if (xi_arr0 == NULL) {\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\\n\");\n return;\n }\n xi_arr2 = malloc(sizeof(double) * n_s);\n if (xi_arr2 == NULL) {\n free(xi_arr0);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\\n\");\n return;\n }\n xi_arr4 = malloc(sizeof(double) * n_s);\n if (xi_arr4 == NULL) {\n free(xi_arr0);\n free(xi_arr2);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_3dRsd ran out of memory\\n\");\n return;\n }\n\n ccl_correlation_multipole(cosmo, a, beta, 0, n_s, s, xi_arr0, status);\n ccl_correlation_multipole(cosmo, a, beta, 2, n_s, s, xi_arr2, status);\n ccl_correlation_multipole(cosmo, a, beta, 4, n_s, s, xi_arr4, status);\n for (i = 0; i < n_s; i++)\n xi[i] = xi_arr0[i] + xi_arr2[i] * gsl_sf_legendre_Pl(2, mu) +\n xi_arr4[i] * gsl_sf_legendre_Pl(4, mu);\n free(xi_arr0);\n free(xi_arr2);\n free(xi_arr4);\n\n } else {\n if ((cosmo->data.rsd_splines[0] == NULL) ||\n (cosmo->data.rsd_splines[1] == NULL) ||\n (cosmo->data.rsd_splines[2] == NULL) ||\n (cosmo->data.rsd_splines_scalefactor != a))\n ccl_correlation_multipole_spline(cosmo, a, status);\n\n for (i = 0; i < n_s; i++)\n xi[i] = (1. + 2. / 3 * beta + 1. / 5 * beta * beta) *\n ccl_f1d_t_eval(cosmo->data.rsd_splines[0],s[i]) -\n (4. / 3 * beta + 4. / 7 * beta * beta) *\n ccl_f1d_t_eval(cosmo->data.rsd_splines[1],s[i]) *\n gsl_sf_legendre_Pl(2, mu) +\n 8. / 35 * beta * beta * ccl_f1d_t_eval(cosmo->data.rsd_splines[2],s[i]) *\n gsl_sf_legendre_Pl(4, mu);\n }\n\n return;\n}\n\n/*--------ROUTINE: ccl_correlation_3dRsd_avgmu ------\nTASK: Calculate the average of redshift-space correlation function xi(s,mu) over mu at constant s\n\nINPUT: cosmology, scale factor a, number of s values, s values, beta (= growth rate / bias)\n\nThe result will be in array xi\n*/\n\nvoid ccl_correlation_3dRsd_avgmu(ccl_cosmology *cosmo, double a, int n_s, double *s,\n double beta, double *xi,\n int *status) {\n// The average is just the l=0 multipole - the higher multiples inetegrate to zero.\n ccl_correlation_multipole(cosmo, a, beta, 0, n_s, s, xi, status);\n\n return;\n}\n\n/*--------ROUTINE: ccl_correlation_pi_sigma ------\nTASK: Calculate the redshift-space correlation function using longitudinal and\n transverse coordinates pi and sigma.\n\nINPUT: cosmology, scale factor a, beta (= growth rate / bias),\n pi, number of sigma values, sigma values,\n key for using spline\n\nCorrelation function result will be in array xi\n*/\n\nvoid ccl_correlation_pi_sigma(ccl_cosmology *cosmo, double a, double beta,\n double pi, int n_sig, double *sig, double *xi,\n int use_spline, int *status) {\n int i;\n double *mu_arr, *s_arr, *xi_arr;\n\n if (!cosmo->computed_nonlin_power) {\n *status = CCL_ERROR_NONLIN_POWER_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_correlation.c: ccl_correlation_pi_sigma(): non-linear power spctrum has not been computed!\");\n return;\n }\n\n mu_arr = malloc(sizeof(double) * n_sig);\n if (mu_arr == NULL) {\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\\n\");\n return;\n }\n\n s_arr = malloc(sizeof(double) * n_sig);\n if (s_arr == NULL) {\n free(mu_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\\n\");\n return;\n }\n\n xi_arr = malloc(sizeof(double) * n_sig);\n if (xi_arr == NULL) {\n free(mu_arr);\n free(s_arr);\n *status = CCL_ERROR_MEMORY;\n strcpy(cosmo->status_message,\n \"ccl_correlation.c: ccl_correlation_pi_sigma ran out of memory\\n\");\n return;\n }\n\n for (i = 0; i < n_sig; i++) {\n s_arr[i] = sqrt(pi * pi + sig[i] * sig[i]);\n mu_arr[i] = pi / s_arr[i];\n }\n\n for (i = 0; i < n_sig; i++) {\n ccl_correlation_3dRsd(cosmo, a, n_sig, s_arr, mu_arr[i], beta, xi_arr,\n use_spline, status);\n xi[i] = xi_arr[i];\n }\n\n free(mu_arr);\n free(xi_arr);\n free(s_arr);\n\n return;\n}\n", "meta": {"hexsha": "5036bcccac4c509bd963a36406436666c2fb1d3f", "size": 30939, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_correlation.c", "max_stars_repo_name": "damonge/CCL", "max_stars_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "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_correlation.c", "max_issues_repo_name": "damonge/CCL", "max_issues_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_forks_repo_path": "src/ccl_correlation.c", "max_forks_repo_name": "damonge/CCL", "max_forks_repo_head_hexsha": "04cb83885ccd5f343b48cd8151bebd5779518ca6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3465045593, "max_line_length": 187, "alphanum_fraction": 0.6458838359, "num_tokens": 9500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46919473005328954}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#undef __FUNCT__\n#define __FUNCT__ \"MatVecMPFR\"\nPetscErrorCode MatVecMPFR(PetscInt size_d, mpfr_t *Mat, mpfr_t *vec, mpfr_t *result) {\n\n PetscErrorCode ierr;\n mpfr_t temp1;\n mpfr_t *res;\n PetscFunctionBegin;\n\n mpfr_init(temp1);\n res = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);\n \n for(PetscInt k=0; k < size_d; ++k)\n mpfr_init(res[k]);\n\n for(PetscInt i=0; i -prec && mpfr_get_d(error2, MPFR_RNDN) > -prec) {\n j++;\n for(PetscInt l=0; l < size_d; ++l)\n\tmpfr_set(prev[l], eigvec[l], MPFR_RNDN);\n ierr = MatVecMPFR(size_d, mat, eigvec, tempvec2);CHKERRQ(ierr);\n //subtract off already found eigenvectors\n for(PetscInt k=0; k\n#include \n#include \n#include \"gsl_sf_erf.h\"\n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_log.h\"\n#include \"gsl_sf_gamma.h\"\n\n#include \"error.h\"\n\n/* The dominant part,\n * D(a,x) := x^a e^(-x) / Gamma(a+1)\n */\nstatic\nint\ngamma_inc_D(const double a, const double x, gsl_sf_result * result)\n{\n if(a < 10.0) {\n double lnr;\n gsl_sf_result lg;\n gsl_sf_lngamma_e(a+1.0, &lg);\n lnr = a * log(x) - x - lg.val;\n result->val = exp(lnr);\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(lnr) + 1.0) * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n double mu = (x-a)/a;\n double term1;\n gsl_sf_result gstar;\n gsl_sf_result ln_term;\n gsl_sf_log_1plusx_mx_e(mu, &ln_term); /* log(1+mu) - mu */\n gsl_sf_gammastar_e(a, &gstar);\n term1 = exp(a*ln_term.val)/sqrt(2.0*M_PI*a);\n result->val = term1/gstar.val;\n result->err = 2.0 * GSL_DBL_EPSILON * (fabs(a*ln_term.val) + 1.0) * fabs(result->val);\n result->err += gstar.err/fabs(gstar.val) * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\n/* P series representation.\n */\nstatic\nint\ngamma_inc_P_series(const double a, const double x, gsl_sf_result * result)\n{\n const int nmax = 5000;\n\n gsl_sf_result D;\n int stat_D = gamma_inc_D(a, x, &D);\n\n double sum = 1.0;\n double term = 1.0;\n int n;\n for(n=1; nval = D.val * sum;\n result->err = D.err * fabs(sum);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n if(n == nmax)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return stat_D;\n}\n\n\n/* Q large x asymptotic\n */\nstatic\nint\ngamma_inc_Q_large_x(const double a, const double x, gsl_sf_result * result)\n{\n const int nmax = 5000;\n\n gsl_sf_result D;\n const int stat_D = gamma_inc_D(a, x, &D);\n\n double sum = 1.0;\n double term = 1.0;\n double last = 1.0;\n int n;\n for(n=1; n 1.0) break;\n if(fabs(term/sum) < GSL_DBL_EPSILON) break;\n sum += term;\n last = term;\n }\n\n result->val = D.val * (a/x) * sum;\n result->err = D.err * fabs((a/x) * sum);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n if(n == nmax)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return stat_D;\n}\n\n\n/* Uniform asymptotic for x near a, a and x large.\n * See [Temme, p. 285]\n * FIXME: need c1 coefficient\n */\nstatic\nint\ngamma_inc_Q_asymp_unif(const double a, const double x, gsl_sf_result * result)\n{\n const double rta = sqrt(a);\n const double eps = (x-a)/a;\n\n gsl_sf_result ln_term;\n const int stat_ln = gsl_sf_log_1plusx_mx_e(eps, &ln_term); /* log(1+eps) - eps */\n const double eta = eps * sqrt(-2.0*ln_term.val/(eps*eps));\n\n gsl_sf_result erfc;\n\n double R;\n double c0, c1;\n\n gsl_sf_erfc_e(eta*M_SQRT2*rta, &erfc);\n\n if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {\n c0 = -1.0/3.0 + eps*(1.0/12.0 - eps*(23.0/540.0 - eps*(353.0/12960.0 - eps*589.0/30240.0)));\n c1 = 0.0;\n }\n else {\n double rt_term;\n rt_term = sqrt(-2.0 * ln_term.val/(eps*eps));\n c0 = (1.0 - 1.0/rt_term)/eps;\n c1 = 0.0;\n }\n\n R = exp(-0.5*a*eta*eta)/(M_SQRT2*M_SQRTPI*rta) * (c0 + c1/a);\n\n result->val = 0.5 * erfc.val + R;\n result->err = GSL_DBL_EPSILON * fabs(R * 0.5 * a*eta*eta) + 0.5 * erfc.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n return stat_ln;\n}\n\n\n/* Continued fraction for Q.\n *\n * Q(a,x) = D(a,x) a/x F(a,x)\n * 1 (1-a)/x 1/x (2-a)/x 2/x (3-a)/x\n * F(a.x) = ---- ------- ----- -------- ----- -------- ...\n * 1 + 1 + 1 + 1 + 1 + 1 +\n *\n * Uses Gautschi equivalent series method for the CF evaluation.\n *\n * Assumes a != x + 1, so that the first term of the\n * CF recursion is not undefined. This is why we need\n * gamma_inc_Q_CF_protected() below. Based on a problem\n * report by Teemu Ikonen [Tue Oct 10 12:17:19 MDT 2000].\n */\nstatic\nint\ngamma_inc_Q_CF(const double a, const double x, gsl_sf_result * result)\n{\n const int kmax = 5000;\n\n gsl_sf_result D;\n const int stat_D = gamma_inc_D(a, x, &D);\n\n double sum = 1.0;\n double tk = 1.0;\n double rhok = 0.0;\n int k;\n\n for(k=1; kval = D.val * (a/x) * sum;\n result->err = D.err * fabs((a/x) * sum);\n result->err += GSL_DBL_EPSILON * (2.0 + 0.5*k) * fabs(result->val);\n\n if(k == kmax)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return stat_D;\n}\n\n\n/* See note above for gamma_inc_Q_CF(). */\nstatic\nint\ngamma_inc_Q_CF_protected(const double a, const double x, gsl_sf_result * result)\n{\n if(fabs(1.0 - a + x) < 2.0*GSL_DBL_EPSILON) {\n /*\n * This is a problem region because when\n * 1.0 - a + x = 0 the first term of the\n * CF recursion is undefined.\n *\n * I missed this condition when I first\n * implemented gamma_inc_Q_CF() function,\n * so now I have to fix it by side-stepping\n * this point, using the recursion relation\n * Q(a,x) = Q(a-1,x) + x^(a-1) e^(-z) / Gamma(a)\n * = Q(a-1,x) + D(a-1,x)\n * to lower 'a' by one, giving an a=x point,\n * which is fine.\n */\n\n gsl_sf_result D;\n gsl_sf_result tmp_CF;\n\n const int stat_tmp_CF = gamma_inc_Q_CF(a-1.0, x, &tmp_CF);\n const int stat_D = gamma_inc_D(a-1.0, x, &D);\n result->val = tmp_CF.val + D.val;\n result->err = tmp_CF.err + D.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_tmp_CF, stat_D);\n }\n else {\n return gamma_inc_Q_CF(a, x, result);\n }\n}\n\n\n/* Useful for small a and x. Handles the subtraction analytically.\n */\nstatic\nint\ngamma_inc_Q_series(const double a, const double x, gsl_sf_result * result)\n{\n double term1; /* 1 - x^a/Gamma(a+1) */\n double sum; /* 1 + (a+1)/(a+2)(-x)/2! + (a+1)/(a+3)(-x)^2/3! + ... */\n int stat_sum;\n double term2; /* a temporary variable used at the end */\n\n {\n /* Evaluate series for 1 - x^a/Gamma(a+1), small a\n */\n const double pg21 = -2.404113806319188570799476; /* PolyGamma[2,1] */\n const double lnx = log(x);\n const double el = M_EULER+lnx;\n const double c1 = -el;\n const double c2 = M_PI*M_PI/12.0 - 0.5*el*el;\n const double c3 = el*(M_PI*M_PI/12.0 - el*el/6.0) + pg21/6.0;\n const double c4 = -0.04166666666666666667\n * (-1.758243446661483480 + lnx)\n * (-0.764428657272716373 + lnx)\n\t\t * ( 0.723980571623507657 + lnx)\n\t\t * ( 4.107554191916823640 + lnx);\n const double c5 = -0.0083333333333333333\n * (-2.06563396085715900 + lnx)\n\t\t * (-1.28459889470864700 + lnx)\n\t\t * (-0.27583535756454143 + lnx)\n\t\t * ( 1.33677371336239618 + lnx)\n\t\t * ( 5.17537282427561550 + lnx);\n const double c6 = -0.0013888888888888889\n * (-2.30814336454783200 + lnx)\n * (-1.65846557706987300 + lnx)\n * (-0.88768082560020400 + lnx)\n * ( 0.17043847751371778 + lnx)\n * ( 1.92135970115863890 + lnx)\n * ( 6.22578557795474900 + lnx);\n const double c7 = -0.00019841269841269841\n * (-2.5078657901291800 + lnx)\n * (-1.9478900888958200 + lnx)\n * (-1.3194837322612730 + lnx)\n * (-0.5281322700249279 + lnx)\n * ( 0.5913834939078759 + lnx)\n * ( 2.4876819633378140 + lnx)\n * ( 7.2648160783762400 + lnx);\n const double c8 = -0.00002480158730158730\n * (-2.677341544966400 + lnx)\n * (-2.182810448271700 + lnx)\n * (-1.649350342277400 + lnx)\n * (-1.014099048290790 + lnx)\n * (-0.191366955370652 + lnx)\n * ( 0.995403817918724 + lnx)\n * ( 3.041323283529310 + lnx)\n * ( 8.295966556941250 + lnx);\n const double c9 = -2.75573192239859e-6\n * (-2.8243487670469080 + lnx)\n * (-2.3798494322701120 + lnx)\n * (-1.9143674728689960 + lnx)\n * (-1.3814529102920370 + lnx)\n * (-0.7294312810261694 + lnx)\n * ( 0.1299079285269565 + lnx)\n * ( 1.3873333251885240 + lnx)\n * ( 3.5857258865210760 + lnx)\n * ( 9.3214237073814600 + lnx);\n const double c10 = -2.75573192239859e-7\n * (-2.9540329644556910 + lnx)\n * (-2.5491366926991850 + lnx)\n * (-2.1348279229279880 + lnx)\n * (-1.6741881076349450 + lnx)\n * (-1.1325949616098420 + lnx)\n * (-0.4590034650618494 + lnx)\n * ( 0.4399352987435699 + lnx)\n * ( 1.7702236517651670 + lnx)\n * ( 4.1231539047474080 + lnx)\n * ( 10.342627908148680 + lnx);\n\n term1 = a*(c1+a*(c2+a*(c3+a*(c4+a*(c5+a*(c6+a*(c7+a*(c8+a*(c9+a*c10)))))))));\n }\n\n {\n /* Evaluate the sum.\n */\n const int nmax = 5000;\n double t = 1.0;\n int n;\n sum = 1.0;\n\n for(n=1; nval = term1 + term2;\n result->err = GSL_DBL_EPSILON * (fabs(term1) + 2.0*fabs(term2));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_sum;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_gamma_inc_Q_e(const double a, const double x, gsl_sf_result * result)\n{\n if(a <= 0.0 || x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x == 0.0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x <= 0.5*a) {\n /* If the series is quick, do that. It is\n * robust and simple.\n */\n gsl_sf_result P;\n int stat_P = gamma_inc_P_series(a, x, &P);\n result->val = 1.0 - P.val;\n result->err = P.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_P;\n }\n else if(a >= 1.0e+06 && (x-a)*(x-a) < a) {\n /* Then try the difficult asymptotic regime.\n * This is the only way to do this region.\n */\n return gamma_inc_Q_asymp_unif(a, x, result);\n }\n else if(a < 0.2 && x < 5.0) {\n /* Cancellations at small a must be handled\n * analytically; x should not be too big\n * either since the series terms grow\n * with x and log(x).\n */\n return gamma_inc_Q_series(a, x, result);\n }\n else if(a <= x) {\n if(x <= 1.0e+06) {\n /* Continued fraction is excellent for x >~ a.\n * We do not let x be too large when x > a since\n * it is somewhat pointless to try this there;\n * the function is rapidly decreasing for\n * x large and x > a, and it will just\n * underflow in that region anyway. We \n * catch that case in the standard\n * large-x method.\n */\n return gamma_inc_Q_CF(a, x, result);\n }\n else {\n return gamma_inc_Q_large_x(a, x, result);\n }\n }\n else {\n if(a < 0.8*x) {\n /* Continued fraction again. The convergence\n * is a little slower here, but that is fine.\n * We have to trade that off against the slow\n * convergence of the series, which is the\n * only other option.\n */\n return gamma_inc_Q_CF(a, x, result);\n }\n else {\n gsl_sf_result P;\n int stat_P = gamma_inc_P_series(a, x, &P);\n result->val = 1.0 - P.val;\n result->err = P.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_P;\n }\n }\n}\n\n\nint\ngsl_sf_gamma_inc_P_e(const double a, const double x, gsl_sf_result * result)\n{\n if(a <= 0.0 || x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x < 20.0 || x < 0.5*a) {\n /* Do the easy series cases. Robust and quick.\n */\n return gamma_inc_P_series(a, x, result);\n }\n else if(a > 1.0e+06 && (x-a)*(x-a) < a) {\n /* Crossover region. Note that Q and P are\n * roughly the same order of magnitude here,\n * so the subtraction is stable.\n */\n gsl_sf_result Q;\n int stat_Q = gamma_inc_Q_asymp_unif(a, x, &Q);\n result->val = 1.0 - Q.val;\n result->err = Q.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_Q;\n }\n else if(a <= x) {\n /* Q <~ P in this area, so the\n * subtractions are stable.\n */\n gsl_sf_result Q;\n int stat_Q;\n if(a > 0.2*x) {\n stat_Q = gamma_inc_Q_CF(a, x, &Q);\n }\n else {\n stat_Q = gamma_inc_Q_large_x(a, x, &Q);\n }\n result->val = 1.0 - Q.val;\n result->err = Q.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_Q;\n }\n else {\n if((x-a)*(x-a) < a) {\n /* This condition is meant to insure\n * that Q is not very close to 1,\n * so the subtraction is stable.\n */\n gsl_sf_result Q;\n int stat_Q = gamma_inc_Q_CF_protected(a, x, &Q);\n result->val = 1.0 - Q.val;\n result->err = Q.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return stat_Q;\n }\n else {\n return gamma_inc_P_series(a, x, result);\n }\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_gamma_inc_P(const double a, const double x)\n{\n EVAL_RESULT(gsl_sf_gamma_inc_P_e(a, x, &result));\n}\n\ndouble gsl_sf_gamma_inc_Q(const double a, const double x)\n{\n EVAL_RESULT(gsl_sf_gamma_inc_Q_e(a, x, &result));\n}\n", "meta": {"hexsha": "ca3d903a3f70bba8b262617435dd47c7e0fd0bbb", "size": 15000, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gamma_inc.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/gamma_inc.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/gamma_inc.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": 28.6806883365, "max_line_length": 96, "alphanum_fraction": 0.5563333333, "num_tokens": 5015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4690216149837015}} {"text": "#ifdef __LOCAL_SIMULATION_ENV__\n\n#include \"model.h\"\n\n#endif\n\n//############# START DYNAMIC_CLAMP CODE ##################\n\n/*!\nDynamic clamp model for a current generated by multiple clusters of cooperative ion channels:\nI_{coop} = -g*N_{open}*(V-E)\nwhere the number of open channels N_{open} changes due to the stochastic opening and closing events guided by rates\nwhich depend on the external voltage and the number of open channels among the surrounding channels in a cluster i.e.\nalpha(V, o) and beta(V,o)\n\n\\par Input/Output\n- V: Measured membrane potential in mV\n- \\f$ I_{inj} \\f$ : Injected current in nA\n\n\\par Parameter\n- g : conductance of a single channel in nS\n- E : reversal potential of the ionic current in mV\n- cN: number of clusters of cooperative ion channels without units\n- cS: number of cooperative ion channels in a cluster without units\n- J : pairwise interaction strength in mV\n- tau : peak reaction time scale of a single channel in ms\n*/\n\n#ifndef __KERNEL__\n\n#include \n#include \n\n#endif\n\n\n#define POWER_2_EXP 28\nunsigned long next = 1;\nconst int RAND_PERIOD = 1 << POWER_2_EXP;\n\n// numerical recipes in c, p. 276, not recommended for usage as the period is 30k and other issues\nfloat evil_rand(void) {\n next = next * 1103515245 + 1234;\n return (float) ((unsigned int) (next / 65536) % 32768) / 32768;\n}\n\n#if defined (__KERNEL__) || defined (DYNCLAMPMODEL)\n\n/*! Name, by which this module is known inside Linux: */\nconst char *modelName;\n\n/*! Variables used by the model */\n#define MAX_CLUSTER_SIZE 8\n#define DEFAULT_CLUSTER_NUMBER 100\n#define DEFAULT_CLUSTER_INIT 0\nint cluster_states[MAX_CLUSTER_SIZE + 1] = {DEFAULT_CLUSTER_NUMBER, 0, 0, 0, 0, 0, 0, 0, 0};\nint cluster_size = MAX_CLUSTER_SIZE;\nint cluster_number = DEFAULT_CLUSTER_NUMBER;\nint cluster_init = DEFAULT_CLUSTER_INIT;\n\n/*! The period length of the realtime periodic task in seconds. */\nfloat loopInterval;\n/*! One over the period length of the realtime periodic task in Hertz. */\nfloat loopRate;\n\n/*! Analog input that is read from the DAQ board. */\n\n#define INPUT_N 1\n/*! The \\a inputNames are used to match the \\a input variables with\nanalog input traces in Relacs. */\nconst char *inputNames[INPUT_N] = {\"V-1\"};\nconst char *inputUnits[INPUT_N] = {\"mV\"};\n/*! The \\a inputChannels are set automatically. */\nint inputChannels[INPUT_N];\n/*! \\a input holds the current value that was read in from the DAQ board. */\nfloat input[INPUT_N] = {0.0};\n\n/*! Analog output that is written to the DAQ board. */\n\n#define OUTPUT_N 1\nconst char *outputNames[OUTPUT_N] = {\"Current-1\"};\nconst char *outputUnits[OUTPUT_N] = {\"nA\"};\nint outputChannels[OUTPUT_N];\nfloat output[OUTPUT_N] = {0.0};\n\n/*! Parameter that are provided by the model and can be read out. */\n\n#define PARAMINPUT_N 2\nconst char *paramInputNames[PARAMINPUT_N] = {\"Cooperative-Cluster-Current\", \"Open-Channels\"};\nconst char *paramInputUnits[PARAMINPUT_N] = {\"nA\", \"\"};\nfloat paramInput[PARAMINPUT_N] = {0.0, 0.0};\n\n/*! Parameter that are read by the model and are written to the model. */\n\n#define PARAMOUTPUT_N 8\nconst char *paramOutputNames[PARAMOUTPUT_N] = {\"g\", \"E\", \"J\", \"tau\", \"Cluster size\", \"Number of clusters\", \"Vhalf\", \"Initial state\"};\nconst char *paramOutputUnits[PARAMOUTPUT_N] = {\"pS\", \"mV\", \"mV\", \"ms\", \"\", \"\", \"mV\", \"\"};\nfloat paramOutput[PARAMOUTPUT_N] = {0.0, 0.0, 0.0, 15, MAX_CLUSTER_SIZE, DEFAULT_CLUSTER_NUMBER, -1.0, 0};\n\n\n/*! Functions used by the model */\ndouble opening_rate(double voltage) {\n double oR;\n float vhalf = paramOutput[6];\n if (paramOutput[3] != 0.0) {\n oR = cosh((voltage - vhalf) / 30.0) * (1.0 + tanh((voltage - vhalf) / 15.0)) / paramOutput[3] / 2.0;\n } else {\n oR = 0;\n }\n return oR;\n}\n\ndouble closing_rate(double voltage) {\n double cR;\n float vhalf = paramOutput[6];\n if (paramOutput[3] != 0.0) {\n cR = cosh((voltage - vhalf) / 30.0) * (1.0 - tanh((voltage - vhalf) / 15.0)) / paramOutput[3] / 2.0;\n } else {\n cR = 0;\n }\n return cR;\n}\n\n\ndouble get_rand(void) {\n double u;\n\n#ifdef ENABLE_LOOKUPTABLES\n // random number from lookuptable:\n next = (next >= (RAND_PERIOD - 1)) ? 0 : (next + 1);\n u = (double) lookupx[0][next];\n#else\n u = (double) evil_rand();\n#endif\n return u;\n}\n\n\nint get_number_of_open_channels(void) {\n int sum = 0;\n int size = cluster_size;\n int i;\n for (i = 0; i <= size; i++) {\n sum += cluster_states[i] * i;\n }\n return sum;\n}\n\n\n/*\nbrute_force on cluster state basis: rates based, does not need any internal state\n- needs 2*cluster_size random numbers per time step\n- problem: as multiple reactions might take place in a single time step an opening and a closing reaction might take\nplace simultaneously leaving behind an inconsistent state e.g. [0 1 0] -> [1 -1 1]\n*/\nvoid evolve_cluster_states(void) {\n double rand;\n double dt = loopInterval * 1000;\n double voltage = input[0];\n int cS = cluster_size;\n float cluster_interaction = paramOutput[2];\n\n //helpers\n int i;\n double opening_rates[cS];\n double closing_rates[cS];\n\n // calculate opening and closing rates\n for (i = 0; i < cS; i++) {\n // opening_rate[i]: rate from (i channels open) to (i+1 channels open)\n opening_rates[i] = cluster_states[i] * (cS - i) * opening_rate(voltage + i * cluster_interaction);\n // closing_rate[i]: rate from (i+1 channels open) to (i channels open)\n closing_rates[i] = cluster_states[i + 1] * (i + 1) * closing_rate(voltage + i * cluster_interaction);\n }\n\n // update cluster states\n for (i = 0; i < cS; i++) {\n //opening reaction from (i channels open) to (i+1 channels open)\n rand = get_rand();\n if (rand <= opening_rates[i] * dt) {\n //DEBUG_MSG(\"C -> Likelihood %.16f, Threshold:%.16f\\n\", opening_rates[i]*dt, rand);\n //DEBUG_MSG(\"Opening %d:%d\\n\", i, cluster_states[i]);\n if (cluster_states[i] != 0) {\n cluster_states[i] -= 1;\n cluster_states[i + 1] += 1;\n }\n }\n\n // closing reaction from (i+1 channels open) to (i channels open)\n rand = get_rand();\n if (rand <= closing_rates[i] * dt) {\n //DEBUG_MSG(\"C -> Likelihood %.16f, Threshold:%.16f\\n\", closing_rates[i]*dt, rand);\n //DEBUG_MSG(\"Closing %d:%d\\n\", i+1,cluster_states[i+1]);\n if (cluster_states[i + 1] != 0) {\n cluster_states[i + 1] -= 1;\n cluster_states[i] += 1;\n }\n }\n }\n}\n\n\nvoid populate_state(int state_idx) {\n int idx;\n cluster_states[state_idx] = cluster_number;\n for (idx = 0; idx <= cluster_size; idx++) {\n if(idx != state_idx) {\n cluster_states[idx] = 0;\n }\n }\n}\n\n\nvoid process_cluster_property_changes(void) {\n int cluster_size_idx = 4;\n int cluster_number_idx = 5;\n int cluster_init_idx = 7;\n\n if (cluster_size != (int) paramOutput[cluster_size_idx] ||\n cluster_number != (int) paramOutput[cluster_number_idx] || cluster_init != (int) paramOutput[cluster_init_idx]) {\n if (paramOutput[cluster_size_idx] > MAX_CLUSTER_SIZE) {\n cluster_size = MAX_CLUSTER_SIZE;\n } else {\n cluster_size = (paramOutput[cluster_size_idx] >= 1) ? (int) paramOutput[cluster_size_idx] : 1;\n };\n\n if (paramOutput[cluster_init_idx] > MAX_CLUSTER_SIZE) {\n cluster_init = MAX_CLUSTER_SIZE;\n } else {\n cluster_init = (paramOutput[cluster_init_idx] >= 0) ? (int) paramOutput[cluster_init_idx] : 0;\n };\n\n\n cluster_number = (paramOutput[cluster_number_idx] > 0) ? (int) paramOutput[cluster_number_idx] : 0;\n\n populate_state(cluster_init);\n }\n}\n\n\n/*! Functions provided by the model for the dynamic clamp module */\n\n\nvoid initModel(void) {\n modelName = \"cooperative_clusters\";\n process_cluster_property_changes();\n}\n\n#define CONDUCTANCE_IDX 0\n#define MEMBRANE_POTENTIAL_IDX 0\n#define REVERSAL_POTENTIAL_IDX 1\n\nvoid computeModel(void) {\n\n int number_of_open_channels = 0;\n process_cluster_property_changes();\n evolve_cluster_states();\n // number of open channels\n number_of_open_channels = get_number_of_open_channels();\n paramInput[0] = (float) (-0.000001 * paramOutput[CONDUCTANCE_IDX] * number_of_open_channels *\n (input[MEMBRANE_POTENTIAL_IDX] - paramOutput[REVERSAL_POTENTIAL_IDX]));\n // current flowing through cooperative clusters :\n paramInput[1] = number_of_open_channels;\n // total injected current:\n output[0] = paramInput[0];\n}\n\n#endif\n\n#ifndef __KERNEL__\n#ifdef ENABLE_LOOKUPTABLES\n\n/*! This function is called from DynClampAnalogOutput in user\n space/C++ context and can be used to create some lookuptables for\n nonlinear functions to be used by computeModel(). The implementation of this\n functions has to allocate an \\a x and \\a y array of floats of a sensible size \\a n.\n \\param[in] \\a k : the index for the lookup table to be generated.\n \\param[out] \\a n : the size of the lookup table (the number of elements in \\a x and \\a y).\n \\param[out] \\a x : the x-values.\n \\param[out] \\a y : the corresponding y-values.\n \\return: 0 if a lookuptable was generated, -1 otherwise.\n*/\n\ngsl_rng *rng_state;\n\nunsigned long get_seed_from_clock();\n\nvoid initialize_random_number_generator() {\n const gsl_rng_type *T;\n unsigned long int seed = get_seed_from_clock();\n\n gsl_rng_env_setup();\n T = gsl_rng_default;\n\n rng_state = gsl_rng_alloc(T);\n gsl_rng_set(rng_state, seed);\n}\n\nunsigned long get_seed_from_clock() {\n clock_t current;\n current = clock();\n return (unsigned long int) current;\n}\n\n\nint generateLookupTable(int k, float **x, float **y, int *n) {\n initialize_random_number_generator();\n if (k == 0) {\n /* Lookup-table for the Random number generator: */\n const int nn = RAND_PERIOD;\n *n = nn;\n#ifdef __LOCAL_SIMULATION_ENV__\n *x = (float *) malloc(nn * sizeof(float));\n#else\n *x = new float[nn];\n#endif\n for (int j = 0; j < nn; j++) {\n float xx = gsl_rng_uniform(rng_state);\n (*x)[j] = xx;\n }\n return 0;\n }\n\n return -1;\n}\n\n#endif\n#endif\n\n//############# END DYNAMIC_CLAMP CODE ##################\n\n#ifdef __LOCAL_SIMULATION_ENV__\n\nvoid setVoltage(float voltage) {\n input[0] = voltage;\n}\n\nvoid setConductance(float conductance) {\n paramOutput[0] = conductance;\n}\n\nvoid setReversalPotential(float reversalPotential) {\n paramOutput[1] = reversalPotential;\n}\n\nvoid setClusterInteraction(float clusterInteraction) {\n paramOutput[2] = clusterInteraction;\n}\n\nvoid setTimeConstant(float timeConstant) {\n paramOutput[3] = timeConstant;\n}\n\nvoid setClusterSize(float clusterSize) {\n paramOutput[4] = clusterSize;\n}\n\nvoid setClusterNumber(float clusterNumber) {\n paramOutput[5] = clusterNumber;\n}\n\nvoid setVhalf(float vhalf) {\n paramOutput[6] = vhalf;\n}\n\nvoid setClusterInit(float clusterInit) {\n paramOutput[7] = clusterInit;\n}\n\nvoid setLoopInterval(float interval) {\n loopInterval = interval;\n}\n\nfloat getCurrentOutput(void) {\n return output[0];\n}\n\nint getClusterSize(void) {\n return cluster_size;\n}\n\nint getClusterState(int i) {\n return cluster_states[i];\n}\n\n#endif\n", "meta": {"hexsha": "9514abc613b2b0fac8c4a67bffb14c0f2d3f8f11", "size": 11306, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dynclamp_models/model.c", "max_stars_repo_name": "elifesciences-publications/49974-dynamic_clamp_model", "max_stars_repo_head_hexsha": "a05557002ba36d1be32c5dd5aa601842091b3e09", "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/dynclamp_models/model.c", "max_issues_repo_name": "elifesciences-publications/49974-dynamic_clamp_model", "max_issues_repo_head_hexsha": "a05557002ba36d1be32c5dd5aa601842091b3e09", "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/dynclamp_models/model.c", "max_forks_repo_name": "elifesciences-publications/49974-dynamic_clamp_model", "max_forks_repo_head_hexsha": "a05557002ba36d1be32c5dd5aa601842091b3e09", "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.2144702842, "max_line_length": 133, "alphanum_fraction": 0.658853706, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46902086651179875}} {"text": "/**\n@file\n\nCopyright John Reid 2007\n\n*/\n\n#ifndef MYRRH_MATH_H_\n#define MYRRH_MATH_H_\n\n#ifdef _MSC_VER\n# pragma once\n#endif //_MSC_VER\n\n#include \"myrrh/defs.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#if BOOST_VERSION < 104400\n# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace\n#elif BOOST_VERSION < 104500\n# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace\n#elif BOOST_VERSION < 104600\n# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace\n#elif BOOST_VERSION < 104900\n# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace\n#elif BOOST_VERSION >= 105900\n# include \n# include \n# define MYRRH_FPC_NS ::boost::math::fpc ///< Floating point comparison namespace\n#else\n# define MYRRH_FPC_NS ::boost::test_tools ///< Floating point comparison namespace\n#endif\n\n#ifdef _MSC_VER\n# define MYRRH_ISNAN( x ) _isnan( x )\n# define MYRRH_ISFINITE( x ) _finite( x )\n#else\n# define MYRRH_ISNAN( x ) ::boost::math::isnan( x )\n# define MYRRH_ISFINITE( x ) ::boost::math::isfinite( x )\n#endif\n\n#ifdef max\n#undef max\n#endif //max\n\n#ifdef min\n#undef min\n#endif //min\n\n\n\nnamespace myrrh {\n\n\n\ntemplate< typename T >\nT int_power( T x, unsigned exponent )\n{\n T result = T( 1.0 );\n for( unsigned i = 0; exponent != i; ++i ) result *= x;\n return result;\n}\n\ninline\nint\nnearest_integer( double a )\n{\n return static_cast( a < 0.0 ? a - 0.5 : a + 0.5 );\n}\n\ninline bool within_closed_range( double x, double lower, double higher )\n{\n return MYRRH_ISFINITE( x ) && lower <= x && x <= higher;\n}\n\ninline bool is_probability( double x )\n{\n return within_closed_range( x, 0.0, 1.0 );\n}\n\ntemplate< typename T >\nbool\nis_close( T t1, T t2, T percent_tolerance )\n{\n return boost::test_tools::check_is_close( t1, t2, MYRRH_FPC_NS::percent_tolerance( percent_tolerance ) );\n}\n\n\ninline\ndouble\nsafe_exp( double x )\n{\n return ( x <= GSL_LOG_DBL_MIN ) ? 0.0 : gsl_sf_exp( x );\n}\n\ninline\ndouble\nsafe_log( double x )\n{\n if( 0.0 == x ) return - std::numeric_limits< double >::max();\n if( 0.0 > x ) return std::numeric_limits< double >::quiet_NaN();\n return gsl_sf_log( x );\n}\n\n\n/**\nReturns the log of the sum of 2 values, when the values are passed as their logarithms.\n\nI.e. we have log(p) and log(q), we want to calculate log(p+q).\n*/\ninline\ndouble\nlog_sum_of_logs(\n double log_p,\n double log_q )\n{\n //make sure log_p is the larger of the two, so that exp( log(q) - log(p) ) is small\n if( log_q > log_p ) std::swap( log_q, log_p );\n BOOST_ASSERT( log_p >= log_q );\n\n return log_p + gsl_sf_log_1plusx( safe_exp( log_q - log_p ) );\n}\n\n/** Ensures that the sum of the elements in the range adds to the given value. Returns the scale factor used. */\ntemplate< typename Range >\ndouble\nscale(\n Range & range,\n typename boost::range_value< Range >::type desired_sum = 1.0 )\n{\n using boost::begin;\n using boost::end;\n using boost::range_value;\n\n typedef typename range_value< Range >::type value_type;\n\n const value_type current_sum =\n std::accumulate(\n begin( range ),\n end( range ),\n 0.0 );\n\n const double scale_factor = desired_sum / current_sum;\n BOOST_FOREACH( value_type & v, range ) v *= scale_factor;\n\n return scale_factor;\n}\n\nnamespace gsl {\nnamespace impl {\n\ninline\nvoid\nerror_handler(\n const char * reason,\n const char * file,\n int line,\n int gsl_errno)\n{\n using namespace std;\n\n const string msg = MYRRH_MAKE_STRING( \"GSL error(\" << gsl_errno << \"): \" << file << \"(\" << line << \"): \" << reason );\n //cout << msg << endl;\n throw logic_error( msg );\n}\n\n} //namespace impl\n\n\ninline\nvoid init()\n{\n static bool inited = false;\n if( ! inited )\n {\n gsl_set_error_handler( impl::error_handler );\n inited = true;\n }\n}\n\ninline\ngsl_rng *\nget_rng()\n{\n static const gsl_rng_type * T = 0;\n static gsl_rng * r = 0;\n\n if( 0 == T || 0 == r )\n {\n init();\n\n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n if( ! T ) throw std::logic_error( \"Could not find default GSL random number generator type\" );\n\n r = gsl_rng_alloc( T );\n if( ! r ) throw std::logic_error( \"Could not allocate GSL random number generator\" );\n }\n return r;\n}\n\n\n\ntemplate< typename Range >\nunsigned\none_sample_from_multinomial(\n const Range & dist,\n double weight = 1.0,\n gsl_rng * rng = gsl::get_rng() )\n{\n double uniform_sample = gsl_rng_uniform( rng ) * weight;\n unsigned result = 0;\n BOOST_FOREACH( double p, dist )\n {\n uniform_sample -= p;\n if( uniform_sample < 0.0 ) return result;\n ++result;\n }\n throw std::logic_error( \"Multinomial parameters did not sum to 1 (or the supplied weight)\" );\n}\n\n\ntemplate<\n typename ParameterRange,\n typename OutputRange\n>\nvoid\ndraw_from_dirichlet(\n const ParameterRange & alpha,\n OutputRange & output,\n gsl_rng * rng = gsl::get_rng() )\n{\n using boost::size;\n using boost::begin;\n\n BOOST_ASSERT( size( alpha ) == size( output ) );\n\n gsl_ran_dirichlet(\n rng,\n size( alpha ),\n &*boost::begin( alpha ),\n &*boost::begin( output ) );\n}\n\n\ntemplate<\n typename ParameterRange,\n typename ValueRange\n>\ndouble\ndirichlet_ln_pdf(\n const ParameterRange & alpha,\n const ValueRange & values )\n{\n using namespace boost;\n\n typedef typename range_value< ParameterRange >::type param_t;\n typedef typename range_value< ValueRange >::type value_t;\n typedef boost::tuple< param_t, value_t > tuple;\n\n BOOST_ASSERT( size( alpha ) == size( values ) );\n\n double result = 0.0;\n param_t alpha_sum = 0.0;\n\n BOOST_FOREACH(\n const tuple & t,\n make_iterator_range(\n make_zip_iterator(\n make_tuple(\n const_begin( alpha ),\n const_begin( values ) ) ),\n make_zip_iterator(\n make_tuple(\n const_end( alpha ),\n const_end( values )) ) ) )\n {\n const param_t a = t.get< 0 >();\n const value_t v = t.get< 1 >();\n alpha_sum += a;\n result += ( a - param_t( 1.0 ) ) * gsl_sf_log( v );\n std::cout << a << \"\\n\";\n result -= gsl_sf_lngamma( a );\n }\n\n return result + gsl_sf_lngamma( alpha_sum );\n}\n\n\n\n/**\nPre-processed sampling from general discrete distributions.\n\nSee http://www.gnu.org/software/gsl/manual/html_node/General-Discrete-Distributions.html\n*/\nstruct ran_discrete : boost::noncopyable\n{\n typedef boost::shared_ptr< ran_discrete > ptr;\n\n gsl_ran_discrete_t * _pre_processed;\n\n inline ran_discrete(size_t K, const double * P)\n : _pre_processed( gsl_ran_discrete_preproc( K, P ) )\n {\n }\n\n template< typename Range >\n ran_discrete( const Range & P_range )\n {\n using namespace boost;\n const size_t K = size( P_range );\n std::vector< double > P( K );\n std::copy( begin( P_range ), end( P_range ), P.begin() );\n _pre_processed = gsl_ran_discrete_preproc( K, &(*(P.begin())) );\n }\n\n inline ~ran_discrete()\n {\n gsl_ran_discrete_free( _pre_processed );\n }\n\n size_t sample(gsl_rng * rng = get_rng()) const\n {\n return gsl_ran_discrete( rng, _pre_processed );\n }\n};\n\n\n\n\n\n\n} //namespace gsl\n} //namespace myrrh\n\n\n#endif //MYRRH_MATH_H_\n\n", "meta": {"hexsha": "54cd347e3b2db1f2e377299448db8550d2f7ae3a", "size": 8039, "ext": "h", "lang": "C", "max_stars_repo_path": "myrrh/math.h", "max_stars_repo_name": "JohnReid/myrrh", "max_stars_repo_head_hexsha": "09dc97c739232c03493e2344e64735b30eea5f99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T00:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-04T00:39:51.000Z", "max_issues_repo_path": "myrrh/math.h", "max_issues_repo_name": "JohnReid/myrrh", "max_issues_repo_head_hexsha": "09dc97c739232c03493e2344e64735b30eea5f99", "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": "myrrh/math.h", "max_forks_repo_name": "JohnReid/myrrh", "max_forks_repo_head_hexsha": "09dc97c739232c03493e2344e64735b30eea5f99", "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.0851648352, "max_line_length": 121, "alphanum_fraction": 0.6405025501, "num_tokens": 2139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.46898006109091606}} {"text": "/* Copyright (c) 2014, Giuseppe Argentieri \n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\n/*\n *\n *\n * Filename: cp_gen.c\n *\n * Description: Bloch matrix for the completely positive generator\n *\n * Version: 1.0\n * Created: 28/04/2014 23:09:21\n * Revision: none\n * License: BSD\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: Università degli Studi di Trieste\n *\n * \n */\n\n#include \n#include \n#include \n#include \"funcs.h\"\n\n\n/* \n * FUNCTION \n * Name: cp_mat\n * Description: Creating the CP generator matrix in Bloch form, taking as\n * \t\t arguments all the integrals, the physical parameters and \n * \t\t the pointer to the matrix\n * \n */\nint cp_mat ( gsl_matrix* cp_mx , void* params )\n{\n\tdouble integrals[12] ;\n\tif ( (integration(params,integrals)) != 0 )\n\t\treturn -1;\n\n\t/* Setting the integrals */\n\tdouble rcc, rss, rsc, isc, rcs, ics, rc0 ;\n\trcc = integrals[0] ;\n\trss = integrals[2] ;\n\trsc = integrals[4] ;\n\tisc = integrals[5] ;\n\trcs = integrals[6] ;\n\tics = integrals[7] ;\n\trc0 = integrals[8] ;\n\n\t/* Copying the parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p ( pars, &o_c, &b, &O, &o_1 ) ;\n\tdouble D = sqrt(POW_2(o_1)-POW_2(O)) ;\n\n\t/* Ensuring that the matrix is zeroed */\n\tgsl_matrix_set_zero ( cp_mx ) ;\n\n\t/* Building the matrix */\n\tunsigned int i ;\n\tfor ( i = 0; i < 4; i++ )\n\t\tgsl_matrix_set ( cp_mx, 0 , i , 0 ) ;\n\tgsl_matrix_set ( cp_mx, 1, 0, 0 ) ; \n\tgsl_matrix_set ( cp_mx, 1, 1, 2*(O/o_1)*rss+(1+POW_2(O/o_1))*rcc+2*POW_2(D/o_1)*rc0 ) ;\n\tgsl_matrix_set ( cp_mx, 1, 2, o_1/4-(1+POW_2(O/o_1))*rcs+2*(O/o_1)*rsc ) ;\n\tgsl_matrix_set ( cp_mx, 1, 3, 0\t) ;\n\tgsl_matrix_set ( cp_mx, 2, 0, 0\t) ;\n\tgsl_matrix_set ( cp_mx, 2, 1, -(o_1/4-(1+POW_2(O/o_1))*rcs+2*(O/o_1)*rsc) ) ;\n\tgsl_matrix_set ( cp_mx, 2, 2, 2*(O/o_1)*rss+(1+POW_2(O/o_1))*rcc+2*POW_2(D/o_1)*rc0 ) ;\n\tgsl_matrix_set ( cp_mx, 2, 3, 0\t) ;\n\tgsl_matrix_set ( cp_mx, 3, 0, (1+POW_2(O/o_1))*ics-2*(O/o_1)*isc ) ;\n\tgsl_matrix_set ( cp_mx, 3, 1, 0\t) ;\n\tgsl_matrix_set ( cp_mx, 3, 2, 0\t) ;\n\tgsl_matrix_set ( cp_mx, 3, 3, (1+POW_2(O/o_1))*rcc+2*(O/o_1)*rss ) ;\n\n\t/* Multiplies times -4 to obtain the Bloch matrix */\n\tgsl_matrix_scale ( cp_mx, -4 ) ;\n\n\treturn 0;\n}\t\t/* ----- end of function cp_mat ----- */\n\n\n", "meta": {"hexsha": "82c1e3441c65854122053e4b31a0071cdee785ec", "size": 3698, "ext": "c", "lang": "C", "max_stars_repo_path": "cp_gen.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cp_gen.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cp_gen.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6181818182, "max_line_length": 88, "alphanum_fraction": 0.6676581936, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.46855441264143993}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid compute_MCMC_ln_likelihood_default(MCMC_info *MCMC,\n double ** M,\n double * P,\n double * ln_likelihood_DS,\n int * n_DoF_DS,\n double * ln_likelihood_all,\n int * n_DoF_all) {\n int i_DS;\n int i_M;\n int n_M;\n double * M_target;\n double * dM_target;\n MCMC_DS_info *current_DS;\n MCMC_DS_info *next_DS;\n (*ln_likelihood_all) = 0.;\n (*n_DoF_all) = 0;\n i_DS = 0;\n current_DS = MCMC->DS;\n while(current_DS != NULL) {\n next_DS = current_DS->next;\n n_M = current_DS->n_M;\n M_target = current_DS->M_target;\n dM_target = current_DS->dM_target;\n ln_likelihood_DS[i_DS] = 0.;\n n_DoF_DS[i_DS] = 0;\n for(i_M = 0; i_M < n_M; i_M++) {\n ln_likelihood_DS[i_DS] += pow((M_target[i_M] - M[i_DS][i_M]) / dM_target[i_M], 2.);\n n_DoF_DS[i_DS]++;\n }\n (*ln_likelihood_all) += ln_likelihood_DS[i_DS];\n ln_likelihood_DS[i_DS] *= -0.5;\n (*n_DoF_all) += n_DoF_DS[i_DS];\n n_DoF_DS[i_DS] -= MCMC->n_P;\n i_DS++;\n current_DS = next_DS;\n }\n (*n_DoF_all) -= MCMC->n_P;\n (*ln_likelihood_all) *= -0.5;\n}\n", "meta": {"hexsha": "1fbf2ba479daeea286df9a44e2090493bbd5a833", "size": 1747, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC_ln_likelihood_default.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC_ln_likelihood_default.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/compute_MCMC_ln_likelihood_default.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 34.2549019608, "max_line_length": 95, "alphanum_fraction": 0.463079565, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.468554401227711}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\n/********************************HOPE: Sum of norm of residuals fitting for Hough Mode Extension Data*****************************************/\r\n//Copyright (C) 2012 Daniel Strano\r\n\r\n/*'Hope' is an open-source project based on Oberheide and Forbes GEOPHYSICAL RESEARCH LETTERS, VOL. 35, L04816, doi:10.1029/2007GL032397, 2008. The program was originally designed for the purpose of handling the challenge of empirically fitting multi-component complex wave data, in situations where the goodness of fit of a least squares model is questionable. The program was originally designed to work with three self-consistent variables to fit simultaneously. The variances of the variables are first scaled to satisify the assumptions of constant variance and independence of errors, necessary for a consistent least squares model. Then, the program takes advantage of the finite phase domain to indirectly search for a maximization of the sum of absolute (norms of) residuals.*/\r\n\r\n/*********************************************************************************************************************************************/\r\n\r\n#define depVar 3\r\nconst int rawblock = 29;\r\nconst int block = 33;\r\nconst int heightsOut = 8;\r\nconst int heightsIn = 8;\r\nconst int HME_N = 2;\r\nconst int HMEBlockCount = 8;\r\nconst int satrows = 264;\r\n\r\nconst double PI = 3.141592653589793;\r\nconst double PHASE_INTERVAL = 0.001;\r\nconst int PHASE_INT_INV = 1000;\r\nconst double P_I_x_PI = 0.001 * 3.141592653589793;\r\n\r\nint outrows=0;\r\ndouble totalSumSqr;\r\ndouble TotalSN[depVar];\r\n\r\nint global_phase_iter1 = 0;\r\nint global_phase_iter2 = 0;\r\n\r\nint threadtracker[4];\r\n\r\npthread_mutex_t iter_update;\r\npthread_mutex_t compare;\r\n\r\nsem_t threadsAvail;\r\n\r\ngsl_matrix *Full_Descrip;\r\ngsl_vector *dependent;\r\ngsl_vector *BestModel;\r\n\r\nint minIndepOffset;\r\ndouble *threadIndep;\r\n\r\ndouble BestPhase1;\r\ndouble BestPhase2;\r\n\r\ndouble BestResid = 0;\r\ndouble BestRNorm = 0;\r\n\r\nint itemscount;\r\n\r\nvoid *threadParallel(void *arg) {\r\n\r\n\tint *threadNum = (int *)arg; //Argument is used for thread scheduling (used at bottom of thread function)\r\n\r\n\tint phase_iter1, phase_iter2; //Local phase iteration holder variables\r\n\r\n\t//Lock the current global phase iteration counters, pull the next value for the local iteration, and update global counters:\r\n\tpthread_mutex_lock(&iter_update);\r\n\t\tphase_iter1 = global_phase_iter1;\r\n\t\tphase_iter2 = global_phase_iter2;\r\n\t\t++global_phase_iter1;\r\n\t\tif (global_phase_iter1 >= PHASE_INT_INV) {\r\n\t\t\tglobal_phase_iter1 = 0;\r\n\t\t\t++global_phase_iter2;\r\n\t\t}\r\n\tpthread_mutex_unlock(&iter_update);\r\n\t\r\n\tint loop1, loop2, loop3, loop4, loop5;\r\n\tint returncode;\r\n\tfloat phase_shift[2]= {P_I_x_PI * phase_iter1, P_I_x_PI * phase_iter2}; //Phase shifts calculated from phase iteration counters\r\n\tfloat Rotation[8]; //Used to rotate complex vectors\r\n\r\n\tint holder, holder2, holder3, holder4, holder5, holder6; //For loop optimization\r\n\r\n\tdouble chiSqr; //Sum of squares of residuals of each iterative model\r\n\tfloat coeff_of_determ; //Normalized coefficient of determination \"\"\r\n\r\n\t//Calculate rotation factors to apply phase shift corresponding to the current iteration:\t\r\n\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\tholder = loop1 * 4;\r\n\t\tholder2 = holder + 2;\r\n\t\tfor (loop2 = 0; loop2 < 2; loop2++) {\r\n\t\t\tRotation[holder + loop2] = cos(phase_shift[loop1]);\r\n\t\t\tif (loop2) {\r\n\t\t\t\tRotation[holder2 + loop2] = -1 * sin(phase_shift[loop1]);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tRotation[holder2 + loop2] = sin(phase_shift[loop1]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t//Declare objects for GSL least squares model for fixed phases:\r\n\tgsl_matrix *Local_Descrip = gsl_matrix_alloc(itemscount, HME_N); //Local description of amplitude-only model\r\n\tgsl_matrix *covariance = gsl_matrix_alloc(HME_N, HME_N);\r\n\tgsl_multifit_linear_workspace *modelspace = gsl_multifit_linear_alloc(itemscount, HME_N);\r\n\tgsl_vector *beta = gsl_vector_alloc(HME_N); //fitting parameters\r\n\r\n\t//Apply rotations and initialize 'Local_Descrip'\r\n\tfor (loop5 = 0; loop5 < HME_N; loop5++) {\r\n\t\tholder = loop5 * 4;\r\n\t\tholder2 = holder + 1;\r\n\t\tholder3 = holder2 + 1;\r\n\t\tholder4 = holder3 + 1;\r\n\t\tholder6 = loop5 * minIndepOffset;\r\n\t\tfor (loop1 = 0; loop1 < itemscount; loop1 += 2) {\r\n\t\t\tholder5 = loop1 + 1;\r\n\t\t\tgsl_matrix_set(Local_Descrip, loop1, loop5,\r\n\t\t\t\tRotation[holder] * threadIndep[holder6 + loop1] + Rotation[holder4] * threadIndep[holder6 + holder5]);\r\n\t\t\tgsl_matrix_set(Local_Descrip, holder5, loop5,\r\n\t\t\t\tRotation[holder2] * threadIndep[holder6 + holder5] + Rotation[holder3] * threadIndep[holder6 + loop1]);\r\n\t\t}\r\n\t}\r\n\r\n\t//Find least squares fit:\r\n\treturncode = gsl_multifit_linear(Local_Descrip, dependent, beta, covariance, &chiSqr, modelspace);\r\n\tcoeff_of_determ = 1 - chiSqr/totalSumSqr;\r\n\r\n\t//Free model space for fit (covariance is also not used):\r\n\tgsl_matrix_free(covariance);\r\n\tgsl_multifit_linear_free(modelspace);\r\n\r\n\t//From partial model beta parameters, calculate equivalent full model parameters:\r\n\tdouble sumNormResid[3] = {0, 0, 0};\r\n\tdouble R_norm = 0;\r\n\tdouble R_resid, I_resid;\r\n\tdouble Full_Beta[2 * HME_N];\r\n\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\tFull_Beta[2 * loop1] = gsl_vector_get(beta, loop1) * cos(phase_shift[loop1]);\r\n\t\tFull_Beta[2 * loop1 + 1] = gsl_vector_get(beta, loop1) * sin(phase_shift[loop1]);\r\n\t}\r\n\r\n\t//Re-weight variables to equal total weight for sum of norms of residuals model, \r\n\t//calculate sum of norms of residuals for full model from least squares beta coefficients:\r\n\tint maxiter1 = 2 * outrows;\r\n\tint maxiter2 = maxiter1 * depVar;\r\n\tint maxiter3 = HME_N * 2;\r\n\tfor (loop2 = 0; loop2 < maxiter2; loop2 += maxiter1) {\r\n\t\tholder3 = (int)(loop2/maxiter1);\r\n\t\tfor (loop1 = 0; loop1 < maxiter1; loop1 += 2) {\r\n\t\t\tR_resid = gsl_vector_get(dependent, loop1 + loop2);\r\n\t\t\tholder = loop2 + loop1;\r\n\t\t\tholder2 = holder + 1;\r\n\t\t\tfor (loop3 = 0; loop3 < maxiter3; loop3++) R_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, holder, loop3);\r\n\t\t\tI_resid = gsl_vector_get(dependent, holder2);\r\n\t\t\tfor (loop3 = 0; loop3 < maxiter3; loop3++) I_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, holder2, loop3);\r\n\t\t\tsumNormResid[holder3] += sqrt((R_resid * R_resid) + (I_resid * I_resid));\r\n\t\t}\r\n\t}\r\n\r\n\t//Calculated normalized coefficient of determination for sum of norms of residuals:\r\n\tfor (loop1 = 0; loop1 < depVar; loop1++) R_norm -= sumNormResid[loop1]/TotalSN[loop1];\r\n\tR_norm = R_norm/3;\r\n\tR_norm++;\r\n\r\n\r\n\t//Lock global best model comparisons and updates,\r\n\t//compare this thread's \"R-norm\" and update global best model if a better model has been found:\r\n\tpthread_mutex_lock(&compare);\r\n\t\tif (BestRNorm < R_norm) {\r\n\t\t\tBestRNorm = R_norm;\r\n\t\t\tBestResid = coeff_of_determ;\r\n\t\t\tBestPhase1 = phase_shift[0];\r\n\t\t\tBestPhase2 = phase_shift[1];\r\n\t\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\t\t\t\r\n\t\t\t\tgsl_vector_set(BestModel, loop1, gsl_vector_get(beta, loop1));\r\n\t\t\t}\r\n\t\t}\r\n\tpthread_mutex_unlock(&compare);\r\n\r\n\t//Free remaining manually allocated memory objects:\r\n\tgsl_matrix_free(Local_Descrip);\r\n\tgsl_vector_free(beta);\r\n\r\n\t//Prepare to signal to loop in main() that this thread identity is becoming free, then post to semaphore:\r\n\tthreadtracker[*threadNum] = 0;\r\n\tsem_post(&threadsAvail);\r\n\r\n\treturn NULL;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\r\n\t//Thread expects input files as specified below:\r\n\tif (argc != 4) {\r\n\t\tprintf(\"usage: hope [saber_t] [tidi_e] [tidi_n]\\n\");\r\n\t\tprintf(\"Note: Satellite data should be in *.csv form, in a single column, aligned by row, with no column or row names. Dummy value is -999. \\n\");\r\n\t}\r\n\telse {\r\n\r\n\t\tgsl_matrix *satellite[3];\r\n\r\n\t\tdouble *minIndep[2];\r\n\r\n\t\tint lev_rows;\r\n\t\tdouble height[heightsIn];\r\n\t\tdouble latitudes[rawblock];\r\n\r\n\t\tdouble *HME_ptr[8][HME_N];\r\n\r\n\t\tdouble **uninterp[HME_N][depVar*2];\r\n\t\tdouble **interp_lat[HME_N][depVar*2];\r\n\t\tdouble **interp_lev[HME_N][depVar*2];\r\n\r\n\t\tBestModel = gsl_vector_alloc(2);\r\n\r\n\t\tpthread_t zero;\r\n\t\tpthread_t one;\r\n\t\tpthread_t two;\r\n\t\tpthread_t three;\r\n\r\n\t\tsem_init(&threadsAvail, 0, 4);\r\n\r\n\t\tlong long maxpage;\r\n\t\tlong long pagein = 1;\r\n\t\tint comp, comp_int, tenth_percent_complete = 0, percent_complete = 0;\r\n\t\r\n\t\tint loop, loop1, loop2, loop3, loop4, loop5, loop6;\r\n\r\n\t\tint threadID[4];\r\n\r\n\t\tdouble TotalSumSqr[depVar];\r\n\t\tdouble Variance[depVar];\r\n\t\tdouble AbsDeviance[depVar];\r\n\t\tdouble Scale[depVar], DevScale[depVar];\r\n\r\n\t\tdouble scaledRow;\r\n\r\n\t\tint holder;\r\n\t\tint holder2;\r\n\t\t \r\n\t\tfor (loop = 0; loop < depVar; loop++) {\r\n\t\t\tTotalSumSqr[loop] = 0;\r\n\t\t\tTotalSN[loop] = 0;\r\n\t\t\tVariance[loop] = 0; //optional\r\n\t\t\tScale[loop] = 0; //optional\r\n\t\t}\r\n\r\n\t\tfor (loop = 0; loop < 4; loop++) {\r\n\t\t\tthreadtracker[loop] = 0;\r\n\t\t\tthreadID[loop] = loop;\r\n\t\t}\r\n\r\n\t\t\t//Read in raw data:\r\n\t\r\n\t\t\t\t//(Independent) descriptor data:\r\n\t\tapop_text_to_db(.text_file=\"HME1.csv\", .tabname=\"X1\", .has_row_names = 0, .has_col_names = 1);\r\n\t\tHME_ptr[0][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT lat FROM X1\"));\r\n\t\tHME_ptr[1][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT lev FROM X1\"));\r\n\t\tHME_ptr[2][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_t FROM X1\"));\r\n\t\tHME_ptr[3][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_t FROM X1\"));\r\n\t\tHME_ptr[4][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_e FROM X1\"));\r\n\t\tHME_ptr[5][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_e FROM X1\"));\r\n\t\tHME_ptr[6][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_n FROM X1\"));\r\n\t\tHME_ptr[7][0] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_n FROM X1\"));\r\n\t\r\n\t\tapop_text_to_db(.text_file=\"HME2.csv\", .tabname=\"X2\", .has_row_names = 0, .has_col_names = 1);\r\n\t\tHME_ptr[0][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT lat FROM X2\"));\r\n\t\tHME_ptr[1][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT lev FROM X2\"));\r\n\t\tHME_ptr[2][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_t FROM X2\"));\r\n\t\tHME_ptr[3][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_t FROM X2\"));\r\n\t\tHME_ptr[4][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_e FROM X2\"));\r\n\t\tHME_ptr[5][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_e FROM X2\"));\r\n\t\tHME_ptr[6][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT amp_n FROM X2\"));\r\n\t\tHME_ptr[7][1] = apop_vector_to_array(apop_query_to_vector(\"SELECT phase_n FROM X2\"));\r\n\r\n\t\t\t\t//(Dependent) variable data:\t\r\n\t\tapop_text_to_db(.text_file=argv[1], .tabname=\"Y_t\", .has_row_names = 0, .has_col_names = 1);\r\n\t\tsatellite[0] = apop_query_to_matrix(\"SELECT * FROM Y_t\");\r\n\t\r\n\t\tapop_text_to_db(.text_file=argv[2], .tabname=\"Y_e\", .has_row_names = 0, .has_col_names = 1);\r\n\t\tsatellite[1] = apop_query_to_matrix(\"SELECT * FROM Y_e\");\r\n\r\n\t\tapop_text_to_db(.text_file=argv[3], .tabname=\"Y_n\", .has_row_names = 0, .has_col_names = 1);\r\n\t\tsatellite[2] = apop_query_to_matrix(\"SELECT * FROM Y_n\");\r\n\r\n\r\n\t\t//Need to know how many non-dummy rows are in satellite data\r\n\t\t//Calculate total sum of squares and total sum of norms of satellite data while tallying non-dummy rows in 'outrows':\r\n\t\toutrows = 0;\r\n\t\tfor (loop1 = 0; loop1 < satrows; loop1++) {\r\n\t\t\tif (gsl_matrix_get(satellite[0], loop1, 0) > -990) {\r\n\t\t\t\tif (gsl_matrix_get(satellite[1], loop1, 0) > -990) {\r\n\t\t\t\t\tif (gsl_matrix_get(satellite[2], loop1, 0) > -990) {\r\n\t\t\t\t\t\tfor (loop2 = 0; loop2 < depVar; loop2++) {\r\n\t\t\t\t\t\t\tfor (loop3 = 0; loop3 < 2; loop3++) {\r\n\t\t\t\t\t\t\t\tTotalSumSqr[loop2] += (gsl_matrix_get(satellite[loop2], loop1, loop3) * gsl_matrix_get(satellite[loop2], loop1, loop3)); \r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tTotalSN[loop2] += sqrt((gsl_matrix_get(satellite[loop2], loop1, 0) * gsl_matrix_get(satellite[loop2], loop1, 0)) + (gsl_matrix_get(satellite[loop2], loop1, 1) * gsl_matrix_get(satellite[loop2], loop1, 1)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t++outrows;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\titemscount = outrows * depVar * 2; //Total number of data items (rows * columns)\r\n\r\n\t\t//Allocate arrays for uninterpolated data, lattitude interpolated data, and data interpolated by both lattitude and elevation:\r\n\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\r\n\t\t\tfor (loop2 = 0; loop2 < depVar * 2; loop2++) {\r\n\t\t\t\tuninterp[loop1][loop2] = malloc(HMEBlockCount * sizeof(double *));\r\n\t\t\t\tinterp_lat[loop1][loop2] = malloc(block * sizeof(double *));\r\n\t\t\t\tinterp_lev[loop1][loop2] = malloc(block * sizeof(double *));\r\n\t\t\t\tfor (loop3 = 0; loop3 < HMEBlockCount; loop3++) {\r\n\t\t\t\t\tuninterp[loop1][loop2][loop3] = malloc(rawblock * sizeof(double));\r\n\t\t\t\t}\r\n\t\t\t\tfor (loop3 = 0; loop3 < block; loop3++) {\r\n\t\t\t\t\tinterp_lat[loop1][loop2][loop3] = malloc(HMEBlockCount * sizeof(double));\r\n\t\t\t\t\tinterp_lev[loop1][loop2][loop3] = malloc(heightsOut * sizeof(double));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Initialize block of uninterpolated data:\r\n\t\tfor (loop1 = 0; loop1 < HMEBlockCount; loop1++) {\r\n\t\t\tholder = rawblock * loop1;\r\n\t\t\tfor (loop2 = 0; loop2 < 2 * depVar; loop2 += 2) {\r\n\t\t\t\tfor (loop3 = 0; loop3 < HME_N; loop3++) {\r\n\t\t\t\t\tfor (loop4 = 0; loop4 < rawblock; loop4++) {\r\n\t\t\t\t\t\tuninterp[loop3][0 + loop2][loop1][(rawblock - 1) - loop4] = *(HME_ptr[2 + loop2][loop3] + (holder + loop4)) * cos(*(HME_ptr[3 + loop2][loop3] + holder + loop4) / 12 * PI);\r\n\t\t\t\t\t\tuninterp[loop3][1 + loop2][loop1][(rawblock - 1) - loop4] = *(HME_ptr[2 + loop2][loop3] + (holder + loop4)) * sin(*(HME_ptr[3 + loop2][loop3] + holder + loop4) / 12 * PI);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Read lattitudes from input:\r\n\t\tfor (loop1 = 0; loop1 < rawblock; loop1++) {\r\n\t\t\tlatitudes[(rawblock - 1) - loop1] = *(HME_ptr[0][0] + loop1);\r\n\t\t}\r\n\t\t\r\n\t\t//Read elevations from input:\r\n\t\tfor (loop1 = 0; loop1 < heightsIn; loop1++) {\r\n\t\t\theight[loop1] = *(HME_ptr[1][0] + (loop1 * rawblock));\r\n\t\t}\r\n\t\t\r\n\r\n\t//GSL Spline Interpolation:\r\n\r\n\t\t//Lattitude interpolation:\r\n\t\tfor (loop = 0; loop < HME_N; loop++) {\t\t\r\n\t\t\tfor (loop3 = 0; loop3 < 2; loop3++) {\r\n\t\t\t\tfor (loop2 = 0; loop2 < HMEBlockCount; loop2++) {\r\n\t\t\t\t\tfor (loop4 = 0; loop4 < depVar * 2; loop4 += 2) {\r\n\t\t\t\t\t\tgsl_interp_accel *lat_acc = gsl_interp_accel_alloc();\r\n\t\t\t\t\t\tgsl_spline *lat_spline = gsl_spline_alloc(gsl_interp_cspline, rawblock);\r\n\t\t\t\t\t\tgsl_spline_init(lat_spline, latitudes, uninterp[loop][loop4 + loop3][loop2], rawblock);\r\n\r\n\t\t\t\t\t\tfor (loop1 = 0; loop1 < block; loop1++) {\r\n\t\t\t\t\t\t\tinterp_lat[loop][loop4 + loop3][loop1][loop2] = gsl_spline_eval(lat_spline, (loop1 * 5) - 80, lat_acc);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tgsl_spline_free (lat_spline);\r\n\t\t\t\t\t\tgsl_interp_accel_free (lat_acc);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Altitude (\"lev\") interpolation:\r\n\t\tholder = 0;\r\n\t\tfor (loop = 0; loop < HME_N; loop++) {\t\t\r\n\t\t\tfor (loop3 = 0; loop3 < 2; loop3++) {\r\n\t\t\t\tfor (loop1 = 0; loop1 < block; loop1++) {\r\n\t\t\t\t\tfor (loop4 = 0; loop4 < depVar * 2; loop4 += 2) {\r\n\t\t\t\t\t\tgsl_interp_accel *lev_acc = gsl_interp_accel_alloc();\r\n\t\t\t\t\t\tgsl_spline *lev_spline = gsl_spline_alloc(gsl_interp_cspline, heightsIn);\r\n\t\t\t\t\t\tgsl_spline_init(lev_spline, height, interp_lat[loop][loop4 + loop3][loop1], heightsIn);\r\n\r\n\t\t\t\t\t\tfor (loop2 = 0; loop2 < heightsOut; loop2++) {\r\n\t\t\t\t\t\t\tinterp_lev[loop][loop4 + loop3][loop1][loop2] = gsl_spline_eval(lev_spline, 87.5 + (loop2 * 2.5), lev_acc);\r\n\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tgsl_spline_free (lev_spline);\r\n\t\t\t\t\t\tgsl_interp_accel_free (lev_acc);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Variance and deviance calculation (for normalizing different variables):\r\n\t\tfor (loop1 = 0; loop1 < depVar; loop1++) {\r\n\t\t\tVariance[loop1] = TotalSumSqr[loop1] / (outrows/2);\r\n\t\t\tAbsDeviance[loop1] = TotalSN[loop1] / (outrows/2);\r\n\t\t}\r\n\r\n\t\tfor (loop1 = 0; loop1 < depVar; loop1++) {\r\n\t\t\tScale[loop1] = sqrt(Variance[0]/ Variance[loop1]);\r\n\t\t\tDevScale[loop1] = AbsDeviance[0] / AbsDeviance[loop1];\r\n\t\t}\r\n\r\n\t\t//In interative fit, phases are held fixed while amplitudes are fit\r\n\t\t//Phases are incremented after each amplitude fit\r\n\t\t//Create an array with the minimum information from the independent matrix necessary to perform iterative fit:\r\n\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\t\tminIndep[loop1] = malloc(satrows * depVar * 2 * sizeof(double));\r\n\t\t}\r\n\r\n\t\tloop4 = 0;\r\n\t\tfor (loop1 = 0; loop1 < heightsOut; loop1++) {\r\n\t\t\tfor (loop3 = 0; loop3 < depVar; loop3++) {\r\n\t\t\t\tfor (loop4 = 0; loop4 < block; loop4++) {\r\n\t\t\t\t\tfor (loop5 = 0; loop5 < HME_N; loop5++) {\r\n\t\t\t\t\t\tfor (loop = 0; loop < 2; loop++) {\r\n\t\t\t\t\t\t\tminIndep[loop5][(loop3 * 2 * satrows) + (block * 2 * loop1) + (loop4 * 2) + loop] = interp_lev[loop5][2 * loop3 + loop][block - 1 - loop4][loop1];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Garbage collection after pre-processing:\r\n\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\t\tfor (loop2 = 0; loop2 < depVar * 2; loop2++) {\r\n\t\t\t\tfor (loop3 = 0; loop3 < HMEBlockCount; loop3++) {\r\n\t\t\t\t\tfree(uninterp[loop1][loop2][loop3]);\r\n\t\t\t\t}\r\n\t\t\t\tfor (loop3 = 0; loop3 < block; loop3++) {\r\n\t\t\t\t\tfree(interp_lat[loop1][loop2][loop3]);\r\n\t\t\t\t\tfree(interp_lev[loop1][loop2][loop3]);\r\n\t\t\t\t}\r\n\t\t\t\tfree(uninterp[loop1][loop2]);\r\n\t\t\t\tfree(interp_lat[loop1][loop2]);\r\n\t\t\t\tfree(interp_lev[loop1][loop2]);\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Dummy values in satellite data can not be passed to GSL fitting functions\r\n\t\t//Real and imaginary components alternate.\r\n\t\t//The dependent variables counted by \"depVar\" are concatenated as contigious blocks\r\n\t\t//Remove dummy values and concatenate satellite vectors;\r\n\t\tdependent = gsl_vector_alloc(2 * depVar * outrows);\r\n\t\ttotalSumSqr = 0;\r\n\t\tfor (loop2 = 0; loop2 < depVar; loop2++) {\r\n\t\t\tloop5 = 0;\r\n\t\t\tfor (loop1 = 0; loop1 < satrows; loop1++) {\r\n\t\t\t\tif (gsl_matrix_get(satellite[0], loop1, 0) > -990) {\r\n\t\t\t\t\tif (gsl_matrix_get(satellite[1], loop1, 0) > -990) {\r\n\t\t\t\t\t\tif (gsl_matrix_get(satellite[2], loop1, 0) > -990) {\r\n\t\t\t\t\t\t\tfor (loop3 = 0; loop3 < 2; loop3++) {\r\n\t\t\t\t\t\t\t\tscaledRow = Scale[loop2] * gsl_matrix_get(satellite[loop2], loop1, loop3);\r\n\t\t\t\t\t\t\t\tgsl_vector_set(dependent, (2 * outrows * loop2) + loop5 + loop3, scaledRow);\r\n\t\t\t\t\t\t\t\ttotalSumSqr += scaledRow * scaledRow;\r\n\t\t\t\t\t\t\t\tfor (loop4 = 0; loop4 < HME_N; loop4++){\r\n\t\t\t\t\t\t\t\t\tminIndep[loop4][(2 * outrows * loop2) + loop5 + loop3] = Scale[loop2] * minIndep[loop4][(2 * satrows * loop2) + 2 * loop1 + loop3];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tloop5+=2;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Reallocate shrink minIndep once dummy values are removed:\r\n\t\tint *error_ptr;\r\n\t\tminIndepOffset = outrows * depVar * 2;\r\n\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\t\t error_ptr = realloc(minIndep[loop1], sizeof(double) * minIndepOffset);\r\n\t\t}\r\n\r\n\t\t//Create a 1D array of the minimum data that needs to be passed to threads for iterative fit:\r\n\t\tthreadIndep = malloc(sizeof(double) * minIndepOffset * HME_N);\r\n\t\tfor (loop1 = 0; loop1 < HME_N; loop1++) {\r\n\t\t\tfor (loop2 = 0; loop2 < minIndepOffset; loop2++) {\r\n\t\t\t\tthreadIndep[minIndepOffset * loop1 + loop2] = minIndep[loop1][loop2];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Create an array with the full 'clean' independent data for an (analytical) R^2 fit to compare against:\r\n\t\tFull_Descrip = gsl_matrix_alloc((outrows * depVar) * 2, HME_N * 2);\r\n\t\tgsl_matrix *covariance = gsl_matrix_alloc(HME_N * 2, HME_N * 2);\r\n\t\tgsl_multifit_linear_workspace *modelspace = gsl_multifit_linear_alloc((outrows * depVar) * 2, HME_N * 2);\r\n\t\tgsl_vector *beta = gsl_vector_alloc(HME_N * 2);\r\n\r\n\t\tfor (loop1 = 0; loop1 < 2 * outrows * depVar; loop1++) {\r\n\t\t\tfor (loop2 = 0; loop2 < HME_N; loop2++) {\r\n\t\t\t\tfor (loop3 = 0; loop3 < 2; loop3++) {\r\n\t\t\t\t\tif (loop3 && !(loop1 % 2)) {\r\n\t\t\t\t\t\tgsl_matrix_set(Full_Descrip, loop1, 2 * loop2 + loop3, -minIndep[loop2][loop1 + loop3]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tgsl_matrix_set(Full_Descrip, loop1, 2 * loop2 + loop3, minIndep[loop2][loop1 + loop3]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//'minIndep' is no longer needed\r\n\t\t//Release 'minIndep':\r\n\t\tfor (loop1 = 0; loop1 < 2; loop1++) {\r\n\t\t\tfree(minIndep[loop1]);\r\n\t\t}\r\n\r\n\t\t//Find R^2 fit for full independent array:\r\n\t\tdouble chiSqr;\r\n\t\tgsl_multifit_linear(Full_Descrip, dependent, beta, covariance, &chiSqr, modelspace);\r\n\t\tdouble coeff_of_determ = 1 - chiSqr/totalSumSqr;\r\n\r\n\t\t//Find sum of absolute norms of residuals for the returned least squares model (normalizing variables weights to new model moment):\r\n\t\tdouble sumNormResid[3] = {0, 0, 0};\r\n\t\tdouble R_norm = 0;\r\n\t\tdouble R_resid, I_resid;\r\n\t\tdouble Full_Beta[2 * HME_N];\r\n\t\tdouble amp_phase[2 * HME_N];\r\n\t\tfor (loop1 = 0; loop1 < HME_N * 2; loop1++) {\r\n\t\t\tFull_Beta[loop1] = gsl_vector_get(beta, loop1);\r\n\t\t}\r\n\r\n\t\tfor (loop1 = 0; loop1 < HME_N * 2; loop1+=2) {\r\n\t\t\tamp_phase[loop1] = sqrt(Full_Beta[loop1] * Full_Beta[loop1] + Full_Beta[loop1 + 1] * Full_Beta[loop1 + 1]);\r\n\t\t\tamp_phase[loop1+1] = atan(Full_Beta[loop1 + 1] / Full_Beta[loop1]);\r\n\t\t}\r\n\r\n\t\tint maxiter1 = 2 * outrows;\r\n\t\tint maxiter2 = maxiter1 * depVar;\r\n\t\tfor (loop2 = 0; loop2 < maxiter2; loop2 += maxiter1) {\r\n\t\t\tfor (loop1 = 0; loop1 < maxiter1; loop1 += 2) {\r\n\t\t\t\tR_resid = gsl_vector_get(dependent, loop1 + loop2);\r\n\t\t\t\tfor (loop3 = 0; loop3 < HME_N * 2; loop3++) R_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, loop2 + loop1, loop3);\r\n\t\t\t\tI_resid = gsl_vector_get(dependent, loop1 + loop2 + 1);\r\n\t\t\t\tfor (loop3 = 0; loop3 < HME_N * 2; loop3++) I_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, loop2 + loop1 + 1, loop3);\r\n\t\t\t\tsumNormResid[(int)(loop2/maxiter1)] += sqrt((R_resid * R_resid) + (I_resid * I_resid));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor (loop1 = 0; loop1 < depVar; loop1++) R_norm -= sumNormResid[loop1]/TotalSN[loop1];\r\n\t\tR_norm = R_norm/3;\r\n\t\tR_norm += 1;\r\n\r\n\t\t//Pre-processing has completed\r\n\t\t\r\n\t\t//Start calling iterative fitting threads for R-norm:\r\n\t\tsem_wait(&threadsAvail);\r\n\t\tthreadtracker[0] = 1;\r\n\t\tpthread_create(&zero,NULL,threadParallel, &threadID[0]);\r\n\t\t++pagein;\r\n\r\n\t\tsem_wait(&threadsAvail);\r\n\t\tthreadtracker[1] = 1;\r\n\t\tpthread_create(&one,NULL,threadParallel, &threadID[1]);\r\n\t\t++pagein;\r\n\r\n\t\tsem_wait(&threadsAvail);\r\n\t\tthreadtracker[2] = 1;\r\n\t\tpthread_create(&two,NULL,threadParallel, &threadID[2]);\r\n\t\t++pagein;\r\n\r\n\t\tsem_wait(&threadsAvail);\r\n\t\tthreadtracker[3] = 1;\r\n\t\tpthread_create(&three,NULL,threadParallel, &threadID[3]);\r\n\t\t++pagein;\r\n\r\n\t\t//With every thread initially called, begin thread scheduling:\r\n\r\n\t\tmaxpage = (PHASE_INT_INV) * (PHASE_INT_INV);\r\n\t\r\n\t\tcomp = floor(maxpage/1000);\r\n\t\tcomp_int = comp;\r\n\t\r\n\t\twhile (pagein < maxpage) {\r\n\r\n\t\t\tsem_wait(&threadsAvail);\r\n\t\t\tif (!threadtracker[0]) {\r\n\t\t\t\tthreadtracker[0] = 1;\r\n\t\t\t\tpthread_join(zero, NULL);\r\n\t\t\t\tpthread_create(&zero,NULL,threadParallel, &threadID[0]);\r\n\t\t\t}\r\n\t\t\telse if (!threadtracker[1]) {\r\n\t\t\t\tthreadtracker[1] = 1;\r\n\t\t\t\tpthread_join(one, NULL);\r\n\t\t\t\tpthread_create(&one,NULL,threadParallel, &threadID[1]);\r\n\t\t\t}\r\n\t\t\telse if (!threadtracker[2]) {\r\n\t\t\t\tthreadtracker[2] = 1;\r\n\t\t\t\tpthread_join(two, NULL);\r\n\t\t\t\tpthread_create(&two,NULL,threadParallel, &threadID[2]);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tthreadtracker[3] = 1;\r\n\t\t\t\tpthread_join(three, NULL);\r\n\t\t\t\tpthread_create(&three, NULL, threadParallel, &threadID[3]);\r\n\t\t\t}\r\n\t\t\t++pagein;\r\n\r\n\t\t\t//Output progress on percent or 1/10 of a percent of completion:\r\n\t\t\tif (pagein > comp) {\r\n\t\t\t\tcomp = comp + comp_int;\r\n\t\t\t\t++tenth_percent_complete;\r\n\t\t\t\tif (tenth_percent_complete > 9) {\r\n\t\t\t\t\t++percent_complete;\r\n\t\t\t\t\ttenth_percent_complete = 0;\t\r\n\t\t\t\t\t//printf(\"Phase intercept 1: %f \\n\", BestPhase1);\r\n\t\t\t\t\t//printf(\"Phase intercept 2: %f \\n\", BestPhase2);\r\n\t\t\t\t\t//printf(\"R Squared average: %f \\n\", BestResid);\r\n\t\t\t\t\t//printf(\"%d.%d percent complete \\n \\n\", percent_complete, tenth_percent_complete);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tprintf(\"Amplitude 1: %f \\n\", gsl_vector_get(BestModel, 0));\r\n\t\t\t\tprintf(\"Phase intercept 1: %f \\n\", BestPhase1);\r\n\t\t\t\tprintf(\"Amplitude 2: %f \\n\", gsl_vector_get(BestModel, 1));\r\n\t\t\t\tprintf(\"Phase intercept 2: %f \\n\", BestPhase2);\r\n\t\t\t\tprintf(\"Best R norm: %f \\n\", BestRNorm);\r\n\t\t\t\tprintf(\"Corresponding R^2: %f \\n\", BestResid);\r\n\t\t\t\tprintf(\"Best R^2: %f \\n\", coeff_of_determ);\r\n\t\t\t\tprintf(\"Best R^2 Amplitude 1: %f \\n\", amp_phase[0]);\r\n\t\t\t\tprintf(\"Best R^2 Phase intercept 1: %f \\n\", amp_phase[1]);\r\n\t\t\t\tprintf(\"Best R^2 Amplitude 2: %f \\n\", amp_phase[2]);\r\n\t\t\t\tprintf(\"Best R^2 Phase intercept 2: %f \\n\", amp_phase[3]);\r\n\t\t\t\tprintf(\"R norm corresponding to analytical best R^2: %f \\n\", R_norm);\r\n\t\t\t\tprintf(\"%d.%d percent complete \\n \\n\", percent_complete, tenth_percent_complete);\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//All iterations have been called\r\n\t\t//Join last calls:\r\n\t\tpthread_join(zero, NULL);\r\n\t\tpthread_join(one, NULL);\r\n\t\tpthread_join(two, NULL);\r\n\t\tpthread_join(three, NULL);\r\n\r\n\t\t//Print final result:\r\n\t\tprintf(\"Best phase 1 intercept: %f \\n\", BestPhase1);\r\n\t\tprintf(\"Best phase 2 intercept: %f \\n\", BestPhase2);\r\n\t\tprintf(\"Best R norm: %f \\n\", BestRNorm);\r\n\t\tprintf(\"Best corresponding R squared: %f \\n\", BestResid);\r\n\t\tprintf(\"Corresponding R^2: %f \\n\", BestResid);\r\n\t\tprintf(\"Best R^2: %f \\n\", coeff_of_determ);\r\n\t\tprintf(\"Best R^2 Amplitude 1: %f \\n\", amp_phase[0]);\r\n\t\tprintf(\"Best R^2 Phase intercept 1: %f \\n\", amp_phase[1]);\r\n\t\tprintf(\"Best R^2 Amplitude 2: %f \\n\", amp_phase[2]);\r\n\t\tprintf(\"Best R^2 Phase intercept 2: %f \\n\", amp_phase[3]);\r\n\t\tprintf(\"R norm corresponding to analytical best R^2: %f \\n\", R_norm);\r\n\r\n\t\t//Free remaining manually allocated memory objects:\r\n\t\tfor (loop1 = 0; loop1 < depVar; loop1++) {\r\n\t\t\tgsl_matrix_free(satellite[loop1]);\r\n\t\t}\r\n\t\tgsl_vector_free(dependent);\r\n\t\tgsl_vector_free(BestModel);\r\n\t\tgsl_matrix_free(Full_Descrip);\r\n\t\t\r\n\t}\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "595e34aad1fb51c148632ba44092fb2bf8f76c83", "size": 25335, "ext": "c", "lang": "C", "max_stars_repo_path": "hope_r-norm.c", "max_stars_repo_name": "WrathfulSpatula/Hope", "max_stars_repo_head_hexsha": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-15T10:28:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T10:28:08.000Z", "max_issues_repo_path": "hope_r-norm.c", "max_issues_repo_name": "WrathfulSpatula/Hope", "max_issues_repo_head_hexsha": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hope_r-norm.c", "max_forks_repo_name": "WrathfulSpatula/Hope", "max_forks_repo_head_hexsha": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2703927492, "max_line_length": 787, "alphanum_fraction": 0.6527333728, "num_tokens": 8119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4685266559918339}} {"text": "//IN method.\n//Bilinear transformation (3D tensor of weights, 1D vector of biases)\n//of Ni1 inputs from X1 and Ni2 inputs from X2 to No outputs in Y.\n//This version uses CBLAS.\n\n//Input X1 has Ni1 neurons, X2 has Ni2 neurons, and output Y has No neurons.\n\n//If col-major: Y[o,l] = X1[:,l]' * W[:,:,o] * X2[:,l] + B[o]\n//where:\n//X1 has size Ni1 x L\n//X2 has size Ni2 x L\n//Y has size No x L\n//W has size Ni1 x Ni2 x No\n//B has size No x 1\n\n//If row-major: Y[l,o] = X1[l,:] * W[o,:,:] * X2[l,:]' + B[o]\n//X1 has size L x Ni1\n//X2 has size L x Ni2\n//Y has size L x No\n//W has size No x Ni2 x Ni1\n//B has size 1 x No\n\n//This is equal to the outer product of X1 and X2 at each l (time point),\n//and then take the weighted sum by each of the No matrices within W,\n//producing No scalars, one for each output neuron in Y.\n\n//I retain the for loop through L for compatibility with real-time streaming.\n\n//This CBLAS version not working yet!!\n\n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint bilinear_cblas_s (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);\nint bilinear_cblas_d (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);\nint bilinear_cblas_c (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);\nint bilinear_cblas_z (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);\n\n\nint bilinear_cblas_s (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)\n{\n const size_t N12 = Ni1*Ni2, Nw = N12*No;\n\n float *outer_prod;\n outer_prod = (float *)malloc(N12*sizeof(float));\n if (!outer_prod) { fprintf(stderr,\"error in bilinear_cblas_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n for (size_t l=L; l>0u; --l, X1+=Ni1, X2+=Ni2, B-=No, W-=Nw)\n {\n //Re-zero outer_prod\n for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0f; }\n\n //Outer product of X1, X2\n cblas_sger(CblasRowMajor,(int)Ni1,(int)Ni2,1.0f,X1,1,X2,1,outer_prod,(int)Ni2);\n\n //Weight by W for each output\n for (size_t o=No; o>0u; --o, ++B, ++Y, W+=N12)\n {\n *Y = *B + cblas_sdot((int)N12,W,1,outer_prod,1);\n //*Y = cblas_sdsdot((int)N12,*B,W,1,outer_prod,1);\n }\n }\n\n free(outer_prod);\n\n return 0;\n}\n\n\nint bilinear_cblas_d (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)\n{\n const size_t N12 = Ni1*Ni2, Nw = N12*No;\n\n double *outer_prod;\n outer_prod = (double *)malloc(N12*sizeof(double));\n if (!outer_prod) { fprintf(stderr,\"error in bilinear_cblas_d: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n for (size_t l=L; l>0u; --l, X1+=Ni1, X2+=Ni2, B-=No, W-=Nw)\n {\n //Re-zero outer_prod\n for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0; }\n\n //Outer product of X1, X2\n cblas_dger(CblasRowMajor,(int)Ni1,(int)Ni2,1.0,X1,1,X2,1,outer_prod,(int)Ni2);\n\n //Weight by W for each output\n for (size_t o=No; o>0u; --o, ++B, ++Y, W+=N12)\n {\n *Y = *B + cblas_ddot((int)N12,W,1,outer_prod,1);\n }\n }\n\n free(outer_prod);\n\n return 0;\n}\n\n\nint bilinear_cblas_c (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)\n{\n const size_t N12 = 2u*Ni1*Ni2, Nw = N12*No;\n const float oz[2] = {1.0f,0.0f};\n\n float *outer_prod;\n outer_prod = (float *)malloc(N12*sizeof(float));\n if (!outer_prod) { fprintf(stderr,\"error in bilinear_cblas_c: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n for (size_t l=L; l>0u; --l, X1+=2u*Ni1, X2+=2u*Ni2, B-=2u*No, W-=Nw)\n {\n //Re-zero outer_prod\n for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0f; }\n\n //Outer product of X1, X2\n cblas_cgeru(CblasRowMajor,(int)Ni1,(int)Ni2,oz,X1,1,X2,1,outer_prod,(int)Ni2);\n\n //Weight by W for each output\n for (size_t o=No; o>0u; --o, W+=N12)\n {\n cblas_cdotu_sub((int)N12,W,1,outer_prod,1,Y);\n *Y++ += *B++; *Y++ += *B++;\n }\n }\n\n free(outer_prod);\n\n return 0;\n}\n\n\nint bilinear_cblas_z (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)\n{\n const size_t N12 = 2u*Ni1*Ni2, Nw = N12*No;\n const double oz[2] = {1.0,0.0};\n\n double *outer_prod;\n outer_prod = (double *)malloc(N12*sizeof(double));\n if (!outer_prod) { fprintf(stderr,\"error in bilinear_cblas_z: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n for (size_t l=L; l>0u; --l, X1+=2u*Ni1, X2+=2u*Ni2, B-=2u*No, W-=Nw)\n {\n //Re-zero outer_prod\n for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0; }\n\n //Outer product of X1, X2\n cblas_zgeru(CblasRowMajor,(int)Ni1,(int)Ni2,oz,X1,1,X2,1,outer_prod,(int)Ni2);\n\n //Weight by W for each output\n for (size_t o=No; o>0u; --o, W+=N12)\n {\n cblas_zdotu_sub((int)N12,W,1,outer_prod,1,Y);\n *Y++ += *B++; *Y++ += *B++;\n }\n }\n\n free(outer_prod);\n\n return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "a81c21c912722f74b34d20a72ab999e10d5a937d", "size": 5686, "ext": "c", "lang": "C", "max_stars_repo_path": "c/bilinear.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/bilinear.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/bilinear.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": 33.2514619883, "max_line_length": 172, "alphanum_fraction": 0.6134365107, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4684858145876389}} {"text": "static char help[] =\n\"Solve a hyperbolic system in one space dimension (1D):\\n\"\n\" q_t + F(t,x,q)_x = g(t,x,q)\\n\"\n\"where solution q(t,x), flux F(t,x,q), and source g(t,x,q) are column vectors\\n\"\n\"of length n. The domain is (t,x) in [0,T] x [a,b]. The initial condition is\\n\"\n\"q(0,x) = f(x). The flux may be of the form\\n\"\n\" F(t,x,q) = A(t,x,q) q\\n\"\n\"but this is not required. Flux boundary conditions are used in all cases,\\n\"\n\" F = bdryflux_a(t,qright)\\n\"\n\" F = bdryflux_b(t,qleft)\\n\"\n\"including nonreflecting, reflecting, outflow, and periodic boundary\\n\"\n\"conditions.\\n\\n\"\n\"Uses a finite volume discretization so the grid values represent cell\\n\"\n\"averages. Each case implements a Riemann solver\\n\"\n\" F = faceflux(t,x,qleft,qright)\\n\"\n\"at cell faces. (The Riemann solver computes the value of the solution on\\n\"\n\"the cell face going forward in time.) Implements the following\\n\"\n\"slope-limiters when computing fluxes:\\n\"\n\" -limiter none Godunov's method, i.e. first-order upwinding\\n\"\n\" -limiter fromm formula (6.14) in LeVeque 2002\\n\"\n\" -limiter mc formula (6.29)\\n\"\n\" -limiter minmod formula (6.26)\\n\"\n\"Control the spatial grid by PETSc option\\n\"\n\" -da_grid_x M [grid of M cells/points]\\n\\n\"\n\"Time stepping is by semi-discretization in space (method of lines) and then\\n\"\n\"application of PETSc's (generally) adaptive and higher-order TS solvers.\\n\"\n\"Control time stepping and solution information by these PETSc options, among\\n\"\n\"others:\\n\"\n\" -ts_monitor [shows time steps]\\n\"\n\" -ts_monitor_solution draw [generate simple movie]\\n\"\n\" -draw_pause 0.1 -draw_size 2000,200 [control the movie]\\n\"\n\" -ts_type [default is rk]\\n\"\n\" -ts_rk_type X [default is 3bs]\\n\"\n\" -ts_dt 0.01 -ts_adapt_type none [turn off adaptive]\\n\"\n\"Note that TS solver type SSP (-ts_type ssp) is recommended for these\\n\"\n\"hyperbolic problems.\\n\\n\"\n\"Use option -problem selects the problem case:\\n\"\n\" -problem acoustic wave equation in system form (n=2) [default]\\n\"\n\" -problem advection scalar advection equation (n=1)\\n\"\n\" -problem swater shallow water equations (n=2)\\n\"\n\" -problem traffic scalar, nonlinear traffic equation (n=1)\\n\"\n\"To see possible initial conditions for problem X see the corresponding\\n\"\n\".h file. Based on the problem-specific possiblities, set\\n\"\n\" -initial Y\\n\\n\"\n\"See the makefile for test examples, and do 'make test' to test.\\n\\n\"\n\"This program is documented by the slides in the fvolume/ directory at\\n\"\n\"https://github.com/bueler/slide-teach\\n\\n\";\n\n\n#include \n\n/* The struct \"ProblemCtx\" is defined in cases.h. The comments in cases.h\nshow how to add new problems. */\n#include \"cases.h\"\n\n// minmod(a,b) as define on LeVeque page 111\nstatic PetscReal minmod(PetscReal a, PetscReal b) {\n if (a*b > 0) // both signs agree\n return (PetscAbs(a) < PetscAbs(b)) ? a : b;\n else\n return 0.0;\n}\n\ntypedef enum {NONE,FROMM,MC,MINMOD} LimiterType;\nstatic const char* LimiterTypes[] = {\"none\",\"fromm\",\"mc\",\"minmod\",\n \"LimiterType\", \"\", NULL};\n\nstatic LimiterType limiter = NONE; // slope-limiter\n\nextern PetscErrorCode FormInitial(DMDALocalInfo*, Vec, PetscReal, ProblemCtx*);\nextern PetscErrorCode GetMaxSpeed(DMDALocalInfo*, Vec, PetscReal, PetscReal*, ProblemCtx*);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal,\n PetscReal*, PetscReal*, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n TS ts; // ODE solver for method-of-lines (MOL)\n DM da; // structured grid\n Vec q; // the solution\n DMDALocalInfo info; // structured grid info\n ProblemType problem = ACOUSTIC; // which problem we are solving\n ProblemCtx user; // problem-specific information\n PetscInt swidth, k, steps;\n PetscBool flg;\n PetscReal hx, qmin, qmax, t0, tf, dt, c;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n // get which problem we are solving\n // (ProblemType, ProblemTypes, InitializerPtrs are defined in cases.h)\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"\",\n \"riemann (hyperbolic system solver) options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-problem\", \"problem type\",\n \"riemann.c\",ProblemTypes,(PetscEnum)(problem),(PetscEnum*)&problem,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-limiter\", \"limiter type\",\n \"riemann.c\",LimiterTypes,(PetscEnum)(limiter),(PetscEnum*)&limiter,\n NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n // call the initializer for the given case\n // (it allocates list of strings in user->field_names thus PetscFree below)\n ierr = (*InitializerPtrs[problem])(&user); CHKERRQ(ierr);\n\n // create grid\n swidth = (limiter == NONE) ? 1 : 2;\n ierr = DMDACreate1d(PETSC_COMM_WORLD,\n user.periodic_bcs ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE,\n 4, // default resolution\n user.n_dim, // system dimension (d.o.f.)\n swidth, // stencil (half) width\n 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 hx = (user.b_right - user.a_left) / info.mx;\n ierr = DMDASetUniformCoordinates(da,user.a_left+hx/2.0,user.b_right-hx/2.0,\n 0.0,1.0,0.0,1.0); CHKERRQ(ierr);\n\n // set field names so that visualization makes sense\n for (k = 0; k < info.dof; k++) {\n ierr = DMDASetFieldName(da,k,(user.field_names)[k]); CHKERRQ(ierr);\n }\n\n // create TS: dq/dt = G(t,q) form\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n ierr = TSSetDM(ts,da); CHKERRQ(ierr);\n ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,\n (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSRK); CHKERRQ(ierr); // defaults to -ts_rk_type 3bs\n\n // set up time axis\n ierr = TSSetTime(ts,user.t0_default); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,user.tf_default); CHKERRQ(ierr);\n dt = user.tf_default - user.t0_default;\n ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); // usually reset below\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts); CHKERRQ(ierr);\n\n // get initial values\n ierr = DMCreateGlobalVector(da,&q); CHKERRQ(ierr);\n ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);\n ierr = FormInitial(&info,q,t0,&user); CHKERRQ(ierr);\n //ierr = VecView(q,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n // use CFL to reset initial time-step dt (unless user sets)\n ierr = PetscOptionsHasName(NULL,NULL,\"-ts_dt\",&flg); CHKERRQ(ierr);\n ierr = GetMaxSpeed(&info,q,t0,&c,&user); CHKERRQ(ierr);\n if (!flg && c > 0.0) {\n ierr = TSGetMaxTime(ts,&tf); CHKERRQ(ierr);\n dt = PetscMin(hx / c, tf-t0);\n ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr);\n } else {\n ierr = TSGetTimeStep(ts,&dt); CHKERRQ(ierr);\n }\n\n // solve\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"solving problem %s, a system of %d equations,\\n\"\n \" on %d-point grid with dx=%.6f and initial dt=%.6f...\\n\",\n ProblemTypes[problem],info.dof,info.mx,hx,dt); CHKERRQ(ierr);\n ierr = TSSolve(ts,q); CHKERRQ(ierr);\n\n // report on solution\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" ... completed %d steps for %.4f <= t <= %.4f\\n\",\n steps,t0,tf); CHKERRQ(ierr);\n for (k = 0; k < info.dof; k++) {\n ierr = VecStrideMin(q,k,NULL,&qmin); CHKERRQ(ierr);\n ierr = VecStrideMax(q,k,NULL,&qmax); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" range of %d component: %8.5f <= %s <= %8.5f\\n\",\n k,qmin,(user.field_names)[k],qmax); CHKERRQ(ierr);\n }\n\n // free memory\n VecDestroy(&q); TSDestroy(&ts); DMDestroy(&da);\n ierr = PetscFree(user.field_names); CHKERRQ(ierr);\n return PetscFinalize();\n}\n\n\nPetscErrorCode FormInitial(DMDALocalInfo *info, Vec q, PetscReal t0, ProblemCtx *user) {\n PetscErrorCode ierr;\n const PetscReal hx = (user->b_right - user->a_left) / info->mx;\n PetscInt j;\n PetscReal x, *aq;\n\n ierr = DMDAVecGetArray(info->da, q, &aq); CHKERRQ(ierr);\n for (j=info->xs; jxs+info->xm; j++) {\n x = user->a_left + (j+0.5) * hx;\n ierr = user->f_initial(t0,x,&aq[(info->dof)*j]); CHKERRQ(ierr);\n }\n ierr = DMDAVecRestoreArray(info->da, q, &aq); CHKERRQ(ierr);\n return 0;\n}\n\n\nPetscErrorCode GetMaxSpeed(DMDALocalInfo *info, Vec q, PetscReal t,\n PetscReal *maxspeed, ProblemCtx *user) {\n PetscErrorCode ierr;\n const PetscReal hx = (user->b_right - user->a_left) / info->mx;\n PetscInt j;\n PetscReal x, cj, locmax, *aq;\n MPI_Comm comm;\n\n ierr = DMDAVecGetArray(info->da, q, &aq); CHKERRQ(ierr);\n locmax = 0.0;\n for (j=info->xs; jxs+info->xm; j++) {\n x = user->a_left + (j+0.5) * hx;\n ierr = user->maxspeed(t,x,&aq[(info->dof)*j],&cj); CHKERRQ(ierr);\n locmax = PetscMax(locmax,cj);\n }\n ierr = DMDAVecRestoreArray(info->da, q, &aq); CHKERRQ(ierr);\n ierr = PetscObjectGetComm((PetscObject)info->da,&comm); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&locmax,maxspeed,1,MPIU_REAL,MPIU_MAX,comm); CHKERRQ(ierr);\n return 0;\n}\n\n\nstatic inline void ncopy(PetscInt n, PetscReal *src, PetscReal *tgt) {\n PetscInt k;\n for (k = 0; k < n; k++)\n tgt[k] = src[k];\n}\n\nstatic inline void slopemodify(PetscInt n, PetscReal C,\n PetscReal *sig, PetscReal *Q_in,\n PetscReal *Q_out) {\n PetscInt k;\n for (k = 0; k < n; k++)\n Q_out[k] = Q_in[k] + C * sig[k];\n}\n\n// Right-hand-side of method-of-lines discretization form of PDE. Implements\n// Gudonov (i.e. Riemann-solver upwind) method with a slope limiter.\nPetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info, PetscReal t,\n PetscReal *aq, PetscReal *aG, void *ctx) {\n PetscErrorCode ierr;\n ProblemCtx *user = (ProblemCtx*)ctx;\n const PetscInt n = info->dof;\n const PetscReal hx = (user->b_right - user->a_left) / info->mx;\n Vec sig;\n PetscInt j, k;\n PetscReal x, *asig, sl, sr,\n *Ql, *Qr, // slope-limited values of solution at either\n // side of current face\n *Fl, *Fr; // face fluxes on either end of current cell\n\n // for each owned cell get slope using the slope-limiter\n ierr = DMCreateLocalVector(info->da,&sig); CHKERRQ(ierr);\n ierr = VecSet(sig,0.0); CHKERRQ(ierr); // implements limiter == NONE\n ierr = DMDAVecGetArray(info->da,sig,&asig); CHKERRQ(ierr);\n if (limiter != NONE) { // following block assumes swidth >= 2\n for (j = info->xs-1; j < info->xs + info->xm+1; j++) { // x_j is cell center\n for (k = 0; k < n; k++) {\n if ((j < 0 || j > info->mx-1) && user->periodic_bcs == PETSC_FALSE)\n continue;\n if (j == 0 && user->periodic_bcs == PETSC_FALSE)\n asig[n*j+k] = (aq[n*(j+1) + k] - aq[n*j + k]) / hx;\n else if (j == info->mx-1 && user->periodic_bcs == PETSC_FALSE)\n asig[n*j+k] = (aq[n*j + k] - aq[n*(j-1) + k]) / hx;\n else {\n if (limiter == FROMM) {\n asig[n*j+k] = (aq[n*(j+1) + k] - aq[n*(j-1) + k]) / (2.0 * hx);\n } else {\n sr = (aq[n*(j+1) + k] - aq[n*j + k]) / hx;\n sl = (aq[n*j + k] - aq[n*(j-1) + k]) / hx;\n if (limiter == MINMOD)\n asig[n*j+k] = minmod(sl,sr);\n else if (limiter == MC)\n asig[n*j+k] = minmod(0.5*(sl+sr),2.0*minmod(sl,sr));\n else {\n SETERRQ(PETSC_COMM_SELF,1,\"how did I get here?\\n\");\n }\n }\n }\n }\n }\n }\n\n // get left-face flux Fl for first cell owned by process; may be at x=a\n ierr = PetscMalloc4(n,&Ql,n,&Qr,n,&Fl,n,&Fr); CHKERRQ(ierr);\n if (info->xs == 0 && user->periodic_bcs == PETSC_FALSE) {\n // use right slope\n slopemodify(n,-hx/2.0,&asig[0],&aq[0],Qr);\n ierr = user->bdryflux_a(t,hx,Qr,Fl); CHKERRQ(ierr);\n } else {\n // use left and right (limited) slope [left is owned by other process]\n x = user->a_left + (info->xs+0.5) * hx;\n slopemodify(n,hx/2.0,&asig[n*(info->xs-1)],&aq[n*(info->xs-1)],Ql);\n slopemodify(n,-hx/2.0,&asig[n*(info->xs)],&aq[n*(info->xs)],Qr);\n ierr = user->faceflux(t,x-hx/2.0,Ql,Qr,Fl); CHKERRQ(ierr);\n }\n\n // for each owned cell, compute RHS G(t,x,q)\n for (j = info->xs; j < info->xs + info->xm; j++) { // x_j is cell center\n x = user->a_left + (j+0.5) * hx;\n // set aG[n j + k] = g(t,x_j,u)_k\n ierr = user->g_source(t,x,&aq[n*j],&aG[n*j]); CHKERRQ(ierr);\n // get right-face flux Fr for cell; may be at x=b\n if (j == info->mx-1 && user->periodic_bcs == PETSC_FALSE) {\n // user left slope\n slopemodify(n,hx/2.0,&asig[n*j],&aq[n*j],Ql);\n ierr = user->bdryflux_b(t,hx,Ql,Fr); CHKERRQ(ierr);\n } else {\n // use left and right (limited) slope; see formulas LeVeque page 193\n slopemodify(n,hx/2.0,&asig[n*j],&aq[n*j],Ql);\n slopemodify(n,-hx/2.0,&asig[n*(j+1)],&aq[n*(j+1)],Qr);\n ierr = user->faceflux(t,x+hx/2.0,Ql,Qr,Fr); CHKERRQ(ierr);\n }\n // complete the RHS:\n // aG[n j + k] = g(t,x_j,u)_k + (F_{j-1/2}_k - F_{j+1/2}_k) / hx\n for (k = 0; k < n; k++)\n aG[n*j+k] += (Fl[k] - Fr[k]) / hx;\n ncopy(n,Fr,Fl); // transfer Fr to Fl, for next loop\n }\n\n // clean up\n ierr = PetscFree4(Ql,Qr,Fl,Fr); CHKERRQ(ierr);\n ierr = DMDAVecRestoreArray(info->da,sig,&asig); CHKERRQ(ierr);\n ierr = VecDestroy(&sig); CHKERRQ(ierr);\n return 0;\n}\n\n", "meta": {"hexsha": "dd7fecb3f6d2acbc7bf50cb3dbf43cb23d30dc7d", "size": 14823, "ext": "c", "lang": "C", "max_stars_repo_path": "c/riemann/riemann.c", "max_stars_repo_name": "bueler/p4pdes-next", "max_stars_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "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/riemann/riemann.c", "max_issues_repo_name": "bueler/p4pdes-next", "max_issues_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "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/riemann/riemann.c", "max_forks_repo_name": "bueler/p4pdes-next", "max_forks_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "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": 44.9181818182, "max_line_length": 91, "alphanum_fraction": 0.5749173582, "num_tokens": 4424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.468211076693745}} {"text": "/* siman/siman_test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi\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/* A cute example of this program to then look at stuff would be:\n ./siman_test D3 | grep -v \"^#\" | awk '{print $3}' | sed 's/::/ /gp' > output\n\n then go into gnuplot and try typing:\n gnuplot> set parametric\n gnuplot> splot 'output' with lines\n\n Or you can plot from a pipe:\n gnuplot> plot '<../siman/siman_test | grep -v \"^#\"' using 1:2 with lines\n gnuplot> plot '<../siman/siman_test | grep -v \"^#\"' using 1:3 with lines\n and so forth. */\n\n/* set up parameters for this simulated annealing run */\n\n#define N_TRIES 200\t\t/* how many points do we try before stepping */\n#define ITERS_FIXED_T 1000\t/* how many iterations for each T? */\n#define STEP_SIZE 1.0\t\t/* max step size in random walk */\n#define K 1.0\t\t\t/* Boltzmann constant */\n#define T_INITIAL 0.008\t\t/* initial temperature */\n#define MU_T 1.003\t\t/* damping factor for temperature */\n#define T_MIN 2.0e-6\n\ngsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE,\n\t\t\t K, T_INITIAL, MU_T, T_MIN};\n\ndouble square(double x);\n\n\ndouble test_E_1D(Element x);\nvoid test_step_1D(const gsl_rng * r, Element *x_p, double step_size);\nvoid print_pos_1D(Element x);\ndouble distance_1D(Element x, Element y);\ndouble test_E_2D(Element x);\nvoid test_step_2D(const gsl_rng * r, Element *x_p, double step_size);\nvoid print_pos_2D(Element x);\ndouble distance_2D(Element x, Element y);\ndouble test_E_3D(Element x);\nvoid test_step_3D(const gsl_rng * r, Element *x_p, double step_size);\nvoid print_pos_3D(Element x);\ndouble distance_3D(Element x, Element y);\ndouble E1(void *xp);\ndouble M1(void *xp, void *yp);\nvoid S1(const gsl_rng * r, void *xp, double step_size);\nvoid P1(void *xp);\n\n\nint main(int argc, char *argv[])\n{\n Element x0;\t\t\t/* initial guess for search */\n\n/* double x_initial = 2.5; */\n double x_initial = -10.0;\n\n gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ;\n\n gsl_ieee_env_setup ();\n\n gsl_siman_solve(r, &x_initial, E1, S1, M1, P1, NULL, NULL, NULL,\n\t\t sizeof(double), params);\n\n return 0;\n\n if (argc != 2) {\n/* fprintf(stderr, \"usage: %s [D1, D2, D3, CA]\\n\", argv[0]); */\n fprintf(stderr, \"usage: %s [D1 | D2 | D3]\\n\", argv[0]);\n return 1;\n }\n\n printf(\"#testing the simulated annealing routines\\n\");\n if (strcmp(argv[1], \"D1\") == 0) {\n x0.D1 = 12.0;\n printf(\"#one dimensional problem, x0 = %f\\n\", x0.D1);\n/* gsl_siman_Usolve(r, &x0, test_E_1D, test_step_1D, distance_1D, */\n/* \t\t print_pos_1D, params); */\n return 0;\n }\n\n if (strcmp(argv[1], \"D2\") == 0) {\n x0.D2[0] = 12.0;\n x0.D2[1] = 5.5;\n printf(\"#two dimensional problem, (x0,y0) = (%f,%f)\\n\",\n\t x0.D2[0], x0.D2[1]);\n/* gsl_siman_Usolve(r, &x0, test_E_2D, test_step_2D, distance_2D, */\n/* \t\t print_pos_2D, params); */\n return 0;\n }\n\n if (strcmp(argv[1], \"D3\") == 0) {\n x0.D3[0] = 12.2;\n x0.D3[1] = 5.5;\n x0.D3[2] = -15.5;\n printf(\"#three dimensional problem, (x0,y0,z0) = (%f,%f,%f)\\n\",\n\t x0.D3[0], x0.D3[1], x0.D3[2]);\n/* gsl_siman_Usolve(r, &x0, test_E_3D, test_step_3D, distance_3D, */\n/* \t\t print_pos_3D, params); */\n }\n/*\n x0.D2[0] = 12.2;\n x0.D2[1] = 5.5;\n\n gsl_siman_solve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params);\n*/\n/*\n x0.D3[0] = 12.2;\n x0.D3[1] = 5.5;\n x0.D3[2] = -15.5;\n\n gsl_siman_solve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params);\n */\n\n return 0;\n}\n\ndouble square(double x)\n{\n return x*x;\n}\n\n\ndouble test_E_1D(Element x)\n{\n double val = x.D1;\n/*return sin(sin(val*val) - cos(val)) + cos(sin(val) + sin(val)*sin(val));*/\n return exp(-square(val-1))*sin(8*val);\n/* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x); */\n/* return 1.0/(square(x-1.0) + 1.0)*sin(8.0*x) + x*x/100.0; */\n}\n\n\n/* takes a step for the test function; max distance: step_size.\n * the new point is put in x_p and returned.\n */\nvoid test_step_1D(const gsl_rng * r, Element *x_p, double step_size)\n{\n double old_x = x_p->D1;\n double new_x;\n\n new_x = gsl_rng_uniform(r);\n new_x = new_x*2*step_size;\n new_x = new_x - step_size + old_x;\n\n x_p->D1 = new_x;\n}\n\n\n/* simple routine to print out a position value */\nvoid print_pos_1D(Element x)\n{\n printf(\"%12g\", x.D1);\n}\n\n/* a metric for the 2D space */\ndouble distance_1D(Element x, Element y)\n{\n return fabs(y.D1 - x.D1);\n}\n\n\n/* a 2-D function to be minimized */\ndouble test_E_2D(Element x)\n{\n double old_x = x.D2[0], old_y = x.D2[1];\n\n return exp(-square(old_x-1) - square(old_y - 0.8))*sin(8*old_x + 8 * old_y);\n}\n\n/* takes a step for the test function; max distance: step_size. the\n new point is put in x_p and returned. */\nvoid test_step_2D(const gsl_rng * r, Element *x_p, double step_size)\n{\n double old_x = x_p->D2[0], old_y = x_p->D2[1], new_x, new_y;\n\n new_x = gsl_rng_uniform(r);\n new_x = new_x*2*step_size;\n new_x = new_x - step_size + old_x;\n\n new_y = gsl_rng_uniform(r);\n new_y = new_y*2*step_size;\n new_y = new_y - step_size + old_y;\n\n x_p->D2[0] = new_x;\n x_p->D2[1] = new_y;\n}\n\n/* simple routine to print out a position value */\nvoid print_pos_2D(Element x)\n{\n printf(\"%g::%g\", x.D2[0], x.D2[1]);\n}\n\n/* a metric for the 2D space */\ndouble distance_2D(Element x, Element y)\n{\n return sqrt(square(y.D2[0]-x.D2[0]) + square(y.D2[1]-x.D2[1]));\n}\n\n\n/**********************************************/\n/************ 3-dimensional search ************/\n/**********************************************/\n\n/* a 3-D function to be minimized */\ndouble test_E_3D(Element x)\n{\n return exp(-square(x.D3[0]-1) - square(x.D3[1] - 0.8)\n - square(x.D3[2] - 0.8)) * sin(8*x.D3[0] + 8*x.D3[1] + 8*x.D3[2])\n + (square(x.D3[0]) + square(x.D3[1]) + square(x.D3[2]))/10000.0;\n}\n\n/* takes a step for the test function; max distance: step_size.\n * the new point is put in x_p and returned.\n */\nvoid test_step_3D(const gsl_rng * r, Element *x_p, double step_size)\n{\n double old_x = x_p->D3[0], old_y = x_p->D3[1], old_z = x_p->D3[2];\n double new_x, new_y, new_z;\n\n new_x = gsl_rng_uniform(r);\n new_x = new_x*2*step_size;\n new_x = new_x - step_size + old_x;\n\n new_y = gsl_rng_uniform(r);\n new_y = new_y*2*step_size;\n new_y = new_y - step_size + old_y;\n\n new_z = gsl_rng_uniform(r);\n new_z = new_z*2*step_size;\n new_z = new_z - step_size + old_z;\n\n x_p->D3[0] = new_x;\n x_p->D3[1] = new_y;\n x_p->D3[2] = new_z;\n}\n\n/* simple routine to print out a position value */\nvoid print_pos_3D(Element x)\n{\n printf(\"%g::%g::%g\", x.D3[0], x.D3[1], x.D3[2]);\n}\n\n/* a metric for the 2D space */\ndouble distance_3D(Element x, Element y)\n{\n return sqrt(square(y.D3[0]-x.D3[0]) + square(y.D3[1]-x.D3[1])\n\t + square(y.D3[2]-x.D3[2]));\n}\n\n/* now some functions to test in one dimension */\ndouble E1(void *xp)\n{\n double x = * ((double *) xp);\n\n return exp(-square(x-1))*sin(8*x) - exp(-square(x-1000))*0.89;\n/* return exp(-square(x-1))*sin(8*x); */\n}\n\ndouble M1(void *xp, void *yp)\n{\n double x = *((double *) xp);\n double y = *((double *) yp);\n\n return fabs(x - y);\n}\n\nvoid S1(const gsl_rng * r, void *xp, double step_size)\n{\n double old_x = *((double *) xp);\n double new_x;\n\n new_x = gsl_rng_uniform(r)*2*step_size - step_size + old_x;\n/* new_x = new_x*2*step_size; */\n/* new_x = new_x - step_size + old_x; */\n\n memcpy(xp, &new_x, sizeof(new_x));\n}\n\nvoid P1(void *xp)\n{\n printf(\" %12g \", *((double *) xp));\n}\n\n\n\n\n\n", "meta": {"hexsha": "5d41d18bde720d7d4a7e12a014e92f51e0a341b5", "size": 8208, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/siman/siman_test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/siman/siman_test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/siman/siman_test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.2236421725, "max_line_length": 86, "alphanum_fraction": 0.6309697856, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.46816169214263115}} {"text": "/* dht/dht.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 \n#include \n#include \"gsl_dht.h\"\n\n\ngsl_dht *\ngsl_dht_alloc (size_t size)\n{\n gsl_dht * t;\n\n if(size == 0) {\n GSL_ERROR_VAL(\"size == 0\", GSL_EDOM, 0);\n }\n\n t = (gsl_dht *)malloc(sizeof(gsl_dht));\n\n if(t == 0) {\n GSL_ERROR_VAL(\"out of memory\", GSL_ENOMEM, 0);\n }\n\n t->size = size;\n\n t->xmax = -1.0; /* Make it clear that this needs to be calculated. */\n t->nu = -1.0; \n\n t->j = (double *)malloc((size+2)*sizeof(double));\n\n if(t->j == 0) {\n free(t);\n GSL_ERROR_VAL(\"could not allocate memory for j\", GSL_ENOMEM, 0);\n }\n\n t->Jjj = (double *)malloc(size*(size+1)/2 * sizeof(double));\n\n if(t->Jjj == 0) {\n free(t->j);\n free(t);\n GSL_ERROR_VAL(\"could not allocate memory for Jjj\", GSL_ENOMEM, 0);\n }\n\n t->J2 = (double *)malloc((size+1)*sizeof(double));\n\n if(t->J2 == 0) {\n free(t->Jjj);\n free(t->j);\n free(t);\n GSL_ERROR_VAL(\"could not allocate memory for J2\", GSL_ENOMEM, 0);\n }\n\n return t;\n}\n\n/* Handle internal calculation of Bessel zeros. */\nstatic int\ndht_bessel_zeros(gsl_dht * t)\n{\n unsigned int s;\n gsl_sf_result z;\n int stat_z = 0;\n t->j[0] = 0.0;\n for(s=1; s < t->size + 2; s++) {\n stat_z += gsl_sf_bessel_zero_Jnu_e(t->nu, s, &z);\n t->j[s] = z.val;\n }\n if(stat_z != 0) {\n GSL_ERROR(\"could not compute bessel zeroes\", GSL_EFAILED);\n }\n else {\n return GSL_SUCCESS;\n }\n}\n\ngsl_dht *\ngsl_dht_new (size_t size, double nu, double xmax)\n{\n int status;\n\n gsl_dht * dht = gsl_dht_alloc (size);\n\n if (dht == 0)\n return 0;\n\n status = gsl_dht_init(dht, nu, xmax);\n \n if (status)\n return 0;\n\n return dht;\n}\n\nint\ngsl_dht_init(gsl_dht * t, double nu, double xmax)\n{\n if(xmax <= 0.0) {\n GSL_ERROR (\"xmax is not positive\", GSL_EDOM);\n } else if(nu < 0.0) {\n GSL_ERROR (\"nu is negative\", GSL_EDOM);\n }\n else {\n size_t n, m;\n int stat_bz = GSL_SUCCESS;\n int stat_J = 0;\n double jN;\n\n if(nu != t->nu) {\n /* Recalculate Bessel zeros if necessary. */\n t->nu = nu;\n stat_bz = dht_bessel_zeros(t);\n }\n\n jN = t->j[t->size+1];\n\n t->xmax = xmax;\n t->kmax = jN / xmax;\n\n t->J2[0] = 0.0;\n for(m=1; msize+1; m++) {\n gsl_sf_result J;\n stat_J += gsl_sf_bessel_Jnu_e(nu + 1.0, t->j[m], &J);\n t->J2[m] = J.val * J.val;\n }\n\n /* J_nu(j[n] j[m] / j[N]) = Jjj[n(n-1)/2 + m - 1], 1 <= n,m <= size\n */\n for(n=1; nsize+1; n++) {\n for(m=1; m<=n; m++) {\n double arg = t->j[n] * t->j[m] / jN;\n gsl_sf_result J;\n stat_J += gsl_sf_bessel_Jnu_e(nu, arg, &J);\n t->Jjj[n*(n-1)/2 + m - 1] = J.val;\n }\n }\n\n if(stat_J != 0) {\n GSL_ERROR(\"error computing bessel function\", GSL_EFAILED);\n }\n else {\n return stat_bz;\n }\n }\n}\n\n\ndouble gsl_dht_x_sample(const gsl_dht * t, int n)\n{\n return t->j[n+1]/t->j[t->size+1] * t->xmax;\n}\n\n\ndouble gsl_dht_k_sample(const gsl_dht * t, int n)\n{\n return t->j[n+1] / t->xmax;\n}\n\n\nvoid gsl_dht_free(gsl_dht * t)\n{\n free(t->J2);\n free(t->Jjj);\n free(t->j);\n free(t);\n}\n\n\nint\ngsl_dht_apply(const gsl_dht * t, double * f_in, double * f_out)\n{\n const double jN = t->j[t->size + 1];\n const double r = t->xmax / jN;\n size_t m;\n size_t i;\n\n for(m=0; msize; m++) {\n double sum = 0.0;\n double Y;\n for(i=0; isize; i++) {\n /* Need to find max and min so that we\n * address the symmetric Jjj matrix properly.\n * FIXME: we can presumably optimize this\n * by just running over the elements of Jjj\n * in a deterministic manner.\n */\n size_t m_local; \n size_t n_local;\n if(i < m) {\n m_local = i;\n\tn_local = m;\n }\n else {\n m_local = m;\n\tn_local = i;\n }\n Y = t->Jjj[n_local*(n_local+1)/2 + m_local] / t->J2[i+1];\n sum += Y * f_in[i];\n }\n f_out[m] = sum * 2.0 * r*r;\n }\n\n return GSL_SUCCESS;\n}\n\n", "meta": {"hexsha": "b82266c70cc09650b4b8c99fdf2b7b411fcbfc10", "size": 4753, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/dht/dht.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/dht/dht.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/dht/dht.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.0309734513, "max_line_length": 72, "alphanum_fraction": 0.5773195876, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4680972367988685}} {"text": "#include \n#include \n#include \n\n/*extern void dtrsm_(char *side, char *uplo, char *transa, char *diag, int *m,\n int *n, double *alpha, double *A, int *lda, double *B,\n int *ldb);*/\n\nJNIEXPORT jint Java_JAMAJni_QRDecomposition_dgeqrf (JNIEnv *env, jclass klass, jint matrix_layout,\n jint m, jint n, jdoubleArray a, jint lda,\n jdoubleArray tau){\n \n double *aElems, *tauElems;\n int info;\n \n aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);\n tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL);\n \n assert(aElems && tauElems);\n \n info = LAPACKE_dgeqrf ((int) matrix_layout, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, tauElems);\n \n (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);\n (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0);\n \n return info;\n \n}\n\nJNIEXPORT jint Java_JAMAJni_QRDecomposition_dorgqr (JNIEnv *env, jclass klass, jint matrix_layout,\n jint m, jint n, jint k, jdoubleArray a, jint lda,\n jdoubleArray tau){\n \n double *aElems, *tauElems;\n int info;\n \n aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);\n tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL);\n \n assert(aElems && tauElems);\n \n info = LAPACKE_dorgqr((int) matrix_layout, (lapack_int) m, (lapack_int) n, (lapack_int) k, aElems, (lapack_int) lda, tauElems);\n \n (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);\n (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0);\n \n return info;\n \n}\n\n\nJNIEXPORT jint Java_JAMAJni_QRDecomposition_dgeqp3 (JNIEnv *env, jclass klass, jint matrix_layout,\n jint m, jint n, jdoubleArray a, jint lda,\n jintArray jpvt, jdoubleArray tau){\n \n double *aElems, *tauElems;\n lapack_int *jpvtElems;\n int info;\n \n aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);\n tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL);\n jpvtElems = (*env)-> GetIntArrayElements (env, jpvt, NULL);\n \n assert(aElems && tauElems && jpvtElems);\n \n info = LAPACKE_dgeqp3 ((int) matrix_layout, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, jpvtElems, tauElems);\n \n (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);\n (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0);\n (*env)-> ReleaseIntArrayElements (env, jpvt, jpvtElems, 0);\n \n return info;\n}\n\nJNIEXPORT jint Java_JAMAJni_QRDecomposition_dormqr\n(JNIEnv *env, jclass klass, jint matrix_layout, jchar side, jchar trans,\n jint m, jint n, jint k, jdoubleArray a, jint lda, jdoubleArray tau,\n jdoubleArray c, jint ldc){\n \n double *aElems, *tauElems, *cElems;\n int info;\n \n aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);\n tauElems = (*env)-> GetDoubleArrayElements (env, tau, NULL);\n cElems = (*env)-> GetDoubleArrayElements (env, c, NULL);\n \n assert(aElems && tauElems && cElems);\n \n info = LAPACKE_dormqr ((int) matrix_layout, (char) side, (char) trans,\n (lapack_int) m, (lapack_int) n, (lapack_int) k,\n aElems, (lapack_int) lda, tauElems, cElems,\n (lapack_int) ldc);\n \n (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);\n (*env)-> ReleaseDoubleArrayElements (env, tau, tauElems, 0);\n (*env)-> ReleaseDoubleArrayElements (env, c, cElems, JNI_ABORT);\n \n return info;\n \n}\n\n\n", "meta": {"hexsha": "9e9881fa61ee3c008a74dd103caacd3f952b21db", "size": 3779, "ext": "c", "lang": "C", "max_stars_repo_path": "src/jni_lapacke/c/QRDecomposition.c", "max_stars_repo_name": "dw6ja/JAMAJni", "max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_stars_repo_licenses": ["AAL"], "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/jni_lapacke/c/QRDecomposition.c", "max_issues_repo_name": "dw6ja/JAMAJni", "max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_issues_repo_licenses": ["AAL"], "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/jni_lapacke/c/QRDecomposition.c", "max_forks_repo_name": "dw6ja/JAMAJni", "max_forks_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_forks_repo_licenses": ["AAL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6893203883, "max_line_length": 131, "alphanum_fraction": 0.5874569992, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.46791483931733724}} {"text": "#ifndef __gslInterp_\n#define __gslInterp__\n\n#include \"include/stdinc.h\"\n#include \n#include \n#include \n#include \n#include \n\nclass gslInterp {\nprotected:\n gsl_interp_accel *acc;\n gsl_interp *interp;\n vector x, y;\npublic:\n \n gslInterp(vector &x0, vector &y0) {\n acc = gsl_interp_accel_alloc();\n for (size_t i = 0; i < x0.size(); i++) {\n x.push_back(x0[i]);\n y.push_back(y0[i]);\n }\n interp = gsl_interp_alloc(gsl_interp_linear, x.size());\n gsl_interp_init(interp, &x[0], &y[0], x.size());\n }\n ~gslInterp() {\n gsl_interp_accel_free(acc);\n gsl_interp_free(interp); \n }\n void init(vector &x0, vector &y0) {\n gsl_interp_accel_free(acc);\n gsl_interp_free(interp); \n acc = gsl_interp_accel_alloc();\n x.clear();\n y.clear();\n for (size_t i = 0; i < x0.size(); i++) {\n x.push_back(x0[i]);\n y.push_back(y0[i]);\n }\n interp = gsl_interp_alloc(gsl_interp_linear, x.size());\n gsl_interp_init(interp, &x[0], &y[0], x.size());\n }\n\n inline double eval(double xc) {\n return gsl_interp_eval(interp, &x[0], &y[0], xc, acc);\n }\n inline double deriv(double xc) { \n return gsl_interp_eval_deriv(interp, &x[0], &y[0], xc, acc);\n }\n inline double deriv2(double xc) { \n return gsl_interp_eval_deriv2(interp, &x[0], &y[0], xc, acc);\n }\n inline double integ(double x_lo, double x_up) {\n return gsl_interp_eval_integ(interp, &x[0], &y[0], x_lo, x_up, acc);\n }\n};\n\n#endif // __gslInterp__\n", "meta": {"hexsha": "cc216048ca376075e17c15a973839124c02c526f", "size": 1598, "ext": "h", "lang": "C", "max_stars_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslInterp.h", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 26.6333333333, "max_line_length": 72, "alphanum_fraction": 0.6307884856, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.4674709263163101}} {"text": "/*\n * rw.c -- Loesung des Randwertproblems mit der GSL\n *\n * (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil\n */\n#include \n#include \n#include \n#include \n#include \n\nstatic double\tg = 9.81;\n\nstatic long\tfcounter = 0;\n\nstatic int\tf(double x, const double y[], double f[], void *params) {\n\tfcounter++;\n\tdouble\tg = *(double *)params;\n\tf[0] = y[2];\n\tf[1] = y[3];\n\tf[2] = 0;\n\tf[3] = -g;\n\treturn GSL_SUCCESS;\n}\n\nstatic long\tdfcounter = 0;\n\nstatic int\tdf(double x, const double y[], double *dfdy, double dfdx[],\n\t\t\tvoid *params) {\n\tdfcounter++;\n\n\tdfdy[0 * 4 + 0] = 0;\n\tdfdy[1 * 4 + 0] = 0;\n\tdfdy[2 * 4 + 0] = 0;\n\tdfdy[3 * 4 + 0] = 0;\n\n\tdfdy[0 * 4 + 1] = 0;\n\tdfdy[1 * 4 + 1] = 0;\n\tdfdy[2 * 4 + 1] = 0;\n\tdfdy[3 * 4 + 1] = 0;\n\n\tdfdy[0 * 4 + 2] = 1;\n\tdfdy[1 * 4 + 2] = 0;\n\tdfdy[2 * 4 + 2] = 0;\n\tdfdy[3 * 4 + 2] = 0;\n\n\tdfdy[0 * 4 + 3] = 0;\n\tdfdy[1 * 4 + 4] = 1;\n\tdfdy[2 * 4 + 4] = 0;\n\tdfdy[3 * 4 + 4] = 0;\n\n\tdfdx[0] = 0;\n\tdfdx[1] = 0;\n\tdfdx[2] = 0;\n\tdfdx[3] = 0;\n\n\treturn GSL_SUCCESS;\n}\n\nstatic long\tFcounter = 0;\n\nstatic int\tF(double x, const double J[], double F[], void *params) {\n\tFcounter++;\n\tfor (int i = 0; i < 2; i++) {\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\tF[i * 4 + j] = J[(i + 2) * 4 + j];\n\t\t}\n\t}\n\tfor (int i = 2; i < 4; i++) {\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\tF[i * 4 + j] = 0;\n\t\t}\n\t}\n\treturn GSL_SUCCESS;\n}\n\nint\tmain(int argc, char *argv[]) {\n\tgsl_odeiv2_system\tsystem = { f, df, 4, &g };\n\tgsl_odeiv2_system\tJsystem = { F, NULL, 16, NULL };\n\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6, 1e-6, 0.0);\n\tgsl_odeiv2_driver\t*Jdriver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&Jsystem, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6, 1e-6, 0.0);\n\t\n\n\tdouble\tt = 0.0;\n\tdouble\tvx = 8;\n\tdouble\tvy = 7;\n\tdouble\ttnext = 20 / vx;\n\tdouble\tdelta;\n\tint\tcounter = 0;\n\tprintf(\" n v_y t x y dy/dv_y vynew delta\\n\");\n\tdo {\n\t\t\n\t\t// compute the solution up to x = 1.5\n\t\tt = 0;\n\t\tdouble\ty[4] = { 0.0, 0.0, vx, vy };\n\t\tint\tstatus = gsl_odeiv2_driver_apply(driver, &t, tnext, y);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"error: return value = %d\\n\", status);\n\t\t}\n\n\t\t// compute the jacobi matrix up to x = 1.5\n\t\tt = 0;\n\t\tdouble\tJ[16] = {\t1.0, 0.0, 0.0, 0.0,\n\t\t\t\t\t0.0, 1.0, 0.0, 0.0,\n\t\t\t\t\t0.0, 0.0, 1.0, 0.0,\n\t\t\t\t\t0.0, 0.0, 0.0, 1.0 };\n\t\tstatus = gsl_odeiv2_driver_apply(Jdriver, &t, tnext, J);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"error: return value = %d\\n\", status);\n\t\t}\n\n\t\t// the derivative is J_{24}\n\t\tdouble\t derivative = J[1 * 4 + 3];\n\n\t\t// compute the newton correction\n\t\tdouble\tvynew = vy - y[1] / derivative;\n\t\tdelta = vy - vynew;\n\t\tprintf(\"%2d%8.4f %8.4f %8.4f %10.6f %12.8f %12.8f %14.10f\\n\",\n\t\t\t counter, vy, t, y[0], y[1], derivative, vynew, delta);\n\t\tvy = vynew;\n\t\tcounter++;\n\t} while ((fabs(delta) > 1e-6) && (counter <= 50));\n\tprintf(\"calls to f: %ld, to df: %ld, to F: %ld\\n\",\n\t\tfcounter, dfcounter, Fcounter);\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1b3585103e60fc84aaf354c6f3718b3511faa386", "size": 3007, "ext": "c", "lang": "C", "max_stars_repo_path": "skript/chapters/examples/rw.c", "max_stars_repo_name": "MatthiasRubin/SeminarDGL", "max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z", "max_issues_repo_path": "skript/chapters/examples/rw.c", "max_issues_repo_name": "MatthiasRubin/SeminarDGL", "max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_issues_repo_licenses": ["CC0-1.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": "skript/chapters/examples/rw.c", "max_forks_repo_name": "MatthiasRubin/SeminarDGL", "max_forks_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7803030303, "max_line_length": 94, "alphanum_fraction": 0.5527103425, "num_tokens": 1320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.4671752682574149}} {"text": "/* Copyright (c) 2014, Giuseppe Argentieri \n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n/*\n *\n *\n * Filename: stationary.c\n *\n * Description: Find the stationary state for the given generator\n *\n * Version: 1.0\n * Created: 05/05/2014 15:27:48\n * Revision: none\n * License: BSD\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: Università degli Studi di Trieste\n *\n * \n */\n\n#include \"funcs.h\"\n#include \n#include \n\n\n/* \n * FUNCTION \n * Name: stationary\n * Description: Given the dissipator in Bloch form, reduce to a 3x3 problem and store\n * \t\t\tthe stationary state in the 3x1 vector *X \n * \t\t\t\n * \t\t\tM X = 0\n * \n * \t \t| 0 0 0 0 | | 1 | 0\n * \t\t | M10 M11 M12 M13 | | X1 | 0\n * \t\t | M20 M21 M22 M23 | | X2 | = 0\n * \t\t\t| M30 M31 M32 M33 | | X3 | 0\n *\n *\n * \t\t\tA x = b\n *\n * \t\t\t| M11 M12 M13 | | X1 | | -M10 |\n * \t\t\t| M21 M22 M23 | | X2 | = | -M20 |\n * \t\t\t| M31 M32 M33 | | X3 | | -M30 |\n */\nint stationary ( const gsl_matrix* M, gsl_vector* stat_state )\n{\n\t/* Store space for the stationary state */\n\tgsl_vector* req = gsl_vector_calloc ( 4 ) ;\n\tgsl_vector_set ( req, 0, 1 ) ;\n\n\t/* Copy the dissipator matrix in a temporary local matrix m\n\t * (because the algorithm destroys it...) */\n\tgsl_matrix* m = gsl_matrix_calloc ( 4, 4 ) ;\n\tgsl_matrix_memcpy ( m, M ) ;\n\n\t/* Create a view of the spatial part of vector req */\n\tgsl_vector_view x = gsl_vector_subvector ( req, 1, 3 ) ;\n\n\t/* Create a submatrix view of the spatial part of m and a vector view\n\t * of the spatial part of the 0-th column, which goes into -b in the system\n\t * A x = b */\n\tgsl_matrix_view A = gsl_matrix_submatrix ( m, 1, 1, 3, 3 ) ;\n\tgsl_vector_view b = gsl_matrix_subcolumn ( m, 0, 1, 3 ) ;\n\tint status1 = gsl_vector_scale ( &b.vector, -1.0 ) ;\t\n\n\t/* Solve the system A x = b using Householder transformations.\n\t * Changing the view x of req => also req is changed, in the spatial part */\n\tint status2 = gsl_linalg_HH_solve ( &A.matrix, &b.vector, &x.vector ) ;\n\n\t/* Set the returning value for the state stat_state */\n\t*stat_state = *req ;\n\n\t/* Free memory */\n\tgsl_matrix_free(m) ;\n\t\n\treturn status1 + status2 ;\n}\t\t/* ----- end of function stationary ----- */\n\n\n\n/* \n * FUNCTION \n * Name: J\n * Description: Ohmic spectral density (divided by alpha)\n * \n */\ndouble J ( double w, double oc )\n{\n\tdouble W = w*exp(-w/oc) ;\n\treturn (W);\n}\t\t/* ----- end of function J ----- */\n\n\n/* \n * FUNCTION \n * Name: polarization\n * Description: Polarization P through the CP formula \n * \n */\ndouble polarization ( void* params, double oc )\n{\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble Omega, omega_1, b ;\n\tOmega = pars->Omega ;\n\tomega_1 = pars->omega_1 ;\n\tb = pars->beta ;\n\n\tdouble P, num, den, add1, add2, Jplus, Jminus ;\n\tJplus = J(omega_1 + Omega, oc) ;\n\tJminus = J(omega_1 - Omega, oc) ;\n\tadd1 = POW_2(omega_1 - Omega)*Jplus ;\n\tadd2 = POW_2(omega_1 + Omega)*Jminus ;\n\tnum = add1 + add2 ;\n\tden = add1/(tanh((omega_1+Omega)*b/2)) +\n\t\tadd2/(tanh((omega_1-Omega)*b/2)) ;\n\tP = num/den ;\n\n\treturn (P);\n}\t\t/* ----- end of function polarization ----- */\n", "meta": {"hexsha": "3053135c56a4998eb4c2f909fd019bbb0354ff8b", "size": 4605, "ext": "c", "lang": "C", "max_stars_repo_path": "stationary.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stationary.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stationary.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5410958904, "max_line_length": 87, "alphanum_fraction": 0.6414766558, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.46697961824946893}} {"text": "/* specfunc/gsl_sf_mathieu.h\n * \n * Copyright (C) 2002 Lowell Johnson\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., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: L. Johnson */\n\n#ifndef __GSL_SF_MATHIEU_H__\n#define __GSL_SF_MATHIEU_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#define GSL_SF_MATHIEU_COEFF 100\n\ntypedef struct \n{\n size_t size;\n size_t even_order;\n size_t odd_order;\n int extra_values;\n double qa; /* allow for caching of results: not implemented yet */\n double qb; /* allow for caching of results: not implemented yet */\n double *aa;\n double *bb;\n double *dd;\n double *ee;\n double *tt;\n double *e2;\n double *zz;\n gsl_vector *eval;\n gsl_matrix *evec;\n gsl_eigen_symmv_workspace *wmat;\n} gsl_sf_mathieu_workspace;\n\n\n/* Compute an array of characteristic (eigen) values from the recurrence\n matrices for the Mathieu equations. */\nint gsl_sf_mathieu_a_array(int order_min, int order_max, double qq, gsl_sf_mathieu_workspace *work, double result_array[]);\nint gsl_sf_mathieu_b_array(int order_min, int order_max, double qq, gsl_sf_mathieu_workspace *work, double result_array[]);\n\n/* Compute the characteristic value for a Mathieu function of order n and\n type ntype. */\nint gsl_sf_mathieu_a(int order, double qq, gsl_sf_result *result);\nint gsl_sf_mathieu_b(int order, double qq, gsl_sf_result *result);\n\n/* Compute the Fourier coefficients for a Mathieu function. */\nint gsl_sf_mathieu_a_coeff(int order, double qq, double aa, double coeff[]);\nint gsl_sf_mathieu_b_coeff(int order, double qq, double aa, double coeff[]);\n\n/* Allocate computational storage space for eigenvalue solution. */\ngsl_sf_mathieu_workspace *gsl_sf_mathieu_alloc(const size_t nn,\n const double qq);\nvoid gsl_sf_mathieu_free(gsl_sf_mathieu_workspace *workspace);\n\n/* Compute an angular Mathieu function. */\nint gsl_sf_mathieu_ce(int order, double qq, double zz, gsl_sf_result *result);\nint gsl_sf_mathieu_se(int order, double qq, double zz, gsl_sf_result *result);\nint gsl_sf_mathieu_ce_array(int nmin, int nmax, double qq, double zz,\n gsl_sf_mathieu_workspace *work,\n double result_array[]);\nint gsl_sf_mathieu_se_array(int nmin, int nmax, double qq, double zz,\n gsl_sf_mathieu_workspace *work,\n double result_array[]);\n\n/* Compute a radial Mathieu function. */\nint gsl_sf_mathieu_Mc(int kind, int order, double qq, double zz,\n gsl_sf_result *result);\nint gsl_sf_mathieu_Ms(int kind, int order, double qq, double zz,\n gsl_sf_result *result);\nint gsl_sf_mathieu_Mc_array(int kind, int nmin, int nmax, double qq,\n double zz, gsl_sf_mathieu_workspace *work,\n double result_array[]);\nint gsl_sf_mathieu_Ms_array(int kind, int nmin, int nmax, double qq,\n double zz, gsl_sf_mathieu_workspace *work,\n double result_array[]);\n\n\n__END_DECLS\n\n#endif /* !__GSL_SF_MATHIEU_H__ */\n", "meta": {"hexsha": "99217b31fda87ff5a75e39f0c435f1199ad42345", "size": 3945, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_sf_mathieu.h", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "gsl-2.6/gsl/gsl_sf_mathieu.h", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "gsl-2.6/gsl/gsl_sf_mathieu.h", "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "avg_line_length": 36.5277777778, "max_line_length": 124, "alphanum_fraction": 0.7051964512, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.46688741014679325}} {"text": "#include \n#include \n#include \n//#include \n#include // suprisingly, both work\n#include \n#include \n#include \n\n/*\n * * Program that reads reference spectra and measure spectra data\n * and linearly unmixes the data using method of least squares fit.\n * Assumes readings is set to 400 and file path is preset to:\n * \"/mnt/c/Users/jakei/'OneDrive - McGill University'/'Year 2'/1BIEN210/'Group Project'/\".\n * \n * syntax: ./linearUnmixer MUfilename ref1filename ref2filename ref3filename ...\n * returns: completion status, prints composition of ref1, ref2, ... , refn\n *\n * * ****************************************************************\n * * Author Dept. Date Notes\n * * ****************************************************************\n * * Jake Z Bio. Eng. Mar 12 2020 Initial version\n * * Jake Z\t\t\"\t Apr 03 2020 It works now! TODO: investigate the discrepancy between what you set $readings and the amount of space you allocate to the matrices as you forgot to account for the initial data clearing of the title headers in the data. \n * * */\nconst int READINGS = 1300;\t\t//note, if the readings specified here is more then the number of readings in file, funky stuff happens, TODO: implent check for this\nconst int SKIP = 50;\nint normalizeVector( gsl_vector *vector )\n{\n\tdouble min = gsl_vector_min( vector );\n\tdouble norm = gsl_vector_max( vector ) - min;\n\tgsl_vector_add_constant( vector, -min );\n\tgsl_vector_scale( vector, 1/norm );\n\treturn 0;\n}\n\nint readFileVector( gsl_vector *vector, char *filePath, char *fileName )\t\t//read file vals into vector\n{\n\tchar tmpFilepath[120] = \"\\0\";\n\tchar tmpReading[20];\n\tchar *tmp2;\n\tdouble reading;\t\t\t\t\t//WARNING this is similar to global var $readings, consider renaming\n\n\tstrcat( tmpFilepath, filePath );\t\t//TODO replace this and the first instance of strcat into strcpy, that should work\n\tstrcat( tmpFilepath, fileName ); \t//combines the filepath and name into one searchable /path/file\n\tFILE *file = fopen( tmpFilepath, \"rt\");\n\tprintf(\"%s\\n\", tmpFilepath);\t\t\t//TODO DELETE THIS\n\tif ( file == NULL ) {\t\t\t//check if file exists\n\t\tfprintf( stderr, \"Error, unable to locate the Mu data file\\n\");\n\t\texit(100);\n\t}\n\n\tfor ( int i = 0; i < SKIP; i++)\t\t//move past header of read files\n\t{\n\t\tfgets( tmpReading, 19, file );\n\t}\n\tfor ( int i = 0; i < READINGS; i++ )\n\t{\n\t\tfgets( tmpReading, 19, file );\n\t\n\t\ttmp2 = strrchr( tmpReading, '\\t' );\n\t\ttmp2 = tmp2 + 1;\n\t\treading = atof(tmp2);\n\t\tgsl_vector_set( vector, i, reading);\n\t}\n\tfclose(file);\n\tprintf(\"successful vector \\n\");\t\t\t//TODO delete this\n\treturn 0;\n}\n\nint readFileMatrix( gsl_matrix *matrix, char *filePath, int argc, char *argv[] )\n{\n\tchar *tmp2;\n\tdouble reading;\n\tfor ( int j = 2; j < argc; j++ )\n\t{\n\t\tgsl_vector_view column;\n\t\tchar tmpFilepath[120] = \"\\0\";\t\t\t\t//TODO replace this and the first instance of strcat into strcpy, that should work\n\t\tchar tmpReading[20];\n\t\tstrcat( tmpFilepath, filePath );\n\t\tstrcat( tmpFilepath, argv[j] ); \t//combines the filepath and name into one searchable /path/file\n\t\tFILE *file = fopen( tmpFilepath, \"rt\");\n\t\tprintf(\"%s\\n\", tmpFilepath);\t\t\t\t//TODO DELETE THIS\n\t\tif ( file == NULL ) {\t\t\t//check if file exists\n\t\t\tfprintf( stderr, \"Error, unable to locate a reference data file\\n\");\n\t\t\texit(100);\n\t\t}\n\t\tfor ( int i = 0; i < SKIP; i++)\t\t//move past header of read files\n\t\t{\n\t\t\tfgets( tmpReading, 20, file);\n\t\t}\n\t\tfor ( int i = 0; i < READINGS; i++ ) //fill the ith element of the jth column\n\t\t{\n\t\t\tfgets( tmpReading, 19, file );\n\t\t\n\t\t\ttmp2 = strrchr( tmpReading, '\\t' );\n\t\t\ttmp2 = tmp2 + 1;\n\t\t\treading = atof(tmp2);\n\t\t\tgsl_matrix_set( matrix, i, j-2, reading );\n\t\t}\n\t\tfclose(file);\n\t\tcolumn = gsl_matrix_column( matrix, j-2 );\t\t\t\t//NORMALISE EACH REFERENCE VECOTR.\n\t\tnormalizeVector( &column.vector );\t\t\n\t}\n\tprintf(\"success, matrix filled \\n\");\t\t\t//TODO DELETE THIS\n\treturn 0;\n}\n\n\nint main(int argc, char *argv[])\n{\n\tif ( argc <= 2 )\n\t{\n\t\tfprintf( stderr, \"Error, incorrect usage.\\n./linearUnmixer MU_SPECTRA REF_SPECTRA\\n\");\n\t\treturn 3;\n\t}\n\t//spectrum files labelled /mnt/c/Users/jakei/'OneDrive - McGill University'/'Year 2'/1BIEN210/'Group Project'/SpectrumFile_00N.txt\n\t//intialize and allocate memory for variabels\n\tint numRefs = argc - 2;\n\t//char *filePath = \"\";\n\tchar *filePath = \"/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/\";\n\tgsl_vector *muVector = gsl_vector_alloc(READINGS);\n\tgsl_vector *fVector = gsl_vector_alloc(numRefs);\n\tgsl_vector *x = gsl_vector_alloc(numRefs);\t\t\t//TODO RENAME x AND PROBECOMPVECTOR\n\tgsl_matrix *refMatrix = gsl_matrix_alloc(READINGS, numRefs);\n\tgsl_matrix *C = gsl_matrix_alloc( numRefs, numRefs );\n\tgsl_matrix *Cinverse = gsl_matrix_alloc( numRefs, numRefs );\n\t\n\tint s;\n\tgsl_permutation *p = gsl_permutation_alloc(numRefs);\t\t\t//CHANGED ALLOC TO CALLOC\n\t\n\t//initailize the variables to 0\n\tgsl_vector_set_zero(muVector);\n\tgsl_vector_set_zero(fVector);\n\tgsl_vector_set_zero(x);\n\tgsl_matrix_set_zero(refMatrix);\n\tgsl_matrix_set_zero(C);\n\n\tgsl_permutation_init(p);\t\t\t//INITIALISED THE PERMUTATION\n\t\n\treadFileVector( muVector, filePath, argv[1] ); //call function which reads in values of first arguement file into the vector mu\n\treadFileMatrix( refMatrix, filePath, argc, argv ); //obtain matrix of reference vals, (400, 2) in 400 READINGS w/ 2 probes\n\t//normalize values, vector is already normalised\n\tnormalizeVector( muVector );\n\t\n\t//print vector to csv file for plotting\n\tFILE *csvfile = fopen( \"/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/muVector.csv\", \"wt\" );\n\tgsl_vector_fprintf( csvfile, muVector, \"%f\" );\n\tfclose(csvfile);\n\tFILE *csvfile2 = fopen( \"/mnt/c/Users/jakei/OneDrive - McGill University/Year 2/1BIEN210/Group Project/refVectors.txt\", \"wt\" );\n\tgsl_matrix_fprintf( csvfile2, refMatrix, \"%f\" );\n\tfclose(csvfile2);\n\n\n\t//now we have variable muVector with vals and refMatrix with vals.\t\n\tgsl_blas_dgemm( CblasTrans, CblasNoTrans, 1, refMatrix, refMatrix, 0, C);\t//matrix C is now A^T A\n\tgsl_blas_dgemv( CblasTrans, 1, refMatrix, muVector, 0, fVector);\t//fVector is 'b'\n\tgsl_linalg_LU_decomp( C, p, &s);\n//\tgsl_linalg_LU_solve( C, p, fVector, x );\t//can replace with gsl_linalg_LU_svx and delete x vector from program\n\n\tgsl_linalg_LU_invert( C, p, Cinverse );\t\t//TODO maybe implement the other way you can solve for basis using inverse on both sides, (A^T A )^-1 A^T A x = (a^t a)^-1 (a^t b) = x \n\tgsl_blas_dgemv( CblasNoTrans, 1, Cinverse, fVector, 0, x);\t\n/*\t\n\tgsl_vector_fprintf( stdout, muVector, \"%f\" );\n\tprintf(\"***********************************************\\n\");\n*/\t\n\tgsl_vector_fprintf( stdout, x, \"%f\" );\n\t\n\tgsl_matrix_free(Cinverse);\n\tgsl_matrix_free(C);\n\tgsl_matrix_free(refMatrix);\n\tgsl_vector_free(muVector);\n\tgsl_vector_free(fVector);\n\tgsl_vector_free(x);\t\n\treturn 0;\n\n}\n", "meta": {"hexsha": "4a089466e354cc78dfc765dc0918d8c93f0c0c92", "size": 6919, "ext": "c", "lang": "C", "max_stars_repo_path": "backup/beta.c", "max_stars_repo_name": "jakeinater/spectralILU", "max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "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": "backup/beta.c", "max_issues_repo_name": "jakeinater/spectralILU", "max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "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": "backup/beta.c", "max_forks_repo_name": "jakeinater/spectralILU", "max_forks_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d", "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": 39.0903954802, "max_line_length": 256, "alphanum_fraction": 0.6795779737, "num_tokens": 2042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4668058447851717}} {"text": "/* FacSexNe.c \n\nSimulation of tracking neutral mutation under facultative sex\nTo calculate Ne under different scenarios\nCode based on that used in Agrawal and Hartfield 2016 (https://github.com/MattHartfield/BalSelSims).\n\nSimulation uses routines found with the GNU Scientific Library (GSL)\n(http://www.gnu.org/software/gsl/)\nSince GSL is distributed under the GNU General Public License \n(http://www.gnu.org/copyleft/gpl.html), you must download it \nseparately from this file.\n\nRun by executing:\n./FacSexNe N sex gc reps\nWhere:\n- N is the population size\n- sex is the frequency of sex (a value between 0 = obligate asex, and 1 = obligate sex)\n- gc is the frequency of mitotic gene conversion\n- reps is how many times to introduce linked neutral allele\n\n*/\n\n/* Preprocessor statements */\n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Function prototypes */\nvoid neutinit(double *geninit, unsigned int N);\nvoid reproduction(double *geninit, double sex);\nvoid gconv(double *geninit, double gc);\ndouble ncheck(double *geninit);\n\n/* Main program */\nint main(int argc, char *argv[]){\n\tunsigned int N = 0;\t\t\t\t/* Population size */\n\tunsigned int g, i; \t\t\t\t/* Counters. Reps counter, geno counter */\n\tunsigned int reps = 0;\t\t\t/* Length of simulation (no. of introductions of neutral site) */\n\tdouble sex = 0;\t\t\t\t\t/* Frequency of sexual reproduction */\n\tdouble gc = 0;\t\t\t\t\t/* Frequency of gene conversion */\n\tdouble Acheck = 0;\t\t\t\t/* Frequency of derived neutral allele (A) after each reproduction */\n\tdouble Hsum = 0;\t\t\t\t/* Summed heterozygosity over transit time of neutral allele */\n\tchar Hout[128];\t\t\t\t\t/* String to hold filename in */\n\tFILE *ofp_hs = NULL;\t\t\t/* Pointer for results output */\n\t\n\t/* GSL random number definitions */\n\tconst gsl_rng_type * T; \n\tgsl_rng * r;\n\t\n\t/* This reads in data from command line. */\n\tif(argc != 5){\n\t\tfprintf(stderr,\"Invalid number of input values.\\n\");\n\t\texit(1);\n\t}\n\tN = atoi(argv[1]);\n\tsex = strtod(argv[2],NULL);\n\tgc = strtod(argv[3],NULL);\n\treps = strtod(argv[4],NULL);\n\t\n\t/* Arrays definition and memory assignment */\n\tdouble *genotype = calloc(3,sizeof(double));\t\t\t\t/* Genotype frequencies */\n\tunsigned int *gensamp = calloc(3,sizeof(unsigned int));\t\t/* New population samples */\n\t \n\t/* create a generator chosen by the \n environment variable GSL_RNG_TYPE */\n\n\tgsl_rng_env_setup();\n\tif (!getenv(\"GSL_RNG_SEED\")) gsl_rng_default_seed = time(0);\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\t\n\t/* Setting up neutral genotype */\n\tneutinit(genotype,N);\n\t\n\t/* Reintroducing neutral genotype, resetting hap sum */\t\n Acheck = ncheck(genotype);\n Hsum = Acheck*(1.0-Acheck);\n \n /* Introduce and track neutral mutations 'reps' times */\n g = 0;\n while(g < reps){\n \t\n \t/* Reproduction routine */\n \treproduction(genotype,sex);\n \t\n \t/* Gene conversion routine */\n \tgconv(genotype,gc);\n \t\n \t/* Sampling based on new frequencies */\n \tgsl_ran_multinomial(r,3,N,genotype,gensamp);\n \tfor(i = 0; i < 3; i++){\n \t\t*(genotype + i) = (*(gensamp + i))/(1.0*N);\n \t}\n \t\n \t/* Checking state of haplotypes: if A fixed reset so can start fresh next time */\n\t\tAcheck = ncheck(genotype);\n\t\tHsum += Acheck*(1.0-Acheck);\n \t\n \tif(Acheck == 0 || Acheck == 1){\n \t\tsprintf(Hout,\"/scratch/mhartfield/CC_FSC_Ne/temp_s%.8lf_gc%.8lf.out\",sex,gc);\n \t\tif(g != 0){\n\t\t\t\tofp_hs = fopen(Hout,\"a\");\n\t\t\t}else if(g == 0){\n\t\t\t\tofp_hs = fopen(Hout,\"w\");\n\t\t\t}\n\t\t\tfprintf(ofp_hs,\"%.10lf\\n\",Hsum);\n\t\t\tfclose(ofp_hs);\n \t\tg++;\n \t\t \n \t\t/* Reintroducing neutral genotype, resetting hap sum */ \t\t\n\t \tneutinit(genotype,N);\n\t\t\tAcheck = ncheck(genotype);\n \t\tHsum = Acheck*(1-Acheck);\n \t}\n \n\t}\t/* End of simulation */\n\t\n\t\n\t/* Freeing memory and wrapping up */\n \tgsl_rng_free(r);\n \tfree(gensamp);\n\tfree(genotype);\n\treturn 0;\n}\n\n/* Setting up neutral polymorphism routine */\nvoid neutinit(double *geninit, unsigned int N){\n\t*(geninit + 0) = 1 - 1/(1.0*N);\n\t*(geninit + 1) = 1/(1.0*N);\n\t*(geninit + 2) = 0;\n}\t/* End of neutral setup routine */\n\n/* Reproduction routine */\nvoid reproduction(double *geninit, double sex){\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble gaas, gAas, gAAs;\n\t/* Genotype frequencies after sex */\t\n\tdouble gaaSX, gAaSX, gAASX;\n\t/* Genotype frequencies after asex */\t\n\tdouble gaaAS, gAaAS, gAAAS;\n\t\n\t/* Initial definition of genotypes */\n\tgaas = *(geninit + 0);\n\tgAas = *(geninit + 1);\n\tgAAs = *(geninit + 2);\n\t\n\t/* Change in frequencies due to sex */\n\tgaaSX = sex*(gaas + gAas/2.0)*(gaas + gAas/2.0);\n\tgAaSX = sex*2.0*(gaas + gAas/2.0)*(gAAs + gAas/2.0);\n\tgAASX = sex*(gAAs + gAas/2.0)*(gAAs + gAas/2.0);\n\t\n\t/* Change in frequencies due to asex */\n\tgaaAS = gaas*(1 - sex);\n\tgAaAS = gAas*(1 - sex);\n\tgAAAS = gAAs*(1 - sex);\n\t\n\t/* Combining to give overall frequency change following reproduction */\n\t*(geninit + 0) = gaaAS + gaaSX;\n\t*(geninit + 1) = gAaAS + gAaSX;\n\t*(geninit + 2) = gAAAS + gAASX;\n\t\t\n}\t/* End of reproduction routine */\n\n/* Gene conversion routine */\nvoid gconv(double *geninit, double gc){\n\t\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble gaar, gAar, gAAr;\n\t/* Frequencies after gene conversion */\n\tdouble gaagc, gAagc, gAAgc;\n\t\n\t/* Initial definition of genotypes */\n\tgaar = *(geninit + 0);\n\tgAar = *(geninit + 1);\n\tgAAr = *(geninit + 2);\n\t\n\t/* Gene conversion equations */\n\tgaagc = gaar + gAar*gc/2.0;\n\tgAagc = gAar*(1.0-gc);\n\tgAAgc = gAAr + gAar*gc/2.0;\n\t\n\t/* Output */\n\t*(geninit + 0) = gaagc;\n\t*(geninit + 1) = gAagc;\n\t*(geninit + 2) = gAAgc;\n\t\n}\t/* End of gene conversion routine */\n\n/* Has neutral allele fixed or not? Measuring its frequency */\ndouble ncheck(double *geninit){\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble gAas, gAAs;\n\tdouble Atot = 0.0; /* Total frequency of A */\n\t\n\t/* Initial definition of genotypes */\n\tgAas = *(geninit + 1);\n\tgAAs = *(geninit + 2);\n\t\t\n\t/* Checking frequency of A */\n\tAtot = gAAs + gAas/2.0;\n\treturn Atot;\n\t\n}\t/* End of neutral check routine */\n\n/* End of program */\n", "meta": {"hexsha": "4f7cac2913c83cd31e8d7c8d5f832b7523bb2d07", "size": 6135, "ext": "c", "lang": "C", "max_stars_repo_path": "FacSexNe.c", "max_stars_repo_name": "MattHartfield/FacSexNe", "max_stars_repo_head_hexsha": "02d5472f3d913c166c9107e3fe5ace9ea0643a78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-22T15:58:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-13T14:50:01.000Z", "max_issues_repo_path": "FacSexNe.c", "max_issues_repo_name": "MattHartfield/FacSexNe", "max_issues_repo_head_hexsha": "02d5472f3d913c166c9107e3fe5ace9ea0643a78", "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": "FacSexNe.c", "max_forks_repo_name": "MattHartfield/FacSexNe", "max_forks_repo_head_hexsha": "02d5472f3d913c166c9107e3fe5ace9ea0643a78", "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.3540669856, "max_line_length": 100, "alphanum_fraction": 0.6441727791, "num_tokens": 1857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4668058387380167}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"intT.h\" \n#include \n#include \n\n //electron mass squared\n double m2 = 1.0;\n //electron charge\n double e = 0.30282212;\n //double m2=1.0;\n //double e=1.0;\n\ndouble EV(double T, void * p, int* WLlist);\n\ndouble Exact(double T, double B, int fermion)\n//Return the exact integrand for constant fields\n{\n double TB = e*T*B;\n double Exact;\n if( B < 1.0e-40)\n\tExact = 0.0;\n else\n if(fermion == 1)\n\tExact = exp(-m2*T)/(T*T*T)*(TB/tanh(TB)-1.0-1.0/3.0*TB*TB);\n else\n\tif (TB < 50.0)\n\t\tExact = exp(-m2*T)/(T*T*T)*(TB/sinh(TB)-1.0+1.0/6.0*TB*TB);\n\telse\n\t\tExact = exp(-m2*T)/(T*T*T)*(1.0/6.0*TB*TB-1.0);\n //printf(\"%f %e\\n\",T, exp(-T));\n return Exact;\n}\n\ndouble bumpd(double x)\n//The bump function\n{\n if (abs(x) < 1.0)\n\treturn exp(-1.0/(1.0-x*x));\n else\n\treturn 0.0;\t \n}\n\ndouble fixfluxB(double rho2, double lambda2)\n//Magnetic field strength for the fixflux profile\n{\n float l = sqrt(lambda2);\n float lmlmin = (l - lmin)/(tubedist - lmin);\n if(sqrt(rho2) > tubedist/2.0) printf(\"Warning: inappropriate magnetic field being used. rho=%f\\n\", sqrt(rho2));\n return 2.0/(lambda2*q2)*(1.0-0.75*lmlmin)*bumpd(2.0*sqrt(rho2/lambda2))\n\t+ 3.0/(tubedist*tubedist)*lmlmin;\n}\n\ndouble periodicB(double rho2, double lambda2)\n//magnetic field for the periodic flux tube profile\n{\n double expr, rho, lambda, flraf, f, ceilraf;\n double expral, exprapl;\n rho = sqrt(rho2);\n lambda = sqrt(lambda2); \n expr = exp(-rho/lambda);\n flraf = floor(rho/tubedist);\n ceilraf = ceil(rho/tubedist);\n if(rho < tubedist)\n {\n\texpral = 0.0;\n\tif((tubedist-rho)/lambda < 10.0)\n\t\texpral = exp(-(rho-tubedist)/lambda);\n\tf = expr/(tubedist*(1.0 + expr)*(1.0 + expr)); \n\tif(rho > 0.0)\n\t\tf += expral/(rho*(1.0+expral)*(1.0+expral));\n }\n else\n {\n if(abs(fmod(rho,tubedist)) < 1.0e-6)\n \t{\n\t\tf = flraf/(4.0*rho);\n\t}\n\telse\n\t{\n\t expral = exp(-(rho-flraf*tubedist)/lambda);\n\t exprapl = exp(-(rho-ceilraf*tubedist)/lambda);\n f = flraf*expral/(rho*(1.0+expral)*(1.0+expral)) +\n\t\tceilraf*exprapl/(rho*(1.0+exprapl)*(1.0+exprapl));\n }\n }\n //f=1.0f/lambda2*exp(-1.0f*rho2/lambda2);\n //f=lambda2/8.0f;\n f=tubedist/(2.0*log(2.0)*lambda2)*f;\n //f=1.0;\n return f;\n}\n\ndouble MagField(double rho2, void* p)\n//Compute the magnetic field. \n{\n double B;\n double sinrho;\n struct Wparams *params = (struct Wparams *) p;\n switch(profile){\n\tcase step:\n\t if(rho2l2)\n\t\tB=1.0/params->l2;\n\t else\n\t\tB=0.0;\n\t break;\n\tcase smooth:\n\t B=params->l2/((params->l2+rho2)*(params->l2+rho2));\n\t break;\n\tcase quadratic:\n\t if(rho2l2)\n\t\tB=2.0/params->l2*(1.0-rho2/params->l2);\n\t else\n\t\tB=0.0;\n\t break;\n\tcase gaussian:\n\t if(rho2<100.0*params->l2)\n\t \tB=1.0/(params->l2*exp(rho2/params->l2));\n\t else\n\t\tB=0.0;\n\t break;\n\tcase periodic:\n\t B=periodicB(rho2,params->l2);\n\t break;\n\tcase spline:\n\t sinrho=sin(pi*sqrt(rho2)/tubedist);\n\t B=1.0/(params->l2*exp(sinrho*sinrho/params->l2));\n\t break;\n\tcase fixflux:\n\t B = fixfluxB(rho2,params->l2);\n\t break;\n }\n B=2.0*params->F/e*B;\n \n return B;\n}\n\ndouble smTscal(double B, double T)\n//Effective action for T<<1.0 for scalar QED\n{\n\tdouble B2=e*e*B*B;\n\tdouble B4=B2*B2;\n\tdouble B6=B2*B4;\n\tdouble T2=T*T;\n\tdouble T3=T2*T;\n\tdouble T4=T3*T;\n\tdouble result;\n\tresult = 7.0/360.0*B4*T*(1.0-m2*T)+(147.0*B4*m2*m2-31.0*B6)/15120.0*T3\n\t\t+(31.0*B6*m2-49.0*B4*m2*m2*m2)/15120.0*T4;\n\treturn result;\n}\n\ndouble smTferm(double B, double T)\n//Effective action for T<<1.0 for fermionic QED\n{\n\tdouble B2=e*e*B*B;\n\tdouble B4=B2*B2;\n\tdouble B6=B2*B4;\n\tdouble T2=T*T;\n\tdouble T3=T2*T;\n\tdouble T4=T3*T;\n\tdouble result;\n\tresult = 1.0/45.0*B4*T*(m2*T-1.0) + (2.0*B6/945.0 - B4*m2*m2/90.0)*T3\n\t\t+(7.0*B4*m2*m2*m2-4.0*B6*m2)/1890.0*T4;\n\t//result = 1.0/45.0*B4*T*(T-1.0) + (2.0*B6/945.0 - B4/90.0)*T3\n\t//\t+(7.0*B4-4.0*B6)/1890.0*T4;\n\treturn result;\n}\n\ndouble meanigrand(double* igrand, int ngroups, double* igranderr)\n//compute the mean and std. err. for igrand\n{\n double meanig=0.0;\n int i;\n *igranderr=0.0;\n for(i=0;ixcm.x*params->xcm.x + params->xcm.y*params->xcm.y;\n double smallT;\n double B;\n double TB;\n double* igrand = malloc(params->ng*sizeof(*igrand));\n int groupsize = 128; //loops per group\n int* WLlist = malloc(groupsize*sizeof(*WLlist));\n int i, j;\n double rho = params->xcm.x;\n double l2 = params->l2;\n double sin2rho = sin(2.0*pi*rho/tubedist);\n double denominator;\n double igmean; double igerr;\n if(!igrand || !WLlist) printf(\"error Tfunc(): malloc failed\\n\");\n\n //printf(\"func: T=%f\\n\",T);\n B=MagField(rho2,p);\n TB=e*T*B;\n //printf(\"T=%f f'/f''=%f\\n\",T,(params->l2+params->xcm.x*params->xcm.x));\n //determine a suitable definition for small T\n switch(profile)\n {\n\tcase step:\n\t smallT=abs(rho*rho-l2);\n break;\n case smooth:\n\t smallT= 0.5*(l2+rho*rho);\n break;\n case quadratic:\n\t smallT= 0.5*(l2+rho*rho);\n break;\n case gaussian:\n\t smallT=l2;\n\t break;\n case periodic:\n\t smallT=0.5*(l2+rho*rho);\n break;\n\tcase spline:\n\t if(rho/tubedist>1.0e-8)\n\t \tsmallT=tubedist*tubedist*l2/(pi*pi*sin2rho*sin2rho);\n\t else\n\t\tsmallT=1.0e12;\n\t break;\n\tcase fixflux:\n\t //small if T << l2, or if the loop is far from any bump functions.\n\t if(rho*rhong; i++)\n { \n\t//printf(\"func igrand[%d]=%f\\n\",i,igrand[i]);\n\tif(T < 0.1 && T < 0.01*smallT)\n\t//if(T<0.7)\n \t{\n\t\tif(verbosity >= 2)\n\t\t printf(\"using small T expression: %f %f %f\\n\", rho2, T, smallT);\n\t\tif(params->fermion == 1)\n\t\t\tigrand[i] = smTferm(B, T);\n\t\telse\n\t\t\tigrand[i] = smTscal(B, T);\n \t}\n else if(T < 0.01*smallT)\n\t//use the exact expression\n\t{\n\t\tif(verbosity >= 2)\n\t\t printf(\"using const. field expression %f %f %f\\n\", rho2, T, smallT);\n\t\tif(TB > 1.0e-6)\n\t\t\tigrand[i] = Exact(T, B, params->fermion);\n\t\telse\n\t\t\tigrand[i] = 0.0;\t\n\t}\n\telse if(T > 49.0)\n\t//for large T, the contribution is exponentially supressed.\n\t{\n\t\tif(verbosity >= 2)\n printf(\"using large T expression %f %f %f\\n\", rho2, T);\n\t\tif(params->fermion==1)\n\t\t{\n\t\t\tigrand[i]=-1.0*exp(-m2*T)/(3.0*T)*e*e*B*B;\n\t\t\t//if(B>1e-6)\n\t\t\t//\tigrand[i]=exp(-m2*T)/(T*T*T)*(TB/tanh(TB)-1.0-1.0/3.0*TB*TB);\n\t\t\t//else \n\t\t\t//\tigrand[i]=0.0;\n\t\t\t//printf(\"igrand(%f)=%f\\n\",T,igrand[i]);\n\t\t}\n\t\telse\n\t\t\tigrand[i]=exp(-m2*T)/(6.0*T)*e*e*B*B;\n\t}\n \telse\n \t{\n\t\tfor(j=0;j= 3)\n\t\t printf(\"EV= %e Exact = %e\\n\",EV(T,p, WLlist),T/sinh(T));\n\t\tif(params->fermion==1)\n\t\t\tigrand[i]= exp(-m2*T)/(T*T*T)*(EV(T, p, WLlist)-1.0-1.0/3.0*TB*TB);\n\t\telse\n\t\t\tigrand[i]= exp(-m2*T)/(T*T*T)*(EV(T, p, WLlist)-1.0+1.0/6.0*TB*TB);\n\t\t//igrand[i]=Exact(T,1.0);\n\t\t//return Exact(T,1.0);\n\n \t}\n \n }\n if(T > 0.0f && verbosity >= 2){\n\tigmean = meanigrand(igrand, params->ng, &igerr);\n\tprintf(\"WLvconstExpression: \");\n \t\tprintf(\"%e %e %e %e %e %e\\n\",\n \t\t rho2, T, Exact(T, B, params->fermion), smTscal(B, T), igmean, igerr);\n }\n free(WLlist);\n return igrand;\n}\n\nvoid signal_handler(int sig)\n//Floating point signal handler\n{\n printf( \"Error: Floating point signal detected.\\n\");\n exit(1);\n}\n\nvoid EVMean(double *EV, float4 *Wsscal_h, float4 *Wsferm_h, int n, int *WL, double T, int fermion)\n//Compute the expectation value and error of the Wilson loops\n//WL is a list representing a group of wordline indices \n//to compute the expectation value of\n{\n int i, WLi;\n double EVWlNb2, EVWlN, EVWlNb4;\n double SEWlNb2, SEWlN, SEWlNb4;\n double *EVpart1;\n double *EVpart2;\n double *EVpart4;\n double Nby4part;\n\n //Turn on floating point exceptions: \n feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW);\n\n // Set the signal handler: \n signal(SIGFPE, signal_handler);\n\n *EV = 0.0;\n EVWlNb2 = 0.0; EVWlN = 0.0; EVWlNb4 = 0.0;\n //allocate arrays to store the wilson loop of each worldline\n EVpart1 = (double *) malloc(n*sizeof(*EVpart1));\n EVpart2 = (double *) malloc(n*sizeof(*EVpart2));\n EVpart4 = (double *) malloc(n*sizeof(*EVpart4));\n if(!EVpart1 || !EVpart2 || !EVpart4) printf(\"EVonly(): malloc failed\\n\");\n //determine the sum of the contributions\n for(i = 0; i < n; i++){\n\tWLi=WL[i];\n\t//Compute the scalar part\n\tNby4part = Wsscal_h[WLi].y + Wsscal_h[WLi].z;\n\tEVpart1[i] = cos(0.5*Wsscal_h[WLi].x+0.25*(Nby4part));\n\tEVpart2[i] = cos(Wsscal_h[WLi].x);\n\tEVpart4[i] = cos(0.5*(Nby4part));\n\tif(fermion == 1)\n\t{\n\t\tif(isinf(Wsferm_h[WLi].x) !=0 ||isinf(Wsferm_h[WLi].y) !=0 ||isinf(Wsferm_h[WLi].z) !=0 \n\t\t || isnan(Wsferm_h[WLi].x) !=0 || isnan(Wsferm_h[WLi].y) !=0 ||isnan(Wsferm_h[WLi].z) !=0 )\n\t\t{\n\t\t\tprintf(\"Warning: WSferm is infinite. Worldline=%d\\n\",WLi);\n\t\t}\n\t\t//Compute the fermion part\n\t\t//printf(\"Wsferm_h[%d].x=%f\\n\",WLi,Wsferm_h[WLi].x);\n\t\t//printf(\"Wsferm_h[%d].y=%f\\n\",WLi,Wsferm_h[WLi].y);\n\t\t//printf(\"Wsferm_h[%d].z=%f\\n\",WLi,Wsferm_h[WLi].z);\n\t\tNby4part = Wsferm_h[WLi].y+Wsferm_h[WLi].z;\n\t\tif(abs(Nby4part) > 600.0 | abs(Wsferm_h[WLi].x) > 600.0)\n\t\t{\n\t\t\tprintf(\"Warning: Large cosh argument. T=%f, WLi=%d\\n\",T,WLi);\n\t\t\tEVpart1[i] *= 1.0e10;\n\t\t\tEVpart2[i] *= 1.0e10;\n\t\t\tEVpart4[i] *= 1.0e10;\n\t\t}\n else\n\t\t{\n\t\t\tEVpart1[i] *= cosh(0.5*(double)Wsferm_h[WLi].x+0.25*((double)Nby4part));\n\t\t\tEVpart2[i] *= cosh((double)Wsferm_h[WLi].x);\n\t\t\tEVpart4[i] *= cosh(0.5*((double)Nby4part));\n\t\t\t//EVpart1[i]*=cosh(T);\n\t\t\t//EVpart2[i]*=cosh(T);\n\t\t\t//EVpart4[i]*=cosh(T);\n\t\t}\n\t\tif(isnan(EVpart1[i]) != 0 || isnan(EVpart2[i]) != 0 || isnan(EVpart4[i]) != 0 \n\t\t\t|| isinf(EVpart1[i]) != 0 || isinf(EVpart2[i]) != 0 || isinf(EVpart4[i]) != 0) \n\t\t\tprintf(\"Warning: Infinity detected: WL# %d\\n\",WLi);\n\t}\n\tEVWlNb4 += EVpart4[i];\n\tEVWlNb2 += EVpart2[i];\n\tEVWlN += EVpart1[i];\n //printf(\"EVpart1[%d]=%f\\n\",i,EVpart1[i]);\n }\n EVWlNb4 /=n;\n EVWlNb2 /=n;\n EVWlN /=n;\n //Extrapolate to N=infinity\n *EV=8.0/3.0*EVWlN - 2.0*EVWlNb2 + 1.0/3.0*EVWlNb4;\n \n\n free(EVpart1);\n free(EVpart2);\n free(EVpart4);\n \n}\n\n\n", "meta": {"hexsha": "a4e2a0b0e5fac134a1eb53df5be4acec9da03243", "size": 10741, "ext": "c", "lang": "C", "max_stars_repo_path": "Integrand.c", "max_stars_repo_name": "QEDan/Worldline-Flux-Tube-Lattice", "max_stars_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "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": "Integrand.c", "max_issues_repo_name": "QEDan/Worldline-Flux-Tube-Lattice", "max_issues_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "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": "Integrand.c", "max_forks_repo_name": "QEDan/Worldline-Flux-Tube-Lattice", "max_forks_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "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.1975609756, "max_line_length": 157, "alphanum_fraction": 0.5912857276, "num_tokens": 4316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.46652632833162294}} {"text": "#include \n#include \n#include \n#include \"matrix_operations.c\"\n#include \"ellipsoid/parametric_function_roots.c\"\n#include \"polynomial.c\"\n\n\n\n\n\nvoid characteristic_ellipsoid_matrix(double *X, double *R, double phi, double *rotax, double exponent)\n{\n\n double w, x, y, z;\n w = cos(phi / 2.0);\n x = sin(phi / 2.0) * rotax[0];\n y = sin(phi / 2.0) * rotax[1];\n z = sin(phi / 2.0) * rotax[2];\n\n // Rotation matrix\n double Q[3][3] = {{ 0 }};\n\n Q[0][0] = 1.0 - 2.0 * (pow(y, 2) + pow(z, 2));\n Q[0][1] = 2.0 * (x * y + w * z);\n Q[0][2] = 2.0 * (x * z - w * y);\n\n Q[1][0] = 2.0 * (x * y - w * z);\n Q[1][1] = 1.0 - 2.0 * (pow(x, 2) + pow(z, 2));\n Q[1][2] = 2.0 * (y * z + w * x);\n\n Q[2][0] = 2.0 * (x * z + w * y);\n Q[2][1] = 2.0 * (y * z - w * x);\n Q[2][2] = 1.0 - 2.0 * (pow(x, 2) + pow(y, 2));\n\n\n //Rotation matrix transpose\n double Qt[3][3] = {{ 0 }};\n matrix_transpose(&Qt[0][0], &Q[0][0], 3, 3);\n\n\n // radii matrix\n double O[3][3] = {{ 0 }};\n double diag_vals[3];\n diag_vals[0] = pow(R[0], exponent * -2.0);\n diag_vals[1] = pow(R[1], exponent * -2.0);\n diag_vals[2] = pow(R[2], exponent * -2.0);\n set_diagonal(&O[0][0], diag_vals, 3, 3);\n\n\n // characteristic ellipse matrix\n double X_temp[3][3] = {{ 0 }};\n matrix_multiply(&X_temp[0][0], &O[0][0], &Q[0][0], 3, 3, 3);\n matrix_multiply(X, &Qt[0][0], &X_temp[0][0], 3, 3, 3);\n\n\n}\n\n\n\n\n\ndouble ellipsoid_overlap(double *rA, double *radiiA, double phiA, double *rotaxA, \n double *rB, double *radiiB, double phiB, double *rotaxB)\n{\n\n\n // find XA^(-1) and XB^(1/2)\n double XA[3][3] = {{ 0 }};\n double XB[3][3] = {{ 0 }};\n characteristic_ellipsoid_matrix(&XA[0][0], &radiiA[0], phiA, &rotaxA[0], -1.0);\n characteristic_ellipsoid_matrix(&XB[0][0], &radiiB[0], phiB, &rotaxB[0], 0.5);\n\n\n // find A_AB\n double A_AB[3][3] = {{ 0 }};\n double A_temp[3][3] = {{ 0 }};\n matrix_multiply(&A_temp[0][0], &XA[0][0], &XB[0][0], 3, 3, 3);\n matrix_multiply(&A_AB[0][0], &XB[0][0], &A_temp[0][0], 3, 3, 3);\n\n // find r_AB\n double rAB[3];\n rAB[0] = rB[0] - rA[0];\n rAB[1] = rB[1] - rA[1];\n rAB[2] = rB[2] - rA[2];\n\n // find a_AB\n double a_AB[3];\n matrix_multiply(&a_AB[0], &XB[0][0], &rAB[0], 3, 3, 1);\n\n // extract elements of the matrix A_AB and a_AB\n double a11, a12, a13, a21, a22, a23, a31, a32, a33;\n double b1, b2, b3;\n a11 = A_AB[0][0];\n a12 = A_AB[0][1];\n a13 = A_AB[0][2];\n a21 = A_AB[1][0];\n a22 = A_AB[1][1];\n a23 = A_AB[1][2];\n a31 = A_AB[2][0];\n a32 = A_AB[2][1];\n a33 = A_AB[2][2];\n b1 = a_AB[0];\n b2 = a_AB[1];\n b3 = a_AB[2];\n\n\n\n\n\n\n // find coefficients for the parametric polynomial derivative used to find max\n double h[7];\n double z[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n size_t n = 7;\n h[0] = h0(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[1] = h1(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[2] = h2(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[3] = h3(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[4] = h4(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[5] = h5(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n h[6] = h6(a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n\n\n\n\n\n // find roots\n size_t m;\n m = find_roots(&z[0], &h[0], n);\n\n\n\n\n\n double F;\n int i;\n\n if (m > 1)\n {\n if (f(0, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3) > f(1, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3))\n {\n\n F = f(0, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n\n }\n else\n {\n\n F = f(1, a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n\n }\n\n\n\n for(i=0; i<=m-2; i++)\n {\n\n if (( z[2 * i + 1] == 0 ) & (z[2 * i] > 0) & (z[2 * i] < 1))\n {\n\n F = f(z[2 * i], a11, a12, a13, a21, a22, a23, a31, a32, a33, b1, b2, b3);\n\n }\n\n }\n }\n else\n {\n F = 0.;\n }\n\n return F;\n\n\n\n}\n\n\n\n\n\n\n\n\n\n\ndouble container_cube_overlap_potential(double *rA, double *radiiA, double phiA, double *rotaxA)\n{\n\n double rB[3];\n double radiiB[3];\n double phiB;\n double rotaxB[3];\n\n double top, bottom, left, right, front, back;\n\n // top\n rB[0] = 0.5;\n rB[1] = 0.5;\n rB[2] = 2;\n\n radiiB[0] = INFINITY;\n radiiB[1] = INFINITY;\n radiiB[2] = 1;\n\n rotaxB[0] = 1;\n rotaxB[1] = 0;\n rotaxB[2] = 0;\n\n phiB = 0.0;\n\n top = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n\n // bottom\n rB[0] = 0.5;\n rB[1] = 0.5;\n rB[2] = -1;\n\n radiiB[0] = INFINITY;\n radiiB[1] = INFINITY;\n radiiB[2] = 1.0;\n\n rotaxB[0] = 1;\n rotaxB[1] = 0;\n rotaxB[2] = 0;\n\n phiB = 0;\n\n bottom = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n\n\n // left\n rB[0] = 0.5;\n rB[1] = -1.0;\n rB[2] = 0.5;\n\n radiiB[0] = INFINITY;\n radiiB[1] = 1;\n radiiB[2] = INFINITY;\n\n rotaxB[0] = 1;\n rotaxB[1] = 0;\n rotaxB[2] = 0;\n\n phiB = 0;\n\n left = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n\n\n // right\n rB[0] = 0.5;\n rB[1] = 2;\n rB[2] = 0.5;\n\n radiiB[0] = INFINITY;\n radiiB[1] = 1;\n radiiB[2] = INFINITY;\n\n rotaxB[0] = 1;\n rotaxB[1] = 0;\n rotaxB[2] = 0;\n\n phiB = 0;\n\n right = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n\n // front\n rB[0] = -1.0;\n rB[1] = 0.5;\n rB[2] = 0.5;\n\n radiiB[0] = 1.0;\n radiiB[1] = INFINITY;\n radiiB[2] = INFINITY;\n\n rotaxB[0] = 1.0;\n rotaxB[1] = 0.0;\n rotaxB[2] = 0.0;\n\n phiB = 0.0;\n\n front = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n\n\n\n // back\n rB[0] = 2.0;\n rB[1] = 0.5;\n rB[2] = 0.5;\n\n radiiB[0] = 1;\n radiiB[1] = INFINITY;\n radiiB[2] = INFINITY;\n\n rotaxB[0] = 1.0;\n rotaxB[1] = 0.0;\n rotaxB[2] = 0.0;\n\n phiB = 0;\n\n back = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0], &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n return fminf(top, fminf(bottom, fminf(left, fminf(right, fminf(front, back)))));\n\n}\n\n\n\n\n\n\n\n\n\nvoid random_point_on_sphere(double *rotax, double theta, double z)\n{\n\n double x, y;\n\n x = sqrt(1 - pow(z, 2)) * cos(theta);\n y = sqrt(1 - pow(z, 2)) * sin(theta);\n\n rotax[0] = x;\n rotax[1] = y;\n rotax[2] = z;\n\n}\n\n\n\n\n\n\nsize_t rsa_align_cube(double *x, double *y, double *z,\n size_t npoints, double *radius, double *rotax, double phi,\n int step_limit, unsigned long randSeed)\n{\n\n // Setup GSL random number generator\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n // Set the seed\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n double rA[3];\n double radiiA[3];\n double phiA;\n double rotaxA[3];\n\n double rB[3];\n double radiiB[3];\n double phiB;\n double rotaxB[3];\n\n size_t valid_pts;\n double F, G;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n\n\n\n // Get new ellipsoid position and orientation\n G = 0;\n while (G < 1)\n {\n\n rB[0] = gsl_rng_uniform (r);\n rB[1] = gsl_rng_uniform (r);\n rB[2] = gsl_rng_uniform (r);\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n radiiB[2] = radius[2];\n phiB = phi;\n rotaxB[0] = rotax[0];\n rotaxB[1] = rotax[1];\n rotaxB[2] = rotax[2];\n\n G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n }\n\n // store ellipsoid position\n x[0] = rB[0];\n y[0] = rB[1];\n z[0] = rB[2];\n\n\n\n\n\n // Generate ellipsoid positions\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n // Get new ellipsoid position and orientation\n G = 0;\n while (G < 1)\n {\n\n rB[0] = gsl_rng_uniform (r);\n rB[1] = gsl_rng_uniform (r);\n rB[2] = gsl_rng_uniform (r);\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n radiiB[2] = radius[2];\n phiB = phi;\n rotaxB[0] = rotax[0];\n rotaxB[1] = rotax[1];\n rotaxB[2] = rotax[2];\n\n G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n }\n\n\n\n flag = 1;\n for (k = 0; k < valid_pts; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n rA[2] = z[k];\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n radiiA[2] = radius[2];\n phiA = phi;\n rotaxA[0] = rotax[0];\n rotaxA[1] = rotax[1];\n rotaxA[2] = rotax[2];\n\n\n F = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0],\n &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n if (F < 1.0)\n {\n\n flag = 0;\n break;\n\n }\n }\n if (flag == 1)\n {\n\n x[valid_pts] = rB[0];\n y[valid_pts] = rB[1];\n z[valid_pts] = rB[2];\n valid_pts += 1;\n\n }\n\n step += 1;\n\n }\n\n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nsize_t rsa_cube(double *x, double *y, double *z,\n size_t npoints, double *radius,\n double *rtx, double *rty, double *rtz, double *phi,\n int step_limit, unsigned long randSeed)\n{\n\n // Setup GSL random number generator\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n // Set the seed\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n double rA[3];\n double radiiA[3];\n double phiA;\n double rotaxA[3];\n\n double rB[3];\n double radiiB[3];\n double phiB;\n double rotaxB[3];\n\n double theta, sz;\n\n size_t valid_pts;\n double F, G;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n\n\n\n // Get new ellipsoid position and orientation\n G = 0;\n while (G < 1)\n {\n\n rB[0] = gsl_rng_uniform (r);\n rB[1] = gsl_rng_uniform (r);\n rB[2] = gsl_rng_uniform (r);\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n radiiB[2] = radius[2];\n phiB = 2 * M_PI * gsl_rng_uniform (r);\n\n // random rotation axis\n theta = 2 * M_PI * gsl_rng_uniform (r);\n sz = 2 * gsl_rng_uniform (r) - 1;\n random_point_on_sphere(&rotaxB[0], theta, sz);\n\n\n G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n }\n\n // store ellipsoid position\n x[0] = rB[0];\n y[0] = rB[1];\n z[0] = rB[2];\n rtx[0] = rotaxB[0];\n rty[0] = rotaxB[1];\n rtz[0] = rotaxB[2];\n phi[0] = phiB;\n\n\n\n\n // Generate ellipsoid positions\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n // Get new ellipsoid position and orientation\n G = 0;\n while (G < 1)\n {\n\n rB[0] = gsl_rng_uniform (r);\n rB[1] = gsl_rng_uniform (r);\n rB[2] = gsl_rng_uniform (r);\n radiiB[0] = radius[0];\n radiiB[1] = radius[1];\n radiiB[2] = radius[2];\n phiB = 2 * M_PI * gsl_rng_uniform (r);\n\n // random rotation axis\n theta = 2 * M_PI * gsl_rng_uniform (r);\n sz = 2 * gsl_rng_uniform (r) - 1;\n random_point_on_sphere(&rotaxB[0], theta, sz);\n\n G = container_cube_overlap_potential(&rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n }\n\n\n\n flag = 1;\n for (k = 0; k < valid_pts; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n rA[2] = z[k];\n radiiA[0] = radius[0];\n radiiA[1] = radius[1];\n radiiA[2] = radius[2];\n phiA = phi[k];\n rotaxA[0] = rtx[k];\n rotaxA[1] = rty[k];\n rotaxA[2] = rtz[k];\n\n\n F = ellipsoid_overlap(&rA[0], &radiiA[0], phiA, &rotaxA[0],\n &rB[0], &radiiB[0], phiB, &rotaxB[0]);\n\n if (F < 1.0)\n {\n\n flag = 0;\n break;\n\n }\n }\n if (flag == 1)\n {\n\n x[valid_pts] = rB[0];\n y[valid_pts] = rB[1];\n z[valid_pts] = rB[2];\n rtx[valid_pts] = rotaxB[0];\n rty[valid_pts] = rotaxB[1];\n rtz[valid_pts] = rotaxB[2];\n phi[valid_pts] = phiB;\n\n valid_pts += 1;\n\n }\n\n step += 1;\n\n }\n\n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}", "meta": {"hexsha": "f8af763794094503799982eed71447a152965448", "size": 12786, "ext": "c", "lang": "C", "max_stars_repo_path": "particle_packing/cython/c/ellipsoid.c", "max_stars_repo_name": "aluchies/particle_packing", "max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "particle_packing/cython/c/ellipsoid.c", "max_issues_repo_name": "aluchies/particle_packing", "max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "particle_packing/cython/c/ellipsoid.c", "max_forks_repo_name": "aluchies/particle_packing", "max_forks_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8540372671, "max_line_length": 138, "alphanum_fraction": 0.476223995, "num_tokens": 5108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.46645583399299956}} {"text": "/* specfunc/gsl_sf_log.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 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#ifndef __GSL_SF_LOG_H__\n#define __GSL_SF_LOG_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/* Provide a logarithm function with GSL semantics.\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_log_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_log(const double x);\n\n\n/* Log(|x|)\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_log_abs_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_log_abs(const double x);\n\n\n/* Complex Logarithm\n * exp(lnr + I theta) = zr + I zi\n * Returns argument in [-pi,pi].\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_complex_log_e(const double zr, const double zi, gsl_sf_result * lnr, gsl_sf_result * theta);\n\n\n/* Log(1 + x)\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_log_1plusx_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_log_1plusx(const double x);\n\n\n/* Log(1 + x) - x\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_log_1plusx_mx_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_log_1plusx_mx(const double x);\n\n\n#ifdef HAVE_INLINE\n#include \n#include \n\nextern inline\nint\ngsl_sf_log_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n result->val = GSL_NAN;\n result->err = GSL_NAN;\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else {\n result->val = log(x);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\nextern inline\nint\ngsl_sf_log_abs_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x == 0.0) {\n result->val = GSL_NAN;\n result->err = GSL_NAN;\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else {\n result->val = log(fabs(x));\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n#endif /* HAVE_INLINE */\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_LOG_H__ */\n", "meta": {"hexsha": "2c90a6b608706d509097f9f6a29e63caf78b2b69", "size": 2867, "ext": "h", "lang": "C", "max_stars_repo_path": "extern/include/gsl/gsl_sf_log.h", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/include/gsl/gsl_sf_log.h", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/include/gsl/gsl_sf_log.h", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.936, "max_line_length": 103, "alphanum_fraction": 0.7024764562, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.46627632568725436}} {"text": "#include \n#include \n\nint\nmain (void)\n{\n gsl_multiset * c;\n size_t i;\n\n printf (\"All multisets of {0,1,2,3} by size:\\n\") ;\n for (i = 0; i <= 4; i++)\n {\n c = gsl_multiset_calloc (4, i);\n do\n {\n printf (\"{\");\n gsl_multiset_fprintf (stdout, c, \" %u\");\n printf (\" }\\n\");\n }\n while (gsl_multiset_next (c) == GSL_SUCCESS);\n gsl_multiset_free (c);\n }\n\n return 0;\n}\n", "meta": {"hexsha": "6ac1e7c1499fe93c6d336bfa27eabf7cf778d146", "size": 458, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/multiset.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/doc/examples/multiset.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/multiset.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": 17.6153846154, "max_line_length": 52, "alphanum_fraction": 0.5021834061, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.4658822585525339}} {"text": "/* multimin/vector_bfgs.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* vector_bfgs.c -- Limited memory Broyden-Fletcher-Goldfarb-Shanno\n conjugate gradient method */\n\n/* Modified by Brian Gough to use single iteration structure */\n\n#include \n#include \n#include \n\n#include \"directional_minimize.c\"\n\ntypedef struct\n{\n int iter;\n double step;\n double max_step;\n double tol;\n gsl_vector *x1;\n gsl_vector *dx1;\n gsl_vector *x2;\n double g0norm;\n double pnorm;\n gsl_vector *p;\n gsl_vector *x0;\n gsl_vector *g0;\n gsl_vector *dx0;\n gsl_vector *dg0;\n}\nvector_bfgs_state_t;\n\nstatic int\nvector_bfgs_alloc (void *vstate, size_t n)\n{\n vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate;\n\n state->x1 = gsl_vector_calloc (n);\n\n if (state->x1 == 0)\n {\n GSL_ERROR (\"failed to allocate space for x1\", GSL_ENOMEM);\n }\n\n state->dx1 = gsl_vector_calloc (n);\n\n if (state->dx1 == 0)\n {\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for dx1\", GSL_ENOMEM);\n }\n\n state->x2 = gsl_vector_calloc (n);\n\n if (state->x2 == 0)\n {\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for x2\", GSL_ENOMEM);\n }\n\n state->p = gsl_vector_calloc (n);\n\n if (state->p == 0)\n {\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for p\", GSL_ENOMEM);\n }\n\n state->x0 = gsl_vector_calloc (n);\n\n if (state->x0 == 0)\n {\n gsl_vector_free (state->p);\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for g0\", GSL_ENOMEM);\n }\n\n state->g0 = gsl_vector_calloc (n);\n\n if (state->g0 == 0)\n {\n gsl_vector_free (state->x0);\n gsl_vector_free (state->p);\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for g0\", GSL_ENOMEM);\n }\n\n state->dx0 = gsl_vector_calloc (n);\n\n if (state->dx0 == 0)\n {\n gsl_vector_free (state->g0);\n gsl_vector_free (state->x0);\n gsl_vector_free (state->p);\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for g0\", GSL_ENOMEM);\n }\n\n state->dg0 = gsl_vector_calloc (n);\n\n if (state->dg0 == 0)\n {\n gsl_vector_free (state->dx0);\n gsl_vector_free (state->g0);\n gsl_vector_free (state->x0);\n gsl_vector_free (state->p);\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n GSL_ERROR (\"failed to allocate space for g0\", GSL_ENOMEM);\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nvector_bfgs_set (void *vstate, gsl_multimin_function_fdf * fdf,\n\t\t const gsl_vector * x, double *f, gsl_vector * gradient,\n\t\t double step_size, double tol)\n{\n vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate;\n\n state->iter = 0;\n state->step = step_size;\n state->max_step = step_size;\n state->tol = tol;\n\n GSL_MULTIMIN_FN_EVAL_F_DF (fdf, x, f, gradient);\n\n /* Use the gradient as the initial direction */\n\n gsl_vector_memcpy (state->x0, x);\n gsl_vector_memcpy (state->p, gradient);\n gsl_vector_memcpy (state->g0, gradient);\n\n {\n double gnorm = gsl_blas_dnrm2 (gradient);\n state->pnorm = gnorm;\n state->g0norm = gnorm;\n }\n\n return GSL_SUCCESS;\n}\n\nstatic void\nvector_bfgs_free (void *vstate)\n{\n vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate;\n\n gsl_vector_free (state->dg0);\n gsl_vector_free (state->dx0);\n gsl_vector_free (state->g0);\n gsl_vector_free (state->x0);\n gsl_vector_free (state->p);\n gsl_vector_free (state->x2);\n gsl_vector_free (state->dx1);\n gsl_vector_free (state->x1);\n}\n\nstatic int\nvector_bfgs_restart (void *vstate)\n{\n vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate;\n\n state->iter = 0;\n return GSL_SUCCESS;\n}\n\nstatic int\nvector_bfgs_iterate (void *vstate, gsl_multimin_function_fdf * fdf,\n\t\t gsl_vector * x, double *f,\n\t\t gsl_vector * gradient, gsl_vector * dx)\n{\n vector_bfgs_state_t *state = (vector_bfgs_state_t *) vstate;\n\n gsl_vector *x1 = state->x1;\n gsl_vector *dx1 = state->dx1;\n gsl_vector *x2 = state->x2;\n gsl_vector *p = state->p;\n gsl_vector *g0 = state->g0;\n gsl_vector *x0 = state->x0;\n\n double pnorm = state->pnorm;\n double g0norm = state->g0norm;\n\n double fa = *f, fb, fc;\n double dir;\n double stepa = 0.0, stepb, stepc = state->step, tol = state->tol;\n\n double g1norm;\n double pg;\n\n if (pnorm == 0.0 || g0norm == 0.0)\n {\n gsl_vector_set_zero (dx);\n return GSL_ENOPROG;\n }\n\n /* Determine which direction is downhill, +p or -p */\n\n gsl_blas_ddot (p, gradient, &pg);\n\n dir = (pg >= 0.0) ? +1.0 : -1.0;\n\n /* Compute new trial point at x_c= x - step * p, where p is the\n current direction */\n\n take_step (x, p, stepc, dir / pnorm, x1, dx);\n\n /* Evaluate function and gradient at new point xc */\n\n fc = GSL_MULTIMIN_FN_EVAL_F (fdf, x1);\n\n if (fc < fa)\n {\n /* Success, reduced the function value */\n state->step = stepc * 2.0;\n *f = fc;\n gsl_vector_memcpy (x, x1);\n GSL_MULTIMIN_FN_EVAL_DF (fdf, x1, gradient);\n state->g0norm = gsl_blas_dnrm2 (gradient);\n return GSL_SUCCESS;\n }\n\n#ifdef DEBUG\n printf (\"got stepc = %g fc = %g\\n\", stepc, fc);\n#endif\n\n /* Do a line minimisation in the region (xa,fa) (xc,fc) to find an\n intermediate (xb,fb) satisifying fa > fb < fc. Choose an initial\n xb based on parabolic interpolation */\n\n intermediate_point (fdf, x, p, dir / pnorm, pg,\n\t\t stepa, stepc, fa, fc, x1, dx1, gradient, &stepb, &fb);\n\n minimize (fdf, x, p, dir / pnorm,\n\t stepa, stepb, stepc, fa, fb, fc, tol,\n\t x1, dx1, x2, dx, gradient, &(state->step), f, &g1norm);\n\n gsl_vector_memcpy (x, x2);\n\n /* Choose a new conjugate direction for the next step */\n\n state->iter = (state->iter + 1) % x->size;\n\n if (state->iter == 0)\n {\n gsl_vector_memcpy (p, gradient);\n state->pnorm = g1norm;\n }\n else\n {\n /* This is the BFGS update: */\n /* p' = g1 - A dx - B dg */\n /* A = - (1+ dg.dg/dx.dg) B + dg.g/dx.dg */\n /* B = dx.g/dx.dg */\n\n gsl_vector *dx0 = state->dx0;\n gsl_vector *dg0 = state->dg0;\n\n double dxg, dgg, dxdg, dgnorm, A, B;\n\n /* dx0 = x - x0 */\n gsl_vector_memcpy (dx0, x);\n gsl_blas_daxpy (-1.0, x0, dx0);\n\n /* dg0 = g - g0 */\n gsl_vector_memcpy (dg0, gradient);\n gsl_blas_daxpy (-1.0, g0, dg0);\n\n gsl_blas_ddot (dx0, gradient, &dxg);\n gsl_blas_ddot (dg0, gradient, &dgg);\n gsl_blas_ddot (dx0, dg0, &dxdg);\n\n dgnorm = gsl_blas_dnrm2 (dg0);\n\n B = dxg / dxdg;\n A = -(1.0 + dgnorm * dgnorm / dxdg) * B + dgg / dxdg;\n\n gsl_vector_memcpy (p, gradient);\n gsl_blas_daxpy (-A, dx0, p);\n gsl_blas_daxpy (-B, dg0, p);\n\n state->pnorm = gsl_blas_dnrm2 (p);\n }\n\n gsl_vector_memcpy (g0, gradient);\n gsl_vector_memcpy (x0, x);\n state->g0norm = gsl_blas_dnrm2 (g0);\n\n#ifdef DEBUG\n printf (\"updated conjugate directions\\n\");\n printf (\"p: \");\n gsl_vector_fprintf (stdout, p, \"%g\");\n printf (\"g: \");\n gsl_vector_fprintf (stdout, gradient, \"%g\");\n#endif\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_multimin_fdfminimizer_type vector_bfgs_type = {\n \"vector_bfgs\",\t\t/* name */\n sizeof (vector_bfgs_state_t),\n &vector_bfgs_alloc,\n &vector_bfgs_set,\n &vector_bfgs_iterate,\n &vector_bfgs_restart,\n &vector_bfgs_free\n};\n\nconst gsl_multimin_fdfminimizer_type\n * gsl_multimin_fdfminimizer_vector_bfgs = &vector_bfgs_type;\n", "meta": {"hexsha": "bbcbed5e23a8f81ab840ee392ccb3c0dcf244ccc", "size": 8470, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multimin/vector_bfgs.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/multimin/vector_bfgs.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/multimin/vector_bfgs.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 24.9117647059, "max_line_length": 72, "alphanum_fraction": 0.6436835891, "num_tokens": 2679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.46580832197988986}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for EOBNRv2HM reduced order model (non-spinning version).\n * See CQG 31 195010, 2014, arXiv:1402.4146 for details on the reduced order method.\n * See arXiv:1106.1021 for the EOBNRv2HM model.\n *\n * Borrows from the SEOBNR ROM LAL code written by Michael Puerrer and John Veitch.\n *\n * Put the untared data in the directory designated by the environment variable ROM_DATA_PATH.\n *\n * Parameter ranges:\n * q = 1-12 (almost)\n * No spin\n * Mtot >= 10Msun for fstart=8Hz\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"EOBNRv2HMROMstruct.h\"\n#include \"EOBNRv2HMROM.h\"\n\n/*************************************************/\n/********* Some general definitions **************/\n\n/* Number and list of modes to generate - to be modified ultimately to allow for a selection of the desired mode(s) */\n/* By convention the first mode of the list is used to set phiRef */\n/* nbmodemax = 5 has been defined in the header */\nconst int listmode[nbmodemax][2] = { {2,2}, {2,1}, {3,3}, {4,4}, {5,5} };\n\n/* Maximal mass ratio covered by the model - q=12 (almost) for now */\nstatic const double q_max = 11.9894197212;\n/* Minimal geometric frequency covered by the model - f=8Hz for M=10Msol for now */\nstatic const double Mf_ROM_min = 0.0003940393857519091;\n/* Maximal geometric frequency covered by the model - Mf=0.285 for the 55 mode - used as default */\nstatic const double Mf_ROM_max = 0.285;\n/* Total mass (in units of solar mass) used to generate the ROM - used to restore the correct amplitude (global factor M) when coming back to physical units */\nstatic const double M_ROM = 10.;\n\n/* Define the number of points in frequency used by the SVD, identical for all modes */\nstatic const int nbfreq = 300;\n/* Define the number of training waveforms used by the SVD, identical for all modes */\nstatic const int nbwf = 301;\n\n/******************************************************************/\n/********* Definitions for the persistent structures **************/\n\n/* SEOBNR-ROM structures are generalized to lists */\nListmodesEOBNRHMROMdata* __EOBNRv2HMROM_data_init = NULL; /* for initialization only */\nListmodesEOBNRHMROMdata** const __EOBNRv2HMROM_data = &__EOBNRv2HMROM_data_init;\nListmodesEOBNRHMROMdata_interp* __EOBNRv2HMROM_interp_init = NULL; /* for initialization only */\nListmodesEOBNRHMROMdata_interp** const __EOBNRv2HMROM_interp = &__EOBNRv2HMROM_interp_init;\n/* Tag indicating whether the data has been loaded and interpolated */\nint __EOBNRv2HMROM_setup = FAILURE; /* To be set to SUCCESS after initialization*/\n\n/********************* Miscellaneous ********************/\n\n/* Return the closest higher power of 2 */\nstatic size_t NextPow2(const size_t n) {\n return 1 << (size_t) ceil(log2(n));\n}\n\n/* Arbitrary tuned q-dependent functions by which the frequencies for the 44 and 55 modes have been multiplied (to put the ringdowns at the same Mf). The frequencies stored in the data for the 44 and 55 modes are the rescaled ones, not the original ones. */\nstatic double Scaling44(const double q) {\n return 1.-1./4.*exp(-(q-1.)/5.);\n}\nstatic double Scaling55(const double q) {\n return 1.-1./3.*exp(-(q-1.)/5.);\n}\n\n/* Function evaluating eta as a function of q */\nstatic double EtaOfq(const double q) {\n return q/(1.+q)/(1.+q);\n}\n/* Function evaluating delta m/m = (m1-m2)/(m1+m2) as a function of q */\nstatic double DeltaOfq(const double q) {\n return( (q-1.)/(q+1.) );\n}\n\n/* Fit of the frequency of the 22 mode at the peak amplitude - from table III in the EOBNRv2HM paper, Pan&al 1106 */\nstatic double omega22peakOfq(const double q) {\n double eta = EtaOfq(q);\n return 0.2733 + 0.2316*eta + 0.4463*eta*eta;\n}\n\n/* Amplitude factors scaled out for each mode; this does not include the global amplitude factor scaled out from all modes. */\nstatic double ModeAmpFactor(const int l, const int m, const double q) {\n double eta = EtaOfq(q);\n if( l==2 && m==2 ) return(sqrt(eta));\n else if( l==2 && m==1 ) return( sqrt(eta)*DeltaOfq(q) );\n else if( l==3 && m==3 ) return( sqrt(eta)*DeltaOfq(q) );\n else if( l==4 && m==4 ) return( sqrt(Scaling44(q))*sqrt(eta)*(1.-3.*eta) );\n else if( l==5 && m==5 ) return( pow(Scaling55(q), 1./6)*sqrt(eta)*DeltaOfq(q)*(1.-2.*eta) );\n else {\n fprintf(stderr, \"Unknown mode (%d,%d) for the amplitude factor.\\n\", l, m);\n return(FAILURE);\n }\n}\n\n/********************* Functions to initialize and cleanup contents of data structures ********************/\nvoid EOBNRHMROMdata_Init(EOBNRHMROMdata **data) {\n if(!data) exit(1);\n /* Create storage for structures */\n if(!*data) *data=malloc(sizeof(EOBNRHMROMdata));\n else\n {\n EOBNRHMROMdata_Cleanup(*data);\n }\n gsl_set_error_handler(&Err_Handler);\n (*data)->q = gsl_vector_alloc(nbwf);\n (*data)->freq = gsl_vector_alloc(nbfreq);\n (*data)->Camp = gsl_matrix_alloc(nk_amp,nbwf);\n (*data)->Cphi = gsl_matrix_alloc(nk_phi,nbwf);\n (*data)->Bamp = gsl_matrix_alloc(nbfreq,nk_amp);\n (*data)->Bphi = gsl_matrix_alloc(nbfreq,nk_phi);\n (*data)->shifttime = gsl_vector_alloc(nbwf);\n (*data)->shiftphase = gsl_vector_alloc(nbwf);\n}\nvoid EOBNRHMROMdata_interp_Init(EOBNRHMROMdata_interp **data_interp) {\n if(!data_interp) exit(1);\n /* Create storage for structures */\n if(!*data_interp) *data_interp=malloc(sizeof(EOBNRHMROMdata_interp));\n else\n {\n EOBNRHMROMdata_interp_Cleanup(*data_interp);\n }\n (*data_interp)->Camp_interp = NULL;\n (*data_interp)->Cphi_interp = NULL;\n (*data_interp)->shifttime_interp = NULL;\n (*data_interp)->shiftphase_interp = NULL;\n}\nvoid EOBNRHMROMdata_coeff_Init(EOBNRHMROMdata_coeff **data_coeff) {\n if(!data_coeff) exit(1);\n /* Create storage for structures */\n if(!*data_coeff) *data_coeff=malloc(sizeof(EOBNRHMROMdata_coeff));\n else\n {\n EOBNRHMROMdata_coeff_Cleanup(*data_coeff);\n }\n gsl_set_error_handler(&Err_Handler);\n (*data_coeff)->Camp_coeff = gsl_vector_alloc(nk_amp);\n (*data_coeff)->Cphi_coeff = gsl_vector_alloc(nk_phi);\n (*data_coeff)->shifttime_coeff = malloc(sizeof(double));\n (*data_coeff)->shiftphase_coeff = malloc(sizeof(double));\n}\nvoid EOBNRHMROMdata_Cleanup(EOBNRHMROMdata *data /* data to destroy */) {\n if(data->q) gsl_vector_free(data->q);\n if(data->freq) gsl_vector_free(data->freq);\n if(data->Camp) gsl_matrix_free(data->Camp);\n if(data->Cphi) gsl_matrix_free(data->Cphi);\n if(data->Bamp) gsl_matrix_free(data->Bamp);\n if(data->Bphi) gsl_matrix_free(data->Bphi);\n if(data->shifttime) gsl_vector_free(data->shifttime);\n if(data->shiftphase) gsl_vector_free(data->shiftphase);\n free(data);\n}\nvoid EOBNRHMROMdata_coeff_Cleanup(EOBNRHMROMdata_coeff *data_coeff) {\n if(data_coeff->Camp_coeff) gsl_vector_free(data_coeff->Camp_coeff);\n if(data_coeff->Cphi_coeff) gsl_vector_free(data_coeff->Cphi_coeff);\n if(data_coeff->shifttime_coeff) free(data_coeff->shifttime_coeff);\n if(data_coeff->shiftphase_coeff) free(data_coeff->shiftphase_coeff);\n free(data_coeff);\n}\nvoid EOBNRHMROMdata_interp_Cleanup(EOBNRHMROMdata_interp *data_interp) {\n if(data_interp->Camp_interp) SplineList_Destroy(data_interp->Camp_interp);\n if(data_interp->Cphi_interp) SplineList_Destroy(data_interp->Cphi_interp);\n if(data_interp->shifttime_interp) SplineList_Destroy(data_interp->shifttime_interp);\n if(data_interp->shiftphase_interp) SplineList_Destroy(data_interp->shiftphase_interp);\n free(data_interp);\n}\n\n/* Read binary ROM data for frequency vectors, coefficients matrices, basis functions matrices, and shiftvectors in time and phase */\nint Read_Data_Mode(const char dir[], const int mode[2], EOBNRHMROMdata *data) {\n /* Load binary data for amplitude and phase spline coefficients as computed in Mathematica */\n int ret = SUCCESS;\n char* file_q = malloc(strlen(dir)+64);\n char* file_freq = malloc(strlen(dir)+64);\n char* file_Camp = malloc(strlen(dir)+64);\n char* file_Cphi = malloc(strlen(dir)+64);\n char* file_Bamp = malloc(strlen(dir)+64);\n char* file_Bphi = malloc(strlen(dir)+64);\n char* file_shifttime = malloc(strlen(dir)+64);\n char* file_shiftphase = malloc(strlen(dir)+64);\n sprintf(file_q, \"%s\", \"EOBNRv2HMROM_q.dat\"); /* The q vector is the same for all modes */\n sprintf(file_freq, \"%s%d%d%s\", \"EOBNRv2HMROM_freq_\", mode[0], mode[1], \".dat\");\n sprintf(file_Camp, \"%s%d%d%s\", \"EOBNRv2HMROM_Camp_\", mode[0], mode[1], \".dat\");\n sprintf(file_Cphi, \"%s%d%d%s\", \"EOBNRv2HMROM_Cphi_\", mode[0], mode[1], \".dat\");\n sprintf(file_Bamp, \"%s%d%d%s\", \"EOBNRv2HMROM_Bamp_\", mode[0], mode[1], \".dat\");\n sprintf(file_Bphi, \"%s%d%d%s\", \"EOBNRv2HMROM_Bphi_\", mode[0], mode[1], \".dat\");\n sprintf(file_shifttime, \"%s%d%d%s\", \"EOBNRv2HMROM_shifttime_\", mode[0], mode[1], \".dat\");\n sprintf(file_shiftphase, \"%s%d%d%s\", \"EOBNRv2HMROM_shiftphase_\", mode[0], mode[1], \".dat\");\n ret |= Read_Vector(dir, file_q, data->q);\n ret |= Read_Vector(dir, file_freq, data->freq);\n ret |= Read_Matrix(dir, file_Camp, data->Camp);\n ret |= Read_Matrix(dir, file_Cphi, data->Cphi);\n ret |= Read_Matrix(dir, file_Bamp, data->Bamp);\n ret |= Read_Matrix(dir, file_Bphi, data->Bphi);\n ret |= Read_Vector(dir, file_shifttime, data->shifttime);\n ret |= Read_Vector(dir, file_shiftphase, data->shiftphase);\n free(file_q);\n free(file_freq);\n free(file_Camp);\n free(file_Cphi);\n free(file_Bamp);\n free(file_Bphi);\n free(file_shifttime);\n free(file_shiftphase);\n return(ret);\n}\n\n/* Function interpolating the data in matrix/vector form produces an interpolated data in the form of SplineLists */\nint Interpolate_Spline_Data(const EOBNRHMROMdata *data, EOBNRHMROMdata_interp *data_interp) {\n\n gsl_set_error_handler(&Err_Handler);\n SplineList* splinelist;\n gsl_spline* spline;\n gsl_interp_accel* accel;\n gsl_vector* matrixline;\n gsl_vector* vector;\n int j;\n\n /* Interpolating Camp */\n splinelist = data_interp->Camp_interp;\n for (j = 0; jCamp, j);\n\n accel = gsl_interp_accel_alloc();\n spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);\n gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(matrixline, 0), nbwf);\n\n splinelist = SplineList_AddElementNoCopy(splinelist, spline, accel, j);\n gsl_vector_free(matrixline);\n }\n data_interp->Camp_interp = splinelist;\n\n /* Interpolating Cphi */\n splinelist = data_interp->Cphi_interp;\n for (j = 0; jCphi, j);\n\n accel = gsl_interp_accel_alloc();\n spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);\n gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(matrixline, 0), nbwf);\n\n splinelist = SplineList_AddElementNoCopy(splinelist, spline, accel, j);\n gsl_vector_free(matrixline);\n }\n data_interp->Cphi_interp = splinelist;\n\n /* Interpolating shifttime */\n splinelist = data_interp->shifttime_interp;\n vector = data->shifttime;\n\n accel = gsl_interp_accel_alloc();\n spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);\n gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(vector, 0), nbwf);\n\n splinelist = SplineList_AddElementNoCopy(NULL, spline, accel, 0); /* This SplineList has only 1 element */\n data_interp->shifttime_interp = splinelist;\n\n /* Interpolating shiftphase */\n splinelist = data_interp->shiftphase_interp;\n vector = data->shiftphase;\n\n accel = gsl_interp_accel_alloc();\n spline = gsl_spline_alloc(gsl_interp_cspline, nbwf);\n gsl_spline_init(spline, gsl_vector_const_ptr(data->q, 0), gsl_vector_const_ptr(vector, 0), nbwf);\n\n splinelist = SplineList_AddElementNoCopy(NULL, spline, accel, 0); /* This SplineList has only 1 element */\n data_interp->shiftphase_interp = splinelist;\n\n return SUCCESS;\n}\n\n/* Function taking as input interpolated data in the form of SplineLists\n * evaluates for a given q the projection coefficients and shifts in time and phase\n*/\nint Evaluate_Spline_Data(const double q, const EOBNRHMROMdata_interp* data_interp, EOBNRHMROMdata_coeff* data_coeff){\n\n SplineList* splinelist;\n /* Evaluating the vector of projection coefficients for the amplitude */\n for (int j=0; jCamp_interp, j);\n gsl_vector_set(data_coeff->Camp_coeff, j, gsl_spline_eval(splinelist->spline, q, splinelist->accel));\n }\n /* Evaluating the vector of projection coefficients for the phase */\n for (int j=0; jCphi_interp, j);\n gsl_vector_set(data_coeff->Cphi_coeff, j, gsl_spline_eval(splinelist->spline, q, splinelist->accel));\n }\n /* Evaluating the shift in time */\n splinelist = SplineList_GetElement(data_interp->shifttime_interp, 0); /* This SplineList has only one element */\n *(data_coeff->shifttime_coeff) = gsl_spline_eval(splinelist->spline, q, splinelist->accel);\n /* Evaluating the shift in phase */\n splinelist = SplineList_GetElement(data_interp->shiftphase_interp, 0); /* This SplineList has only one element */\n *(data_coeff->shiftphase_coeff) = gsl_spline_eval(splinelist->spline, q, splinelist->accel);\n\n return SUCCESS;\n}\n\n/*\n * Core function for computing the ROM waveform.\n * Evaluates projection coefficients and shifts in time and phase at desired q.\n * Construct 1D splines for amplitude and phase.\n * Compute strain waveform from amplitude and phase.\n*/\nint EOBNRv2HMROMCore(\n struct tagListmodesCAmpPhaseFrequencySeries **listhlm,\n int nbmode,\n double deltatRef,\n double phiRef,\n double fRef,\n double Mtot_sec,\n double q,\n double distance,\n int setphiRefatfRef)\n{\n int ret = SUCCESS;\n int j;\n double tpeak22estimate = 0;\n /* Check output arrays */\n if(!listhlm) exit(1);\n if(*listhlm)\n {\n printf(\"Error: (*listhlm) is supposed to be NULL, but got %p\\n\",(*listhlm));\n exit(1);\n }\n /* Check number of modes */\n if(nbmode<1 || nbmode>nbmodemax) {\n printf(\"Error: incorrect number of modes: %d\", nbmode);\n exit(1);\n }\n\n /* Check if the data has been set up */\n if(__EOBNRv2HMROM_setup) {\n printf(\"Error: the ROM data has not been set up\\n\");\n exit(1);\n }\n /* Set the global pointers to data */\n ListmodesEOBNRHMROMdata* listdata = *__EOBNRv2HMROM_data;\n ListmodesEOBNRHMROMdata_interp* listdata_interp = *__EOBNRv2HMROM_interp;\n\n /* Global amplitude prefactor - includes total mass scaling, Fourier scaling, distance scaling, and undoing an additional arbitrary scaling */\n double Mtot_msol = Mtot_sec / MTSUN_SI; /* Mtot_msol and M_ROM in units of solar mass */\n double amp0 = (Mtot_msol/M_ROM) * Mtot_sec * 1.E-16 * 1.E6 * PC_SI / distance;\n\n /* Highest allowed geometric frequency for the first mode of listmode in the ROM - used for fRef\n * by convention, we use the first mode of listmode (presumably the 22) for phiref */\n ListmodesEOBNRHMROMdata* listdata_ref = ListmodesEOBNRHMROMdata_GetMode(listdata, listmode[0][0], listmode[0][1]);\n EOBNRHMROMdata* data_ref = listdata_ref->data;\n double Mf_ROM_max_ref = gsl_vector_get(data_ref->freq, nbfreq-1);\n /* Convert to geometric units the reference time and frequency */\n double deltatRef_geom = deltatRef / Mtot_sec;\n double fRef_geom = fRef * Mtot_sec;\n\n /* Enforce allowed geometric frequency range for fRef */\n /* In case the user asks for a reference frequency higher than covered by the ROM, we keep it that way as we will just 0-pad the waveform (and do it anyway for some modes) */\n if (fRef_geom > Mf_ROM_max_ref || fRef_geom == 0)\n fRef_geom = Mf_ROM_max_ref; /* If fRef > fhigh or 0 we reset fRef to default value of cutoff frequency for the first mode of the list (presumably the 22 mode) */\n if (0 < fRef_geom && fRef_geom < Mf_ROM_min) {\n //printf(\"WARNING: Reference frequency Mf_ref=%g is smaller than lowest frequency in ROM Mf=%g. Setting it to the lowest frequency in ROM.\\n\", fRef_geom, Mf_ROM_min);\n fRef_geom = Mf_ROM_min;\n }\n\n /* Internal storage for the projection coefficients and shifts in time and phase */\n /* Initialized only once, and reused for the different modes */\n EOBNRHMROMdata_coeff *data_coeff = NULL;\n EOBNRHMROMdata_coeff_Init(&data_coeff);\n\n /* The phase change imposed by phiref, from the phase of the first mode in the list - to be set in the first step of the loop on the modes */\n double phase_change_ref = 0;\n\n /* Main loop over the modes */\n for(int i=0; idata_interp, data_coeff);\n\n /* Evaluating the unnormalized amplitude and unshifted phase vectors for the mode */\n /* Notice a change in convention: B matrices are transposed with respect to the B matrices in SEOBNRROM */\n /* amp_pts = Bamp . Camp_coeff */\n /* phi_pts = Bphi . Cphi_coeff */\n gsl_vector* amp_f = gsl_vector_alloc(nbfreq);\n gsl_vector* phi_f = gsl_vector_alloc(nbfreq);\n //clock_t begblas = clock();\n gsl_blas_dgemv(CblasNoTrans, 1.0, listdata_mode->data->Bamp, data_coeff->Camp_coeff, 0.0, amp_f);\n gsl_blas_dgemv(CblasNoTrans, 1.0, listdata_mode->data->Bphi, data_coeff->Cphi_coeff, 0.0, phi_f);\n //clock_t endblas = clock();\n //printf(\"Mode (%d,%d) Blas time: %g s\\n\", l, m, (double)(endblas - begblas) / CLOCKS_PER_SEC);\n\n /* The downsampled frequencies for the mode - we undo the rescaling of the frequency for the 44 and 55 modes */\n gsl_vector* freq_ds = gsl_vector_alloc(nbfreq);\n gsl_vector_memcpy(freq_ds, listdata_mode->data->freq);\n if ( l==4 && m==4) gsl_vector_scale( freq_ds, 1./Scaling44(q));\n if ( l==5 && m==5) gsl_vector_scale( freq_ds, 1./Scaling55(q));\n\n /* Evaluating the shifts in time and phase - conditional scaling for the 44 and 55 modes */\n /* Note: the stored values of 'shifttime' correspond actually to 2pi*Deltat */\n SplineList* shifttime_splinelist = listdata_interp_mode->data_interp->shifttime_interp;\n SplineList* shiftphase_splinelist = listdata_interp_mode->data_interp->shiftphase_interp;\n double twopishifttime;\n if( l==4 && m==4) {\n twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel) * Scaling44(q);\n }\n else if( l==5 && m==5) {\n twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel) * Scaling55(q);\n }\n else {\n twopishifttime = gsl_spline_eval(shifttime_splinelist->spline, q, shifttime_splinelist->accel);\n }\n double shiftphase = gsl_spline_eval(shiftphase_splinelist->spline, q, shiftphase_splinelist->accel);\n\n /* If first mode in the list, assumed to be the 22 mode, set totalshifttime and phase_change_ref */\n if( i==0 ) {\n if(l==2 && m==2) {\n /* Setup 1d cubic spline for the phase of the 22 mode */\n gsl_interp_accel* accel_phi22 = gsl_interp_accel_alloc();\n gsl_spline* spline_phi22 = gsl_spline_alloc(gsl_interp_cspline, nbfreq);\n gsl_spline_init(spline_phi22, gsl_vector_const_ptr(freq_ds,0), gsl_vector_const_ptr(phi_f,0), nbfreq);\n /* Compute the shift in time needed to set the peak of the 22 mode roughly at deltatRef */\n /* We use the SPA formula tf = -(1/2pi)*dPsi/df to estimate the correspondence between frequency and time */\n /* The frequency corresponding to the 22 peak is omega22peak/2pi, with omega22peak taken from the fit to NR in Pan&al 1106 EOBNRv2HM paper */\n double f22peak = fmin(omega22peakOfq(q)/(2*PI), Mf_ROM_max_ref); /* We ensure we evaluate the spline within its range */\n /* Note : twopishifttime is almost 0 (order 1e-8) by construction for the 22 mode, so it does not intervene here */\n tpeak22estimate = -1./(2*PI) * gsl_spline_eval_deriv(spline_phi22, f22peak, accel_phi22);\n /* Determine the change in phase (to be propagated to all modes) required to have phi22(fRef) = 2*phiRef */\n if(setphiRefatfRef) {\n phase_change_ref = 2*phiRef + (gsl_spline_eval(spline_phi22, fRef_geom, accel_phi22) - (twopishifttime - 2*PI*tpeak22estimate + 2*PI*deltatRef_geom) * fRef_geom - shiftphase);\n }\n else {\n phase_change_ref = 2*phiRef;\n }\n gsl_spline_free(spline_phi22);\n gsl_interp_accel_free(accel_phi22);\n }\n else {\n \tprintf(\"Error: the first mode in listmode must be the 22 mode to set the changes in phase and time \\n\");\n \treturn FAILURE;\n }\n }\n /* Total shift in time, and total change in phase for this mode */\n double totaltwopishifttime = twopishifttime - 2*PI*tpeak22estimate + 2*PI*deltatRef_geom;\n double constphaseshift = m/2. * phase_change_ref + shiftphase;\n\n //\n //printf(\"deltatRef_geom: %g\\n\", deltatRef_geom);\n //printf(\"freq_ds 0: %g\\n\", gsl_vector_get(freq_ds, 0));\n\n //printf(\"2*PI*deltatRef_geom * gsl_vector_get(freq_ds, 0), phase_change_ref: %g, %g\\n\", 2*PI*deltatRef_geom * gsl_vector_get(freq_ds, 0), phase_change_ref);\n\n /* Initialize the complex series for the mode */\n CAmpPhaseFrequencySeries *modefreqseries = NULL;\n int len = (int) freq_ds->size;\n CAmpPhaseFrequencySeries_Init(&modefreqseries, len);\n\n /* Mode-dependent complete amplitude prefactor */\n double amp_pre = amp0 * ModeAmpFactor( l, m, q);\n\n /* Final result for the mode */\n /* Scale and set the amplitudes (amplitudes are real at this stage)*/\n gsl_vector_scale(amp_f, amp_pre);\n gsl_vector_memcpy(modefreqseries->amp_real, amp_f);\n gsl_vector_set_zero(modefreqseries->amp_imag); /* Amplitudes are real at this stage */\n /* Add the linear term and the constant (including the shift to phiRef), and set the phases */\n gsl_vector_scale(phi_f, -1.); /* Change the sign of the phases: ROM convention Psi=-phase */\n gsl_blas_daxpy(totaltwopishifttime, freq_ds, phi_f); /*Beware: here freq_ds must still be in geometric units*/\n gsl_vector_add_constant(phi_f, constphaseshift);\n gsl_vector_memcpy(modefreqseries->phase, phi_f);\n\n//\n//printf(\"first phi_f: %g\\n\", gsl_vector_get(phi_f, 0 ));\n//printf(\"last phi_f: %g\\n\", gsl_vector_get(phi_f, phi_f->size -1 ));\n\n /* Scale (to physical units) and set the frequencies */\n gsl_vector_scale(freq_ds, 1./Mtot_sec);\n gsl_vector_memcpy(modefreqseries->freq, freq_ds);\n\n /* Append the computed mode to the ListmodesCAmpPhaseFrequencySeries structure */\n *listhlm = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listhlm, modefreqseries, l, m);\n\n //\n //printf(\"Mode (%d,%d) generated:\\n\", l, m);\n //for( int j=0; jfreq, j), gsl_vector_get(modefreqseries->amp_real, j), gsl_vector_get(modefreqseries->amp_imag, j), gsl_vector_get(modefreqseries->phase, j));\n //}\n\n /* Cleanup for the mode */\n gsl_vector_free(freq_ds);\n gsl_vector_free(amp_f);\n gsl_vector_free(phi_f);\n }\n\n /* Cleanup of the coefficients data structure */\n EOBNRHMROMdata_coeff_Cleanup(data_coeff);\n\n return(SUCCESS);\n}\n\n/* Compute waveform in downsampled frequency-amplitude-phase format */\nint SimEOBNRv2HMROM(\n struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */\n int nbmode, /* Number of modes to generate (starting with the 22) */\n double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */\n double phiRef, /* Phase at reference frequency */\n double fRef, /* Reference frequency (Hz); 0 defaults to fLow */\n double m1SI, /* Mass of companion 1 (kg) */\n double m2SI, /* Mass of companion 2 (kg) */\n double distance, /* Distance of source (m) */\n int setphiRefatfRef) /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */\n{\n /* Get masses in terms of solar mass */\n double mass1 = m1SI / MSUN_SI;\n double mass2 = m2SI / MSUN_SI;\n double Mtot = mass1 + mass2;\n double q = fmax(mass1/mass2, mass2/mass1); /* Mass-ratio >1 by convention*/\n double Mtot_sec = Mtot * MTSUN_SI; /* Total mass in seconds */\n\n if ( q > q_max ) {\n //printf( \"Error - %s: q out of range!\\nEOBNRv2HMROM is only available for a mass ratio in the range q <= %g.\\n\", __func__, q_max);\n return FAILURE;\n }\n\n /* Set up (load and build interpolation) ROM data if not setup already */\n //clock_t beg = clock();\n EOBNRv2HMROM_Init_DATA();\n //clock_t end = clock();\n //printf(\"Initialization time: %g s\\n\", (double)(end - beg) / CLOCKS_PER_SEC);\n\n //beg = clock();\n int retcode = EOBNRv2HMROMCore(listhlm, nbmode, deltatRef, phiRef, fRef, Mtot_sec, q, distance, setphiRefatfRef);\n //end = clock();\n //printf(\"ROM evaluation time: %g s\\n\", (double)(end - beg) / CLOCKS_PER_SEC);\n\n return(retcode);\n}\n\n/* Setup EOBNRv2HMROM model using data files installed in $ROM_DATA_PATH */\nint EOBNRv2HMROM_Init_DATA(void) {\n if (!__EOBNRv2HMROM_setup) return SUCCESS;\n\n int ret=FAILURE;\n char *envpath=NULL;\n char path[32768];\n char *brkt,*word;\n envpath=getenv(\"ROM_DATA_PATH\");\n if(!envpath) {\n printf(\"Error: the environment variable ROM_DATA_PATH, giving the path to the ROM data, seems undefined\\n\");\n return(FAILURE);\n }\n strncpy(path,envpath,sizeof(path));\n\n#pragma omp critical\n {\n for(word=strtok_r(path,\":\",&brkt); word; word=strtok_r(NULL,\":\",&brkt))\n {\n\tret = EOBNRv2HMROM_Init(word);\n\tif(ret == SUCCESS) break;\n }\n if(ret!=SUCCESS) {\n printf(\"Error: unable to find EOBNRv2HMROM data files in $ROM_DATA_PATH\\n\");\n exit(FAILURE);\n }\n __EOBNRv2HMROM_setup = ret;\n }\n return(ret);\n}\n\n/* Setup EOBNRv2HMROM model using data files installed in dir */\nint EOBNRv2HMROM_Init(const char dir[]) {\n if(!__EOBNRv2HMROM_setup) {\n printf(\"Error: EOBNRHMROMdata was already set up!\");\n exit(1);\n }\n\n int ret = SUCCESS;\n ListmodesEOBNRHMROMdata* listdata = *__EOBNRv2HMROM_data;\n ListmodesEOBNRHMROMdata_interp* listdata_interp = *__EOBNRv2HMROM_interp;\n\n for (int j=0; j -flux/dEnergy = fdot / (3*v^2) [using x=v^2]*/\n //amp[i] = amp0 * sqrt(-dEnergy/flux) * v; (Based on LAL)\n amp[i] = amp0B * amp22fac * v2 / sqrt(-flux/dEnergy * 3 * v2 );\n //printf(\"v=%g: a=%g ph=%g; amp22fac=%g sqrt(v^-9)=%g\\n\",v,amp[i],phase[i],amp22fac,sqrt(v/v10));\n //Note ampB = - amp * 4*sqrt(3/5) * / sqrt(3) + higher-order = -4/sqrt(5)*( 1 + higher-order )\n // ...possibly related to sph-harm normalization\n // HACK: Strangely it seems that an additional factor of 4/sqrt(5) is just right to nearly match the EOB wf FT\n amp[i] *= 4/sqrt(5); //HACK\n\n //Here we depart from LAL, referencing phase and time-shift to two neighboring freq points\n //First we match the freq derivative\n }\n}\n\n/*Wrapper for waveform generation with possibly a combination of EOBNRv2HMROM and TaylorF2*/\n/* Note: GenerateWaveform accepts masses and distances in SI units, whereas LISA params is in solar masses and Mpc */\n/* Note: the extended waveform will now a different number of frequency points for each mode */\n/* Note: phiRef is readjusted after the extension -- for the case where fRef is below the band covered by ROM, in which case the core function defaults fRef to the max geometric freq of the ROM */\nint SimEOBNRv2HMROMExtTF2(\n ListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */\n int nbmode, /* Number of modes to generate (starting with the 22) */\n double Mf_match, /* Minimum frequency using EOBNRv2HMROM in inverse total mass units*/\n double minf, /* Minimum frequency required */\n int tagexthm, /* Tag to decide whether or not to extend the higher modes as well */\n double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */\n double phiRef, /* Phase at reference frequency */\n double fRef, /* Reference frequency (Hz); 0 defaults to fLow */\n double m1SI, /* Mass of companion 1 (kg) */\n double m2SI, /* Mass of companion 2 (kg) */\n double distance, /* Distance of source (m) */\n int setphiRefatfRef) /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) */\n{//\n //printf(\"calling SimEOBNRv2HMROMExtTF2 with minf=%g\\n\", minf);\n //printf(\"params: %d %g %g %g %g %g %g %g %g\\n\", nbmode, Mf_match, minf, deltatRef, phiRef, fRef, m1SI, m2SI, distance);\n\n\n int ret,i;\n ListmodesCAmpPhaseFrequencySeries* listROM = NULL;\n //int lout=-1,mout=-1;\n int lout=-1,mout=-1;\n\n /* Generate the waveform with the ROM */\n ret = SimEOBNRv2HMROM(&listROM, nbmode, deltatRef, phiRef, fRef, m1SI, m2SI, distance, setphiRefatfRef);\n\n /* If the ROM waveform generation failed (e.g. parameters were out of bounds) return FAILURE */\n //if(ret==FAILURE)printf(\"SimEOBNRv2HMROMExtTF2: Generation of ROM for injection failed!\\n\");\n if(ret==FAILURE) return FAILURE;\n\n /* Main loop over the modes (as linked list) to perform the extension */\n /* The 2-2 mode will be extended by TaylorF2 model with the phase and time offset\n determined by matching conditions. All other modes will be extended as some\n sort of power-law fall-off in amplitude and power-law growth in phase. */\n ListmodesCAmpPhaseFrequencySeries* listelement = listROM;\n while(listelement) { // For each l-m (ie each listelement)\n\n\n /* Definitions: l,m, frequency series and length */\n int l = listelement->l;\n int m = listelement->m;\n\n //NOTE: temporary hack to allow avoiding power-law extension of higher modes which seems problematic\n // if((l==2&&m==2) || tagexthm) {\n\n /* First we must compute a new frequency grid including a possible extension to lower frequencies*/\n gsl_vector *freq_new;\n gsl_vector* freq = listelement->freqseries->freq;\n int len = (int) freq->size;\n // Construct frequency grid extension on the geometric mean of the lowest few ROM frequencies after the matching point\n const int Navg=3;\n int imatch=-1;\n double f_match;\n if(Mf_match<=0) {\n f_match = Mf_ROM_min/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;\n }\n else if(Mf_match>Mf_ROM_min) {\n f_match = Mf_match/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;\n }\n else {\n printf(\"WARNING: Mf_match lower than the lowest geometric frequency of the ROM model - used instead\\n\");\n f_match = Mf_ROM_min/(m1SI+m2SI)*MSUN_SI/MTSUN_SI;\n }\n f_match = f_match*m/2; //Shift the matching frequency for non-22 modes to correspond to a comparable orbital freq.\n //printf(\"f_match=%g\\n\",f_match);\n for(i=0;if_match){\n imatch=i;\n break;\n }\n }\n if(imatch<0){\n printf(\"WARNING: f_match exceeds high-freq range of the ROM model\\n\");\n imatch=len-Navg-1;\n }\n double lnfmatch=log(gsl_vector_get(freq,imatch));\n double lnfmin=log(minf);\n double dlnf=(log(gsl_vector_get(freq,imatch+Navg))-lnfmatch)/Navg;\n double dffac=exp(dlnf);\n //The new grid will include the old grid, from imatch and after, plus adequate lower-freq\n int len_add = (lnfmatch-lnfmin)/dlnf;\n if(len_add<0) len_add=0;\n int len_new = len - imatch + len_add;\n //printf(\"extending waveform: len_add + len - imatch = len_new: %i + %i - %i = %i\\n\",len_add,len,imatch,len_new);\n /* construct the extended freq grid */\n freq_new=gsl_vector_alloc(len_new);\n for(i=len_add;i0;i--)gsl_vector_set(freq_new,i-1,gsl_vector_get(freq_new,i)/dffac);\n //for(i=0;i=len_new-len?freq->data[i-len_new+len]:0),freq_new->data[i]);\n\n\n //copy the old freqseries data to a new one and extend with power-law\n CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n if(l==lout&&m==mout){ //write to file for debugging\n printf(\"Writing waveform-before for (%i,%i)\\n\",l,m);\n FILE *f = fopen(\"waveform-before.dat\", \"w\");\n for(i=0;ifreq->size;i++){\n fprintf(f,\"%i %i %g %g %g %g %i\\n\",l,m,\n gsl_vector_get(freqseries->freq,i),\n gsl_vector_get(freqseries->amp_real,i),\n gsl_vector_get(freqseries->amp_imag,i),\n gsl_vector_get(freqseries->phase,i),\n i);\n }\n fclose(f);\n }\n CAmpPhaseFrequencySeries* freqseries_new=0; //New result will be assembled here\n CAmpPhaseFrequencySeries_Init(&freqseries_new,len_new);\n //set the new freqs\n for(i=0;ifreq,i,gsl_vector_get(freq_new,i));\n }\n //copy in the high-freq ROM-model data\n //printf(\"l,m = %i,%i; lenghts=%i,%i\\n\",l,m,freqseries->freq->size, freqseries_new->freq->size);\n for(i=len_add;iamp_real,i,gsl_vector_get(freqseries->amp_real,len-len_new+i));\n gsl_vector_set(freqseries_new->amp_imag,i,gsl_vector_get(freqseries->amp_imag,len-len_new+i));\n gsl_vector_set(freqseries_new->phase,i,gsl_vector_get(freqseries->phase,len-len_new+i));\n //printf(\"%i: copying %g %g %g %g\\n\",i,freqseries_new->freq->data[i],freqseries_new->amp_real->data[i],freqseries_new->amp_imag->data[i],freqseries_new->phase->data[i]);\n }\n //extend\n if(l==2&&m==2&&len_add>0) {//extend 2-2 with TaylorF2\n //Assemble data for matching\n double f0=freq_new->data[len_add],f1=freq_new->data[len_add+1];\n double ph0=freqseries_new->phase->data[len_add],ph1=freqseries_new->phase->data[len_add+1];\n double amp=sqrt(freqseries_new->amp_real->data[len_add]*freqseries_new->amp_real->data[len_add]\n +freqseries_new->amp_imag->data[len_add]*freqseries_new->amp_imag->data[len_add]);\n double amp1=sqrt(freqseries_new->amp_real->data[len_add+1]*freqseries_new->amp_real->data[len_add+1]\n +freqseries_new->amp_imag->data[len_add+1]*freqseries_new->amp_imag->data[len_add+1]);\n double amprfac=freqseries_new->amp_real->data[len_add]/amp,ampifac=freqseries_new->amp_imag->data[len_add]/amp;\n //Compute raw TaylorF2\n TaylorF2nonspin(freqseries_new->amp_real->data,freqseries_new->phase->data,freq_new->data,len_add+2,m1SI,m2SI,distance,imatch);\n //Compute offsets in phase, first phase derivative, and amplitude argument\n double dphase0tf2=(freqseries_new->phase->data[len_add+1]-freqseries_new->phase->data[len_add])/(f1-f0);\n double phase0tf2=freqseries_new->phase->data[len_add];\n double dphase0eob=(ph1-ph0)/(f1-f0);\n double dphase0=dphase0eob-dphase0tf2;\n double phase0=ph0 - phase0tf2 - f0*dphase0;\n double amp0bcoeff = amp / freqseries_new->amp_real->data[len_add] - 1.0; //Compute correction for continuity matching.\n double amp0ccoeff = ((amp1/freqseries_new->amp_real->data[len_add+1]-1.0)/amp0bcoeff/(f1*f1/f0/f0)-1.0)/(f1/f0-1.0);\n //TESTING\n //printf(\"%g, %g\\n\", amp0bcoeff, amp0ccoeff);\n //Compute correction for continuity matching.\n /*\n printf(\"ph0eob,dph0eob= %g, %g\\n\",ph0,dphase0eob);\n printf(\"ph0tf2,dph0tf2= %g, %g\\n\",phase0tf2,dphase0tf2);\n printf(\"ph0,dph0= %g, %g\\n\",phase0,dphase0);\n printf(\"f0,f0*dph0= %g, %g\\n\",f0,dphase0*f0);\n printf(\"imatch=%i\\n\",imatch);\n */\n //Apply offsets\n for (i = 0; i < len_add+2; i++){\n double f=freqseries_new->freq->data[i];\n //printf(\"%i<%i,%g\\n\",i,len_add,len_add-i);\n //printf(\"f,ph0+f*dph0= %g, %g\\n\",freqseries_new->freq->data[i],phase0 + dphase0*f);\n freqseries_new->phase->data[i] += phase0 + dphase0*f;\n //First apply continuity matching\n // amp -> amp * ( 1 + b*f^2/f0^2 * ( 1 + c*(f/f0 -1) )\n //(starts at order f^2 since we only keep 2PN order ampl corrections in TaylorF2 code below; could change to f^3 if higher order terms are used)\n freqseries_new->amp_real->data[i] *= 1.0 + amp0bcoeff*f*f/f0/f0*(1+amp0ccoeff*(f/f0-1));\n freqseries_new->amp_imag->data[i] = freqseries_new->amp_real->data[i]*ampifac;\n freqseries_new->amp_real->data[i] *= amprfac;\n //printf(\"%i: extending TF2 %g %g %g %g\\n\",i,freqseries_new->freq->data[i],freqseries_new->amp_real->data[i],freqseries_new->amp_imag->data[i],freqseries_new->phase->data[i]);\n }\n } else { //extend other modes with power-law\n //The results are many cycles out of phase almost immediately, so this definitely is not an accurate\n //waveform, but the results are reasonably smooth and of plausible structure.\n //Alternatively, we could also extend these with TaylorF2, btu we are mostly assuming this part of the WF is small\n double phref=freqseries->phase->data[len-1];//For phase we extend by a power-law referenced to zero phase at end of ROM\n for(i=0;ifreqseries->phase->data[i])phref=freqseries->phase->data[i];//get the smallest value of phi to use as ref.\n phref=phref+1.0;//add one more\n double ldArfac = 0;\n if(gsl_vector_get(freqseries->amp_real,imatch)>0) //avoid div0 in trivial cases\n //dArfac=exp(-log( gsl_vector_get(freqseries->amp_real,imatch+Navg)\n //\t\t /gsl_vector_get(freqseries->amp_real,imatch) ) / Navg);\n ldArfac=(log( gsl_vector_get(freqseries->amp_real,imatch+Navg)\n /gsl_vector_get(freqseries->amp_real,imatch) ) /\n log( gsl_vector_get(freqseries->freq,imatch+Navg)\n /gsl_vector_get(freqseries->freq,imatch) ) );\n //double dphfac = exp(-log( (gsl_vector_get(freqseries->phase,imatch+Navg)-phref)\n //\t\t\t/(gsl_vector_get(freqseries->phase,imatch) -phref)) / Navg);\n double ldphfac = (log( (gsl_vector_get(freqseries->phase,imatch+Navg)-phref)\n /(gsl_vector_get(freqseries->phase,imatch) -phref)) /\n log( gsl_vector_get(freqseries->freq,imatch+Navg)\n /gsl_vector_get(freqseries->freq,imatch) ) );\n if(1&&l==lout&&m==mout)printf(\"ldphfac(%i,%i)=%g\\n\",l,m,ldphfac);\n //double f0=gsl_vector_get(freqseries->freq,imatch);\n for(i=len_add;i>0;i--){\n double fratio=gsl_vector_get(freqseries_new->freq,i-1)/gsl_vector_get(freqseries_new->freq,i);\n double dArfac=pow(fratio,ldArfac);\n gsl_vector_set(freqseries_new->amp_real,i-1,gsl_vector_get(freqseries_new->amp_real,i)*dArfac);\n gsl_vector_set(freqseries_new->amp_imag,i-1,gsl_vector_get(freqseries_new->amp_imag,i)*dArfac);\n double dphfac=pow(fratio,ldphfac);\n gsl_vector_set(freqseries_new->phase,i-1,(gsl_vector_get(freqseries_new->phase,i)-phref)*dphfac+phref);\n //printf(\"%i: extending %g %g %g %g\\n\",i,freqseries_new->freq->data[i-1],freqseries_new->amp_real->data[i-1],freqseries_new->amp_imag->data[i-1],freqseries_new->phase->data[i-1]);\n }\n //printf(\"Extended (%i,%i) down to f=%g, ampR=%g, ampI=%g, phase=%g\\n\",l,m,freqseries_new->freq->data[0],freqseries_new->amp_real->data[0],freqseries_new->amp_imag->data[0],freqseries_new->phase->data[0]);\n }\n //delete the old content data and replace with the new\n CAmpPhaseFrequencySeries_Cleanup(freqseries);\n listelement->freqseries=freqseries_new;\n\n //TESTING\n //printf(\"In ext: len freqseries: %d\\n\", freqseries_new->freq->size);\n //for(int i=0; ifreq->size; i++) {\n //printf(\"%g %g %g %g\\n\", gsl_vector_get(freqseries_new->freq, i), gsl_vector_get(freqseries_new->amp_real, i), gsl_vector_get(freqseries_new->amp_imag, i), gsl_vector_get(freqseries_new->phase, i));\n //}\n\n //debugging\n // freqseries=listelement->freqseries;\n // if(1&&l==lout&&m==mout){ //write to file for debugging\n // FILE *f = fopen(\"waveform.dat\", \"w\");\n // for(i=0;ifreq->size;i++){\n // fprintf(f,\"%i %i %g %g %g %g %i\\n\",l,m,\n // \tfreqseries->freq->data[i],\n // \tfreqseries->amp_real->data[i],\n // \tfreqseries->amp_imag->data[i],\n // \tfreqseries->phase->data[i],\n // \ti);\n // }\n // fclose(f);\n // }\n\n gsl_vector_free(freq_new);\n listelement=listelement->next;\n }\n\n /* Compute phase shift to set phiRef at fRef */\n /* Covers the case where input fRef is outside the range of the ROM, in which case the Core function defaulted to Mfmax_ROM */\n /* Not very clean and a bit redundant */\n if (setphiRefatfRef) {\n CAmpPhaseFrequencySeries* h22 = ListmodesCAmpPhaseFrequencySeries_GetMode(listROM, 2, 2)->freqseries;\n gsl_vector* freq22 = h22->freq;\n gsl_vector* phase22 = h22->phase;\n int nbfreq = freq22->size;\n gsl_interp_accel* accel_phi22 = gsl_interp_accel_alloc();\n gsl_spline* spline_phi22 = gsl_spline_alloc(gsl_interp_cspline, nbfreq);\n gsl_spline_init(spline_phi22, gsl_vector_const_ptr(freq22,0), gsl_vector_const_ptr(phase22,0), nbfreq);\n /* If fRef was not set (fRef=0), use the last frequency generated for 22 mode -- as is done internally in Core */\n if (fRef==0.) fRef = freq22->data[freq22->size - 1];\n /* Compute 22 phase at fRef before adjustment, check the extended range */\n if ( (fRefdata[0]) || (fRef>freq22->data[freq22->size - 1]) ) {\n printf(\"Error: fRef is not covered by the frequency range of the waveform after extension.\\n\");\n return FAILURE;\n }\n double phi22atfRef = gsl_spline_eval(spline_phi22, fRef, accel_phi22);\n /* Phase shift, as an orbital or observer phase shift (change in 22 is 2*phaseshift) */\n double phaseshift = (2*phiRef - phi22atfRef)/2.;\n\n /* Propagate phase shift to full list of modes */\n listelement = listROM;\n while(listelement) {\n int l = listelement->l;\n int m = listelement->m;\n\n double phaseshiftlm = m/2. * phaseshift;\n gsl_vector* philm = listelement->freqseries->phase;\n gsl_vector_add_constant(philm, phaseshiftlm);\n\n listelement = listelement->next;\n }\n\n /* Cleanup */\n gsl_spline_free(spline_phi22);\n gsl_interp_accel_free(accel_phi22);\n }\n\n\n /* Output */\n *listhlm = listROM;\n\n /*\n printf(\"generated listROM: n=%i l=%i m=%i\\n\",(*listhlm)->freqseries->amp_real->size,listROM->l,listROM->m);\n for(i=0;i<(*listhlm)->freqseries->freq->size;i++){\n printf(\"%i: %g %g %g %g\\n\",i,(*listhlm)->freqseries->freq->data[i],(*listhlm)->freqseries->amp_real->data[i],(*listhlm)->freqseries->amp_imag->data[i],(*listhlm)->freqseries->phase->data[i]);\n }\n printf(\"listlhm=%x\\n\",listhlm);\n printf(\"*listlhm=%x\\n\",*listhlm);\n */\n return SUCCESS;\n}\n", "meta": {"hexsha": "4a2ccdc80ec653068bfb72b7b9e2868ccebd036d", "size": 48402, "ext": "c", "lang": "C", "max_stars_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c", "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c", "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EOBNRv2HMROM/EOBNRv2HMROM.c", "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 46.8557599226, "max_line_length": 257, "alphanum_fraction": 0.677926532, "num_tokens": 14371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.46579509230563554}} {"text": "#include \"common/c_math/gsl_linalg_extra.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// TODO(kennyjensen): Remove these and allocate arrays in calling\n// library.\n#define MAX_VECTOR_SIZE (32U)\n#define MAX_MATRIX_SIZE (16U * 16U)\n\n// Solves triangular matrix equations of the form:\n//\n// op(T) * X = B or X * op(T) = B\n//\n// using forward or back substitution. For rectangular T\n// (i.e. underdetermined or overdetermined systems), this only solves\n// the square submatrix of T. For underdetermined systems, the\n// remaining elements of X are set to zeros. If the triangular matrix\n// T is singular, then this will only solve the part of the matrix up\n// to the first zero diagonal element.\n//\n// Args:\n// side: Which side of the multiplication op(T) appears.\n// uplo: Whether T is upper or lower triangular.\n// transpose: Whether op(.) is a transpose or not.\n// T: Triangular matrix (m x n).\n// B: Right hand side matrix (m x k).\n// X: Solution matrix (n x k).\n//\n// Returns:\n// GSL_ESING if T is singular and GSL_SUCCESS otherwise.\nint32_t GslTriangularSolve(CBLAS_SIDE_t side, CBLAS_UPLO_t uplo,\n CBLAS_TRANSPOSE_t transpose, const gsl_matrix *T,\n const gsl_matrix *B, gsl_matrix *X) {\n assert(T != NULL && B != NULL && X != NULL);\n assert(T != X && B != X);\n assert(side != CblasLeft ||\n (X->size2 == B->size2 &&\n (transpose == CblasNoTrans ? T->size1 : T->size2) == B->size1 &&\n (transpose == CblasNoTrans ? T->size2 : T->size1) == X->size1));\n assert(side != CblasRight ||\n (X->size1 == B->size1 &&\n (transpose == CblasNoTrans ? T->size1 : T->size2) == X->size2 &&\n (transpose == CblasNoTrans ? T->size2 : T->size1) == B->size2));\n\n int32_t err = GSL_SUCCESS;\n size_t small_dim = (T->size1 < T->size2) ? T->size1 : T->size2;\n\n gsl_matrix_set_zero(X);\n // Calling this \"rank\" here is assuming that the diagonal elements\n // of T are in descending order.\n size_t rank = small_dim;\n for (size_t i = 0U; i < small_dim; ++i) {\n if (fabs(gsl_matrix_get(T, i, i)) <= DBL_EPSILON) {\n rank = i;\n err = GSL_ESING;\n break;\n }\n gsl_vector_const_view row = gsl_matrix_const_row(B, i);\n gsl_matrix_set_row(X, i, &row.vector);\n }\n if (rank == 0U) return err;\n\n // Make a square sub-matrix of T that has all non-zero elements\n // along the diagonal and a reduced B matrix with the same number of\n // rows.\n gsl_matrix_const_view T_rank =\n gsl_matrix_const_submatrix(T, 0U, 0U, rank, rank);\n gsl_matrix_view X_rank = gsl_matrix_submatrix(X, 0U, 0U, rank, X->size2);\n\n // Solve the triangular system op(T) * X = B or X * op(T) = B.\n gsl_blas_dtrsm(side, uplo, transpose, CblasNonUnit, 1.0, &T_rank.matrix,\n &X_rank.matrix);\n return err;\n}\n\n// Converts a trapezoidal matrix R with m < n to a pure upper\n// triangular matrix with zeros outside of the square portion of the\n// matrix using orthogonal transformations from the right:\n//\n// R = [T, 0] * Z\n//\n// Here Z = Z_1 * Z_2 * ... * Z_m with Z_k = I - tau_k * v_k * v_k'\n// where v_k is the Householder vector which cancels the\n// non-triangular elements of the kth row of T. This is similar to\n// the DTZRZF function from LAPACK.\n//\n// Args:\n// R: Right trapezoidal matrix with m < n. This function will\n// happily ignore non-zero components in the lower portion of\n// the R matrix; however these will also appear in the T matrix.\n// T: Upper triangular matrix output (m x n). The \"zero\" portion of\n// the T matrix is used to store the Householder vectors that,\n// with tau, form Z.\n// tau: Vector of length m of Householder coefficients.\nvoid GslTrapezoidalToTriangular(const gsl_matrix *R, gsl_matrix *T,\n gsl_vector *tau) {\n assert(R != NULL && T != NULL && tau != NULL);\n assert(R->size1 == T->size1 && R->size2 == T->size2);\n assert(tau->size == T->size1);\n assert(R->size1 > 0U && R->size1 < R->size2);\n\n if (T != R) gsl_matrix_memcpy(T, R);\n\n size_t i_max = R->size1 - 1U;\n for (size_t k = 0U; k < R->size1; ++k) {\n size_t i = i_max - k;\n\n // hh is used to calculate the Householder vector; however, the\n // Household vector itself is only stored in hh1.\n gsl_vector_view hh = gsl_matrix_subrow(T, i, i_max, R->size2 - i_max);\n gsl_vector_view hh1 =\n gsl_matrix_subrow(T, i, R->size1, R->size2 - R->size1);\n\n // GSL assumes that the elements you want to cancel are adjacent\n // to the diagonal element, which isn't the case here, so we have\n // to swap elements around.\n gsl_vector_view row = gsl_matrix_row(T, i);\n gsl_vector_swap_elements(&row.vector, i, i_max);\n double tau_k = gsl_linalg_householder_transform(&hh.vector);\n gsl_vector_set(tau, k, tau_k);\n gsl_vector_swap_elements(&row.vector, i, i_max);\n\n // Apply Householder reflections to the right hand side of the\n // triangular matrix. We don't apply the reflection to the ith\n // row itself because GSL's Householder transform sets the\n // diagonal element for us. (Doing this with the\n // gsl_linalg_householder_mh function would require swapping\n // columns because of assumptions GSL makes about the diagonal\n // element being adjacent to the elements that the Householder\n // vector cancels.)\n for (size_t j = 0U; j < i; ++j) {\n gsl_vector_view T_jm =\n gsl_matrix_subrow(T, j, R->size1, R->size2 - R->size1);\n double alpha, T_ji = gsl_matrix_get(T, j, i);\n gsl_blas_ddot(&hh1.vector, &T_jm.vector, &alpha);\n alpha += T_ji;\n gsl_blas_daxpy(-tau_k * alpha, &hh1.vector, &T_jm.vector);\n gsl_matrix_set(T, j, i, -tau_k * alpha + T_ji);\n }\n }\n}\n\n// Applies the inverse of the Householder transformations output by\n// GslTrapezoidalToTriangular to the matrix X. More specifically, for\n// the matrix Z defined by:\n//\n// R = [T, 0] * Z\n//\n// this function applies Z' to the input matrix X.\n//\n// Args:\n// T: The R matrix of a QR decomposition after complete\n// orthogonalization. The elements that should be zero from the\n// QR decomposition are ignored. The elements that should be\n// zero from the complete orthogonalization must contain the\n// Householder vectors used in the orthogonalization.\n// tau: The factors to multiply the Householder vectors by which is\n// output by the GslTrapezoidalToTriangular function.\n// X: The input matrix to which we apply Z'.\n// Zt_X: Output matrix with Householder transformations applied Z' * X.\nvoid GslTrapezoidalToTriangularZTMat(const gsl_matrix *T, const gsl_vector *tau,\n const gsl_matrix *X, gsl_matrix *Zt_X) {\n assert(X != NULL && tau != NULL && Zt_X != NULL && T != NULL);\n assert(T != X && T != Zt_X);\n assert(T->size1 == tau->size && T->size2 == X->size1);\n assert(X->size1 == Zt_X->size1 && X->size2 == Zt_X->size2);\n assert(T->size1 <= T->size2);\n\n if (X != Zt_X) gsl_matrix_memcpy(Zt_X, X);\n\n for (size_t i = 0U; i < T->size1; ++i) {\n // Grab the Householder vector from the columns past the square\n // section of the T matrix.\n gsl_vector_const_view hh1 =\n gsl_matrix_const_subrow(T, i, T->size1, T->size2 - T->size1);\n\n // Apply Householder reflections to the left hand side of X.\n // (Doing this with the gsl_linalg_householder_hm function would\n // require swapping rows because of assumptions GSL makes about\n // the diagonal element being adjacent to the elements that the\n // Householder vector cancels.)\n //\n // TODO(kennyjensen): If we need this non-standard\n // gsl_linalg_householder_hm in other places, we should make a\n // helper function.\n double tau_k = gsl_vector_get(tau, T->size1 - i - 1U);\n for (size_t j = 0U; j < Zt_X->size2; ++j) {\n gsl_vector_view Zt_X_mj =\n gsl_matrix_subcolumn(Zt_X, j, T->size1, T->size2 - T->size1);\n double alpha, Zt_X_ij = gsl_matrix_get(Zt_X, i, j);\n gsl_blas_ddot(&hh1.vector, &Zt_X_mj.vector, &alpha);\n alpha += Zt_X_ij;\n gsl_blas_daxpy(-tau_k * alpha, &hh1.vector, &Zt_X_mj.vector);\n gsl_matrix_set(Zt_X, i, j, -tau_k * alpha + Zt_X_ij);\n }\n }\n}\n\n// Left or right matrix divide. Finds a solution, X, to the equations\n// A*X = B or X*A = B for left and right divide respectively. If the\n// system is overdetermined or underdetermined, then this returns a\n// least-squares solution that minimizes |A*X - B| or |X*A - B|,\n// similar to MATLAB's \"\\\" or \"/\" operators. The solution is found\n// using QR decomposition with column pivoting followed by back\n// substitution. For matrix left divide, the solution proceeds as:\n//\n// A*X = B\n// Q*R*P' * X = B\n// R * P'*X = Q'*B\n//\n// For matrix right divide, the solution proceeds as:\n//\n// X*A = B\n// A'*X' = B'\n// Q*R*P' * X' = B'\n// R * (X*P)' = Q'*B'\n//\n// Args:\n// side: CblasLeft or CblasRight for left or right divide.\n// A: Left hand side matrix.\n// B: Right hand side matrix.\n// X: Solution matrix.\n//\n// Returns:\n// GSL_ESING A is rank deficient and thus the R matrix is singular and\n// GSL_SUCCESS otherwise.\nint32_t GslMatrixDivide(CBLAS_SIDE_t side, const gsl_matrix *A,\n const gsl_matrix *B, gsl_matrix *X) {\n assert(A != NULL && B != NULL && X != NULL);\n assert(A != X && B != X);\n assert(side != CblasLeft || (A->size1 == B->size1 && A->size2 == X->size1 &&\n X->size2 == B->size2));\n assert(side != CblasRight || (A->size2 == B->size2 && A->size1 == X->size2 &&\n X->size1 == B->size1));\n assert(A->size1 <= MAX_VECTOR_SIZE && A->size2 <= MAX_VECTOR_SIZE);\n assert(A->size1 * A->size2 <= MAX_MATRIX_SIZE);\n assert(B->size1 * B->size2 <= MAX_MATRIX_SIZE);\n assert(X->size1 * X->size2 <= MAX_MATRIX_SIZE);\n\n int32_t err = GSL_SUCCESS;\n size_t m = (side == CblasLeft) ? A->size1 : A->size2;\n size_t n = (side == CblasLeft) ? A->size2 : A->size1;\n size_t k = (side == CblasLeft) ? B->size2 : B->size1;\n\n // Allocate workspace variables.\n double workspace[MAX_MATRIX_SIZE];\n double qr_data[MAX_MATRIX_SIZE];\n double tau_data[MAX_VECTOR_SIZE];\n size_t perm_data[MAX_VECTOR_SIZE];\n int signum;\n\n // Decompose op(A) into Q*R*P'.\n gsl_matrix_view QR = gsl_matrix_view_array(qr_data, m, n);\n gsl_vector_view tau = gsl_vector_view_array(tau_data, m < n ? m : n);\n gsl_permutation p = {n, perm_data};\n gsl_vector_view norm = gsl_vector_view_array(workspace, n);\n if (side == CblasLeft) {\n gsl_matrix_memcpy(&QR.matrix, A);\n } else {\n gsl_matrix_transpose_memcpy(&QR.matrix, A);\n }\n gsl_linalg_QRPT_decomp(&QR.matrix, &tau.vector, &p, &signum, &norm.vector);\n\n // Calculate Q'*op(B) matrix.\n gsl_matrix_view Qt_opB = gsl_matrix_view_array(workspace, m, k);\n if (side == CblasLeft) {\n gsl_matrix_memcpy(&Qt_opB.matrix, B);\n } else {\n gsl_matrix_transpose_memcpy(&Qt_opB.matrix, B);\n }\n gsl_linalg_QR_QTmat(&QR.matrix, &tau.vector, &Qt_opB.matrix);\n\n // Determine the rank of the R matrix.\n //\n // TODO(tobenkin): DGELSY uses a different iterative condition\n // number estimation technique to determine the rank of the\n // submatrix R(1:rank, 1:rank). See http://www.netlib.org/lapack/\n // lapack-3.1.1/html/dgelsy.f.html#DGEQP3.269.\n double R_00 = fabs(gsl_matrix_get(&QR.matrix, 0U, 0U));\n uint32_t rank = 0U;\n if (R_00 > DBL_EPSILON) {\n for (rank = 1U; rank < m && rank < n; ++rank) {\n if (fabs(gsl_matrix_get(&QR.matrix, rank, rank)) < 1e-9 * R_00) {\n err = GSL_ESING;\n break;\n }\n }\n } else {\n gsl_matrix_set_zero(X);\n return GSL_ESING;\n }\n\n // Solve the triangular system R * Z * P' * op(X) = Q' * op(B) and\n // multiply the solution by Z' to get P' * op(X).\n gsl_matrix_view Z_Pt_opX = gsl_matrix_view_array(X->data, n, k);\n gsl_matrix_set_zero(&Z_Pt_opX.matrix);\n\n // For underdetermined or rank deficient matrices, use complete\n // orthogonalization to provide the minimal 2-norm solution.\n gsl_vector_view tau_trap = gsl_vector_view_array(tau_data, rank);\n gsl_matrix_view QR_trap = gsl_matrix_submatrix(&QR.matrix, 0U, 0U, rank, n);\n if (rank < n) {\n GslTrapezoidalToTriangular(&QR_trap.matrix, &QR_trap.matrix,\n &tau_trap.vector);\n }\n\n // Solve the non-singular square triangular system.\n gsl_matrix_const_view QR_rank =\n gsl_matrix_const_submatrix(&QR.matrix, 0U, 0U, rank, rank);\n gsl_matrix_const_view Qt_opB_rank =\n gsl_matrix_const_submatrix(&Qt_opB.matrix, 0U, 0U, rank, k);\n gsl_matrix_view Z_Pt_opX_rank =\n gsl_matrix_submatrix(&Z_Pt_opX.matrix, 0U, 0U, rank, k);\n gsl_matrix_memcpy(&Z_Pt_opX_rank.matrix, &Qt_opB_rank.matrix);\n gsl_blas_dtrsm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0,\n &QR_rank.matrix, &Z_Pt_opX_rank.matrix);\n\n // For full-rank square and overdetermined matrices, Z = I.\n if (rank < n) {\n GslTrapezoidalToTriangularZTMat(&QR_trap.matrix, &tau_trap.vector,\n &Z_Pt_opX.matrix, &Z_Pt_opX.matrix);\n }\n\n // Apply the permutation matrix to get op(X).\n for (uint32_t i = 0U; i < k; ++i) {\n gsl_vector_view col = gsl_matrix_column(&Z_Pt_opX.matrix, i);\n gsl_permute_vector_inverse(&p, &col.vector);\n }\n\n if (side == CblasRight) {\n // We can't transpose within the same memory, hence the\n // unfortunate extra memcpy.\n gsl_matrix_view X_copy = gsl_matrix_view_array(qr_data, k, n);\n gsl_matrix_transpose_memcpy(&X_copy.matrix, &Z_Pt_opX.matrix);\n gsl_matrix_memcpy(X, &X_copy.matrix);\n }\n\n return err;\n}\n", "meta": {"hexsha": "f7a64ccc627d6129cd8f8535b38cdeb58cd705c0", "size": 13889, "ext": "c", "lang": "C", "max_stars_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c", "max_stars_repo_name": "OpenFAST/KiteFAST", "max_stars_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T18:21:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:13:27.000Z", "max_issues_repo_path": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c", "max_issues_repo_name": "OpenFAST/KiteFAST", "max_issues_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7", "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": "modules/kitefast-controller/src/common/c_math/gsl_linalg_extra.c", "max_forks_repo_name": "OpenFAST/KiteFAST", "max_forks_repo_head_hexsha": "a7329f7c454aab102fadd77771b741a923abd0a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-13T11:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-20T21:04:46.000Z", "avg_line_length": 39.4573863636, "max_line_length": 80, "alphanum_fraction": 0.6534667723, "num_tokens": 4108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.46564843066688394}} {"text": "/* integration/qagp.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\nstatic int\nqagp (const gsl_function *f,\n const double *pts, const size_t npts,\n const double epsabs, const double epsrel, const size_t limit,\n gsl_integration_workspace * workspace,\n double *result, double *abserr,\n gsl_integration_rule * q);\n\n#include \"initialise.c\"\n#include \"qpsrt.c\"\n#include \"util.c\"\n#include \"append.c\"\n#include \"reset.c\"\n#include \"qelg.c\"\n#include \"qpsrt2.c\"\n#include \"ptsort.c\"\n#include \"positivity.c\"\n\nint\ngsl_integration_qagp (const gsl_function *f,\n double * pts, size_t npts,\n double epsabs, double epsrel, size_t limit,\n gsl_integration_workspace * workspace,\n double * result, double * abserr)\n{\n int status = qagp (f, pts, npts, \n epsabs, epsrel, limit,\n workspace,\n result, abserr,\n &gsl_integration_qk21) ;\n \n return status ;\n}\n\n\nstatic int\nqagp (const gsl_function * f,\n const double *pts, const size_t npts,\n const double epsabs, const double epsrel, \n const size_t limit,\n gsl_integration_workspace * workspace,\n double *result, double *abserr,\n gsl_integration_rule * q)\n{\n double area, errsum;\n double res_ext, err_ext;\n double result0, abserr0, resabs0;\n double tolerance;\n\n double ertest = 0;\n double error_over_large_intervals = 0;\n double reseps = 0, abseps = 0, correc = 0;\n size_t ktmin = 0;\n int roundoff_type1 = 0, roundoff_type2 = 0, roundoff_type3 = 0;\n int error_type = 0, error_type2 = 0;\n\n size_t iteration = 0;\n\n int positive_integrand = 0;\n int extrapolate = 0;\n int disallow_extrapolation = 0;\n\n struct extrapolation_table table;\n\n const size_t nint = npts - 1; /* number of intervals */\n\n size_t *ndin = workspace->level; /* temporarily alias ndin to level */\n\n size_t i;\n\n /* Initialize results */\n\n *result = 0;\n *abserr = 0;\n\n /* Test on validity of parameters */\n\n if (limit > workspace->limit)\n {\n GSL_ERROR (\"iteration limit exceeds available workspace\", GSL_EINVAL) ;\n }\n\n if (npts > workspace->limit)\n {\n GSL_ERROR (\"npts exceeds size of workspace\", GSL_EINVAL);\n }\n\n if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))\n {\n GSL_ERROR (\"tolerance cannot be acheived with given epsabs and epsrel\",\n GSL_EBADTOL);\n }\n\n /* Check that the integration range and break points are an\n ascending sequence */\n\n for (i = 0; i < nint; i++)\n {\n if (pts[i + 1] < pts[i])\n {\n GSL_ERROR (\"points are not in an ascending sequence\", GSL_EINVAL);\n }\n }\n\n /* Perform the first integration */\n\n result0 = 0;\n abserr0 = 0;\n resabs0 = 0;\n\n initialise (workspace, 0.0, 0.0) ;\n\n for (i = 0; i < nint; i++)\n {\n double area1, error1, resabs1, resasc1;\n const double a1 = pts[i];\n const double b1 = pts[i + 1];\n\n q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);\n\n result0 = result0 + area1;\n abserr0 = abserr0 + error1;\n resabs0 = resabs0 + resabs1;\n\n append_interval (workspace, a1, b1, area1, error1);\n\n if (error1 == resasc1 && error1 != 0.0)\n {\n ndin[i] = 1;\n }\n else\n {\n ndin[i] = 0;\n }\n }\n\n /* Compute the initial error estimate */\n\n errsum = 0.0;\n\n for (i = 0; i < nint; i++)\n {\n if (ndin[i])\n {\n workspace->elist[i] = abserr0;\n }\n\n errsum = errsum + workspace->elist[i];\n\n }\n\n for (i = 0; i < nint; i++)\n {\n workspace->level[i] = 0;\n }\n\n /* Sort results into order of decreasing error via the indirection\n array order[] */\n\n sort_results (workspace);\n\n /* Test on accuracy */\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));\n\n if (abserr0 <= 100 * GSL_DBL_EPSILON * resabs0 && abserr0 > tolerance)\n {\n *result = result0;\n *abserr = abserr0;\n\n GSL_ERROR (\"cannot reach tolerance because of roundoff error\"\n \"on first attempt\", GSL_EROUND);\n }\n else if (abserr0 <= tolerance)\n {\n *result = result0;\n *abserr = abserr0;\n\n return GSL_SUCCESS;\n }\n else if (limit == 1)\n {\n *result = result0;\n *abserr = abserr0;\n\n GSL_ERROR (\"a maximum of one iteration was insufficient\", GSL_EMAXITER);\n }\n\n /* Initialization */\n\n initialise_table (&table);\n append_table (&table, result0);\n\n area = result0;\n\n res_ext = result0;\n err_ext = GSL_DBL_MAX;\n\n error_over_large_intervals = errsum;\n ertest = tolerance;\n\n positive_integrand = test_positivity (result0, resabs0);\n\n iteration = nint - 1; \n\n do\n {\n size_t current_level;\n double a1, b1, a2, b2;\n double a_i, b_i, r_i, e_i;\n double area1 = 0, area2 = 0, area12 = 0;\n double error1 = 0, error2 = 0, error12 = 0;\n double resasc1, resasc2;\n double resabs1, resabs2;\n double last_e_i;\n\n /* Bisect the subinterval with the largest error estimate */\n\n retrieve (workspace, &a_i, &b_i, &r_i, &e_i);\n\n current_level = workspace->level[workspace->i] + 1;\n\n a1 = a_i;\n b1 = 0.5 * (a_i + b_i);\n a2 = b1;\n b2 = b_i;\n\n iteration++;\n\n q (f, a1, b1, &area1, &error1, &resabs1, &resasc1);\n q (f, a2, b2, &area2, &error2, &resabs2, &resasc2);\n\n area12 = area1 + area2;\n error12 = error1 + error2;\n last_e_i = e_i;\n\n /* Improve previous approximations to the integral and test for\n accuracy.\n\n We write these expressions in the same way as the original\n QUADPACK code so that the rounding errors are the same, which\n makes testing easier. */\n\n errsum = errsum + error12 - e_i;\n area = area + area12 - r_i;\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));\n\n if (resasc1 != error1 && resasc2 != error2)\n {\n double delta = r_i - area12;\n\n if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)\n {\n if (!extrapolate)\n {\n roundoff_type1++;\n }\n else\n {\n roundoff_type2++;\n }\n }\n\n if (i > 10 && error12 > e_i)\n {\n roundoff_type3++;\n }\n }\n\n /* Test for roundoff and eventually set error flag */\n\n if (roundoff_type1 + roundoff_type2 >= 10 || roundoff_type3 >= 20)\n {\n error_type = 2; /* round off error */\n }\n\n if (roundoff_type2 >= 5)\n {\n error_type2 = 1;\n }\n\n /* set error flag in the case of bad integrand behaviour at\n a point of the integration range */\n\n if (subinterval_too_small (a1, a2, b2))\n {\n error_type = 4;\n }\n\n /* append the newly-created intervals to the list */\n\n update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);\n\n if (errsum <= tolerance)\n {\n goto compute_result;\n }\n\n if (error_type)\n {\n break;\n }\n\n if (iteration >= limit - 1)\n {\n error_type = 1;\n break;\n }\n\n if (disallow_extrapolation)\n {\n continue;\n }\n\n error_over_large_intervals += -last_e_i;\n\n if (current_level < workspace->maximum_level)\n {\n error_over_large_intervals += error12;\n }\n\n if (!extrapolate)\n {\n /* test whether the interval to be bisected next is the\n smallest interval. */\n if (large_interval (workspace))\n continue;\n\n extrapolate = 1;\n workspace->nrmax = 1;\n }\n\n /* The smallest interval has the largest error. Before\n bisecting decrease the sum of the errors over the larger\n intervals (error_over_large_intervals) and perform\n extrapolation. */\n\n if (!error_type2 && error_over_large_intervals > ertest)\n {\n if (increase_nrmax (workspace))\n continue;\n }\n\n /* Perform extrapolation */\n\n append_table (&table, area);\n\n if (table.n < 3) \n {\n goto skip_extrapolation;\n } \n\n qelg (&table, &reseps, &abseps);\n\n ktmin++;\n\n if (ktmin > 5 && err_ext < 0.001 * errsum)\n {\n error_type = 5;\n }\n\n if (abseps < err_ext)\n {\n ktmin = 0;\n err_ext = abseps;\n res_ext = reseps;\n correc = error_over_large_intervals;\n ertest = GSL_MAX_DBL (epsabs, epsrel * fabs (reseps));\n if (err_ext <= ertest)\n break;\n }\n\n /* Prepare bisection of the smallest interval. */\n\n if (table.n == 1)\n {\n disallow_extrapolation = 1;\n }\n\n if (error_type == 5)\n {\n break;\n }\n\n skip_extrapolation:\n\n reset_nrmax (workspace);\n extrapolate = 0;\n error_over_large_intervals = errsum;\n\n }\n while (iteration < limit);\n\n *result = res_ext;\n *abserr = err_ext;\n\n if (err_ext == GSL_DBL_MAX)\n goto compute_result;\n\n if (error_type || error_type2)\n {\n if (error_type2)\n {\n err_ext += correc;\n }\n\n if (error_type == 0)\n error_type = 3;\n\n if (result != 0 && area != 0)\n {\n if (err_ext / fabs (res_ext) > errsum / fabs (area))\n goto compute_result;\n }\n else if (err_ext > errsum)\n {\n goto compute_result;\n }\n else if (area == 0.0)\n {\n goto return_error;\n }\n }\n\n /* Test on divergence. */\n\n {\n double max_area = GSL_MAX_DBL (fabs (res_ext), fabs (area));\n\n if (!positive_integrand && max_area < 0.01 * resabs0)\n goto return_error;\n }\n\n {\n double ratio = res_ext / area;\n\n if (ratio < 0.01 || ratio > 100 || errsum > fabs (area))\n error_type = 6;\n }\n\n goto return_error;\n\ncompute_result:\n\n *result = sum_results (workspace);\n *abserr = errsum;\n\nreturn_error:\n\n if (error_type > 2)\n error_type--;\n\n if (error_type == 0)\n {\n return GSL_SUCCESS;\n }\n else if (error_type == 1)\n {\n GSL_ERROR (\"number of iterations was insufficient\", GSL_EMAXITER);\n }\n else if (error_type == 2)\n {\n GSL_ERROR (\"cannot reach tolerance because of roundoff error\",\n GSL_EROUND);\n }\n else if (error_type == 3)\n {\n GSL_ERROR (\"bad integrand behavior found in the integration interval\",\n GSL_ESING);\n }\n else if (error_type == 4)\n {\n GSL_ERROR (\"roundoff error detected in the extrapolation table\",\n GSL_EROUND);\n }\n else if (error_type == 5)\n {\n GSL_ERROR (\"integral is divergent, or slowly convergent\",\n GSL_EDIVERGE);\n }\n else\n {\n GSL_ERROR (\"could not integrate function\", GSL_EFAILED);\n }\n}\n", "meta": {"hexsha": "fc8e039ff4330491e104a10adeb19f83bffaf6d5", "size": 11824, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/integration/qagp.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/integration/qagp.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/integration/qagp.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.1389432485, "max_line_length": 81, "alphanum_fraction": 0.5627537212, "num_tokens": 3221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4655041747457189}} {"text": "/*\n * resampling.c\n *\n * Created on: 5.5.2017\n * Author: heine\n */\n#define _XOPEN_SOURCE 600\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \"ziggurat.h\"\n\nconst gsl_rng_type *T; // Generator type\nconst gsl_rng *rgen; // Generator\n\nvoid set_resamplingseed( int id ) {\n\n struct timespec spec;\n\n clock_gettime( CLOCK_REALTIME, &spec );\n \n gsl_rng_env_setup();\n T = gsl_rng_default;\n rgen = gsl_rng_alloc( T );\n\n gsl_rng_set( rgen, ( unsigned long int ) ( round( spec.tv_nsec / 1.0e6 ) + 223 * id ) );\n\n}\n\ndouble depth_first_sum(double *x, long len) {\n \n long n = len;\n double *x_tmp, out;\n x_tmp = malloc(sizeof(double) * len);\n for (long i = 0; i < len; i++)\n x_tmp[i] = x[i];\n \n while (n > 1) {\n for (long i = 0; i < n / 2; i++) {\n x_tmp[i] = x_tmp[2 * i] + x_tmp[2 * i + 1];\n }\n if (n % 2 != 0) {\n x_tmp[n / 2] = x_tmp[n - 1];\n }\n n = n / 2 + n % 2;\n }\n out = x_tmp[0];\n free(x_tmp);\n return out;\n}\n\ndouble *depth_first_cumsum(double *x, long len) {\n \n double *W;\n W = malloc(sizeof(double) * len);\n\n for (long i = 0; i < len; i++) {\n W[i] = depth_first_sum(x, i);\n }\n return W;\n}\n\ndouble *exclusive_prefix_sum(double *w, long len) {\n double *W;\n W = malloc(sizeof(double) * len);\n \n W[0] = 0;\n for (long i = 1; i < len; i++) {\n W[i] = W[i - 1] + w[i - 1];\n }\n \n return W;\n}\n\ndouble *combining_exclusive_prefix_sum(double *w, double *w_recv, long n) {\n \n double *W;\n W = malloc(sizeof(double) * 2 * n);\n \n W[0] = 0;\n \n for (long i = 1; i <= n; i++) {\n W[i] = W[i - 1] + w[i - 1];\n }\n \n for (long i = 0; i < n-1; i++) {\n W[n + i + 1] = W[n + i] + w_recv[i];\n }\n \n return W;\n}\n\n\ndouble serial_multinomial_resample(long n, double *w, double *w_recv, long *inds) {\n \n double *W;\n double total_weight, lnmax = 0, u;\n long j = 2 * n - 1;\n \n W = combining_exclusive_prefix_sum(w, w_recv, n);\n \n total_weight = log(W[2 * n - 1] + w_recv[n - 1]);\n \n for (long i = n; i >= 1; i--) {\n\n u = gsl_rng_uniform_pos( rgen );\n\n lnmax = lnmax + log(u) / (double) i;\n\n u = exp(total_weight + lnmax);\n\n while (u < W[j])\n j--;\n\n inds[i - 1] = j;\n }\n\n free(W);\n\n return exp(total_weight);\n}\n\ndouble serial_multinomial_resample_sng(long n, double *w, long *inds) {\n \n double *W;\n double total_weight, lnmax = 0, u;\n long j = n - 1;\n \n W = exclusive_prefix_sum(w, n);\n \n total_weight = log(W[n - 1] + w[n - 1]);\n \n for (long i = n; i >= 1; i--) {\n\n u = gsl_rng_uniform_pos( rgen ); \n\n lnmax = lnmax + log(u) / (double) i;\n\n u = exp(total_weight + lnmax);\n\n while (u < W[j])\n j--;\n\n inds[i - 1] = j;\n }\n\n free(W);\n\n return exp(total_weight);\n}\n\ndouble serial_multinomial_resample_sng_noutk(long n, double *w, long *inds, long k) {\n \n double *W;\n double total_weight, lnmax = 0, u;\n long j = k - 1;\n \n W = exclusive_prefix_sum(w, k);\n \n total_weight = log( W[ k - 1 ] + w[ k - 1 ] );\n \n for (long i = n; i >= 1; i--) {\n\n u = gsl_rng_uniform_pos( rgen ); \n\n lnmax = lnmax + log(u) / (double) i;\n\n u = exp(total_weight + lnmax);\n\n while (u < W[j])\n j--;\n\n inds[i - 1] = j;\n }\n\n free(W);\n\n return exp(total_weight);\n}\n\ndouble serial_multinomial_resample_noutk(long n, double *w, double* W, long *inds, long k) {\n \n double total_weight, lnmax = 0, u;\n long j = k - 1;\n \n total_weight = log(W[k - 1] + w[k - 1]);\n \n for (long i = n; i >= 1; i--) {\n\n u = gsl_rng_uniform_pos( rgen ); \n\n lnmax = lnmax + log(u) / (double) i;\n\n u = exp(total_weight + lnmax);\n\n while (u < W[j])\n j--;\n\n inds[i - 1] = j;\n }\n \n return -1;\n}\n\nvoid binary_resampler(long n, double w, long *counts) {\n\n counts[0] = 0;\n counts[1] = 0;\n\n for ( long i = 0; i < n; i++ ) \n counts[ gsl_rng_uniform_pos( rgen ) < w ? 0 : 1 ]++;\n\n}\n\nvoid \nsimplified_resample(\n\t\t long n, \n\t\t long *inds,\n\t\t long k) \n{\n\n for ( long i = 0; i < n; i++ ) \n inds[ i ] = ( long ) ( gsl_rng_uniform_int( rgen, ( unsigned long int ) k ) ); \n}\n\nvoid serial_multinomial_resample_counts(long n, long k, double *w, long *cnts) {\n \n double *W;\n double total_weight, lnmax = 0, u;\n long j = k - 1;\n \n for( long i = 0; i < k ; i++ ) \n cnts[ i ] = 0;\n\n W = exclusive_prefix_sum(w, k);\n \n total_weight = log(W[k - 1] + w[k - 1]);\n \n for (long i = n; i >= 1; i--) {\n\n u = gsl_rng_uniform_pos( rgen );\n\n lnmax = lnmax + log(u) / (double) i;\n\n u = exp(total_weight + lnmax);\n\n while (u < W[j])\n j--;\n\n cnts[j]++;\n }\n\n free(W);\n \n}\n", "meta": {"hexsha": "d0936bb9e49cf82656e8027f43482c9075a16b20", "size": 4642, "ext": "c", "lang": "C", "max_stars_repo_path": "src/resampling.c", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "src/resampling.c", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/resampling.c", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7175572519, "max_line_length": 92, "alphanum_fraction": 0.5364067212, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.46533066657191635}} {"text": "#ifndef ALM_KATYUSHA_H\r\n#define ALM_KATYUSHA_H\r\n\r\n#include \"Primal_Dual_LOOPLESS_Katyusha0.h\"\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include /* printf */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n//#include \"cmd_line.h\"\r\n\r\n\r\n//This class implements the method IPALM_Katyusha\r\n\r\n/*\r\nThe optimization problem to solve is:\r\n\r\nmin \\sum_i f^i(A_ix)+ \\sum_i h^i(M_ix)+ P(x) \r\nAssumption 1: For each i, f_i is 1-smooth, P(x) is seperable\r\n// Each subproblem solves problem of the form \\sum_i f^i(A_ix)+ \\sum_i h^i_{\\beta_s}(M_ix;\\lambda_s^i) +P(x)+ \\beta_s/2\\|x-x_s\\|^2 by L_Katyuhsa\r\n*/\r\n\r\ntemplate\r\nclass ALM_Katyusha: public Primal_Dual_LOOPLESS_Katyusha0\r\n{\r\nprivate:\r\n\r\n std::vector Ax_s;\r\n std::vector old_Ax_s;\r\n \r\n std::vector Mx_s;\r\n std::vector old_Mx_s;\r\n\r\nprotected:\r\n Matrix\tdata_A;\r\n\t\r\n Matrix data_M;\r\n\r\n std::vector x_s;\r\n\r\n std::vector old_x_s;\r\n\r\n std::vector lambda_s;\r\n\r\n std::vector old_lambda_s;\r\n\r\n\r\n D beta_s;\r\n\r\n D epsilon_s;\r\n\r\n D m_s;\r\n\r\n D m_0;\r\n\r\n L m_1;\r\n\r\n L m_2;\r\n \r\n L m_3;\r\n\r\n D eta;\r\n\r\n D rho;\r\n\r\n D tau_s;\r\n\r\n std::vector L_phi;\r\n\r\n D function_value;\r\n\r\n L print_every_N_ALM;\r\n\r\n D running_time_ALM;\r\n\r\n L nb_outer_iters;\r\n\r\n ofstream samp_ALM;\r\n\r\n ofstream samp_x_ALM;\r\n\r\npublic:\r\n\r\n D mu_g;\r\n \r\n D lambda1;\r\n \r\n D lambda2;\r\n \r\n D L_h;\r\n\r\n \r\n virtual inline D value_of_f_j(D, L){return D(NULL);}\r\n virtual inline D value_of_h_j(D, L){return D(NULL);}\r\n virtual inline D gradient_of_f_j(D, L){return D(NULL);}\r\n virtual inline D value_of_f_star_j(D, L){return D(NULL);}\r\n virtual inline D value_of_h_star_j(D, L){return D(NULL);}\r\n virtual inline D prox_of_h_star_j(D,D, L){return D(NULL);}\r\n virtual inline D value_of_P_j(D, L){return D(NULL);}\r\n virtual inline D prox_of_P_j(D, D, L){return D(NULL);}\r\n virtual inline D feasible_dual(vector &){return D(NULL);}\r\n virtual inline void compute_just_in_time_prox_grad_without_x_s(D, D, D &, L,L, D, D &, L){}\r\n virtual inline void rescale(){}\r\n virtual inline void set_matrix_M(){}\r\n virtual inline void set_matrix_A(){}\r\n\r\n ALM_Katyusha()\r\n : Primal_Dual_LOOPLESS_Katyusha0(),data_A(),data_M()\r\n {\r\n \tthis->gamma= 1;\r\n }\r\n\r\n ALM_Katyusha(const char* matrix_file, const char* vector_file)\r\n : Primal_Dual_LOOPLESS_Katyusha0(matrix_file, vector_file),data_A(), data_M()\r\n {\r\n this->gamma=1;\r\n }\r\n\r\n ALM_Katyusha(const char* matrix_file)\r\n : Primal_Dual_LOOPLESS_Katyusha0(matrix_file),data_A(), data_M()\r\n {\r\n this->gamma=1;\r\n }\r\n/*\r\n ALM_Katyusha(const char* matrix_file, const char* matrix_file2)\r\n : Primal_Dual_LOOPLESS_Katyusha0(),data_A(matrix_file), data_M(matrix_file2)\r\n {\r\n \tthis->matrix_merge(data_A,data_M);\r\n this->gamma=1;\r\n }\r\n */ \r\n inline void set_L_phi(){\r\n \tfor(int i=m_3; insamples;\r\n\t }\r\n \tfor(int i= 0; insamples/beta_s;\r\n\t}\r\n }\r\n\r\n L get_nb_features(){\r\n return data_A.get_d();\r\n }\r\n\r\n inline D value_of_phi_i(D x, L i) {\r\n if ( i>= data_M.nsamples){\r\n return value_of_f_j(x, i- data_M.nsamples);\r\n }\r\n else{\r\n D tmp= prox_of_h_star_j(1.0/beta_s*x+ lambda_s[i],beta_s,i);\r\n return beta_s*(x*tmp- value_of_h_star_j(tmp,i)- beta_s/2*(tmp- lambda_s[i])*(tmp- lambda_s[i]));\r\n }\r\n }\r\n\r\n\r\n\r\n inline D gradient_of_phi_i(D x, L i){\r\n if (i>= data_M.nsamples){\r\n return gradient_of_f_j(x,i- data_M.nsamples);\r\n }\r\n else{\r\n D tmp= prox_of_h_star_j(1.0/beta_s*x+ lambda_s[i],beta_s,i);\r\n return beta_s*tmp;\r\n }\r\n\r\n }\r\n\r\n\r\n inline D value_of_phistar_i(D x, L i) {\r\n if ( i>= data_M.nsamples){\r\n return value_of_f_star_j(x,i- data_M.nsamples);\r\n }\r\n else{\r\n return beta_s*value_of_h_star_j(x/beta_s,i)+ 0.5*(x- beta_s*lambda_s[i])*(x- beta_s*lambda_s[i]);\r\n }\r\n }\r\n\r\n inline D value_of_g_j(D x, L j){\r\n \treturn value_of_P_j(x,j)+ beta_s/2*(x- x_s[j])*(x- x_s[j]);\r\n }\r\n \r\n inline D value_of_gstar(vector &x){\r\n \tD res= 0;\r\n \tL l= x.size();\r\n \tD tmp= 0;\r\n \tfor (L i= 0; i< l; i++){\r\n \t\ttmp= prox_of_P_j(1.0/beta_s*x[i]+ x_s[i],beta_s,i);\r\n res+= x[i]*tmp- value_of_P_j(tmp,i)- beta_s/2*(tmp- x_s[i])*(tmp- x_s[i]);\r\n\t }\r\n \treturn res;\r\n }\r\n \r\n inline D gradient_of_gstar_j(D x, L j){\r\n \treturn prox_of_P_j(1.0/beta_s*x+ x_s[j],beta_s,j);\r\n } \r\n\r\n inline D value_of_gstar_minus(vector &x, D scal){\r\n \tL l= x.size();\r\n \tvector tmp(l,0);\r\n \tfor (L j= 0;j< l; j++){\r\n \t\ttmp[j]= -scal*x[j];\r\n\t }\r\n \treturn value_of_gstar(tmp);\r\n } \r\n /* inline D get_lambda1(){return lambda1;}\r\n inline D get_lambda2(){return lambda2;}\r\n*/\r\n\r\n void compute_x(){\r\n for (L i=0; i< this->nfeatures; i++){\r\n x_s[i]= this->primal_x[i];\r\n }\r\n for (L j=m_3; j< m_2+ m_3; j++){\r\n Ax_s[j- m_3]= compute_AiTx_s(j);\r\n }\r\n for (L j=0; j< m_3; j++){\r\n Mx_s[j]= compute_AiTx_s(j);\r\n\t}\r\n }\r\n\r\n D compute_AiTx_s(L i){\r\n D res=0;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n res+= this->A[k]*x_s[j];\r\n }\r\n return res;\r\n }\r\n \r\n inline void compute_just_in_time_prox_grad(D tau, D u, D &x, L t0,L t1, D w, D &y, L j){\r\n D u_s=u-tau_s*beta_s*x_s[j];\r\n compute_just_in_time_prox_grad_without_x_s(tau, u_s, x, t0, t1, w, y,j);\r\n }\r\n\r\n void compute_function_value(){\r\n D res= 0;\r\n for (L i= 0; i< this->nfeatures; i++){\r\n res+= value_of_P_j(x_s[i],i);\r\n }\r\n for (L i= 0; i< data_M.nsamples; i++){\r\n res+= value_of_h_j(Mx_s[i],i);\r\n }\r\n for (L i= 0; insamples; j++){\r\n if (1- Ax_s[j]> tmp1){\r\n tmp1= 1- Ax_s[j];\r\n}\r\ntmp2+= max(0.0,1- Ax_s[j]);\r\n}\r\nresidual1= tmp1;\r\nresidual2= tmp2/this->nsamples;\r\n}*/\r\n\r\n\r\n\r\ninline void compute_m0(D beta0, D val_eta, D val_rho, L val_tau){\r\n cout<<\"beta0=\"<nsamples/val_tau*1e+6;\r\n\r\n //D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0));\r\n //cout<<\"tmp7: \"<n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))< & x0,vector & y0){\r\n cout<<\"start initializing\"<tau=val_tau;\r\n m_1=data_A.get_d();\r\n m_2=data_A.get_n();\r\n m_3=data_M.get_n();\r\n cout<<\"m_1=\"<nsamples;\r\n tau_s= 1;\r\n\r\n epsilon_s=epsilon_0;\r\n compute_m0(beta_s,val_eta,val_rho,val_tau);\r\n\r\n eta=val_eta;\r\n rho=val_rho;\r\n\r\n x_s.resize(m_1,0);\r\n old_x_s.resize(m_1,0);\r\n lambda_s.resize(m_3,0);\r\n old_lambda_s.resize(m_3,0);\r\n for(L i=0;insamples/beta_0;\r\n }\r\n for(int i=m_3; i< m_2+ m_3; i++){\r\n \tL_phi[i]= this->nsamples;\r\n }\r\n}\r\n\r\nvoid reset_everything(){\r\n epsilon_s*=rho;\r\n beta_s*=eta;\r\n\r\n}\r\n\r\nvoid update_m_s(L val_tau){\r\n D tmp= 0;\r\n D tmpx= 0;\r\n D tmpy= 0;\r\n D tmpy2= 0;\r\n for(L j=0;jsumLi);\r\n m_s= ceil((tmp1- tmp2)/log(2)*4*max(1.0*this->nsamples,1/tmp3)/val_tau);\r\n}\r\n\r\ninline void compute_and_record_res(){\r\n if(nb_outer_iters%print_every_N_ALM==0){\r\n compute_function_value();\r\n cout< & x0,vector & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, string filename1, string filename2, D time){\r\n Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0);\r\n nb_outer_iters=0;\r\n //string sampname2= ALGparam.data_dir +\"/results/L_Katyusha_\"+filename2;\r\n string sampname2= \"results/L_Katyusha_\"+filename2;\r\n this->samp.open(sampname2.c_str());\r\n string sampname_x=\"results/L_Katyusha_x_\"+filename1;\r\n //filename1= ALGparam.data_dir +\"/results/ALM_\"+filename1;\r\n filename1= \"results/ALM_\"+filename1;\r\n samp_x_ALM.open(sampname_x.c_str());\r\n samp_ALM.open(filename1.c_str());\r\n running_time_ALM=0;\r\n print_every_N_ALM=p_N_1;\r\n this->set_print_every_N(p_N_2);\r\n compute_and_record_res();\r\n D start;\r\n start = std::clock();\r\n //cout<<\"m0=\"<n*val_tau)<nsamples*val_tau)<<\"; beta_s=\"<L_Katyusga_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1);\r\n rescale();\r\n set_L_phi();\r\n this->loopless_Katyusha(y0, x_s, filename2, L_phi, mu_g+ tau_s*beta_s, epsilon_s, ceil(m_s/this->nsamples*val_tau), val_tau, 1, 1, 0, 1);\r\n for(L i=0;insamples*val_tau)<<\"; beta_s=\"<loopless_Katyusha(y0, x_s, filename2, L_phi, mu_g+ tau_s*beta_s, epsilon_s, ceil(m_s/this->nsamples*val_tau), val_tau, 1, 1, 0, 1);\r\n for(L i=0;i time){\r\n break;\r\n }\r\n }\r\n for (L i= 0; i< m_1; i++){\r\n \tsamp_x_ALM<< x_s[i]<< endl;\r\n }\r\n}\r\n};\r\n\r\n#endif /* MIN_SMOOTH_CONVEX_H */\r\n", "meta": {"hexsha": "ea4eaad848493fd836b91095cdb94b68909bfe1e", "size": 12008, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM/ALM_Katyusha.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM/ALM_Katyusha.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM/ALM_Katyusha.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 26.0477223427, "max_line_length": 189, "alphanum_fraction": 0.6068454364, "num_tokens": 4191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46433904715250884}} {"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include \"Data/Data.h\"\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"eigen.h\"\n\nnamespace mage\n{\n using Quaternion = Eigen::Quaternionf;\n\n inline Quaternion ToQuat(const cv::Matx33f& rotation)\n {\n Eigen::Matrix3f eigenMat;\n cv::cv2eigen(rotation, eigenMat);\n\n Quaternion eigenQuat(eigenMat);\n // TODO validate if this normalize is even necessary, eigen might already be doing this\n eigenQuat.normalize();\n\n return eigenQuat;\n }\n\n template\n inline Eigen::Map> ToMap(cv::Vec& vec)\n {\n return Eigen::Map{ vec.val };\n }\n\n template\n inline Eigen::Map> ToCMap(const cv::Vec& vec)\n {\n return Eigen::Map>{ vec.val };\n }\n\n inline Eigen::Map ToMap(cv::Matx31f& vec)\n {\n return Eigen::Map{ vec.val };\n }\n\n inline Eigen::Map ToCMap(const cv::Matx31f& vec)\n {\n return Eigen::Map{ vec.val };\n }\n\n inline Eigen::Map ToMap(cv::Point3f& vec)\n {\n return Eigen::Map{ &vec.x };\n }\n\n inline Eigen::Map ToCMap(const cv::Point3f& vec)\n {\n return Eigen::Map{ &vec.x };\n }\n\n inline Eigen::Map ToMap(cv::Point2f& vec)\n {\n return Eigen::Map{ &vec.x };\n }\n\n inline Eigen::Map ToCMap(const cv::Point2f& vec)\n {\n return Eigen::Map{ &vec.x };\n }\n\n template\n inline cv::Vec ToVec(gsl::span values)\n {\n return cv::Vec(values.data());\n }\n\n inline Quaternion QuatFromTwoVectors(const cv::Vec3f& from, const cv::Vec3f& to)\n {\n Quaternion quat;\n quat.setFromTwoVectors(Eigen::Vector3f{ from(0), from(1), from(2) }, Eigen::Vector3f{ to(0), to(1), to(2) });\n return quat;\n }\n\n inline cv::Matx33f ToMat(const Quaternion& quat)\n {\n cv::Matx33f mat;\n cv::eigen2cv(quat.toRotationMatrix(), mat);\n return mat;\n }\n\n inline cv::Matx33f ToMat(float pitchRads, float rollRads, float yawRads)\n {\n // Formula for (Pitch * Roll * Yaw) from http://www.songho.ca/opengl/gl_anglestoaxes.html\n float a = pitchRads;\n float b = yawRads;\n float c = rollRads;\n\n float sa = sinf(a);\n float sb = sinf(b);\n float sc = sinf(c);\n\n float ca = cosf(a);\n float cb = cosf(b);\n float cc = cosf(c);\n\n return cv::Matx33f{\n cc * cb, -sc, cc * sb,\n ca * sc * cb + sa * sb, ca * cc, ca * sc * sb - sa * cb,\n sa * sc * cb - ca * sb, sa * cc, sa * sc * sb + ca * cb\n };\n }\n\n inline cv::Matx44f To4x4(const cv::Matx34f& mat)\n {\n return{\n mat(0, 0), mat(0, 1), mat(0, 2), mat(0, 3),\n mat(1, 0), mat(1, 1), mat(1, 2), mat(1, 3),\n mat(2, 0), mat(2, 1), mat(2, 2), mat(2, 3),\n 0, 0, 0, 1\n };\n }\n\n inline cv::Matx34f To3x4(const cv::Matx44f& mat)\n {\n return{\n mat(0, 0), mat(0, 1), mat(0, 2), mat(0, 3),\n mat(1, 0), mat(1, 1), mat(1, 2), mat(1, 3),\n mat(2, 0), mat(2, 1), mat(2, 2), mat(2, 3)\n };\n }\n\n inline cv::Matx44f To4x4(const cv::Matx33f& rot, const cv::Vec3f& trans)\n {\n return{\n rot(0, 0), rot(0, 1), rot(0, 2), trans(0),\n rot(1, 0), rot(1, 1), rot(1, 2), trans(1),\n rot(2, 0), rot(2, 1), rot(2, 2), trans(2),\n 0, 0, 0, 1\n };\n }\n\n inline cv::Matx44f FromQuatAndTrans(const Quaternion& quat, const cv::Vec3f& trans)\n {\n return To4x4(ToMat(quat), trans);\n }\n\n inline cv::Matx33f Rotation(const cv::Matx44f& mat)\n {\n return{\n mat(0, 0), mat(0, 1), mat(0, 2),\n mat(1, 0), mat(1, 1), mat(1, 2),\n mat(2, 0), mat(2, 1), mat(2, 2)\n };\n }\n\n inline cv::Matx33f Rotation(const cv::Matx34f& mat)\n {\n return{\n mat(0, 0), mat(0, 1), mat(0, 2),\n mat(1, 0), mat(1, 1), mat(1, 2),\n mat(2, 0), mat(2, 1), mat(2, 2)\n };\n }\n\n inline cv::Vec3f Translation(const cv::Matx44f& mat)\n {\n return{\n mat(0, 3),\n mat(1, 3),\n mat(2, 3)\n };\n }\n\n inline cv::Vec3f Translation(const cv::Matx34f& mat)\n {\n return{\n mat(0, 3),\n mat(1, 3),\n mat(2, 3)\n };\n }\n\t//Swap the returned parameters to suppress x64 compile warning c4324\n\t//c:\\program files(x86)\\microsoft visual studio\\2017\\enterprise\\vc\\tools\\msvc\\14.11.25503\\include\\utility(271) : warning C4324 : 'std::pair' : structure was padded due to alignment specifier\n inline std::pair Decompose(const cv::Matx44f& matrix)\n {\n return std::make_pair(Translation(matrix), ToQuat(matrix.get_minor<3, 3>(0, 0)));\n }\n\n template\n inline bool MatxEqual(const cv::Matx& mat0, const cv::Matx& mat1)\n {\n for (int i = 0; i < ROWS; i++)\n {\n for (int j = 0; j < COLS; j++)\n {\n if (mat0(i,j) != mat1(i,j))\n return false;\n }\n }\n\n return true;\n }\n\n inline bool MatEqual(const cv::Mat& mat0, const cv::Mat& mat1)\n {\n if (mat0.size != mat1.size)\n return false;\n\n for (int i = 0; i < mat0.rows; i++)\n {\n for (int j = 0; j < mat0.cols; j++)\n {\n if (mat0.at(i, j) != mat1.at(i, j))\n return false;\n }\n }\n\n return true;\n }\n\n template\n inline cv::Matx44f Invert(const cv::Matx& transform)\n {\n static_assert((ROWS == 3 || ROWS == 4) && COLS == 4, \"Invert only supports 3x4 or 4x4 matrices\");\n\n //invert rotation by transpose on copy of upper 3x3 for inverse rotation \n cv::Matx44f invRotation{\n transform(0, 0), transform(1, 0), transform(2, 0), 0,\n transform(0, 1), transform(1, 1), transform(2, 1), 0,\n transform(0, 2), transform(1, 2), transform(2, 2), 0,\n 0, 0, 0, 1\n };\n\n#ifndef NDEBUG\n // this approach would only work if the upper 3x3 was a pure rotation matrix (no scale)\n // that would mean all rows and columns were unit length and orthogonal. this tests for the former.\n for(int idx=0; idx < 3; idx++)\n { \n assert(abs(1.0 - cv::norm(invRotation.col(idx))) <= 0.001 && \"Expecting unit length (no scale) for rotation matrix\");\n assert(abs(1.0 - cv::norm(invRotation.row(idx))) <= 0.001 && \"Expecting unit length (no scale) for rotation matrix\");\n }\n\n //a valid rotation matrix has determinant 1 (a mirror would be -1)\n assert(abs(1.0 - cv::determinant(invRotation)) < 0.001 && \"Expecting determinant of 1 for rotation matrix\");\n#endif\n\n\n //invert translation by negation on copy\n cv::Matx44f invTranslation{\n 1, 0, 0, -transform(0, 3),\n 0, 1, 0, -transform(1, 3),\n 0, 0, 1, -transform(2, 3),\n 0, 0, 0, 1\n };\n\n //inverse matrix\n return invRotation * invTranslation;\n }\n\n inline cv::Matx44f ComputeFrameTransform(const cv::Matx44f& from, const cv::Matx44f& to)\n {\n return to * Invert(from);\n }\n\n inline cv::Point3f UnProject(const cv::Matx33f& invCameraMatrix, const cv::Matx44f& viewMatrix, const cv::Point2i& point, float depth)\n {\n cv::Matx31f pixelSpace{ static_cast(point.x), static_cast(point.y), 1.f };\n cv::Matx31f cameraSpace = invCameraMatrix * pixelSpace;\n cameraSpace *= depth;\n\n cv::Matx41f world = Invert(viewMatrix) * cv::Matx41f{ cameraSpace(0), cameraSpace(1), cameraSpace(2), 1 };\n return{ world(0), world(1), world(2) };\n }\n\n const float NRM_EPSILON = 0.00001f;\n\n inline float Length(const cv::Vec3f& vec)\n {\n return std::sqrtf(vec.dot(vec));\n }\n\n inline cv::Vec3f Normalize(const cv::Vec3f& vec)\n { \n float distance = Length(vec);\n if (distance == 0)\n return vec;\n\n cv::Vec3f normVec = (vec / distance);\n assert(abs(sqrt(normVec.dot(normVec)) - 1.0f) < NRM_EPSILON);\n return normVec;\n }\n\n //rightHanded, column vec convention, intended for rotation of vectors (active)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames\n inline cv::Matx44f RotationXForVectors(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, cosR, -sinR, 0.0f,\n 0.0f, sinR, cosR, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n }\n\n //rightHanded, column vec convention, intended for rotation of vectors (active)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames\n inline cv::Matx44f RotationYForVectors(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ cosR, 0.0f, sinR, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n -sinR, 0.0f, cosR, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n }\n\n //rightHanded, column vec convention, intended for rotation of vectors (active)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //vs http://mathworld.wolfram.com/RotationMatrix.html intended for rotation of coordinate frames\n inline cv::Matx44f RotationZForVectors(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ cosR, -sinR, 0.0f, 0.0f,\n sinR, cosR, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n \n }\n\n //rightHanded, column vec convention, intended for rotation of coordinate frames (passive)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //ala http://mathworld.wolfram.com/RotationMatrix.html \n inline cv::Matx44f RotationXForCoordinateFrames(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, cosR, sinR, 0.0f,\n 0.0f, -sinR, cosR, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n }\n\n //rightHanded, column vec convention,intended for rotation of coordinate frames (passive)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //ala http://mathworld.wolfram.com/RotationMatrix.html \n inline cv::Matx44f RotationYForCoordinateFrames(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ cosR, 0.0f, -sinR, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n sinR, 0.0f, cosR, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n }\n\n //rightHanded, column vec convention, intended for rotation of coordinate frames (passive)\n //https://en.wikipedia.org/wiki/Rotation_matrix\n //ala http://mathworld.wolfram.com/RotationMatrix.html \n inline cv::Matx44f RotationZForCoordinateFrames(float radians)\n {\n float cosR = std::cosf(radians);\n float sinR = std::sinf(radians);\n\n return{ cosR, sinR, 0.0f, 0.0f,\n -sinR, cosR, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n }\n\n // encoding of axis/angle in a vec3f\n // http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#rodrigues\n inline cv::Matx33f RotationFromRodrigues(const cv::Matx31f& rotation)\n {\n cv::Matx33f rotationMat;\n cv::Rodrigues(rotation, rotationMat);\n return rotationMat;\n }\n\n template\n inline std::array ArrayFromMat(const cv::Matx& mat)\n {\n std::array out;\n std::copy(std::begin(mat.val), std::end(mat.val), out.begin());\n return out;\n }\n\n inline cv::Matx44f ToCVMat4x4(const mage::Matrix& matrix)\n {\n return cv::Matx44f(&matrix.M11);\n }\n\n inline bool IsEntirelyOffscreen(const cv::Rect& rect, const cv::Size& screenResPixels)\n {\n assert(rect.width > 0 && \"invalid rect\");\n assert(rect.height > 0 && \"invalid rect\");\n assert(screenResPixels.width > 0 && \"invalid screenResPixels\");\n assert(screenResPixels.height > 0 && \"invalid screenResPixels\");\n\n int maxHorizPixel = rect.width + rect.x - 1;\n int maxVerticalPixel = rect.height + rect.y - 1;\n\n bool offscreenX = (maxHorizPixel < 0) || (rect.x >(int)(screenResPixels.width - 1));\n bool offscreenY = (maxVerticalPixel < 0) || (rect.y >(int)(screenResPixels.height - 1));\n\n return (offscreenX || offscreenY);\n }\n\n inline bool IsWithinArea(const cv::Point2f& pt, const cv::Rect& crop)\n {\n assert(crop.width > 0 && \"width must be positive nonzero\");\n assert(crop.height > 0 && \"height must be positive nonzero\");\n\n return (pt.x >= crop.x && pt.x < (crop.x+crop.width)) && (pt.y >= crop.y && pt.y <= (crop.y + crop.height));\n }\n\n inline cv::Rect ToCVRect(const mage::Rect& rect)\n {\n return { (int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height };\n }\n\n cv::Mat CreateGrayCVMat(const cv::Size& resolution, const PixelFormat& format, const gsl::span imageBytes);\n cv::Mat CreateBGRCVMat(const cv::Mat& source, const PixelFormat& format);\n}\n", "meta": {"hexsha": "87a6e1fee57ac7cd4e58dc31223a9beeb9661f26", "size": 14414, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/Utils/cv.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Utils/cv.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Utils/cv.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 32.9839816934, "max_line_length": 219, "alphanum_fraction": 0.5634105731, "num_tokens": 4529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.46385791031266116}} {"text": "//This does CELL (~soma) stage of minimal GRU (gated recurrent unit) model.\n//This requires each neuron to have 2 input time series, X and Xf,\n//where X is the usual input and Xf the input for the forget-gate.\n//Both X and Xf are the output of a linear IN stage (weights and baises).\n\n//For dim=0: F[:,t] = sig(Xf[:,t] + Uf*Y[:,t-1])\n// H[:,t] = F[:,t].*Y[:,t-1]\n// Y[:,t] = H[:,t] + (1-F[:,t]).*tanh(X[:,t] + U*H[:,t])\n//\n//For dim=1: F[t,:] = sig(Xf[t,:] + Y[t-1,:]*Uf)\n// H[t,:] = F[t,:].*Y[t-1,:]\n// Y[t,:] = H[t,:] + (1-F[t,:]).*tanh(X[t,:] + H[t,:]*U)\n//\n//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),\n//F is the forget gate signal, H is an intermediate vector,\n//U and Uf are NxN update matrices, and Y is the output.\n\n//Note that, the neurons of a layer are independent only if U and Uf are diagonal matrices.\n//This is only really a CELL (~soma) stage in that case.\n\n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint gru_min2_s (float *Y, const float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru_min2_d (double *Y, const double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\nint gru_min2_inplace_s (float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru_min2_inplace_d (double *X, const double *Xf, const double *U, const double *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint gru_min2_s (float *Y, const float *X, const float *Xf, const float *U, const float *Uf, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n size_t nT, tN;\n\n float *F, *H;\n if (!(F=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru_min2_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru_min2_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n\n if (N==1u)\n {\n F[0] = 1.0f / (1.0f+expf(-Xf[0]));\n Y[0] = (1.0f-F[0]) * tanhf(X[0]);\n for (size_t t=1; t\n#include \n#include \n#include \n#include \n#include \n#include \n\n/* number of data points to fit */\n#define N 6\n\n/* number of fit coefficients */\n#define NCOEFFS 6\n\n\n/* Spline order */\n#define K 3\n\n/* nbreak = ncoeffs + 2 - k */\n#define NBREAK (NCOEFFS + 2 - K)\n\n\nvoid gsl_solve( gsl_matrix *A, const size_t n,\n double xmax, double xmin,\n double *B )\n{\n\n printf(\"\\n *** Solve with GSL *** \\n\");\n gsl_vector *d; d = gsl_vector_alloc(n);\n gsl_vector *e; e = gsl_vector_alloc(n-1);\n gsl_vector *f; f = gsl_vector_alloc(n-1);\n gsl_vector *b; b = gsl_vector_alloc(n);\n gsl_vector *x; x = gsl_vector_alloc(n);\n\n for (int i = 0; i < n; i++) \n { \n gsl_vector_set(d, i, gsl_matrix_get(A,i,i));\n if (i>0) \n gsl_vector_set(f, i-1, gsl_matrix_get(A,i,i-1));\n if (i0) \n gsl_vector_set(f, i-1, gsl_matrix_get(A,i,i-1));\n if (i=0;j--)\n u[j] -= gam[j+1]*u[j+1]; \n\n free(gam);\n\n}\n\nvoid cyclic(double a[], \n double b[], \n double c[], \n double alpha, \n double beta, \n double r[], \n double x[], int n)\n\n{\n double fact,gamma;\n double *bb;\n double *u;\n double *z;\n \n if (n <= 2) printf(\"n too small in cyclic\"); \n bb = (double *) malloc(n*sizeof(double));\n u = (double *) malloc(n*sizeof(double));\n z = (double *) malloc(n*sizeof(double));\n \n gamma = -b[0]; \n bb[0] = b[0]-gamma; \n bb[n-1] = b[n-1]-alpha*beta/gamma; \n\n for (int i=1;i0) a[i] = gsl_matrix_get (A, i, i-1);\n b[i] = gsl_matrix_get (A, i, i);\n if (iknots, i);\n\n gsl_vector_set(tau, i, taui);\n\n /* compute B_j(xi) for all j */\n gsl_bspline_eval(taui, B, bw);\n\n printf(\"%f %f\\n\", taui, ti);\n\n /* fill in row i of X */\n for (j = 0; j < ncoeffs; ++j)\n {\n double Bj = gsl_vector_get(B, j);\n gsl_matrix_set(A, i, j, Bj);\n }\n\n }\n\n for (int i = 0; i < n; i++) \n { for (int j = 0; j < n; j++)\n {\n printf (\"%6.3f\", gsl_matrix_get (A, i, j));\n }\n printf(\"\\n\");\n }\n\n for (int i=0; i\n#include \n#include \"types.h\"\n#include \"cuda.h\"\n\n__host__ __device__ void angle_ab(const double dir1[3], const double vel[3], double dir2[3]);\n__host__ __device__ double doppler(const double dir1[3], const double vel[3]);\n__host__ __device__ void scatter_dir(const double dir_in[3], double cos_theta, double dir_out[3]);\n__host__ __device__ void get_rand_isotropic_unitvec(double vecout[3]);\n__host__ __device__ void move_pkt(PKT *pkt_ptr, double distance, const double time);\n\n\n__host__ __device__\ninline double vec_len(const double x[3])\n// return the the magnitude of a vector\n{\n #ifdef __CUDA_ARCH__\n return sqrt((x[0] * x[0]) + (x[1] * x[1]) + (x[2] * x[2]));\n #else\n return cblas_dnrm2(3, x, 1);\n #endif\n}\n\n\n__host__ __device__\ninline void vec_norm(const double vec_in[3], double vec_out[3])\n// Routine for normalizing a vector.\n{\n const double magnitude = vec_len(vec_in);\n\n vec_out[0] = vec_in[0] / magnitude;\n vec_out[1] = vec_in[1] / magnitude;\n vec_out[2] = vec_in[2] / magnitude;\n\n // vec_copy(vec_out, vec_in);\n // cblas_dscal(3, 1 / magnitude, vec_out, 1)\n}\n\n\n__host__ __device__\ninline double dot(const double x[3], const double y[3])\n// Routine for taking dot product.\n{\n #ifdef __CUDA_ARCH__\n return (x[0] * y[0]) + (x[1] * y[1]) + (x[2] * y[2]);\n #else\n return cblas_ddot(3, x, 1, y, 1);\n #endif\n}\n\n\n__host__ __device__\ninline void get_velocity(const double x[3], double y[3], const double t)\n// Routine for getting velocity vector of the flow at a position with homologous expansion.\n{\n y[0] = x[0] / t;\n y[1] = x[1] / t;\n y[2] = x[2] / t;\n}\n\n\n__host__ __device__\ninline void cross_prod(const double vec1[3], const double vec2[3], double vecout[3])\n{\n vecout[0] = (vec1[1] * vec2[2]) - (vec2[1] * vec1[2]);\n vecout[1] = (vec1[2] * vec2[0]) - (vec2[2] * vec1[0]);\n vecout[2] = (vec1[0] * vec2[1]) - (vec2[0] * vec1[1]);\n}\n\n\n__host__ __device__\ninline void vec_scale(double vec[3], const double scalefactor)\n{\n #ifdef __CUDA_ARCH__\n for (int d = 0; d < 3; d++)\n {\n vec[d] *= scalefactor;\n }\n #else\n cblas_dscal(3, scalefactor, vec, 1);\n #endif\n}\n\n\n__host__ __device__\ninline void vec_copy(double destination[3], const double source[3])\n{\n #ifdef __CUDA_ARCH__\n for (int d = 0; d < 3; d++)\n {\n destination[d] = source[d];\n }\n #else\n cblas_dcopy(3, source, 1, destination, 1);\n #endif\n}\n\n\n__host__ __device__\ninline double doppler_packetpos(const PKT *const pkt_ptr)\n{\n double vel_vec[3];\n get_velocity(pkt_ptr->pos, vel_vec, pkt_ptr->prop_time); // homologous flow velocity\n const double dopplerfactor = doppler(pkt_ptr->dir, vel_vec);\n return dopplerfactor;\n}\n\n#endif //VECTORS_H\n", "meta": {"hexsha": "77931a367071071204d5f2a55bad88864cb0df4d", "size": 2740, "ext": "h", "lang": "C", "max_stars_repo_path": "vectors.h", "max_stars_repo_name": "artis-mcrt/artis", "max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z", "max_issues_repo_path": "vectors.h", "max_issues_repo_name": "artis-mcrt/artis", "max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z", "max_forks_repo_path": "vectors.h", "max_forks_repo_name": "artis-mcrt/artis", "max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4642857143, "max_line_length": 98, "alphanum_fraction": 0.6737226277, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4632509407419115}} {"text": "//Include guard\n#ifndef MISC_H\n#define MISC_H\n\n\n//Forward declared dependencies\n\n//Included dependencies\n#include \n#include \n#include \n#include \n#include \"sequence.h\"\n#include \"diploidSequence.h\"\n#include \"modelMR.hpp\"\n#include \"model.hpp\"\n#include \"simParamPH.h\"\n#include \"anaParam.h\"\n#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\nvoid rescale(std::vector &vec);\nvoid rescaleZeroAccepted(std::vector &vec);\nvoid rescaleMin(std::vector &vec, double min);\nvoid printDoubleVector(std:: vector &vec);\nstd::string printDoubleVectorToString(std:: vector &vec);\nvoid printIntVector(std:: vector &vec);\nstd::string printIntVectorToString(std:: vector &vec);\nstd::vector multinomialSampling(int N, std::vector p, const gsl_rng *r);\nint sumOfVector(std::vector intVec);\ndouble sumOfVector(std::vector doubleVec);\nstd::vector subtractVectorsDouble(std::vector &a, std::vector &b);\nstd::vector addVectorsDouble(std::vector &a, std::vector &b);\ndouble my_gsl_linalg_LU_det (gsl_matrix * LU, int signum);\ndouble determinant(gsl_matrix *A);\ndouble logMultivariateNormalPDF(std::vector &x, std::vector &mu, gsl_matrix *sigma);\ndouble logMultivariateNormalPDFPrint(std::vector &x, std::vector &mu, gsl_matrix *sigma);\nvoid printMatrix(gsl_matrix *A);\nvoid printMatrixMathematica(gsl_matrix *A);\nstd::string printMatrixMathematicaToString(gsl_matrix* A);\nSequence randomSequence(int length, gsl_rng *r);\nstd::vector generateRandomFullHaplotypes(int length, int number, gsl_rng *r);\nstd::vector generateMajorMinorFullHaplotypes(int length, int number, gsl_rng *r);\nbool identicalSeqs(Sequence & a, Sequence & b);\nbool identicalIntVectors(std::vector & a, std::vector & b);\nbool nonZeroIntVector(std::vector & a);\nbool nonZeroDoubleVector(std::vector & a);\n\nvoid setupRNG(gsl_rng *r, unsigned long int seed);\n\nDiploidSequence generateRandomDiploidSequence(int length, gsl_rng *r);\nDiploidSequence generateRandomSemiConstrainedDiploidSequence(Sequence constraint, gsl_rng *r);\nDiploidSequence generateRandomSemiConstrainedDiploidSequence(DiploidSequence constraint, gsl_rng *r);\nstd::vector generateFullHapsFromAlleles(DiploidSequence &fullHapAlleles);\n\n\nvoid randomiseSequenceVector(std::vector & s, gsl_rng *r);\n\nstd::vector pickRandomInts(gsl_rng *r, int max, int length);\n\nvoid addRandom(std::vector& oldVec, std::vector& newVec, double delta, gsl_rng *r);\nvoid addRandomMin(std::vector& oldVec, std::vector& newVec, double delta, gsl_rng *r, double min);\nvoid addRandom(std::vector& vec, double delta, gsl_rng *r);\ndouble logMultinomialProb(std::vector &freq, std::vector & obs);\nvoid findLogFactorial(std::vector & fact_store, int N);\ndouble logDirMultProbC(double C, std::vector &obs, std::vector &inf, std::vector &fact_store);\ndouble logDirMultProb(std::vector& alpha, std::vector &x, int& n);\ndouble logBetaBinProb(double alpha, double beta, int x, int n);\ndouble BetaBinCDF(double alpha, double beta, double threshold, int n);\n\nbool fileExists(std::string &fileName);\nstd::vector DirMultSampling(int N, std::vector & freqs, double C, const gsl_rng *r);\n\n//Mean, no var\ndouble computeLSelection(std::vector &obsB, std::vector &obsA, int Nt, AnaParam* ap, std::vector &qBfhFreqs, std::vector &hapFit, std::vector >* contribs, bool print);\ndouble computeLNeutral(std::vector& obsB, std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, std::vector >* contribs, bool print);\n\n//Mean and var\ndouble computeLSelTVar(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitT, std::vector >* contribs, bool print);\ndouble computeLSelTVarOld(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitT, std::vector >* contribs, bool print);\ndouble computeLSelTSelGVar(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitT, std::vector &hapFitG, std::vector >* contribs, bool print);\ndouble computeLSelTSelGVarOld(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitT, std::vector &hapFitG, std::vector >* contribs, bool print);\ndouble computeLNeutralVar(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector >* contribs, bool print);\ndouble computeLNeutralVarAdvanced(std::vector& obsA, int& deltaDays, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector >* contribs, bool print);\ndouble computeLNeutralVarReduced(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector >* contribs, bool print);\ndouble computeLNeutralSelGVar(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitG, std::vector >* contribs, bool print);\ndouble computeLNeutralSelGVarOld(std::vector& obsA, int Nt, AnaParam* ap, std::vector& qBfhFreqs, gsl_matrix* var, std::vector& hapFitG, std::vector >* contribs, bool print);\n\n\nvoid constructMatrixM(std::vector x, gsl_matrix *M);\nvoid constructMatrixMoriginal(std::vector x, gsl_matrix *M);\n\nstd::vector computeHapFit(std::vector &fullHaps, Sequence &selModel, std::vector &selCoefsNew);\nstd::vector computeSimulationHapFitT(std::vector &fullHaps, SimParamPH *spPH);\nstd::vector computeSimulationHapFitG(std::vector &fullHaps, SimParamPH *spPH);\n\nstd::vector createOneLocusCollapsed(std::vector > &oneLocusModels);\n\nstd::vector generateModelsFromPreviousBest(std::vector &collapsedFullHaps, Model &bestModelBefore); \nstd::vector generateModelsFromPreviousBest(std::vector &collapsedFullHaps, ModelMR &bestModelBefore); \n\nint binomialCoeff(int n, int k);\nint logBinCoeffStirling(int n, int k);\n\nint getNextLeft(std::vector alreadyPicked, int max);\nstd::vector findRemainingSeqs(std::vector subset, std::vector set);\n\nDiploidSequence constructDiploidFromFullHap(std::vector &fhs, std::vector &freqs);\nDiploidSequence constructDiploidFromFullHap(std::vector &fhs);\nbool noEntryTheSameExceptZero(std::vector &v);\n\nstd::vector > getAllCombs(int N, int k);\n\nstd::vector > getLinkedPairs(std::vector &haps);\n\nstd::vector split(const std::string& s, char delim);\n\n//Related to gaining information on memory usage\nint parseLine(char* line);\nint getValue();\n\nbool stringToBool(std::string& s);\nbool compareBySize(const std::vector& a, const std::vector& b);\n\n//gamma and delta functions for compound solutions\ndouble gamma_n(int n, double lambda, int Nt);\ndouble delta_n(int n, double lambda, int Nt);\ndouble qPochhammer(double a, double q, int n);\n\n#endif\n", "meta": {"hexsha": "f95b27ae1e899f6494ff11c7c772e00ec7a6d9e0", "size": 7625, "ext": "h", "lang": "C", "max_stars_repo_path": "Codes/Codes_for_xStar/misc.h", "max_stars_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_stars_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "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": "Codes/Codes_for_xStar/misc.h", "max_issues_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_issues_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "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": "Codes/Codes_for_xStar/misc.h", "max_forks_repo_name": "CasperLumby/Bottleneck_Size_Estimation", "max_forks_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:25:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-12T13:25:36.000Z", "avg_line_length": 57.7651515152, "max_line_length": 239, "alphanum_fraction": 0.7628852459, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4630600043588331}} {"text": "/*\n *\n * ML fitting of dots using a 2D Gaussian model provided by gaussianInt2.\n * I.e., only x and y are fitted.\n *\n * Compilation:\n * For debugging:\n * gcc 3.c -Wall -std=c99 -I/usr/local/include -L/usr/local/lib -lgsl -lgslcblas -lm -g -o 3 \n * valgrind ./3\n * For speed:\n * gcc -Wall -std=c99 3.c -I/usr/local/include -L/usr/local/lib -lgsl -lgslcblas -lm -O3 -o 3\n * ./3\n * Memory accesses can also be checked with Valgrind or the gcc -fmudflap memory protection option. \n *\n * MATLAB interface in df_mlfit1.c\n * 2017.04.12. Valgrind ok.\n *\n * TODO: \n * - What are good step sizes?\n * - Set the initial positions with higher than integer precision if possible.\n * \n */\n\n\n/*\n From the GSL documentation:\n\n If necessary you can turn off range checking completely without\n modifying any source files by recompiling your program with the\n preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler\n supports inline functions the effect of turning off range checking is\n to replace calls to gsl_vector_get(v,i) by v->data[i*v->stride] and\n calls to gsl_vector_set(v,i,x) by v->data[i*v->stride]=x. Thus there\n should be no performance penalty for using the range checking\n functions when range checking is turned off. \n\n*/\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"gaussianInt2.h\"\n#include \"mlfit.h\"\n#include \"blit3.h\"\n#include \"mlfit1.h\"\n\n// use the compile flag -D verbose=0 etc\n// 0 = no information\n// 1 = per dot information\n// 2 = per iteration information\n#ifndef verbose\n#define verbose 1\n#endif\n\n// Globals\nconst size_t maxIterations = 10000; // for z-fitting\nconst double convCriteria = 1e-7; // for z-fitting\n\n// Possibly, add the window size, denoted Ws in most places\n\n// Headers\ndouble lxy (const gsl_vector *, void *);\ndouble lz (const gsl_vector *, void *);\nint localizeDotXY(double *, size_t, double *, double *, \n double); // sigma\nint localizeDotZ(double *, size_t, double *, double *, \n double); // sigma\nint localize(double *, size_t, size_t, size_t, double *, size_t, double *, \n double, double); // sigma_xy, sigma_z -- size of dot\nint unit_tests(void);\n\nvoid lxy_df (const gsl_vector *v, void *params, gsl_vector * df);\nvoid lxy_fdf (const gsl_vector *v, void *params, double * f, gsl_vector *df);\n\n// Optimization constants\ntypedef struct {\n double * R; // local region\n double * G; // A already allocated temporary space for the Gaussian kernel\n size_t Rw; // R and G has size Rw*Rw\n double sigma; // For constant sigma fitting\n double bg;\n} optParams;\n\n\ndouble lz (const gsl_vector *v, void *params)\n{\n double x;\n\n optParams *p = (optParams *) params;\n\n size_t Rw = p->Rw;\n double * R = p->R;\n double * GI = p->G;\n double sigma = p->sigma;\n double bg = p->bg;\n\n#if verbose > 2\n printf(\"Rw: %lu\\n\", Rw);\n printf(\"Nphot: %lu\\n\", Nphot);\n printf(\"sigma: %f\\n\", sigma);\n printf(\"bg : %f\\n\", bg);\n#endif\n\n // Get the other parameters ... \n x = gsl_vector_get(v, 0);\n double Nphot = gsl_vector_get(v,1);\n\n // printf(\"bg: %f, Nphot: %f, sigma: %f z: %f\\n\", bg, Nphot, sigma, x);\n\n // Create Gaussian ...\n double mu[] = {x};\n gaussianInt1(GI, mu, &sigma, Rw);\n for(size_t kk = 0; kk2\n printf(\"GI:\\n\");\n showRegion(GI, Rw);\n#endif \n\n /* \n * from LL2PG.m\n * model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2);\n * mask = disk2d((size(patch,1)-1)/2);\n * %L = -sum(sum(-(patch-model).^2./model - .5*log(model)));\n * L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model))));\n */\n\n double E = 0;\n for (size_t kk=0; kkRw;\n double * R = p->R;\n double * GI = p->G;\n double sigma = p->sigma;\n double bg = p->bg;\n\n#if verbose > 2\n printf(\"Rw: %lu\\n\", Rw);\n printf(\"Nphot: %lu\\n\", Nphot);\n printf(\"sigma: %f\\n\", sigma);\n printf(\"bg : %f\\n\", bg);\n#endif\n\n // Get the other parameters ... \n x = gsl_vector_get(v, 0);\n y = gsl_vector_get(v, 1);\n double Nphot = gsl_vector_get(v,2);\n\n // Create Gaussian ...\n double mu[] = {x,y};\n gaussianInt2(GI, mu, &sigma, Rw);\n for(size_t kk = 0; kk2\n printf(\"GI:\\n\");\n showRegion(GI, Rw);\n#endif \n\n /* \n * from LL2PG.m\n * model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2);\n * mask = disk2d((size(patch,1)-1)/2);\n * %L = -sum(sum(-(patch-model).^2./model - .5*log(model)));\n * L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model))));\n */\n\n double E = 0;\n for (size_t kk=0; kkgradient, 1e-4);\n\n if (status == GSL_SUCCESS)\n {\n#if verbose > 0\n printf (\"converged to minimum at\\n\");\n printf (\"%5lu x:%10.3e y:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\\n\", \n iter,\n gsl_vector_get (s->x, 0), \n gsl_vector_get (s->x, 1), \n gsl_vector_get (s->x, 2), \n 0.0, size);\n#endif\n }\n }\n while (status == GSL_CONTINUE && iter < maxIterationsQN);\n\n // F is always written even if the convergence failed\n F[0] = gsl_vector_get (s->x, 0)+nearbyint(D[0]);\n F[1] = gsl_vector_get (s->x, 1)+nearbyint(D[1]);\n F[2] = D[2]; // Not optimized\n\n gsl_vector_free(x);\n gsl_vector_free(ss);\n gsl_multimin_fdfminimizer_free (s);\n\n free(par.G);\n\n return status;\n}\n\nint localizeDotZ(double * V, size_t Vm,\n double * D, double * F, double sigma)\n // Localization for a dot roughly centered in V of size Vm x Vm\n // D[0], D[1], D[3] are the global coordinates of the dot\n // F are the fitted coordinates\n{\n\n // Non-optimized parameters\n optParams par;\n par.R = V;\n par.Rw = Vm;\n par.sigma = sigma;\n par.bg = estimateBG(V, Vm);\n par.G = (double *) malloc(Vm*sizeof(double));\n\n const gsl_multimin_fminimizer_type *T =\n gsl_multimin_fminimizer_nmsimplex2;\n gsl_multimin_fminimizer *s = NULL;\n gsl_vector *ss, *x;\n gsl_multimin_function minex_func;\n\n size_t iter = 0;\n int status;\n double size;\n\n /* Starting point */\n x = gsl_vector_alloc (2);\n gsl_vector_set(x, 0, 0); // z position\n gsl_vector_set(x, 1, estimateNphot(V, Vm)); // Nphot\n\n /* Set initial step sizes */\n ss = gsl_vector_alloc(2);\n gsl_vector_set_all(ss, 0.1);\n gsl_vector_set(ss, 1, 10); // Number of photons\n\n /* Initialize method and iterate */\n minex_func.n = 2;\n minex_func.f = lz;\n minex_func.params = ∥\n\n //printf(\".\\n\"); fflush(stdout);\n\n s = gsl_multimin_fminimizer_alloc (T, 2);\n\n // printf(\"..\\n\"); fflush(stdout);\n int error = gsl_multimin_fminimizer_set(s,\n &minex_func,\n x, // starting point\n ss); // Step sizes\n if(error>0)\n printf(\"error: %d\\n\", error);\n // printf(\"...\\n\"); fflush(stdout);\n\n do\n {\n iter++;\n status = gsl_multimin_fminimizer_iterate(s);\n // printf(\"....\\n\"); fflush(stdout);\n\n if (status)\n break;\n\n size = gsl_multimin_fminimizer_size(s);\n status = gsl_multimin_test_size(size, convCriteria);\n // printf(\".....\\n\"); fflush(stdout);\n\n if (status == GSL_SUCCESS)\n {\n#if verbose > 0\n printf (\"converged to minimum at\\n\");\n printf (\"%5lu z:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\\n\",\n iter,\n gsl_vector_get (s->x, 0),\n gsl_vector_get (s->x, 1),\n s->fval, size);\n#endif\n }\n }\n while (status == GSL_CONTINUE && iter < maxIterations);\n\n // Always Update Z position -- even if convergence failed\n F[2] = gsl_vector_get (s->x, 0)+nearbyint(D[2]);\n\n gsl_vector_free(x);\n gsl_vector_free(ss);\n gsl_multimin_fminimizer_free (s);\n\n free(par.G);\n\n return status;\n}\nint localize(double * V, size_t Vm, size_t Vn, size_t Vp, \n double * D, size_t Dm, double * F, double sigma_xy, double sigma_z)\n // run the localization routine for a list of dots\n{\n\n /* The window size is a very important parameter. Small windows can not capture the full signals and that results in \n * bad fittings. \n * Ws = 7 is good until sigma = 1.1\n * Ws = 9 is good at least until sigma = 1.6 \n */\n int Ws = 9; // Window size\n double * W = malloc(Ws*Ws*sizeof(double));\n\n for(size_t kk =0; kk 1\n printf(\"W:\\n\");\n showRegion(W, Ws);\n#endif\n // Local fitting in W\n#if verbose > 0\n int status = localizeDotXY(W, Ws, D+kk*3, F+kk*3, sigma_xy);\n printf(\"Status: %d\\n\", status);\n#else\n localizeDotXY(W, Ws, D+kk*3, F+kk*3, sigma_xy);\n#endif\n\n if(getZLine(W,Ws, \n V, Vm, Vn, Vp, D+kk*3) == 0)\n {\n localizeDotZ(W, Ws, D+kk*3, F+kk*3, sigma_z);\n }\n\n }\n else\n {\n // TODO: add also Nphot and status to the output \n F[kk*3] = -1;\n F[kk*3+1] = -1;\n F[kk*3+2] = -1;\n }\n }\n free(W);\n return 0;\n}\n\nint unit_tests(){\n double * V; // image\n int Vm = 1024; int Vn = 1024; int Vp = 60;\n double * D; // list of dots\n size_t Dm = 5; // number of dots\n double * F; // fitted dots\n\n printf(\"Image size: %dx%dx%d\\n\", Vm, Vn, Vp);\n printf(\"Localizing %lu dots\\n\", Dm);\n\n V = (double *) malloc(Vm*Vn*Vp*sizeof(double));\n D = (double *) malloc(3*Dm*sizeof(double));\n F = (double *) malloc(3*Dm*sizeof(double));\n\n // Initialize the data\n for(int kk=0; kk 0\n printf(\"D %03d %f %f %f\\n\", kk, D[pos], D[pos+1], D[pos+2]);\n#endif\n }\n\n for(uint32_t kk=0; kk0\n for(size_t kk = 0; kk (%f, %f, %f)\\n\", kk,\n D[pos], D[pos+1], D[pos+2],\n F[pos], F[pos+1], F[pos+2]);\n }\n#endif \n free(F);\n free(D);\n free(V);\n return 0; \n}\n\nint main(int argc, char ** argv)\n // For testing, not used any more, see the MATLAB interface in\n // df_mlfit.c\n{\n\n printf(\"%s\\n\", argv[0]);\n\n if(argc == 1)\n return unit_tests();\n\n return 0;\n}\n\n\n", "meta": {"hexsha": "cb1e2122204af8ffbb53f0c553db83d477cdb63f", "size": 14991, "ext": "c", "lang": "C", "max_stars_repo_path": "common/mex/mlfit1.c", "max_stars_repo_name": "elgw/dotter", "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_issues_repo_path": "common/mex/mlfit1.c", "max_issues_repo_name": "elgw/dotter", "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "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": "common/mex/mlfit1.c", "max_forks_repo_name": "elgw/dotter", "max_forks_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "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.8606965174, "max_line_length": 119, "alphanum_fraction": 0.5938896671, "num_tokens": 5141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4630599969359084}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"util.h\"\n\n\n\nint main(int argc, char *argv[]) {\n char* input_fileName1 = argv[1];\n char* input_fileName2 = argv[2];\n int N_doc_bg = atoi(argv[3]);\n int N_kw = atoi(argv[4]);\n int N_obs = atoi(argv[5]);\n int N_iter = atoi(argv[6]);\n double sec_budget = atoi(argv[7]) / 100.0;\n char* output_fileName = argv[8];\n int N_doc = 480000 / 2;\n int fixed_padding = 2 * log(2) * (64 + log(N_doc) / log(2)) / sec_budget;\n printf(\"Padding: %d\\n\", fixed_padding);\n\n int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw);\n int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);\n int* true_index = (int*) malloc(sizeof(int) * N_kw);\n int* permutation = (int*) malloc(sizeof(int) * N_obs);\n gsl_matrix* matrix_obs;\n\n for (int round = 0; round < 10; round++)\n {\n char input_fileName1_extend[40];\n char input_fileName2_extend[40];\n sprintf(input_fileName1_extend, \"%s%d\", input_fileName1, round);\n sprintf(input_fileName2_extend, \"%s%d\", input_fileName2, round);\n \n // Setup\n struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);\n read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);\n gettimeofday(&tv2, NULL);\n printf(\"Reading done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n for (int iter = 0; iter < 10; iter++)\n {\n printf(\"Run %d\\n\", iter);\n matrix_obs = gsl_matrix_alloc(N_obs, N_obs);\n\n gettimeofday(&tv1, NULL);\n pad_matrix(&matrix_padded, &matrix, N_obs, N_doc, sec_budget, fixed_padding);\n gettimeofday(&tv2, NULL);\n printf(\"Padding done: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n gettimeofday(&tv1, NULL);\n observe_matrix(matrix_obs, &matrix_padded, N_obs);\n gettimeofday(&tv2, NULL);\n printf(\"Observed matrix generated: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n\n // Permute observed matrix randomly and attack\n gettimeofday(&tv1, NULL);\n attack(matrix_obs, &matrix_bg, &permutation, N_kw, N_obs, N_doc, sec_budget, fixed_padding, N_iter);\n gettimeofday(&tv2, NULL);\n printf(\"Main attack done: %f.\\n\", (tv2.tv_usec - tv1.tv_usec) / 1000000.0 + (tv2.tv_sec - tv1.tv_sec));\n fflush(stdout);\n\n char output_fileName_full[40];\n sprintf(output_fileName_full, \"%s%d-%d\", output_fileName, round, iter);\n print_result(output_fileName_full, &permutation, &true_index, N_obs);\n //sprintf(output_fileName_full, \"%s%d-%d-full\", output_fileName, round, iter);\n //print_full_result(output_fileName_full, &permutation, &true_index, N_obs);\n }\n }\n\n free(matrix);\n free(matrix_padded);\n gsl_matrix_free(matrix_obs);\n return(0);\n}\n\n\ndouble log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc, double sec_budget, int fixed_padding)\n{\n int idx1_m = (*permutation)[idx1];\n int idx2_m = (*permutation)[idx2];\n\n if (idx1 == idx2)\n {\n int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);\n int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;\n N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;\n int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n \n double score = 0;\n double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc;\n for (int kk = N_lower; kk < N_upper+1; kk+=20)\n score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_laplace_pdf(count_total - fixed_padding - 2*kk, 2.0/sec_budget);\n if (score == 0)\n return(-500.0);\n }\n\n\n int n1 = (int) gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx1_m];\n int n2 = (int) gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx2_m*N_kw + idx2_m];\n\n double mean = 0.5 * gsl_matrix_get(matrix_obs, idx2, idx2) / N_doc * n1 + 0.5 * gsl_matrix_get(matrix_obs, idx1, idx1) / N_doc * n2;\n double var = 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);\n var += 0.25 * n1 / N_doc * gsl_matrix_get(matrix_obs, idx2, idx2) * (2 * N_doc - gsl_matrix_get(matrix_obs, idx2, idx2)) / N_doc;\n var += 0.25 * n2 / N_doc * gsl_matrix_get(matrix_obs, idx1, idx1) * (2 * N_doc - gsl_matrix_get(matrix_obs, idx1, idx1)) / N_doc;\n int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);\n\n int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);\n int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;\n N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;\n\n double score = 0;\n double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc;\n for (int kk = N_lower; kk < N_upper+1; kk+=20)\n score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_gaussian_pdf(count_total - mean - kk, sqrt(var));\n\n if (score == 0)\n return(-500.0);\n return(log(20*score));\n}\n\n\n\nvoid initial_solution(int** permutation, gsl_matrix* matrix_obs, int** matrix, int fixed_padding, int N_kw, int N_obs)\n{\n int* diff = (int*) malloc(sizeof(int) * N_kw);\n int* index = (int*) malloc(sizeof(int) * N_kw);\n int* occupied = (int*) malloc(sizeof(int) * N_kw);\n\n for (int ii = 0; ii < N_kw; ii++)\n occupied[ii] = -1;\n\n for (int ii = 0; ii < N_obs; ii++)\n {\n // reset index\n for (int jj = 0; jj < N_kw; jj++)\n index[jj] = jj;\n\n // compute differences\n for (int jj = 0; jj < N_kw; jj++)\n diff[jj] = abs(gsl_matrix_get(matrix_obs, ii, ii) - fixed_padding - 2*(*matrix)[jj*N_kw+jj]);\n\n // sorting\n for (int jj = 0; jj < N_kw-1; jj++)\n {\n for (int kk = 0; kk < N_kw-jj-1; kk++)\n {\n if (diff[kk] > diff[kk+1])\n {\n int temp = diff[kk+1];\n diff[kk+1] = diff[kk];\n diff[kk] = temp;\n\n temp = index[kk+1];\n index[kk+1] = index[kk];\n index[kk] = temp;\n }\n }\n }\n\n // use the smallest index available\n int idx = 0;\n while (occupied[idx] > 0)\n idx++;\n\n // update the data structures\n (*permutation)[ii] = index[idx];\n occupied[idx] = 1;\n }\n\n}\n\n\n\n\nvoid attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, double sec_budget, int fixed_padding, int N_iter)\n{\n // Initialise data structures\n double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs);\n double* score_row1 = (double*) malloc(sizeof(double) * N_obs);\n double* score_row2 = (double*) malloc(sizeof(double) * N_obs);\n\n int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);\n int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);\n\n // Initialise permutations\n // Initial solution\n initial_solution(permutation, matrix_obs, matrix, fixed_padding, N_kw, N_obs);\n for (int ii = 0; ii < N_obs; ii++)\n permutation_tmp[ii] = (*permutation)[ii];\n for (int ii = 0; ii < N_kw; ii++)\n permutation_inv[ii] = -1;\n for (int ii = 0; ii < N_obs; ii++)\n permutation_inv[permutation_tmp[ii]] = ii;\n\n // Initialising RNG\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 struct timeval tv1,tv2;\n gettimeofday(&tv1, NULL);\n\n // Compute initial score\n #pragma omp parallel for shared(score_matrix, matrix_obs, matrix)\n for (int ii = 0; ii < N_obs * N_obs; ii++)\n score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc, sec_budget, fixed_padding);\n gettimeofday(&tv2, NULL);\n printf(\"Initial score computed: %f.\\n\", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));\n \n // Iterations of simulated annealing\n double temp = (double) N_kw;\n int N_stuck = 0;\n for (int iter = 0; iter < N_iter; iter++)\n {\n /* Status code */\n if (iter % (N_iter / 10) == 0)\n {\n gettimeofday(&tv1, NULL);\n printf(\"Iteration: %d, %d, %d.\\n\", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));\n fflush(stdout);\n gettimeofday(&tv2, NULL);\n }\n\n\t // used to be 10k\n if (N_stuck >= N_kw * 20)\n iter = N_iter;\n\n /* Main code */\n int idx1, idx2;\n permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, matrix_obs, matrix, fixed_padding, N_kw, N_obs, N_doc, sec_budget);\n if (idx1 == idx2)\n {\n N_stuck += 1;\n continue;\n }\n\n #pragma omp parallel for shared(score_row1)\n for (int ii = 0; ii < N_obs; ii++)\n score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, sec_budget, fixed_padding);\n\n if (idx2 >= 0)\n #pragma omp parallel for shared(score_row2)\n for (int ii = 0; ii < N_obs; ii++)\n score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, sec_budget, fixed_padding);\n\n\n double score_diff = 0;\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx1*N_obs + ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_diff += score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_diff -= score_matrix[idx2*N_obs + ii];\n }\n\n // compute difference in score, with exponentiation\n score_diff = score_diff / temp;\n \n if (score_diff < -40)\n score_diff = 0;\n else if (score_diff > 0)\n score_diff = 1.01;\n else\n score_diff = exp(score_diff);\n\n if (gsl_ran_flat(r, 0, 1) < score_diff)\n {\n // Update the scores\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx1*N_obs + ii] = score_row1[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx1] = score_row1[ii];\n if (idx2 >= 0)\n {\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[idx2*N_obs + ii] = score_row2[ii];\n for (int ii = 0; ii < N_obs; ii++)\n score_matrix[ii*N_obs + idx2] = score_row2[ii];\n }\n\n // Update the permutation\n permutation_inv[(*permutation)[idx1]] = -1;\n (*permutation)[idx1] = permutation_tmp[idx1];\n permutation_inv[permutation_tmp[idx1]] = idx1;\n if (idx2 >= 0)\n {\n (*permutation)[idx2] = permutation_tmp[idx2];\n permutation_inv[permutation_tmp[idx2]] = idx2;\n }\n N_stuck = 0;\n }\n else\n {\n // Update the permutation\n permutation_tmp[idx1] = (*permutation)[idx1];\n if (idx2 >= 0)\n permutation_tmp[idx2] = (*permutation)[idx2];\n N_stuck += 1;\n }\n\n temp *= 0.995;\n }\n\n free(score_matrix);\n free(score_row1);\n free(score_row2);\n gsl_rng_free(r);\n}\n\n\n\nvoid print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n {\n //if (ii < 50)\n // printf(\"%d, %d\\n\", (*permutation)[ii], (*true_index)[ii]);\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n }\n\n fprintf(fp, \"%d\\n\", count);\n fclose(fp);\n printf(\"Success: %d/%d.\\n\", count, N_obs);\n}\n\n\n\nvoid print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)\n{\n FILE* fp = fopen(output_fileName, \"w\");\n int count = 0;\n for (int ii = 0; ii < N_obs; ii++)\n if ((*permutation)[ii] == (*true_index)[ii])\n count++;\n\n fprintf(fp, \"%d\\n\", count);\n for (int ii = 0; ii < N_obs; ii++)\n fprintf(fp, \"%d,%d\\n\", (*permutation)[ii], (*true_index)[ii]);\n\n\n fclose(fp);\n}", "meta": {"hexsha": "f6a2b17985bbd68ba4559b658ebb614779dd140e", "size": 13090, "ext": "c", "lang": "C", "max_stars_repo_path": "DP-EMM/attack_mp.c", "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DP-EMM/attack_mp.c", "max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "DP-EMM/attack_mp.c", "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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.6675749319, "max_line_length": 161, "alphanum_fraction": 0.5636363636, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4627623074288461}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// From Alam et al '02\ndouble R_half_V_max_NFW(double M_vir, double z, int mode, cosmo_info **cosmo) {\n double c_vir;\n double R_vir;\n double r_o;\n double r_val = 0.;\n\n set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);\n\n r_o = R_vir / c_vir;\n r_val = 0.13 * r_o;\n\n return (r_val);\n}\n", "meta": {"hexsha": "cf691eb10dcead249572fb05fa052cc354be3442", "size": 500, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/R_half_V_max_NFW.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 20.8333333333, "max_line_length": 79, "alphanum_fraction": 0.66, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.46270800892119557}} {"text": "// Copyright (c) 2021 Stig Rune Sellevag\n//\n// This file is distributed under the MIT License. See the accompanying file\n// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms\n// and conditions.\n\n#ifndef SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H\n#define SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H\n\n#ifdef USE_MKL\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Sci {\nnamespace Linalg {\n\nnamespace stdex = std::experimental;\n\ntemplate ::size_type nrows_a,\n stdex::extents<>::size_type ncols_a,\n class Layout_a,\n class Accessor_a,\n class T_x,\n stdex::extents<>::size_type ext_x,\n class Layout_x,\n class Accessor_x,\n class T_y,\n stdex::extents<>::size_type ext_y,\n class Layout_y,\n class Accessor_y>\n requires(!std::is_const_v)\ninline void matrix_vector_product(\n stdex::mdspan, Layout_a, Accessor_a>\n a,\n stdex::mdspan, Layout_x, Accessor_x> x,\n stdex::mdspan, Layout_y, Accessor_y> y)\n{\n static_assert(x.static_extent(0) == a.static_extent(1));\n using size_type = stdex::extents<>::size_type;\n\n for (size_type i = 0; i < a.extent(0); ++i) {\n y(i) = T_y{0};\n for (size_type j = 0; j < a.extent(1); ++j) {\n y(i) += a(i, j) * x(j);\n }\n }\n}\n\ntemplate \ninline void matrix_vector_product(Sci::Matrix_view a,\n Sci::Vector_view x,\n Sci::Vector_view y)\n{\n static_assert(x.static_extent(0) == a.static_extent(1));\n\n constexpr double alpha = 1.0;\n constexpr double beta = 0.0;\n\n const BLAS_INT m = static_cast(a.extent(0));\n const BLAS_INT n = static_cast(a.extent(1));\n const BLAS_INT incx = static_cast(x.stride(0));\n const BLAS_INT incy = static_cast(y.stride(0));\n\n auto matrix_layout = CblasRowMajor;\n BLAS_INT lda = n;\n\n if constexpr (std::is_same_v) {\n matrix_layout = CblasColMajor;\n lda = m;\n }\n cblas_dgemv(matrix_layout, CblasNoTrans, m, n, alpha, a.data(), lda,\n x.data(), incx, beta, y.data(), incy);\n}\n\ntemplate \ninline void matrix_vector_product(Sci::Matrix_view a,\n Sci::Vector_view x,\n Sci::Vector_view y)\n{\n static_assert(x.static_extent(0) == a.static_extent(1));\n\n constexpr double alpha = 1.0;\n constexpr double beta = 0.0;\n\n const BLAS_INT m = static_cast(a.extent(0));\n const BLAS_INT n = static_cast(a.extent(1));\n const BLAS_INT incx = static_cast(x.stride(0));\n const BLAS_INT incy = static_cast(y.stride(0));\n\n auto matrix_layout = CblasRowMajor;\n BLAS_INT lda = n;\n\n if constexpr (std::is_same_v) {\n matrix_layout = CblasColMajor;\n lda = m;\n }\n cblas_dgemv(matrix_layout, CblasNoTrans, m, n, alpha, a.data(), lda,\n x.data(), incx, beta, y.data(), incy);\n}\n\n#ifdef USE_MKL\n// Does not work with OpenBLAS version 0.2.14.1\ntemplate \ninline void\nmatrix_vector_product(Sci::Matrix_view, Layout> a,\n Sci::Vector_view, Layout> x,\n Sci::Vector_view, Layout> y)\n{\n static_assert(x.static_extent(0) == a.static_extent(1));\n\n constexpr std::complex alpha = {1.0, 0.0};\n constexpr std::complex beta = {0.0, 0.0};\n\n const BLAS_INT m = static_cast(a.extent(0));\n const BLAS_INT n = static_cast(a.extent(1));\n const BLAS_INT incx = static_cast(x.stride(0));\n const BLAS_INT incy = static_cast(y.stride(0));\n\n auto matrix_layout = CblasRowMajor;\n BLAS_INT lda = n;\n\n if constexpr (std::is_same_v) {\n matrix_layout = CblasColMajor;\n lda = m;\n }\n cblas_zgemv(matrix_layout, CblasNoTrans, m, n, &alpha, a.data(), lda,\n x.data(), incx, &beta, y.data(), incy);\n}\n\ntemplate \ninline void\nmatrix_vector_product(Sci::Matrix_view, Layout> a,\n Sci::Vector_view, Layout> x,\n Sci::Vector_view, Layout> y)\n{\n static_assert(x.static_extent(0) == a.static_extent(1));\n\n constexpr std::complex alpha = {1.0, 0.0};\n constexpr std::complex beta = {0.0, 0.0};\n\n const BLAS_INT m = static_cast(a.extent(0));\n const BLAS_INT n = static_cast(a.extent(1));\n const BLAS_INT incx = static_cast(x.stride(0));\n const BLAS_INT incy = static_cast(y.stride(0));\n\n auto matrix_layout = CblasRowMajor;\n BLAS_INT lda = n;\n\n if constexpr (std::is_same_v) {\n matrix_layout = CblasColMajor;\n lda = m;\n }\n cblas_zgemv(matrix_layout, CblasNoTrans, m, n, &alpha, a.data(), lda,\n x.data(), incx, &beta, y.data(), incy);\n}\n#endif\n\ntemplate \ninline Sci::Vector\nmatrix_vector_product(const Sci::Matrix& a,\n const Sci::Vector& x)\n{\n Sci::Vector res(a.extent(0));\n matrix_vector_product(a.view(), x.view(), res.view());\n return res;\n}\n\ntemplate \ninline void matrix_vector_product(const Sci::Matrix& a,\n const Sci::Vector& x,\n Sci::Vector& res)\n{\n assert(res.size() == a.extent(0));\n matrix_vector_product(a.view(), x.view(), res.view());\n}\n\n} // namespace Linalg\n} // namespace Sci\n\n#endif // SCILIB_LINALG_BLAS2_MATRIX_VECTOR_PRODUCT_H\n", "meta": {"hexsha": "93ff8d84a9ac44dc701fcaea28a567b77bff0f55", "size": 6431, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h", "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h", "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scilib/linalg_impl/blas2_matrix_vector_product.h", "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "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.4947916667, "max_line_length": 78, "alphanum_fraction": 0.6380034209, "num_tokens": 1754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.46255379447792994}} {"text": "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/*\n Contains the PERDIF program that implements personalized diffusions for\n recommendations.\n\n Code by: Dimitris Berberidis and Athanasios N. Nikolakopoulos\n University of Minnesota 2018-2019\n*/\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \n#include \n\n#include \"perdif_fit.h\"\n#include \"rec_defs.h\"\n\n#if DEBUG\nstatic double cost_func(double *, double *, double *, sz_med_t);\n#endif\n\nstatic void matrix_matrix_product(double *C, double *A, double *B, int, int, int);\nstatic double *unfold_matrix(d_mat_t);\nstatic void constr_QP_with_PG(double *, double *, double *, sz_med_t);\nstatic void grammian_matrix(double *, double *, int, int);\nstatic double max_abs_dif(double *, double *, sz_long_t);\n// static void project_to_simplex(double *, sz_med_t);\n// static void project_to_simplex_thanos(double *, double *, sz_med_t length);\nstatic void simplexproj_Duchi(double *y, double *x, const unsigned int length);\nstatic void matvec(double *, double *, double *, int, int);\nstatic double frob_norm(double *, sz_med_t);\n\n///////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid k_simplex(double *theta, d_mat_t P, int max_walk, double *dummy, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n // Unfold P for BLAS compatibility\n double *P_unfold = unfold_matrix(P);\n\n // Prepare parameters for constraned QP\n\n // first the Hessian matrix\n double A[max_walk * max_walk];\n grammian_matrix(A, P_unfold, (int)P.num_rows, (int)P.num_cols);\n\n // then the linear part\n double b[max_walk];\n\n if (rmse) {\n for (int i = 0; i < max_walk; i++)\n b[i] = -2.0 * (P_unfold[i]);\n } else {\n for (int i = 0; i < max_walk; i++) {\n b[i] = 0.0;\n for (int j = 0; j < P.num_rows; j++) {\n b[i] += P.val[i][j];\n }\n b[i] *= -2.0;\n }\n }\n\n constr_QP_with_PG(theta, A, b, (sz_med_t)max_walk);\n\n // free\n free(P_unfold);\n}\n\n// Simple search returns the single best step ( i.e. theta = [0 0 0 1 0 0 .... 0\n// 0 ] )\n\nvoid single_best(double *theta, d_mat_t P, int max_walk, double *dummy, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n for (int k = 0; k < max_walk; k++)\n theta[k] = 0.0;\n\n double loss[max_walk];\n\n // Compute loss of each k-step and find smallest\n int best_k = 0;\n double min_loss = 1.0e5;\n for (int k = 0; k < max_walk; k++) {\n loss[k] += pow(1.0 - P.val[0][k], 2);\n if (rmse) {\n for (int j = 1; j < P.num_rows; j++)\n loss[k] += P.val[j][k] * P.val[j][k];\n } else {\n for (int j = 1; j < P.num_rows; j++)\n loss[k] += pow(1.0 - P.val[j][k], 2);\n }\n if (loss[k] < min_loss) {\n min_loss = loss[k];\n best_k = k;\n }\n }\n\n theta[best_k] = 1.0;\n}\n\nvoid ppr_grid(double *theta, d_mat_t P, int max_walk, double *ppr_c, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n // Unfold P for BLAS compatibility\n double *P_unfold = unfold_matrix(P);\n\n // Candidate diffusions\n double *C = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));\n matrix_matrix_product(C, P_unfold, ppr_c, P.num_rows, max_walk, GRID_POINTS);\n\n // find the best one\n double loss[GRID_POINTS];\n int best_point = 0;\n double min_loss = 1.0e5;\n for (int i = 0; i < GRID_POINTS; i++) {\n // first the regularizer\n loss[i] = 0.0;\n // then the ratings\n if (rmse) {\n loss[i] += pow(1.0 - C[i], 2);\n for (int j = 1; j < P.num_rows; j++)\n loss[i] += pow(C[j * GRID_POINTS + i], 2);\n } else {\n for (int j = 0; j < P.num_rows; j++)\n loss[i] += pow(1.0 - C[j * GRID_POINTS + i], 2);\n }\n\n if (loss[i] < min_loss) {\n min_loss = loss[i];\n best_point = i;\n }\n }\n\n // return the best one\n for (int k = 0; k < max_walk; k++)\n theta[k] = ppr_c[k * GRID_POINTS + best_point];\n\n // free\n free(P_unfold);\n free(C);\n}\n\nvoid hk_grid(double *theta, d_mat_t P, int max_walk, double *hk_c, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n // Unfold P for BLAS compatibility\n double *P_unfold = unfold_matrix(P);\n\n double *C = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));\n matrix_matrix_product(C, P_unfold, hk_c, P.num_rows, max_walk, GRID_POINTS);\n\n // find the best one\n double loss[GRID_POINTS];\n int best_point = 0;\n double min_loss = 1.0e5;\n for (int i = 0; i < GRID_POINTS; i++) {\n // first the regularizer\n loss[i] = 0.0;\n\n // then the ratings\n if (rmse) {\n loss[i] += pow(1.0 - C[i], 2);\n for (int j = 1; j < P.num_rows; j++)\n loss[i] += pow(C[j * GRID_POINTS + i], 2);\n } else {\n for (int j = 0; j < P.num_rows; j++)\n loss[i] += pow(1.0 - C[j * GRID_POINTS + i], 2);\n }\n\n if (loss[i] < min_loss) {\n min_loss = loss[i];\n best_point = i;\n }\n }\n\n // return the best one\n for (int k = 0; k < max_walk; k++)\n theta[k] = hk_c[k * GRID_POINTS + best_point];\n\n // free\n free(P_unfold);\n free(C);\n}\n\nvoid dictionary_single(double *theta, d_mat_t P, int max_walk, double *dict, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n // Unfold P for BLAS compatibility\n double *P_unfold = unfold_matrix(P);\n\n // Prepare matrices\n double *PD = (double *)malloc(P.num_rows * GRID_POINTS * sizeof(double));\n matrix_matrix_product(PD, P_unfold, dict, (int)P.num_rows, (int)P.num_cols,\n GRID_POINTS);\n double DD[GRID_POINTS * GRID_POINTS];\n grammian_matrix(DD, dict, max_walk, GRID_POINTS);\n double A[GRID_POINTS * GRID_POINTS];\n grammian_matrix(A, PD, (int)P.num_rows, GRID_POINTS);\n\n double g_D[GRID_POINTS];\n for (int i = 0; i < GRID_POINTS; i++) {\n g_D[i] = 0.0;\n }\n\n if (rmse) {\n for (int i = 0; i < GRID_POINTS; i++)\n g_D[i] += -2.0 * PD[i];\n } else {\n for (int i = 0; i < GRID_POINTS; i++) {\n for (int j = 0; j < P.num_rows; j++)\n g_D[i] += -2.0 * PD[j * GRID_POINTS + i];\n }\n }\n\n double theta_dict[GRID_POINTS];\n\n // call QP solver for dictionary coefficients\n constr_QP_with_PG(theta_dict, A, g_D, (sz_med_t)GRID_POINTS);\n\n // construct diffusion from dictionary coefficients\n matvec(theta, dict, theta_dict, max_walk, GRID_POINTS);\n\n // free\n free(PD);\n free(P_unfold);\n}\n\nvoid dictionary(double *theta, d_mat_t P, int max_walk, double *dict, bool rmse) {\n\n if (!rmse) {\n // adjust for BPR metric\n for (int i = 1; i < P.num_rows; i++) {\n for (int j = 0; j < P.num_cols; j++)\n P.val[i][j] = P.val[0][j] - P.val[i][j];\n }\n }\n\n // Unfold P for BLAS compatibility\n double *P_unfold = unfold_matrix(P);\n\n // Prepare matrices\n double *PD = (double *)malloc(P.num_rows * 2 * GRID_POINTS * sizeof(double));\n matrix_matrix_product(PD, P_unfold, dict, (int)P.num_rows, (int)P.num_cols,\n 2 * GRID_POINTS);\n double DD[4 * GRID_POINTS * GRID_POINTS];\n grammian_matrix(DD, dict, max_walk, 2 * GRID_POINTS);\n double A[4 * GRID_POINTS * GRID_POINTS];\n grammian_matrix(A, PD, (int)P.num_rows, 2 * GRID_POINTS);\n\n double g_D[2 * GRID_POINTS];\n for (int i = 0; i < 2 * GRID_POINTS; i++) {\n g_D[i] = 0.0;\n }\n\n if (rmse) {\n for (int i = 0; i < 2 * GRID_POINTS; i++)\n g_D[i] += -2.0 * PD[i];\n } else {\n for (int i = 0; i < 2 * GRID_POINTS; i++) {\n for (int j = 0; j < P.num_rows; j++)\n g_D[i] += -2.0 * PD[j * 2 * GRID_POINTS + i];\n }\n }\n\n double theta_dict[2 * GRID_POINTS];\n\n // call QP solver for dictionary coefficients\n constr_QP_with_PG(theta_dict, A, g_D, (sz_med_t)2 * GRID_POINTS);\n\n // construct diffusion from dictionary coefficients\n matvec(theta, dict, theta_dict, max_walk, 2 * GRID_POINTS);\n\n // free\n free(PD);\n free(P_unfold);\n}\n\n// Returns PPR coefficients for given points on a grid of parameter a\ndouble *ppr_coefficients(int max_walk) {\n\n int grid_points = GRID_POINTS;\n\n double *coef = (double *)malloc(max_walk * grid_points * sizeof(double));\n double width = 1.0 / (double)(grid_points + 2);\n\n double col_sum[grid_points];\n for (int j = 0; j < grid_points; j++)\n col_sum[j] = 0.0;\n\n for (int i = 0; i < max_walk; i++) {\n for (int j = 0; j < grid_points; j++) {\n // pagerank weights per step\n coef[i * grid_points + j] = (i == 0)\n ? (1 - (0.01 + width * ((double)j)))\n : (1 - (0.01 + width * ((double)j))) *\n pow(0.01 + width * ((double)j), i);\n col_sum[j] += coef[i * grid_points + j];\n }\n }\n\n // Normalize coefficients so tha they sum to 1\n for (int i = 0; i < max_walk; i++) {\n for (int j = 0; j < grid_points; j++)\n coef[i * grid_points + j] /= col_sum[j];\n }\n\n return coef;\n}\n\n// Returns HK coefficients for given points on a grid of parameter \\tau\ndouble *hk_coefficients(int max_walk) {\n\n int grid_points = GRID_POINTS;\n\n double *coef = (double *)malloc(max_walk * grid_points * sizeof(double));\n double width = (double)MAX_HK_COEF / (double)(grid_points + 2);\n\n // compute factorials from 1 to max_walk\n sz_long_t factorial[max_walk];\n factorial[0] = 1;\n for (int j = 1; j < max_walk; j++)\n factorial[j] = factorial[j - 1] * j;\n\n double col_sum[grid_points];\n for (int j = 0; j < grid_points; j++)\n col_sum[j] = 0.0;\n\n for (int i = 0; i < max_walk; i++) {\n for (int j = 0; j < grid_points; j++) {\n coef[i * grid_points + j] =\n pow(1.0 + width * ((double)j), i) / (double)factorial[i];\n col_sum[j] += coef[i * grid_points + j];\n }\n }\n // Normalize coefficients so that they sum to 1\n for (int i = 0; i < max_walk; i++) {\n for (int j = 0; j < grid_points; j++)\n coef[i * grid_points + j] /= col_sum[j];\n }\n\n return coef;\n}\n\n// Returns dictionary coefficients by concatenating PPR and HK\ndouble *dict_coefficients(int max_walk) {\n int grid_points = GRID_POINTS;\n\n double *coef = (double *)malloc(2 * max_walk * grid_points * sizeof(double));\n\n double *hk = hk_coefficients(max_walk);\n double *ppr = ppr_coefficients(max_walk);\n\n for (int i = 0; i < max_walk; i++) {\n for (int j = 0; j < grid_points; j++) {\n coef[2 * i * grid_points + j] = ppr[i * grid_points + j];\n }\n for (int j = grid_points; j < 2 * grid_points; j++) {\n coef[2 * i * grid_points + j] = hk[i * grid_points + j - grid_points];\n }\n }\n\n // free temporary coefs\n free(ppr);\n free(hk);\n return coef;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////////////////////\n\n// AUXILIARY FUNCTIONS\n\n// Interface for CBLAS mutrix matrix product\n// C =A*B\n// A : m x k\n// B : k x n\nstatic void matrix_matrix_product(double *C, double *A, double *B, int m, int k,\n int n) {\n\n for (int i = 0; i < m * n; i++)\n C[i] = 0.0f;\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f, A, k, B,\n n, 0.0f, C, n);\n}\n\n// Unfold matrix from A[i[j] to A[i*M + j]\nstatic double *unfold_matrix(d_mat_t A) {\n\n double *A_u = (double *)malloc(A.num_cols * A.num_rows * sizeof(double));\n\n for (sz_long_t i = 0; i < A.num_rows; i++)\n memcpy(A_u + i * A.num_cols, A.val[i], A.num_cols * sizeof(double));\n\n return A_u;\n}\n\n// Solving constrained quadratic minimization via projected gradient descent\n// The following function returns x =arg min {x^T*A*x +x^T*B} s.t. x in Prob.\n// Simplex\nstatic void constr_QP_with_PG(double *x, double *A, double *b, sz_med_t K) {\n double inf_norm, step_size;\n double x_temp[K];\n double x_prev[K];\n\n step_size = STEPSIZE_2 / frob_norm(A, K);\n\n // Initialize to uniform\n for (sz_med_t i = 0; i < K; i++)\n x[i] = 1.0f / (double)K;\n\n sz_med_t iter = 0;\n memcpy(x_prev, x, K * sizeof(double));\n // int count=0;\n do {\n iter++;\n // step_size = 1 / ((double)iter) * step_size;\n // step_size = 1/(sqrt(iter));//*step_size;\n // step_size = 1/(double)iter;\n // Take gradient step\n matvec(x_temp, A, x, K, K);\n\n for (sz_med_t j = 0; j < K; j++)\n x[j] -= step_size * (2.0f * x_temp[j] + b[j]);\n\n // project to feasible set\n simplexproj_Duchi(x, x, K);\n\n#if DEBUG\n printf(\"\\n COST: \");\n printf(\" %lf \", cost_func(A, b, x, K));\n#endif\n\n inf_norm = max_abs_dif(x_prev, x, (sz_long_t)K);\n\n memcpy(x_prev, x, K * sizeof(double));\n\n } while (iter < MAXIT_GD && inf_norm > GD_TOL_2);\n\n // printf(\"\\n Counter = %d\", count);\n // printf(\"\\n Optimization finished after: %\"PRIu32\" iterations\\n\", (uint32_t)\n // iter);\n}\n\n// Grammian matrix G =A'*A using CBLAS\n// A : m x n\nstatic void grammian_matrix(double *G, double *A, int m, int n) {\n\n for (int i = 0; i < n * n; i++)\n G[i] = 0.0f;\n\n double *A_copy = (double *)malloc(m * n * sizeof(double));\n\n memcpy(A_copy, A, m * n * sizeof(double));\n\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, m, 1.0f, A_copy, n,\n A, n, 0.0f, G, n);\n\n free(A_copy);\n}\n\n// Interface for CBLAS matrix vector product\n// A : M x N\nstatic void matvec(double *y, double *A, double *x, int M, int N) {\n\n // for (int i = 0; i < M; i++)\n // {\n // \ty[i] = 0.0f;\n // }\n\n cblas_dgemv(CblasRowMajor, CblasNoTrans, M, N, 1.0f, A, N, x, 1, 0.0f, y, 1);\n}\n\n//\n\n/* Algorithm using partitioning with respect to a pivot, chosen randomly,\nas given by Duchi et al. in \"Efficient Projections onto the l1-Ball for\nLearning in High Dimensions\" */\nstatic void simplexproj_Duchi(double *y, double *x, const unsigned int length) {\n double *auxlower = (x == y ? (double *)malloc(length * sizeof(double)) : x);\n double *auxupper = (double *)malloc(length * sizeof(double));\n double *aux = auxlower;\n double pivot;\n int auxlowerlength = 0;\n int auxupperlength = 1;\n int upperlength;\n int auxlength;\n int i = 0;\n int pospivot = (int)(rand() / (((double)RAND_MAX + 1.0) / length));\n double tauupper;\n double tau = (pivot = y[pospivot]) - 1.0;\n while (i < pospivot)\n if (y[i] < pivot)\n auxlower[auxlowerlength++] = y[i++];\n else {\n auxupper[auxupperlength++] = y[i];\n tau += (y[i++] - tau) / auxupperlength;\n }\n i++;\n while (i < length)\n if (y[i] < pivot)\n auxlower[auxlowerlength++] = y[i++];\n else {\n auxupper[auxupperlength++] = y[i];\n tau += (y[i++] - tau) / auxupperlength;\n }\n if (tau < pivot) {\n upperlength = auxupperlength;\n tauupper = tau;\n auxlength = auxlowerlength;\n } else {\n tauupper = 0.0;\n upperlength = 0;\n aux = auxupper + 1;\n auxlength = auxupperlength - 1;\n }\n while (auxlength > 0) {\n pospivot = (int)(rand() / (((double)RAND_MAX + 1.0) / auxlength));\n if (upperlength == 0)\n tau = (pivot = aux[pospivot]) - 1.0;\n else\n tau = tauupper + ((pivot = aux[pospivot]) - tauupper) / (upperlength + 1);\n i = 0;\n auxlowerlength = 0;\n auxupperlength = 1;\n while (i < pospivot)\n if (aux[i] < pivot)\n auxlower[auxlowerlength++] = aux[i++];\n else {\n auxupper[auxupperlength++] = aux[i];\n tau += (aux[i++] - tau) / (upperlength + auxupperlength);\n }\n i++;\n while (i < auxlength)\n if (aux[i] < pivot)\n auxlower[auxlowerlength++] = aux[i++];\n else {\n auxupper[auxupperlength++] = aux[i];\n tau += (aux[i++] - tau) / (upperlength + auxupperlength);\n }\n if (tau < pivot) {\n upperlength += auxupperlength;\n tauupper = tau;\n auxlength = auxlowerlength;\n aux = auxlower;\n } else {\n aux = auxupper + 1;\n auxlength = auxupperlength - 1;\n }\n }\n for (i = 0; i < length; i++)\n x[i] = (y[i] > tau ? y[i] - tauupper : 0.0000000001);\n double sum = 0.0;\n for (i = 0; i < length; i++)\n sum += x[i];\n for (i = 0; i < length; i++)\n x[i] /= sum;\n if (x == y)\n free(auxlower);\n free(auxupper);\n}\n\n// Infinity norm\nstatic double max_abs_dif(double *a, double *b, sz_long_t len) {\n double dif, max = 0.0;\n\n for (sz_long_t i = 0; i < len; i++) {\n dif = fabs(a[i] - b[i]);\n max = (dif > max) ? dif : max;\n }\n\n return max;\n}\n\n#if DEBUG\n// Evaluates quadratic with Hessian A and linear part b at x\nstatic double cost_func(double *A, double *b, double *x, sz_med_t len) {\n\n double quad = 0.0f, lin = 0.0f;\n\n for (sz_med_t i = 0; i < len; i++) {\n for (sz_med_t j = 0; j < len; j++) {\n quad += A[i * len + j] * x[i] * x[j];\n }\n lin += b[i] * x[i];\n }\n return quad + lin;\n}\n#endif\n\n// frobenious norm of double-valued square matrix\nstatic double frob_norm(double *A, sz_med_t dim) {\n double norm = 0.0f;\n\n for (sz_med_t i = 0; i < dim * dim; i++) {\n norm += pow(A[i], 2.0f);\n }\n\n return sqrt(norm);\n}\n", "meta": {"hexsha": "5b37b7a5810aabc17921e1caa2a9ac0f4d82982e", "size": 17882, "ext": "c", "lang": "C", "max_stars_repo_path": "src/perdif_fit.c", "max_stars_repo_name": "nikolakopoulos/Personalized-Diffusions", "max_stars_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-09-18T10:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T00:07:13.000Z", "max_issues_repo_path": "src/perdif_fit.c", "max_issues_repo_name": "nikolakopoulos/Personalized-Diffusions", "max_issues_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2", "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/perdif_fit.c", "max_forks_repo_name": "nikolakopoulos/Personalized-Diffusions", "max_forks_repo_head_hexsha": "8a35c36407158f83682b9ddee24026fa5aac46d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-09-16T15:02:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-14T18:50:25.000Z", "avg_line_length": 27.6383307573, "max_line_length": 135, "alphanum_fraction": 0.5536852701, "num_tokens": 5656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.46239592015176195}} {"text": "// Copyright (c) 2021 Stig Rune Sellevag\n//\n// This file is distributed under the MIT License. See the accompanying file\n// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms\n// and conditions.\n\n#ifndef SCILIB_LINALG_INV_H\n#define SCILIB_LINALG_INV_H\n\n#ifdef USE_MKL\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Sci {\nnamespace Linalg {\n\n// Matrix inversion.\ntemplate \n requires(std::is_same_v, double>)\ninline void inv(Sci::Matrix_view a,\n Sci::Matrix_view res)\n{\n namespace stdex = std::experimental;\n\n static_assert(a.is_contiguous());\n static_assert(res.is_contiguous());\n\n assert(a.extent(0) == a.extent(1));\n\n if (det(a) == 0.0) {\n throw std::runtime_error(\"inv: matrix not invertible\");\n }\n const BLAS_INT n = static_cast(a.extent(0));\n\n auto matrix_layout = LAPACK_ROW_MAJOR;\n BLAS_INT lda = n;\n\n if constexpr (std::is_same_v) {\n matrix_layout = LAPACK_COL_MAJOR;\n }\n\n Sci::copy(a, res);\n\n Sci::Vector ipiv(n);\n Sci::Linalg::lu(res, ipiv.view()); // perform LU factorization\n\n BLAS_INT info =\n LAPACKE_dgetri(matrix_layout, n, res.data(), lda, ipiv.data());\n if (info != 0) {\n throw std::runtime_error(\"dgetri: matrix inversion failed\");\n }\n}\n\ntemplate \ninline Sci::Matrix\ninv(const Sci::Matrix& a)\n{\n Sci::Matrix res(a.extent(0), a.extent(1));\n inv(a.view(), res.view());\n return res;\n}\n\n} // namespace Linalg\n} // namespace Sci\n\n#endif // SCILIB_LINALG_INV_H\n", "meta": {"hexsha": "32581d4f49a8b7c21c394a59a1d249174d868992", "size": 1941, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scilib/linalg_impl/inv.h", "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scilib/linalg_impl/inv.h", "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scilib/linalg_impl/inv.h", "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "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.5394736842, "max_line_length": 78, "alphanum_fraction": 0.6831530139, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.46221939333551454}} {"text": "/* specfunc/hyperg.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/* Miscellaneous implementations of use\n * for evaluation of hypergeometric functions.\n */\n#include \n#include \n#include \n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_gamma.h\"\n\n#include \"error.h\"\n#include \"hyperg.h\"\n\n#define SUM_LARGE (1.0e-5*GSL_DBL_MAX)\n\n\nint\ngsl_sf_hyperg_1F1_series_e(const double a, const double b, const double x,\n gsl_sf_result * result\n )\n{\n double an = a;\n double bn = b;\n double n = 1.0;\n double del = 1.0;\n double abs_del = 1.0;\n double max_abs_del = 1.0;\n double sum_val = 1.0;\n double sum_err = 0.0;\n\n while(abs_del/fabs(sum_val) > GSL_DBL_EPSILON) {\n double u, abs_u;\n\n if(bn == 0.0) {\n DOMAIN_ERROR(result);\n }\n if(an == 0.0 || n > 1000.0) {\n result->val = sum_val;\n result->err = sum_err;\n result->err += 2.0 * GSL_DBL_EPSILON * n * fabs(sum_val);\n return GSL_SUCCESS;\n }\n\n u = x * (an/(bn*n));\n abs_u = fabs(u);\n if(abs_u > 1.0 && max_abs_del > GSL_DBL_MAX/abs_u) {\n result->val = sum_val;\n result->err = fabs(sum_val);\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n del *= u;\n sum_val += del;\n if(fabs(sum_val) > SUM_LARGE) {\n result->val = sum_val;\n result->err = fabs(sum_val);\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n\n abs_del = fabs(del);\n max_abs_del = GSL_MAX_DBL(abs_del, max_abs_del);\n sum_err += 2.0*GSL_DBL_EPSILON*abs_del;\n\n an += 1.0;\n bn += 1.0;\n n += 1.0;\n }\n\n result->val = sum_val;\n result->err = sum_err;\n result->err += abs_del;\n result->err += 2.0 * GSL_DBL_EPSILON * n * fabs(sum_val);\n\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_sf_hyperg_1F1_large_b_e(const double a, const double b, const double x, gsl_sf_result * result)\n{\n if(fabs(x/b) < 1.0) {\n const double u = x/b;\n const double v = 1.0/(1.0-u);\n const double pre = pow(v,a);\n const double uv = u*v;\n const double uv2 = uv*uv;\n const double t1 = a*(a+1.0)/(2.0*b)*uv2;\n const double t2a = a*(a+1.0)/(24.0*b*b)*uv2;\n const double t2b = 12.0 + 16.0*(a+2.0)*uv + 3.0*(a+2.0)*(a+3.0)*uv2;\n const double t2 = t2a*t2b;\n result->val = pre * (1.0 - t1 + t2);\n result->err = pre * GSL_DBL_EPSILON * (1.0 + fabs(t1) + fabs(t2));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n DOMAIN_ERROR(result);\n }\n}\n\n\nint\ngsl_sf_hyperg_U_large_b_e(const double a, const double b, const double x,\n gsl_sf_result * result,\n\t\t\t double * ln_multiplier\n\t\t\t )\n{\n double N = floor(b); /* b = N + eps */\n double eps = b - N;\n \n if(fabs(eps) < GSL_SQRT_DBL_EPSILON) {\n double lnpre_val;\n double lnpre_err;\n gsl_sf_result M;\n if(b > 1.0) {\n double tmp = (1.0-b)*log(x);\n gsl_sf_result lg_bm1;\n gsl_sf_result lg_a;\n gsl_sf_lngamma_e(b-1.0, &lg_bm1);\n gsl_sf_lngamma_e(a, &lg_a);\n lnpre_val = tmp + x + lg_bm1.val - lg_a.val;\n lnpre_err = lg_bm1.err + lg_a.err + GSL_DBL_EPSILON * (fabs(x) + fabs(tmp));\n gsl_sf_hyperg_1F1_large_b_e(1.0-a, 2.0-b, -x, &M);\n }\n else {\n gsl_sf_result lg_1mb;\n gsl_sf_result lg_1pamb;\n gsl_sf_lngamma_e(1.0-b, &lg_1mb);\n gsl_sf_lngamma_e(1.0+a-b, &lg_1pamb);\n lnpre_val = lg_1mb.val - lg_1pamb.val;\n lnpre_err = lg_1mb.err + lg_1pamb.err;\n gsl_sf_hyperg_1F1_large_b_e(a, b, x, &M);\n }\n\n if(lnpre_val > GSL_LOG_DBL_MAX-10.0) {\n result->val = M.val;\n result->err = M.err;\n *ln_multiplier = lnpre_val;\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n else {\n gsl_sf_result epre;\n int stat_e = gsl_sf_exp_err_e(lnpre_val, lnpre_err, &epre);\n result->val = epre.val * M.val;\n result->err = epre.val * M.err + epre.err * fabs(M.val);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n *ln_multiplier = 0.0;\n return stat_e;\n }\n }\n else {\n double omb_lnx = (1.0-b)*log(x);\n gsl_sf_result lg_1mb; double sgn_1mb;\n gsl_sf_result lg_1pamb; double sgn_1pamb;\n gsl_sf_result lg_bm1; double sgn_bm1;\n gsl_sf_result lg_a; double sgn_a;\n gsl_sf_result M1, M2;\n double lnpre1_val, lnpre2_val;\n double lnpre1_err, lnpre2_err;\n double sgpre1, sgpre2;\n gsl_sf_hyperg_1F1_large_b_e( a, b, x, &M1);\n gsl_sf_hyperg_1F1_large_b_e(1.0-a, 2.0-b, x, &M2);\n\n gsl_sf_lngamma_sgn_e(1.0-b, &lg_1mb, &sgn_1mb);\n gsl_sf_lngamma_sgn_e(1.0+a-b, &lg_1pamb, &sgn_1pamb);\n\n gsl_sf_lngamma_sgn_e(b-1.0, &lg_bm1, &sgn_bm1);\n gsl_sf_lngamma_sgn_e(a, &lg_a, &sgn_a);\n\n lnpre1_val = lg_1mb.val - lg_1pamb.val;\n lnpre1_err = lg_1mb.err + lg_1pamb.err;\n lnpre2_val = lg_bm1.val - lg_a.val - omb_lnx - x;\n lnpre2_err = lg_bm1.err + lg_a.err + GSL_DBL_EPSILON * (fabs(omb_lnx)+fabs(x));\n sgpre1 = sgn_1mb * sgn_1pamb;\n sgpre2 = sgn_bm1 * sgn_a;\n\n if(lnpre1_val > GSL_LOG_DBL_MAX-10.0 || lnpre2_val > GSL_LOG_DBL_MAX-10.0) {\n double max_lnpre_val = GSL_MAX(lnpre1_val,lnpre2_val);\n double max_lnpre_err = GSL_MAX(lnpre1_err,lnpre2_err);\n double lp1 = lnpre1_val - max_lnpre_val;\n double lp2 = lnpre2_val - max_lnpre_val;\n double t1 = sgpre1*exp(lp1);\n double t2 = sgpre2*exp(lp2);\n result->val = t1*M1.val + t2*M2.val;\n result->err = fabs(t1)*M1.err + fabs(t2)*M2.err;\n result->err += GSL_DBL_EPSILON * exp(max_lnpre_err) * (fabs(t1*M1.val) + fabs(t2*M2.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n *ln_multiplier = max_lnpre_val;\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n else {\n double t1 = sgpre1*exp(lnpre1_val);\n double t2 = sgpre2*exp(lnpre2_val);\n result->val = t1*M1.val + t2*M2.val;\n result->err = fabs(t1) * M1.err + fabs(t2)*M2.err;\n result->err += GSL_DBL_EPSILON * (exp(lnpre1_err)*fabs(t1*M1.val) + exp(lnpre2_err)*fabs(t2*M2.val));\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n *ln_multiplier = 0.0;\n return GSL_SUCCESS;\n }\n }\n}\n\n\n\n/* [Carlson, p.109] says the error in truncating this asymptotic series\n * is less than the absolute value of the first neglected term.\n *\n * A termination argument is provided, so that the series will\n * be summed at most up to n=n_trunc. If n_trunc is set negative,\n * then the series is summed until it appears to start diverging.\n */\nint\ngsl_sf_hyperg_2F0_series_e(const double a, const double b, const double x,\n int n_trunc,\n gsl_sf_result * result\n )\n{\n const int maxiter = 2000;\n double an = a;\n double bn = b; \n double n = 1.0;\n double sum = 1.0;\n double del = 1.0;\n double abs_del = 1.0;\n double max_abs_del = 1.0;\n double last_abs_del = 1.0;\n \n while(abs_del/fabs(sum) > GSL_DBL_EPSILON && n < maxiter) {\n\n double u = an * (bn/n * x);\n double abs_u = fabs(u);\n\n if(abs_u > 1.0 && (max_abs_del > GSL_DBL_MAX/abs_u)) {\n result->val = sum;\n result->err = fabs(sum);\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n\n del *= u;\n sum += del;\n\n abs_del = fabs(del);\n\n if(abs_del > last_abs_del) break; /* series is probably starting to grow */\n\n last_abs_del = abs_del;\n max_abs_del = GSL_MAX(abs_del, max_abs_del);\n\n an += 1.0;\n bn += 1.0;\n n += 1.0;\n \n if(an == 0.0 || bn == 0.0) break; /* series terminated */\n \n if(n_trunc >= 0 && n >= n_trunc) break; /* reached requested timeout */\n }\n\n result->val = sum;\n result->err = GSL_DBL_EPSILON * n + abs_del;\n if(n >= maxiter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "a13950fb99ea69c3099e1f32f9bb618a26e7bfaf", "size": 8531, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/hyperg.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.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.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.9333333333, "max_line_length": 107, "alphanum_fraction": 0.612823819, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.46176469791825514}} {"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid mark_debug (void)\n{\n static int number;\n printf(\"---> Mark %d <---\\n\", number);\n fflush(stdout);\n number++;\n}\n\n\nvoid label_debug (const char * label)\n{\n printf(\"---> Mark %s <---\\n\", label);\n fflush(stdout);\n}\n\n/* =========================== Pure-C source code =========================== */\n\n/* Regularization workspace */\nstruct rglz_wksp {\n double lamb; /* Lambda value */\n gsl_vector *Ldiag; /* Pointer to vector with diagonal values of the\n\t\t\t * regularization matrix L. */\n const gsl_vector *Y; /* Pointer to original Y */\n gsl_vector *Ys; /* Ponter to Y vector of the standard form. */\n const gsl_matrix *X; /* Pointer to original X matrix */\n gsl_matrix *Xs; /* Pointer to X matrix of the standard form. */\n gsl_multifit_linear_workspace *lwksp; /* Pointer to GSL workspace where SVDs are stored. */\n /* L-curve data */\n struct lcurve {\n\tgsl_vector *reg_param;\n\tgsl_vector *rho;\n\tgsl_vector *eta;\n } lcurve;\n};\ntypedef struct rglz_wksp rglz_wksp;\n\n\n/* Allocate and initialize inner variables of a regularization workspace. */\nrglz_wksp * rglz_init(const double *Ldiag, const int p, \n\t\t const gsl_vector *Y, const gsl_matrix *X, const gsl_vector *W,\n\t\t gsl_multifit_linear_workspace *lwksp)\n{\n rglz_wksp *rw;\n\n /* Allocate space for the workspace */\n rw = (rglz_wksp*) malloc(sizeof(rglz_wksp));\n\n rw->lamb = 0.0; /* Initial value */\n rw->lcurve.reg_param = NULL;\n rw->lcurve.rho = NULL;\n rw->lcurve.eta = NULL;\n\n /* Allocate space for the standard-form matrixes */\n rw->Xs = gsl_matrix_alloc(X->size1, X->size2);\n rw->Ys = gsl_vector_alloc(Y->size);\n\n /* Initialize the regularization weights Ldiag */\n rw->Ldiag = gsl_vector_alloc(p);\n for (int i = 0; i < p; i++)\n gsl_vector_set(rw->Ldiag, i, Ldiag[i]);\n\n /* Convert the system to standard form */\n gsl_multifit_linear_wstdform1(rw->Ldiag, X, W, Y, rw->Xs, rw->Ys, lwksp);\n\n /* Calculate SVD of standard-form matrix Xs */\n gsl_multifit_linear_svd(rw->Xs, lwksp);\n\n rw->lwksp = lwksp;\n rw->X = X;\n rw->Y = Y;\n return rw;\n}\n\nvoid rglz_estimate_lambda(rglz_wksp *rw, const int lcsize)\n{\n size_t idx; /* Temporary index to store corner of the L-curve */\n /* Allocate vectors */\n rw->lcurve.reg_param = gsl_vector_alloc(lcsize);\n rw->lcurve.rho = gsl_vector_alloc(lcsize);\n rw->lcurve.eta = gsl_vector_alloc(lcsize);\n /* Create Lcurve */\n gsl_multifit_linear_lcurve(rw->Y, rw->lcurve.reg_param, rw->lcurve.rho, rw->lcurve.eta, rw->lwksp);\n#ifdef PRINT_LCURVE\n for (int i = 0; i < lcsize; i++)\n {\n printf(\"%12.4e%12.4e\\n\",\n gsl_vector_get(rw->lcurve.rho, i),\n gsl_vector_get(rw->lcurve.eta, i));\n }\n#endif\n /* Estimate corner */\n gsl_multifit_linear_lcorner(rw->lcurve.rho, rw->lcurve.eta, &idx);\n /* Set lambda estimate */\n rw->lamb = gsl_vector_get(rw->lcurve.reg_param, idx);\n fprintf(stdout, \"From gslpy_ridge: lambda = %.4e\\n\", rw->lamb);\n}\n\nvoid rglz_solve(gsl_vector *c, double *rnorm, double *snorm, rglz_wksp *rw)\n{\n /* Solve in standard form */\n gsl_multifit_linear_solve(rw->lamb, rw->Xs, rw->Ys, c, rnorm, snorm, rw->lwksp);\n /* Convert back to original parameters */\n gsl_multifit_linear_genform1(rw->Ldiag, c, c, rw->lwksp);\n return;\n}\n\ninline void rglz_set_lambda(rglz_wksp *rw, const int lamb)\n{\n rw->lamb = lamb;\n}\n\nvoid rglz_close(rglz_wksp *rw)\n{\n gsl_vector_free(rw->Ldiag);\n gsl_matrix_free(rw->Xs);\n gsl_vector_free(rw->Ys);\n if (rw->lcurve.reg_param != NULL)\n\tgsl_vector_free(rw->lcurve.reg_param);\n if (rw->lcurve.rho != NULL)\n\tgsl_vector_free(rw->lcurve.rho);\n if (rw->lcurve.eta != NULL)\n\tgsl_vector_free(rw->lcurve.eta);\n free(rw);\n}\n\nint\ngslpy_ridge_regression(const gsl_vector * y,\n\t\t const gsl_matrix * X,\n\t\t const gsl_vector * w,\n\t\t const double lambda, \n\t\t const double * L,\n\t\t const unsigned long Lcurve_size,\n\t\t gsl_vector * coefs)\n{\n\n \n \n unsigned long n_samples = X->size1;\n unsigned long n_features = X->size2;\n\n double snorm;\n double chisq;\n\n gsl_multifit_linear_workspace\n\t* gmlw = gsl_multifit_linear_alloc(n_samples, n_features);\n \n rglz_wksp * rw = rglz_init(L, n_features, y, X, w, gmlw);\n\n /* If the user specified gamma, do not attempt to optimize it. */\n if (lambda >= 0)\n\trglz_set_lambda(rw, lambda);\n else\n\trglz_estimate_lambda(rw, Lcurve_size);\n\n rglz_solve(coefs, &chisq, &snorm, rw);\n\n rglz_close(rw);\n\n gsl_multifit_linear_free(gmlw);\n return 0;\n}\n\n/* ============================= Python wrapper ============================= */\n\nstatic PyObject*\ngslpy_ridge_fit(PyObject* self, PyObject* args, PyObject* kwargs)\n{\n static char * keywords[] = {\n\t\"X\",\n\t\"y\",\n\t\"sample_weight\",\n\t\"lamb\",\n\t\"ldiag\",\n\t\"lcurve_size\",\n\tNULL,\n };\n\n PyArrayObject\n\t*X=NULL,\n\t*y=NULL,\n\t*w=NULL,\n\t*Ldiag=NULL,\n\t*coefs=NULL;\n\n /* Negative lambda means that lambda is optimized */\n double lambda = -1;\n unsigned long Lcurve_size = 10000;\n\n /* Flag to check if things are set */\n int wei_set = 0;\n int L_set = 0;\n\n /* GSL stuff */\n gsl_vector * g_y;\n gsl_matrix * g_X;\n gsl_vector * g_w;\n gsl_vector * g_coefs;\n \n if (!PyArg_ParseTupleAndKeywords(args,\n kwargs,\n \"O!O!|O!dO!k\",\n keywords,\n &PyArray_Type, &X,\n\t\t\t\t &PyArray_Type, &y,\n\t\t\t\t &PyArray_Type, &w,\n\t\t\t\t &lambda,\n\t\t\t\t &PyArray_Type, &Ldiag,\n\t\t\t\t &Lcurve_size)) {\n return NULL;\n }\n\n \n /* If weights are not given, set them as 1 */\n if (w == NULL)\n {\n\twei_set = 1;\n\tw = (PyArrayObject*) PyArray_ZEROS(PyArray_NDIM(y),\n\t\t\t\t\t PyArray_DIMS(y),\n\t\t\t\t\t NPY_DOUBLE,\n\t\t\t\t\t 0);\n\t\n\tnpy_double * w_data = PyArray_DATA(w);\n\t\n\tfor (npy_intp i = 0; i < PyArray_SIZE(w); ++i)\n\t w_data[i] = 1.0;\n }\n\n /* If Ldiag is not given, set it to identity. */\n if (Ldiag == NULL)\n {\n\tnpy_intp Lshape[] = {PyArray_DIM(X,1)};\n\tL_set = 1;\n\tLdiag = (PyArrayObject*) PyArray_ZEROS(1,\n\t\t\t\t\t Lshape,\n\t\t\t\t\t NPY_DOUBLE,\n\t\t\t\t\t 0);\n\n\tfor (npy_intp i = 0; i < PyArray_DIM(X, 1); i++)\n\t ((double *) PyArray_DATA(Ldiag))[i] = 1.0;\n }\n \n\n /* Convert PyArray objects to gsl types */\n g_y = gsl_vector_calloc(PyArray_DIM(y, 0));\n g_w = gsl_vector_calloc(PyArray_DIM(w, 0));\n g_X = gsl_matrix_calloc(PyArray_DIMS(X)[0], PyArray_DIMS(X)[1]);\n g_coefs = gsl_vector_calloc(PyArray_DIM(X, 1));\n \n for (npy_intp i = 0; i < (npy_intp) g_y->size; i++)\n {\n\tgsl_vector_set(g_y, i, ((double *) PyArray_DATA(y))[i]);\n\tgsl_vector_set(g_w, i, ((double *) PyArray_DATA(w))[i]);\n }\n \n for (npy_intp i = 0; i < PyArray_SIZE(X); i++)\n\tg_X->data[i] = ((double *) PyArray_DATA(X))[i];\n\n /* Run regression */\n gslpy_ridge_regression(g_y, g_X,\n\t\t\t g_w, lambda,\n\t\t\t (double *) PyArray_DATA(Ldiag),\n\t\t\t Lcurve_size, g_coefs);\n \n\n /* Convert g_coefs back to a Python object */\n /* Local scope just to delete ``coefs_shape``after. */\n {\n\tnpy_intp coefs_shape[] = {g_coefs->size, 1};\n\tcoefs = (PyArrayObject *) PyArray_ZEROS(2,\n\t\t\t\t\t\tcoefs_shape,\n\t\t\t\t\t\tNPY_DOUBLE,\n\t\t\t\t\t\t0);\n\tfor (npy_intp i = 0; i < (npy_intp) g_coefs->size; i++)\n\t ((double *) PyArray_DATA(coefs))[i] = gsl_vector_get(g_coefs, i);\n\n }\n \n if (wei_set)\n\tPy_XDECREF(w);\n\n if (L_set)\n\tPy_XDECREF(Ldiag);\n\n gsl_matrix_free(g_X);\n gsl_vector_free(g_y);\n gsl_vector_free(g_w);\n gsl_vector_free(g_coefs);\n\n return (PyObject *) coefs;\n}\n\n/* =========================== Python boilerplate =========================== */\n\nPyDoc_STRVAR(module_doc,\n\t \"Ridge regression model methods using the GNU Scientific Library.\");\n\nPyDoc_STRVAR(fit_doc,\n\t \"Fits a ridge regression model to data.\\n\"\n\t \"fit(X, y, sample_weights=None, lambda=None, ldiag=None, Lcurve_size=10000).\\n\");\n\n\nPyMethodDef methods[] = {\n {\n\t\"fit\",\n\t(PyCFunction) gslpy_ridge_fit,\n\tMETH_VARARGS | METH_KEYWORDS,\n\tfit_doc,\n },\n {NULL},\n};\n\n\nPyModuleDef gslpyridge_module = {\n PyModuleDef_HEAD_INIT,\n \"gslpyridge\",\n module_doc,\n -1,\n methods,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\nPyMODINIT_FUNC\nPyInit_gslpyridge(void)\n{\n import_array();\n return PyModule_Create(&gslpyridge_module);\n}\n", "meta": {"hexsha": "48dfd79b48030d702a6eac0045f1439c4f3d1075", "size": 8651, "ext": "c", "lang": "C", "max_stars_repo_path": "profilerTools/gslpy_ridge/gslpy_ridge.c", "max_stars_repo_name": "mssm-labmmol/profiler", "max_stars_repo_head_hexsha": "6c4a508cd656a8cdf05ab3db19680e6239296a88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T13:06:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T13:40:46.000Z", "max_issues_repo_path": "profilerTools/gslpy_ridge/gslpy_ridge.c", "max_issues_repo_name": "mssm-labmmol/profiler", "max_issues_repo_head_hexsha": "6c4a508cd656a8cdf05ab3db19680e6239296a88", "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": "profilerTools/gslpy_ridge/gslpy_ridge.c", "max_forks_repo_name": "mssm-labmmol/profiler", "max_forks_repo_head_hexsha": "6c4a508cd656a8cdf05ab3db19680e6239296a88", "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.3695014663, "max_line_length": 103, "alphanum_fraction": 0.6051323546, "num_tokens": 2592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.46143670963089645}} {"text": "/*\nMatrix multiplication.\n\nBased on the amazing:\nhttps://github.com/HandsOnOpenCL/Exercises-Solutions/tree/a908ac3f0fadede29f2735eb1264b0db7f4311a0/Solutions/Exercise08\n\nThe most basic / useful application where OpenCL might be faster than CPU.\n\nTODO: make a SERIOUS matrix implementation. Also compare with existing SERIOUS CPU and GPU implementations:\n\n- http://stackoverflow.com/questions/1907557/optimized-matrix-multiplication-in-c\n- http://stackoverflow.com/questions/12289235/simple-and-fast-matrix-vector-multiplication-in-c-c\n- https://www.quora.com/What-is-the-best-way-to-multiply-two-matrices-in-C++\n- http://stackoverflow.com/questions/25900312/optimizing-batched-matrix-multiplication-opencl-code\n\nSerious CPU implementation means it considers:\n\n- caching\n- SIMD\n\nArticles:\n\n- http://www.netlib.org/utk/papers/autoblock/node2.html\n- http://codereview.stackexchange.com/questions/101144/simd-matrix-multiplication\n*/\n\n#include \"common.h\"\n\n#include \n#include \n\n#define NELEMS(a) sizeof(a)/sizeof(a[0])\n#define UNUSED(x) (void)(x)\n\n/* TODO how to auto tune this?\n * GCC 6 was not smart enough to use widest type automatically:\n * anything larger than the widest type just dropped perf drastically. */\n#define VECTOR_NELEMS 4\n#define VECTOR_SIZEOF (VECTOR_NELEMS * sizeof(F))\n\ntypedef cl_float F;\ntypedef F Vec __attribute__ ((vector_size(VECTOR_SIZEOF)));\n/* Stuff reused across OpenCL calls.\n * It would not be fair to consider their alocation time for each call,\n * as the functions will be called millions of times.\n *\n * TODO: also factor out the kernel compile time.\n * Currently recompiled every time.\n * Implementations already cache compiled kernels, but we would need\n * to call each function multiple times.\n * */\ntypedef struct {\n Common common;\n /* We only factor out the allocation of those buffers.\n * Data transfer time with clEnqueueWriteBuffer must still be considered. */\n cl_mem buf_a, buf_b, buf_c;\n} Cache;\ntypedef void (*MatMul)(const F *A, const F *B, F *C, size_t n, Cache *cache);\n\nvoid cl_buf_init(Cache *cache, size_t mat_sizeof) {\n cache->buf_a = clCreateBuffer(cache->common.context, CL_MEM_READ_ONLY, mat_sizeof, NULL, NULL);\n cache->buf_b = clCreateBuffer(cache->common.context, CL_MEM_READ_ONLY, mat_sizeof, NULL, NULL);\n cache->buf_c = clCreateBuffer(cache->common.context, CL_MEM_WRITE_ONLY, mat_sizeof, NULL, NULL);\n}\n\nvoid cl_buf_deinit(Cache *cache) {\n clReleaseMemObject(cache->buf_a);\n clReleaseMemObject(cache->buf_b);\n clReleaseMemObject(cache->buf_c);\n}\n\n/* No, this was not created for debugging, my code is flawless from the first try. */\nvoid mat_print(const F *A, size_t n) {\n size_t i, j;\n for (i = 0; i < n; ++i) {\n for (j = 0; j < n; ++j) {\n printf(\"%f \", A[i*n+j]);\n }\n puts(\"\");\n }\n}\n\n/* Zero a matrix. */\nvoid mat_zero(F *A, size_t n) {\n size_t i, n2;\n n2 = n*n;\n for (i = 0; i < n2; ++i) {\n A[i] = 0.0;\n }\n}\n\n/* Initialize a random matrix. */\nvoid mat_rand(F *A, size_t n) {\n size_t i, n2;\n n2 = n*n;\n for (i = 0; i < n2; ++i) {\n A[i] = ((float)rand()) / ((float)RAND_MAX);\n }\n}\n\n/* Initialize a random matrix. */\nvoid mat_trans(F *A, size_t n) {\n size_t i, j, i1, i2;\n F tmp;\n for (i = 0; i < n; ++i) {\n for (j = 0; j < i; ++j) {\n i1 = i*n+j;\n i2 = j*n+i;\n tmp = A[i1];\n A[i1] = A[i2];\n A[i2] = tmp;\n }\n }\n}\n\n/* Check if two matrices are equal with given mean squared err_maxor. */\nint mat_eq(const F *A, const F *B, size_t n) {\n const F err_max = 10e-3;\n F err, diff, a, b;\n size_t i, i_max;\n\n err = 0.0;\n i_max = n*n;\n for (i = 0; i < i_max; ++i) {\n a = A[i];\n b = B[i];\n diff = a - b;\n err += diff * diff;\n }\n return (sqrt(err) / i_max) < err_max;\n}\n\nvoid mat_assert_eq(const F *A, const F *B, size_t n) {\n if (!mat_eq(A, B, n)) {\n puts(\"\");\n mat_print(A, n);\n puts(\"\");\n mat_print(B, n);\n assert(0);\n }\n}\n\nsize_t zmin(size_t x, size_t y) {\n return (x < y) ? x : y;\n}\n\n/* C = A*B, width n, naive. */\nvoid mat_mul_cpu(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n F tmp;\n size_t i, j, k;\n UNUSED(cache);\n\n for (i = 0; i < n; ++i) {\n for (j = 0; j < n; ++j) {\n tmp = 0.0;\n for (k = 0; k < n; ++k) {\n tmp += A[i*n+k] * B[k*n+j];\n }\n C[i*n+j] = tmp;\n }\n }\n}\n\n/* Transpose matrix B to increase cache hits. */\nvoid mat_mul_cpu_trans(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n F tmp;\n size_t i, j, k;\n UNUSED(cache);\n\n mat_trans((F*)B, n);\n for (i = 0; i < n; ++i) {\n for (j = 0; j < n; ++j) {\n tmp = 0.0;\n for (k = 0; k < n; ++k) {\n tmp += A[i*n+k] * B[j*n+k];\n }\n C[i*n+j] = tmp;\n }\n }\n mat_trans((F*)B, n);\n}\n\n/* Zero vector. */\nvoid vec_zero(Vec *vec, size_t vec_n) {\n size_t i;\n for (i = 0; i < vec_n; ++i) {\n (*vec)[i] = 0.0;\n }\n}\n\n/* Load vector from array. */\nvoid vec_load(Vec *vec, size_t vec_n, const F* A, size_t A_base) {\n size_t i;\n for (i = 0; i < vec_n; ++i) {\n (*vec)[i] = A[A_base + i];\n }\n}\n\n/* Sum elements of the vector. */\nF vec_sum(Vec vec, size_t vec_n) {\n size_t i;\n F sum;\n sum = 0.0;\n for (i = 0; i < vec_n; ++i) {\n sum += vec[i];\n }\n return sum;\n}\n\n/* Transpose matrix B to both:\n *\n * - increase cache hits\n * - simd GCC vector extensions which is made possible.\n * by the transposition, to increase likelyhood of SIMDs.\n *\n * Note that GCC 6 O=3 is smart enough to use SIMD\n * even for the naive CPU method. However this was still way faster.\n * */\nvoid mat_mul_cpu_trans_vec(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n F tmpf;\n size_t i, j, k, k_max, ai, bi;\n Vec tmp, a, b;\n UNUSED(cache);\n\n mat_trans((F*)B, n);\n k_max = (n / VECTOR_NELEMS) * VECTOR_NELEMS;\n for (i = 0; i < n; ++i) {\n for (j = 0; j < n; ++j) {\n vec_zero(&tmp, VECTOR_NELEMS);\n for (k = 0; k < k_max; k += VECTOR_NELEMS) {\n ai = i * n + k;\n bi = j * n + k;\n vec_load(&a, VECTOR_NELEMS, A, ai);\n vec_load(&b, VECTOR_NELEMS, B, bi);\n tmp += a * b;\n }\n tmpf = 0.0;\n for (; k < n; ++k) {\n tmpf += A[i*n+k] * B[j*n+k];\n }\n C[i*n+j] = vec_sum(tmp, VECTOR_NELEMS) + tmpf;\n }\n }\n mat_trans((F*)B, n);\n}\n\n/* Blocked matrix multiplication.\n * TODO slower than transpose, sometimes similar timing to naive.\n * Why do they say that this is better?\n * */\nvoid mat_mul_cpu_block(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n size_t ib, jb, kb, i, j, k, i_max, j_max, k_max, nb ;\n F tmp;\n UNUSED(cache);\n\n nb = lround(sqrt(n));\n for (ib = 0; ib < n; ib += nb) {\n i_max = zmin(ib + nb, n);\n for (jb = 0; jb < n; jb += nb) {\n k_max = zmin(jb + nb, n);\n for (kb = 0; kb < n; kb += nb) {\n j_max = zmin(kb + nb, n);\n\n /* TODO would be cool to recurse here, but would require more offset parameters,\n * likely similar to tose of CBLAS. */\n for (i = ib; i < i_max; ++i) {\n for (j = kb; j < j_max; ++j) {\n tmp = 0.0;\n for (k = jb; k < k_max; ++k) {\n tmp += A[i*n+k] * B[k*n+j];\n }\n C[i*n+j] += tmp;\n }\n }\n }\n }\n }\n}\n\n/* The golden single thread CPU standard. */\nvoid mat_mul_cpu_cblas(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n UNUSED(cache);\n cblas_sgemm(\n CblasRowMajor,\n CblasNoTrans,\n CblasNoTrans,\n n,\n n,\n n,\n 1.0,\n A,\n n,\n B,\n n,\n 0.0,\n C,\n n\n );\n}\n\n/* Simplest possible CL implementation. No speedup. */\nvoid mat_mul_cl(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n cl_uint ncl;\n size_t global_work_size[2], mat_sizeof;\n\n /* Setup variables. */\n global_work_size[0] = n;\n global_work_size[1] = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n common_create_kernel_file(&cache->common, \"matmul.cl\", NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, sizeof(ncl), &ncl);\n clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 2, NULL, global_work_size, NULL, 0, NULL, NULL);\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\n/* Cache rows in private memory. Drastic speedups expected over naive CPU. */\nvoid mat_mul_cl_row_priv(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n char options[256];\n cl_uint ncl;\n size_t global_work_size, mat_sizeof;\n\n /* Setup variables. */\n global_work_size = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n snprintf(options, sizeof(options), \"-DPRIV_ROW_SIZE=%ju\", n);\n common_create_kernel_file(&cache->common, \"matmul_row_priv.cl\", options);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, sizeof(ncl), &ncl);\n clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, NULL, 0, NULL, NULL);\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\n/* Let's see if this is any different from local memory.\n * Outcome: much slower than private memory, slower than naive method. */\nvoid mat_mul_cl_row_local(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n cl_uint ncl;\n size_t global_work_size, local_work_size, mat_sizeof;\n\n /* Setup variables. */\n /* Cannot be larger than 1 on this example, otherwise memory conflicts\n * will happen between work items. */\n local_work_size = 1;\n global_work_size = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n common_create_kernel_file(&cache->common, \"matmul_row_local.cl\", NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, n * sizeof(F), NULL);\n clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl);\n clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\n/* Like row private, but to reduce global memory accesses,\n * we copy only once per work group to local memory.\n *\n * Each work group contains a few rows of A.\n *\n * We load the first column, multiply all rows by that column, synrhconize,\n * load another column, and so on.\n *\n * This leads to a thread blockage / memory access tradeoff.\n *\n * We make work groups as large as possible to reload memory less times. */\nvoid mat_mul_cl_row_priv_col_local(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n char options[256];\n cl_uint ncl;\n size_t global_work_size, local_work_size, mat_sizeof;\n\n /* Setup variables. */\n global_work_size = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n snprintf(options, sizeof(options), \"-DPRIV_ROW_SIZE=%ju\", n);\n common_create_kernel_file(&cache->common, \"matmul_row_priv_col_local.cl\", options);\n local_work_size = 0;\n clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(local_work_size), &local_work_size, NULL);\n local_work_size = zmin(local_work_size, n);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, n * sizeof(F), NULL);\n clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl);\n clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\n/* Copy as many cols from B as possibl to the local memory, only then start multiplying.\n * This leads to less memory barrier hits.\n * How many rows we copy is limited by the local memory size, ideally the entire matrix will fit. */\nvoid mat_mul_cl_row_priv_cols_local(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n char options[256];\n cl_uint ncl, n_local_cols;\n cl_ulong local_mem_size;\n size_t col_size, global_work_size, local_work_size, mat_sizeof;\n\n /* Setup variables. */\n col_size = n * sizeof(F);\n global_work_size = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n snprintf(options, sizeof(options), \"-DPRIV_ROW_SIZE=%ju\", n);\n common_create_kernel_file(&cache->common, \"matmul_row_priv_cols_local.cl\", options);\n local_work_size = 0;\n clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(local_work_size), &local_work_size, NULL);\n local_work_size = zmin(local_work_size, n);\n local_mem_size = 0;\n clGetDeviceInfo(cache->common.device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(local_mem_size), &local_mem_size, NULL);\n /* TODO: can blow up without that - 1. Why?\n * It only reaches the max without it, not crosses, right?\n * So bug in the kernel? */\n n_local_cols = zmin(local_mem_size / col_size, n) - 1;\n /*puts(\"\");*/\n /*printf(\"max memory %llu\\n\", (unsigned long long)local_mem_size);*/\n /*printf(\"n_local_cols %llu\\n\", (unsigned long long)n_local_cols);*/\n /*printf(\"memory %llu\\n\", (unsigned long long)n_local_cols * n * sizeof(F));*/\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, n_local_cols * col_size, NULL);\n clSetKernelArg(cache->common.kernel, 4, sizeof(ncl), &ncl);\n clSetKernelArg(cache->common.kernel, 5, sizeof(n_local_cols), &n_local_cols);\n clEnqueueNDRangeKernel(cache->common.command_queue, cache->common.kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\nvoid mat_mul_cl_block(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n cl_uint ncl, nblkcl;\n size_t global_work_size[2], local_work_size[2], mat_sizeof, nblk;\n\n /* Setup variables. */\n global_work_size[0] = n;\n global_work_size[1] = n;\n mat_sizeof = n * n * sizeof(F);\n ncl = n;\n\n /* Run kernel. */\n common_create_kernel_file(&cache->common, \"matmul_block.cl\", NULL);\n clGetDeviceInfo(cache->common.device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(nblk), &nblk, NULL);\n nblk = sqrt(zmin(nblk, n));\n nblk = zmin(nblk, 3);\n nblkcl = nblk;\n local_work_size[0] = nblk;\n local_work_size[1] = nblk;\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clSetKernelArg(cache->common.kernel, 0, sizeof(cache->buf_a), &cache->buf_a);\n clSetKernelArg(cache->common.kernel, 1, sizeof(cache->buf_b), &cache->buf_b);\n clSetKernelArg(cache->common.kernel, 2, sizeof(cache->buf_c), &cache->buf_c);\n clSetKernelArg(cache->common.kernel, 3, nblk * nblk * sizeof(F), NULL);\n printf(\"nblk = %llu\\n\", (unsigned long long)nblk);\n printf(\"local memory = %llu\\n\", (unsigned long long)2 * nblk * nblk * sizeof(F));\n clSetKernelArg(cache->common.kernel, 4, nblk * nblk * sizeof(F), NULL);\n clSetKernelArg(cache->common.kernel, 5, sizeof(ncl), &ncl);\n clSetKernelArg(cache->common.kernel, 6, sizeof(nblkcl), &nblkcl);\n clEnqueueNDRangeKernel(\n cache->common.command_queue, cache->common.kernel, 2, NULL,\n global_work_size, local_work_size, 0, NULL, NULL\n );\n clFlush(cache->common.command_queue);\n clFinish(cache->common.command_queue);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\nvoid mat_mul_cl_clblas(const F *A, const F *B, F *C, size_t n, Cache *cache) {\n cl_event event;\n size_t mat_sizeof;\n\n mat_sizeof = n * n * sizeof(F);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_a, CL_TRUE, 0, mat_sizeof, (F*)A, 0, NULL, NULL);\n clEnqueueWriteBuffer(cache->common.command_queue, cache->buf_b, CL_TRUE, 0, mat_sizeof, (F*)B, 0, NULL, NULL);\n clblasSgemm(\n clblasRowMajor,\n clblasNoTrans,\n clblasNoTrans,\n\n n,\n n,\n n,\n 1.0,\n\n cache->buf_a,\n 0,\n n,\n\n cache->buf_b,\n 0,\n n,\n\n 0.0,\n cache->buf_c,\n 0,\n n,\n\n 1,\n &(cache->common.command_queue),\n 0,\n NULL,\n &event\n );\n clWaitForEvents(1, &event);\n clEnqueueReadBuffer(cache->common.command_queue, cache->buf_c, CL_TRUE, 0, mat_sizeof, C, 0, NULL, NULL);\n}\n\ndouble bench(MatMul f, const F *A, const F *B, F *C, F *C_ref, size_t n, Cache *cache) {\n double dt, time;\n mat_zero(C, n);\n time = common_get_nanos();\n f(A, B, C, n, cache);\n dt = common_get_nanos() - time;\n if (C_ref != NULL)\n mat_assert_eq(C, C_ref, n);\n printf(\"%.3e \", dt);\n fflush(stdout);\n return dt;\n}\n\nint main(int argc, char **argv) {\n srand(time(NULL));\n Cache cache;\n double max_runtime;\n /* Overly slow ones commented out by default. */\n MatMul mat_mul_funcs[] = {\n /*mat_mul_cpu,*/\n mat_mul_cpu_trans,\n mat_mul_cpu_trans_vec,\n mat_mul_cpu_block,\n mat_mul_cpu_cblas,\n /*mat_mul_cl,*/\n mat_mul_cl_row_priv,\n mat_mul_cl_row_local,\n mat_mul_cl_row_priv_col_local,\n mat_mul_cl_row_priv_cols_local,\n /* TODO broken for larger matrics, some cells contain trash.\n * Likey some memory overflow problem. */\n /*mat_mul_cl_block,*/\n mat_mul_cl_clblas,\n };\n int first, func_done[NELEMS(mat_mul_funcs)] = {0};\n size_t f, i;\n size_t mat_sizeof;\n\n /* CLI args. */\n if (argc > 1) {\n max_runtime = strtod(argv[1], NULL);\n } else {\n max_runtime = 1.0;\n }\n\n common_init(&(cache.common), NULL);\n\n /* Unit test 2x2. */\n {\n const F A[] = {\n 1.0, 2.0,\n 3.0, 4.0\n };\n const F B[] = {\n 5.0, 6.0,\n 7.0, 8.0\n };\n enum N { n = 2 };\n F C[n*n];\n const F C_ref[] = {\n 19.0, 22.0,\n 43.0, 50.0\n };\n cl_buf_init(&cache, n * n * sizeof(F));\n for (f = 0; f < sizeof(mat_mul_funcs)/sizeof(mat_mul_funcs[0]); ++f) {\n mat_zero(C, n);\n mat_mul_funcs[f](A, B, C, n, &cache);\n mat_assert_eq(C, C_ref, n);\n }\n cl_buf_deinit(&cache);\n }\n\n /* Unit test 4x4. */\n {\n const F A[] = {\n 1.0, 2.0, 3.0, 4.0,\n 5.0, 6.0, 7.0, 8.0,\n 9.0, 10.0, 11.0, 12.0,\n 13.0, 14.0, 15.0, 16.0,\n };\n const F B[] = {\n 17.0, 18.0, 19.0, 20.0,\n 21.0, 22.0, 23.0, 24.0,\n 25.0, 26.0, 27.0, 28.0,\n 29.0, 30.0, 31.0, 32.0,\n };\n const F C_ref[] = {\n 250.0, 260.0, 270.0, 280.0,\n 618.0, 644.0, 670.0, 696.0,\n 986.0, 1028.0, 1070.0, 1112.0,\n 1354.0, 1412.0, 1470.0, 1528.0,\n };\n enum N { n = 4 };\n F C[n*n];\n cl_buf_init(&cache, n * n * sizeof(F));\n for (f = 0; f < NELEMS(mat_mul_funcs); ++f) {\n mat_zero(C, n);\n mat_mul_funcs[f](A, B, C, n, &cache);\n mat_assert_eq(C, C_ref, n);\n }\n cl_buf_deinit(&cache);\n }\n\n /* Benchmarks. */\n {\n double dt;\n F *A = NULL, *B = NULL, *C = NULL, *C_ref = NULL, *dst = NULL, *ref = NULL;\n int done;\n size_t n = 2;\n\n puts(\"#matmul\");\n done = 0;\n while(1) {\n printf(\"%zu \", (size_t)log2(n));\n mat_sizeof = n * n * sizeof(F);\n\n /* CPU setup. */\n A = aligned_alloc(VECTOR_SIZEOF, mat_sizeof);\n B = aligned_alloc(VECTOR_SIZEOF, mat_sizeof);\n C = aligned_alloc(VECTOR_SIZEOF, mat_sizeof);\n C_ref = aligned_alloc(VECTOR_SIZEOF, mat_sizeof);\n if (NULL == A || NULL == B || NULL == C) {\n printf(\"error: could not allocate memory for n = %zu\", n);\n break;\n }\n mat_rand(A, n);\n mat_rand(B, n);\n\n cl_buf_init(&cache, mat_sizeof);\n first = 1;\n for (f = 0; f < NELEMS(mat_mul_funcs); ++f) {\n if (func_done[f]) {\n printf(\"%*s\", 10, \"\");\n } else {\n if (first) {\n dst = C_ref;\n ref = NULL;\n first = 0;\n } else {\n dst = C;\n ref = C_ref;\n }\n dt = bench(mat_mul_funcs[f], A, B, dst, ref, n, &cache);\n if (dt > max_runtime)\n func_done[f] = 1;\n }\n }\n puts(\"\");\n done = 1;\n for (i = 0; i < NELEMS(mat_mul_funcs); ++i) {\n if (!func_done[i]) {\n done = 0;\n break;\n }\n }\n if (done)\n break;\n n *= 2;\n\n /* CPU deinit. */\n free(A);\n free(B);\n free(C);\n free(C_ref);\n\n cl_buf_deinit(&cache);\n }\n common_deinit(&cache.common);\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "2dfd4757560ee25430cd77fb4c395de420429ca1", "size": 24639, "ext": "c", "lang": "C", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/opencl/interactive/matmul.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/opencl/interactive/matmul.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/opencl/interactive/matmul.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": 34.4120111732, "max_line_length": 139, "alphanum_fraction": 0.5865091927, "num_tokens": 7361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6757646140788308, "lm_q1q2_score": 0.4612591762154906}} {"text": "#if !defined (RAND_H)\n#define RAND_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nconst double TOLERANCE = numeric_limits::epsilon();\nconst int INTMAX = numeric_limits::max();\n\nconst int BIGPRIME = 899999963;\nconst double PI = 3.1415926535897932384626433832795028841971693993751;\n\ntypedef double (*FUNC)(const double, const double, const double);\ninline double fx(const double htilde, const double y, const double u) \n{\n return (pow(htilde,y+1) - (y+1)*htilde + fabs(2*u-1)*y);\n} \n\n\ninline int Getnode(list& X, int index)\n{\n int pos=0;\n for(list::iterator p = X.begin(); p!= X.end(); p++, pos++) {\n if(pos==index) \n return (*p);\n }\n\n return -1;\n}\n\nclass Rand {\n double c,cd,cm,u[97];\n int i97,j97 ;\n bool outputReady;\n double output;\n\n int idum; \n\n public:\n Rand(int seed) {\n ranmarin(fabs(seed%BIGPRIME));\n outputReady=false;\n idum=-1*seed; \n\n flag_setFvector = false;\n flag_setPvector = false;\n }\n\n Rand() {\n ranmarin(1);\n outputReady=false;\n idum=-1;\n\n flag_setFvector = false;\n flag_setPvector = false;\n }\n\n void seed(int seed) {\n ranmarin(fabs(seed%BIGPRIME));\n outputReady=false;\n idum=-1*seed; \n\n flag_setFvector = false;\n flag_setPvector = false;\n }\n\n\n double ran() { return rand()/(double)RAND_MAX;}\n \n double uniform()\n {\n double uni;\n\t\n uni=u[i97]-u[j97];\n if (uni<0.0) uni+=1.0;\n u[i97]=uni;\n if (--i97<0) i97=96;\n if (--j97<0) j97=96;\n c-=cd;\n if (c<0.0) c+=cm;\n uni-=c;\n if (uni<0.0) uni+=1.0;\n return(uni);\n }\n\n double ran1()\n {\n const int IA=16807,IM=2147483647,IQ=127773,IR=2836,NTAB=32;\n const int NDIV=(1+(IM-1)/NTAB);\n const double EPS=3.0e-16,AM=1.0/IM,RNMX=(1.0-EPS);\n static int iy=0;\n static vector iv(NTAB);\n int j,k;\n double temp;\n\n if (idum <= 0 || !iy) {\n if (-idum < 1) idum=1;\n else idum = -idum;\n for (j=NTAB+7;j>=0;j--) {\n\tk=idum/IQ;\n\tidum=IA*(idum-k*IQ)-IR*k;\n\tif (idum < 0) idum += IM;\n\tif (j < NTAB) iv[j] = idum;\n }\n iy=iv[0];\n }\n k=idum/IQ;\n idum=IA*(idum-k*IQ)-IR*k;\n if (idum < 0) idum += IM;\n j=iy/NDIV;\n iy=iv[j];\n iv[j] = idum;\n if ((temp=AM*iy) > RNMX) return RNMX;\n else return temp;\n }\n\n\n\n int discrete(int min, int max)\n {\n int ret= (int)(floor(ran1()*(max+1-min)+min));\n return ret;\n }\n\n\n void discrete(int min, int max, int& a, int& b)\n {\n a = (int)(floor(ran1()*(max+1-min)+min));\n \n do {\n b = (int)(floor(ran1()*(max+1-min)+min));\n } while (a==b);\n \n }\n\n\n void discrete(int min, int max, int& a, int& b, int& c)\n {\n a = (int)(floor(ran1()*(max+1-min)+min));\n \n do {\n b = (int)(floor(ran1()*(max+1-min)+min));\n } while (b==a);\n\n do {\n c = (int)(floor(ran1()*(max+1-min)+min));\n } while (c==b || c==a);\n \n }\n\n\n void discrete(int min, int max, int& a, int& b, int& c, int& d)\n {\n a = (int)(floor(ran1()*(max+1-min)+min));\n \n do {\n b = (int)(floor(ran1()*(max+1-min)+min));\n } while (b==a);\n\n do {\n c = (int)(floor(ran1()*(max+1-min)+min));\n } while (c==b || c==a);\n\n do {\n d = (int)(floor(ran1()*(max+1-min)+min));\n } while (d==c || d==b || d==a);\n \n }\n\n\n void discrete(int min, int max, int n, set& Set)\n {\n Set.clear();\n for(int i=0; i& Vec)\n {\n set Set;\n \n Vec.clear();\n for(int i=0; ixmax)\n b = xmax;\n \n int x = discrete(a,b);\n return x;\n }\n\n\n\n void randomsubset(int N, int Nc, vector& S)\n {\n list Lbig;\n for(int i=0; iN0) ? (N0-Nc) : Nc;\n \n list Lsmall;\n for(int i=0; iN0) \n copy(Lbig.begin(), Lbig.end(), S.begin());\n else\n copy(Lsmall.begin(), Lsmall.end(), S.begin());\n\n }\n\n void randomsubset_knuth(int n, int m, vector& S)\n { \n for (int i = 0; i < n; i++)\n if ((discrete(1,n) % (n-i)) < m) {\n\tS.push_back(i);\n\tm--;\n }\n }\n\n\n void randomsubset_shuf(int n, int m, vector& S)\n { \n int i,j,t;\n vector x(n);\n for (i = 0; i < n; i++)\n x[i] = i;\n for (i = 0; i < m; i++) {\n j = discrete(i, n-1);\n t = x[i]; \n x[i] = x[j]; \n x[j] = t;\n }\n sort(x.begin(), x.begin()+m);\n for (i = 0; i< m; i++)\n S.push_back(x[i]);\n }\n\n void randomsubset_shuffle(int n, int m, vector& S)\n { \n vector x(n);\n for(int i=0; i=1.0);\n\n z=sqrt(-2.0*log(Rsq)/Rsq);\n output = v1*z*sd;\n outputReady=true;\n return v2*z*sd;\n }\n\n double lorentzian(double sd) \n {\n double v1,v2,z;\n do {\n v2 = uniform();\n v1 = 2.0 * uniform() - 1.0;\n } while ((v1*v1+v2*v2)>1.0);\n z = v2/v1;\n return sd*z/2.0;\n }\n\n double powerlaw_continuous(double alpha, double xmin)\n {\n return ( xmin*pow(1-ran1(), 1./(1-alpha) ) );\n }\n\n double powerlaw_continuous_interval(double a, double beta)\n {\n return pow( (1- (1-ran1())*(1-pow(a, 1-beta))), 1/(1-beta) );\n }\n\n\n int powerlaw_discrete_approximate(double alpha, double xmin)\n {\n double r = ran1();\n int k = (int)( (xmin-0.5)*pow(1-r, 1./(1-alpha) ) + 0.5 );\n if(k<0) {\n cout << 1-r << ',' << k << endl;\n k = INTMAX;\n }\n return k;\n\n }\n\n\n int powerlaw_discrete(double alpha, int xmin)\n {\n if(!flag_setPvector)\n SetPvector(alpha,xmin);\n\n double r = ran1();\n int j = Findj(P, 1-r);\n return j;\n\n }\n \n\n\n\n\n\n int powerlaw_exponentialcutoff_discrete(double gamma, double kappa)\n {\n if(!flag_setPvector)\n SetPvector_SFEC(gamma, kappa);\n\n double r = ran1();\n\n int j = Findj(P, 1-r);\n return j;\n\n }\n \n int arbitrary_discrete(vector& CDF)\n {\n double r = ran1();\n int j = Findj(CDF, r);\n return j+1;\n }\n\n int arbitrary_discrete(vector& CDF)\n {\n double r = ran1();\n int j = Findj(CDF, r);\n return j+1;\n }\n\n\n\n double lognormal(double sd) \n {\n double v1,v2,Rsq,z;\n if(outputReady)\n {\n\toutputReady = false;\n\treturn output;\n }\n\n do\n {\n\tv1=(ran1()*2.0)-1.0; \n\tv2=(ran1()*2.0)-1.0; \n\tRsq=v1*v1+v2*v2;\n } while (Rsq>=1.0);\n\n z=sqrt(-2.0*log(Rsq)/Rsq);\n output = exp(v1*z*sd);\n outputReady=true;\n return exp(v2*z*sd);\n }\n\n\n \n double bimodal(double R)\n {\n \n return (ran1()>0.5) ? (R) : (-R);\n }\n\n \n double rectangular(double R)\n {\n \n return ((ran1()*2-1)*R); \n }\n\n\n \n \n \n \n \n \n\n \n \n \n \n \n \n double parabolic(double R)\n {\n \n double x = ran1();\n\n int sign = (x>0.5) ? (-1) : (+1);\n\n double R2 = R*R;\n double R3 = R2*R;\n\n double q = 4*R3*(x-0.5);\n double p = -3*R2;\n double Disc = q*q/4. + p*p*p/27.;\n double r = R3;\n double theta = atan(sqrt(-Disc)/(-q/2.));\n double ronethird = pow(r,1/3.);\n\t \n double h1 = sign * 2 * ronethird * cos(theta/3.);\n double h2 = sign * 2 * ronethird * cos((theta+2*PI)/3.);\n double h3 = sign * 2 * ronethird * cos((theta-2*PI)/3.);\n\n double y = 0;\n if(h1(-R)) \n y = h1;\n else if(h2(-R)) \n y = h2;\n else if(h3(-R)) \n y = h3;\n else\n cout << \"range is wrong!\";\n\t\n \n\n return y;\n }\n\n\n\n \n \n \n \n \n \n \n\n double antiparabolic(double R)\n {\n \n double x = ran1();\n\n int sign = (x>0.5) ? (+1) : (-1);\n\n double h = sign * pow(sign*(2*x-1),1./3.) * R;\n return h;\n }\n\n\n\n\n \n \n \n \n \n \n \n\n \n \n \n \n \n \n double DMI_lookuptable(double y, double R)\n \n {\n if(!flag_setFvector)\n SetFvector(y,R);\n\n double u = ran1();\n int j = Findj(F, u);\n double h = -R + j*dh;\n\n return h;\n }\n\n\n \n \n double DMI(double y, double R)\n {\n double u = ran1();\n int sign = (u>0.5) ? (+1) : (-1);\n\n \n \n \n \n\n const double hacc = 1e-12;\n double htilde = rtbis(&fx, y, u, 0, 1, hacc);\n double h = sign*htilde*R;\n return h;\n }\n \n\n\n \n \n \n \n \n \n int exponential(double kappa)\n {\n double u = ran1();\n \n int k = -kappa * log(1-u); \n return k;\n }\n \n \n\n\n\n private:\n\n \n \n\n\n \n \n \n \n \n\n bool flag_setFvector;\n vector F;\n double dh;\n\n double P_DMI(double h, double y, double R)\n {\n if(h<-R || h>R) return 0;\n else return (y+1)/(2*y*R)*(1-pow(fabs(h)/R,y));\n }\n\n void SetFvector(double y, double R)\n {\n int N = 10000001; \n dh = R/(double)(N-1);\n F.resize(2*N-1,0);\n\t \n \n\n F[0] = 0;\n F[2*N-2] = 1 - F[0];\n for(int i=1;i& xx, const double x)\n {\n int j,jl,jm,ju;\n int n=xx.size();\n\n jl=-1; ju=n; \n\n bool ascnd = (xx[n-1] >= xx[0]); \n while (ju-jl > 1) \n {\n\tjm=(ju+jl) >> 1; \n\tif ((x >= xx[jm]) == ascnd) jl=jm; \n\telse \t ju=jm; \n }\n\t \n if (x == xx[0]) j=0;\n else if (x == xx[n-1]) j=n-2;\n else j=jl;\n\n return j;\n }\n\n int Findj(vector& xx, const double x)\n {\n int j,jl,jm,ju;\n int n=xx.size();\n\n jl=-1; ju=n; \n\n bool ascnd = (xx[n-1] >= xx[0]); \n while (ju-jl > 1) \n {\n\tjm=(ju+jl) >> 1; \n\tif ((x >= xx[jm]) == ascnd) jl=jm; \n\telse \t ju=jm; \n }\n\t \n if (x == xx[0]) j=0;\n else if (x == xx[n-1]) j=n-2;\n else j=jl;\n\n return j;\n }\n\n \n \n\n\n \n \n \n\n\n \n \n double rtbis(FUNC func, const double y, const double u, const double x1, const double x2, const double xacc)\n {\n const int JMAX=40; \n int j;\n double dx,f,fmid,xmid,rtb;\n\t \n f=func(x1,y,u);\n fmid=func(x2,y,u);\n if (f*fmid >= 0.0) \n cout << \"Root must be bracketed for bisection in rtbis\\n\";\n\t \n rtb = f < 0.0 ? (dx=x2-x1,x1) : (dx=x1-x2,x2);\n for (j=0;j=32) s+=t;\n\tt*=0.5;\n }\n u[ii]=s;\n }\n c=362436.0/16777216.0;\n cd=7654321.0/16777216.0;\n cm=16777213.0/16777216.0;\n i97=96;\n j97=32;\n }\n\t\n\n\n \n \n \n bool flag_setPvector;\n vector P;\n\n \n \n double Hzeta(double s, double q)\n {\n double sum = 0;\n double nterm = 0;\n int n;\n for(n=0; ;n++)\n {\n\tnterm = pow((n+q),-s);\n\tsum += nterm;\n\n\tif(fabs(nterm/sum) < TOLERANCE)\n\t break;\n }\n cout << \"nmax= \" << n << endl; \n return sum;\n }\n\n void SetPvector(double alpha, int xmin)\n {\n \n double a = gsl_sf_hzeta(alpha, xmin);\n \n\n int N = 10000000+xmin; \n\n P.resize(N,2);\n \n \n \n \n\n P[xmin] = 1; \n for(int i=xmin;i\n\n#include \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/* Power of 2 routines */\n\n\nint gsl_fft_complex_radix2_forward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_backward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_inverse (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_transform (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n,\n const gsl_fft_direction sign);\n\nint gsl_fft_complex_radix2_dif_forward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_dif_backward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_dif_inverse (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n);\n\nint gsl_fft_complex_radix2_dif_transform (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n,\n const gsl_fft_direction sign);\n\nint gsl_fft_complex_bitreverse_order (gsl_complex_packed_array data,\n size_t stride,\n size_t n,\n size_t n_bits);\n\n/* Mixed Radix general-N routines */\n\ntypedef struct\n {\n size_t n;\n size_t nf;\n size_t factor[64];\n gsl_complex *twiddle[64];\n gsl_complex *trig;\n }\ngsl_fft_complex_wavetable;\n\ntypedef struct\n{\n size_t n;\n double *scratch;\n}\ngsl_fft_complex_workspace;\n\n\ngsl_fft_complex_wavetable *gsl_fft_complex_wavetable_alloc (size_t n);\n\nvoid gsl_fft_complex_wavetable_free (gsl_fft_complex_wavetable * wavetable);\n\ngsl_fft_complex_workspace *gsl_fft_complex_workspace_alloc (size_t n);\n\nvoid gsl_fft_complex_workspace_free (gsl_fft_complex_workspace * workspace);\n\nint gsl_fft_complex_memcpy (gsl_fft_complex_wavetable * dest,\n gsl_fft_complex_wavetable * src);\n\n\nint gsl_fft_complex_forward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n,\n const gsl_fft_complex_wavetable * wavetable,\n gsl_fft_complex_workspace * work);\n\nint gsl_fft_complex_backward (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n,\n const gsl_fft_complex_wavetable * wavetable,\n gsl_fft_complex_workspace * work);\n\nint gsl_fft_complex_inverse (gsl_complex_packed_array data,\n const size_t stride,\n const size_t n,\n const gsl_fft_complex_wavetable * wavetable,\n gsl_fft_complex_workspace * work);\n\nint gsl_fft_complex_transform (gsl_complex_packed_array data,\n const size_t stride, const size_t n,\n const gsl_fft_complex_wavetable * wavetable,\n gsl_fft_complex_workspace * work,\n const gsl_fft_direction sign);\n\n__END_DECLS\n\n#endif /* __GSL_FFT_COMPLEX_H__ */\n", "meta": {"hexsha": "d2f2b7adb87aca23a10c93f7c66f99e2636a8478", "size": 5028, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/fft/gsl_fft_complex.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/fft/gsl_fft_complex.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/fft/gsl_fft_complex.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": 35.4084507042, "max_line_length": 76, "alphanum_fraction": 0.5920843278, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4610194578308071}} {"text": "/**\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"aXe_utils.h\"\n#include \"aXe_errors.h\" \n#include \"fringe_conf.h\"\n#include \"fringe_model.h\"\n\n#define MAX(x,y) (((x)>(y))?(x):(y))\n#define MIN(x,y) (((x)<(y))?(x):(y))\n\n/**\n * Function: compute_fringe_amplitude\n * The function computes the fringe image for a CCD setup stored\n * in a fringe configuration structure. This fringe configuration\n * structure completely describes the problem, and this function\n * executes the loops for every pixel over the wavelength\n * range spanned by the filter.\n *\n * Parameters\n * @param fconf - the fringe configuration structure\n *\n * Returns:\n * @return fringe_image - the image with the computed fringe amplitudes\n */\ngsl_matrix *\ncompute_fringe_amplitude(fringe_conf *fconf)\n{\n gsl_matrix *fringe_image;\n \n gsl_vector **filter_vectors;\n\n int index=0;\n int ii=0;\n int jj=0;\n\n double lambda_mean;\n double pixel_ampl;\n //double phase_number;\n\n optical_property *optprops;\n\n // allocate the fringe image\n fringe_image = alloc_fringe_image(fconf->opt_layers);\n\n // allocate memory for the optical property structure \n optprops = alloc_optprops_list(fconf);\n\n // find the exact wavelength range,\n // and define the wavelength values and\n // normalized fiter throughput there\n filter_vectors = evaluate_wavelength_steps(fconf);\n //filter_vectors = get_PET_calibration_data();\n\n // compute the mean wavelength\n lambda_mean = gsl_vector_get(filter_vectors[0],filter_vectors[0]->size-1)/2.0\n\t\t + gsl_vector_get(filter_vectors[0],0)/2.0;\n\n // initialize some values in the optical property list\n init_optprops_list(fconf, lambda_mean, optprops);\n\n for (ii=0; ii < (int)fringe_image->size1; ii++)\n // for (ii=0; ii < 2; ii++)\n {\n fprintf(stderr, \"Computing row No.: %i\\n\", ii);\n for (jj=0; jj < (int)fringe_image->size2; jj++)\n\t //for (jj=0; jj < 2; jj++)\n\t{\n\t // fill the optical thickness of the layers\n\t // into the structure\n\t fill_optprops_thickness(fconf->opt_layers, ii, jj, optprops);\n\n\t pixel_ampl = 0.0;\n\t for (index=0; index < (int)filter_vectors[0]->size; index++)\n\t {\n\t // fill all information in the optical\n\t // property list\n\t fill_optprops_all(fconf->opt_layers,\n\t\t\t\tgsl_vector_get(filter_vectors[0],index),\n\t\t\t\toptprops);\n\n\t // compute and add the contribution at a wavelength\n\t pixel_ampl += gsl_vector_get(filter_vectors[1],index)*\n\t\tfringe_contrib_single(optprops, fconf);\n\t }\n\n\t // finally set the pixel value\n\t // in the output image\n\t gsl_matrix_set(fringe_image, ii, jj,\n\t\t\t fconf->fringe_amp * pixel_ampl + 1.0);\n\t}\n }\n\n // release the memory in the vectors\n gsl_vector_free(filter_vectors[0]);\n gsl_vector_free(filter_vectors[1]);\n free(filter_vectors);\n\n // free the optical property structure\n free_optprops_list(optprops);\n\n // return the fringe image\n return fringe_image;\n}\n\n\n/**\n * Function: alloc_fringe_image\n * The function browses through the the structure for the CCD layers\n * and extracts all information on image sizes stored there in\n * one or several thickness images. This information is checked\n * for consistency.\n * Finally, a matrix for a fringe image is allocated, initialized\n * and returned.\n *\n * Parameters:\n * @param opt_layers - the optical layers in the CCD\n *\n * Returns:\n * @return fringe_image - the allocated matrix for the fringe image\n */\ngsl_matrix *\nalloc_fringe_image(const ccd_layers *opt_layers)\n{\n int n1 = 0;\n int n2 = 0;\n int n1_new = 0;\n int n2_new = 0;\n int index = 0;\n int is_defined = 0;\n \n gsl_matrix *fringe_image=NULL;\n // go through all CCD layers\n for (index=0; index < opt_layers->num_layers; index++)\n {\n // check whether the thickness information\n // is represented by an image\n if (opt_layers->opt_layer[index]->thickness2D != NULL)\n\t{\n\n\t // mark that an image was found\n\t is_defined=1;\n\n\t // get the dimension of the image\n\t n1_new = opt_layers->opt_layer[index]->thickness2D->size1;\n\t n2_new = opt_layers->opt_layer[index]->thickness2D->size2;\n\t\n\t // check the frst axix value against\n\t // previous values, if possible\n\t if (n1 && n1_new != n1)\n\t // give an error if the new value is different\n\t aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t\t \"Thickness image of layer %i \"\n\t\t\t \"has %i pixels in first axis.\"\n\t\t\t \"This differs from the previous value %i\\n\",\n\t\t\t index, n1_new, n1);\n\t else\n\t // store the new value\n\t n1 = n1_new;\n\t \n\t // check the frst axix value against\n\t // previous values, if possible\n\t if (n2 && n2_new != n2)\n\t // give an error if the new value is different\n\t aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t\t \"Thickness image of layer %i \"\n\t\t\t \"has %i pixels in second axis.\"\n\t\t\t \"This differs from the previous value %i\\n\",\n\t\t\t index, n2_new, n2);\n\t else\n\t // store the new value\n\t n2 = n2_new;\n\t}\n }\n\n#ifdef DEBUGFCONF\n fprintf(stdout, \"Allocating an image with size: (%i, %i)\\n\", n1, n2);\n#endif\n\n // check whether at least one image was\n // found as thickness information\n if (is_defined)\n {\n // allocate the image\n fringe_image = gsl_matrix_alloc(n1, n2);\n \n // set all vallues to zero\n gsl_matrix_set_all(fringe_image, 0.0);\n }\n else\n {\n // no image found; report the error\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"The size of the fringe image is unknown\\n\"\n\t\t \"since none of the layers has an image \"\n\t\t \"to specify its thickness!\\n\");\n }\n\n // return the image\n return fringe_image;\n}\n\n\n/**\n * Function: get_calibration_data()\n * This function is a data storage for filter throughput values\n * as computed by the orioginal program 'final.f' of J.Walsh.\n * The cubic spline routine used there turned out to give\n * (slightly) different results than the gsl-routine used\n * here. To be able making a in-depth comparison the throughuts\n * were computed for the filter 'ccd_ref.fits' and stored here.\n *\n * Parameters:\n *\n * Returns:\n * @return double_vector - interpolated standard filter throughputs\n */\ngsl_vector **\nget_calibration_data()\n{\n gsl_vector *lambda_values;\n gsl_vector *through_values;\n\n gsl_vector **double_vector;\n\n\n // allocate space for the return vector\n double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *));\n\n // allocate the space for the vectors\n lambda_values = gsl_vector_alloc(43);\n through_values = gsl_vector_alloc(43);\n\n\n // what follows is the wavelength steps as well as the normalized\n // filter throughputs which were computed in the original\n // program 'final.f' of J.Walsh.\n // The gsl-cubic spline routine yields slightly different values.\n // The values fixed here are good for a detailed cross-check\n // of the two programs.\n gsl_vector_set(through_values, 0, 0.0000000000000000);gsl_vector_set(lambda_values, 0, 0.9179);\n gsl_vector_set(through_values, 1, 0.0095066184313808);gsl_vector_set(lambda_values, 1, 0.9180);\n gsl_vector_set(through_values, 2, 0.0176006475945001);gsl_vector_set(lambda_values, 2, 0.9181);\n gsl_vector_set(through_values, 3, 0.0240259215044616);gsl_vector_set(lambda_values, 3, 0.9182);\n gsl_vector_set(through_values, 4, 0.0289185490230508);gsl_vector_set(lambda_values, 4, 0.9183);\n gsl_vector_set(through_values, 5, 0.0324146730103703);gsl_vector_set(lambda_values, 5, 0.9184);\n gsl_vector_set(through_values, 6, 0.0346504181940869);gsl_vector_set(lambda_values, 6, 0.9185);\n gsl_vector_set(through_values, 7, 0.0357619115684218);gsl_vector_set(lambda_values, 7, 0.9186);\n gsl_vector_set(through_values, 8, 0.0358852710613785);gsl_vector_set(lambda_values, 8, 0.9187);\n gsl_vector_set(through_values, 9, 0.0351566282002872);gsl_vector_set(lambda_values, 9, 0.9188);\n gsl_vector_set(through_values,10, 0.0337121099793692);gsl_vector_set(lambda_values,10, 0.9189);\n gsl_vector_set(through_values,11, 0.0316878433928458);gsl_vector_set(lambda_values,11, 0.9190);\n gsl_vector_set(through_values,12, 0.0292199509018293);gsl_vector_set(lambda_values,12, 0.9191);\n gsl_vector_set(through_values,13, 0.0264445572339866);gsl_vector_set(lambda_values,13, 0.9192);\n gsl_vector_set(through_values,14, 0.0234977916500934);gsl_vector_set(lambda_values,14, 0.9193);\n gsl_vector_set(through_values,15, 0.0205157811443709);gsl_vector_set(lambda_values,15, 0.9194);\n gsl_vector_set(through_values,16, 0.0176346504444861);gsl_vector_set(lambda_values,16, 0.9195);\n gsl_vector_set(through_values,17, 0.0149905288112146);gsl_vector_set(lambda_values,17, 0.9196);\n gsl_vector_set(through_values,18, 0.0127195375723916);gsl_vector_set(lambda_values,18, 0.9197);\n gsl_vector_set(through_values,19, 0.0109578003224067);gsl_vector_set(lambda_values,19, 0.9198);\n gsl_vector_set(through_values,20, 0.0098414542549762);gsl_vector_set(lambda_values,20, 0.9199);\n gsl_vector_set(through_values,21, 0.0095066184313808);gsl_vector_set(lambda_values,21, 0.9200);\n gsl_vector_set(through_values,22, 0.0100435357173845);gsl_vector_set(lambda_values,22, 0.9201);\n gsl_vector_set(through_values,23, 0.0113589226644173);gsl_vector_set(lambda_values,23, 0.9202);\n gsl_vector_set(through_values,24, 0.0133136264280558);gsl_vector_set(lambda_values,24, 0.9203);\n gsl_vector_set(through_values,25, 0.0157684646986687);gsl_vector_set(lambda_values,25, 0.9204);\n gsl_vector_set(through_values,26, 0.0185842800987238);gsl_vector_set(lambda_values,26, 0.9205);\n gsl_vector_set(through_values,27, 0.0216219095843027);gsl_vector_set(lambda_values,27, 0.9206);\n gsl_vector_set(through_values,28, 0.0247421844451007);gsl_vector_set(lambda_values,28, 0.9207);\n gsl_vector_set(through_values,29, 0.0278059450370313);gsl_vector_set(lambda_values,29, 0.9208);\n gsl_vector_set(through_values,30, 0.0306740203832353);gsl_vector_set(lambda_values,30, 0.9209);\n gsl_vector_set(through_values,31, 0.0332072463065172);gsl_vector_set(lambda_values,31, 0.9210);\n gsl_vector_set(through_values,32, 0.0352664608962358);gsl_vector_set(lambda_values,32, 0.9211);\n gsl_vector_set(through_values,33, 0.0367124999751954);gsl_vector_set(lambda_values,33, 0.9212);\n gsl_vector_set(through_values,34, 0.0374061970996460);gsl_vector_set(lambda_values,34, 0.9213);\n gsl_vector_set(through_values,35, 0.0372083835592830);gsl_vector_set(lambda_values,35, 0.9214);\n gsl_vector_set(through_values,36, 0.0359798997100196);gsl_vector_set(lambda_values,36, 0.9215);\n gsl_vector_set(through_values,37, 0.0335815745749970);gsl_vector_set(lambda_values,37, 0.9216);\n gsl_vector_set(through_values,38, 0.0298742553097917);gsl_vector_set(lambda_values,38, 0.9217);\n gsl_vector_set(through_values,39, 0.0247187709375447);gsl_vector_set(lambda_values,39, 0.9218);\n gsl_vector_set(through_values,40, 0.0179759414151792);gsl_vector_set(lambda_values,40, 0.9219);\n gsl_vector_set(through_values,41, 0.0095066184313808);gsl_vector_set(lambda_values,41, 0.9220);\n gsl_vector_set(through_values,42, 0.0000000000000000);gsl_vector_set(lambda_values,42, 0.9221);\n \n // build up the output array\n double_vector[0] = lambda_values;\n double_vector[1] = through_values;\n\n // return the two vectors\n return double_vector;\n}\n\n\n/**\n * Function: get_PET_calibration_data()\n */\ngsl_vector **\nget_PET_calibration_data()\n{\n gsl_vector *lambda_values;\n gsl_vector *through_values;\n\n gsl_vector **double_vector;\n\n\n // allocate space for the return vector\n double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *));\n\n // allocate the space for the vectors\n lambda_values = gsl_vector_alloc(21);\n through_values = gsl_vector_alloc(21);\n\n gsl_vector_set(lambda_values, 0,1.069460); gsl_vector_set(through_values, 0, 0.000000);\n gsl_vector_set(lambda_values, 1,1.069653); gsl_vector_set(through_values, 1, 0.012630);\n gsl_vector_set(lambda_values, 2,1.069846); gsl_vector_set(through_values, 2, 0.025261);\n gsl_vector_set(lambda_values, 3,1.070039); gsl_vector_set(through_values, 3, 0.037891);\n gsl_vector_set(lambda_values, 4,1.070232); gsl_vector_set(through_values, 4, 0.050522);\n gsl_vector_set(lambda_values, 5,1.070424); gsl_vector_set(through_values, 5, 0.063152);\n gsl_vector_set(lambda_values, 6,1.070617); gsl_vector_set(through_values, 6, 0.069010);\n gsl_vector_set(lambda_values, 7,1.070810); gsl_vector_set(through_values, 7, 0.069010);\n gsl_vector_set(lambda_values, 8,1.071003); gsl_vector_set(through_values, 8, 0.069010);\n gsl_vector_set(lambda_values, 9,1.071196); gsl_vector_set(through_values, 9, 0.069010);\n gsl_vector_set(lambda_values, 10,1.071389); gsl_vector_set(through_values, 10, 0.069010);\n gsl_vector_set(lambda_values, 11,1.071582); gsl_vector_set(through_values, 11, 0.069010);\n gsl_vector_set(lambda_values, 12,1.071775); gsl_vector_set(through_values, 12, 0.069010);\n gsl_vector_set(lambda_values, 13,1.071967); gsl_vector_set(through_values, 13, 0.069010);\n gsl_vector_set(lambda_values, 14,1.072160); gsl_vector_set(through_values, 14, 0.069010);\n gsl_vector_set(lambda_values, 15,1.072353); gsl_vector_set(through_values, 15, 0.063152);\n gsl_vector_set(lambda_values, 16,1.072546); gsl_vector_set(through_values, 16, 0.050522);\n gsl_vector_set(lambda_values, 17,1.072739); gsl_vector_set(through_values, 17, 0.037891);\n gsl_vector_set(lambda_values, 18,1.072932); gsl_vector_set(through_values, 18, 0.025261);\n gsl_vector_set(lambda_values, 19,1.073125); gsl_vector_set(through_values, 19, 0.012630);\n gsl_vector_set(lambda_values, 20,1.073318); gsl_vector_set(through_values, 20, 0.000000);\n\n //Wavelength: 10713.888672, fringe factor: 1.097945, (x,y): (18, 745)\n\n \n // build up the output array\n double_vector[0] = lambda_values;\n double_vector[1] = through_values;\n\n // return the two vectors\n return double_vector;\n}\n\n/**\n * Function: evaluate_wavelength_steps\n * The function defines and computes the wavelength steps and the\n * filter throughputs which are used to compute the fringe amplitude\n * for all pixels. The basis for the wavelength data are the\n * filter data and the general are where fringing is significant\n * and computed, which is defined in the fringe\n * configuration structure.\n * First all throughput values below a certain value are discarded\n * at the short and long wavelength edge. Then the final wavelength\n * range is determined using the fringing range. Then all wavelength\n * values and the filter throughputs are determined and returned\n * as two gsl-vectors.\n *\n * Parameters:\n * @param fconf - the fringe configuration structure\n *\n * Returns:\n * @return double_vector - a set of two gsl-vectors with wavlength\n and throughput\n */\ngsl_vector **\nevaluate_wavelength_steps(fringe_conf *fconf)\n{\n int index=0;\n int lower=0;\n int upper=0;\n\n int nsteps;\n\n double lambda_min;\n double lambda_max;\n double lambda_act;\n double through_act=0.0;\n double through_tot=0.0;\n\n gsl_vector *lambda_values;\n gsl_vector *through_values;\n\n gsl_vector **double_vector;\n\n\n // allocate space for the return vector\n double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *));\n\n // search through the filter data\n // to narrow the usable range from below\n lower=0;\n while (lower < fconf->filter_through->nvals\n\t && fconf->filter_through->yvals[lower] < FILTER_THRESHOLD)\n lower++;\n lower = MAX(0,lower-1);\n\n // search through the filter data\n // to narrow the usable range from above\n upper=fconf->filter_through->nvals - 1;\n while (upper > -1\n\t && fconf->filter_through->yvals[upper] < FILTER_THRESHOLD)\n upper--;\n upper = MIN(fconf->filter_through->nvals - 1, upper+1);\n\n#ifdef DEBUGFCONF\n fprintf(stderr, \"New lower range index: %i, new upper: %i, old number: %i\\n\",\n\t lower, upper, fconf->filter_through->nvals);\n#endif\n\n // replace the old filter interpolator\n // with a new one, if necessary\n if (lower != 0 || upper != (fconf->filter_through->nvals - 1))\n fconf->filter_through = redefine_filter_throughput(lower, upper, fconf);\n\n // compute the lower wavelength range by comparing\n // the filter throughput with the range important\n // for fringing; the latter is given in AA!!\n lambda_min = MAX(gsl_vector_get(fconf->fringe_range, 0),\n\t\t fconf->filter_through->xmin);\n\n // compute the upper wavelength range by comparing\n // the filter throughput with the range important\n // for fringing; the latter is given in AA!!\n lambda_max = MIN(gsl_vector_get(fconf->fringe_range, 1),\n\t\t fconf->filter_through->xmax);\n\n // find the number of steps to cover the wavelength range\n nsteps = (int)ceil((lambda_max-lambda_min)/(fconf->fringe_step)) + 1;\n\n // allocate the space for the vectors\n lambda_values = gsl_vector_alloc(nsteps);\n through_values = gsl_vector_alloc(nsteps);\n\n // fill the vectors with the wavelength steps and the \n // filter throughput at those wavelengths.\n lambda_act = lambda_min;\n for (index=0; index < nsteps-1; index+=1)\n {\n gsl_vector_set(lambda_values, index, lambda_act);\n through_act = eval_interp(fconf->filter_through, lambda_act);\n through_tot += through_act;\n gsl_vector_set(through_values, index, through_act);\n lambda_act += fconf->fringe_step;\n }\n\n // add also the values at lambda_amax\n gsl_vector_set(lambda_values, nsteps-1, lambda_max);\n through_act = eval_interp(fconf->filter_through, lambda_max);\n through_tot += through_act;\n gsl_vector_set(through_values, nsteps-1, through_act);\n\n \n for (index=0; index < (int)through_values->size; index++)\n {\n // normalize the filter throughput values\n gsl_vector_set(through_values, index,\n\t\t gsl_vector_get(through_values, index)/through_tot);\n\n // convert the wavelength from AA to micron\n gsl_vector_set(lambda_values, index,\n\t\t gsl_vector_get(lambda_values, index)*1.0e-04);\n }\n#ifdef DEBUGFCONF\n through_tot = 0.0;\n for (index=0; index < through_values->size; index++)\n {\n fprintf(stderr, \"Wavelength: %f, Throughput: %f\\n\",\n\t gsl_vector_get(lambda_values, index),\n\t gsl_vector_get(through_values, index));\n through_tot += gsl_vector_get(through_values, index);\n }\n fprintf(stderr, \"Total throughput: %f\\n\", through_tot);\n#endif\n\n // build up the output array\n double_vector[0] = lambda_values;\n double_vector[1] = through_values;\n\n return double_vector;\n}\n\n/**\n * Function: redefine_filter_throughput\n * The function re-defines an existing interpolator using only the\n * existing data values in an index range given as parameters.\n *\n * Parameters:\n * @param lower - index with the lowest data point\n * @param upper - index with the highest data point\n *\n * Returns:\n * @return new_interp - the new interpolator\n */\ninterpolator *\nredefine_filter_throughput(const int lower, const int upper,\n\t\t\t fringe_conf *fconf)\n{\n int new_nvals;\n int index;\n\n double *new_x;\n double *new_y;\n\n interpolator *new_interp;\n \n // allocate space for the return structure;\n // complain if this fails\n new_interp = (interpolator *)malloc (sizeof (interpolator));\n if (new_interp == NULL)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"Could not allocate memory for interpolator\");\n\n // compute the new length of the data arrays\n new_nvals = upper-lower+1;\n\n // allocate space for the new data arrays\n new_x = (double *)malloc(new_nvals*sizeof(double));\n new_y = (double *)malloc(new_nvals*sizeof(double));\n\n // transfer the data\n for (index=lower; index < upper+1; index++)\n {\n new_x[index-lower] = fconf->filter_through->xvals[index];\n new_y[index-lower] = fconf->filter_through->yvals[index];\n }\n\n // free the old structure\n free_interp(fconf->filter_through);\n\n // build up the interpolator structure\n new_interp->xmin = new_x[0];\n new_interp->xmax = new_x[new_nvals-1];\n new_interp->nvals = new_nvals;\n new_interp->xvals = new_x;\n new_interp->yvals = new_y;\n new_interp->acc = gsl_interp_accel_alloc();\n new_interp->interp = gsl_interp_alloc(FILTER_INTERP_TYPE,\n\t\t\t\t\t new_interp->nvals);\n\n // initialize the cubic spline\n gsl_interp_init(new_interp->interp, new_interp->xvals, new_interp->yvals, \n\t\t new_interp->nvals);\n \n // return the new structure\n return new_interp;\n}\n\n\n/**\n * Function: eval_linear_interp\n * The function computes and returns the interpolated value\n * at a given position for a linear interpolator.\n *\n * Parameters:\n * @param lin_int - the linear interpolator\n * @param xval - the position to evaluate the linear interpolator\n *\n * Returns:\n * @return (value) - the interpolated data value\n */\ndouble\neval_linear_interp(linear_interp *lin_int, const double xval)\n{\n\n double factor=0.0;\n\n // check whether the x-value is within \n // the range spanned by the data;\n // complain if the x-value is outside\n if (xval < lin_int->xmin || xval > lin_int->xmax)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"independent linear interpolation value %f \"\n\t\t \"is outside interval (%f, %f)\\n\", xval,\n\t\t lin_int->xmin, lin_int->xmax);\n\n // check whether you have to search upwards or downwards\n if (xval >= gsl_vector_get(lin_int->xvals, lin_int->act_index))\n {\n\n // in case that you search upwards, go up\n // the independent values until you find the right interval\n lin_int->act_index += 1;\n while(xval > gsl_vector_get(lin_int->xvals, lin_int->act_index))\n\tlin_int->act_index++;\n }\n else\n {\n\n // in case that you search downwards, go down\n // the independent values until you find the right interval\n // while(wavelength < resp->spec[nact-1].lambda_mean)\n while(xval < gsl_vector_get(lin_int->xvals, lin_int->act_index-1))\n\tlin_int->act_index--;\n }\n\n // interpolate within the interval to calculate the \n // sensitivity\n factor = (xval - gsl_vector_get(lin_int->xvals, lin_int->act_index-1))/\n (gsl_vector_get(lin_int->xvals, lin_int->act_index) - gsl_vector_get(lin_int->xvals, lin_int->act_index-1));\n\n // compute and terutn the interpolated value\n return (gsl_vector_get(lin_int->yvals, lin_int->act_index-1)\n + factor * (gsl_vector_get(lin_int->yvals, lin_int->act_index)-gsl_vector_get(lin_int->yvals, lin_int->act_index-1)));\n}\n\n\n\n/**\n * Function: get_layer_thickness\n * The function determines the thickness of an individual layer\n * at a given pixel position.\n *\n * Parameters:\n * @param opt_layer - the optical layer\n * @param ii - the first pixel index\n * @param jj - the second pixel index\n *\n * Returns:\n * @return (value) - the thickness of the layer at the requested position\n */\ndouble\nget_layer_thickness(const ccd_layer *opt_layer, const int ii, const int jj)\n{\n // check whether the thickness is 2D\n if (opt_layer->thickness2D)\n // return the 2D value\n return gsl_matrix_get(opt_layer->thickness2D, ii, jj);\n else\n // return the constant value\n return opt_layer->thickness;\n}\n\n\n/**\n * Function: get_complex_refindex\n * The function computes and returns the complex refraction index of\n * a given CCD layer at a given wavelength.\n *\n * Parameters:\n * @param opt_layer - the optical layer\n * @param lambda - the wavelength\n *\n * Returns:\n * @return (value) - the complex refraction index\n */\ngsl_complex\nget_complex_refindex(const ccd_layer *opt_layer, const double lambda)\n{\n double re;\n double im;\n\n // compute the real part\n re = eval_interp(opt_layer->re_refraction, lambda);\n\n // comute the imaginary part\n im = eval_interp(opt_layer->im_refraction, lambda);\n\n // return the complex number\n return gsl_complex_rect(re, im);\n}\n\n\n/**\n * Function: compute_reflection\n * The function computes and returns the reflection index (in %)\n * for two complex refraction indices at a given wavelength.\n *\n * Parameters:\n * @param refract_l1 - refraction index of one layer \n * @param refract_l2 - refraction index of the second layer \n *\n * Returns:\n * @return (value) - the reflection index\n */\ndouble\ncompute_reflection(const gsl_complex refract_l1,\n\t\t const gsl_complex refract_l2)\n{\n gsl_complex conj_l1;\n gsl_complex conj_l2;\n\n gsl_complex refl_compl;\n\n // get the comlex conjugated values of the input\n conj_l1 = gsl_complex_conjugate(refract_l1);\n conj_l2 = gsl_complex_conjugate(refract_l2);\n\n // compute the complex reflection\n refl_compl = gsl_complex_div(gsl_complex_sub(conj_l1, conj_l2),\n\t\t\t gsl_complex_add(conj_l1, conj_l2));\n\n // return the magnitude of the complex reflection\n return gsl_complex_abs2(refl_compl);\n}\n\n\n/**\n * Function: compute_transmission\n * The function computes and returns the transmission index (in %)\n * for two complex refraction indices at a given wavelength.\n *\n * Parameters:\n * @param refract_l1 - refraction index of one layer \n * @param refract_l2 - refraction index of the second layer \n *\n * Returns:\n * @return (value) - the trnasmission index\n */\ndouble\ncompute_transmission(const gsl_complex refract_l1,\n\t\t const gsl_complex refract_l2)\n{\n gsl_complex conj_l1;\n gsl_complex conj_l2;\n\n gsl_complex trans_compl;\n\n // get the comlex conjugated values of the input\n conj_l1 = gsl_complex_conjugate(refract_l1);\n conj_l2 = gsl_complex_conjugate(refract_l2);\n\n // compute the complex transmission\n trans_compl =\n gsl_complex_div(gsl_complex_sqrt(gsl_complex_mul(conj_l1, conj_l2)),\n\t\t gsl_complex_add(conj_l1, conj_l2));\n \n // finish the computation of the complex transmission\n trans_compl = gsl_complex_mul_real (trans_compl, 2.0);\n\n // return the magnitude of the complex transmission\n return gsl_complex_abs2(trans_compl);\n}\n\n\n/**\n * Function: compute_attenuation\n * The function computes the attenuation/damping of a plane wave\n * with a given inverse wavelelength (phase number) traversing\n * TWO TIMES a layer of a given thickness and complex refraction\n * index.\n *\n * Parameters:\n * @param refract - the complex refraction index\n * @param thickness - the thickness of the layer\n * @param phase_number - the inverse wavelength\n *\n * Returns:\n * @return (value) - the attenuation\n */\ndouble\ncompute_attenuation(const gsl_complex refract, const double thickness,\n\t\t const double phase_number)\n{\n // check if there is something to compute\n if (GSL_IMAG(refract)) \n // compute and return the value\n return exp(-2.0*GSL_IMAG(refract)*thickness*phase_number);\n else\n // return the value for exp(0.0)\n return 1.0;\n}\n\n\n/**\n * Function: compute_pshift\n * The function computes the phase shift of a plane wave\n * with a given inverse wavelelength (phase number) traversing\n * TWO TIMES a layer of a given thickness and complex refraction\n * index.\n *\n * Parameters:\n * @param refract - the complex refraction index\n * @param thickness - the thickness of the layer\n * @param phase_number - the inverse wavelength\n *\n * Returns:\n * @return (value) - the complex phase shift\n */\ngsl_complex\ncompute_pshift(const gsl_complex refract, const double thickness,\n\t const double phase_number)\n{\n // all in one line:\n return gsl_complex_exp(gsl_complex_rect(0.0,2.0*GSL_REAL(refract)*thickness*phase_number));\n}\n\n\n/**\n * Function: alloc_optprops_list\n * The function allocates space for a list of optical property\n * elements. the size of the list is derived from a fringe\n * configuration structure given in the input.\n *\n * Parameters:\n * @param fconf - the fringe configuration file\n *\n * Returns:\n * @return optprops - the list of optical properties\n */\noptical_property *\nalloc_optprops_list(const fringe_conf *fconf)\n{\n optical_property *optprops;\n\n // allocate large enough memory \n optprops =\n (optical_property *)malloc(fconf->opt_layers->num_layers*sizeof(ap_pixel));\n\n // return the pointer\n return optprops;\n}\n\n\n/**\n * Function: print_optprops_list\n * The function prints the content of an optical property\n * list onto the screen.\n *\n * Parameters:\n * @param optprops - the optical property list\n *\n * Returns:\n * @return -\n */\nvoid\nprint_optprops_list(const optical_property *optprops, const int num_entries)\n{\n int index;\n \n for (index = 0; index < num_entries; index++)\n {\n fprintf(stdout, \"#%i: %f %f %f %f %f %f \\n\",index,\n\t optprops[index].trans_upper, optprops[index].reflect_upper,\n\t GSL_REAL(optprops[index].double_phshift),\n\t GSL_IMAG(optprops[index].double_phshift),\n\t optprops[index].trans_lower, optprops[index].reflect_lower);\n }\n}\n\n/**\n * Function: free_optprops_list\n * The function releases the space allocated in an\n * optical property list.\n *\n * Parameters:\n * @param optprops - the optical property list\n *\n * Returns:\n * @return -\n */\nvoid\nfree_optprops_list(optical_property *optprops)\n{\n if (optprops != NULL)\n {\n // free the structure\n free(optprops);\n\n // set it to NULL\n optprops = NULL;\n }\n}\n\n\n/*\n * Function: init_optprops_list\n * The function initializes an optical property list. This means\n * it computes and stores values for the list elements. Here\n * only elements are fixed, which will not change during the\n * whole fringe computation and remain constant for all pixels\n * at all wavelengths.\n *\n * Parameters:\n * @params fconf - the fringe configuration structure\n * @params lambda_mean - the mean wavelength of analyzed waveband\n * @params optprops - the list of optical property elements\n *\n * Returns:\n * @return -\n */\nvoid\ninit_optprops_list(const fringe_conf *fconf, const double lambda_mean,\n\t\t optical_property *optprops)\n{\n int num_layers;\n int index;\n\n double n1;\n double n2;\n\n // determine the number of layers\n num_layers = fconf->opt_layers->num_layers;\n\n if (num_layers > 0)\n {\n // set the transmission and reflection\n // vacuum -- first CCD layer\n // that's a bit heuristic, since\n // the true value using the true\n // refration index for vacuum would\n // give a different result\n optprops[0].trans_upper = 1.0;\n optprops[0].reflect_upper = 0.0; \n\n // also that one is a bit heuristic\n // but assuming n(vacuum)=1.0 its also true \n optprops[0].sign_upper = 1.0;\n\n // set the sign of the lowest layer -- substrate\n // this is purely heuristic and works \n // only for the HRC/WFC fringing models!! \n optprops[num_layers-1].sign_lower = -1.0;\n }\n\n for (index=0; index < num_layers-1; index++)\n {\n // get the real part of the refraction index\n // of the upper layer\n n1 = GSL_REAL(get_complex_refindex(fconf->opt_layers->opt_layer[index],\n\t\t\t\t\t lambda_mean));\n\n // get the real part of the refraction index\n // of the lower layer\n n2 = GSL_REAL(get_complex_refindex(fconf->opt_layers->opt_layer[index+1],\n\t\t\t\t\t lambda_mean));\n\n // distribute the signs\n // for the upper and lower layer\n if (n1 < n2)\n\t{\n\t optprops[index].sign_lower = 1.0;\n\t optprops[index+1].sign_upper = -1.0;\n\t}\n else\n\t{\n\t optprops[index].sign_lower = -1.0;\n\t optprops[index+1].sign_upper = 1.0;\n\t}\n }\n}\n\n\n/*\n * Function: fill_optprops_thickness\n * The function fills the thickness of the optival layers\n * at a given pixel into a list of optical properties.\n *\n * Parameters:\n * @params opt_layers - the structure for the optical layers\n * @params ii - the mean wavelength of analyzed waveband\n * @params jj - the list of optical property elements\n * @params optprops - the list of optical property elements\n *\n * Returns:\n * @return -\n */\nvoid\nfill_optprops_thickness(const ccd_layers *opt_layers, const int ii,\n\t\t\tconst int jj, optical_property *optprops)\n{\n int index;\n\n // go over all layers\n for (index=0; index < opt_layers->num_layers; index++)\n // get and store the thickness\n optprops[index].thickness =\n get_layer_thickness(opt_layers->opt_layer[index], ii, jj);\n}\n\n\n/*\n * Function: fill_optprops_all\n * This function computes and fills in all pixel AND wavelength\n * dependent values into a list of optical properties. The completely\n * filled list can then be used to determine the fringe contribution\n * at that wavelength according to a certain model which defines\n * the various light-paths.\n *\n * Parameters:\n * @params opt_layers - the structure for the optical layers\n * @params lambda - the actual wavelength\n * @params optprops - the list of optical property elements\n *\n * Returns:\n * @return -\n */\nvoid\nfill_optprops_all(const ccd_layers *opt_layers, const double lambda,\n\t\t optical_property *optprops)\n{\n int index;\n\n double phase_number;\n\n gsl_complex compl_upp;\n gsl_complex compl_low;\n\n int num_layers;\n\n // store the number of layers\n num_layers = opt_layers->num_layers;\n\n // compute the phase number\n phase_number = 2.0*M_PI / lambda;\n\n // get the complex refractive index for the first layer\n compl_upp =\n get_complex_refindex(opt_layers->opt_layer[0],lambda);\n\n for (index=0; index < num_layers-1; index++)\n {\n\n // get the refractive index for the next layer\n compl_low =\n \tget_complex_refindex(opt_layers->opt_layer[index+1],lambda);\n\n // compute the reflection and transmission\n // to the lower layers\n optprops[index].reflect_lower =\n\tcompute_reflection(compl_upp, compl_low);\n optprops[index].trans_lower = 1.0 - optprops[index].reflect_lower;\n\n // compute the reflection and transmission\n // to the upper layers\n optprops[index+1].reflect_upper = optprops[index].reflect_lower;\n optprops[index+1].trans_upper = 1.0 - optprops[index+1].reflect_upper;\n\n // compute the attenuation\n optprops[index].double_attenuation =\n \tcompute_attenuation(compl_upp,optprops[index].thickness,phase_number);\n\n // compute the phase shift\n optprops[index].double_phshift =\n\tcompute_pshift(compl_upp, optprops[index].thickness, phase_number);\n\n\n // prepare the next iteration:\n // the now upper layer will then be the lower\n compl_upp = compl_low;\n }\n // compute the attenuation for the last layer\n optprops[num_layers-1].double_attenuation =\n compute_attenuation(compl_upp,optprops[num_layers-1].thickness,phase_number);\n \n // compute the phase shift for the last layer\n optprops[num_layers-1].double_phshift =\n compute_pshift(compl_upp, optprops[num_layers-1].thickness, phase_number);\n\n // compute the transmission of the last layer\n // towards the substrate\n optprops[num_layers-1].trans_lower = \n eval_interp(opt_layers->substrate, lambda);\n\n // compute the reflection of the last layer\n // towards the substrate\n optprops[num_layers-1].reflect_lower =\n 1.0 - optprops[num_layers-1].trans_lower;\n\n}\n\n\n/*\n * Function: fill_contrib_single\n * The function computes the contribution to the fringe amplitude\n * on the basis of an appropriately filled list of optical properties.\n * In the properties the ingredients such as phase shifts and\n * attenuation and transmissions and reflections are defined.\n * This function just combines the ingredients using a model\n * which includes all single reflected beam combinations\n * as contributors to the fringing.\n *\n * Parameters:\n * @params optprops - the list of optical property elements\n * @params fconf - the fringe configuration structure\n *\n * Returns:\n * @return (value) - the fringe contribution \n */\ndouble\nfringe_contrib_single(const optical_property *optprops,\n\t\t const fringe_conf *fconf)\n{\n int index=2;\n \n gsl_complex amp_tmp;\n gsl_complex amp_tot;\n\n\n // compute the initial phase at the top of the\n // first layer\n amp_tot =\n gsl_complex_mul_real(gsl_complex_exp(gsl_complex_rect(0.0,fconf->fringe_phase*M_PI/180.0)), 1.0);\n \n\n // transfer the intitial value \n // to the running variable\n amp_tmp = amp_tot; \n \n // pile up the amplitude,\n // also putting in the transmission\n amp_tmp =\n gsl_complex_mul(amp_tmp,\n\t\t gsl_complex_mul_real(optprops[0].double_phshift,\n\t\t\t\t\t 1.0*1.0*optprops[0].double_attenuation));\n\n // compute the intermediate result \n // for the first layer\n amp_tot = \n gsl_complex_add(amp_tot, \n\t\t gsl_complex_mul_real(amp_tmp,\n\t\t\t\t\t optprops[0].sign_lower*optprops[0].reflect_lower));\n\n // go over layer 2 to the end\n for (index=1; index < fconf->opt_layers->num_layers; index++)\n {\n // pile up the amplitude \n // to that layer\n amp_tmp =\n\tgsl_complex_mul(amp_tmp,\n\t\t\tgsl_complex_mul_real(optprops[index].double_phshift,\n\t\t\t\t\t optprops[index-1].trans_lower*optprops[index].trans_upper*optprops[index].double_attenuation));\n\n // compute the intermediate result \n // for the that layer\n amp_tot = \n\tgsl_complex_add(amp_tot, \n\t\t\tgsl_complex_mul_real(amp_tmp,\n\t\t\t\t\t optprops[index].sign_lower*optprops[index].reflect_lower));\n // if (index==3)\n //\tfprintf(stdout,\"ccc:%f, %f\\n\", GSL_REAL(amp_tmp),GSL_IMAG(amp_tmp) );\n\n }\n\n // return the final value\n return (GSL_REAL(amp_tot) - 1.0);\n}\n", "meta": {"hexsha": "29d00f8d926b2342a9925e54fb81bfb8272ace06", "size": 36932, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/fringe_model.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/fringe_model.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/fringe_model.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": 32.2550218341, "max_line_length": 122, "alphanum_fraction": 0.7185638471, "num_tokens": 10108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.46091536708264336}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef double (*eval_func)(const gsl_interp*,const double *x,const double *y,\n double,gsl_interp_accel*);\n\nstatic const double EPSILON = 0.00000001;\nstatic const double EPS = 0.0001;\nstatic const int PTS = 801;\n\nstatic const double x_values[] = { 0, 1, 2, 3, 4, 5 };\nstatic const double y_values[] = { 5, 0, 5, 2, 0, 5 };\nstatic double x_range;\n\nstatic const int N = sizeof(x_values)/sizeof(double);\n\nstatic double* interpolate(const gsl_interp_type *type, const size_t order);\nstatic void check_discont(gsl_interp *interp, const eval_func func,\n const char *dsym, const double x,\n gsl_interp_accel *accel);\n\nstatic inline double\nscale_x(const int i)\n{\n return x_values[0] + (double)i/(PTS-1)*x_range;\n}\n\nint\nmain(int argc, char *argv[])\n{\n int i;\n double *cspline, *cspline_d, *cspline_dd;\n double *akima, *akima_d, *akima_dd;\n\n x_range = x_values[N-1] - x_values[0];\n\n akima = interpolate(gsl_interp_akima_periodic, 0);\n akima_d = interpolate(gsl_interp_akima_periodic, 1);\n akima_dd = interpolate(gsl_interp_akima_periodic, 2);\n cspline = interpolate(gsl_interp_cspline_periodic, 0);\n cspline_d = interpolate(gsl_interp_cspline_periodic, 1);\n cspline_dd = interpolate(gsl_interp_cspline_periodic, 2);\n\n puts(\"# x akima cspline akima' cspline' akima'' cspline''\");\n for (i = -PTS/2; i < PTS/2; i++)\n printf(\"%0.5f %0.5f %0.5f %0.5f %0.5f %0.5f %0.5f\\n\",\n scale_x(i),\n akima[(i + PTS)%PTS],\n cspline[(i + PTS)%PTS],\n akima_d[(i + PTS)%PTS],\n cspline_d[(i + PTS)%PTS],\n akima_dd[(i + PTS)%PTS],\n cspline_dd[(i + PTS)%PTS]);\n\n free(akima);\n free(akima_d);\n free(akima_dd);\n free(cspline);\n free(cspline_d);\n free(cspline_dd);\n return 0;\n}\n\nstatic double*\ninterpolate(const gsl_interp_type *type, const size_t order)\n{\n static const eval_func DERIV_ORDERS[] = {\n gsl_interp_eval,\n gsl_interp_eval_deriv,\n gsl_interp_eval_deriv2\n };\n static const char *DERIV_SYMS[] = {\n \"\",\n \"'\",\n \"''\"\n };\n\n gsl_interp *interp = gsl_interp_alloc(type, N);\n gsl_interp_accel *accel = gsl_interp_accel_alloc();\n double *plotpts = (double*)malloc(PTS*sizeof(double));\n int i;\n\n assert(order < sizeof(DERIV_ORDERS));\n gsl_interp_init(interp, x_values, y_values, N);\n for (i = 0; i < PTS; i++)\n plotpts[i] = DERIV_ORDERS[order](interp, x_values, y_values,\n scale_x(i), accel);\n\n for (i = 0; i < N-1; i++)\n check_discont(interp, DERIV_ORDERS[order], DERIV_SYMS[order],\n x_values[i], accel);\n\n gsl_interp_free(interp);\n gsl_interp_accel_free(accel);\n\n return plotpts;\n}\n\nstatic void\ncheck_discont(gsl_interp *interp, const eval_func func, const char *dsym,\n const double x, gsl_interp_accel *accel)\n{\n double xm, xp;\n double ym, yp;\n\n xm = fmod(x - EPSILON + x_range, x_range);\n xp = fmod(x + EPSILON, x_range);\n ym = func(interp, x_values, y_values, xm, accel);\n yp = func(interp, x_values, y_values, xp, accel);\n if (fabs(yp - ym) > EPS) {\n fprintf(stderr, \"discontinuity in %s%s at %f:\\n\"\n \"\\t left value: %f\\n\"\n \"\\tright value: %f\\n\"\n \"\\t difference: %f\\n\\n\",\n gsl_interp_name(interp), dsym, x, ym, yp, yp-ym);\n }\n}\n", "meta": {"hexsha": "f41b5983a3f701e063435a627f9683da0db2e07a", "size": 3500, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/test_disc.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/test_disc.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/test_disc.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.6885245902, "max_line_length": 78, "alphanum_fraction": 0.6245714286, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4606796658671747}} {"text": "#include \n\n//#ifndef DARWIN \n//#include \n//#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * A simple helper function to display the contents of a 2-D gsl matrix\n */\nint print_matrix(FILE *f, const gsl_matrix *m)\n{\n int status, n = 0;\n size_t i, j;\n\n for (i = 0; i < m->size1; i++) {\n for (j = 0; j < m->size2; j++) {\n if ((status = fprintf(f,\"%g \", gsl_matrix_get(m, i, j))) < 0)\n return -1;\n n += status;\n }\n\n if ((status = fprintf(f, \"\\n\")) < 0)\n return -1;\n n += status;\n }\n return n;\n}\n\n/*\n * A simple helper function to display the contennts of a 1-D gsl vector\n */\nint print_vector(FILE *f, const gsl_vector *m)\n{\n int status, n = 0;\n size_t i;\n\n for (i = 0; i < m->size; i++) {\n if ((status = fprintf(f, \"%g \", gsl_vector_get(m, i))) < 0)\n return -1;\n n += status;\n }\n return n;\n}\n\n\nvoid print_mat(double* mat, int dim1, int dim2)\n{\n int i, j;\n printf(\"\\n\");\n for (i=0; isize1);\n\n // Go through each star, calculating and storing overlap\n for (star_count=0; star_countsize1);\n\n//for (l=0; l<1; l++){ //DELETE\n\n //Inserting values into matricies and vectors\n for (i=0; isize1);\n\n //Inserting values into matricies and vectors\n for (i=0; isize1);\n\n // INITIALISE GROUP MATRICES\n for (i=0; isize1);\n\n printf(\"Memory allocated\\n\");\n // INITIALISE STAR MATRICES\n for (i=0; idata, 6);\n printf(\"Matrices initialised\\n\\n\");\n\n result = 6*log(2*M_PI);\n printf(\"Added 6log(2pi):\\n%6.2f\\n\", result);\n\n // Get inverse of BpA, this line is wrong, fix when have internet\n gsl_linalg_LU_decomp(BpA, p1, &signum);\n ln_det_BpA = log(fabs(gsl_linalg_LU_det(BpA, signum)));\n printf(\"Log of det(ApB): %6.2f\\n\", ln_det_BpA);\n result += ln_det_BpA;\n\n printf(\"result so far:\\n%6.2f\\n\",result);\n //\n gsl_vector_set_zero(v_temp);\n gsl_linalg_LU_solve(BpA, p1, bma, v_temp); //v_temp holds (B+A)^-1 (b-a)\n gsl_blas_ddot(v_temp, bma, &d_temp); //d_temp holds (b-a)^T (B+A)-1 (b-a)\n printf(\"Printing bma_BpAi_bma\\n\");\n printf(\"%6.2f\\n\\n\", d_temp);\n\n result += d_temp;\n printf(\"result after bma_BpAi_bma:\\n%6.2f\\n\",result);\n\n result *= -0.5;\n printf(\"Everything calculated\\n\");\n printf(\"Final result:\\n%6.8f\\n\", result);\n //\n\n // DEALLOCATE THE MEMORY\n gsl_matrix_free(BpA);\n //gsl_matrix_free(BpAi);\n gsl_vector_free(bma);\n gsl_vector_free(v_temp);\n\n gsl_permutation_free(p1);\n\n return result;\n //printf(\"At end of new_get_lnoverlaps function\\n\");\n}\n\n\n\n", "meta": {"hexsha": "7e814159d945777f6a3ef0d9526fa4dcc3ad7a80", "size": 21073, "ext": "c", "lang": "C", "max_stars_repo_path": "chronostar/overlap/overlap.c", "max_stars_repo_name": "mikeireland/chronostar", "max_stars_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z", "max_issues_repo_path": "chronostar/overlap/overlap.c", "max_issues_repo_name": "mikeireland/chronostar", "max_issues_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z", "max_forks_repo_path": "chronostar/overlap/overlap.c", "max_forks_repo_name": "mikeireland/chronostar", "max_forks_repo_head_hexsha": "fcf37614e1d145f3a5e265e54512bf8cd98051a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z", "avg_line_length": 30.7635036496, "max_line_length": 80, "alphanum_fraction": 0.629146301, "num_tokens": 6902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.46047924679785296}} {"text": "/* interpolation/interp_poly.c\n * \n * Copyright (C) 2001 DAN, HO-JIN\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\ntypedef struct\n{\n double *d;\n double *coeff;\n double *work;\n}\npolynomial_state_t;\n\nstatic void *\npolynomial_alloc (size_t size)\n{\n polynomial_state_t *state =\n (polynomial_state_t *) malloc (sizeof (polynomial_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for polynomial state\",\n GSL_ENOMEM);\n }\n\n state->d = (double *) malloc (sizeof (double) * size);\n\n if (state->d == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n state->coeff = (double *) malloc (sizeof (double) * size);\n\n if (state->coeff == 0)\n {\n free (state->d);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n state->work = (double *) malloc (sizeof (double) * size);\n\n if (state->work == 0)\n {\n free (state->coeff);\n free (state->d);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n return state;\n}\n\nstatic int\npolynomial_init (void *vstate,\n const double xa[], const double ya[], size_t size)\n{\n polynomial_state_t *state = (polynomial_state_t *) vstate;\n\n int status = gsl_poly_dd_init (state->d, xa, ya, size);\n\n return status;\n}\n\nstatic int\npolynomial_eval (const void *vstate,\n const double xa[], const double ya[], size_t size, double x,\n gsl_interp_accel * acc, double *y)\n{\n const polynomial_state_t *state = (const polynomial_state_t *) vstate;\n\n *y = gsl_poly_dd_eval (state->d, xa, size, x);\n\n return GSL_SUCCESS;\n}\n\n\nstatic int\npolynomial_deriv (const void *vstate,\n const double xa[], const double ya[], size_t size, double x,\n gsl_interp_accel * acc, double *y)\n{\n const polynomial_state_t *state = (const polynomial_state_t *) vstate;\n\n gsl_poly_dd_taylor (state->coeff, x, state->d, xa, size, state->work);\n\n *y = state->coeff[1];\n\n return GSL_SUCCESS;\n}\n\nstatic int\npolynomial_deriv2 (const void *vstate,\n const double xa[], const double ya[], size_t size,\n double x, gsl_interp_accel * acc, double *y)\n{\n const polynomial_state_t *state = (const polynomial_state_t *) vstate;\n\n gsl_poly_dd_taylor (state->coeff, x, state->d, xa, size, state->work);\n\n *y = 2.0 * state->coeff[2];\n\n return GSL_SUCCESS;\n}\n\nstatic int\npolynomial_integ (const void *vstate, const double xa[], const double ya[],\n size_t size, gsl_interp_accel * acc, double a, double b,\n double *result)\n{\n const polynomial_state_t *state = (const polynomial_state_t *) vstate;\n size_t i;\n double sum;\n\n gsl_poly_dd_taylor (state->coeff, 0.0, state->d, xa, size, state->work);\n\n sum = state->coeff[0] * (b - a);\n\n for (i = 1; i < size; i++)\n {\n sum += state->coeff[i] * (pow (b, i + 1) - pow (a, i + 1)) / (i + 1.0);\n }\n\n *result = sum;\n\n return GSL_SUCCESS;\n}\n\nstatic void\npolynomial_free (void *vstate)\n{\n polynomial_state_t *state = (polynomial_state_t *) vstate;\n free (state->d);\n free (state->coeff);\n free (state->work);\n free (state);\n}\n\nstatic const gsl_interp_type polynomial_type = {\n \"polynomial\",\n 3,\n &polynomial_alloc,\n &polynomial_init,\n &polynomial_eval,\n &polynomial_deriv,\n &polynomial_deriv2,\n &polynomial_integ,\n &polynomial_free,\n};\n\nconst gsl_interp_type *gsl_interp_polynomial = &polynomial_type;\n", "meta": {"hexsha": "a0cd68aa123614e21ec2d653d03894000a6b4237", "size": 4333, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/poly.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/interpolation/poly.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/interpolation/poly.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.9022988506, "max_line_length": 81, "alphanum_fraction": 0.6510500808, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.46035733017655117}} {"text": "/*\n * kjg_fpca.c\n *\n * Created on: Apr 28, 2014\n * Author: Kevin\n */\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kjg_fpca.h\"\n#include \"kjg_gsl.h\"\n\n#include \"admutils.h\"\n#include \"gval.h\"\n\nsize_t KJG_FPCA_ROWS = 256;\n\nvoid\nkjg_fpca (size_t K, size_t L, size_t I, double *eval, double *evec)\n{\n if (K >= L)\n exit (1);\n if (I == 0)\n exit (1);\n\n size_t m = get_ncols ();\n size_t n = get_nrows ();\n\n // PART A - compute Q such that X ~ Q * (Q^T) * X\n gsl_matrix *G1 = gsl_matrix_alloc (n, L);\n gsl_matrix *G2 = gsl_matrix_alloc (n, L);\n gsl_matrix *Q = gsl_matrix_alloc (m, (I + 1) * L);\n gsl_matrix *Gswap;\n\n gsl_rng *r = kjg_gsl_rng_init ();\n kjg_gsl_ran_ugaussian_matrix (r, G1);\n gsl_rng_free (r);\n\n size_t i;\n for (i = 0; i < I; i++)\n {\n gsl_matrix_view Qi = gsl_matrix_submatrix (Q, 0, i * L, m, L);\n\n // do the multiplication\n kjg_fpca_XTXA (G1, &Qi.matrix, G2);\n\n // scale to prevent G2 from blowing up\n gsl_matrix_scale (G2, 1.0 / m);\n\n Gswap = G2;\n G2 = G1;\n G1 = Gswap;\n }\n\n gsl_matrix_view Qi = gsl_matrix_submatrix (Q, 0, I * L, m, L);\n kjg_fpca_XA (G1, &Qi.matrix);\n\n {\n gsl_matrix *V = gsl_matrix_alloc (Q->size2, Q->size2);\n gsl_vector *S = gsl_vector_alloc (Q->size2);\n\n kjg_gsl_SVD (Q, V, S);\n\n gsl_matrix_free (V);\n gsl_vector_free (S);\n }\n\n // kjg_gsl_matrix_QR(Q); // QR decomposition is less accurate than SVD\n\n gsl_matrix_free (G1);\n gsl_matrix_free (G2);\n\n // PART B - compute B matrix, take SVD and return\n gsl_matrix *B = gsl_matrix_alloc (n, (I + 1) * L);\n kjg_fpca_XTB (Q, B);\n\n gsl_matrix *Utilda = gsl_matrix_alloc ((I + 1) * L, (I + 1) * L);\n gsl_vector *Stilda = gsl_vector_alloc ((I + 1) * L);\n\n kjg_gsl_SVD (B, Utilda, Stilda);\n\n gsl_matrix_view Vk = gsl_matrix_submatrix (B, 0, 0, n, K);\n gsl_matrix_view evec_view = gsl_matrix_view_array (evec, n, K);\n gsl_matrix_memcpy (&evec_view.matrix, &Vk.matrix);\n\n gsl_vector_view Sk = gsl_vector_subvector (Stilda, 0, K);\n gsl_vector_view eval_view = gsl_vector_view_array (eval, K);\n gsl_vector_mul (&Sk.vector, &Sk.vector);\n gsl_vector_scale (&Sk.vector, 1.0 / m);\n gsl_vector_memcpy (&eval_view.vector, &Sk.vector);\n\n gsl_matrix_free (Q);\n gsl_matrix_free (B);\n gsl_matrix_free (Utilda);\n gsl_vector_free (Stilda);\n}\n\nvoid\nkjg_fpca_XTXA (const gsl_matrix * A1, gsl_matrix * B, gsl_matrix * A2)\n{\n size_t m = get_ncols ();\n size_t n = get_nrows ();\n\n size_t i, r;\t\t\t// row index\n double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS);\t// normalized\n\n gsl_matrix_view Bi, Xi;\n\n gsl_matrix_set_zero (A2);\n\n for (i = 0; i < m; i += KJG_FPCA_ROWS)\n {\n r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y);\n Xi = gsl_matrix_view_array (Y, r, n);\n Bi = gsl_matrix_submatrix (B, i, 0, r, B->size2);\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1, &Xi.matrix, A1, 0,\n\t\t &Bi.matrix);\n gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1, &Xi.matrix, &Bi.matrix,\n\t\t 1, A2);\n }\n\n free (Y);\n}\n\nvoid\nkjg_fpca_XA (const gsl_matrix * A, gsl_matrix * B)\n{\n size_t n = get_nrows ();\n size_t m = get_ncols ();\n\n size_t i, r;\n double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS);\n\n gsl_matrix_view Hmat, Xmat;\n\n gsl_matrix_set_zero (B);\n\n for (i = 0; i < m; i += KJG_FPCA_ROWS)\n {\n r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y);\n Xmat = gsl_matrix_view_array (Y, r, n);\n Hmat = gsl_matrix_submatrix (B, i, 0, r, B->size2);\n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1, &Xmat.matrix, A, 0,\n\t\t &Hmat.matrix);\n }\n\n free (Y);\n}\n\nvoid\nkjg_fpca_XTB (const gsl_matrix * B, gsl_matrix * A)\n{\n size_t n = get_nrows ();\n size_t m = get_ncols ();\n\n size_t i, r;\n double *Y = malloc (sizeof (double) * n * KJG_FPCA_ROWS);\n gsl_matrix_view Xmat;\n\n gsl_matrix_set_zero (A);\n\n for (i = 0; i < m; i += KJG_FPCA_ROWS)\n {\n r = kjg_geno_get_normalized_rows (i, KJG_FPCA_ROWS, Y);\n Xmat = gsl_matrix_view_array (Y, r, n);\n gsl_matrix_const_view Hmat = gsl_matrix_const_submatrix (B, i, 0, r,\n\t\t\t\t\t\t\t B->size2);\n gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1, &Xmat.matrix, &Hmat.matrix,\n\t\t 1, A);\n }\n\n free (Y);\n}\n", "meta": {"hexsha": "4fb16ce86baecc5bb7a6a3f0afd280314d48ae8d", "size": 4301, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ksrc/kjg_fpca.c", "max_stars_repo_name": "nevrome/EIG", "max_stars_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "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/ksrc/kjg_fpca.c", "max_issues_repo_name": "nevrome/EIG", "max_issues_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "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/ksrc/kjg_fpca.c", "max_forks_repo_name": "nevrome/EIG", "max_forks_repo_head_hexsha": "f7b857d4d347d44c57f70194bb4588fad5b1ffed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0279329609, "max_line_length": 78, "alphanum_fraction": 0.628225994, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.46025819867157397}} {"text": "//im_clam.c --\n// A. Kern 3/20/15\n//\n// Composite Likelihood estimation of canonical IM models via AFS\n\n//going to use NLopt for optimization\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AFS.h\"\n#include \"adkGSL.h\"\n#include \"cs.h\"\n#include \"time.h\"\n#include \n#include \"adkCSparse.h\"\n#include \"AFS_ctmc.h\"\n#include \n#include \"AFS_ctmc_petsc.h\"\n#include \"im_clam.h\"\n\nvoid import2DSFSData(const char *fileName, gsl_matrix *obsData);\n\nPetscInt n1, n2;\n\nafsStateSpace *stateSpace, *reducedStateSpace;\n\nclam_lik_params *currentParams, *nextParams;\n\ngsl_matrix *transMat;\ndouble *res;\n\ndouble lowerBounds[5] = {0.01,0.01,0.0,0.0,0.001};\ndouble upperBounds[5] = {10.0,10.0,20.0,20.0,10.0};\nPetscBool vbse = PETSC_FALSE;\n\nstatic char help[] = \"im_clam\\n\\\n\tExample: mpiexec -n ./im_clam -s -m -d \\n\\n\\toptions:\\n\\\n\t\\t-exp expected value mode (requires -x flag too)\\n\\\n\t\\t-GIM uncertainty estimation mode (requires -x flag too)\\n\\\n\t\\t-mo multiple optimizations from different start points\\n\\\n\t\\t-global multi-level optimization (MLSL algo.)\\n\\\n\t\\t-x parameter starting values\\n\\\n\t\\t-obs (prints out observed AFS as well as that expected from MLE params)\\n\\\n\t\\t-u mutation rate per base pair per generation (only used to unscale parameters; default 1e-8)\\n\\\n\t\\t-g generation time (gens/year; default 20)\\n\\\n\t\\t-seqLen sequence length scanned for polymorphisms (used to unscale parameter)\\n\\\n\t\\t-put upper bound for optimization of thetas\\n\\\n\t\\t-pum upper bound for optimization of migration rates\\n\\\n\t\\t-pudt upper bound for optimization of divergence time\\n\\\n\t\\t-r randomSeed\\n\\\n\t\\t-v verbose output\\n\";\n\t\n\n\nint main(int argc, char **argv){\n\tPetscInt i,j, N,runMode;\n\tclock_t time1, time2;\n\tPetscInt nnz;\n\tPetscInt seed;\n\tchar filename[PETSC_MAX_PATH_LEN], filename2[PETSC_MAX_PATH_LEN], filename3[PETSC_MAX_PATH_LEN] ;\n\tdouble lik = 0.0;\n\tdouble mle[5] = {0.1,2,1,1,5};\n \tconst gsl_rng_type * T;\n \tgsl_rng * r;\n\tPetscErrorCode ierr;\n\tPetscMPIInt rank,size;\n\tPetscBool flg,obsFlag;\n//\tVec tmpVec;\n\tPetscInt dim=5;\n\tdouble snpNumber, pi_est, p, N0;\n\tdouble u=1e-8;\n\tdouble genPerYear=20;\n\tdouble put = 10.0;\n\tdouble pum = 20.0;\n\tdouble pudt=10.0;\n\tdouble propSnp;\n\tPetscInt seqLen;\n\tgsl_matrix *fi,*gi;\n\tFILE *infile;\n\tPetscInt testInt=0;\n\tPetscScalar one = 1.0;\n\tcs *ident;\n\t \n\t///////////////////\n\t/////\tPETSC / Slepc library version of this code\n\tSlepcInitialize(&argc,&argv,(char*)0,help);\n\tierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank);CHKERRQ(ierr);\n\tierr = MPI_Comm_size(PETSC_COMM_WORLD, &size);CHKERRQ(ierr);\n\tif(rank==0){\n\n\t\tprintf(\"\\n.___ _____ .__\\n| | / \\\\ ____ | | _____ _____\\n| |/ \\\\ / \\\\ _/ ___\\\\| | \\\\__ \\\\ / \\\\\\n| / Y \\\\ \\\\ \\\\___| |__/ __ \\\\| Y Y \\\\\\n|___\\\\____|__ /____\\\\___ >____(____ /__|_| /\\n \\\\/_____/ \\\\/ \\\\/ \\\\/\\n\\n\\n\");\n\n\n\t\tprintf(\"im_clam -- Isolation with Migration Composite Likelihood Analysis using Markov chains\\n\");\n\t\t//printf(\"A.D. Kern 2015\\n///////////////////\\n\");\n\t\tprintf(\"\\n\\n\");\n\t}\n\tif(argc<2){\n\t\tprintf(\"%s\",help);\n\t\texit(666);\n\t}\n\ttime1=clock();\n\t\n\tierr = PetscOptionsGetString(NULL,\"-s\",filename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetString(NULL,\"-m\",filename2,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetString(NULL,\"-d\",filename3,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetInt(NULL,\"-r\",&seed,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetReal(NULL,\"-u\",&u,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetReal(NULL,\"-g\",&genPerYear,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetInt(NULL,\"-seqLen\",&seqLen,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetReal(NULL,\"-put\",&put,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetReal(NULL,\"-pum\",&pum,&flg);CHKERRQ(ierr);\n\tierr = PetscOptionsGetReal(NULL,\"-pudt\",&pudt,&flg);CHKERRQ(ierr);\n\t//set upper bounds\n\tupperBounds[0]=put;upperBounds[1]=put;upperBounds[2]=pum;upperBounds[3]=pum;upperBounds[4]=pudt;\n\t\n\tif(!flg) seed=time(NULL);\n\t\n\t//printf(\"rank:%d %d\\n\",rank,seed);\n\tMPI_Bcast(&seed,1,MPI_INT,0,PETSC_COMM_WORLD);\n\t//printf(\"rank:%d %d\\n\",rank,seed);\n\t\n\trunMode = 1;\n\tobsFlag=PETSC_FALSE;\n\t\n\t//setup RNG for starting point for optimization\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\tgsl_rng_set(r,seed);\n\t\n\tfor(i=0;instates;\n\n\n\t//quick peak at the mats file to set nnz\n\t//open file\n\tinfile = fopen(filename2, \"r\");\n\tif (infile == NULL){\n\t\tfprintf(stderr,\"Error opening mats file! ARRRRR!!!!\\n\");\n\t\texit(1);\n\t}\n\ttestInt=fscanf(infile,\"nnz: %d\", &nnz);\n\tfclose(infile);\n\t//got nnz, time for allocs\n\t\n\t//setup currentParams struct; alloc all arrays\n\tcurrentParams = malloc(sizeof(clam_lik_params));\n\tcurrentParams->rng = r;\n\tcurrentParams->n1 = n1 = stateSpace->states[0]->popMats[0]->size1 - 1;\n\tcurrentParams->n2 = n2 = stateSpace->states[0]->popMats[1]->size2 - 1;\n\tcurrentParams->stateSpace = stateSpace;\n\tcurrentParams->rank = rank;\n//\tcurrentParams->snpNumber = snpNumber;\n\tcurrentParams->expAFS = gsl_matrix_alloc(n1+1,n2+1);\n\tcurrentParams->expAFS2 = gsl_matrix_alloc(n1+1,n2+1);\n\tcurrentParams->map = malloc(sizeof(PetscInt)*N);\n\tcurrentParams->reverseMap = malloc(sizeof(PetscInt)*N);\n\tcurrentParams->rates = gsl_vector_alloc(stateSpace->nstates);\n\tcurrentParams->stateVec = gsl_vector_alloc(stateSpace->nstates);\n\tcurrentParams->resVec = gsl_vector_alloc(stateSpace->nstates);\n\tgsl_vector_set_zero(currentParams->resVec);\n//\tcurrentParams->paramVector = gsl_vector_alloc(5);\n//\tcurrentParams->paramCIUpper = gsl_vector_alloc(5);\n//\tcurrentParams->paramCILower = gsl_vector_alloc(5);\n//\tcurrentParams->mlParams = gsl_vector_alloc(5);\n\n\tcurrentParams->top = malloc(sizeof(double) * nnz);\n\tcurrentParams->topA = malloc(sizeof(double) * nnz);\n\n\tcurrentParams->move = malloc(sizeof(PetscInt) * nnz);\n\tcurrentParams->moveA = malloc(sizeof(PetscInt) * nnz);\n//\tprintf(\"allocated moveType...\\n\");\n\tfor(i=0;i< (nnz);i++){\n\t\tcurrentParams->move[i]=0;\n\t\tcurrentParams->top[i]=0;\n\t\tcurrentParams->moveA[i]=0;\n\t\tcurrentParams->topA[i]=0;\n\t}\n\tcurrentParams->dim1 = malloc(sizeof(PetscInt) * nnz);\n\tcurrentParams->dim2 = malloc(sizeof(PetscInt) * nnz);\n\tcurrentParams->dim1A = malloc(sizeof(PetscInt) * N * 10);\n\tcurrentParams->dim2A = malloc(sizeof(PetscInt) * N * 10);\n\tcurrentParams->b = malloc(N*sizeof(double));\n\tcurrentParams->expoArray = malloc(N*sizeof(double));\t\n\tcurrentParams->st = malloc(N*sizeof(double));\t\n\tcurrentParams->paramVector = gsl_vector_alloc(5);\n\tgsl_vector_set_all(currentParams->paramVector,1.0);\n\tcurrentParams->fEvals=0;\n\n\n\tcurrentParams->triplet = cs_spalloc(N, N, nnz + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats\n\tident = cs_spalloc(N,N,N,1,1);\n\tfor(i=0;ieye = cs_compress(ident);\n\tcs_spfree(ident);\n\t\n\t//set up some petsc matrices//////////////////////////////////////////////////////////////\n\t//\n\t//\n\t\n\tierr = MatCreate(PETSC_COMM_WORLD,¤tParams->C);CHKERRQ(ierr);\n//\tMatSetType(C,MATMPIAIJ);\n\tierr = MatSetSizes(currentParams->C, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr);\n\tierr = MatSetFromOptions(currentParams->C);CHKERRQ(ierr);\n//\tMatSetOption(currentParams->C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE);\n\tierr = MatSetUp(currentParams->C);CHKERRQ(ierr);\n\n\tierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, N, N, NULL, ¤tParams->denseMat1);CHKERRQ(ierr);\n\tierr = MatSetFromOptions(currentParams->denseMat1);CHKERRQ(ierr); \n\tMatAssemblyBegin(currentParams->denseMat1,MAT_FINAL_ASSEMBLY);\n\tMatAssemblyEnd(currentParams->denseMat1,MAT_FINAL_ASSEMBLY);\n\n\t///////// Set up MFN ////////////////////////////////////////////////////////////////////////////////////////\n\tierr = MFNCreate(PETSC_COMM_WORLD,¤tParams->mfn);CHKERRQ(ierr);\t\n\tierr = MFNSetFunction(currentParams->mfn,SLEPC_FUNCTION_EXP);CHKERRQ(ierr);\n\tierr = MFNSetTolerances(currentParams->mfn,1e-07,PETSC_DEFAULT);CHKERRQ(ierr);\n\t\n\t\n\t//mapping stateSpace to reducedSpace\n\tcurrentParams->reducedStateSpace = afsStateSpaceNew();\n\tafsStateSpaceMapAndReducePopn(currentParams->stateSpace, currentParams->map, currentParams->reducedStateSpace, currentParams->reverseMap);\n\tcurrentParams->Na=currentParams->reducedStateSpace->nstates;\n\t\t\n\tVecCreate(PETSC_COMM_WORLD,¤tParams->ancStateVec);\n\tVecSetSizes(currentParams->ancStateVec,PETSC_DECIDE,currentParams->Na);\n\tVecSetFromOptions(currentParams->ancStateVec);\n\tVecDuplicate(currentParams->ancStateVec,¤tParams->ancResVec);\n\n\t//set up more matrices\n\tierr = MatCreate(PETSC_COMM_WORLD,¤tParams->C2);CHKERRQ(ierr);\n\tMatSetType(currentParams->C2,MATMPIAIJ);\n\tierr = MatSetSizes(currentParams->C2, PETSC_DECIDE, PETSC_DECIDE,currentParams->Na,currentParams->Na);CHKERRQ(ierr);\n\tierr = MatSetFromOptions(currentParams->C2);CHKERRQ(ierr);\n\tierr = MatSetUp(currentParams->C2);CHKERRQ(ierr);\n\n\tierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, currentParams->Na, currentParams->Na, NULL, ¤tParams->denseMat2);CHKERRQ(ierr);\n\t\n\tident = cs_spalloc(currentParams->Na,currentParams->Na,currentParams->Na,1,1);\n\tfor(i=0;iNa;i++) cs_entry(ident,i,i,1);\n\tcurrentParams->eyeAnc = cs_compress(ident);\n\tcs_spfree(ident);\n\t\n\t//DTMC with PETSC /////////////\n//\tierr = MatCreate(PETSC_COMM_WORLD,¤tParams->D);CHKERRQ(ierr);\n//\tierr = MatSetSizes(currentParams->D, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr);\n//\tierr = MatSetFromOptions(currentParams->D);CHKERRQ(ierr);\n//\tierr = MatSetUp(currentParams->D);CHKERRQ(ierr);\n\t\n//\tierr = MatCreate(PETSC_COMM_WORLD,¤tParams->D_copy);CHKERRQ(ierr);\n//\tierr = MatSetSizes(currentParams->D_copy, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr);\n//\tierr = MatSetFromOptions(currentParams->D_copy);CHKERRQ(ierr);\n//\tierr = MatSetUp(currentParams->D_copy);CHKERRQ(ierr);\n\t\n\t//sparse identity mat\n//\tierr = MatCreate(PETSC_COMM_WORLD,¤tParams->ident);CHKERRQ(ierr);\n//\tierr = MatSetSizes(currentParams->ident, PETSC_DECIDE, PETSC_DECIDE,N,N);CHKERRQ(ierr);\n//\tierr = MatSetFromOptions(currentParams->ident);CHKERRQ(ierr);\n//\tierr = MatSetUp(currentParams->ident);CHKERRQ(ierr);\n\n //\tMatAssemblyBegin(currentParams->ident,MAT_FINAL_ASSEMBLY);\n //\tMatAssemblyEnd(currentParams->ident,MAT_FINAL_ASSEMBLY);\n//\tMatShift(currentParams->ident,one);\n\t\n\t//dense identity mat\n//\tierr = MatCreateDense(PETSC_COMM_WORLD,PETSC_DECIDE, PETSC_DECIDE, N, N, NULL, ¤tParams->denseIdent);CHKERRQ(ierr);\n//\tierr = MatSetFromOptions(currentParams->denseIdent);CHKERRQ(ierr); \n\t\n//\tMatAssemblyBegin(currentParams->denseIdent,MAT_FINAL_ASSEMBLY);\n //\tMatAssemblyEnd(currentParams->denseIdent,MAT_FINAL_ASSEMBLY);\n//\tMatShift(currentParams->denseIdent,one);\n\t\n\n//\tVecCreate(PETSC_COMM_WORLD,¤tParams->xInv);\n//\tVecSetSizes(currentParams->xInv,PETSC_DECIDE,N);\n//\tVecSetFromOptions(currentParams->xInv);\n//\tVecDuplicate(currentParams->xInv,¤tParams->bInv);\n\t\n\n\n\t\n\t///////////////////////////////////////\n\t\n\t//////////////////////////////\n\t\n\t// setup done! ///////////////\n\t////////////////////////////////////\n\n\t\n\t//import mats\n\tmcMatsImportFromFile(filename2, &nnz, currentParams->top, currentParams->move, currentParams->dim1, currentParams->dim2);\n\tcurrentParams->nnz = nnz;\n\t\t\n\n\t//init snpNumber to avoid compiler warning\n\tsnpNumber=0;\t\n\tif(runMode != 2){\n\t\t//alloc data matrix and import data; estimate pi and N1\n\t\tcurrentParams->obsData = gsl_matrix_alloc(n1+1,n2+1);\n\t\timport2DSFSData(filename3, currentParams->obsData);\n\t\tsnpNumber = gsl_matrix_sum(currentParams->obsData);\n\t\tpropSnp = (float) snpNumber / (float) seqLen;\n\t//\tpi_est = 0.0;\n\t//\tfor(i=1;iobsData,i,j);\n\t//\t\t}\n\t//\t}\n\t//\tpi_est *= n1 / (n1 - 1) / snpNumber;\n\t//\tN0=pi_est / u / 4;\n\t}\n\n\t////////////////////////////\n\ttime2=clock();\n\tif(rank==0)printf(\"setup time:%f secs\\n\\n\",(double) (time2-time1)/CLOCKS_PER_SEC);\n\t\n\ttime1=clock();\n\t//expected AFS\n\t//printf(\"runMode = %d\\n\",runMode);\n\tswitch(runMode){\n\t\t\n\t\t\n\t\tcase 1:\n\t\tif(rank==0){\n\t\t\tprintf(\"\\nParameter estimation run mode\\n\\n\");\n\t\t\tprintf(\"now optimizing....\\n\\n\");\n\t\t\tprintf(\"initial parameter guess:\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f \",mle[i]);\n\t\t\tprintf(\"\\n\\n\");\n\t\t}\n\t\tmaximizeLikNLOpt(&lik, currentParams, mle);\n\t\tfi = getGodambeInfoMatrix(mle, lik, currentParams);\n\t\t//get N0 estimate\n\t\tN0 = propSnp / currentParams->meanTreeLength / 4.0 / u;\t\n\t\tif(rank == 0){\n\t\t\tprintf(\"for scaling:\\nu: %e gen: %lf N0:%lf meanTreeLength:%lf seqLen:%d\\n\",u,genPerYear,N0,currentParams->meanTreeLength,seqLen);\n\t\t\tprintf(\"Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float)mle[i]);\n\t\t\tprintf(\"\\n\\nComposite Likelihood estimates of IM params (unscaled):\\n\");\n\t\t\t\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<2;i++)printf(\"%f\\t\",(float)mle[i]*N0);\n\t\t\tfor(i=2;i<4;i++)printf(\"%f\\t\",(float)mle[i]/N0/4);\n\t\t\tprintf(\"%f\\t\",(float)mle[i] * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i)));\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (unscaled):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<2;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i))*N0);\n\t\t\tfor(i=2;i<4;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i))/N0/4);\n\t\t\tprintf(\"%f\\t\",(float)sqrt(gsl_matrix_get(fi,i,i)) * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\");\n\t\t\t\n\t\t\tprintf(\"\\n\\nlikelihood: %lf\\n\",-lik);\n\t\t\tcurrentParams->nnz = nnz;\n\t\t\tprintf(\"\\nExpected AFS:\\n\");\n\t\t\tgsl_matrix_prettyPrint(currentParams->expAFS);\n\t\t}\n\t\t\n\t\t\n\t\tbreak;\t\n\t\tcase 2:\n\t\tif(rank == 0)printf(\"expected value run mode\\n\");\n\t\tfor(i=0;i<5;i++){\n\t\t\tgsl_vector_set(currentParams->paramVector,i,mle[i]);\n\t\t}\n\t\tcalcLogAFS_IM(currentParams);\n\t\tcurrentParams->nnz = nnz;\n\t\tif(rank == 0){\n\t\t\tprintf(\"Expected AFS:\\n\");\n\t\t\tgsl_matrix_prettyPrint(currentParams->expAFS);\n\t\t\tprintf(\"parameter values used:\\n\");\n\t\t\tfor(i=0;iparamVector,i));\n\t\t\tprintf(\"\\n\\n\");\n\t\t}\n\t\ttime2=clock();\n\t\t//lik = calcLikNLOpt(5,mle,NULL,currentParams);\n\t\t//\n\t\t\n\t\t//printf(\"Likelihood: %g\\n\",lik);\n\t\t//if(rank==0)printf(\"w/ CSPARSE time:%f secs\\n Liklihood Func. Evals: %d\\n\",(double) (time2-time1)/CLOCKS_PER_SEC,currentParams->fEvals);\n\t\ttime1=clock();\n\t\tbreak;\n\t\tcase 3:\n\t\tif(rank==0){\n\t\t\tprintf(\"\\nParameter estimation run mode with multiple optimizations\\n\\n\");\n\t\t\tprintf(\"now optimizing....\\n\\n\");\n\t\t\tprintf(\"initial parameter guess:\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f \",mle[i]);\n\t\t\tprintf(\"\\n\\n\");\n\t\t}\n\t\tfor(j = 0; j < 3; j++){\n\t\t\t\n\t\t\tfor(i=0;i<5;i++)mle[i] = gsl_ran_flat(r,lowerBounds[i], upperBounds[i]);\n\t\t\tprintf(\"optimization %d initial parameter guess:\\n\",j);\n\t\t\tfor(i=0;i<5;i++)printf(\"%f \",mle[i]);\n\t\t\tmaximizeLikNLOpt(&lik, currentParams, mle);\t\n\t\t\tif(rank == 0){\n\t\t\t\tprintf(\"Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float)mle[i]);\n\t\t\t\tprintf(\"\\n\\nlikelihood: %lf\\n\",-lik);\n\t\t\t\tcurrentParams->nnz = nnz;\n\t\t\t\tprintf(\"\\nExpected AFS:\\n\");\n\t\t\t\tgsl_matrix_prettyPrint(currentParams->expAFS);\n\t\t\t}\n\t\t}\n\t\t\n\t\tbreak;\n\t\tcase 4:\n\t\tif(rank==0){\n\t\t\tprintf(\"\\nParameter estimation run mode\\n\\n\");\n\t\t\tprintf(\"now optimizing....\\n\\n\");\n\t\t\tprintf(\"initial parameter guess:\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f \",mle[i]);\n\t\t\tprintf(\"\\n\\n\");\n\t\t}\n\t\tmaximizeLikNLOpt_MLSL(&lik, currentParams, mle);\n\t\tfi = getGodambeInfoMatrix(mle, lik, currentParams);\t\n\t\tif(rank == 0){\n\t\t\tN0 = propSnp / currentParams->meanTreeLength / 4.0 / u;\t\n\t\t\tprintf(\"Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float)mle[i]);\n\t\t\tprintf(\"\\n\\nComposite Likelihood estimates of IM params (unscaled):\\n\");\n\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<2;i++)printf(\"%f\\t\",(float)mle[i]*N0);\n\t\t\tfor(i=2;i<4;i++)printf(\"%f\\t\",(float)mle[i]/N0/4);\n\t\t\tprintf(\"%f\\t\",(float)mle[i] * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i)));\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (unscaled):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<2;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i))*N0);\n\t\t\tfor(i=2;i<4;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(fi,i,i))/N0/4);\n\t\t\tprintf(\"%f\\t\",(float)sqrt(gsl_matrix_get(fi,i,i)) * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\");\n\n\t\t\tprintf(\"\\n\\nlikelihood: %lf\\n\",-lik);\n\t\t\tcurrentParams->nnz = nnz;\n\t\t\tprintf(\"\\nExpected AFS:\\n\");\n\t\t\tgsl_matrix_prettyPrint(currentParams->expAFS);\n\t\t}\n\t\t\n\t\t\n\t\tbreak;\n\t\tcase 5:\n\t\tfor(i=0;i<5;i++){\n\t\t\tgsl_vector_set(currentParams->paramVector,i,mle[i]);\n\t\t}\n\t\tif(rank==0){\n\t\t\tprintf(\"\\nUncertainty estimation (via Godambe Information) run mode\\n\\n\");\n\t\t\tprintf(\"MLE parameters:\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f \",mle[i]);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tlik = calcLikNLOpt(5,mle,NULL,currentParams);\n\t\tgi = getGodambeInfoMatrix(mle, lik, currentParams);\n\t\tN0 = propSnp / currentParams->meanTreeLength / 4.0 / u;\t\n\t\t\n\t\t// if(rank==0){\n\t\t// \tprintf(\"FIM:\\n\");\n\t\t// \tgsl_matrix_prettyPrint(fi);\n\t\t// \tprintf(\"\\nGIM:\\n\");\n\t\t// \tgsl_matrix_prettyPrint(gi);\n\t\t// \tprintf(\"\\n\");\n\t\t// }\n\t\tif(rank==0){\n\t\t\tprintf(\"\\nlikelihood: %lf\\n\",-lik);\n\t\t\tprintf(\"Composite Likelihood estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float)mle[i]);\n\t\t\tprintf(\"\\n\\nComposite Likelihood estimates of IM params (unscaled):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<4;i++)printf(\"%f\\t\",(float)mle[i]*N0);\n\t\t\tprintf(\"%f\\t\",(float)mle[i] * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (scaled by 1/theta_pop1):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<5;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(gi,i,i)));\n\t\t\tprintf(\"\\n\\nUncertainty estimates of IM params (unscaled):\\n\");\n\t\t\tprintf(\"theta_pop2\\ttheta_anc\\tmig_1->2\\tmig_2->1\\tt_div\\n\");\n\t\t\tfor(i=0;i<4;i++)printf(\"%f\\t\",(float) sqrt(gsl_matrix_get(gi,i,i))*N0);\n\t\t\tprintf(\"%f\\t\",(float)sqrt(gsl_matrix_get(gi,i,i)) * N0 * 4.0/ (float)genPerYear);\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t\tbreak;\n\t}\n\t\t\n\tif(obsFlag && rank==0){\n\t\tgsl_matrix_scale(currentParams->obsData,1.0/snpNumber);\n\t\tprintf(\"%f SNPs in dataset\\n\",snpNumber);\n\t\tprintf(\"Observed AFS:\\n\");\n\t\tgsl_matrix_prettyPrint(currentParams->obsData);\n\t\tgsl_matrix_scale(currentParams->obsData,snpNumber);\n\t}\n\t\n\t\n\tMatDestroy(¤tParams->denseMat1);\n\tMatDestroy(¤tParams->denseMat2);\n\tMatDestroy(¤tParams->C);\n\tMatDestroy(¤tParams->C2);\n\tMatDestroy(¤tParams->D);\n\tMatDestroy(¤tParams->D_copy);\n\tMatDestroy(¤tParams->denseIdent);\n\tMatDestroy(¤tParams->ident);\n\tMFNDestroy(¤tParams->mfn);\n\tVecDestroy(¤tParams->ancStateVec);\n\tVecDestroy(¤tParams->ancResVec);\n\tVecDestroy(¤tParams->xInv);\n\tVecDestroy(¤tParams->bInv);\n\tgsl_rng_free (r);\n\t\n\tafsStateSpaceFree(currentParams->reducedStateSpace);\t\n\ttime2=clock();\n\tif(rank==0)printf(\"total run time:%f secs\\n Liklihood Func. Evals: %d\\n\",(double) (time2-time1)/CLOCKS_PER_SEC,currentParams->fEvals);\n\tierr = PetscFinalize();\n\n\treturn(0);\n}\n\n//import2DSFSData -- imports a matrix from fileName and stuffs it in prealloc'd obsData\nvoid import2DSFSData(const char *fileName, gsl_matrix *obsData){\n\tFILE *infile;\n\t\n\t//open file\n\tinfile = fopen(fileName, \"r\");\n\tif (infile == NULL){\n\t\tfprintf(stderr,\"Error opening data file! ARRRRR!!!!\\n\");\n\t\texit(1);\n\t}\n\tgsl_matrix_fscanf(infile,obsData);\n\tfclose(infile);\n}\n", "meta": {"hexsha": "0780e0251d4480b37b2425d6c972baa2bd8db582", "size": 21256, "ext": "c", "lang": "C", "max_stars_repo_path": "im_clam.c", "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_issues_repo_path": "im_clam.c", "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_forks_repo_path": "im_clam.c", "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3567662566, "max_line_length": 303, "alphanum_fraction": 0.6825837411, "num_tokens": 6752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.45948887065546895}} {"text": "/* Copyright (c) 2014, Giuseppe Argentieri \n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\n/*\n *\n *\n * Filename: red_gen.c\n *\n * Description: Redfield-type Generator \n *\n * Version: 1.0\n * Created: 25/04/2014 22:28:19\n * Revision: none\n * License: BSD\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: Università degli Studi di Trieste\n *\n * \n */\n\n#include \n#include \n#include \n#include \"funcs.h\"\n\n\n/* \n * FUNCTION \n * Name: red_mat\n * Description: Creating the Redfield generator matrix in Bloch form, taking as\n * \t\t arguments all the integrals, the physical parameters \n * \t\t and the pointer to the matrix\n * \n */\nint red_mat ( gsl_matrix* red_mx , void* params )\n{\n\tdouble integrals[12] ;\n\tif ( integration(params,integrals) != 0 )\n\t\treturn -1;\n\n\t/* Setting the integrals */\n\tdouble rcc, icc, rss, iss, rsc, isc, rcs, ics, rc0, ic0, rs0, is0 ;\n\trcc = integrals[0] ;\n\ticc = integrals[1] ;\n\trss = integrals[2] ;\n\tiss = integrals[3] ;\n\trsc = integrals[4] ;\n\tisc = integrals[5] ;\n\trcs = integrals[6] ;\n\tics = integrals[7] ;\n\trc0 = integrals[8] ;\n\tic0 = integrals[9] ;\n\trs0 = integrals[10] ;\n\tis0 = integrals[11] ;\n\n\t/* Copying the parameters */\n\tstruct f_params* pars = (struct f_params*) params ;\n\tdouble o_c, b, O, o_1 ;\n\tassign_p ( pars, &o_c, &b, &O, &o_1 ) ;\n\tdouble D = sqrt(POW_2(o_1)-POW_2(O)) ;\n\n\t/* Ensuring that the matrix is zeroed */\n\tgsl_matrix_set_zero ( red_mx ) ;\n\n\t/* Building the matrix */\n\tgsl_matrix_set ( red_mx, 1, 0, (D/o_1)*(-(O/o_1)*ic0+iss+(O/o_1)*icc) ) ;\n\tgsl_matrix_set ( red_mx, 1, 1, POW_2(D/o_1)*rc0+(O/o_1)*rss+POW_2(O/o_1)*rcc ) ;\n\tgsl_matrix_set ( red_mx, 1, 2, o_1/4+(O/o_1)*rsc-POW_2(O/o_1)*rcs ) ;\n\tgsl_matrix_set ( red_mx, 1, 3, (D/o_1)*(rsc-(O/o_1)*rcs) ) ;\n\tgsl_matrix_set ( red_mx, 2, 0, (D/o_1)*(is0+isc-(O/o_1)*ics) ) ;\n\tgsl_matrix_set ( red_mx, 2, 1, -(o_1/4)-(O/o_1)*rsc+rcs ) ;\n\tgsl_matrix_set ( red_mx, 2, 2, POW_2(D/o_1)*rc0+rcc+(O/o_1)*rss ) ;\n\tgsl_matrix_set ( red_mx, 2, 3, -(D/o_1)*((O/o_1)*rcc+rss) ) ;\n\tgsl_matrix_set ( red_mx, 3, 0, (1+POW_2(O/o_1))*ics-2*(O/o_1)*isc ) ;\n\tgsl_matrix_set ( red_mx, 3, 1, -(D/o_1)*rs0 ) ; \n\tgsl_matrix_set ( red_mx, 3, 2, -(O*D/(o_1*o_1))*rc0 ) ;\n\tgsl_matrix_set ( red_mx, 3, 3, (1+POW_2(O/o_1))*rcc+2*(O/o_1)*rss ) ;\n\n\t/* Multiplies times -4 to obtain the Bloch matrix */\n\tgsl_matrix_scale ( red_mx, -4 ) ;\n\n\n\treturn 0;\n}\t\t/* ----- end of function red_mat ----- */\n\n\n", "meta": {"hexsha": "682f7ff433585c6862b33848283520dfbda88d86", "size": 3836, "ext": "c", "lang": "C", "max_stars_repo_path": "red_gen.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "red_gen.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "red_gen.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9469026549, "max_line_length": 81, "alphanum_fraction": 0.6676225235, "num_tokens": 1250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4594888650590204}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mathfunctions.h\"\n#include \"globals.h\"\n#include \"constitutive_equations.h\"\n\n/*****************************************************************************/\n/***************************************************************************/\n/************ Compute the spatial discretization of the equation ***********/\n/***************************************************************************/\n\n\nextern const double g;\nextern void Compute_InnerProducts(double IP1[], double IP2[], double IP3[], double IP4[], double IP5[], double IP6[], double IP7[], double IP8[], double IP9[], double IP10[]);\nextern void RoeFlux( double *Fhat, double A_L, double A_R, double Q_L, double Q_R, double b, double m1val, double m2val, double g);\nextern void LF(double *Fhat, double A_L, double A_R, double Q_L, double Q_R, double b, double g);\n\nextern void* xcalloc(int items, int size);\nextern void GetLGLWeights(int N, double *w);\n\nvoid computeL()\n{\n\tdouble* Fhat1L = xcalloc(NumNodes, sizeof(double));\n\tdouble* Fhat2L = xcalloc(NumNodes, sizeof(double));\n\tdouble* Fhat1R = xcalloc(NumNodes, sizeof(double));\n\tdouble* Fhat2R = xcalloc(NumNodes, sizeof(double));\n\n\n#ifdef WDON\n/**** Compute the mass over an element to use later for ensuring ********/\n/**** positive mass with the flux in a wetting and drying treatment *************/\n\tdouble mass[NumEl];\n\tdouble LGLWeight[Np];\n\tGetLGLWeights(P, LGLWeight);\n\n\tfor (int i = 0; i < NumEl; ++i)\n\t{\n\t\tdouble avgArea = 0;\n\t\tint begNode = i*Np + 1;\n\t\tfor (int j =0; j < Np; j++)\n\t\t{\n\t\t\tavgArea += LGLWeight[j]*A[begNode+1];\n\t\t}\n\t\tmass[i] = avgArea;\n\t}\n#endif\n\t\t\n/************** Compute the numerical flux at the faces *****************/\n\tfor (int i=0; i < NumEdges; ++i)\n\t{\n\t\tdouble A_L, Q_L, A_R, Q_R, m1val, m2val;\n\n\t\tint leftNode = i*Np;\n\t\tint rightNode = leftNode+1;\n\t\n\t\tm1val = m1[i];\n\t\tm2val = m2[i];\n\n\t\tdouble tmpF[2];\n\t\t\n\t\t#ifdef WDON\n\t\t// Check to see if the elements separated by this boundary are both dry\n\t\tif (i > 0 && i < NumNodes-1)\n\t\t{\n\t\t\tif (WD[i-1] == 0 && WD[i] == 0)\n\t\t\t{\n\t\t\t\t// Reflection flux for the left element\n\t\t\t\tA_L = A[leftNode];\n\t\t\t\tA_R = A_L;\n\t\t\t\tQ_L = Q[leftNode];\n\t\t\t\tQ_R = -Q_L;\n\t\t\t\t//LF(tmpF, A_L, A_R, Q_L, Q_R,b[i], m1val, m2val, 0);\n\t\t\t\tRoeFlux(tmpF, A_L, A_R, Q_L, Q_R,b[i], m1val, m2val,0);\n\t\t\t\tFhat1L[i] = tmpF[0];\n\t\t\t\tFhat2L[i] = tmpF[1];\n\t\t\t\t\n\t\t\t\t// Reflection flux for the right element\n\t\t\t\tA_R = A[rightNode];\n\t\t\t\tA_L = A_R;\n\t\t\t\tQ_R = Q[rightNode];\n\t\t\t\tQ_L = -Q_R;\n\t\t\t\t//LF(tmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0);\n\t\t\t\tRoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0);\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\n\n\t\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"both elements dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t}\n\n\t\t// if the elements are not both dry\n\t\tif ((i == 0) || (i == NumEl) || WD[i-1] == 1 || WD[i] == 1)\n\t\t{\n\t\t\tA_L = A[leftNode];\n\t\t\tA_R = A[rightNode];\n\t\n\t\t\tQ_L = Q[leftNode];\n\t\t\tQ_R = Q[rightNode];\n\n\t\t\tRoeFlux(tmpF, A_L, A_R, Q_L,Q_R,b[i], m1val, m2val, g);\n\t\t\t//LF(tmpF, A_L, A_R, Q_L,Q_R,b[i], m1val, m2val, g);\n\t\n\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t{\n\t\t\t\tprintf(\" both elements wet flux not a number, edge %d \\n\",i);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\t\n\t\t\tif (i==0 || WD[i-1] == 1)\n\t\t\t{\n\t\t\t\tFhat1L[i] = tmpF[0];\n\t\t\t\tFhat2L[i] = tmpF[1];\t\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble newtmpF[2];\n\t\t\t\t//LF(newtmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0);\n\t\t\t\tRoeFlux(newtmpF, A_L, A_R, Q_L, Q_R, b[i], m1val, m2val, 0);\n\t\t\t\tFhat1L[i] = newtmpF[0];\n\t\t\t\tFhat2L[i] = newtmpF[1];\n\t\t\t\tif (isnan(newtmpF[0]) || isnan(newtmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"left element dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\n\t\t\t}\n\t\t\tif (i == NumEl || WD[i]==1)\n\t\t\t{\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//LF(tmpF, A_L,A_R,Q_L,Q_R,b[i], m1val, m2val, 0);\n\t\t\t\tRoeFlux(tmpF, A_L,A_R,Q_L,Q_R,b[i], m1val, m2val, 0);\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\t\t\n\t\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"right element dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\n\t\t\t}\n\t\t}\n\n\t\t#else\n\t\tA_L = A[leftNode];\n\t\tA_R = A[rightNode];\n\t\n\t\tQ_L = Q[leftNode];\n\t\tQ_R = Q[rightNode];\n\n\t\tRoeFlux(tmpF, A_L, A_R, Q_L,Q_R,b[i],m1val,m2val,g);\n\t\t//LF(tmpF, A_L, A_R, Q_L,Q_R,b[i],m1val,m2val,g);\n\t\n\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t{\n\t\t\tprintf(\"flux not a number, edge %d \\n\",i);\n\t\t\tprintf(\"A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf, b = %lf, m1 = %lf, m2 = %lf \\n\", A_L, A_R, Q_L, Q_R, b[i], m1val, m2val);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t\t\n\t\tFhat1L[i] = tmpF[0];\n\t\tFhat2L[i] = tmpF[1];\t\n\n\t\tFhat1R[i] = tmpF[0];\n\t\tFhat2R[i] = tmpF[1];\n\t\t\n\t\t#endif\n\n\t\t/**************************************************************************************************/\n\t\tdouble u_L = Q_L/A_L;\n\t\tdouble u_R = Q_R/A_R;\n\t\tdouble c_L = sqrt(g*A_L/b[i]);\n\t\tdouble c_R = sqrt(g*A_R/b[i]);\n\n\t\tif (i==0)\n\t\t\tmax_lambda = fmax((fabs(u_L)+c_L), (fabs(u_R)+c_R));\t\t\t\n\t\t// Compute maximum eigenvalue for the next time step\n\t\tdouble current_max =fmax((fabs(u_L) + c_L), (fabs(u_R) + c_R));\n\t\tmax_lambda = max((max_lambda),(current_max));\n\t}\n\n\tprintf(\"max_lambda = %lf\\n\", max_lambda);\n\t#ifdef WDON\n\tfor (int i =1; i < NumNodes-1; ++i)\n\t{\n\t\tint leftNode = i*Np;\n\t\tint rightNode = leftNode+1;\n\t\tdouble maxBetaOverAlpha = 2;\n\t\t// Check to see if this flux might possibly result in negative mass\n\t\t// If the mass will be negative on the left side\n\t \tif (Fhat1L[i]*maxBetaOverAlpha*dt > mass[i-1])\n\t\t{\n\t double A_L = A[leftNode];\n\t\t\tdouble A_R = A_L;\n\t\t\tdouble Q_L = Q[leftNode];\n\t double Q_R = -Q_L;\n\t double tmpF[2];\n\t\t\tdouble localG = g;\n\t\t\t\n\t\t\t\n\t\t\tif (WD[i] == 0)\n\t\t\t\tlocalG = 0;\n\t\t\t\n\t\t\t//LF(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG);\n\t\t\tRoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG);\n\t \t\tFhat1L[i] = tmpF[0];\n\t \t\tFhat2L[i] = tmpF[1];\n\t\t\tprintf(\"element %d will be dry\\n\",i);\n\t \t}\n\t\t\n\t\n\t\t// If the mass will be negative on the right side\n\t\tif (-Fhat1R[i]*maxBetaOverAlpha*dt > mass[i])\n\t\t{\n\t\t\tdouble A_R = A[rightNode];\n\t\t\tdouble A_L = A_R;\n\t\t\tdouble Q_R = Q[rightNode];\n\t\t\tdouble Q_L = -Q_R;\n\t\t\tdouble tmpF[2];\n\t\t\tdouble localG = g;\n\t\t\tif (WD[i] == 0)\n\t\t\t\tlocalG = 0;\n\t\t\t//LF(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG);\n\t\t\tRoeFlux(tmpF, A_L, A_R, Q_L, Q_R, b[i],m1val,m2val,localG);\n\t\t\tFhat1R[i] = tmpF[0];\n\t\t\tFhat2R[i] = tmpF[1];\n\t\t\tprintf(\"element %d will be dry \\n\",i);\n\t\t\t\t\n\t\t}\n\t}\n\t#endif\n\n\t// Compute the right hand side\n//\tdouble IP1[NumEl], IP2[NumEl], IP3[NumEl], IP4[NumEl], IP5[NumEl], IP6[NumEl], IP7[NumEl], IP8[NumEl], IP9[NumEl], IP10[NumEl];\t\n//\tCompute_InnerProducts(IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9, IP10);\n\n\tint k;\n\tfor (k=0; k < NumEl; ++k) \n\t{\n\t\t\n\t\tdouble h = dh[k];\t\n\t\tgsl_vector *F1 = gsl_vector_alloc(Np);\n\t\tgsl_vector *F2 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST21 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST22 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST23 = gsl_vector_alloc(Np);\n\n\t\tint begNode = k*Np;\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tdouble Aval = A[begNode+i+1];\n\t\t\tdouble Qval = Q[begNode+i+1];\n\t\t\tdouble bval = NodalB[begNode+i];\n\t\t\tdouble S0 = dz[begNode+i];\n\t\t\tdouble m1val = Nodalm1[begNode+i];\n\t\t\tdouble m2val = Nodalm2[begNode+i];\n\t\t\tdouble dm1val = dm1[begNode+i];\n\t\t\tdouble dm2val = dm2[begNode+i];\n\t\t\tdouble hval = getH(Aval, bval, m1val, m2val);\n\t\t\tdouble I1val = getI1(Aval, bval, m1val, m2val);\n\t\t\tdouble I2val = getI2(Aval, bval, db[k*Np+i], m1val, dm1val, m2val, dm2val);\n\t\t\tdouble Sfval = getS_f(Aval, Qval, bval, m1val, m2val, NodalnFriction[begNode+i]);\n\t\t\tdouble beta = 1.0;\n\t\t\tdouble localG;\n\t\t\t#ifdef WDON\n\t\t\tif(WD[k]==1)\n\t\t\t\tlocalG = g;\n\t\t\telse\n\t\t\t\tlocalG = 0;\n\t\t\t#else\n\t\t\t\tlocalG = g;\n\t\t\t#endif\n\t\t\t\n\t\t\tgsl_vector_set(F1, i, Qval);\n\t\t\tgsl_vector_set(F2, i, beta*Qval*Qval/Aval + g*I1val); \n\t\t\tgsl_vector_set(ST21, i, g*I2val);\n\t\t\t//gsl_vector_set(ST22, i, g*hval*bval*S0);\n\t\t\tgsl_vector_set(ST22, i, g*Aval*S0);\n\t\t\tgsl_vector_set(ST23, i, g*Aval*Sfval);\n\n\t\t}\n\n\t\tgsl_vector *localFhat1 = gsl_vector_alloc(2);\n\t\tgsl_vector_set(localFhat1, 0, Fhat1R[k]);\n\t\tgsl_vector_set(localFhat1, 1, Fhat1L[k+1]);\n\n\t\tgsl_vector *localFhat2 = gsl_vector_alloc(2);\n\t\tgsl_vector_set(localFhat2, 0, Fhat2R[k]);\n\t\tgsl_vector_set(localFhat2, 1, Fhat2L[k+1]);\n\n\t\t// cacluate the volume integral of the flux\n\t\tgsl_vector *localRHS1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *localRHS2 = gsl_vector_calloc(Np);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F1, 1.0, localRHS1);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F2, 1.0, localRHS2);\n\n\t\t// calculate the surface integral of the flux\n\t\tgsl_vector *SurfPart1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *SurfPart2 = gsl_vector_calloc(Np);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat1, 1.0, SurfPart1);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat2, 1.0, SurfPart2);\n\n\t\t// calculate the RHS\n\t\tgsl_vector_add(localRHS1, SurfPart1);\n\t\tgsl_vector_add(localRHS2, SurfPart2);\n\t\tgsl_vector_add(localRHS2, ST21);\n\t\tgsl_vector_add(localRHS2, ST22);\n\t\tgsl_vector_sub(localRHS2, ST23);\n\n\t\tgsl_vector_free(F1);\n\t\tgsl_vector_free(F2);\n\t\tgsl_vector_free(localFhat1);\n\t\tgsl_vector_free(localFhat2);\n\t\tgsl_vector_free(SurfPart1);\n\t\tgsl_vector_free(SurfPart2);\n\t\tgsl_vector_free(ST21);\n\t\tgsl_vector_free(ST22);\n\t\tgsl_vector_free(ST23);\n\t\n\t\tfor(int i = 0; i < Np; i++)\n\t\t{\n\t\t\tRHSA[begNode+i+1] = gsl_vector_get(localRHS1, i);\n\t\t\tRHSQ[begNode+i+1] = gsl_vector_get(localRHS2, i);\n\t\t}\n\n\t\tgsl_vector_free(localRHS1);\n\t\tgsl_vector_free(localRHS2);\n\n\t/*\t\n\t\tdouble F_el1[2] = {Fhat1R[k], Fhat1L[k+1]};\n\t\tdouble F_el2[2] = {Fhat2R[k], Fhat2L[k+1]};\n\n\t\tdouble invMrow1[2] = {4/h, -2/h};\n\t\tdouble invMrow2[2] = {-2/h, 4/h};\n\t\t//double invM[2][2] = {{4/(b-a), 2/(a-b)},{2/(a-b), 4/(b-a)}};\n\n\t\tdouble S1 = IP1[k] + F_el1[0];\n\t\tdouble S2 = IP2[k] - F_el1[1];\n\t\tdouble S3 = IP3[k] + F_el2[0] + IP4[k] + IP5[k] - IP6[k];\n\t\tdouble S4 = IP7[k] - F_el2[1] + IP8[k] + IP9[k] - IP10[k];\n\t\n\t\t// Compute RHSA = invM*[S1;S2] and RHSQ = invM*[S3;S4]\n\t\tRHSA[2*k + 1] = invMrow1[0]*S1 + invMrow1[1]*S2; \n\t\tRHSA[2*k + 2] = invMrow2[0]*S1 + invMrow2[1]*S2;\n\t\tRHSQ[2*k + 1] = invMrow1[0]*S3 + invMrow1[1]*S4;\n\t\tRHSQ[2*k + 2] = invMrow2[0]*S3 + invMrow2[1]*S4;\n*/\n\t}\n\n\t// The value at the ghost nodes will be the same as the values at the other side of the face\n\n\tRHSA[0] = RHSA[1];\n\tRHSA[NumNodes - 1] = RHSA[NumNodes - 2];\n\n\tRHSQ[0] = RHSQ[1];\n\tRHSQ[NumNodes - 1] = RHSQ[NumNodes - 2];\n\n\tfree(Fhat1L);\n\tfree(Fhat1R);\n\tfree(Fhat2L);\n\tfree(Fhat2R);\n\n}\n\n\n", "meta": {"hexsha": "e4458da3afdf60d29c9700c88931488eb2f679bb", "size": 10643, "ext": "c", "lang": "C", "max_stars_repo_path": "1DCode/computeL.c", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "1DCode/computeL.c", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "1DCode/computeL.c", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 27.8612565445, "max_line_length": 175, "alphanum_fraction": 0.5892135676, "num_tokens": 4136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45911459764382756}} {"text": "/* linalg/qr_ud.c\n * \n * Copyright (C) 2020 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * this module contains routines for the QR factorization of a matrix\n * using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with\n * additional modifications courtesy of Julien Langou.\n */\n\nstatic int aux_QR_TRD_decomp (gsl_matrix * U, gsl_matrix * A, const gsl_vector * D, gsl_matrix * T);\nstatic double qrtd_householder_transform (double *v0, double *v1);\nstatic double qrtrd_householder_transform (double *v0, gsl_vector * v, double *d);\n\n/*\ngsl_linalg_QR_UD_decomp()\n Compute the QR decomposition of the \"triangle on top of diagonal\" matrix\n\n [ U ] = Q [ R ]\n [ D ] [ 0 ]\n\nwhere U is N-by-N upper triangular, D is N-by-N diagonal\n\nInputs: U - on input, upper triangular N-by-N matrix\n on output, R factor in upper triangle\n D - diagonal N-by-N matrix\n Y - (output) upper triangular N-by-N matrix (lower part of V)\n T - (output) block reflector matrix, N-by-N\n\nNotes:\n1) Based on the Elmroth/Gustavson algorithm, taking into account the\nsparse structure of the U,S matrices\n\n2) The Householder matrix V has the special form:\n\n N\nV = [ I ] N\n [ Y ] N\n\nwith Y upper triangular\n\n3) The orthogonal matrix is\n\nQ = I - V T V^T\n*/\n\nint\ngsl_linalg_QR_UD_decomp (gsl_matrix * U, const gsl_vector * D, gsl_matrix * Y, gsl_matrix * T)\n{\n const size_t N = U->size1;\n\n if (N != U->size2)\n {\n GSL_ERROR (\"U matrix must be square\", GSL_ENOTSQR);\n }\n else if (D->size != N)\n {\n GSL_ERROR (\"D matrix does not match dimensions of U\", GSL_EBADLEN);\n }\n else if (Y->size1 != Y->size2)\n {\n GSL_ERROR (\"Y matrix must be square\", GSL_ENOTSQR);\n }\n else if (Y->size1 != N)\n {\n GSL_ERROR (\"Y matrix does not match dimensions of U\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (N == 1)\n {\n /* base case, compute Householder transform for single column matrix */\n double * T00 = gsl_matrix_ptr(T, 0, 0);\n double * U00 = gsl_matrix_ptr(U, 0, 0);\n double * Y00 = gsl_matrix_ptr(Y, 0, 0);\n *Y00 = gsl_vector_get(D, 0);\n *T00 = qrtd_householder_transform(U00, Y00);\n return GSL_SUCCESS;\n }\n else\n {\n /*\n * partition matrices:\n *\n * N1 N2 N1 N2\n * N1 [ U11 U12 ] and N1 [ T11 T12 ]\n * N2 [ 0 U22 ] N2 [ 0 T22 ]\n * N1 [ D11 D12 ]\n * N2 [ 0 D22 ]\n */\n int status;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1);\n gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2);\n gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2);\n\n gsl_vector_const_view D1 = gsl_vector_const_subvector(D, 0, N1);\n gsl_vector_const_view D2 = gsl_vector_const_subvector(D, N1, N2);\n\n gsl_matrix_view Y11 = gsl_matrix_submatrix(Y, 0, 0, N1, N1);\n gsl_matrix_view Y12 = gsl_matrix_submatrix(Y, 0, N1, N1, N2);\n\n gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);\n\n gsl_matrix_view m;\n\n /*\n * Eq. 2: recursively factor\n *\n * N1 N1\n * N1 [ U11 ] = Q1 [ R11 ] N1\n * N2 [ 0 ] [ 0 ] N2\n * N1 [ D11 ] [ 0 ] N1\n * N2 [ 0 ] [ 0 ] N2\n */\n status = gsl_linalg_QR_UD_decomp(&U11.matrix, &D1.vector, &Y11.matrix, &T11.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 3:\n *\n * N2 N2 N2\n * N1 [ R12 ] = Q1^T [ U12 ] = [ U12 - W ] N1\n * N2 [ U22~ ] [ U22 ] [ U22 ] N2\n * N1 [ D12~ ] [ 0 ] [ - V31 W ] N1\n * N2 [ D22~ ] [ D22 ] [ D22 ] N2\n *\n * where W = T11^T U12, using T12 as temporary storage, and\n *\n * N1\n * V1 = [ I ] N1\n * [ 0 ] N2\n * [ V31 ] N1\n * [ 0 ] N2\n */\n gsl_matrix_memcpy(&T12.matrix, &U12.matrix); /* W := U12 */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */\n gsl_matrix_sub(&U12.matrix, &T12.matrix); /* R12 := U12 - W */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Y11.matrix, &T12.matrix); /* W := -V31 W */\n gsl_matrix_memcpy(&Y12.matrix, &T12.matrix); /* Y12 := -V31 W */\n\n /*\n * Eq. 4: factor the \"triangle on top of rectangle on top of diagonal\" matrix\n *\n * N2 [ U22 ] = Q2~ [ R22 ] N2\n * N1 [ Y12 ] [ 0 ] N1\n * N2 [ D22 ] [ 0 ] N2\n */\n m = gsl_matrix_submatrix(Y, 0, N1, N, N2);\n status = aux_QR_TRD_decomp(&U22.matrix, &m.matrix, &D2.vector, &T22.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 13: update T12 := -T11 * V1^T * V2 * T22\n *\n * where:\n *\n * N1 N2\n * V1 = [ I ] N1 V2 = [ 0 ] N1\n * [ 0 ] N2 [ I ] N2\n * [ V31~ ] N1 [ V32~ ] N1\n * [ 0 ] N2 [ V42~ ] N2\n *\n * Note: V1^T V2 = V31~^T V32~\n */\n\n gsl_matrix_memcpy(&T12.matrix, &Y12.matrix); /* T12 := V32~ */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &Y11.matrix, &T12.matrix); /* T12 := V31~^T V32~ */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */\n\n return GSL_SUCCESS;\n }\n}\n\n/* Find the least squares solution to the overdetermined system \n *\n * [ U ] x = b\n * [ D ]\n * \n * using the QR factorization [ U; D ] = Q R. \n *\n * Inputs: R - upper triangular R matrix, N-by-N\n * Y - upper triangular Y matrix, N-by-N\n * T - upper triangular block reflector, N-by-N\n * b - right hand side, size 2*N\n * x - (output) solution, size 2*N\n * x(1:N) = least squares solution vector\n * x(N+1:2*N) = vector whose norm equals ||b - Ax||\n * work - workspace, size N\n */\n\nint\ngsl_linalg_QR_UD_lssolve (const gsl_matrix * R, const gsl_matrix * Y, const gsl_matrix * T,\n const gsl_vector * b, gsl_vector * x, gsl_vector * work)\n{\n const size_t N = R->size1;\n const size_t M = 2 * N;\n\n if (R->size2 != N)\n {\n GSL_ERROR (\"R matrix must be square\", GSL_ENOTSQR);\n }\n else if (Y->size1 != Y->size2)\n {\n GSL_ERROR (\"Y matrix must be square\", GSL_ENOTSQR);\n }\n else if (Y->size1 != N)\n {\n GSL_ERROR (\"Y and R must have same dimensions\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix must be N-by-N\", GSL_EBADLEN);\n }\n else if (M != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (M != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else if (N != work->size)\n {\n GSL_ERROR (\"workspace must be length N\", GSL_EBADLEN);\n }\n else\n {\n return gsl_linalg_QR_UU_lssolve(R, Y, T, b, x, work);\n }\n}\n\n/*\naux_QR_TRD_decomp()\n Compute the QR decomposition of the \"triangle on top of rectangle on top of diagonal\" matrix\n\n [ U ] = Q [ R ]\n [ A ] [ 0 ]\n [ D ] [ 0 ]\n\nwhere U is N-by-N upper triangular, A is M-by-N dense, D is N-by-N diagonal\n\nInputs: U - on input, upper triangular N-by-N matrix\n on output, R factor in upper triangle\n A - on input, A is stored in A(1:M,1:N)\n on output, Y is stored in A(1:M+N,1:N)\n size (M+N)-by-N\n D - diagonal N-by-N matrix\n T - (output) block reflector matrix, N-by-N\n\nNotes:\n1) Based on the Elmroth/Gustavson algorithm, taking into account the\nsparse structure of the U,S matrices\n\n2) The Householder matrix V has the special form:\n\n N\nV = [ I ] N\n [ Y ] M+N\n\nwith Y upper trapezoidal\n\n3) The orthogonal matrix is\n\nQ = I - V T V^T\n*/\n\nstatic int\naux_QR_TRD_decomp (gsl_matrix * U, gsl_matrix * A, const gsl_vector * D, gsl_matrix * T)\n{\n const size_t N = U->size1;\n\n if (N != U->size2)\n {\n GSL_ERROR (\"U matrix must be square\", GSL_ENOTSQR);\n }\n else if (A->size1 <= N)\n {\n GSL_ERROR (\"A matrix must have > N rows\", GSL_EBADLEN);\n }\n else if (D->size != N)\n {\n GSL_ERROR (\"D matrix does not match dimensions of U\", GSL_EBADLEN);\n }\n else if (T->size1 != N || T->size2 != N)\n {\n GSL_ERROR (\"T matrix has wrong dimensions\", GSL_EBADLEN);\n }\n else if (N == 1)\n {\n /* base case, compute Householder transform for single column matrix */\n const size_t M = A->size1 - N;\n double * T00 = gsl_matrix_ptr(T, 0, 0);\n double * U00 = gsl_matrix_ptr(U, 0, 0);\n gsl_vector_view v = gsl_matrix_subcolumn(A, 0, 0, M);\n double * D00 = gsl_matrix_ptr(A, M, 0);\n *D00 = gsl_vector_get(D, 0);\n *T00 = qrtrd_householder_transform(U00, &v.vector, D00);\n return GSL_SUCCESS;\n }\n else\n {\n /*\n * partition matrices:\n *\n * N1 N2 N1 N2\n * N1 [ U11 U12 ] and N1 [ T11 T12 ]\n * N2 [ 0 U22 ] N2 [ 0 T22 ]\n * N1 [ D11 D12 ]\n * N2 [ 0 D22 ]\n */\n int status;\n const size_t M = A->size1 - N;\n const size_t N1 = N / 2;\n const size_t N2 = N - N1;\n\n gsl_matrix_view U11 = gsl_matrix_submatrix(U, 0, 0, N1, N1);\n gsl_matrix_view U12 = gsl_matrix_submatrix(U, 0, N1, N1, N2);\n gsl_matrix_view U22 = gsl_matrix_submatrix(U, N1, N1, N2, N2);\n\n gsl_matrix_view A1 = gsl_matrix_submatrix(A, 0, 0, M, N1);\n gsl_matrix_view A2 = gsl_matrix_submatrix(A, 0, N1, M, N2);\n\n gsl_vector_const_view D1 = gsl_vector_const_subvector(D, 0, N1);\n gsl_vector_const_view D2 = gsl_vector_const_subvector(D, N1, N2);\n\n gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);\n gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);\n gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);\n\n gsl_matrix_view Y41 = gsl_matrix_submatrix(A, M, 0, N1, N1);\n gsl_matrix_view Y42 = gsl_matrix_submatrix(A, M, N1, N1, N2);\n\n gsl_matrix_view m;\n\n /*\n * Eq. 2: recursively factor\n *\n * N1 N1\n * N1 [ U11 ] = Q1 [ R11 ] N1\n * N2 [ 0 ] [ 0 ] N2\n * M [ A1 ] [ 0 ] M\n * N1 [ D11 ] [ 0 ] N1\n * N2 [ 0 ] [ 0 ] N2\n */\n m = gsl_matrix_submatrix(A, 0, 0, M + N1, N1);\n status = aux_QR_TRD_decomp(&U11.matrix, &m.matrix, &D1.vector, &T11.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 3:\n *\n * N2 N2 N2\n * N1 [ R12 ] = Q1^T [ U12 ] = [ U12 - W ] N1\n * N2 [ U22~ ] [ U22 ] [ U22 ] N2\n * M [ A2~ ] [ A2 ] [ A2 - V31 W ] M\n * N1 [ D12~ ] [ 0 ] [ - V41 W ] N1\n * N2 [ D22~ ] [ D22 ] [ D22 ] N2\n *\n * where W = T11^T ( U12 + V31^T A2 ), using T12 as temporary storage, and\n *\n * N1\n * V1 = [ I ] N1\n * [ 0 ] N2\n * [ V31 ] M\n * [ V41 ] N1\n * [ 0 ] N2\n */\n gsl_matrix_memcpy(&T12.matrix, &U12.matrix); /* W := U12 */\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* W := U12 + V31^T A2 */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */\n gsl_matrix_sub(&U12.matrix, &T12.matrix); /* R12 := U12 - W */\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A1.matrix, &T12.matrix, 1.0, &A2.matrix); /* A2 := A2 - V31 W */\n\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &Y41.matrix, &T12.matrix); /* W := -V41 W */\n gsl_matrix_memcpy(&Y42.matrix, &T12.matrix); /* V42 := -431 W */\n\n /*\n * Eq. 4: factor the \"triangle on top of rectangle on top of diagonal\" matrix\n *\n * N2 [ U22 ] = Q2~ [ R22 ] N2\n * N1 [ Y12 ] [ 0 ] N1\n * N2 [ D22 ] [ 0 ] N2\n */\n m = gsl_matrix_submatrix(A, 0, N1, M + N, N2);\n status = aux_QR_TRD_decomp(&U22.matrix, &m.matrix, &D2.vector, &T22.matrix);\n if (status)\n return status;\n\n /*\n * Eq. 13: update T12 := -T11 * V1^T * V2 * T22\n *\n * where:\n *\n * N1 N2\n * V1 = [ I ] N1 V2 = [ 0 ] N1\n * [ 0 ] N2 [ I ] N2\n * [ V31~ ] M [ V32~ ] M \n * [ V41~ ] N1 [ V42~ ] N1\n * [ 0 ] N2 [ V52~ ] N2\n *\n * Note: V1^T V2 = V31~^T V32~ + V41~^T V42~\n */\n\n gsl_matrix_memcpy(&T12.matrix, &Y42.matrix); /* T12 := V42~ */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &Y41.matrix, &T12.matrix); /* T12 := V41~^T V42~ */\n gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* T12 := V31~^T V32~^T + V41~^T V42~ */\n gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */\n gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */\n\n return GSL_SUCCESS;\n }\n}\n\n/*\nqrtd_householder_transform()\n This routine is an optimized version of\ngsl_linalg_householder_transform(), designed for the QR\ndecomposition of M-by-N matrices of the form:\n\nB = [ U ]\n [ S ]\n\nwhere U,S are N-by-N upper triangular.\nThis routine computes a householder transformation (tau,v) of a \nx so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will\nbe a subcolumn of the matrix B, and so its structure will be:\n\nx = [ x0 ] <- 1 nonzero value for the diagonal element of U\n [ y0 ] <- 1 nonzero value for the diagonal element of S\n\nInputs: v0 - pointer to diagonal element of U\n on input, v0 = x0;\n v1 - on input, pointer to diagonal element of S\n on output, householder vector v\n*/\n\nstatic double\nqrtd_householder_transform (double *v0, double *v1)\n{\n /* replace v[0:M-1] with a householder vector (v[0:M-1]) and\n coefficient tau that annihilate v[1:M-1] */\n\n double alpha, beta, tau ;\n \n /* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */\n double xnorm = fabs(*v1);\n\n if (xnorm == 0) \n {\n return 0.0; /* tau = 0 */\n }\n\n alpha = *v0;\n beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ;\n tau = (beta - alpha) / beta ;\n \n {\n double s = (alpha - beta);\n \n if (fabs(s) > GSL_DBL_MIN) \n {\n *v1 /= s;\n *v0 = beta;\n }\n else\n {\n *v1 *= GSL_DBL_EPSILON / s;\n *v1 /= GSL_DBL_EPSILON;\n *v0 = beta;\n }\n }\n \n return tau;\n}\n\n/*\nqrtrd_householder_transform()\n This routine is an optimized version of\ngsl_linalg_householder_transform(), designed for the QR\ndecomposition of M-by-N matrices of the form:\n\nB = [ U ]\n [ A ]\n [ D ]\n\nwhere U is N-by-N upper triangular A is M-by-N dense and D is N-by-N diagonal.\nThis routine computes a householder transformation (tau,v) of a \nx so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will\nbe a subcolumn of the matrix B, and so its structure will be:\n\nx = [ x0 ] <- 1 nonzero value for the diagonal element of S\n [ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1]\n [ x ] <- M nonzero values for the dense part A\n\nInputs: v0 - pointer to diagonal element of S\n on input, v0 = x0;\n v - on input, x vector\n on output, householder vector v\n d - on input, diagonal element of D\n on output, householder element\n*/\n\nstatic double\nqrtrd_householder_transform (double *v0, gsl_vector * v, double *d)\n{\n /* replace v[0:M-1] with a householder vector (v[0:M-1]) and\n coefficient tau that annihilate v[1:M-1] */\n\n double alpha, beta, tau ;\n \n /* compute xnorm = || [ 0 ; v ; 0 ; d] ||, ignoring zero part of vector */\n double xnorm;\n \n xnorm = gsl_blas_dnrm2(v);\n xnorm = gsl_hypot(xnorm, *d);\n\n if (xnorm == 0) \n {\n return 0.0; /* tau = 0 */\n }\n\n alpha = *v0;\n beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ;\n tau = (beta - alpha) / beta ;\n \n {\n double s = (alpha - beta);\n \n if (fabs(s) > GSL_DBL_MIN) \n {\n gsl_blas_dscal (1.0 / s, v);\n *d /= s;\n *v0 = beta;\n }\n else\n {\n gsl_blas_dscal (GSL_DBL_EPSILON / s, v);\n gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);\n *d *= GSL_DBL_EPSILON / s;\n *d /= GSL_DBL_EPSILON;\n *v0 = beta;\n }\n }\n \n return tau;\n}\n", "meta": {"hexsha": "8a4280badb381fa1257155d8093bbb04b95b316b", "size": 18525, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ud.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": 31.8298969072, "max_line_length": 142, "alphanum_fraction": 0.5394871795, "num_tokens": 6073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4590916389555596}} {"text": "#ifndef ALE_INCLUDE_ALE_H\n#define ALE_INCLUDE_ALE_H\n\n#include \n#include \n#include \n\n#include \n \n#include \nusing json = nlohmann::json;\n\nnamespace ale {\n\n /// Interpolation enum for defining different methods of interpolation\n enum interpolation {\n /// Interpolate using linear interpolation\n linear,\n /// Interpolate using spline interpolation\n spline\n };\n\n /**\n *@brief Get the position of the spacecraft at a given time based on a set of coordinates, and their associated times\n *@param coords A vector of double vectors of coordinates\n *@param times A double vector of times\n *@param time Time to observe the spacecraft's position at\n *@param interp Interpolation type\n *@return A vector double of the spacecrafts position\n */\n std::vector getPosition(std::vector> coords,\n std::vector times,\n double time, interpolation interp);\n /**\n *@brief Get the velocity of the spacecraft at a given time based on a set of coordinates, and their associated times\n *@param coords A vector of double vectors of coordinates\n *@param times A double vector of times\n *@param time Time to observe the spacecraft's velocity at\n *@param interp Interpolation type\n *@return A vector double of the spacecrafts velocity\n */\n std::vector getVelocity(std::vector> coords,\n std::vector times,\n double time, const interpolation interp);\n /**\n *@brief Get the position of the spacecraft at a given time based on a derived function from a set of coeffcients\n *@param coeffs A vector of double vector of coeffcients\n *@param time Time to observe the spacecraft's position at\n *@return A vector double of the spacecrafts position\n */\n std::vector getPosition(std::vector> coeffs, double time);\n\n /**\n *@brief Get the velocity of the spacecraft at a given time based on a derived function from a set of coeffcients\n *@param coeffs A vector of double vector of coeffcients\n *@param time Time to observe the spacecraft's velocity at\n *@return A vector double of the spacecrafts velocity\n */\n std::vector getVelocity(std::vector> coeffs, double time);\n\n /**\n *@brief Get the rotation of the spacecraft at a given time based on a set of rotations, and their associated times\n *@param rotations A vector of double vector of rotations\n *@param times A double vector of times\n *@param time Time to observe the spacecraft's rotation at\n *@param interp Interpolation type\n *@return A vector double of the spacecrafts rotation\n */\n std::vector getRotation(std::vector> rotations,\n std::vector times,\n double time, interpolation interp);\n\n /**\n *@brief Get the angular velocity of the spacecraft at a given time based on a set of rotations, and their associated times\n *@param rotations A vector of double vector of rotations\n *@param times A double vector of times\n *@param time Time to observe the spacecraft's angular velocity at\n *@param interp Interpolation type\n *@return A vector double of the spacecrafts angular velocity\n */\n std::vector getAngularVelocity(std::vector> rotations,\n std::vector times,\n double time, interpolation interp);\n\n /**\n *@brief Get the rotation of the spacecraft at a given time based on a derived function from a set of coeffcients\n *@param coeffs A vector of double vector of coeffcients\n *@param time Time to observe the spacecraft's rotation at\n *@return A vector double of the spacecrafts rotation\n */\n std::vector getRotation(std::vector> coeffs, double time);\n\n /**\n *@brief Get the angular velocity of the spacecraft at a given time based on a derived function from a set of coeffcients\n *@param coeffs A vector of double vector of coeffcients\n *@param time Time to observe the spacecraft's angular velocity at\n *@return A vector double of the spacecrafts angular velocity\n */\n std::vector getAngularVelocity(std::vector> coeffs, double time);\n\n /**\n *@brief Generates a derivatives in respect to time from a polynomial constructed using the given coeffcients, time, and derivation number\n *@param coeffs A double vector of coefficients can be any number of coefficients\n *@param time Time to use when deriving\n *@param d The order of the derivative to generate (Currently supports 0, 1, and 2)\n *@return Evalutation of the given polynomial as a double\n */\n double evaluatePolynomial(std::vector coeffs, double time, int d);\n\n /**\n *@brief Interpolates the spacecrafts position along a path generated from a set of points,\n times, and a time of observation\n *@param points A double vector of points\n *@param times A double vector of times\n *@param time A double to use as the time of observation\n *@param interp An interpolation enum dictating what type of interpolation to use\n *@param d The order of the derivative to generate when interpolating\n (Currently supports 0, 1, and 2)\n *@return\n */\n double interpolate(std::vector points, std::vector times, double time, interpolation interp, int d);\n std::string loads(std::string filename, std::string props=\"\", std::string formatter=\"usgscsm\", bool verbose=true);\n\n json load(std::string filename, std::string props=\"\", std::string formatter=\"usgscsm\", bool verbose=true);\n\n\n}\n\n#endif // ALE_H\n", "meta": {"hexsha": "fb7841ba50cbb6831dfab782f1e50232453b3c8a", "size": 5881, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ale.h", "max_stars_repo_name": "kaitlyndlee/ale", "max_stars_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ale.h", "max_issues_repo_name": "kaitlyndlee/ale", "max_issues_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ale.h", "max_forks_repo_name": "kaitlyndlee/ale", "max_forks_repo_head_hexsha": "44db2f5910a2f937a1946c6ff485b0d4b7b26a18", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2384615385, "max_line_length": 140, "alphanum_fraction": 0.6995408944, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4583045583669433}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n\n/*----- ROUTINE: dc_NakamuraSuto -----\nINPUT: cosmology, scale factor\nTASK: Computes the peak threshold: delta_c(z) assuming LCDM.\nCosmology dependence of the critical linear density according to the spherical-collapse model.\nFitting function from Nakamura & Suto (1997; arXiv:astro-ph/9710107).\n*/\ndouble dc_NakamuraSuto(ccl_cosmology *cosmo, double a, int *status){\n\n double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);\n double dc0 = (3./20.)*pow(12.*M_PI,2./3.);\n double dc = dc0*(1.+0.012299*log10(Om_mz));\n\n return dc;\n\n}\n\n/*----- ROUTINE: Dv_BryanNorman -----\nINPUT: cosmology, scale factor\nTASK: Computes the virial collapse density contrast with respect to the matter density assuming LCDM.\nCosmology dependence of the virial collapse density according to the spherical-collapse model\nFitting function from Bryan & Norman (1998; arXiv:astro-ph/9710107)\n*/\ndouble Dv_BryanNorman(ccl_cosmology *cosmo, double a, int *status){\n\n double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);\n double x = Om_mz-1.;\n double Dv0 = 18.*pow(M_PI,2);\n double Dv = (Dv0+82.*x-39.*pow(x,2))/Om_mz;\n\n return Dv;\n}\n\nstatic double sigmaM_m2r(ccl_cosmology *cosmo, double halomass, int *status)\n{\n double rho_m, smooth_radius;\n\n // Comoving matter density\n //rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;\n rho_m = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status);\n\n smooth_radius = pow((3.0*halomass) / (4*M_PI*rho_m), (1.0/3.0));\n\n return smooth_radius;\n}\n\nvoid ccl_cosmology_compute_sigma(ccl_cosmology *cosmo, int *status)\n{\n if(cosmo->computed_sigma)\n return;\n\n // create linearly-spaced values of the mass.\n int nm = cosmo->spline_params.LOGM_SPLINE_NM;\n double *m = NULL;\n double *y = NULL;\n double smooth_radius;\n double na, nb;\n\n m = ccl_linear_spacing(cosmo->spline_params.LOGM_SPLINE_MIN, cosmo->spline_params.LOGM_SPLINE_MAX, nm);\n if (m == NULL ||\n (fabs(m[0]-cosmo->spline_params.LOGM_SPLINE_MIN)>1e-5) ||\n (fabs(m[nm-1]-cosmo->spline_params.LOGM_SPLINE_MAX)>1e-5) ||\n (m[nm-1]>10E17)) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\"ccl_cosmology_compute_sigmas(): Error creating linear spacing in m\\n\");\n }\n\n if (*status == 0) {\n // create space for y, to be filled with sigma and dlnsigma_dlogm\n y = malloc(sizeof(double)*nm);\n if (y == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n }\n\n // start up of GSL pointers\n int gslstatus = 0;\n gsl_spline *logsigma = NULL;\n gsl_spline *dlnsigma_dlogm = NULL;\n\n // fill in sigma, if no errors have been triggered at this time.\n if (*status == 0) {\n for (int i=0; ispline_params.M_SPLINE_TYPE, nm);\n if (logsigma == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n }\n\n if (*status == 0) {\n gslstatus = gsl_spline_init(logsigma, m, y, nm);\n if (gslstatus != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE ;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating sigma(M) spline\\n\");\n }\n }\n\n // again, making splines assuming nothing bad has happened to this point\n if (*status == 0 ) {\n for (int i=0; ispline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);\n y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;\n }\n else if (i==nm-1) {\n gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);\n gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&nb);\n y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;\n }\n else {\n gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);\n gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);\n y[i] = (na-nb) / cosmo->spline_params.LOGM_SPLINE_DELTA;\n }\n }\n\n if(gslstatus != GSL_SUCCESS ) {\n ccl_raise_gsl_warning(\n gslstatus, \"ccl_massfunc.c: ccl_cosmology_compute_sigma():\");\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): \"\n \"Error evaluating grid points for dlnsigma/dlogM spline\\n\");\n }\n }\n\n if (*status == 0) {\n dlnsigma_dlogm = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);\n if (dlnsigma_dlogm == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n }\n\n if (*status == 0) {\n gslstatus = gsl_spline_init(dlnsigma_dlogm, m, y, nm);\n if (gslstatus != GSL_SUCCESS) {\n *status = CCL_ERROR_SPLINE ;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating dlnsigma/dlogM spline\\n\");\n }\n }\n\n if (*status == 0) {\n cosmo->data.logsigma = logsigma;\n cosmo->data.dlnsigma_dlogm = dlnsigma_dlogm;\n cosmo->computed_sigma = true;\n } else {\n gsl_spline_free(logsigma);\n gsl_spline_free(dlnsigma_dlogm);\n }\n\n free(m);\n free(y);\n}\n\n/*----- ROUTINE: ccl_sigma_M -----\nINPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor\nTASK: returns sigma from the sigmaM interpolation. Also computes the sigma interpolation if\nnecessary.\n*/\ndouble ccl_sigmaM(ccl_cosmology *cosmo, double log_halomass, double a, int *status)\n{\n double sigmaM;\n // Check if sigma has already been calculated\n if (!cosmo->computed_sigma) {\n *status = CCL_ERROR_SIGMA_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!\");\n return NAN;\n }\n\n double lgsigmaM;\n\n int gslstatus = gsl_spline_eval_e(cosmo->data.logsigma, log_halomass, NULL, &lgsigmaM);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: ccl_sigmaM():\");\n *status |= gslstatus;\n }\n\n // Interpolate to get sigma\n sigmaM = exp(lgsigmaM)*ccl_growth_factor(cosmo, a, status);\n return sigmaM;\n}\n\n/*----- ROUTINE: ccl_dlnsigM_dlogM -----\nINPUT: ccl_cosmology *cosmo, double halo mass in units of Msun\nTASK: returns the value of the derivative of ln(sigma^-1) with respect to log10 in halo mass.\n*/\ndouble ccl_dlnsigM_dlogM(ccl_cosmology *cosmo, double log_halomass, int *status)\n{\n // Check if sigma has already been calculated\n if (!cosmo->computed_sigma) {\n *status = CCL_ERROR_SIGMA_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!\");\n return NAN;\n }\n \n double dlsdlgm;\n int gslstatus = gsl_spline_eval_e(cosmo->data.dlnsigma_dlogm,\n\t\t\t\t log_halomass, NULL, &dlsdlgm);\n if(gslstatus) { \n ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: ccl_dlnsigM_dlogM():\");\n *status |= gslstatus;\n }\n return dlsdlgm;\n}\n", "meta": {"hexsha": "f121d77326dfc7c5ac0a0fc7b0e08f8d507bd5ad", "size": 7371, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_massfunc.c", "max_stars_repo_name": "timothydmorton/CCL", "max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "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_massfunc.c", "max_issues_repo_name": "timothydmorton/CCL", "max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_forks_repo_path": "src/ccl_massfunc.c", "max_forks_repo_name": "timothydmorton/CCL", "max_forks_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9090909091, "max_line_length": 115, "alphanum_fraction": 0.6832180166, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4581196596320422}} {"text": "/* Standard C Libraries */\r\n#include \r\n#include \r\n#include \r\n\r\n#include \"interpolation.h\"\r\n#include \"float.h\"\r\n\r\n#include \r\n#include \r\n\r\ntypedef struct {\r\n int start_index;\r\n int end_index;\r\n int n;\r\n double* x;\r\n double* y;\r\n} segment;\r\n\r\ntypedef struct {\r\n int n;\r\n segment * seg;\r\n} segments;\r\n\r\nvoid free_segments(segments segs)\r\n{\r\n for(int i=0; i data.x) end_data = data.x - 1;\r\n\r\n int new_size = segs.n + 1;\r\n segs.seg = realloc(segs.seg, sizeof(segment)*new_size);\r\n\r\n int data_size = edges * 2;\r\n\r\n segs.seg[segs.n].start_index = start_data_to;\r\n segs.seg[segs.n].end_index = end_data;\r\n segs.seg[segs.n].n = data_size;\r\n segs.seg[segs.n].x = calloc(data_size, sizeof(double));\r\n segs.seg[segs.n].y = calloc(data_size, sizeof(double));\r\n\r\n for(int i=0; i= data->x) end_index = data->x;\r\n\r\n int n = (start - start_index) + (end_index - end) + 1;\r\n int index = 0;\r\n vector x = zerov(n);\r\n vector y = zerov(n);\r\n\r\n for(int i=start_index; i<=start; i++)\r\n {\r\n// printf(\"i %i\\n\", i);\r\n// fprintf(stdout, \"val %f\\n\", data->v[i]);\r\n setv(y, index, data->v[i]);\r\n setv(x, index, i);\r\n index++;\r\n }\r\n\r\n for(int i=end; iv[i]);\r\n setv(y, index, getv(*data, i));\r\n setv(x, index, i);\r\n index++;\r\n }\r\n\r\n// for (int i=start_index; i=end_index)&&(indexv[i]!=0||i==start_index||i==end_index))\r\n// {\r\n// setv(y, index, getv(data, i));\r\n// setv(x, index, i);\r\n// index++;\r\n// }\r\n// }\r\n\r\n n = index;\r\n\r\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\r\n gsl_spline *liner = gsl_spline_alloc(T, n);\r\n gsl_spline_init (liner, x.v, y.v, n);\r\n\r\n for(int j=(start); jv[j] = gsl_spline_eval (liner, j, acc);\r\n }\r\n\r\n gsl_spline_free (liner);\r\n gsl_interp_accel_free (acc);\r\n\r\n freev(x);\r\n freev(y);\r\n}\r\n\r\nvoid vector_interpolate_part(vector * data, int start, int end, int type)\r\n{\r\n if(end - start > 1)\r\n switch (type) {\r\n case 1: // Linear interpolation\r\n interpolate_part(data, start, end, gsl_interp_linear);\r\n break;\r\n case 2: // Cubic spline (тatural boundary conditions)\r\n interpolate_part(data, start, end, gsl_interp_cspline);\r\n break;\r\n case 3: // Cubic spline (periodic boundary conditions)\r\n interpolate_part(data, start, end, gsl_interp_cspline_periodic);\r\n break;\r\n case 4: // Non-rounded Akima spline (natural boundary conditions)\r\n interpolate_part(data, start, end, gsl_interp_akima);\r\n break;\r\n case 5: // Non-rounded Akima spline (periodic boundary conditions)\r\n interpolate_part(data, start, end, gsl_interp_akima_periodic);\r\n break;\r\n case 6: // Steffen’s method\r\n interpolate_part(data, start, end, gsl_interp_steffen);\r\n break;\r\n }\r\n}\r\n", "meta": {"hexsha": "19743812633e9746924cb33b0c000e035d2f0657", "size": 7952, "ext": "c", "lang": "C", "max_stars_repo_path": "sptk/others/interpolation.c", "max_stars_repo_name": "zhitko/sptk-analyzer", "max_stars_repo_head_hexsha": "d70de9ae4c3c20efe51864a174310ca59d31c11f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T20:47:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T12:22:17.000Z", "max_issues_repo_path": "sptk/others/interpolation.c", "max_issues_repo_name": "zhitko/sptk-analyzer", "max_issues_repo_head_hexsha": "d70de9ae4c3c20efe51864a174310ca59d31c11f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-27T21:31:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-27T21:31:30.000Z", "max_forks_repo_path": "sptk/others/interpolation.c", "max_forks_repo_name": "zhitko/inton-trainer", "max_forks_repo_head_hexsha": "d70de9ae4c3c20efe51864a174310ca59d31c11f", "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.2357414449, "max_line_length": 105, "alphanum_fraction": 0.5259054326, "num_tokens": 2075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.4580054023815717}} {"text": "#include \"stdio.h\"\n#include \"gsl/gsl_integration.h\"\n#include \"gsl/gsl_errno.h\"\n#include \"non_limber.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// This is a workspace size for the gsl integrator\n#define LIMBER_FIXED_TABLE_SIZE 4096\n\n// data that is passed into the integrator\n// This is everything we need to compute the\n// integrand\nstruct ClIntegrandData {\n\tdouble ell;\n\tdouble chimin;\n\tdouble chimax;\n\tgsl_spline * WbX;\n\tgsl_spline * WbY;\n gsl_spline * D_chi;\n\tgsl_spline2d * P;\n\tgsl_interp_accel * accelerator_wx;\n\tgsl_interp_accel * accelerator_wy;\n\tgsl_interp_accel * accelerator_px;\n\tgsl_interp_accel * accelerator_py;\n\tgsl_interp_accel * accelerator_growth;\n};\n\ndouble cl_integrand(double *x, size_t dim, void *data_void)\n{\n\tstruct ClIntegrandData * data = (struct ClIntegrandData*) data_void;\n\t\n\tdouble chi1 = x[0];\n\tdouble log_delta = x[1];\n\tdouble log_nu = x[2];\n\tdouble nu = exp(log_nu);\n\tdouble delta = exp(log_delta);\n\tdouble chi2_p = chi1 * ( 1 + delta);\n\tdouble chi2_m = chi1 * (1 - delta);\n\tdouble logk = log_nu / chi1;\n\n\tif(chi2_m < data->chimin || chi2_p > data->chimax) return 0.0;\n\n\tdouble FX = gsl_spline_eval(data->WbX, chi1, data->accelerator_wx);\n\tdouble FY_p = gsl_spline_eval(data->WbY, chi2_p, data->accelerator_wy);\n\tdouble FY_m = gsl_spline_eval(data->WbY, chi2_m, data->accelerator_wy);\n\n\n\tdouble growth_1 = gsl_spline_eval(data->D_chi, chi1, data->accelerator_growth);\n\tdouble growth_2_p = gsl_spline_eval(data->D_chi, chi2_p, data->accelerator_growth);\n\tdouble growth_2_m = gsl_spline_eval(data->D_chi, chi2_m, data->accelerator_growth);\n\n\t// Get P(k,chi)\n\t// Deactivate error handling \n\tgsl_error_handler_t * old_handler = gsl_set_error_handler_off();\n\n\tdouble p;\n\tint status = gsl_spline2d_eval_e(data->P, chi1, logk, data->accelerator_px, data->accelerator_py, &p);\n\n\t// Restore the old error handler\n\tgsl_set_error_handler(old_handler); \n\tif (status) \n\t{\n\t\t//printf(stderr,'spline failed, for now, assume this is because k was out of range and return 0...should probably be more careful here though.');\n\t\treturn 0.0;\n\t}\n\tdouble j1 = gsl_sf_bessel_jl(data->ell, nu);\n\tdouble j2_p = gsl_sf_bessel_jl(data->ell, nu*(1+delta));\n\tdouble j2_m = gsl_sf_bessel_jl(data->ell, nu*(1-delta));\n\tdouble prefac = 2 * delta * 2 * nu * nu * nu * p / growth_1 / M_PI / chi1 / chi1 ;\n\treturn prefac * ( FY_p * growth_2_p * j2_p + FY_m * growth_2_m * j2_m );\n}\n\nstatic double inline gsl_spline_min_x(gsl_spline * s)\n{\n\treturn s->x[0];\n}\nstatic double inline gsl_spline_max_x(gsl_spline * s)\n{\n\treturn s->x[s->size-1];\n}\n\nint get_chi_mean_sigma(double chimin, double chimax, gsl_spline * WbX, gsl_spline * WbY,\n\t\t\t\tgsl_interp_accel * accelerator_wx,\tgsl_interp_accel * accelerator_wy,\n\t\t\t\tdouble *chi_mean, double *chi_sigma)\n{\n int nchi = 1000;\n double dchi = (chimax-chimin)/nchi;\n double chi = chimin;\n double wxwy_sum = 0.;\n double wxwy2_sum = 0.;\n double wx,wy;\n for (int i=0; istatus = LIMBER_STATUS_ERROR;\n int any_parameter_error=0;\n if (WbX==NULL){\n fprintf(stderr, \"NULL WX parameter in limber_integral\\n\");\n any_parameter_error = 1;\n }\n if (WbY==NULL){\n fprintf(stderr, \"NULL WY parameter in limber_integral\\n\");\n any_parameter_error = 1;\n }\n if (P==NULL){\n fprintf(stderr, \"NULL P parameter in limber_integral\\n\");\n any_parameter_error = 1;\n }\n if (D_chi==NULL){\n fprintf(stderr, \"NULL D_chi parameter in limber_integral\\n\");\n any_parameter_error = 1;\n }\n if (config->n_ell<0){\n fprintf(stderr, \"Negative n_ell parameter in limber_integral\\n\");\n any_parameter_error = 1;\n }\n if (any_parameter_error){\n return 1;\n }\n\n\tconfig->status = LIMBER_STATUS_OK;\n\n static int n_ell_zero_warning = 0;\n if (config->n_ell==0){\n if (n_ell_zero_warning==0){\n fprintf(stderr, \"Warning: n_ell=0 in Limber. Will not be treated as an error. Warning once only per process.\\n\");\n }\n n_ell_zero_warning = 1;\n return 1;\n }\n\n\t// Get the appropriate ranges over which to integrate\n\t// It is assumed that (at least one of) the kernel\n\t// splines should go to zero in some kind of reasonable\n\t// place, so we just use the range they specify\n\tstruct ClIntegrandData data;\n\tdouble chimin_x = gsl_spline_min_x(WbX);\n\tdouble chimin_y = gsl_spline_min_x(WbY);\n\tdouble chimax_x = gsl_spline_max_x(WbX);\n\tdouble chimax_y = gsl_spline_max_x(WbY);\n\tdouble c_ell, c_ell_error;\n\n\t// Workspaces\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 size_t calls = 5000000;\n\n\tdouble reltol = config->relative_tolerance;\n\tdouble abstol = config->absolute_tolerance;\n\n\t// Take the smallest range since we want both the\n\t// splines to be valid there.\n\t// This range as well as all the data needed to compute\n\t// the integrand is put into a struct to be passed\n\t// through the integrator to the function above.\n\tdouble chimin = chimin_x>chimin_y ? chimin_x : chimin_y;\n double chimax = chimax_xn_ell];\n\tdouble nu_0;\n\n gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (3);\n\n\t// loop through ell values according to the input configuration\n\tfor (int i_ell = 0; i_elln_ell; i_ell++){\n\t\tdouble ell = config->ell[i_ell];\n\t\tdouble log_nu_0 = log(ell+0.5);\n\t\tdouble log_nu_min = log_nu_0 - config->log_nu_range;\n\t\tdouble log_nu_max = log_nu_0 + config->log_nu_range;\n\t\tprintf(\"delta_range_factor %f\\n\", config->delta_range_factor);\n\t\tdouble delta_min = 1. / ell / config->delta_range_factor;\n\t\tdouble delta_max = 1. * config->delta_range_factor / ell;\n\n\t\tdouble log_delta_min = log(delta_min);\n\t\tdouble log_delta_max = log(delta_max);\n\t\tprintf(\"log_delta_min,max %f %f\\n\", delta_min, delta_max);\n\t\tdouble xl[3] = { chimin_x, log_delta_min, log_nu_min };\n\t\tdouble xu[3] = { chimax_x, log_delta_max, log_nu_max };\n\t\tdata.ell=ell;\n\t\tgsl_monte_function G = {&cl_integrand, 3, &data};\n\n gsl_monte_vegas_integrate (&G, xl, xu, 3, 10000, r, s,\n &c_ell, &c_ell_error);\n gsl_monte_vegas_integrate (&G, xl, xu, 3, calls/5, r, s,\n &c_ell, &c_ell_error);\n gsl_monte_vegas_init (s);\n\n\t\t//Include the prefactor scaling\n\t\tc_ell *= config->prefactor;\n\t\t// Record the results into arrays\n\t\tcl_out[i_ell] = c_ell;\n\t\tcl_err_out[i_ell] = c_ell_error;\n\t\tell_vector[i_ell] = ell;\n\t}\n\tgsl_monte_vegas_free (s);\n\n\n\t// Tidy up\n\tgsl_interp_accel_free(data.accelerator_wx);\n\tgsl_interp_accel_free(data.accelerator_wy);\n\tgsl_interp_accel_free(data.accelerator_px);\n\tgsl_interp_accel_free(data.accelerator_py);\n\tgsl_interp_accel_free(data.accelerator_growth);\n\n\t// These two are not deallocated because they are static and only initialized once.\n\t// gsl_integration_glfixed_table_free(table);\t\n\t// gsl_integration_workspace_free(W);\n\n\t// And that's it\n\treturn 0;\n}\n", "meta": {"hexsha": "f79333cf5b4fe3bd94dcc14440d57a0a386fdd9d", "size": 8136, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/non_limber.c", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 32.2857142857, "max_line_length": 147, "alphanum_fraction": 0.7008357915, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4579367197869259}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include // gsl_finite\n\n#ifdef _OPENMP\n#include \n#endif\n\nconst size_t N=10000;\nconst size_t T=1000;\nconst size_t K=20;\nconst size_t L=2;\nconst double alpha_k = 0.5;\n\n/*\n * 0: thompson sampling\n * 1: uniform subset\n *\n */\nconst unsigned int strategy = 0;\n\n#include \"helpers.h\"\n#include \"model.h\"\n#include \"set_counter.h\"\n\n#define to_string(arr, k) \\\n for (size_t i = 0; i < k-1; i++) { \\\n printf(\"%.16lf,\", arr[i]); \\\n } \\\n printf(\"%.16lf\", arr[k-1]);\n\n\nunsigned int\nmove_gibbs(double *restrict random_numbers, double logth[K], size_t ngames,\n const size_t games[ngames][L], const size_t game_counts[ngames],\n const size_t win_counts[K])\n{\n double ll, ll_p;\n double alpha;\n double logth_comp_old;\n double logth_Km1_old;\n unsigned int accepted = 0;\n\n for (size_t comp=0; comp logth[K-1]) {\n logth[comp] = log(*random_numbers++) + logth_comp_old + log1p(exp(logth[K-1] - logth_comp_old));\n logth[K-1] = logth_comp_old + log1p(exp(logth_Km1_old - logth_comp_old) - exp(logth[comp] - logth_comp_old));\n } else {\n logth[comp] = log(*random_numbers++) + logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old));\n logth[K-1] = logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old) - exp(logth[comp] - logth_Km1_old));\n }\n\n /* compute full conditional density at th_p */\n ll_p = fullcond(comp, logth, ngames, games, game_counts, win_counts);\n\n alpha = *random_numbers++;\n if (log(alpha) < ll_p - ll) {\n /* accept */\n accepted = 1;\n }\n else {\n /* reject */\n /* reset the proposed component back to its original value */\n /* th[K-1] += th[comp] - th_comp_old; */\n /* th[comp] = th_comp_old; */\n /* assert(th[K-1] >= 0); */\n logth[comp] = logth_comp_old;\n logth[K-1] = logth_Km1_old;\n }\n }\n\n return accepted;\n}\n\n\nvoid\nresample_move(const gsl_rng *r, double logtheta[N][K], const double w[N],\n const struct set_counter *games_counter, const size_t wins[K])\n{\n unsigned int cnt[N];\n size_t accepted = 0;\n\n gsl_ran_multinomial(r, N, N, w, cnt);\n\n /* populate particles */\n double (*logtheta_new)[K] = malloc(N * sizeof *logtheta_new);\n size_t n_new = 0;\n for (size_t n=0; nsize;\n size_t (*games)[L] = malloc(ngames * sizeof *games);\n size_t *game_counts = malloc(ngames * sizeof *game_counts);\n set_counter_keys(games_counter, games);\n set_counter_values(games_counter, game_counts);\n\n#pragma omp parallel for reduction(+:accepted)\n for (size_t n=0; nsize);\n\n double player_w[L];\n\n printf(\"# game: \");\n for (size_t l=0; l\n#include \n#include \n#include \n#include \n\nint\nmain (void)\n{\n int i, n = 100;\n double data[n];\n\n gsl_fft_real_wavetable * real;\n gsl_fft_halfcomplex_wavetable * hc;\n gsl_fft_real_workspace * work;\n\n for (i = 0; i < n; i++)\n {\n data[i] = 0.0;\n }\n\n for (i = n / 3; i < 2 * n / 3; i++)\n {\n data[i] = 1.0;\n }\n\n for (i = 0; i < n; i++)\n {\n printf (\"%d: %e\\n\", i, data[i]);\n }\n printf (\"\\n\");\n\n work = gsl_fft_real_workspace_alloc (n);\n real = gsl_fft_real_wavetable_alloc (n);\n\n gsl_fft_real_transform (data, 1, n,\n real, work);\n\n gsl_fft_real_wavetable_free (real);\n\n for (i = 11; i < n; i++)\n {\n data[i] = 0;\n }\n\n hc = gsl_fft_halfcomplex_wavetable_alloc (n);\n\n gsl_fft_halfcomplex_inverse (data, 1, n,\n hc, work);\n gsl_fft_halfcomplex_wavetable_free (hc);\n\n for (i = 0; i < n; i++)\n {\n printf (\"%d: %e\\n\", i, data[i]);\n }\n\n gsl_fft_real_workspace_free (work);\n return 0;\n}", "meta": {"hexsha": "cee5beea50847d05637b28b6201889b350de1ee9", "size": 1143, "ext": "c", "lang": "C", "max_stars_repo_path": "07-lib/gsl/fft1.c", "max_stars_repo_name": "al2698/sp", "max_stars_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "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": "07-lib/gsl/fft1.c", "max_issues_repo_name": "al2698/sp", "max_issues_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "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": "07-lib/gsl/fft1.c", "max_forks_repo_name": "al2698/sp", "max_forks_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "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": 19.05, "max_line_length": 53, "alphanum_fraction": 0.5555555556, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4576907174003546}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n// convex hull is obtained as cvh(n_bin[0],...,n_bin[end])\n// inputs are y = Ef(x). x:n_data by 4, y:n_data by 1\nvoid obtain_convex_h_Nd(int n_data, double *ef2cvh, int *x, double *y, int Ndim, int *nCat_min, int *nCat_max, double *E0) {\n \n int i, j, k, l, nid, id1, id2, ctr;\n double tmp;\n int convex_h_ids[n_data]; //preallocated, not all filled\n double convex_h_x[n_data][Ndim]; //preallocated, not all filled\n double convex_h_y[n_data]; //preallocated, not all filled\n\n printf(\"Convex hull is created.\\n\");\n printf(\"Input data\\n\");\n printf(\"---------------------------\\n\");\n printf(\" nL nN nM nC nV Ef\\n\");\n for (i=0;i 0) {\n convex_h_ids[nid] = i;\n for (j=0;j\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n//#include \"stream/pyStream.h\"\n#include \"beamformer/spectralinfoarray.h\"\n#include \"modulated/modulated.h\"\n#include \"beamformer/beamformer.h\"\n\n\n// ----- definition for class `ModeAmplitudeCalculator' -----\n//\ngsl_complex modeAmplitude(int order, double ka);\n\nclass ModeAmplitudeCalculator {\n public:\n ModeAmplitudeCalculator(int order, float minKa=0.01, float maxKa=20, float wid=0.01);\n\n ~ModeAmplitudeCalculator();\n\n gsl_vector_complex *get() const { return mode_amplitude_; }\n\nprivate:\n gsl_vector_complex *mode_amplitude_;\n float minKa_;\n float maxKa_;\n float wid_;\n};\n\ntypedef refcount_ptr ModeAmplitudeCalculatorPtr;\n\n// ----- definition for class `EigenBeamformer' -----\n//\n\n/**\n @class EigenBeamformer\n @brief This beamformer is implemented based on Meyer and Elko's ICASSP paper. \n In Boaz Rafaely's paper, this method is referred to as the phase-mode beamformer\n @usage \n 1) construct this object, bf = EigenBeamformer(...)\n 2) set the radious of the spherical array with bf.set_eigenmike_geometry() or bf.set_array_geometry(..).\n 3) set the look direction with bf.set_look_direction(..)\n 4) process each block with bf.next() until it hits the end\n*/\nclass EigenBeamformer : public SubbandDS {\npublic:\n EigenBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"EigenBeamformer\");\n ~EigenBeamformer();\n virtual const gsl_vector_complex* next(int frame_no = -5);\n virtual void reset();\n virtual unsigned dim() const { return dim_;}\n\n void set_sigma2(float sigma2){ sigma2_ = sigma2; }\n void set_weight_gain(float wgain){ wgain_ = wgain; }\n void set_eigenmike_geometry();\n void set_array_geometry(double a, gsl_vector *theta_s, gsl_vector *phi_s);\n virtual void set_look_direction(double theta, double phi);\n\n const gsl_matrix_complex *mode_amplitudes();\n const gsl_vector *array_geometry(int type); // type==0 -> theta, type==1 -> phi\n virtual gsl_matrix *beampattern(unsigned fbinX, double theta = 0, double phi = 0,\n double minTheta=-M_PI, double maxTheta=M_PI,\n double minPhi=-M_PI, double maxPhi=M_PI,\n double widthTheta=0.1, double widthPhi=0.1 );\n /**\n @brief obtain the spherical transformation coefficients at each frame\n @return spherical harmonics transformation coefficients at the current frame\n */\n virtual SnapShotArrayPtr snapshot_array() const { return(st_snapshot_array_); }\n virtual SnapShotArrayPtr snapshot_array2() const { return(snapshot_array_); }\n\n const gsl_matrix_complex *blocking_matrix(unsigned fbinX, unsigned unitX=0 ) const {\n return (bfweight_vec_[unitX]->B())[fbinX];\n }\n\n#ifdef ENABLE_LEGACY_BTK_API\n void setSigma2(float sigma2){ set_sigma2(sigma2); }\n void setWeightGain(float wgain){ set_weight_gain(wgain); }\n void setEigenMikeGeometry(){ set_eigenmike_geometry(); }\n void setArrayGeometry(double a, gsl_vector *theta_s, gsl_vector *phi_s){ set_array_geometry(a, theta_s, phi_s); }\n virtual void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); }\n const gsl_matrix_complex *getModeAmplitudes(){ return mode_amplitudes(); }\n const gsl_vector *getArrayGeometry(int type){ return array_geometry(type);}\n virtual gsl_matrix *getBeamPattern( unsigned fbinX, double theta = 0, double phi = 0,\n double minTheta=-M_PI, double maxTheta=M_PI,\n double minPhi=-M_PI, double maxPhi=M_PI,\n double widthTheta=0.1, double widthPhi=0.1 ){\n return beampattern(fbinX, theta, phi, minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi);\n }\n virtual SnapShotArrayPtr getSnapShotArray(){ return snapshot_array(); }\n virtual SnapShotArrayPtr getSnapShotArray2(){ return snapshot_array2(); }\n const gsl_matrix_complex *getBlockingMatrix(unsigned fbinX, unsigned unitX=0){\n return blocking_matrix(fbinX, unitX);\n }\n#endif\n\n protected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool calc_spherical_harmonics_at_each_position_( gsl_vector *theta_s, gsl_vector *phi_s ); // need to be tested!!\n virtual bool calc_steering_unit_( int unitX=0, bool isGSC=false );\n virtual bool alloc_steering_unit_( int unitN=1 );\n void alloc_image_( bool flag=true );\n bool calc_mode_amplitudes_();\n\n unsigned samplerate_;\n unsigned NC_;\n unsigned maxOrder_;\n unsigned dim_; // the number of the spherical harmonics transformation coefficients\n bool weights_normalized_;\n gsl_matrix_complex *mode_mplitudes_; // [maxOrder_] the mode amplitudes.\n gsl_vector_complex *F_; // Spherical Transform coefficients [dim_]\n gsl_vector_complex **sh_s_; // Conjugate of spherical harmonics at each sensor position [dim_][nChan]: Y_n^{m*}\n SnapShotArrayPtr st_snapshot_array_; // for compatibility with a post-filtering object\n\n double theta_; // look direction\n double phi_; // look direction\n\n double a_; // the radius of the rigid sphere.\n gsl_vector *theta_s_; // sensor positions\n gsl_vector *phi_s_; // sensor positions\n gsl_matrix *beampattern_;\n gsl_vector *WNG_; // white noise gain\n float wgain_; //\n float sigma2_; // dialog loading\n};\n\ntypedef Inherit EigenBeamformerPtr;\n\n// ----- definition for class DOAEstimatorSRPEB' -----\n// \n\n/**\n @class DOAEstimatorSRPEB\n @brief estimate the direction of arrival based on the maximum steered response power\n @usage \n 1) construct this object, doaEstimator = DOAEstimatorSRPEB(...)\n 2) set the radious of the spherical array, doaEstimator.set_eigenmike_geometry() or doaEstimator.set_array_geometry(..).\n 3) process each block, doaEstimator.next() \n 4) get the N-best hypotheses at the current instantaneous frame through doaEstimator.nbest_doas()\n 5) do doaEstimator.getFinalNBestHypotheses() after a static segment is processed.\n You can then obtain the averaged N-best hypotheses of the static segment with doaEstimator.nbest_doas().\n*/\nclass DOAEstimatorSRPEB :\n public DOAEstimatorSRPBase, public EigenBeamformer {\n public:\n DOAEstimatorSRPEB( unsigned nBest, unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"DirectionEstimatorSRPBase\");\n ~DOAEstimatorSRPEB();\n\n const gsl_vector_complex* next(int frame_no = -5);\n void reset();\n\nprotected:\n virtual void calc_steering_unit_table_();\n virtual float calc_response_power_( unsigned uttX );\n};\n\ntypedef Inherit DOAEstimatorSRPEBPtr;\n\n// ----- definition for class `SphericalDSBeamformer' -----\n// \n\n/**\n @class SphericalDSBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note this implementation is based on Boaz Rafaely's letter,\n \"Phase-Mode versus Delay-and-Sum Spherical Microphone Array\", IEEE Signal Processing Letters, vol. 12, Oct. 2005.\n*/\nclass SphericalDSBeamformer : public EigenBeamformer {\npublic:\n SphericalDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"SphericalDSBeamformer\");\n ~SphericalDSBeamformer();\n virtual gsl_vector *calc_wng();\n\n#ifdef ENABLE_LEGACY_BTK_API\n virtual gsl_vector *calcWNG(){ return calc_wng(); }\n#endif\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool calc_spherical_harmonics_at_each_position_( gsl_vector *theta_s, gsl_vector *phi_s );\n};\n\ntypedef Inherit SphericalDSBeamformerPtr;\n\n// ----- definition for class `DualSphericalDSBeamformer' -----\n// \n\n/**\n @class DualSphericalDSBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note In addition to SphericalDSBeamformer, this class has an object of the *normal* D&S beamformer\n*/\nclass DualSphericalDSBeamformer : public SphericalDSBeamformer {\npublic:\n DualSphericalDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"SphericalDSBeamformer\");\n ~DualSphericalDSBeamformer();\n\n virtual SnapShotArrayPtr snapshot_array() const { return snapshot_array_; }\n virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const {\n return bfweight_vec2_[srcX];\n }\n\n#ifdef ENABLE_LEGACY_BTK_API\n virtual SnapShotArrayPtr getSnapShotArray(){ return snapshot_array(); }\n#endif\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool alloc_steering_unit_( int unitN=1 );\n\n vector bfweight_vec2_; // weights of a normal D&S beamformer.\n};\n\ntypedef Inherit DualSphericalDSBeamformerPtr;\n\n// ----- definition for class DOAEstimatorSRPPSphDSB' -----\n// \n\nclass DOAEstimatorSRPSphDSB : public DOAEstimatorSRPBase, public SphericalDSBeamformer {\npublic:\n DOAEstimatorSRPSphDSB( unsigned nBest, unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"DOAEstimatorSRPPSphDSB\" );\n ~DOAEstimatorSRPSphDSB();\n const gsl_vector_complex* next(int frame_no = -5);\n void reset();\n\nprotected:\n virtual void calc_steering_unit_table_();\n virtual float calc_response_power_( unsigned uttX );\n};\n\ntypedef Inherit DOAEstimatorSRPSphDSBPtr;\n\n// ----- definition for class `SphericalHWNCBeamformer' -----\n// \n\n/**\n @class SphericalHWNCBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n*/\nclass SphericalHWNCBeamformer : public EigenBeamformer {\npublic:\n SphericalHWNCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = \"SphericalHWNCBeamformer\");\n ~SphericalHWNCBeamformer();\n\n virtual gsl_vector *calc_wng();\n virtual void set_wng( double ratio){ ratio_=ratio; calc_wng();}\n\n#ifdef ENABLE_LEGACY_BTK_API\n gsl_vector *calcWNG(){ return calc_wng(); }\n void setWNG( double ratio){ set_wng(ratio);}\n#endif\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n\nprotected:\n float ratio_;\n};\n\ntypedef Inherit SphericalHWNCBeamformerPtr;\n\n// ----- definition for class `SphericalGSCBeamformer' -----\n// \n\n/**\n @class SphericalGSCBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note this implementation is based on Boaz Rafaely's letter,\n \"Phase-Mode versus Delay-and-Sum Spherical Microphone Array\", IEEE Signal Processing Letters, vol. 12, Oct. 2005.\n*/\nclass SphericalGSCBeamformer : public SphericalDSBeamformer {\npublic:\n SphericalGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"SphericalGSCBeamformer\");\n ~SphericalGSCBeamformer();\n\n virtual const gsl_vector_complex* next(int frame_no = -5);\n virtual void reset();\n\n void set_look_direction(double theta, double phi);\n void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);\n\n#ifdef ENABLE_LEGACY_BTK_API\n void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); }\n void setActiveWeights_f( unsigned fbinX, const gsl_vector* packedWeight ){ set_active_weights_f(fbinX, packedWeight); }\n#endif\n};\n\ntypedef Inherit SphericalGSCBeamformerPtr;\n\n// ----- definition for class `SphericalHWNCGSCBeamformer' -----\n// \n\n/**\n @class SphericalHWNCGSCBeamformer\n @usage \n 1) construct this object, mb = SphericalHWNCGSCBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n*/\nclass SphericalHWNCGSCBeamformer : public SphericalHWNCBeamformer {\npublic:\n SphericalHWNCGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = \"SphericalHWNCGSCBeamformer\");\n ~SphericalHWNCGSCBeamformer();\n\n virtual const gsl_vector_complex* next(int frame_no = -5);\n virtual void reset();\n\n void set_look_direction(double theta, double phi);\n void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);\n\n#ifdef ENABLE_LEGACY_BTK_API\n void setLookDirection(double theta, double phi){ set_look_direction(theta, phi); }\n void setActiveWeights_f( unsigned fbinX, const gsl_vector* packedWeight ){ set_active_weights_f(fbinX, packedWeight); }\n#endif\n};\n\ntypedef Inherit SphericalHWNCGSCBeamformerPtr;\n\n// ----- definition for class `DualSphericalGSCBeamformer' -----\n// \n\n/**\n @class DualSphericalGSCBeamformer\n @usage \n 1) construct this object, mb = DualSphericalGSCBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note In addition to DualSphericalGSCBeamformer, this class has an object of the *normal* D&S beamformer\n*/\nclass DualSphericalGSCBeamformer : public SphericalGSCBeamformer {\npublic:\n DualSphericalGSCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"DualSphericalGSCBeamformer\");\n ~DualSphericalGSCBeamformer();\n\n virtual SnapShotArrayPtr snapshot_array() const {return(snapshot_array_);}\n virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const {\n return bfweight_vec2_[srcX];\n }\n\n#ifdef ENABLE_LEGACY_BTK_API\n virtual SnapShotArrayPtr getSnapShotArray(){return(snapshot_array_);}\n#endif\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool alloc_steering_unit_( int unitN=1 );\n\n vector bfweight_vec2_; // weights of a normal D&S beamformer.\n};\n\ntypedef Inherit DualSphericalGSCBeamformerPtr;\n\n// ----- definition for class `SphericalMOENBeamformer' -----\n// \n\n/**\n @class SphericalGSCBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note this implementation is based on Z. Li and R. Duraiswami's letter,\n \"Flexible and Optimal Design of Spherical Microphone Arrays for Beamforming\", IEEE Trans. SAP.\n*/\nclass SphericalMOENBeamformer : public SphericalDSBeamformer {\npublic:\n SphericalMOENBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"SphericalMOENBeamformer\");\n ~SphericalMOENBeamformer();\n\n virtual const gsl_vector_complex* next(int frame_no = -5);\n virtual void reset();\n void fix_terms(bool flag){ is_term_fixed_ = flag; }\n void set_diagonal_looading(unsigned fbinX, float diagonalWeight);\n virtual SnapShotArrayPtr snapshot_array() const { return snapshot_array_; }\n virtual gsl_matrix *beampattern(unsigned fbinX, double theta = 0, double phi = 0,\n double minTheta=-M_PI, double maxTheta=M_PI,\n double minPhi=-M_PI, double maxPhi=M_PI,\n double widthTheta=0.1, double widthPhi=0.1 );\n\n#ifdef ENABLE_LEGACY_BTK_API\n void fixTerms( bool flag ){ fix_terms(flag); }\n void setLevelOfDiagonalLoading( unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); }\n virtual gsl_matrix *getBeamPattern( unsigned fbinX, double theta = 0, double phi = 0,\n double minTheta=-M_PI, double maxTheta=M_PI,\n double minPhi=-M_PI, double maxPhi=M_PI,\n double widthTheta=0.1, double widthPhi=0.1 ){\n return beampattern(fbinX, theta, phi, minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi);\n }\n#endif\n\nprotected:\n virtual bool alloc_steering_unit_( int unitN=1 );\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n bool calc_moen_weights_( unsigned fbinX, gsl_vector_complex *weights, double dThreshold = 1.0E-8, bool calcInverseMatrix = true, unsigned unitX=0 );\n\nprivate:\n // maxOrder_ == Neff in the Li's paper.\n unsigned bf_order_; // N in the Li's paper.\n float CN_;\n gsl_matrix_complex** A_; /* A_[fftLen2+1][dim_][nChan]; Coeffcients of the spherical harmonics expansion; See Eq. (31) & (32) */\n gsl_matrix_complex** fixedW_; /* _fixedW[fftLen2+1][nChan][dim_]; [ A^H A + l^2 I ]^{-1} A^H */\n gsl_vector_complex** BN_; // _BN[fftLen2+1][dim_]\n float* diagonal_weights_;\n bool is_term_fixed_;\n float dthreshold_;\n};\n\ntypedef Inherit SphericalMOENBeamformerPtr;\n\n\n// ----- definition for class `SphericalSpatialDSBeamformer' -----\n// \n\n/**\n @class SphericalSpatialDSBeamformer\n @usage \n 1) construct this object, mb = SphericalSpatialDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n @note this implementation is based on Boaz Rafaely's letter,\n \"Phase-Mode versus Delay-and-Sum Spherical Microphone Array\", IEEE Signal Processing Letters, vol. 12, Oct. 2005.\n*/\nclass SphericalSpatialDSBeamformer : public SphericalDSBeamformer {\npublic:\n SphericalSpatialDSBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, const String& nm = \"SphericalSpatialDSBeamformer\");\n ~SphericalSpatialDSBeamformer();\n virtual const gsl_vector_complex* next(int frame_no = -5);\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool alloc_steering_unit_( int unitN = 1 );\n virtual bool calc_steering_unit_( int unitX = 0, bool isGSC = false );\n};\n\ntypedef Inherit SphericalSpatialDSBeamformerPtr;\n\n\n// ----- definition for class `SphericalSpatialHWNCBeamformer' -----\n// \n\n/**\n @class SphericalSpatialHWNCBeamformer\n @usage \n 1) construct this object, mb = SphericalDSBeamformer(...)\n 2) set the radious of the spherical array mb.set_array_geometry(..) or \n 3) set the look direction mb.set_look_direction()\n 4) process each block mb.next()\n*/\nclass SphericalSpatialHWNCBeamformer : public SphericalHWNCBeamformer {\npublic:\n SphericalSpatialHWNCBeamformer( unsigned sampleRate, unsigned fftLen = 512, bool halfBandShift = false, unsigned NC=1, unsigned maxOrder=4, bool normalizeWeight=false, float ratio=1.0, const String& nm = \"SphericalHWNCBeamformer\");\n ~SphericalSpatialHWNCBeamformer();\n virtual const gsl_vector_complex* next(int frame_no = -5);\n\nprotected:\n virtual void calc_weights_( unsigned fbinX, gsl_vector_complex *weights );\n virtual bool alloc_steering_unit_( int unitN = 1 );\n virtual bool calc_steering_unit_( int unitX = 0, bool isGSC = false );\n\nprivate:\n gsl_matrix_complex *calc_diffuse_noise_model_( unsigned fbinX );\n\n gsl_matrix_complex **SigmaSI_; // SigmaSI_[fftLen/2+1][chanN]\n double dthreshold_;\n};\n\ntypedef Inherit SphericalSpatialHWNCBeamformerPtr;\n\n#endif\n", "meta": {"hexsha": "45e5149a732c0d925f3d287dfc18b5730f41c166", "size": 21350, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/beamformer/modalbeamformer.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 42.0275590551, "max_line_length": 233, "alphanum_fraction": 0.7449180328, "num_tokens": 5481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4574458615609408}} {"text": "/*\n** BCM - bipartite connectivity mapping\n**\n** G.Lohmann, MPI-KYB, Aug 2017\n*/\n#include \n#include \n#include \n#include \n\n#include \"viaio/Vlib.h\"\n#include \"viaio/VImage.h\"\n#include \"viaio/mu.h\"\n#include \"viaio/option.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nextern void gsl_sort_vector_index(gsl_permutation *,gsl_vector *);\n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\nextern gsl_matrix_float *DataMatrix(VImage *src,int nslices,VImage roi,int);\nextern size_t NumVoxels(VImage src);\nextern VImage VoxelMap(VImage roi);\n\ntypedef struct SpointStruct{\n VShort x;\n VShort y;\n VShort z;\n} SPoint;\n\nVDictEntry MetricDict[] = {\n { \"pearson\", 0 },\n { \"spearman\", 1 },\n { \"MI\", 2 },\n { NULL }\n};\n\n\nVImage VCallocImage(int nslices,int nrows,int ncols,VRepnKind repn,VImage ref)\n{\n VImage image = VCreateImage(nslices,nrows,ncols,repn);\n if (image == NULL) VError(\" error allocating image\");\n VFillImage(image,VAllBands,0);\n if (ref != NULL) VCopyImageAttrs (ref,image);\n return image;\n}\n\nvoid ShowImage(gsl_matrix_float *A,char *filename)\n{\n int i,j;\n int n=A->size1;\n int m=A->size2;\n VImage tstimage = VCallocImage(1,n,m,VFloatRepn,NULL);\n for (i=0; i rad2) continue;\n\ti++;\n }\n }\n }\n VImage roi = VCreateImage(nslices,nrows,ncols,VBitRepn);\n VFillImage(roi,VAllBands,0);\n for (b=b0-radius; b<=b0+radius; b++) {\n if (b < 0 || b >= nslices) VError(\" b %d\",b);\n for (r=r0-radius; r<=r0+radius; r++) {\n if (r < 0 || r >= nrows) VError(\" r %d\",r);\n for (c=c0-radius; c<=c0+radius; c++) {\n\tif (c < 0 || c >= ncols) VError(\" c %d\",c);\n\tif (SQR(b-b0) + SQR(r-r0) + SQR(c-c0) > rad2) continue;\n\tVPixel(roi,b,r,c,VBit) = 1;\n }\n }\n }\n return roi;\n}\n\n\ndouble Pearson(const float *data1,const float *data2,int n)\n{\n int i;\n double corr=0;\n for (i=0; i tiny) mi = -0.5 * log(u);\n if (mi < 0) {\n VWarning(\"MI: %f\",mi);\n mi = 0;\n }\n return mi;\n}\n\n\ndouble Correlation(const float *data1,const float *data2,int n,int metric)\n{\n double corr=0.0;\n if (metric == 0) corr = Pearson(data1,data2,n);\n if (metric == 1) corr = Spearman(data1,data2,n);\n if (metric == 2) corr = MutualInformation(data1,data2,n);\n if (gsl_isnan(corr) || gsl_isinf(corr)) corr = 0;\n return corr;\n}\n\n\nvoid VectorNormalize(gsl_vector_float *x)\n{\n int i;\n double nx = (float)x->size;\n double sum1=0,sum2=0;\n for (i=0; isize; i++) {\n sum1 += x->data[i];\n sum2 += x->data[i]*x->data[i];\n }\n double mean = sum1/nx;\n double sigma = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0)));\n\n for (i=0; isize; i++) {\n x->data[i] = (x->data[i] - mean)/sigma;\n }\n}\n\n\n/* bipartite eigenvector centrality mapping */\nvoid VBiadjacencyECM(gsl_matrix_float *C,gsl_vector_float *xa,gsl_vector_float *xb)\n{\n int na = C->size1;\n int nb = C->size2;\n int i,iter,maxiter=100;\n double d=0,sum=0,sum_old=0;\n\n /* ini */\n gsl_vector_float *ya = gsl_vector_float_calloc(na);\n gsl_vector_float *yb = gsl_vector_float_calloc(nb); \n double nx = (double)(na+nb);\n for (i=0; idata[i] = 1.0/nx;\n for (i=0; idata[i] = 1.0/nx;\n\n /* iterations */\n for (iter=0; iterdata[i]*ya->data[i];\n for (i=0; idata[i]*yb->data[i];\n sum = sqrt(sum);\n\n for (i=0; idata[i] = ya->data[i]/sum;\n for (i=0; idata[i] = yb->data[i]/sum;\n\n d = fabs(sum-sum_old);\n if (iter > 0) fprintf(stderr,\" %5d %f\\n\",(int)iter,d);\n if (d < 1.0e-8 && iter > 3) break;\n if (iter > 5 && sum > sum_old) break;\n sum_old = sum;\n }\n\n gsl_vector_float_free(ya);\n gsl_vector_float_free(yb);\n}\n\n\n/* bipartite degree centrality mapping */\nvoid VBiadjacencyDegreeMap(gsl_matrix_float *C,gsl_vector_float *xa,gsl_vector_float *xb)\n{\n size_t na = C->size1;\n size_t nb = C->size2;\n size_t i;\n\n gsl_vector_float *ya = gsl_vector_float_calloc(na);\n gsl_vector_float *yb = gsl_vector_float_calloc(nb);\n for (i=0; idata[i] = 1.0/(double)na;\n for (i=0; idata[i] = 1.0/(double)nb;\n \n gsl_blas_sgemv (CblasNoTrans,1.0,C,xb,0.0,ya);\n gsl_blas_sgemv (CblasTrans,1.0,C,xa,0.0,yb);\n\n gsl_vector_float_memcpy(xa,ya);\n gsl_vector_float_memcpy(xb,yb);\n\n gsl_vector_float_free(ya);\n gsl_vector_float_free(yb);\n}\n\n\n\n/* project onto ROI */\nvoid VNetworkProjection(gsl_matrix_float *C,gsl_vector_float *x)\n{\n size_t na = C->size1;\n size_t nb = C->size2;\n size_t i,n1=0,n2=0;\n \n if (x->size == na) {\n n1 = na;\n n2 = nb;\n }\n else {\n n1 = nb;\n n2 = na;\n }\n float nx = (float)n2;\n\n fprintf(stderr,\" network projection\\n\");\n\n /* project bipartite graph onto ROI */\n gsl_matrix_float *A = gsl_matrix_float_calloc(n1,n1);\n if (!A) VError(\" err allocating projection network\");\n int progress=0;\n\n#pragma omp parallel for schedule(guided) firstprivate(C,A)\n for (i=0; idata[i] = w/nx;\n }\n gsl_matrix_float_free(A);\n}\n\n\n\n/* make matrix positive */\nvoid VThresholdMatrix(gsl_matrix_float *C,float threshold)\n{\n int i,j;\n size_t nneg=0,npos=0;\n float u=0,tiny=1.0e-6;\n double sum1=0,sum2=0;\n double nx = (double)(C->size1 * C->size2);\n for (i=0; isize1; i++) {\n for (j=0; jsize2; j++) {\n u = gsl_matrix_float_get(C,i,j);\n sum1 += u;\n sum2 += u*u;\n if (u < threshold+tiny) nneg++;\n else npos++;\n if (u < threshold+tiny) gsl_matrix_float_set(C,i,j,0.0);\n }\n }\n if (npos < 1) VWarning(\" Subthreshold correlations only\");\n double mean = sum1/nx;\n double sigma = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0)));\n fprintf(stderr,\" matrix mean,std: %f %f, npos: %lu, nneg: %lu\\n\",mean,sigma,npos,nneg);\n}\n\n\nint main (int argc,char *argv[])\n{ \n static SPoint addr1;\n static SPoint addr2; \n static VString roi1_filename = \"\";\n static VString roi2_filename = \"\"; \n static VShort type=1;\n static VFloat threshold = 0.0;\n static VShort radius=5;\n static VShort metric = 0;\n static VBoolean plotboth=FALSE;\n static VBoolean normalize=TRUE;\n static VOptionDescRec options[] = { \n {\"roi1\",VStringRepn,1,(VPointer) &roi1_filename,VOptionalOpt,NULL,\"ROI 1\"},\n {\"roi2\",VStringRepn,1,(VPointer) &roi2_filename,VOptionalOpt,NULL,\"ROI 2\"},\n {\"seed1\",VShortRepn,3,(VPointer) &addr1,VOptionalOpt,NULL,\"Voxel address of seed point (x,y,z)\"},\n {\"seed2\",VShortRepn,3,(VPointer) &addr2,VOptionalOpt,NULL,\"Voxel address of seed point (x,y,z)\"},\n {\"type\", VShortRepn,1,(VPointer) &type,VOptionalOpt,NULL,\"Type, 0:ECM, 1: DCM, 2: project onto ROI1, 3: project onto ROI2\"}, \n {\"threshold\", VFloatRepn,1,(VPointer) &threshold,VOptionalOpt,NULL,\"Matrix threshold\"},\n {\"metric\",VShortRepn,1,(VPointer) &metric,VOptionalOpt,MetricDict,\"Correlation metric\"},\n {\"radius\", VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,\"Radius around seed voxel\"},\n {\"both\", VBooleanRepn,1,(VPointer) &plotboth,VOptionalOpt,NULL,\"Whether to plot results of both ROIs\"},\n {\"normalize\", VBooleanRepn,1,(VPointer) &normalize,VOptionalOpt,NULL,\"Whether to normalize results\"},\n };\n FILE *out_file=NULL;\n VString in_file=NULL;\n VImage roi1=NULL,roi2=NULL;\n int i;\n char *prg = GetLipsiaName(\"vbcm\");\n\n\n /* Parse command line arguments and identify files: */\n VParseFilterCmdX (VNumber (options), options, argc, argv,&in_file,&out_file);\n fprintf(stderr,\" type= %d\\n\",type);\n\n /* read functional data */\n VAttrList list = VReadAttrList(in_file,0L,TRUE,FALSE);\n if (list == NULL) VError(\" error reading input file %s\",in_file);\n\n /* get pointers to image data */\n int nrows=0,ncols=0,nt=0;\n int nslices = VAttrListNumImages(list);\n VImage *src = VAttrListGetImages(list,nslices);\n VImageDimensions(src,nslices,&nt,&nrows,&ncols);\n fprintf(stderr,\" image dims: %d %d %d, nt: %d\\n\",nslices,nrows,ncols,nt);\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n printf(\"using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n /* ROI 1 */\n if (strlen(roi1_filename) > 0) {\n VAttrList list1 = VReadAttrList(roi1_filename,0L,TRUE,FALSE);\n if (list1 == NULL) VError(\" error reading roi file %s\",roi1_filename);\n roi1 = VReadImage(list1);\n if (roi1 == NULL) VError(\" err reading %s\",roi1_filename);\n }\n\n /* ROI 2 */\n if (strlen(roi2_filename) > 0) {\n VAttrList list2 = VReadAttrList(roi2_filename,0L,TRUE,FALSE);\n if (list2 == NULL) VError(\" error reading roi file %s\",roi2_filename);\n roi2 = VReadImage(list2);\n if (roi2 == NULL) VError(\" err reading %s\",roi2_filename);\n }\n\n\n /* ROIs from seed voxels */\n if (roi1 == NULL) roi1 = GetRoi(addr1,nslices,nrows,ncols,radius);\n if (roi2 == NULL) roi2 = GetRoi(addr2,nslices,nrows,ncols,radius);\n\n\n /* voxel maps */\n VImage map1 = VoxelMap(roi1);\n VImage map2 = VoxelMap(roi2);\n size_t nvox1 = NumVoxels(roi1);\n size_t nvox2 = NumVoxels(roi2);\n fprintf(stderr,\" nvox1: %lu, nvox2: %lu\\n\",nvox1,nvox2);\n\n\n /* read data matrices */\n gsl_matrix_float *X1 = DataMatrix(src,nslices,roi1,(int)metric);\n gsl_matrix_float *X2 = DataMatrix(src,nslices,roi2,(int)metric);\n \n\n /* correlation matrix */\n fprintf(stderr,\" CorrMatrix...\\n\");\n int rad2 = 3*3; /* exclusion radius */\n gsl_matrix_float *A = gsl_matrix_float_calloc(nvox1,nvox2);\n if (A == NULL) VError(\" err allocating corr matrix, %d x %d\",nvox1,nvox2);\n int progress=0;\n\n#pragma omp parallel for schedule(guided) firstprivate(A)\n for (i=0; idata[i];\n }\n if (plotboth) {\n for (i=0; idata[i];\n }\n }\n \n\n /* write output to disk */\n VAttrList out_list = VCreateAttrList();\n VAttrList geolist = VGetGeoInfo(list);\n if (geolist != NULL) {\n double *D = VGetGeoDim(geolist,NULL);\n D[0] = 3; /* 3D */\n D[4] = 1;\n VSetGeoDim(geolist,D);\n VSetGeoInfo(geolist,out_list);\n }\n VHistory(VNumber(options),options,prg,&list,&out_list);\n VAppendAttr(out_list,\"image\",NULL,VImageRepn,dest);\n VWriteFile (out_file, out_list);\n fclose(out_file);\n fprintf (stderr, \"%s: done. \\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "88fa4177661dacd21e4f9294e8ba94aafd08c697", "size": 14653, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nets/vbcm/vbcm.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/nets/vbcm/vbcm.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/nets/vbcm/vbcm.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": 26.2128801431, "max_line_length": 132, "alphanum_fraction": 0.6221934075, "num_tokens": 5124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45744586156094075}} {"text": "/* ode-initval/rk4.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/* Runge-Kutta 4, Classical */\n\n/* Author: G. Jungman\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\ntypedef struct\n{\n double *k;\n double *y0;\n double *ytmp;\n}\nrk4_state_t;\n\nstatic void *\nrk4_alloc (size_t dim)\n{\n rk4_state_t *state = (rk4_state_t *) malloc (sizeof (rk4_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rk4_state\", GSL_ENOMEM);\n }\n\n state->k = (double *) malloc (dim * sizeof (double));\n\n if (state->k == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k\", GSL_ENOMEM);\n }\n\n state->y0 = (double *) malloc (dim * sizeof (double));\n\n if (state->y0 == 0)\n {\n free (state->k);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n }\n\n state->ytmp = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp == 0)\n {\n free (state->y0);\n free (state->k);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\nstatic int\nrk4_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], \n const gsl_odeiv_system * sys)\n{\n rk4_state_t *state = (rk4_state_t *) vstate;\n\n size_t i;\n int status = 0;\n\n double *const k = state->k;\n double *const y0 = state->y0;\n double *const ytmp = state->ytmp;\n\n\n /* Copy the starting value. We will write over\n * the y[] vector, using it for scratch and\n * then filling it with the final result.\n */\n\n DBL_MEMCPY (y0, y, dim);\n\n if (dydt_in != NULL)\n {\n DBL_MEMCPY (k, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t, y0, k);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n y[i] = h / 6.0 * k[i]; /* use y[] to store delta_y */\n ytmp[i] = y0[i] + 0.5 * h * k[i];\n }\n\n /* k2 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n y[i] += h / 3.0 * k[i];\n ytmp[i] = y0[i] + 0.5 * h * k[i];\n }\n\n /* k3 step */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n y[i] += h / 3.0 * k[i];\n ytmp[i] = y0[i] + h * k[i];\n }\n\n /* k4 step, error estimate, and final sum */\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n for (i = 0; i < dim; i++)\n {\n y[i] += h / 6.0 * k[i];\n yerr[i] = h * y[i];\n y[i] += y0[i];\n if (dydt_out != NULL)\n dydt_out[i] = k[i];\n }\n\n return status;\n}\n\nstatic int\nrk4_reset (void *vstate, size_t dim)\n{\n rk4_state_t *state = (rk4_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->k, dim);\n DBL_ZERO_MEMSET (state->y0, dim);\n DBL_ZERO_MEMSET (state->ytmp, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrk4_order (void *vstate)\n{\n rk4_state_t *state = (rk4_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 4;\n}\n\nstatic void\nrk4_free (void *vstate)\n{\n rk4_state_t *state = (rk4_state_t *) vstate;\n free (state->k);\n free (state->y0);\n free (state->ytmp);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type rk4_type = { \"rk4\", /* name */\n 1, /* can use dydt_in */\n 0, /* gives exact dydt_out */\n &rk4_alloc,\n &rk4_apply,\n &rk4_reset,\n &rk4_order,\n &rk4_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_rk4 = &rk4_type;\n", "meta": {"hexsha": "ae944e7a20e5650d14a69272dc74e3c4e66181aa", "size": 4536, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl_subset/ode-initval/rk4.c", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/ode-initval/rk4.c", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/ode-initval/rk4.c", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 21.8076923077, "max_line_length": 76, "alphanum_fraction": 0.5824514991, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.4565600926907293}} {"text": "/* ode-initval/rk4imp.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/* Runge-Kutta 4, Gaussian implicit */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\ntypedef struct\n{\n double *k1nu;\n double *k2nu;\n double *ytmp1;\n double *ytmp2;\n}\nrk4imp_state_t;\n\nstatic void *\nrk4imp_alloc (size_t dim)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) malloc (sizeof (rk4imp_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for rk4imp_state\",\n GSL_ENOMEM);\n }\n\n state->k1nu = (double *) malloc (dim * sizeof (double));\n\n if (state->k1nu == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k1nu\", GSL_ENOMEM);\n }\n\n state->k2nu = (double *) malloc (dim * sizeof (double));\n\n if (state->k2nu == 0)\n {\n free (state->k1nu);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k2nu\", GSL_ENOMEM);\n }\n\n state->ytmp1 = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp1 == 0)\n {\n free (state->k2nu);\n free (state->k1nu);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp1\", GSL_ENOMEM);\n }\n\n state->ytmp2 = (double *) malloc (dim * sizeof (double));\n\n if (state->ytmp2 == 0)\n {\n free (state->ytmp1);\n free (state->k2nu);\n free (state->k1nu);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for ytmp2\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\nstatic int\nrk4imp_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], \n const gsl_odeiv_system * sys)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n const double ir3 = 1.0 / M_SQRT3;\n const int iter_steps = 3;\n int status = 0;\n int nu;\n size_t i;\n\n double *const k1nu = state->k1nu;\n double *const k2nu = state->k2nu;\n double *const ytmp1 = state->ytmp1;\n double *const ytmp2 = state->ytmp2;\n\n /* initialization step */\n if (dydt_in != 0)\n {\n DBL_MEMCPY (k1nu, dydt_in, dim);\n }\n else\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1nu);\n GSL_STATUS_UPDATE (&status, s);\n }\n\n DBL_MEMCPY (k2nu, k1nu, dim);\n\n /* iterative solution */\n for (nu = 0; nu < iter_steps; nu++)\n {\n for (i = 0; i < dim; i++)\n {\n ytmp1[i] =\n y[i] + h * (0.25 * k1nu[i] + 0.5 * (0.5 - ir3) * k2nu[i]);\n ytmp2[i] =\n y[i] + h * (0.25 * k2nu[i] + 0.5 * (0.5 + ir3) * k1nu[i]);\n }\n {\n int s =\n GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h * (1.0 - ir3), ytmp1, k1nu);\n GSL_STATUS_UPDATE (&status, s);\n }\n {\n int s =\n GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h * (1.0 + ir3), ytmp2, k2nu);\n GSL_STATUS_UPDATE (&status, s);\n }\n }\n\n /* assignment */\n for (i = 0; i < dim; i++)\n {\n const double d_i = 0.5 * (k1nu[i] + k2nu[i]);\n if (dydt_out != NULL)\n dydt_out[i] = d_i;\n y[i] += h * d_i;\n yerr[i] = h * h * d_i; /* FIXME: is this an overestimate ? */\n }\n\n return status;\n}\n\nstatic int\nrk4imp_reset (void *vstate, size_t dim)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->k1nu, dim);\n DBL_ZERO_MEMSET (state->k2nu, dim);\n DBL_ZERO_MEMSET (state->ytmp1, dim);\n DBL_ZERO_MEMSET (state->ytmp2, dim);\n\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\nrk4imp_order (void *vstate)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 4;\n}\n\nstatic void\nrk4imp_free (void *vstate)\n{\n rk4imp_state_t *state = (rk4imp_state_t *) vstate;\n free (state->k1nu);\n free (state->k2nu);\n free (state->ytmp1);\n free (state->ytmp2);\n free (state);\n}\n\nstatic const gsl_odeiv_step_type rk4imp_type = { \"rk4imp\", /* name */\n 1, /* can use dydt_in */\n 0, /* gives exact dydt_out */\n &rk4imp_alloc,\n &rk4imp_apply,\n &rk4imp_reset,\n &rk4imp_order,\n &rk4imp_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_rk4imp = &rk4imp_type;\n", "meta": {"hexsha": "7f31eac0ff5a598906bdbf7ccbc9ff42a6a67716", "size": 5058, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl_subset/ode-initval/rk4imp.c", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/ode-initval/rk4imp.c", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/ode-initval/rk4imp.c", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 24.0857142857, "max_line_length": 78, "alphanum_fraction": 0.591735864, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.456438005577683}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"prob_functions.h\"\n#include \"data.h\"\n\nstatic const double ALPHA_PRIOR_MEAN = 1, BETA_PRIOR_MEAN = 1;\n\ndouble my_f (const gsl_vector *x, void *params)\n{\n\tDataset *data = (Dataset *) params;\n\n\tunpackX(x, data);\n\n\treturn - computeQ(data);\n}\n\nvoid my_df (const gsl_vector *x, void *params, gsl_vector *g)\n{\n\tint i, j;\n\n\tDataset *data = (Dataset *) params;\n\tdouble *dQdAlpha = (double *) malloc(sizeof(double) * data->numLabelers * data->numWorkflows);\n\tdouble *dQdBeta = (double *) malloc(sizeof(double) * data->numImages * data->numWorkflows);\n\t\n\tunpackX(x, data);\n\t\n\tgradientQ(data, dQdAlpha, dQdBeta);\n\n\t/* Pack dQdAlpha and dQdBeta into gsl_vector */\n\tfor (i = 0; i < data->numLabelers * data->numWorkflows; i++) {\n\t\tgsl_vector_set(g, i, - dQdAlpha[i]); /* Flip the sign since we want to minimize */\n\t}\n\tfor (j = 0; j < data->numImages * data->numWorkflows; j++) {\n\t gsl_vector_set(g, (data->numLabelers * data->numWorkflows) + j, - dQdBeta[j]); /* Flip the sign since we want to minimize */\n\t}\n\n\tfree(dQdAlpha);\n\tfree(dQdBeta);\n}\n\nvoid my_fdf (const gsl_vector *x, void *params, double *f, gsl_vector *g)\n{\n\t*f = my_f(x, params);\n\tmy_df(x, params, g);\n}\n\nvoid gradientQ (Dataset *data, double *dQdAlpha, double *dQdBeta)\n{\n\tint i, j;\n\tint idx;\n\n\t/* This comes from the priors */\n\t/*RandoPriors*/\n\t/*\n\tfor (i = 0; i < data->numLabelers; i++) {\n\t\tdQdAlpha[i] = - 1 * (data->alpha[i] - data->priorAlpha[i]);\n\t}\n\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tdQdBeta[j] = - 5 * (data->beta[j] - data->priorBeta[j]);\n\t}\n\t*/\n\t/*Here's where the real shit starts*/\n\tfor (idx = 0; idx < data->numLabels; idx++) {\n\t\tint i = data->labels[idx].labelerId;\n\t\tint j = data->labels[idx].imageIdx;\n\t\tint k = data->labels[idx].workflowId;\n\t\tint alphaidx = k * data->numLabelers + i;\n\t\tint betaidx = k * data->numImages + j;\n\t\tint lij = data->labels[idx].label;\n\t\tdouble sigma = prob(data->alpha[alphaidx], data->beta[betaidx]);\n\n\t\tdouble increa, increb;\n\t\tdouble weight = data->probZ1[j] * (lij - sigma) + data->probZ0[j] * (1 - lij - sigma);\n\t\t//double weight = data->probZ1[j] * (2 * lij - 1) + data->probZ0[j] * (-2 * lij + 1);\n\t\tincrea = .5 * weight * log(1-data->beta[betaidx]) * pow( 1-data->beta[betaidx], \n\t\t\t\t\t\t\t\t\t data->alpha[alphaidx] );\n\t\tincreb = -.5 * weight * data->alpha[alphaidx] * pow( 1-data->beta[betaidx], \n\t\t\t\t\t\t\t\t data->alpha[alphaidx]-1 );\n\t\tdQdAlpha[alphaidx] += increa;\n\t\tdQdBeta[betaidx] += increb;\n\t\t//printf(\"Alpha: %f Beta: %f\", data->alpha[alphaidx], data->beta[betaidx]);\n\t\t//printf(\"Blah%f %f %f\\n\", log(1-data->beta[j]), 1-data->beta[j], data->alpha[i]);\n\t\t//printf(\"%d %d %d %f %f %f %f\\n\", i, j, lij, sigma, increa, increb, weight); \n\t\t//printf(\"%f %f\\n\", data->probZ1[j], data->probZ0[j]);\n\t\t/*\n\t\tif ( isnan(prob(data->alpha[i], data->beta[j])) )\n{\nprintf(\"%d %d\\n\", i, j);\nprintf(\"%f %f\\n\", data->probZ1[j], data->probZ0[j]);\nprintf(\"alpha %f beta %f\\n\", data->alpha[i], data->beta[j]);\nprintf(\"sigma %f\\n\", sigma);\nprintf(\"label %d\\n\", lij);\nprintf(\"prob: %f\\n\", prob);\nprintf(\"%f\\n\", pow( 1-data->beta[j], data->alpha[i]-1 ));\nprintf(\"%f\\n\", data->alpha[i]);\nprintf(\"%f %f\\n\", increa, increb);\n}\nfflush(0);\n\n\n\tfor (i = 0; i < data->numLabelers; i++) {\n\t\tprintf(\"i %d %f %f\\n\", i, data->alpha[i], dQdAlpha[i]);\n\t}\n\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tprintf(\"j %d %f %f\\n\", j, data->beta[j], dQdBeta[j]);\n\t}\n\t\t*/\n\t }\n\t\n}\n/*\ndouble computeLikelihood (Dataset *data)\n{\n\tint i, j;\n\tint idx;\n\tdouble L = 0;\n\n\tdouble *alpha = data->alpha, *beta = data->beta;\n\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tdouble P1 = data->priorZ1[j];\n\t\tdouble P0 = 1 - data->priorZ1[j];\n\t\tfor (idx = 0; idx < data->numLabels; idx++) {\n\t\t\tif (data->labels[idx].imageIdx == j) {\n\t\t\t\tint i = data->labels[idx].labelerId;\n\t\t\t\tint lij = data->labels[idx].label;\n\t\tdouble sigma = prob(alpha[i], beta[j]);\n\t\t\t\tP1 *= pow(sigma, lij) * pow(1 - sigma, 1 - lij);\n\t\t\t\tP0 *= pow(sigma, 1 - lij) * pow(1 - sigma, lij);\n\t\t\t}\n\t\t}\n\t\tL += log(P1 + P0);\n\t}\n\n\t/// Add Gaussian (standard normal) prior for alpha\n\tfor (i = 0; i < data->numLabelers; i++) {\n\t\tL += log(gsl_sf_erf_Z(alpha[i] - data->priorAlpha[i]));\n\t}\n\n\t/// Add Gaussian (standard normal) prior for beta\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tL += log(gsl_sf_erf_Z(beta[j] - data->priorBeta[j]));\n\t}\n\n\treturn L;\n}*/\n\ndouble computeQ (Dataset *data)\n{\n\tint i, j;\n\tint idx;\n\tdouble Q = 0;\n\n\tdouble *alpha = data->alpha, *beta = data->beta;\n\n\t/* Start with the expectation of the sum of priors over all images */\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tQ += data->probZ1[j] * log(data->priorZ1[j]);\n\t\tQ += data->probZ0[j] * log(1 - data->priorZ1[j]);\n\t}\n\n\tfor (idx = 0; idx < data->numLabels; idx++) {\n\t\tint i = data->labels[idx].labelerId;\n\t\tint j = data->labels[idx].imageIdx;\n\t\tint k = data->labels[idx].workflowId;\n\t\tint alphaidx = k * data->numLabelers + i;\n\t\tint betaidx = k * data->numImages + j;\n\t\tint lij = data->labels[idx].label;\n\t\t/* Do some analytic manipulation first for numerical stability! */\n\t\tdouble logSigma = log( prob(alpha[alphaidx], beta[betaidx]) );\n\t\tdouble logOneMinusSigma = log( 1-prob(alpha[alphaidx], beta[betaidx]) );\n\t\tif (beta[betaidx] > 1 || beta[betaidx] < 0 || alpha[alphaidx] < 0) {\n\t\t Q += -100000000000000000;\n\t\t} else {\n\t\t Q += data->probZ1[j] * (lij * logSigma + (1 - lij) * logOneMinusSigma) +\n\t\t data->probZ0[j] * ((1 - lij) * logSigma + lij * logOneMinusSigma);\n\n\t\t}\n\t\tif (isnan(Q)) { \n\t\t printf(\"%d %d %d %f %f %f %f %f %f %f %f\\n\", i, j, lij, logSigma, \n\t\t\t logOneMinusSigma,\n\t\t\t prob(alpha[i], beta[j]),\n\t\t\t data->probZ1[j],\n\t\t\t data->probZ0[j],\n\t\t\t alpha[alphaidx],\n\t\t\t beta[betaidx],\n\t\t\t Q);\n\t\t abort();\n\t\t}\n\t}\n\n\t/* Add Gaussian (standard normal) prior for alpha */\n\tfor (i = 0; i < data->numLabelers * data->numWorkflows; i++) {\n\t\t//Q += log(gsl_sf_erf_Z(alpha[i] - data->priorAlpha[i]));\n\t}\n\n\t/* Add Gaussian (standard normal) prior for beta */\n\tfor (j = 0; j < data->numImages * data->numWorkflows; j++) {\n\t\t//Q += log(gsl_sf_erf_Z(beta[j] - data->priorBeta[j]));\n\t}\n\n\t// add penalty of beta not between 0 and 1\n\tfor (j = 0; j < data->numImages * data->numWorkflows; j++) {\n\t if ( data->beta[j] > 1 || data->beta[j] < 0 ) {\n\t Q -= 100;\n\t }\n\t}\n\treturn Q;\n}\n\ndouble logProbL (int l, int z, double alphaI, double betaJ)\n{\n\tdouble p;\n\n\tif (z == l) {\n\t\tp = log(prob(alphaI, betaJ));\n\t} else {\n\t\tp = log(1-prob(alphaI, betaJ));\n\t}\n/*\n printf(\"p: %f\\n\", prob(alphaI, betaJ) );\n printf(\"1-p: %f\\n\", 1-prob(alphaI, betaJ) );\n printf(\"log: %f\\n\", p);\n*/\n\treturn p;\n}\n\ndouble prob(double alpha, double beta)\n{\n return .5 + .5 * pow(1-beta, alpha);\n}\n\nvoid EStep (Dataset *data)\n{\n\tint j;\n\tint idx;\n/*\n printf(\"begin Estep\\n\");\n fflush(0);\n*/\n\tfor (j = 0; j < data->numImages; j++) {\n\t\tdata->probZ1[j] = log(data->priorZ1[j]);\n\t\tdata->probZ0[j] = log(1 - data->priorZ1[j]);\n\t\t//printf(\"%d %f %f\\n\", j, data->probZ1[j], data->probZ0[j]);\n\t}\n\n\tfor (idx = 0; idx < data->numLabels; idx++) {\n\t\tint i = data->labels[idx].labelerId;\n\t\tint j = data->labels[idx].imageIdx;\n\t\tint k = data->labels[idx].workflowId;\n\t\tint alphaidx = k * data->numLabelers + i;\n\t\tint betaidx = k * data->numImages + j;\n\t\tint lij = data->labels[idx].label;\n\t\t//printf(\"JOE%d %d %d %f %f\\n\", k, alphaidx, betaidx, data->alpha[alphaidx], data->beta[betaidx]); \n\t\tdata->probZ1[j] += logProbL(lij, 1, data->alpha[alphaidx], \n\t\t\t\t\t data->beta[betaidx]);\n\t\tdata->probZ0[j] += logProbL(lij, 0, data->alpha[alphaidx], \n\t\t\t\t\t data->beta[betaidx]);\n\t\t//printf(\"%d %d %f %f\\n\", j, lij, data->probZ1[j], data->probZ0[j]);\n\t}\n\n\t/* Exponentiate and renormalize */\n\tfor (j = 0; j < data->numImages; j++) {\n\t //printf(\"Before: %f %f\\n\", data->probZ1[j], data->probZ0[j]);\n\t /*Chris adding code here to do this better */\n\t double normalizingDenominator = data->probZ1[j] + \n\t log(1 + exp(data->probZ0[j] -\n\t\t\tdata->probZ1[j]));\n\t data->probZ1[j] = data->probZ1[j] - normalizingDenominator;\n\t data->probZ0[j] = data->probZ0[j] - normalizingDenominator;\n\t //printf(\"Hmm: %f %f %f\\n\", normalizingDenominator, data->probZ1[j], data->probZ0[j]);\n\t data->probZ1[j] = exp(data->probZ1[j]);\n\t data->probZ0[j] = exp(data->probZ0[j]);\n\t /*\n\t data->probZ1[j] = exp(data->probZ1[j]);\n\t data->probZ0[j] = exp(data->probZ0[j]);\n\t printf(\"%f %f\\n\", data->probZ1[j], data->probZ0[j]);\n\t data->probZ1[j] = data->probZ1[j] / (data->probZ1[j] + data->probZ0[j]); \n\t data->probZ0[j] = 1 - data->probZ1[j];\n\t */\n\t //printf(\"%d %f %f\\n\", j, data->probZ1[j], data->probZ0[j]);\n\t if (isnan(data->probZ1[j])) {\n\t printf(\"ABORTING?\");\n\t abort();\n\t }\n\t}\n/*\n printf(\"end Estep\\n\");\n fflush(0);\n*/\n}\n\nvoid MStep (Dataset *data)\n{\n\tdouble lastF;\n\tint iter, status;\n\tint i, j;\n\n\tint numLabelers = data->numLabelers;\n\tint numImages = data->numImages;\n\tint numWorkflows = data->numWorkflows;\n\t\t\n\tgsl_vector *x;\n\tgsl_multimin_fdfminimizer *s;\n\tconst gsl_multimin_fdfminimizer_type *T;\n\tgsl_multimin_function_fdf my_func;\n\n\tx = gsl_vector_alloc((numLabelers * numWorkflows) + (numImages * numWorkflows));\n\n\t/* Pack alpha and beta into a gsl_vector */\n\tpackX(x, data);\n\n\t/* Initialize objective function */\n\tmy_func.n = (numLabelers * numWorkflows) + (numImages * numWorkflows);\n\tmy_func.f = &my_f;\n\tmy_func.df = &my_df;\n\tmy_func.fdf = &my_fdf;\n\tmy_func.params = data;\n\n\t/* Initialize minimizer */\n\tT = gsl_multimin_fdfminimizer_conjugate_pr;\n\ts = gsl_multimin_fdfminimizer_alloc(T, (numLabelers * numWorkflows) + (numImages * numWorkflows));\n\n\tgsl_multimin_fdfminimizer_set(s, &my_func, x, 0.01, 0.01);\n\titer = 0;\n\tdo {\n\t\tlastF = s->f;\n\t\titer++;\n\t\t/*printf(\"iter=%d f=%f\\n\", iter, s->f);*/\n\t\n\t\tstatus = gsl_multimin_fdfminimizer_iterate(s);\n\t\tif (status) {\n\t\t\tbreak;\n\t\t}\n\t\tstatus = gsl_multimin_test_gradient(s->gradient, 1e-3);\n//\t} while (lastF - s->f > 0.01 && status == GSL_CONTINUE && iter < 25);\n\t} while (iter < 5);\n\n\t/* Unpack alpha and beta from gsl_vector */\n\tunpackX(s->x, data);\n\t\n\tgsl_multimin_fdfminimizer_free(s);\n\tgsl_vector_free(x);\n}\n", "meta": {"hexsha": "5dcc4ecf5cdd115bc888aca5c20726742bb8491b", "size": 10068, "ext": "c", "lang": "C", "max_stars_repo_path": "EM/prob_functions.c", "max_stars_repo_name": "ShreyaR/WorkerPoolSelection", "max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "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": "EM/prob_functions.c", "max_issues_repo_name": "ShreyaR/WorkerPoolSelection", "max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "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": "EM/prob_functions.c", "max_forks_repo_name": "ShreyaR/WorkerPoolSelection", "max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z", "avg_line_length": 28.7657142857, "max_line_length": 128, "alphanum_fraction": 0.6066746126, "num_tokens": 3549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954684, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.45641981111293856}} {"text": "/*\n * BIG_DATA.c\n *\n * Created on: 3 Sep 2020\n * Author: heine\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kalman_filter.h\"\n#include \"particle_filters.h\"\n\n#define N_SETTINGS 10\n#define N_SCALES 11\n\nvoid init_with_zeros(double* array, long length);\nvoid scale_sample_sizes(double scaler, long sample_size_collection[N_SETTINGS][2], int n_settings);\nvoid particle_allocation_time_matching(int bpf_sample_size, double std_sig, double obs_std, int Nobs, int data_length, double x0, double *y, double *Rinv1, double *Rinv0, gsl_matrix *R);\n\nint main(void) {\n \n gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n gsl_rng_set(rng,clock());\n \n double scaler;\n int N_top = 50;\n int N_bpf = 250;\n int run_time_matching = 0;\n int data_length = 50;\n int Nobs = 500;\n double sig_std = .1;\n double obs_std = 1;\n double x0 = 0;\n double p0 = sig_std * sig_std;\n double sample_size_coeff = (double)68000 / (double) 250;\n \n /* -----------------------------------------------------------------------------------\n *\n * Create data\n *\n -----------------------------------------------------------------------------------*/\n double *x = (double*) malloc(data_length * sizeof(double));\n double *y = (double*) malloc(data_length * Nobs * sizeof(double));\n double *noise = (double*) malloc(Nobs * sizeof(double));\n gsl_matrix * A;\n \n double x_prev = 0;\n \n /* Create the measurement covariance square root */\n A = gsl_matrix_alloc(Nobs, Nobs);\n for (int i = 0; i < Nobs; i++) {\n for (int j = 0; j < Nobs; j++) {\n /* Uncomment for identity matrix */\n /*\n * if (i == j) {\n * gsl_matrix_set(A, i, j, 1);\n * } else {\n * gsl_matrix_set(A, i, j, 0);\n } */\n// gsl_matrix_set(A, i, j, gsl_ran_gaussian(rng, 1));\n gsl_matrix_set(A, i, j, gsl_rng_uniform(rng));\n }\n }\n \n /* Calculate the observation covariance */\n gsl_matrix * R = gsl_matrix_alloc(Nobs, Nobs);\n double tmp;\n double decay = 2; // Decay of correlations\n FILE * R_out = fopen(\"R_matrix.txt\", \"w\");\n for (int i = 0; i < Nobs; i++) {\n for (int j = 0; j < Nobs; j++) {\n tmp = 0;\n for (int k = 0; k < Nobs; k++) {\n tmp += gsl_matrix_get(A, i, k) * gsl_matrix_get(A, j, k);\n }\n tmp = obs_std * obs_std * exp(-decay * (double) abs(i - j)) * tmp;\n gsl_matrix_set(R, i, j, tmp);\n fprintf(R_out, \"%e \", tmp);\n }\n fprintf(R_out, \"\\n\");\n }\n fclose(R_out);\n \n // Copy R to A\n for (int i = 0; i < Nobs; i++) {\n for (int j = 0; j < Nobs; j++) {\n gsl_matrix_set(A, i, j, gsl_matrix_get(R, i, j));\n }\n }\n gsl_linalg_cholesky_decomp1(A);\n \n printf(\"Obsevation covariance written in R_matrix.txt\\n\");\n \n /* Main loop for generating the signal and the data */\n FILE *data_file = fopen(\"data.txt\", \"w\");\n for (int n = 0; n < data_length; n++) {\n \n x[n] = x_prev + gsl_ran_gaussian(rng, sig_std);\n x_prev = x[n];\n fprintf(data_file, \"%i %e\", n, x[n]);\n \n /* Uncorrelated observation noise */\n for (int i = 0; i < Nobs; i++) {\n noise[i] = gsl_ran_gaussian(rng, obs_std);\n }\n /* Make the noise correlated by multiplying by A */\n for (int i = 0; i < Nobs; i++) {\n y[n * Nobs + i] = x[n];\n for (int j = 0; j <= i; j++)\n y[n * Nobs + i] += gsl_matrix_get(A, i, j) * noise[j];\n fprintf(data_file, \" %e,\", y[n * Nobs + i]);\n }\n fprintf(data_file, \"\\n\");\n \n }\n fclose(data_file);\n printf(\"Signal and data of length %i generated and written in data.txt\\n\", data_length);\n \n /*\n * Calculate the inverse observation covariances\n */\n printf(\"Computing the observation covariance inverse...\\n\");\n fflush(stdout);\n clock_t start = clock();\n \n /* Observation noise covariance */\n gsl_vector * eval = gsl_vector_alloc(Nobs);\n gsl_matrix * evec = gsl_matrix_alloc(Nobs, Nobs);\n double * Rinv1 = (double*) malloc(Nobs * Nobs * sizeof(double));\n gsl_eigen_symmv_workspace * workspace = gsl_eigen_symmv_alloc(Nobs);\n \n /* Compute the eigen decomposition of R to get the inverse */\n gsl_eigen_symmv(R, eval, evec, workspace);\n FILE* rinv_out = fopen(\"R_inv.txt\", \"w\");\n for (int i = 0; i < Nobs; i++) {\n for (int k = 0; k < Nobs; k++) {\n tmp = 0;\n for (int j = 0; j < Nobs; j++) {\n tmp += gsl_matrix_get(evec, i, j) * gsl_matrix_get(evec, k, j)\n / gsl_vector_get(eval, j);\n \n }\n Rinv1[i * Nobs + k] = tmp;\n fprintf(rinv_out, \"%e, \", tmp);\n }\n fprintf(rinv_out, \"\\n\");\n }\n fclose(rinv_out);\n printf(\"Observation covariance inverse computed and written in R_inv.txt\\n\");\n \n gsl_matrix_free(evec);\n gsl_vector_free(eval);\n gsl_eigen_symmv_free(workspace);\n \n /* Limit the observation correlation to a band and ... */\n int band = 0; // Note we only consider diagonal, i.e. band = 0.\n gsl_matrix * R_low = gsl_matrix_alloc(Nobs, Nobs);\n for (int i = 0; i < Nobs; i++) {\n for (int j = 0; j < Nobs; j++) {\n tmp = abs(i - j) <= band ? gsl_matrix_get(R, i, j) : 0;\n gsl_matrix_set(R_low, i, j, tmp);\n }\n }\n /* ...take inverse */\n gsl_vector * eval_low = gsl_vector_alloc(Nobs);\n gsl_matrix * evec_low = gsl_matrix_alloc(Nobs, Nobs);\n gsl_eigen_symmv_workspace * workspace_low = gsl_eigen_symmv_alloc(Nobs);\n double * Rinv0 = (double*) malloc(Nobs * Nobs * sizeof(double));\n \n gsl_eigen_symmv(R_low, eval_low, evec_low, workspace_low);\n \n FILE * band_R_out = fopen(\"R_band_inv.txt\", \"w\");\n for (int i = 0; i < Nobs; i++) {\n for (int k = 0; k < Nobs; k++) {\n tmp = 0;\n for (int j = 0; j < Nobs; j++) {\n tmp += gsl_matrix_get(evec_low, i, j) * gsl_matrix_get(evec_low, k, j)\n / gsl_vector_get(eval_low, j);\n \n }\n Rinv0[i * Nobs + k] = tmp;\n fprintf(band_R_out, \"%e \", tmp);\n }\n fprintf(band_R_out, \"\\n\");\n }\n fclose(band_R_out);\n printf(\n \"Inverse of the diagonal covariance approximation computed and written in R_band_inv.txt\\n\");\n \n gsl_matrix_free(evec_low);\n gsl_vector_free(eval_low);\n gsl_eigen_symmv_free(workspace_low);\n \n printf(\"elapsed %5.2f sec\\n\", (double) (clock() - start) / CLOCKS_PER_SEC);\n \n if (run_time_matching == 1) {\n /*\n * Particle allocation time matching\n *\n * This part of the code should be run when trying to find the correct N0 sample sizes to match\n * the BPF running time\n */\n \n particle_allocation_time_matching(N_bpf, sig_std, obs_std, Nobs, data_length, x0, y, Rinv1, Rinv0, R);\n \n printf(\"Particle allocation time matching done! Exiting...\\n\");\n return 0; // the code exits\n }\n \n /* ------------------------------------------------------------\n * Kalman filter\n * --------------------------------------------------------- */\n double *x_hat = (double*) malloc(data_length * sizeof(double));\n double *p_hat = (double*) malloc(data_length * sizeof(double));\n \n kalman_filter(x, y, Rinv1, sig_std, obs_std, x_hat, p_hat, data_length, x0, p0, Nobs);\n \n /* Write KF results in a file */\n FILE *kf_out = fopen(\"kf_out.txt\", \"w\");\n for (int i = 0; i < data_length; i++)\n fprintf(kf_out, \"%i %f %f %f\\n\", i, x[i], x_hat[i], p_hat[i]);\n fclose(kf_out);\n \n /*\n * Top level loop\n * */\n double scalers[N_SCALES] = {0.5,1,2,3,4,5,6,7,8,9,10};\n short N_levels = 2;\n long sample_sizes[2] = {0,0};\n long sample_size[1] = { N_bpf }; // This is for one level BPF\n \n double *x_hat_bpf = (double*) malloc(data_length * sizeof(double));\n double *errors = (double *) malloc((N_SETTINGS + 1) * sizeof(double));\n double *times = (double *) malloc((N_SETTINGS + 1) * sizeof(double));\n init_with_zeros(errors, N_SETTINGS + 1);\n init_with_zeros(times, N_SETTINGS + 1);\n \n double error;\n FILE * error_out = fopen(\"error.txt\", \"w\");\n \n double filtering_time[4];\n double worst_case_sign_ratio[1] = { 100 }; // This is basically sustitute for \"Inf\"\n long unilevel_sample_size = N_bpf;\n long error_matched_unilevel_sample_size = 7 * N_bpf;\n int N1, N0;\n double step;\n \n /*\n * MAIN LOOP FOR TOP LEVEL MONTE CARLO\n */\n for (int i = 0; i < N_top; i++) {\n \n printf(\"Top level iteration %i\\n\", i);\n \n for (int k = 0; k < N_SCALES; k++) {\n \n scaler = scalers[k];\n \n printf(\"Scaler %f\\n\", scaler);\n \n \n /* Run the basic BPF (time matched) */\n sample_size[0] = (long) round(unilevel_sample_size * scaler);\n bootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, sample_size[0],\n x_hat_bpf, filtering_time, Rinv1, 1);\n \n /* Sum of squared errors over the whole signal */\n error = 0;\n for (int n = 0; n < data_length; n++) {\n error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);\n }\n \n fprintf(error_out, \"%e %i %lu %f %i %e %e %f %e %f\\n\",\n error / (double) data_length, 0, sample_size[0], filtering_time[0], 0,\n filtering_time[1], filtering_time[2], worst_case_sign_ratio[0],\n filtering_time[3], scaler);\n fflush(error_out);\n \n if(scaler < 8) {\n /* Run the basic BPF (error matched) */\n sample_size[0] = (long) round(error_matched_unilevel_sample_size * scaler);\n bootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, sample_size[0],\n x_hat_bpf, filtering_time, Rinv1, 1);\n \n /* Sum of squared errors over the whole signal */\n error = 0;\n for (int n = 0; n < data_length; n++) {\n error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);\n }\n \n fprintf(error_out, \"%e %i %lu %f %i %e %e %f %e %f\\n\",\n error / (double) data_length, 0, sample_size[0], filtering_time[0], -1,\n filtering_time[1], filtering_time[2], worst_case_sign_ratio[0],\n filtering_time[3], scaler);\n fflush(error_out);\n }\n \n /* Iterate over different configurations */\n N1 = 0;\n for (int j = 0; j < N_SETTINGS; j++) {\n \n step = (double)(N_bpf - 5) / (double)(N_SETTINGS-1);\n N1 = (int) j * step;\n N0 = (int) floor((N_bpf-N1)*sample_size_coeff);\n worst_case_sign_ratio[0] = 100;\n \n sample_sizes[0] = N0 * scaler;\n sample_sizes[1] = N1 * scaler;\n \n printf(\"N0 = %lu, N1 = %lu, N = %lu\\n\", sample_sizes[0], sample_sizes[1], sample_sizes[0]+sample_sizes[1]);\n \n MLbootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, N_levels,\n sample_sizes, x_hat_bpf, filtering_time, Rinv0, Rinv1,\n worst_case_sign_ratio);\n \n /* Sum of squared errors over the whole signal */\n error = 0;\n for (int n = 0; n < data_length; n++) {\n error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);\n }\n \n fprintf(error_out, \"%e %lu %lu %f %i %e %e %f %e %f\\n\",\n error / (double) data_length, sample_sizes[0],\n sample_sizes[1], filtering_time[0], j+1, filtering_time[1],\n filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler);\n \n }\n fflush(error_out);\n }\n \n }\n \n fclose(error_out);\n \n printf(\"Results of all BPF runs written in error.txt\\n\");\n printf(\"Error summary written in error_summary.txt\\n\");\n \n return 0;\n}\n\nvoid init_with_zeros(double *array, long length) {\n for (int i = 0; i < length; i++)\n array[i] = 0;\n}\n\nvoid scale_sample_sizes(double scaler, long sample_size_collection[N_SETTINGS][2], int n_settings) {\n \n for (int i = 0; i < n_settings; i++)\n for (int j = 0; j < 1; j++)\n sample_size_collection[i][j] = (long) round(scaler * sample_size_collection[i][j]);\n \n}\n\nvoid particle_allocation_time_matching(int bpf_sample_size, double std_sig, double obs_std, int Nobs, int data_length, double x0, double *y, double *Rinv1, double *Rinv0, gsl_matrix *R) {\n \n int N1_step = 20;\n int N0_step = 10000;\n int N0_init = 10;\n int N_top = 5;\n double time_per_iteration;\n double time_tolerance = 1.00; //\n double filtering_time[1];\n double worst_case_sign_ratio[1] = { 100 };\n \n double *x_hat_bpf = (double*) malloc(data_length * sizeof(double));\n \n /* Find the reference time per iteration for BPF */\n double bpf_time_per_iteration = 0;\n \n for(int nmc = 0; nmc < N_top; nmc++) {\n bootstrapfilter(y, std_sig, obs_std, data_length, x0, Nobs, bpf_sample_size,\n x_hat_bpf, filtering_time, Rinv1, 1);\n bpf_time_per_iteration += filtering_time[0] / (double) N_top;\n }\n \n printf(\"Time per iteration (BPF): %0.5f\\n\",bpf_time_per_iteration);\n fflush(stdout);\n \n long sample_sizes[2] = {0,0};\n int N0;\n short direction;\n \n FILE* out = fopen(\"time_matched_sample_sizes.txt\",\"w\");\n \n /* For given L0 mesh, iterate over N1 */\n for(int N1 = 0; N1 <= bpf_sample_size ; N1 = N1 + N1_step) {\n \n N0 = N0_init;\n N0_step = 10000;\n \n /* For given L0 mesh and N1 iterate over increasing N0 until MLBPF time per iteration exceeds\n BPF time per iteration */\n time_per_iteration = 0;\n \n direction = 1; // up\n while(1) {\n \n sample_sizes[0] = N0;\n sample_sizes[1] = N1;\n \n /* Estimate the time per iteration by averaging N_top runs */\n time_per_iteration = 0;\n for(int nmc = 0; nmc < N_top; nmc++) {\n \n MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, Nobs, 2,\n sample_sizes, x_hat_bpf, filtering_time, Rinv0, Rinv1,\n worst_case_sign_ratio);\n \n time_per_iteration += filtering_time[0] / (double) N_top;\n }\n \n if (direction == 1 && time_per_iteration > bpf_time_per_iteration * time_tolerance && N0_step > 10) {\n direction = -1; // start going down\n N0_step /= 2; // halve the step\n \n } else if (direction == -1 && time_per_iteration < bpf_time_per_iteration * 1.00 && N0_step > 10) {\n direction = 1;\n N0_step /= 2;\n } else if (N0_step < 10) {\n break;\n }\n N0 = N0 + direction * N0_step;\n \n if(N0 < 1) { // Make sure N0 remains positive and go up if this happens\n N0 = 1;\n direction = 1;\n }\n \n }\n fprintf(out,\"%i %i %i %i\\n\",N0-N0_step,N1,0,0);\n fflush(out);\n }\n \n fclose(out);\n free(x_hat_bpf);\n}\n", "meta": {"hexsha": "7b6419ed1a8ff5fdcecbfc7c7257fc90689d3493", "size": 14533, "ext": "c", "lang": "C", "max_stars_repo_path": "BIG_DATA/BIG_DATA.c", "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BIG_DATA/BIG_DATA.c", "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BIG_DATA/BIG_DATA.c", "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6584269663, "max_line_length": 187, "alphanum_fraction": 0.5787518062, "num_tokens": 4324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4564198087861008}} {"text": "/* integration/qaws.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"initialise.c\"\n#include \"append.c\"\n#include \"qpsrt.c\"\n#include \"util.c\"\n#include \"qc25s.c\"\n\nint\ngsl_integration_qaws (gsl_function * f,\n const double a, const double b,\n gsl_integration_qaws_table * t,\n const double epsabs, const double epsrel,\n const size_t limit,\n gsl_integration_workspace * workspace,\n double *result, double *abserr)\n{\n double area, errsum;\n double result0, abserr0;\n double tolerance;\n size_t iteration = 0;\n int roundoff_type1 = 0, roundoff_type2 = 0, error_type = 0;\n\n /* Initialize results */\n\n initialise (workspace, a, b);\n\n *result = 0;\n *abserr = 0;\n\n if (limit > workspace->limit)\n {\n GSL_ERROR (\"iteration limit exceeds available workspace\", GSL_EINVAL) ;\n }\n\n if (b <= a) \n {\n GSL_ERROR (\"limits must form an ascending sequence, a < b\", GSL_EINVAL) ;\n }\n\n if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))\n {\n GSL_ERROR (\"tolerance cannot be acheived with given epsabs and epsrel\",\n GSL_EBADTOL);\n }\n\n /* perform the first integration */\n\n {\n double area1, area2;\n double error1, error2;\n int err_reliable1, err_reliable2;\n double a1 = a;\n double b1 = 0.5 * (a + b);\n double a2 = b1;\n double b2 = b;\n\n qc25s (f, a, b, a1, b1, t, &area1, &error1, &err_reliable1);\n qc25s (f, a, b, a2, b2, t, &area2, &error2, &err_reliable2);\n \n if (error1 > error2)\n {\n append_interval (workspace, a1, b1, area1, error1);\n append_interval (workspace, a2, b2, area2, error2);\n }\n else\n {\n append_interval (workspace, a2, b2, area2, error2);\n append_interval (workspace, a1, b1, area1, error1);\n }\n \n result0 = area1 + area2;\n abserr0 = error1 + error2;\n }\n\n /* Test on accuracy */\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (result0));\n\n /* Test on accuracy, use 0.01 relative error as an extra safety\n margin on the first iteration (ignored for subsequent iterations) */\n\n if (abserr0 < tolerance && abserr0 < 0.01 * fabs(result0))\n {\n *result = result0;\n *abserr = abserr0;\n\n return GSL_SUCCESS;\n }\n else if (limit == 1)\n {\n *result = result0;\n *abserr = abserr0;\n\n GSL_ERROR (\"a maximum of one iteration was insufficient\", GSL_EMAXITER);\n }\n\n area = result0;\n errsum = abserr0;\n\n iteration = 2;\n\n do\n {\n double a1, b1, a2, b2;\n double a_i, b_i, r_i, e_i;\n double area1 = 0, area2 = 0, area12 = 0;\n double error1 = 0, error2 = 0, error12 = 0;\n int err_reliable1, err_reliable2;\n\n /* Bisect the subinterval with the largest error estimate */\n\n retrieve (workspace, &a_i, &b_i, &r_i, &e_i);\n\n a1 = a_i; \n b1 = 0.5 * (a_i + b_i);\n a2 = b1;\n b2 = b_i;\n\n qc25s (f, a, b, a1, b1, t, &area1, &error1, &err_reliable1);\n qc25s (f, a, b, a2, b2, t, &area2, &error2, &err_reliable2);\n\n area12 = area1 + area2;\n error12 = error1 + error2;\n\n errsum += (error12 - e_i);\n area += area12 - r_i;\n\n if (err_reliable1 && err_reliable2)\n {\n double delta = r_i - area12;\n\n if (fabs (delta) <= 1.0e-5 * fabs (area12) && error12 >= 0.99 * e_i)\n {\n roundoff_type1++;\n }\n if (iteration >= 10 && error12 > e_i)\n {\n roundoff_type2++;\n }\n }\n\n tolerance = GSL_MAX_DBL (epsabs, epsrel * fabs (area));\n\n if (errsum > tolerance)\n {\n if (roundoff_type1 >= 6 || roundoff_type2 >= 20)\n {\n error_type = 2; /* round off error */\n }\n\n /* set error flag in the case of bad integrand behaviour at\n a point of the integration range */\n\n if (subinterval_too_small (a1, a2, b2))\n {\n error_type = 3;\n }\n }\n\n update (workspace, a1, b1, area1, error1, a2, b2, area2, error2);\n\n retrieve (workspace, &a_i, &b_i, &r_i, &e_i);\n\n iteration++;\n\n }\n while (iteration < limit && !error_type && errsum > tolerance);\n\n *result = sum_results (workspace);\n *abserr = errsum;\n\n if (errsum <= tolerance)\n {\n return GSL_SUCCESS;\n }\n else if (error_type == 2)\n {\n GSL_ERROR (\"roundoff error prevents tolerance from being achieved\",\n GSL_EROUND);\n }\n else if (error_type == 3)\n {\n GSL_ERROR (\"bad integrand behavior found in the integration interval\",\n GSL_ESING);\n }\n else if (iteration == limit)\n {\n GSL_ERROR (\"maximum number of subdivisions reached\", GSL_EMAXITER);\n }\n else\n {\n GSL_ERROR (\"could not integrate function\", GSL_EFAILED);\n }\n\n}\n", "meta": {"hexsha": "a358a580c1e388da5b15cad7068992e595fdfd0e", "size": 5791, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/qaws.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/integration/qaws.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/integration/qaws.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": 26.2036199095, "max_line_length": 81, "alphanum_fraction": 0.5831462614, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4562814663681294}} {"text": "/* eigen/gsl_eigen.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_EIGEN_H__\n#define __GSL_EIGEN_H__\n\n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n} gsl_eigen_symm_workspace;\n\ngsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n);\nvoid gsl_eigen_symm_free (gsl_eigen_symm_workspace * w);\nint gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * gc;\n double * gs;\n} gsl_eigen_symmv_workspace;\n\ngsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n);\nvoid gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w);\nint gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w);\n\ntypedef struct {\n size_t size; /* matrix size */\n size_t max_iterations; /* max iterations since last eigenvalue found */\n size_t n_iter; /* number of iterations since last eigenvalue found */\n size_t n_evals; /* number of eigenvalues found so far */\n\n gsl_vector *hv2; /* temporary 2-by-1 householder vector */\n gsl_vector *hv3; /* temporary 3-by-1 householder vector */\n\n int compute_t; /* compute Schur form T = Z^t A Z */\n\n gsl_matrix *H; /* pointer to Hessenberg matrix */\n\n gsl_matrix *Z; /* pointer to Schur vector matrix */\n} gsl_eigen_francis_workspace;\n\ngsl_eigen_francis_workspace * gsl_eigen_francis_alloc (void);\nvoid gsl_eigen_francis_free (gsl_eigen_francis_workspace * w);\nvoid gsl_eigen_francis_T (const int compute_t,\n gsl_eigen_francis_workspace * w);\nint gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval,\n gsl_eigen_francis_workspace * w);\nint gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval,\n gsl_matrix * Z,\n gsl_eigen_francis_workspace * w);\n\ntypedef struct {\n size_t size; /* size of matrices */\n gsl_vector *diag; /* diagonal matrix elements from balancing */\n gsl_vector *tau; /* Householder coefficients */\n gsl_matrix *Z; /* pointer to Z matrix */\n int do_balance; /* perform balancing transformation? */\n size_t n_evals; /* number of eigenvalues found */\n\n gsl_eigen_francis_workspace *francis_workspace_p;\n} gsl_eigen_nonsymm_workspace;\n\ngsl_eigen_nonsymm_workspace * gsl_eigen_nonsymm_alloc (const size_t n);\nvoid gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w);\nvoid gsl_eigen_nonsymm_params (const int compute_t, const int balance,\n gsl_eigen_nonsymm_workspace *w);\nint gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_eigen_nonsymm_workspace * w);\nint gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w);\n\ntypedef struct {\n size_t size; /* size of matrices */\n gsl_vector *work; /* scratch workspace */\n gsl_vector *work2; /* scratch workspace */\n gsl_vector *work3; /* scratch workspace */\n\n gsl_matrix *Z; /* pointer to Schur vectors */\n\n gsl_eigen_nonsymm_workspace *nonsymm_workspace_p;\n} gsl_eigen_nonsymmv_workspace;\n\ngsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc (const size_t n);\nvoid gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w);\nint gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix_complex * evec,\n gsl_eigen_nonsymmv_workspace * w);\nint gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,\n gsl_matrix_complex * evec, gsl_matrix * Z,\n gsl_eigen_nonsymmv_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * tau;\n} gsl_eigen_herm_workspace;\n\ngsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n);\nvoid gsl_eigen_herm_free (gsl_eigen_herm_workspace * w);\nint gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval,\n gsl_eigen_herm_workspace * w);\n\ntypedef struct {\n size_t size;\n double * d;\n double * sd;\n double * tau;\n double * gc;\n double * gs;\n} gsl_eigen_hermv_workspace;\n\ngsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n);\nvoid gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w);\nint gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, \n gsl_matrix_complex * evec,\n gsl_eigen_hermv_workspace * w);\n\n\n\ntypedef enum {\n GSL_EIGEN_SORT_VAL_ASC,\n GSL_EIGEN_SORT_VAL_DESC,\n GSL_EIGEN_SORT_ABS_ASC,\n GSL_EIGEN_SORT_ABS_DESC\n}\ngsl_eigen_sort_t;\n\n/* Sort eigensystem results based on eigenvalues.\n * Sorts in order of increasing value or increasing\n * absolute value.\n *\n * exceptions: GSL_EBADLEN\n */\n\nint gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec,\n gsl_eigen_sort_t sort_type);\n\nint gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec,\n gsl_eigen_sort_t sort_type);\n\nint gsl_eigen_nonsymmv_sort(gsl_vector_complex * eval,\n gsl_matrix_complex * evec,\n gsl_eigen_sort_t sort_type);\n\n\n/* The following functions are obsolete: */\n\n/* Eigensolve by Jacobi Method\n *\n * The data in the matrix input is destroyed.\n *\n * exceptions: \n */\nint\ngsl_eigen_jacobi(gsl_matrix * matrix,\n gsl_vector * eval,\n gsl_matrix * evec,\n unsigned int max_rot, \n unsigned int * nrot);\n\n\n/* Invert by Jacobi Method\n *\n * exceptions: \n */\nint\ngsl_eigen_invert_jacobi(const gsl_matrix * matrix,\n gsl_matrix * ainv,\n unsigned int max_rot);\n\n\n\n__END_DECLS\n\n#endif /* __GSL_EIGEN_H__ */\n", "meta": {"hexsha": "25983dc1defbaace5a47ba8c5fec5b5c414a71f4", "size": 7006, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/gsl_eigen.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/gsl_eigen.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/gsl_eigen.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 33.2037914692, "max_line_length": 106, "alphanum_fraction": 0.6768484156, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.45626715197740986}} {"text": "#ifdef HAVE_PETSC\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"common_c.h\"\n#include \"FCMangle.h\"\n\n#define fillsparsecpetscs FortranCInterface_GLOBAL_(fillsparsecpetscs, FILLSPARSECPETSCS)\n#define fillsparsecpetscc FortranCInterface_GLOBAL_(fillsparsecpetscc, FILLSPARSECPETSCC)\n\n#define COLMAJ2D(row,col,numrow) (row-1)+(col-1)*numrow\n#define COLMAJ3D(a,b,c,amax,bmax,cmax) (a-1)+amax*((b-1)+bmax*(c-1))\n#define ROWMAJ2D_ONE(row,col,numcol) (row-1)*numcol+(col-1)\ntypedef long long int gcorp_t;\n\nvoid fillsparsecpetscs(gcorp_t* ieng, double* EGmass, Mat* lhsP)\n{\n int npro = propar.npro;\n int nshl = shpdat.nshl;\n double* mb = (double*) malloc(sizeof(double)*nshl*nshl); //block to insert\n int e,i,j,aa; //following along with fillsparse.f\n PetscInt* locat = (PetscInt*) malloc(sizeof(PetscInt)*nshl);\n for(e=0;e=0);\n for (i=0; i=0);\n for (i=0; i\n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\n#include \"funcs.h\"\n#include \"initial.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nint main ( int argc, char* argv[] )\n{\n\tgsl_ieee_env_setup () ;\t\t\t/* read GSL_IEEE_MODE */\n\n\tprintf(\"Temperature: %g\\n\\n\", T*HBAR*Delta/BOLTZ) ;\n\n\tdouble beta = 1.0/T ; \t/* Boltzmann factor: beta */\n\tdouble omega_1 = gsl_hypot(OMEGA,D) ; /* omega' */\n\n\tstruct f_params params;\n\tparams.omega_c = omega_c ;\n\tparams.beta = beta ;\n\tparams.Omega = OMEGA ;\n\tparams.omega_1 = omega_1 ;\n\tparams.alpha = alpha ;\n \n\tint status1 = save_integrals ( ¶ms ) ;\n\tint status2 = save_matrices ( ¶ms ) ;\n\t\n\t/* read the Redfield matrix from a file */\n\tgsl_matrix* red_m = gsl_matrix_calloc ( 4, 4 ) ;\n\tint status3 = mat_read ( red_m, \"REDFIELD_MATRIX\" ) ;\n\n\t/* read the CP matrix from a file */\n\tgsl_matrix* cp_m = gsl_matrix_calloc ( 4, 4 ) ;\n\tint status4 = mat_read ( cp_m, \"CP_MATRIX\" ) ;\n\t\n\t/* Hamiltonian generator */\n\tconst double om[] = { 0 , 0 , 0 , omega_1/2 } ;\n\tgsl_matrix* H = gsl_matrix_calloc ( 4, 4 ) ;\n\tint status5 = ham_gen ( H, om ) ;\n\n\n\t/* \n\t * Find the stationary state by solving the linear systems\n\t * and the associated stationary currents\n\t */\n\tgsl_vector* req_red = gsl_vector_calloc (4) ;\n\tgsl_vector* req_cp = gsl_vector_calloc (4) ;\n\n\tprintf(\"REDFIELD DYNAMICS\\n\") ;\n\tint status6 = stationary ( red_m , req_red ) ;\n\tprintf(\"Stationary state: ( %.1f , %.9f , %.9f , %.9f )\\n\", \n\t\t\tVECTOR(req_red,0), VECTOR(req_red,1),\n\t\t\tVECTOR(req_red,2), VECTOR(req_red,3) ) ;\n\tprintf(\"Stationary normalized (I/I0) DC current: %.9f\\n\\n\",\n\t\t\t-VECTOR(req_red,3)*OMEGA/omega_1) ;\n\t\n\tprintf(\"CP DYNAMICS\\n\") ;\n\tint status7 = stationary ( cp_m , req_cp ) ;\n\tprintf(\"Stationary state: ( %.1f , %.9f , %.9f , %.9f )\\n\", \n\t\t\tVECTOR(req_cp,0), VECTOR(req_cp,1),\n\t\t\tVECTOR(req_cp,2), VECTOR(req_cp,3) ) ;\n\tprintf(\"Stationary normalized (I/I0) DC current: %.9f\\n\\n\",\n\t\t\t-VECTOR(req_cp,3)*OMEGA/omega_1) ;\n\n\t/* Save the stationary states into files */\n\tFILE* f = fopen ( \"RED_STATIONARY.dat\", \"w\" ) ;\n\tgsl_vector_fprintf ( f, req_red, \"%.9f\" ) ;\n\tFILE* g = fopen ( \"CP_STATIONARY.dat\", \"w\" ) ;\n\tgsl_vector_fprintf ( g, req_cp, \"%.9f\" ) ;\n\n\tfclose (f) ; fclose (g) ;\n\n\t/* polarization */\n\tdouble D30 = gsl_matrix_get(cp_m,3,0) ;\n\tdouble D33 = gsl_matrix_get(cp_m,3,3) ;\n\tdouble pol = -D30/D33 ;\n\tprintf(\"n-Polarization of the CP dynamics -D30/D33: %.9f\\n\", pol ) ;\n\n\t/* polarization through the formula (for checking) */\n\tdouble P = polarization ( ¶ms, omega_c ) ;\n\tprintf(\"\\n\") ;\n\tprintf(\"n-Polarization through the given formula: %.9f\\n\", P ) ;\n\tprintf(\"Stationary normalized (I/I0) DC current: %.9f\\n\", -P*OMEGA/omega_1 ) ;\n\n\t/* free memory for matrices */\n\tgsl_matrix_free(red_m) ;\n \tgsl_matrix_free(cp_m) ;\t\n\n\treturn status1 + status2 + status3 + status4 + status5 + status6 + status7 ;\n}\n\n", "meta": {"hexsha": "875761b0097b56b6bd6b311a553cf29a027db0ad", "size": 4285, "ext": "c", "lang": "C", "max_stars_repo_path": "asymptotic.c", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "asymptotic.c", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "asymptotic.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4132231405, "max_line_length": 79, "alphanum_fraction": 0.6896149358, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4558081691965784}} {"text": "#ifndef PRIMAL_DUAL_LOOPLESS_KATYUSHA0_H\r\n#define PRIMAL_DUAL_LOOPLESS_KATYUSHA0_H\r\n\r\n#include \"Primal_Dual_LOOPLESS.h\"\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include /* printf */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n//This class implements the method loopless kATYUSHA with arbitrary sampling\r\n\r\n/*\r\nThe optimization problem to solve is:\r\n\r\n\\sum_{i=1}^n \\lambda_i\\phi_i(A_i^{\\top} w)+ g(w)\r\nAssumption 1: For each i, \\phi_i is 1-smooth\r\nBy default, lambda_i=1/n for all i.\r\n*\r\n* The dual problem is\r\n* g*(-sum_{i=1}^n \\lambda_i \\alpha_i A_i)+\\sum_{i=1}^n \\lambda_i \\phi*_i(\\alpha_i)\r\n*/\r\n\r\ntemplate\r\nclass Primal_Dual_LOOPLESS_Katyusha0: public Primal_Dual_LOOPLESS\r\n{\r\n\r\n\r\nprotected:\r\n D theta1;\r\n D theta2;\r\n D theta3;\r\n D eta; //the stepsize parameter alpha in the paper\r\n\r\n D x;\r\n D w;\r\n D y;\r\n D z;\r\n\r\n std::vector primal_y; // the y variable\r\n\r\n std::vector primal_z; // the z variable\r\n\r\n std::vector primal_w; // the w variable\r\n\r\n\r\npublic:\r\n\r\n\r\n virtual inline D gradient_of_phi_i(D, L){return D(NULL);}\r\n virtual inline D gradient_of_gstar_j(D, L){return D(NULL);}\r\n virtual inline D value_of_phi_i(D, L) {return D(NULL);}\r\n virtual inline D value_of_g_j(D, L){return D(NULL);}\r\n virtual inline D value_of_phistar_i(D,L) {return D(NULL);}\r\n virtual inline D value_of_gstar(vector &){return D(NULL);}\r\n virtual inline D value_of_gstar_minus(vector &, D){return D(NULL);}\r\n virtual inline D feasible_dual(vector &){return D(NULL);}\r\n virtual inline D compute_delta_alpha(D,D,L){return D(NULL);}\r\n virtual inline void set_auxiliary_v(){}\r\n virtual inline D get_lambda1(){return D(NULL);}\r\n virtual inline D get_lambda2(){return D(NULL);}\r\n virtual inline void compute_just_in_time_prox_grad(D, D, D &, L,L, D, D &, L){}\r\n\r\n Primal_Dual_LOOPLESS_Katyusha0()\r\n : Primal_Dual_LOOPLESS()\r\n {\r\n \t\r\n }\r\n\r\n\r\n Primal_Dual_LOOPLESS_Katyusha0(const char* matrix_file, const char* vector_file)\r\n : Primal_Dual_LOOPLESS(matrix_file, vector_file)\r\n {\r\n\r\n }\r\n\r\n Primal_Dual_LOOPLESS_Katyusha0(const char* matrix_file)\r\n : Primal_Dual_LOOPLESS(matrix_file)\r\n {\r\n\r\n }\r\n\r\n\r\n void set_theta(){\r\n theta2=this->L2/2/max(this->Lf,this->L2);\r\n if(this->Lf<=this->L2/this->p){\r\n D tmp=this->mu/this->L2/this->p;\r\n cout<<\"this->L2=\"<L2<=1){\r\n theta1=theta2;\r\n }\r\n else{\r\n theta1=sqrt(tmp)*theta2;\r\n }\r\n }else\r\n theta1=min(sqrt(this->mu/this->Lf),this->p/2);\r\n theta3=1-theta1-theta2;\r\n eta=1./(theta1*(this->Lf+2*max(this->L2,this->Lf)));\r\n cout<<\"this->Lf=\"<Lf<<\"; this->L2=\"<L2<<\"; theta1=\"<nfeatures,0);\r\n primal_z.resize(this->nfeatures,0);\r\n primal_w.resize(this->nfeatures,0);\r\n for(L j=0; jnfeatures; j++){\r\n primal_y[j]=this->primal_x[j];\r\n primal_z[j]=this->primal_x[j];\r\n primal_w[j]=this->primal_x[j];\r\n }\r\n cout<<\"w size=\"<primal_x[j]=xj;\r\n primal_z[j]=z;\r\n primal_y[j]=y;\r\n }\r\n\r\n\r\n inline void update_baralpha()\r\n {\r\n D yi=gsl_rng_uniform(this->rng);\r\n if(yi<=this->p){\r\n this->nb_iters+=this->nsamples/this->tau;\r\n D aitg=0;\r\n D deltaalphai=0;\r\n for(L i=0;insamples;i++)\r\n {\r\n aitg=this->compute_AiTxk(i);\r\n deltaalphai=gradient_of_phi_i(aitg,i)-this->dual_alpha[i];\r\n this->dual_alpha[i]+=deltaalphai;\r\n for (L k = this->ptr[i]; k < this->ptr[i + 1];k++)\r\n {\r\n L j=this->row_idx[k];\r\n this->baralpha[j]+=this->lambda_f[i]*deltaalphai*this->A[k];\r\n }\r\n }\r\n\r\n for(L j=0;jnfeatures;j++)\r\n primal_w[j]=this->primal_x[j];\r\n }\r\n }\r\n\r\n\r\n\r\n void loopless_Katyusha(vector & x0, vector & w0, string filename, vector & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\r\n {\r\n filename=\"Katyusha\"+filename;\r\n this->loopless( x0, w0, filename, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod,scal_p);\r\n }\r\n \r\n void loopless_Katyusha2(vector & x0, vector & w0, string filename, vector & L_phi, D val_mu, D val_epsilon, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\r\n {\r\n filename=\"Katyusha\"+filename;\r\n this->loopless2( x0, w0, filename, L_phi, val_mu, val_epsilon, max_nb, nb_tau, nb_c, u, p_mod,scal_p);\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n };\r\n\r\n #endif /* MIN_SMOOTH_CONVEX_H */\r\n", "meta": {"hexsha": "e7fb1d54973c7b1edf89db666baf592b92c19918", "size": 5300, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM/Primal_Dual_LOOPLESS_Katyusha0.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM/Primal_Dual_LOOPLESS_Katyusha0.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM/Primal_Dual_LOOPLESS_Katyusha0.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 26.7676767677, "max_line_length": 171, "alphanum_fraction": 0.6052830189, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.45527226105455115}} {"text": "/* ode-initval/gear2.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/* Gear 2 */\n\n/* Author: G. Jungman\n */\n#include \n#include \n#include \n#include \n#include \n#include \"odeiv_util.h\"\n#include \n\n\n/* gear2 state object */\ntypedef struct\n{\n int primed; /* flag indicating that yim1 is ready */\n double t_primed; /* system was primed for this value of t */\n double last_h; /* last step size */\n gsl_odeiv_step *primer; /* stepper to use for priming */\n double *yim1; /* y_{i-1} */\n double *k; /* work space */\n double *y0; /* work space */\n double *y0_orig;\n double *y_onestep;\n int stutter;\n}\ngear2_state_t;\n\nstatic void *\ngear2_alloc (size_t dim)\n{\n gear2_state_t *state = (gear2_state_t *) malloc (sizeof (gear2_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for gear2_state\", GSL_ENOMEM);\n }\n\n state->yim1 = (double *) malloc (dim * sizeof (double));\n\n if (state->yim1 == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for yim1\", GSL_ENOMEM);\n }\n\n state->k = (double *) malloc (dim * sizeof (double));\n\n if (state->k == 0)\n {\n free (state->yim1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for k\", GSL_ENOMEM);\n }\n\n state->y0 = (double *) malloc (dim * sizeof (double));\n\n if (state->y0 == 0)\n {\n free (state->k);\n free (state->yim1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n }\n\n state->y0_orig = (double *) malloc (dim * sizeof (double));\n\n if (state->y0_orig == 0)\n {\n free (state->y0);\n free (state->k);\n free (state->yim1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0_orig\", GSL_ENOMEM);\n }\n\n state->y_onestep = (double *) malloc (dim * sizeof (double));\n\n if (state->y_onestep == 0)\n {\n free (state->y0_orig);\n free (state->y0);\n free (state->k);\n free (state->yim1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for y0_orig\", GSL_ENOMEM);\n }\n\n state->primed = 0;\n state->primer = gsl_odeiv_step_alloc (gsl_odeiv_step_rk4imp, dim);\n\n if (state->primer == 0)\n {\n free (state->y_onestep);\n free (state->y0_orig);\n free (state->y0);\n free (state->k);\n free (state->yim1);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for primer\", GSL_ENOMEM);\n }\n\n state->last_h = 0.0;\n\n return state;\n}\n\nstatic int\ngear2_step (double *y, gear2_state_t * state,\n const double h, const double t,\n const size_t dim, const gsl_odeiv_system * sys)\n{\n /* Makes a Gear2 advance with step size h.\n y0 is the initial values of variables y. \n The implicit matrix equations to solve are:\n k = y0 + h * f(t + h, k)\n y = y0 + h * f(t + h, k)\n */\n\n const int iter_steps = 3;\n int nu;\n size_t i;\n double *y0 = state->y0;\n double *yim1 = state->yim1;\n double *k = state->k;\n\n /* Iterative solution of k = y0 + h * f(t + h, k)\n Note: This method does not check for convergence of the\n iterative solution! \n */\n\n for (nu = 0; nu < iter_steps; nu++)\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, k);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n\n for (i = 0; i < dim; i++)\n {\n y[i] = ((4.0 * y0[i] - yim1[i]) + 2.0 * h * k[i]) / 3.0;\n }\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\ngear2_apply (void *vstate,\n size_t dim,\n double t,\n double h,\n double y[],\n double yerr[],\n const double dydt_in[],\n double dydt_out[], const gsl_odeiv_system * sys)\n{\n gear2_state_t *state = (gear2_state_t *) vstate;\n\n state->stutter = 0;\n\n if (state->primed == 0 || t == state->t_primed || h != state->last_h)\n {\n /* Execute a single-step method to prime the process. Note that\n * we do this if the step size changes, so frequent step size\n * changes will cause the method to stutter. \n * \n * Note that we reuse this method if the time has not changed,\n * which can occur when the adaptive driver is attempting to find\n * an appropriate step-size on its first iteration */\n\n int status;\n DBL_MEMCPY (state->yim1, y, dim);\n\n status =\n gsl_odeiv_step_apply (state->primer, t, h, y, yerr, dydt_in, dydt_out,\n sys);\n\n /* Make note of step size and indicate readiness for a Gear step. */\n\n state->primed = 1;\n state->t_primed = t;\n state->last_h = h;\n state->stutter = 1;\n\n return status;\n }\n else\n {\n /* We have a previous y value in the buffer, and the step\n * sizes match, so we go ahead with the Gear step.\n */\n\n double *const k = state->k;\n double *const y0 = state->y0;\n double *const y0_orig = state->y0_orig;\n double *const yim1 = state->yim1;\n double *y_onestep = state->y_onestep;\n\n int s;\n size_t i;\n\n DBL_MEMCPY (y0, y, dim);\n\n /* iterative solution */\n\n if (dydt_out != NULL)\n {\n DBL_MEMCPY (k, dydt_out, dim);\n }\n\n /* First traverse h with one step (save to y_onestep) */\n\n DBL_MEMCPY (y_onestep, y, dim);\n\n s = gear2_step (y_onestep, state, h, t, dim, sys);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n\n /* Then with two steps with half step length (save to y) */\n\n s = gear2_step (y, state, h / 2.0, t, dim, sys);\n\n if (s != GSL_SUCCESS)\n {\n /* Restore original y vector */\n DBL_MEMCPY (y, y0_orig, dim);\n return s;\n }\n\n DBL_MEMCPY (y0, y, dim);\n\n s = gear2_step (y, state, h / 2.0, t + h / 2.0, dim, sys);\n\n if (s != GSL_SUCCESS)\n {\n /* Restore original y vector */\n DBL_MEMCPY (y, y0_orig, dim);\n return s;\n }\n\n /* Cleanup update */\n\n if (dydt_out != NULL)\n {\n s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);\n\n if (s != GSL_SUCCESS)\n {\n /* Restore original y vector */\n DBL_MEMCPY (y, y0_orig, dim);\n return s;\n }\n }\n\n /* Estimate error and update the state buffer. */\n\n for (i = 0; i < dim; i++)\n {\n yerr[i] = 4.0 * (y[i] - y_onestep[i]);\n yim1[i] = y0[i];\n }\n\n /* Make note of step size. */\n state->last_h = h;\n\n return 0;\n }\n}\n\nstatic int\ngear2_reset (void *vstate, size_t dim)\n{\n gear2_state_t *state = (gear2_state_t *) vstate;\n\n DBL_ZERO_MEMSET (state->yim1, dim);\n DBL_ZERO_MEMSET (state->k, dim);\n DBL_ZERO_MEMSET (state->y0, dim);\n\n state->primed = 0;\n state->last_h = 0.0;\n return GSL_SUCCESS;\n}\n\nstatic unsigned int\ngear2_order (void *vstate)\n{\n gear2_state_t *state = (gear2_state_t *) vstate;\n state = 0; /* prevent warnings about unused parameters */\n return 3;\n}\n\nstatic void\ngear2_free (void *vstate)\n{\n gear2_state_t *state = (gear2_state_t *) vstate;\n\n free (state->yim1);\n free (state->k);\n free (state->y0);\n free (state->y0_orig);\n free (state->y_onestep);\n gsl_odeiv_step_free (state->primer);\n\n free (state);\n}\n\nstatic const gsl_odeiv_step_type gear2_type = { \"gear2\", /* name */\n 1, /* can use dydt_in */\n 0, /* gives exact dydt_out */\n &gear2_alloc,\n &gear2_apply,\n &gear2_reset,\n &gear2_order,\n &gear2_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_gear2 = &gear2_type;\n", "meta": {"hexsha": "e1afe21840d8355f872b461e1d549f22ec32fd0b", "size": 8505, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/gear2.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/ode-initval/gear2.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/ode-initval/gear2.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.7238372093, "max_line_length": 81, "alphanum_fraction": 0.5675485009, "num_tokens": 2485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4551927035949167}} {"text": "/* specfunc/bessel_K1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * Copyright (C) 2016 Pavel Holoborodko, Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/*\n Minimax rational approximation for [0,1), peak relative error = 1.83*GSL_DBL_EPSILON.\n Source: http://www.advanpix.com/?p=3987\n*/\nstatic double k1_poly[9] = {\n -3.0796575782920622440538935e-01,\n -8.5370719728650778045782736e-02,\n -4.6421827664715603298154971e-03,\n -1.1253607036630425931072996e-04,\n -1.5592887702110907110292728e-06,\n -1.4030163679125934402498239e-08,\n -8.8718998640336832196558868e-11,\n -4.1614323580221539328960335e-13,\n -1.5261293392975541707230366e-15\n};\n\nstatic double i1_poly[7] = {\n 8.3333333333333325191635191e-02,\n 6.9444444444467956461838830e-03,\n 3.4722222211230452695165215e-04,\n 1.1574075952009842696580084e-05,\n 2.7555870002088181016676934e-07,\n 4.9724386164128529514040614e-09\n};\n\n/*\n Chebyshev expansion for [1,8], peak relative error = 1.28*GSL_DBL_EPSILON. \n Source: Pavel Holoborodko.\n*/\nstatic double ak1_data[25] = {\n +2.07996868001418246e-01,\n +1.62581565017881476e-01,\n -5.87070423518863640e-03,\n +4.95021520115789501e-04,\n -5.78958347598556986e-05,\n +8.18614610209334726e-06,\n -1.31604832009487277e-06,\n +2.32546031520101213e-07,\n -4.42206518311557987e-08,\n +8.92163994883100361e-09,\n -1.89046270526983427e-09,\n +4.17568808108504702e-10,\n -9.55912361791375794e-11,\n +2.25769353153867758e-11,\n -5.48128000211158482e-12,\n +1.36386122546441926e-12,\n -3.46936690565986409e-13,\n +9.00354564415705942e-14,\n -2.37950577776254432e-14,\n +6.39447503964025336e-15,\n -1.74498363492322044e-15,\n +4.82994547989290473e-16,\n -1.35460927805445606e-16,\n +3.84604274446777234e-17,\n -1.10456856122581316e-17\n};\n\nstatic cheb_series ak1_cs = {\n ak1_data,\n 24,\n -1, 1,\n 9\n};\n\n/* \n Chebyshev expansion for [8,inf), peak relative error = 1.25*GSL_DBL_EPSILON.\n Source: SLATEC/dbsk1e.f\n*/\nstatic double ak12_data[14] = {\n +.637930834373900104E-1,\n +.283288781304972094E-1,\n -.247537067390525035E-3,\n +.577197245160724882E-5,\n -.206893921953654830E-6,\n +.973998344138180418E-8,\n -.558533614038062498E-9,\n +.373299663404618524E-10,\n -.282505196102322545E-11,\n +.237201900248414417E-12,\n -.217667738799175398E-13,\n +.215791416161603245E-14,\n -.229019693071826928E-15,\n +.258288572982327496E-16\n};\n\nstatic cheb_series ak12_cs = {\n ak12_data,\n 13,\n -1, 1,\n 7\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < 2.0*GSL_DBL_MIN) {\n OVERFLOW_ERROR(result);\n }\n else if(x < 1.0) {\n const double lx = log(x);\n const double ex = exp(x);\n const double x2 = x*x;\n const double t = 0.25*x2; \n const double i1 = 0.5 * x * (1.0 + t * (0.5 + t * gsl_poly_eval(i1_poly,6,t)));\n result->val = ex * (x2 * gsl_poly_eval(k1_poly,9,x2) + x * lx * i1 + 1) / x;\n result->err = ex * (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x <= 8.0) {\n const double sx = sqrt(x);\n gsl_sf_result c;\n cheb_eval_e(&ak1_cs, (16.0/x-9.0)/7.0, &c);\n result->val = (1.375 + c.val) / sx; /* 1.375 = 11/8 */\n result->err = c.err / sx;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n const double sx = sqrt(x);\n gsl_sf_result c;\n cheb_eval_e(&ak12_cs, 16.0/x-1.0, &c);\n result->val = (1.25 + c.val) / sx;\n result->err = c.err / sx;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\n\nint gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x <= 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < 2.0*GSL_DBL_MIN) {\n OVERFLOW_ERROR(result);\n }\n else if(x < 1.0) {\n const double lx = log(x);\n const double x2 = x*x;\n const double t = 0.25*x2; \n const double i1 = 0.5 * x * (1.0 + t * (0.5 + t * gsl_poly_eval(i1_poly,6,t)));\n result->val = (x2 * gsl_poly_eval(k1_poly,9,x2) + x * lx * i1 + 1) / x;\n result->err = (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS; \n }\n else {\n gsl_sf_result K1_scaled;\n int stat_K1 = gsl_sf_bessel_K1_scaled_e(x, &K1_scaled);\n int stat_e = gsl_sf_exp_mult_err_e(-x, 0.0,\n K1_scaled.val, K1_scaled.err,\n result);\n result->err = fabs(result->val) * (GSL_DBL_EPSILON*fabs(x) + K1_scaled.err/K1_scaled.val);\n return GSL_ERROR_SELECT_2(stat_e, stat_K1);\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_K1_scaled(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_K1_scaled_e(x, &result));\n}\n\ndouble gsl_sf_bessel_K1(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_K1_e(x, &result));\n}\n", "meta": {"hexsha": "0c2369c0145c1af788742ba2a2d7966628d63f23", "size": 6109, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_K1.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/specfunc/bessel_K1.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_K1.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": 28.0229357798, "max_line_length": 94, "alphanum_fraction": 0.6595187428, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.45498775340557}} {"text": "/* integration/rational.c\n * \n * Copyright (C) 2017 Konrad Griessinger, Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * The code in this module is based on IQPACK, specifically the LGPL\n * implementation found in HERMITE_RULE:\n * https://people.sc.fsu.edu/~jburkardt/c_src/hermite_rule/hermite_rule.html\n */\n\n#include \n#include \n#include \n#include \n#include \n\nstatic int\nrational_check(const size_t n, const gsl_integration_fixed_params * params)\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->alpha <= -1.0)\n {\n GSL_ERROR(\"alpha must be > -1\", GSL_EDOM);\n }\n else if (params->beta >= 0.0 || params->alpha+params->beta+2*n >= 0.0 || 0.0 >= params->alpha+2*n)\n {\n GSL_ERROR(\"beta < alpha + beta + 2n < 0 is required\", GSL_EDOM);\n }\n else if (params->a + params->b <= 0.0)\n {\n GSL_ERROR(\"a + b <= 0 is not allowed\", GSL_EDOM);\n }\n else\n {\n return GSL_SUCCESS;\n }\n}\n\nstatic int\nrational_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 a1 = params->alpha + 1.0;\n const double aba1 = absum*a1;\n double ab2i = absum + 2.0;\n size_t i;\n\n /* construct the diagonal and subdiagonal elements of Jacobi matrix */\n \n diag[0] = -a1/(absum + 2.0);\n subdiag[0] = sqrt( -diag[0] * ( params->beta + 1.0 ) / ( (absum + 2.0)*(absum + 3.0) ) );\n \n for (i = 1; i < n-1; i++)\n {\n ab2i += 2.0;\n diag[i] = ( -aba1 - 2.0 * i * ( absum + i + 1.0 ) ) / ( ab2i * ( ab2i - 2.0 ) );\n subdiag[i] = sqrt( (i+1.0) * ( params->alpha + i + 1.0 ) / ( ab2i - 1.0 ) * ( params->beta + i + 1.0 ) / ( ab2i * ab2i ) * ( absum + i + 1.0 ) / ( ab2i + 1.0 ) );\n }\n \n diag[n-1] = ( -aba1 - 2.0 * (n-1.0) * ( absum + n ) ) / ( (absum + 2.0*n) * ( absum + 2.0*n - 2.0 ) );\n subdiag[n-1] = 0.0;\n \n params->zemu = gsl_sf_gamma(params->alpha + 1.0) * gsl_sf_gamma(-absum - 1.0) / gsl_sf_gamma(-params->beta);\n params->shft = params->a;\n params->slp = 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 rational_type =\n{\n rational_check,\n rational_init\n};\n\nconst gsl_integration_fixed_type *gsl_integration_fixed_rational = &rational_type;\n", "meta": {"hexsha": "b6f1960fd06de0267c5a6205888313a2fee74497", "size": 3162, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/rational.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/rational.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/rational.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.5979381443, "max_line_length": 168, "alphanum_fraction": 0.6366223909, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4548193669179813}} {"text": "/* stable/stable_integration.h\n * \n * Functions to perform numerical integration used when calculating\n * the PDF and CDF of alpha-stable distributions. Based on GSL\n * numerical quadrature methods.\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 */\n#ifndef _STABLE_INTEGRATION_H_\n#define _STABLE_INTEGRATION_H_\n\n#include \"stable.h\"\n\n#include \n#include \n#include \n#include \n\n\nint stable_integration_METHODNAME(unsigned short method, char *s);\n\nvoid\nstable_integration(StableDist *dist,double(function)(double, void*),\n double a, double b,\n double epsabs, double epsrel, unsigned short limit,\n double *result, double *abserr, unsigned short method);\n\n#endif\n", "meta": {"hexsha": "9c36bfab4ccca163b8c6486c993312f7acf525e6", "size": 1614, "ext": "h", "lang": "C", "max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable_integration.h", "max_stars_repo_name": "TantraLabs/gonum", "max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "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": "stat/distuv/libs/libstable/stable/src/stable_integration.h", "max_issues_repo_name": "TantraLabs/gonum", "max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "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": "stat/distuv/libs/libstable/stable/src/stable_integration.h", "max_forks_repo_name": "TantraLabs/gonum", "max_forks_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "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.28, "max_line_length": 74, "alphanum_fraction": 0.7162329616, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45479903989833753}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"parmt_config.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#include \n#include \n#else\n#include \n#include \n#endif\n#include \"parmt_mtsearch.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/linalg/linalg.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/signal/convolve.h\"\n\n#define LDG 8\n#define LDCG 8\n#define SIZEOF_DOUBLE sizeof(double)\n\n#ifndef MAX\n#define MAX(x,y) (((x) > (y)) ? (x) : (y))\n#endif\n#ifndef MIN\n#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n#endif\n\nenum covarianceMatrixType_enum\n{\n INVERSE_COVARIANCE_MATRIX = 0,\n EIGEN_BASIS = 1\n};\n\n// Set the Green's functions matrix\nstatic int computePadding64f(const int n);\nstatic int computePadding32f(const int n);\nstatic int setG32f(const int npts,\n const float *__restrict__ Gxx,\n const float *__restrict__ Gyy,\n const float *__restrict__ Gzz,\n const float *__restrict__ Gxy,\n const float *__restrict__ Gxz,\n const float *__restrict__ Gyz,\n float *__restrict__ G);\nstatic int setG64f(const int npts,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n double *__restrict__ G);\nstatic int setGxc64f(const int npts,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy, \n const double *__restrict__ Gzz, \n const double *__restrict__ Gxy, \n const double *__restrict__ Gxz, \n const double *__restrict__ Gyz, \n const double *__restrict__ d,\n double *__restrict__ Gxc);\n// Compute C*d\nstatic int computeCd32f(const int npts,\n const int ldc,\n const bool ldiag,\n const float *__restrict__ CeInv,\n const float *__restrict__ d,\n float *__restrict__ Cd);\nstatic int computeCd64f(const int npts,\n const int ldc,\n const bool ldiag,\n const double *__restrict__ CeInv,\n const double *__restrict__ d,\n double *__restrict__ Cd);\n// Compute C*G\nstatic int computeCG64f(const int npts,\n const int ldc,\n const bool ldiag,\n const double *__restrict__ CeInv,\n const double *__restrict__ G,\n double *__restrict__ CG);\nstatic int computeCG32f(const int npts,\n const int ldc,\n const bool ldiag,\n const float *__restrict__ CeInv,\n const float *__restrict__ G,\n float *__restrict__ CG);\n// Compute G^T C G\nstatic int computeGtCG32f(const int npts,\n const float *__restrict__ G,\n const float *__restrict__ CG,\n float *__restrict__ GtCG);\nstatic int computeGtCG64f(const int npts,\n const double *__restrict__ G,\n const double *__restrict__ CG, \n double *__restrict__ GtCG);\n// Compute L1 objective function\nstatic int performL1Search64f(const int nmt, const int ldm,\n const int npts,\n const int blockSize, const int mblock,\n const int Mrows, const int Kcols,\n const int klag,\n const bool lminLags, const bool lwantLags,\n const bool lrescale,\n const double dnorm,\n const double *__restrict__ Dmat,\n const double *__restrict__ CG,\n const double *__restrict__ Cd,\n const double *__restrict__ mts,\n int *__restrict__ lags,\n double *__restrict__ phi,\n double *__restrict__ var);\n// Compute m^T G^T G m\nstatic double computemtGTGmt64f(const double *__restrict__ m,\n const double *__restrict__ GtG);\n\n#pragma omp declare simd\nstatic float computeLeastSquaresResidual32f(const float *__restrict__ m,\n const float *__restrict__ GtCG,\n const float *__restrict__ GtCd,\n const float dtCd);\n#pragma omp declare simd\nstatic double computeLeastSquaresResidual64f(const double *__restrict__ m,\n const double *__restrict__ GtCG,\n const double *__restrict__ GtCd,\n const double dtCd);\n\n/*!\n * @brief Computes the likelihood function\n */\n/*\nint parmt_mtsearch64f( )\n{\n \n return 0;\n}\n*/\n\n\nint parmt_mtSearchKL64f(const int ldm, const int nlags, const int nmt, \n const int npts, const int ldz, \n const int rank,\n const double sigma,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n const double *__restrict__ sqrtEig,\n const double *__restrict__ Z,\n const double *__restrict__ mts, \n const double *__restrict__ d,\n double *__restrict__ phi)\n{\n double *G, *V, *phiCerf, *phiWork, sigma2, xdiv, xdiv1, xdiv2, xdiv3, xdiv4;\n int i, ierr, ir, ldv;\n //const double sqrt2 = sqrt(2.0);\n const double sqrt2pi = sqrt(2.0*M_PI);\n //------------------------------------------------------------------------//\n ldv = ldz + (64 - ldz%64)/SIZEOF_DOUBLE;\n V = memory_calloc64f(ldv*npts);\n G = memory_calloc64f(LDG*npts);\n sigma2 = sigma*sigma;\n phiWork = memory_calloc64f(nmt);\n phiCerf = memory_calloc64f(nmt);\n ierr = setG64f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, G);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set G\\n\", __func__);\n return -1;\n }\n ierr = array_set64f_work(nmt, 1.0, phi);\n if (nlags == 0)\n {\n // Extract \n for (ir=0; ir 0){ltrunc = true;}\n if (ltrunc)\n {\n if (maxlag >= npts)\n {\n printf(\"%s: Error maxlag can't exceed npts\\n\", __func__);\n return -1;\n }\n }\n // Set the data\n ierr = setG64f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, G);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set G\\n\", __func__);\n return -1;\n }\n ierr = setGxc64f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, d, Gxc);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set Gxc\\n\", __func__);\n return -1;\n }\n // Compute G^T G\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,\n 6, 6, npts, 1.0, G, LDG,\n G, LDG, 0.0, GtG, 6);\n for (i=0; i<8; i++){m8[i] = zero;}\n memory_free64f(&G);\n // Compute the normalization\n dNorm = cblas_dnrm2(npts, d, 1);\n // Cross-correlate the data\n/*\n #pragma omp parallel for \\\n firstprivate(csum, M, R) \\\n private (i, ic, idx, imt, jdx, jmt, Ncols) \\\n shared (d, CG, Dmat, mts, phi, Mrows, mblock) \\\n default (none) reduction(+:var)\n*/\n for (jmt=0; jmt 0)\n {\n for (i=k; i rnorm[ic])\n {\n phi[imt] = rnorm[ic];\n lags[imt] = k;\n }\n }\n }\n else\n {\n for (ic=0; ic= npts\\n\", __func__);\n return -1;\n }\n if (nlags > 0 && nlags > npts)\n {\n printf(\"%s: Error nlags can't exceed npts\\n\", __func__);\n return -1;\n }\n // Set space and make G matrix\n G = memory_calloc64f(LDG*npts);\n ierr = setG64f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, G);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set G\\n\", __func__);\n return -1;\n }\n // straight application of Ce^{-1}\n if (nlags == 0)\n {\n // Diagonal\n if (ldiag)\n {\n ierr = parmt_mtSearch_mahalanobis64f(ldm, nmt, npts,\n ldc, true,\n G, CeInv,\n mts, d, phi);\n }\n // General matrix\n else\n {\n ierr = parmt_mtSearch_mahalanobis64f(ldm, nmt, npts,\n ldc, false,\n G, CeInv,\n mts, d, phi);\n }\n }\n else\n {\n // Diagonal weighting matrix\n if (ldiag)\n {\n ierr = parmt_mtSearch_shiftedMahalanobis64f(nlags, nmt, \n npts, ldc, \n true,\n G, CeInv,\n mts, d, phi);\n }\n else\n {\n ierr = parmt_mtSearch_shiftedMahalanobis64f(nlags, nmt, \n npts, ldc, \n false,\n G, CeInv,\n mts, d, phi);\n }\n }\n if (ierr != 0)\n {\n printf(\"%s: Error computing search\\n\", __func__);\n }\n // Free memory\n memory_free64f(&G);\n return ierr;\n}\n//============================================================================//\nint parmt_mtSearch32f(const int ldm, const int nlags, const int nmt,\n const int npts, const int ldc,\n const bool ldiag,\n const float *__restrict__ Gxx,\n const float *__restrict__ Gyy, \n const float *__restrict__ Gzz,\n const float *__restrict__ Gxy,\n const float *__restrict__ Gxz,\n const float *__restrict__ Gyz,\n const float *__restrict__ CeInv,\n const float *__restrict__ mts,\n const float *__restrict__ d,\n float *__restrict__ phi)\n{\n float *G;\n int ierr;\n if (nmt < 1 || npts < 1 || mts == NULL || Gxx == NULL || Gyy == NULL ||\n Gzz == NULL || Gxy == NULL || Gxz == NULL || Gxy == NULL ||\n CeInv == NULL || d == NULL || phi == NULL)\n {\n if (nmt < 1){printf(\"%s: No moment tensors\\n\", __func__);}\n if (npts < 1){printf(\"%s: No data points\\n\", __func__);}\n if (Gxx == NULL){printf(\"%s: Gxx is NULL\\n\", __func__);}\n if (Gyy == NULL){printf(\"%s: Gyy is NULL\\n\", __func__);}\n if (Gzz == NULL){printf(\"%s: Gzz is NULL\\n\", __func__);}\n if (Gxy == NULL){printf(\"%s: Gxy is NULL\\n\", __func__);}\n if (Gxz == NULL){printf(\"%s: Gxz is NULL\\n\", __func__);}\n if (CeInv == NULL){printf(\"%s: CeInv is NULL\\n\", __func__);}\n if (mts == NULL){printf(\"%s: mts is NULL\\n\", __func__);}\n if (d == NULL){printf(\"%s: d is NULL\\n\", __func__);}\n if (phi == NULL){printf(\"%s: phi is NULL\\n\", __func__);}\n return -1;\n }\n if (!ldiag && ldc < npts)\n {\n printf(\"%s: Error ldc must be >= npts\\n\", __func__);\n return -1;\n }\n if (nlags > 0 && nlags > npts)\n {\n printf(\"%s: Error nlags can't exceed npts\\n\", __func__);\n return -1;\n }\n // Set space and make G matrix\n G = memory_calloc32f(LDG*npts);\n ierr = setG32f(npts, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz, G);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set G\\n\", __func__);\n return -1;\n }\n // straight application of Ce^{-1}\n if (nlags == 0)\n {\n if (ldiag)\n {\n ierr = parmt_mtSearch_mahalanobis32f(ldm, nmt, npts,\n ldc, true,\n G, CeInv,\n mts, d, phi);\n }\n else\n {\n ierr = parmt_mtSearch_mahalanobis32f(ldm, nmt, npts,\n ldc, false,\n G, CeInv,\n mts, d, phi);\n }\n }\n // shifting the data to the green's functions\n else\n {\n // Diagonal weighting matrix\n if (ldiag)\n {\n ierr = parmt_mtSearch_shiftedMahalanobis32f(nlags, nmt,\n npts, ldc,\n true,\n G, CeInv,\n mts, d, phi);\n }\n // Full inverse covariance matrix\n else\n {\n ierr = parmt_mtSearch_shiftedMahalanobis32f(nlags, nmt,\n npts, ldc,\n false,\n G, CeInv,\n mts, d, phi);\n }\n }\n if (ierr != 0)\n {\n printf(\"%s: Error computing search\\n\", __func__);\n }\n // Free memory\n memory_free32f(&G);\n return ierr;\n}\n//============================================================================//\nint parmt_mtSearch_mahalanobis64f(const int ldm, const int nmt, const int npts,\n const int ldc, const bool ldiag,\n const double *__restrict__ G,\n const double *__restrict__ CeInv,\n const double *__restrict__ mts,\n const double *__restrict__ d,\n double *__restrict__ phi)\n{\n double *Cd, *CG;\n double GtCG[36], GtCd[6], m[6] __attribute__ ((aligned (64)));\n double dtCd __attribute__ ((aligned (64))) = 0.0;\n int imt, M;\n //------------------------------------------------------------------------// \n //\n // Set space\n CG = memory_calloc64f(LDCG*npts);\n Cd = memory_calloc64f(npts);\n // Compute C G\n computeCG64f(npts, ldc, ldiag, CeInv, G, CG);\n // Compute G^T C G\n computeGtCG64f(npts, G, CG, GtCG);\n // Compute C d\n computeCd64f(npts, ldc, ldiag, CeInv, d, Cd);\n // Compute d^T C G = (G^T C d)^T\n M = npts;\n cblas_dgemv(CblasRowMajor, CblasTrans, M, 6, 1.0, CG, LDCG,\n d, 1, 0.0, GtCd, 1);\n // Compute d^T C d\n dtCd = cblas_ddot(npts, d, 1, Cd, 1);\n#ifdef __INTEL_COMPILER\n __assume_aligned(mts, 64);\n __assume_aligned(phi, 64);\n #pragma omp parallel for simd \\\n firstprivate (GtCG, GtCd, dtCd) \\\n private(m) shared(mts, phi) \\\n default(none)\n#else\n/*\n #pragma omp parallel for simd \\\n firstprivate (GtCG, GtCd, dtCd) \\\n private(m) shared(mts, phi) \\\n default(none) aligned(phi, mts: 64)\n*/\n#endif\n for (imt=0; imt 0)\n {\n ncopy = npts - k;\n for (i=ncopy; i 0)\n {\n ncopy = npts - k;\n for (i=ncopy; i phi[imt])\n {\n phi[imt] = robj;\n lags[imt] = klag;\n }\n }\n }\n }\n } // Loop on moment tensor block\n #pragma omp critical\n {\n for (i=0; i= npts.\n * @param[in] CeInv inverse of data error (covariance) matrix. if\n * ldiag is true then this is diagonal of length [nobs].\n * if false then it is a symmetric [nobs x ldc] matrix\n * in row major format where ldc >= nobs.\n * @param[in] d data vector [npts]\n *\n * @param[out] Cd multiplication of C*d [npts]\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nstatic int computeCd32f(const int npts,\n const int ldc,\n const bool ldiag,\n const float *__restrict__ CeInv,\n const float *__restrict__ d,\n float *__restrict__ Cd)\n{\n int i, M, N;\n // Compute C d\n if (CeInv != NULL)\n {\n if (ldiag)\n {\n #pragma omp simd aligned(Cd, CeInv, d: 64)\n for (i=0; i= npts.\n * @param[in] CeInv inverse of data error (covariance) matrix. if\n * ldiag is true then this is diagonal of length [nobs].\n * if false then it is a symmetric [nobs x ldc] matrix\n * in row major format where ldc >= nobs.\n * @param[in] d data vector [npts]\n *\n * @param[out] Cd multiplication of C*d [npts]\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nstatic int computeCd64f(const int npts,\n const int ldc,\n const bool ldiag,\n const double *__restrict__ CeInv,\n const double *__restrict__ d,\n double *__restrict__ Cd)\n{\n int i, M, N;\n // Compute C d\n if (CeInv != NULL)\n {\n if (ldiag)\n {\n #pragma omp simd aligned(Cd, CeInv, d: 64)\n for (i=0; i= npts.\n * @param[in] ldiag if true then CeInv is diagonal. if false then\n * CeInv is a general [npts x npts] matrix.\n * @param[in] CeInv inverse of data error (covariance) matrix. if\n * ldiag is true then this is diagonal of length [nobs].\n * if false then it is a symmetric [nobs x ldc] matrix\n * in row major format where ldc >= nobs.\n * @param[in] G Green's functions matrix in row major order [npts x LDG]\n *\n * @param[out] CG row major C*G matrix [npts x LDCG]\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nstatic int computeCG32f(const int npts,\n const int ldc,\n const bool ldiag,\n const float *__restrict__ CeInv,\n const float *__restrict__ G,\n float *__restrict__ CG)\n{\n int i, j, jndx, K, kndx, M;\n const int N = 6; // Number of columns of G \n if (CeInv != NULL)\n {\n if (ldiag)\n {\n // Set C G\n for (i=0; i= npts.\n * @param[in] ldiag if true then CeInv is diagonal. if false then\n * CeInv is a general [npts x npts] matrix.\n * @param[in] CeInv inverse of data error (covariance) matrix. if\n * ldiag is true then this is diagonal of length [nobs].\n * if false then it is a symmetric [nobs x ldc] matrix\n * in row major format where ldc >= nobs.\n * @param[in] G Green's functions matrix in row major order [npts x LDG]\n *\n * @param[out] CG row major C*G matrix [npts x LDCG]\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nstatic int computeCG64f(const int npts,\n const int ldc,\n const bool ldiag,\n const double *__restrict__ CeInv,\n const double *__restrict__ G,\n double *__restrict__ CG)\n{\n int i, j, jndx, K, kndx, M;\n const int N = 6; // Number of columns of G\n if (CeInv != NULL)\n {\n if (ldiag)\n {\n // Set C G\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 \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n\n#define SQR(x) ((x) * (x))\n#define ReLU(x) ((x) > 0 ? (x) : 0)\n\nextern void VMatrixECM(gsl_matrix_float *,float *,int,int,VImage);\nextern void VMatrixProjection(gsl_matrix_float *X,float *ev,int,int seed);\nextern VImage VoxelMap(VAttrList list,VImage mask,size_t nvox);\nextern size_t NumVoxels(VImage);\nextern gsl_matrix_float *ReadDataECM(VAttrList,VImage,VImage,VShort,VShort,int,size_t);\nextern VImage WriteOutput(VAttrList,VImage,float *,size_t);\nextern int Irreducible(gsl_matrix_float *X,int type);\n\n\nvoid NormVec(float *x,size_t nvox)\n{\n size_t i;\n float sum=0;\n sum = 0;\n for (i=0; isize2;\n size_t i,j,n=nt/2;\n for (i=0; isize1; i++) {\n for (j=n; jsize1;\n size_t nt = X->size2;\n float scale = 1.0/(float)nt;\n \n fprintf(stderr,\" power iteration...\\n\");\n gsl_vector_float *y = gsl_vector_float_calloc(nvox);\n gsl_vector_float *z = gsl_vector_float_calloc(nt);\n\n Irreducible(X,type); /* check if corr matrix is irreducible */\n \n NormVec(ev,nvox);\n for (i=0; idata[i] = ev[i];\n\n\n /* power iterations */\n for (iter=0; iterdata[i] += vsum;\n } \n\n /* normalize */\n NormVec(y->data,nvox);\n \n /* check convergence */\n d = 0;\n for (i=0; idata[i]);\n ev[i] = y->data[i];\n }\n fprintf(stderr,\" %5d %.6f\\n\",(int)iter,d);\n\n if (iter > 2 && d < 1.0e-6) break;\n }\n gsl_vector_float_free(y);\n gsl_vector_float_free(z);\n}\n\n\n\nfloat *VECM(gsl_matrix_float *X,int type,VBoolean project,int seed,int maxiter,VImage map)\n{\n size_t i,j;\n size_t nvox = X->size1;\n size_t nt = X->size2;\n if (type == 0 || type == 7) nt /= 2;\n\n \n /* ini eigenvector */\n float u=0;\n float *eigvec = (float *) VCalloc(nvox,sizeof(float));\n for (i=0; isize1; i++) {\n\tfor (j=0; jsize1; i++) {\n\tfor (j=0; j 8) VError(\" unknown metric\");\n if (type < 6) fprintf(stderr,\" Correlation metric %d: %s\\n\",type,TYPDict[type].keyword);\n if (project && (type < 2 || type == 7))\n VError(\" matrix projection not needed for metric %d (%s)\\n\",type,TYPDict[type].keyword);\n \n \n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n if (type > 3 || project == TRUE) fprintf(stderr,\"using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n\n \n /* read functional data */\n VAttrList list = VReadAttrListZ(in_file,in_filename,0L,TRUE,FALSE);\n if (list == NULL) VError(\" error reading input file %s\",in_file);\n VAttrList geolist = VGetGeoInfo(list);\n\n\n /* read mask */\n VAttrList listm = VReadAttrList(mask_filename,0L,TRUE,FALSE);\n VImage mask = VReadImage(listm);\n if (mask == NULL) VError(\" no mask found\");\n size_t nvox = NumVoxels(mask);\n\n \n /* voxel map */\n VImage map = VoxelMap(list,mask,nvox);\n\n\n /* read data into X */\n gsl_matrix_float *X = ReadDataECM(list,mask,map,first,length,type,nvox);\n\n\n\n /* main process */\n float *eigvec = VECM(X,(int)type,project,(VLong)seed,(int)maxiter,map);\n\n \n \n /* create output image */\n VImage dest = WriteOutput(list,map,eigvec,nvox);\n VSetAttr(VImageAttrList(dest),\"name\",NULL,VStringRepn,\"ECM\");\n VAttrList out_list = VCreateAttrList();\n VAppendAttr(out_list,\"image\",NULL,VImageRepn,dest);\n \n\n /* update geoinfo, 4D to 3D */\n if (geolist != NULL) {\n double *D = VGetGeoDim(geolist,NULL);\n D[0] = 3; /* 3D */\n D[4] = 1; /* just one timestep */\n VSetGeoDim(geolist,D);\n VSetGeoInfo(geolist,out_list);\n }\n \n /* write to disk */\n VHistory(VNumber(options),options,prg_name,&list,&out_list);\n if (! VWriteFile (out_file, out_list)) exit (1);\n fprintf (stderr, \"%s: done.\\n\", argv[0]);\n return 0;\n}\n", "meta": {"hexsha": "86de44666a70c2201c008dc315b643c76db38c04", "size": 7951, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nets/vecm/vecm.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/nets/vecm/vecm.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/nets/vecm/vecm.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": 26.5919732441, "max_line_length": 125, "alphanum_fraction": 0.6235693623, "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.45460662942135305}} {"text": "/* These functions compute linear preprocessing for\nthe UE using LAPACKE and CBLAS modules of\nLAPACK libraries.\nMMSE and MMSE whitening filters are available.\nFunctions are using RowMajor storage of the\nmatrices, like in conventional C. Traditional\nFortran functions of LAPACK employ ColumnMajor\ndata storage. */\n\n#include\n#include\n#include\n#include \n#include \n#include \n#include \n#if RHEL_RELEASE_CODE >= 1796\n#include \n#include \n#else\n#include \n#include \n#endif\n//#define DEBUG_PREPROC\n\n\nvoid transpose (int N, float complex *A, float complex *Result)\n{\n // COnputes C := alpha*op(A)*op(B) + beta*C,\n enum CBLAS_TRANSPOSE transa = CblasTrans;\n enum CBLAS_TRANSPOSE transb = CblasNoTrans;\n int rows_opA = N; // number of rows in op(A) and in C\n int col_opB = N; //number of columns of op(B) and in C\n int col_opA = N; //number of columns in op(A) and rows in op(B)\n int col_B; //number of columns in B\n float complex alpha = 1.0+I*0;\n int lda = rows_opA;\n float complex beta = 0.0+I*0;\n int ldc = rows_opA;\n int i;\n float complex* B;\n\n int ldb = col_opB;\n\n if (transb == CblasNoTrans) {\n B = (float complex*)calloc(ldb*col_opB,sizeof(float complex));\n col_B= col_opB;\n }\n else {\n B = (float complex*)calloc(ldb*col_opA, sizeof(float complex));\n col_B = col_opA;\n }\n float complex* C = (float complex*)malloc(ldc*col_opB*sizeof(float complex));\n\n for (i=0; i>2)*sizeof(float complex));\n float complex *H1_re = malloc(n_rx*(n_tx>>2)*sizeof(float complex));\n float complex *R_corr_col_n_0_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *R_corr_col_n_1_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *U_0_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *U_1_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *U_0_herm_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *U_1_herm_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *D_0_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *D_1_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *W_Wh_0_re = malloc(n_rx*n_tx*sizeof(float complex));\n float complex *W_Wh_1_re = malloc(n_rx*n_tx*sizeof(float complex));\n\n for (aatx=0; aatx>2), H1_re, sigma2, R_corr_col_n_0_re);\n HH_herm_plus_sigma2I(n_rx, (n_tx>>2), H0_re, sigma2, R_corr_col_n_1_re);\n\n eigen_vectors_values(n_rx, R_corr_col_n_0_re, U_0_re, D_0_re);\n eigen_vectors_values(n_rx, R_corr_col_n_1_re, U_1_re, D_1_re);\n\n transpose (n_rx, U_0_re, U_0_herm_re);\n transpose (n_rx, U_1_re, U_1_herm_re);\n\n sigma = (float)(sqrt((double)(sigma2)));\n\n /*The inverse of a diagonal matrix is obtained by replacing each element in the diagonal with its reciprocal.\n A square root of a diagonal matrix is given by the diagonal matrix, whose diagonal entries are just the square\n roots of the original matrix.*/\n\n\n D_0_re_inv_sqrt[0] = sqrt_float(1/D_0_re_inv[0]);\n D_0_re_inv_sqrt[5] = sqrt_float(1/D_0_re_inv[5]);\n D_0_re_inv_sqrt[10] = sqrt_float(1/D_0_re_inv[10]);\n D_0_re_inv_sqrt[15] = sqrt_float(1/D_0_re_inv[15]);\n\n D_1_re_inv[0] = sqrt_float(1/D_1_re_inv[0]);\n D_1_re_inv[5] = sqrt_float(1/D_1_re_inv[5]);\n D_1_re_inv[10] = sqrt_float(1/D_1_re_inv[10]);\n D_1_re_inv[15] = sqrt_float(1/D_1_re_inv[15]);\n\n now only to multiply\n\n free(H0);\n free(H1);\n free(R_corr_col_n_0);\n free(R_corr_col_n_1);\n}\n#endif\n\nfloat sqrt_float(float x, float sqrt_x)\n{\n sqrt_x = (float)(sqrt((double)(x)));\n return sqrt_x;\n}\n", "meta": {"hexsha": "7d063e326effc919180e5ebe12c02fa19d85b6a2", "size": 11913, "ext": "c", "lang": "C", "max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_stars_repo_name": "shadansari/onos-cu-cp", "max_stars_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T17:03:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-24T07:04:29.000Z", "max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_issues_repo_name": "shadansari/onos-cu-cp", "max_issues_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-17T05:01:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T14:23:54.000Z", "max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c", "max_forks_repo_name": "shadansari/onos-cu-cp", "max_forks_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-12-27T00:55:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:13:45.000Z", "avg_line_length": 31.768, "max_line_length": 146, "alphanum_fraction": 0.6617140938, "num_tokens": 4176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.45453025271249753}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"fftlog.h\"\n\n#include \"ccl.h\"\n#include \"ccl_params.h\"\n\n/*--------ROUTINE: taper_cl ------\nTASK:n Apply cosine tapering to Cls to reduce aliasing\nINPUT: number of ell bins for Cl, ell vector, C_ell vector, limits for tapering\n e.g., ell_limits=[low_ell_limit_lower,low_ell_limit_upper,high_ell_limit_lower,high_ell_limit_upper]\n*/\nstatic int taper_cl(int n_ell,double *ell,double *cl, double *ell_limits)\n{\n\n for(int i=0;iell_limits[3]) {\n cl[i]=0;//ell outside desirable range\n continue;\n }\n if(ell[i]>=ell_limits[1] && ell[i]<=ell_limits[2])\n continue;//ell within good ell range\n \n if(ell[i]ell_limits[2])//tapering high ell\n cl[i]*=cos((ell[i]-ell_limits[2])/(ell_limits[3]-ell_limits[2])*M_PI/2.);\n }\n\n return 0;\n}\n\n/*--------ROUTINE: ccl_tracer_corr_fftlog ------\nTASK: For a given tracer, get the correlation function\n Following function takes a function to calculate angular cl as well.\n By default above function will call it using ccl_angular_cl\nINPUT: type of tracer, number of theta values to evaluate = NL, theta vector\n */\nstatic void ccl_tracer_corr_fftlog(ccl_cosmology *cosmo,\n\t\t\t\t int n_ell,double *ell,double *cls,\n\t\t\t\t int n_theta,double *theta,double *wtheta,\n\t\t\t\t int corr_type,int do_taper_cl,double *taper_cl_limits,\n\t\t\t\t int *status)\n{\n int i;\n double *l_arr,*cl_arr,*th_arr,*wth_arr;\n\n l_arr=ccl_log_spacing(ccl_splines->ELL_MIN_CORR,ccl_splines->ELL_MAX_CORR,ccl_splines->N_ELL_CORR);\n if(l_arr==NULL) {\n *status=CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n cl_arr=malloc(ccl_splines->N_ELL_CORR*sizeof(double));\n if(cl_arr==NULL) {\n free(l_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n\n //Interpolate input Cl into array needed for FFTLog\n SplPar *cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);\n if(cl_spl==NULL) {\n free(l_arr);\n free(cl_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n\n double cl_tilt,l_edge,cl_edge;\n l_edge=ell[n_ell-1];\n if((cls[n_ell-1]*cls[n_ell-2]<0) || (cls[n_ell-2]==0)) {\n cl_tilt=0;\n cl_edge=0;\n }\n else {\n cl_tilt=log(cls[n_ell-1]/cls[n_ell-2])/log(ell[n_ell-1]/ell[n_ell-2]);\n cl_edge=cls[n_ell-1];\n }\n for(i=0;iN_ELL_CORR;i++) {\n if(l_arr[i]>=l_edge)\n cl_arr[i]=cl_edge*pow(l_arr[i]/l_edge,cl_tilt);\n else\n cl_arr[i]=ccl_spline_eval(l_arr[i],cl_spl);\n }\n ccl_spline_free(cl_spl);\n\n if (do_taper_cl)\n taper_cl(ccl_splines->N_ELL_CORR,l_arr,cl_arr,taper_cl_limits);\n\n th_arr=malloc(sizeof(double)*ccl_splines->N_ELL_CORR);\n if(th_arr==NULL) {\n free(l_arr);\n free(cl_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n wth_arr=(double *)malloc(sizeof(double)*ccl_splines->N_ELL_CORR);\n if(wth_arr==NULL) {\n free(l_arr); free(cl_arr); free(th_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_fftlog ran out of memory\\n\");\n return;\n }\n\n for(i=0;iN_ELL_CORR;i++)\n th_arr[i]=0;\n //Although set here to 0, theta is modified by FFTlog to obtain the correlation at ~1/l\n\n int i_bessel=0;\n if(corr_type==CCL_CORR_GG) i_bessel=0;\n if(corr_type==CCL_CORR_GL) i_bessel=2;\n if(corr_type==CCL_CORR_LP) i_bessel=0;\n if(corr_type==CCL_CORR_LM) i_bessel=4;\n fftlog_ComputeXi2D(i_bessel,ccl_splines->N_ELL_CORR,l_arr,cl_arr,th_arr,wth_arr);\n\n // Interpolate to output values of theta\n SplPar *wth_spl=ccl_spline_init(ccl_splines->N_ELL_CORR,th_arr,wth_arr,wth_arr[0],0);\n for(i=0;ith;\n\n if(lell0) {\n if(p->extrapol_0)\n cl=p->cl0*pow(l/p->ell0,p->tilt0);\n else\n cl=0;\n }\n else if(l>p->ellf) {\n if(p->extrapol_f)\n cl=p->clf*pow(l/p->ellf,p->tiltf);\n else\n cl=0;\n }\n else\n cl=ccl_spline_eval(l,p->cl_spl);\n\n jbes=gsl_sf_bessel_Jn(p->i_bessel,x);\n\n return l*jbes*cl;\n}\n\nstatic void ccl_tracer_corr_bessel(ccl_cosmology *cosmo,\n\t\t\t\t int n_ell,double *ell,double *cls,\n\t\t\t\t int n_theta,double *theta,double *wtheta,\n\t\t\t\t int corr_type,int *status)\n{\n corr_int_par *cp=malloc(sizeof(corr_int_par));\n if(cp==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\\n\");\n return;\n }\n\n cp->nell=n_ell;\n cp->ell0=ell[0];\n cp->ellf=ell[n_ell-1];\n cp->cl0=cls[0];\n cp->clf=cls[n_ell-1];\n cp->cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);\n if(cp->cl_spl==NULL) {\n free(cp);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_bessel ran out of memory\\n\");\n return;\n }\n switch(corr_type) {\n case CCL_CORR_GG :\n cp->i_bessel=0;\n break;\n case CCL_CORR_GL :\n cp->i_bessel=2;\n break;\n case CCL_CORR_LP :\n cp->i_bessel=0;\n break;\n case CCL_CORR_LM :\n cp->i_bessel=4;\n break;\n }\n\n if(cls[0]*cls[1]<=0)\n cp->extrapol_0=0;\n else {\n cp->extrapol_0=1;\n cp->tilt0=log10(cls[1]/cls[0])/log10(ell[1]/ell[0]);\n }\n\n if(cls[n_ell-2]*cls[n_ell-1]<=0)\n cp->extrapol_f=0;\n else {\n cp->extrapol_f=1;\n cp->tiltf=log10(cls[n_ell-1]/cls[n_ell-2])/log10(ell[n_ell-1]/ell[n_ell-2]);\n }\n\n int ith, gslstatus;\n double result,eresult;\n gsl_function F;\n gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);\n for(ith=0;ithth=theta[ith]*M_PI/180;\n F.function=&corr_bessel_integrand;\n F.params=cp;\n //TODO: Split into intervals between first bessel zeros before integrating\n //This will help both speed and accuracy of the integral.\n gslstatus = gsl_integration_qag(&F, 0, ccl_splines->ELL_MAX_CORR, 0,\n ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,\n ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,\n w, &result, &eresult);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_correlation.c: ccl_tracer_corr_bessel():\");\n *status |= gslstatus;\n }\n wtheta[ith]=result/(2*M_PI);\n }\n gsl_integration_workspace_free(w);\n ccl_spline_free(cp->cl_spl);\n free(cp);\n}\n\n\n/*--------ROUTINE: ccl_compute_legendre_polynomial ------\nTASK: Compute input factor for ccl_tracer_corr_legendre\nINPUT: tracer 1, tracer 2, i_bessel, theta array, n_theta, L_max, output Pl_theta\n */\nstatic void ccl_compute_legendre_polynomial(int corr_type,double theta,int ell_max,double *Pl_theta)\n{\n int i,j;\n double k=0;\n double cth=cos(theta*M_PI/180);\n \n //Initialize Pl_theta\n for (j=0;j<=ell_max;j++)\n Pl_theta[j]=0.;\n\n if(corr_type==CCL_CORR_GG) {\n gsl_sf_legendre_Pl_array(ell_max,cth,Pl_theta);\n for (j=0;j<=ell_max;j++)\n Pl_theta[j]*=(2*j+1);\n }\n else if(corr_type==CCL_CORR_GL) {\n for (j=2;j<=ell_max;j++) {//https://arxiv.org/pdf/1007.4809.pdf\n Pl_theta[j]=gsl_sf_legendre_Plm(j,2,cth);\n Pl_theta[j]*=(2*j+1.)/((j+0.)*(j+1.));\n }\n }\n}\n\n/*--------ROUTINE: ccl_tracer_corr_legendre ------\nTASK: Compute correlation function via Legendre polynomials\nINPUT: cosmology, number of theta bins, theta array, tracer 1, tracer 2, i_bessel, boolean\n for tapering, vector of tapering limits, correlation vector, angular_cl function.\n */\nstatic void ccl_tracer_corr_legendre(ccl_cosmology *cosmo,\n\t\t\t\t int n_ell,double *ell,double *cls,\n\t\t\t\t int n_theta,double *theta,double *wtheta,\n\t\t\t\t int corr_type,int do_taper_cl,double *taper_cl_limits,\n\t\t\t\t int *status)\n{\n int i;\n double *l_arr,*cl_arr,*Pl_theta;\n SplPar *cl_spl;\n\n if(corr_type==CCL_CORR_LM || corr_type==CCL_CORR_LP){\n *status=CCL_ERROR_NOT_IMPLEMENTED;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: CCL does not support full-sky xi+- calcuations.\\nhttps://arxiv.org/abs/1702.05301 indicates flat-sky to be sufficient.\\n\");\n }\n \n if(*status==0) {\n l_arr=malloc(((int)(ccl_splines->ELL_MAX_CORR)+1)*sizeof(double));\n if(l_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n \n if(*status==0) {\n cl_arr=malloc(((int)(ccl_splines->ELL_MAX_CORR)+1)*sizeof(double));\n if(cl_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n\n if(*status==0) {\n //Interpolate input Cl into \n cl_spl=ccl_spline_init(n_ell,ell,cls,cls[0],0);\n if(cl_spl==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n\n if(*status==0) {\n double cl_tilt,l_edge,cl_edge;\n l_edge=ell[n_ell-1];\n if((cls[n_ell-1]*cls[n_ell-2]<0) || (cls[n_ell-2]==0)) {\n cl_tilt=0;\n cl_edge=0;\n }\n else {\n cl_tilt=log(cls[n_ell-1]/cls[n_ell-2])/log(ell[n_ell-1]/ell[n_ell-2]);\n cl_edge=cls[n_ell-1];\n }\n for(i=0;i<=(int)(ccl_splines->ELL_MAX_CORR);i++) {\n double l=(double)i;\n l_arr[i]=l;\n if(l>=l_edge)\n\tcl_arr[i]=cl_edge*pow(l/l_edge,cl_tilt);\n else\n\tcl_arr[i]=ccl_spline_eval(l,cl_spl);\n }\n ccl_spline_free(cl_spl);\n\n if (do_taper_cl)\n *status=taper_cl((int)(ccl_splines->ELL_MAX_CORR)+1,l_arr,cl_arr,taper_cl_limits);\n }\n\n if(*status==0) {\n Pl_theta=malloc(sizeof(double)*((int)(ccl_splines->ELL_MAX_CORR)+1));\n if(Pl_theta==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_tracer_corr_legendre ran out of memory\\n\");\n }\n }\n \n if(*status==0) {\n for (int i=0;iELL_MAX_CORR),Pl_theta);\n for(int i_L=1;i_L<(int)(ccl_splines->ELL_MAX_CORR);i_L+=1)\n\twtheta[i]+=cl_arr[i_L]*Pl_theta[i_L];\n wtheta[i]/=(M_PI*4);\n }\n }\n\n free(Pl_theta);\n free(l_arr);\n free(cl_arr);\n}\n\n/*--------ROUTINE: ccl_tracer_corr ------\nTASK: For a given tracer, get the correlation function. Do so by running\n ccl_angular_cls. If you already have Cls calculated, go to the next\n function to pass them directly.\nINPUT: cosmology, number of theta values to evaluate = NL, theta vector,\n tracer 1, tracer 2, i_bessel, key for tapering, limits of tapering\n correlation function.\n */\nvoid ccl_correlation(ccl_cosmology *cosmo,\n\t\t int n_ell,double *ell,double *cls,\n\t\t int n_theta,double *theta,double *wtheta,\n\t\t int corr_type,int do_taper_cl,double *taper_cl_limits,int flag_method,\n\t\t int *status)\n{\n switch(flag_method) {\n case CCL_CORR_FFTLOG :\n ccl_tracer_corr_fftlog(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,\n\t\t\t do_taper_cl,taper_cl_limits,status);\n break;\n case CCL_CORR_LGNDRE :\n ccl_tracer_corr_legendre(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,\n\t\t\t do_taper_cl,taper_cl_limits,status);\n break;\n case CCL_CORR_BESSEL :\n ccl_tracer_corr_bessel(cosmo,n_ell,ell,cls,n_theta,theta,wtheta,corr_type,status);\n break;\n default :\n *status=CCL_ERROR_INCONSISTENT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation. Unknown algorithm\\n\");\n }\n\n ccl_check_status(cosmo,status);\n}\n\n/*--------ROUTINE: ccl_correlation_3d ------\nTASK: Calculate the 3d-correlation function. Do so by using FFTLog. \n\nINPUT: cosmology, scale factor a,\n number of r values, r values, \n key for tapering, limits of tapering\n\nCorrelation function result will be in array xi\n */\n\nvoid ccl_correlation_3d(ccl_cosmology *cosmo, double a,\n\t\t\tint n_r,double *r,double *xi,\n\t\t\tint do_taper_pk,double *taper_pk_limits,\n\t\t\tint *status)\n{\n int i,N_ARR;\n double *k_arr,*pk_arr,*r_arr,*xi_arr;\n\n //number of data points for k and pk array\n N_ARR=(int)(ccl_splines->N_K_3DCOR*log10(ccl_splines->K_MAX/ccl_splines->K_MIN)); \n\n k_arr=ccl_log_spacing(ccl_splines->K_MIN,ccl_splines->K_MAX,N_ARR);\n if(k_arr==NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation_3d ran out of memory\\n\");\n return;\n }\n\n pk_arr=malloc(N_ARR*sizeof(double));\n if(pk_arr==NULL) {\n free(k_arr);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_correlation.c: ccl_correlation_3d ran out of memory\\n\");\n return;\n } \n\n for (i=0; i\n#include \n#include \n#include \n\n/**********************************\n * Pseudo-random number generator *\n **********************************/\n\nstatic uint64_t mat_rng[2] = { 11ULL, 1181783497276652981ULL };\n\nstatic inline uint64_t xorshift128plus(uint64_t s[2])\n{\n\tuint64_t x, y;\n\tx = s[0], y = s[1];\n\ts[0] = y;\n\tx ^= x << 23;\n\ts[1] = x ^ y ^ (x >> 17) ^ (y >> 26);\n\ty += s[1];\n\treturn y;\n}\n\ndouble mat_drand(void)\n{\n\treturn (xorshift128plus(mat_rng)>>11) * (1.0/9007199254740992.0);\n}\n\n/*******************************************\n * Helper routines for matrix manipulation *\n *******************************************/\n\nfloat **mat_init(int n_rows, int n_cols)\n{\n\tfloat **m;\n\tint i;\n\tm = (float**)malloc(n_rows * sizeof(float*));\n\tm[0] = (float*)calloc(n_rows * n_cols, sizeof(float));\n\tfor (i = 1; i < n_rows; ++i)\n\t\tm[i] = m[i-1] + n_cols;\n\treturn m;\n}\n\nvoid mat_destroy(float **m)\n{\n\tfree(m[0]); free(m);\n}\n\nfloat **mat_gen_random(int n_rows, int n_cols)\n{\n\tfloat **m;\n\tint i, j;\n\tm = mat_init(n_rows, n_cols);\n\tfor (i = 0; i < n_rows; ++i)\n\t\tfor (j = 0; j < n_cols; ++j)\n\t\t\tm[i][j] = mat_drand();\n\treturn m;\n}\n\nfloat **mat_transpose(int n_rows, int n_cols, float *const* a)\n{\n\tint i, j;\n\tfloat **m;\n\tm = mat_init(n_cols, n_rows);\n\tfor (i = 0; i < n_rows; ++i)\n\t\tfor (j = 0; j < n_cols; ++j)\n\t\t\tm[j][i] = a[i][j];\n\treturn m;\n}\n\nfloat sdot_1(int n, const float *x, const float *y)\n{\n\tint i;\n\tfloat s = 0.0f;\n\tfor (i = 0; i < n; ++i) s += x[i] * y[i];\n\treturn s;\n}\n\nfloat sdot_8(int n, const float *x, const float *y)\n{\n\tint i, n8 = n>>3<<3;\n\tfloat s, t[8];\n\tt[0] = t[1] = t[2] = t[3] = t[4] = t[5] = t[6] = t[7] = 0.0f;\n\tfor (i = 0; i < n8; i += 8) {\n\t\tt[0] += x[i+0] * y[i+0];\n\t\tt[1] += x[i+1] * y[i+1];\n\t\tt[2] += x[i+2] * y[i+2];\n\t\tt[3] += x[i+3] * y[i+3];\n\t\tt[4] += x[i+4] * y[i+4];\n\t\tt[5] += x[i+5] * y[i+5];\n\t\tt[6] += x[i+6] * y[i+6];\n\t\tt[7] += x[i+7] * y[i+7];\n\t}\n\tfor (s = 0.0f; i < n; ++i) s += x[i] * y[i];\n\ts += t[0] + t[1] + t[2] + t[3] + t[4] + t[5] + t[6] + t[7];\n\treturn s;\n}\n\n#ifdef __SSE__\n#include \n\nfloat sdot_sse(int n, const float *x, const float *y)\n{\n\tint i, n8 = n>>3<<3;\n\t__m128 vs1, vs2;\n\tfloat s, t[4];\n\tvs1 = _mm_setzero_ps();\n\tvs2 = _mm_setzero_ps();\n\tfor (i = 0; i < n8; i += 8) {\n\t\t__m128 vx1, vx2, vy1, vy2;\n\t\tvx1 = _mm_loadu_ps(&x[i]);\n\t\tvx2 = _mm_loadu_ps(&x[i+4]);\n\t\tvy1 = _mm_loadu_ps(&y[i]);\n\t\tvy2 = _mm_loadu_ps(&y[i+4]);\n\t\tvs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1));\n\t\tvs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2));\n\t}\n\tfor (s = 0.0f; i < n; ++i) s += x[i] * y[i];\n\t_mm_storeu_ps(t, vs1);\n\ts += t[0] + t[1] + t[2] + t[3];\n\t_mm_storeu_ps(t, vs2);\n\ts += t[0] + t[1] + t[2] + t[3];\n\treturn s;\n}\n#endif\n\n/*************************\n * Matrix multiplication *\n *************************/\n\nfloat **mat_mul0(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, k;\n\tfloat **m;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tfor (i = 0; i < n_a_rows; ++i) {\n\t\tfor (j = 0; j < n_b_cols; ++j) {\n\t\t\tfloat t = 0.0;\n\t\t\tfor (k = 0; k < n_a_cols; ++k)\n\t\t\t\tt += a[i][k] * b[k][j];\n\t\t\tm[i][j] = t;\n\t\t}\n\t}\n\treturn m;\n}\n\nfloat **mat_mul1(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, k, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; ++i) {\n\t\tconst float *ai = a[i];\n\t\tfloat *mi = m[i];\n\t\tfor (j = 0; j < n_b_cols; ++j) {\n\t\t\tfloat t = 0.0f, *bTj = bT[j];\n\t\t\tfor (k = 0; k < n_a_cols; ++k)\n\t\t\t\tt += ai[k] * bTj[k];\n\t\t\tmi[j] = t;\n\t\t}\n\t}\n\tmat_destroy(bT);\n\treturn m;\n}\n\n#ifdef __SSE__\nfloat **mat_mul2(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; ++i)\n\t\tfor (j = 0; j < n_b_cols; ++j)\n\t\t\tm[i][j] = sdot_sse(n_a_cols, a[i], bT[j]);\n\tmat_destroy(bT);\n\treturn m;\n}\nfloat **mat_mul7(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, ii, jj, x = 16, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; i += x) {\n\t\tfor (j = 0; j < n_b_cols; j += x) {\n\t\t\tint je = n_b_cols < j + x? n_b_cols : j + x;\n\t\t\tint ie = n_a_rows < i + x? n_a_rows : i + x;\n\t\t\tfor (ii = i; ii < ie; ++ii)\n\t\t\t\tfor (jj = j; jj < je; ++jj)\n\t\t\t\t\tm[ii][jj] += sdot_sse(n_a_cols, a[ii], bT[jj]);\n\t\t}\n\t}\n\tmat_destroy(bT);\n\treturn m;\n}\n#endif\n\nfloat **mat_mul3(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; ++i)\n\t\tfor (j = 0; j < n_b_cols; ++j)\n\t\t\tm[i][j] = sdot_8(n_a_cols, a[i], bT[j]);\n\tmat_destroy(bT);\n\treturn m;\n}\n\nfloat **mat_mul4(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; ++i)\n\t\tfor (j = 0; j < n_b_cols; ++j)\n\t\t\tm[i][j] = sdot_1(n_a_cols, a[i], bT[j]);\n\tmat_destroy(bT);\n\treturn m;\n}\n\n#ifdef HAVE_CBLAS\n#include \n\nfloat **mat_mul5(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tint i, j, n_b_rows = n_a_cols;\n\tfloat **m, **bT;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tbT = mat_transpose(n_b_rows, n_b_cols, b);\n\tfor (i = 0; i < n_a_rows; ++i)\n\t\tfor (j = 0; j < n_b_cols; ++j)\n\t\t\tm[i][j] = cblas_sdot(n_a_cols, a[i], 1, bT[j], 1);\n\tmat_destroy(bT);\n\treturn m;\n}\n\nfloat **mat_mul6(int n_a_rows, int n_a_cols, float *const *a, int n_b_cols, float *const *b)\n{\n\tfloat **m, n_b_rows = n_a_cols;\n\tm = mat_init(n_a_rows, n_b_cols);\n\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n_a_rows, n_b_cols, n_a_cols, 1.0f, a[0], n_a_rows, b[0], n_b_rows, 0.0f, m[0], n_a_rows);\n\treturn m;\n}\n#endif\n\n/*****************\n * Main function *\n *****************/\n\n#include \n#include \n\nint main(int argc, char *argv[])\n{\n\tint c, n = 1000, algo = 2;\n\tclock_t t;\n\tfloat **a, **b, **m = 0;\n\n\twhile ((c = getopt(argc, argv, \"n:a:h\")) >= 0) {\n\t\tif (c == 'n') n = atoi(optarg);\n\t\telse if (c == 'a') algo = atoi(optarg);\n\t\telse if (c == 'h') {\n\t\t\tfprintf(stderr, \"Usage: mat-eval [options]\\n\");\n\t\t\tfprintf(stderr, \"Options:\\n\");\n\t\t\tfprintf(stderr, \" -n INT size of the square matrix [%d]\\n\", n);\n\t\t\tfprintf(stderr, \" -a INT matrix multiplication implementation [%d]\\n\", algo);\n\t\t\tfprintf(stderr, \" 0: naive - no optimization\\n\");\n\t\t\tfprintf(stderr, \" 1: transposing the second matrix\\n\");\n#ifdef __SSE__\n\t\t\tfprintf(stderr, \" 2: explicitly vectorized sdot() with SSE\\n\");\n\t\t\tfprintf(stderr, \" 7: explicitly SSE sdot() plus loop tiling\\n\");\n#endif\n\t\t\tfprintf(stderr, \" 3: implicitly vectorized sdot()\\n\");\n\t\t\tfprintf(stderr, \" 4: no vectorization hints\\n\");\n#ifdef HAVE_CBLAS\n\t\t\tfprintf(stderr, \" 5: with sdot() from an external CBLAS library\\n\");\n\t\t\tfprintf(stderr, \" 6: with sgemm() from an external CBLAS library\\n\");\n#endif\n\t\t\tfprintf(stderr, \" -h this help message\\n\");\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\ta = mat_gen_random(n, n);\n\tb = mat_gen_random(n, n);\n\n\tt = clock();\n\tif (algo == 0) {\n\t\tm = mat_mul0(n, n, a, n, b);\n\t} else if (algo == 1) {\n\t\tm = mat_mul1(n, n, a, n, b);\n#ifdef __SSE__\n\t} else if (algo == 2) {\n\t\tm = mat_mul2(n, n, a, n, b);\n\t} else if (algo == 7) {\n\t\tm = mat_mul7(n, n, a, n, b);\n#endif\n\t} else if (algo == 3) {\n\t\tm = mat_mul3(n, n, a, n, b);\n\t} else if (algo == 4) {\n\t\tm = mat_mul4(n, n, a, n, b);\n#ifdef HAVE_CBLAS\n\t} else if (algo == 5) {\n\t\tm = mat_mul5(n, n, a, n, b);\n\t} else if (algo == 6) {\n\t\tm = mat_mul6(n, n, a, n, b);\n#endif\n\t} else {\n\t\tfprintf(stderr, \"ERROR: unknown algorithm %d\\n\", algo);\n\t\treturn 1;\n\t}\n\tfprintf(stderr, \"CPU time: %g\\n\", (double)(clock() - t) / CLOCKS_PER_SEC);\n\tfprintf(stderr, \"Central cell: %g\\n\", m[n/2][n/2]);\n\n\tif (m) mat_destroy(m);\n\tmat_destroy(b); mat_destroy(a);\n\treturn 0;\n}\n\n", "meta": {"hexsha": "045ce1b08104c50973e968f2bcf2eecad98517a4", "size": 8232, "ext": "c", "lang": "C", "max_stars_repo_path": "benchmarks/matmul.c", "max_stars_repo_name": "chrisroman/llvm-pass-skeleton", "max_stars_repo_head_hexsha": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T02:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T02:45:22.000Z", "max_issues_repo_path": "benchmarks/matmul.c", "max_issues_repo_name": "chrisroman/llvm-pass-skeleton", "max_issues_repo_head_hexsha": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "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": "benchmarks/matmul.c", "max_forks_repo_name": "chrisroman/llvm-pass-skeleton", "max_forks_repo_head_hexsha": "5e0308c38bd8aec7ac33b794f7d9551cfdf01733", "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.3292307692, "max_line_length": 146, "alphanum_fraction": 0.5507774538, "num_tokens": 3191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.45404562287280786}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"index.h\"\n#include \"parse_mmaps.h\"\n#include \"probability.h\"\n\ndouble reference_probability(const struct mmap_info* mmap_info, \n\t\t\t struct revision_assignment* parent,\n\t\t\t struct revision_assignment* child,\n\t\t\t int disagrees,\n\t\t\t const struct index_patch* index_patch) {\n double action_prob = 1.0;\n if (parent != NULL && parent->topic >= 0 && parent->pov >= 0\n && child->topic >= 0 && child->pov >= 0) {\n struct revision_assignment_header* revision_assignment_header\n = (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;\n struct topic_summary* topic_summary;\n struct pov_summary* pov_dist;\n get_topic_summary(mmap_info, child->topic, &topic_summary, &pov_dist, NULL);\n if (parent->topic == child->topic) {\n if (parent->pov != child->pov) {\n\t// POV reference\n\tstruct pov_summary* pov_summary = get_ant_pov(mmap_info, pov_dist, \n\t\t\t\t\t\t child->pov, parent->pov);\n\tdouble denom = (double)(pov_summary->norevert_count \n\t\t\t\t+ pov_summary->revert_count)\n\t + revision_assignment_header->psi_alpha\n\t + revision_assignment_header->psi_beta;\n\tint correction = 0;\n\tif (index_patch != NULL\n\t && index_patch->topic == child->topic\n\t && index_patch->pov == child->pov\n\t && index_patch->parent_pov == parent->pov\n\t && index_patch->parent_topic == index_patch->topic) {\n\t assert(denom -= 1.0 >= 0.0);\n\t if (!disagrees == !(index_patch->disagrees)) {\n\t correction += 1;\n\t }\n\t}\n\tif (index_patch != NULL\n\t && index_patch->child_topic == child->topic\n\t && index_patch->child_pov == child->pov\n\t && index_patch->pov == parent->pov\n\t && index_patch->topic == index_patch->child_topic) {\n\t assert(denom -= 1.0 >= 0.0);\n\t if (!disagrees == !(index_patch->child_disagrees)) {\n\t correction += 1;\n\t }\n\t}\n\tif (disagrees) {\n\t action_prob *= ((double)(pov_summary->revert_count \n\t\t\t\t - correction)\n\t\t\t + revision_assignment_header->psi_alpha) / denom;\n\t} else {\n\t action_prob *= ((double)(pov_summary->norevert_count\n\t\t\t\t - correction)\n\t\t\t + revision_assignment_header->psi_beta) / denom;\n\t}\n } else {\n\t// topic reference\n\tdouble denom = (double)(topic_summary->revert_topic_count\n\t\t\t\t+ topic_summary->norevert_topic_count\n\t\t\t\t+ revision_assignment_header->gamma_alpha \n\t\t\t\t+ revision_assignment_header->gamma_beta);\n\tint correction = 0;\n\tif (index_patch != NULL\n\t && index_patch->topic == child->topic\n\t && index_patch->parent_pov == index_patch->pov\n\t && index_patch->parent_topic == index_patch->topic) {\n\t assert(denom -= 1.0 >= 0.0);\n\t if (!disagrees == !(index_patch->disagrees)) {\n\t correction += 1;\n\t }\n\t}\n\tif (index_patch != NULL\n\t && index_patch->child_topic == child->topic\n\t && index_patch->pov == index_patch->child_pov\n\t && index_patch->topic == index_patch->child_topic) {\n\t assert(denom -= 1.0 >= 0.0);\n\t if (!disagrees == !(index_patch->child_disagrees)) {\n\t correction += 1;\n\t }\n\t}\n\tif (disagrees) {\n\t action_prob *= ((double)(topic_summary->revert_topic_count \n\t\t\t\t - correction)\n\t\t\t + revision_assignment_header->gamma_alpha) / denom;\n\t} else {\n\t action_prob *= ((double)(topic_summary->norevert_topic_count\n\t\t\t\t - correction)\n\t\t\t + revision_assignment_header->gamma_beta) / denom;\n\t}\n }\n } else {\n // general reference\n double denom = (double)(topic_summary->revert_general_count\n\t\t\t + topic_summary->norevert_general_count)\n\t+ revision_assignment_header->gamma_alpha \n\t+ revision_assignment_header->gamma_beta;\n int correction = 0;\n if (index_patch != NULL\n\t && index_patch->parent_topic >= 0\n\t && index_patch->topic == child->topic\n\t && index_patch->parent_topic != index_patch->topic) {\n\tassert(denom -= 1.0 >= 0.0);\n\tif (!disagrees == !(index_patch->disagrees)) {\n\t correction += 1;\n\t}\n }\n if (index_patch != NULL\n\t && index_patch->topic >= 0\n\t && index_patch->child_topic == child->topic\n\t && index_patch->topic != index_patch->child_topic) {\n\tassert(denom -= 1.0 >= 0.0);\n\tif (!disagrees == !(index_patch->child_disagrees)) {\n\t correction = 1;\n\t}\n }\n if (disagrees) {\n\taction_prob *= ((double)(topic_summary->revert_general_count \n\t\t\t\t - correction) \n\t\t\t+ revision_assignment_header->gamma_alpha) / denom;\n } else {\n\taction_prob *= ((double)(topic_summary->norevert_general_count \n\t\t\t\t - correction)\n\t\t\t+ revision_assignment_header->gamma_beta) / denom;\n }\n }\n } // Else, a constant not dependant on POV or topic\n assert(action_prob > 0.0);\n return action_prob;\n}\n\ndouble revision_probability(const struct mmap_info* mmap_info, int64_t revision_id,\n\t\t\t int32_t topic, int32_t pov, \n\t\t\t int include_child,\n\t\t\t int include_user_topic_pov,\n\t\t\t const struct index_patch* index_patch) {\n const struct revision* revision = get_revision(mmap_info, revision_id);\n struct revision_assignment current_assignment;\n current_assignment.topic = topic;\n current_assignment.pov = pov;\n double ret = 1.0;\n // Revert probability\n if (revision->parent >= 0) {\n ret *= reference_probability(mmap_info,\n\t\t\t\t get_revision_assignment(mmap_info, revision->parent), \n\t\t\t\t ¤t_assignment, revision->disagrees,\n\t\t\t\t index_patch);\n }\n if (revision->child >= 0 && include_child) {\n ret *= reference_probability(mmap_info, ¤t_assignment,\n\t\t\t\t get_revision_assignment(mmap_info, revision->child),\n\t\t\t\t get_revision(mmap_info, revision->child)->disagrees,\n\t\t\t\t index_patch);\n }\n\n // Topic, pov probability\n struct revision_assignment_header* revision_assignment_header\n = (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;\n if (include_user_topic_pov) {\n int pov_correction = 0;\n if (index_patch\n\t&& index_patch->user == revision->user \n\t&& pov == index_patch->pov\n\t&& topic == index_patch->topic) {\n pov_correction = 1;\n }\n\n double* user_pov_dist;\n get_user_topics(mmap_info, revision->user, &user_pov_dist);\n // Alpha is already added to this array. The normalizing constant is\n // independant of topic/pov, so we exclude it here.\n ret *= (user_pov_dist[topic * revision_assignment_header->pov_per_topic + pov] \n\t - pov_correction);\n }\n\n // Page probability\n struct topic_summary_header* topic_summary_header\n = (struct topic_summary_header*)mmap_info->topic_index_mmap;\n int64_t* page_dist;\n struct topic_summary* topic_summary;\n get_topic_summary(mmap_info, topic, &topic_summary, NULL, &page_dist);\n int64_t topic_page_revisions = page_dist[revision->article];\n int64_t topic_revisions = topic_summary->total_revisions;\n if (index_patch && index_patch->topic == topic) {\n topic_revisions -= 1;\n if (index_patch->page == revision->article) {\n topic_page_revisions -= 1;\n }\n }\n ret *= ((double)(topic_page_revisions) + revision_assignment_header->beta) \n / ((double)(topic_revisions)\n + revision_assignment_header->beta * topic_summary_header->num_pages);\n assert(ret > 0.0);\n return ret;\n}\n\nvoid fill_index_patch(const struct mmap_info* mmap_info, \n\t\t int64_t revision_id,\n\t\t struct index_patch* index_patch) {\n const struct revision* revision = get_revision(mmap_info, revision_id);\n index_patch->user = revision->user;\n index_patch->page = revision->article;\n const struct revision_assignment* revision_assignment \n = get_revision_assignment(mmap_info, revision_id);\n index_patch->topic = revision_assignment->topic;\n index_patch->pov = revision_assignment->pov;\n index_patch->disagrees = revision->disagrees;\n if (revision->parent >= 0) {\n const struct revision_assignment* parent_assignment\n = get_revision_assignment(mmap_info, revision->parent);\n index_patch->parent_topic = parent_assignment->topic;\n index_patch->parent_pov = parent_assignment->pov;\n } else {\n index_patch->parent_topic = -1;\n index_patch->parent_pov = -1;\n }\n if (revision->child >= 0) {\n const struct revision_assignment* child_assignment\n = get_revision_assignment(mmap_info, revision->child);\n index_patch->child_topic = child_assignment->topic;\n index_patch->child_pov = child_assignment->pov;\n index_patch->child_disagrees = get_revision(mmap_info, \n\t\t\t\t\t\trevision->child)->disagrees;\n } else {\n index_patch->child_topic = -1;\n index_patch->child_pov = -1;\n index_patch->child_disagrees = -1;\n }\n}\n\ndouble users_pages_probability_modn(const struct mmap_info* mmap_info, int sample, int modn) {\n struct revision_assignment_header* revision_assignment_header \n = (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;\n struct user_topic_header* user_topic_header = (struct user_topic_header*)mmap_info->user_topic_mmap;\n double log_likelihood = 0.0;\n int64_t user_edits;\n double* user_topic_pov_dist;\n int topic_pov_count\n = revision_assignment_header->num_topics * revision_assignment_header->pov_per_topic;\n for (int64_t user_num = sample; user_num < user_topic_header->num_users; user_num += modn) {\n get_user(mmap_info, user_num, &user_edits, NULL);\n get_user_topics(mmap_info, user_num, &user_topic_pov_dist);\n if (user_edits <= 0) {\n // This user does not actually exist\n continue;\n }\n log_likelihood -= gsl_sf_lngamma(user_edits + revision_assignment_header->alpha * topic_pov_count);\n for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {\n for (int pov = 0; pov < revision_assignment_header->pov_per_topic; ++pov) {\n\tlog_likelihood += gsl_sf_lngamma(user_topic_pov_dist[topic * revision_assignment_header->pov_per_topic\n\t\t\t\t\t\t\t + pov]);\n }\n }\n }\n struct topic_summary_header* topic_summary_header\n = (struct topic_summary_header*)mmap_info->topic_index_mmap;\n int64_t* page_dist;\n for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {\n get_topic_summary(mmap_info, topic, NULL, NULL, &page_dist);\n for (int64_t page = sample; page < topic_summary_header->num_pages; page += modn) {\n log_likelihood += gsl_sf_lngamma(page_dist[page] + revision_assignment_header->beta);\n }\n }\n return log_likelihood;\n}\n\ndouble log_likelihood(const struct mmap_info* mmap_info) {\n return log_likelihood_gamma(mmap_info, 1);\n}\n\ndouble log_likelihood_gamma(const struct mmap_info* mmap_info, int include_users_pages) {\n struct user_topic_header* user_topic_header = (struct user_topic_header*)mmap_info->user_topic_mmap;\n struct revision_assignment_header* revision_assignment_header \n = (struct revision_assignment_header*)mmap_info->revision_assignment_mmap;\n int topic_pov_count\n = revision_assignment_header->num_topics * revision_assignment_header->pov_per_topic;\n double log_likelihood = 0.0;\n log_likelihood += user_topic_header->num_users\n * gsl_sf_lngamma(revision_assignment_header->alpha * topic_pov_count);\n log_likelihood -= user_topic_header->num_users * topic_pov_count\n * gsl_sf_lngamma(revision_assignment_header->alpha);\n if (include_users_pages) {\n log_likelihood += users_pages_probability_modn(mmap_info, 0, 1);\n }\n \n struct topic_summary_header* topic_summary_header\n = (struct topic_summary_header*)mmap_info->topic_index_mmap;\n struct topic_summary* topic_summary;\n struct pov_summary* pov_dist;\n struct pov_summary* pov_summary;\n log_likelihood += revision_assignment_header->num_topics \n * gsl_sf_lngamma(revision_assignment_header->beta * topic_summary_header->num_pages);\n log_likelihood -= revision_assignment_header->num_topics * topic_summary_header->num_pages\n * gsl_sf_lngamma(revision_assignment_header->beta);\n for (int topic = 0; topic < revision_assignment_header->num_topics; ++topic) {\n get_topic_summary(mmap_info, topic, &topic_summary, &pov_dist, NULL);\n log_likelihood -= gsl_sf_lngamma(topic_summary->total_revisions + revision_assignment_header->beta\n\t\t\t\t * topic_summary_header->num_pages);\n // General reverts\n log_likelihood += gsl_sf_lngamma(topic_summary->revert_general_count\n\t\t\t\t + revision_assignment_header->gamma_alpha);\n log_likelihood += gsl_sf_lngamma(topic_summary->norevert_general_count\n\t\t\t\t + revision_assignment_header->gamma_beta);\n log_likelihood -= gsl_sf_lngamma(topic_summary->revert_general_count\n\t\t\t\t + topic_summary->norevert_general_count\n\t\t\t\t + revision_assignment_header->gamma_alpha\n\t\t\t\t + revision_assignment_header->gamma_beta);\n // Topic reverts\n log_likelihood += gsl_sf_lngamma(topic_summary->revert_topic_count\n\t\t\t\t + revision_assignment_header->gamma_alpha);\n log_likelihood += gsl_sf_lngamma(topic_summary->norevert_topic_count\n\t\t\t\t + revision_assignment_header->gamma_beta);\n log_likelihood -= gsl_sf_lngamma(topic_summary->revert_topic_count\n\t\t\t\t + topic_summary->norevert_topic_count\n\t\t\t\t + revision_assignment_header->gamma_alpha\n\t\t\t\t + revision_assignment_header->gamma_beta);\n \n // POV reverts\n for (int pov = 0; pov < revision_assignment_header->pov_per_topic; ++pov) {\n for (int ant_pov = 0; ant_pov < revision_assignment_header->pov_per_topic - 1; ++ant_pov) {\n\tpov_summary = pov_dist + pov * (revision_assignment_header->pov_per_topic - 1) + ant_pov;\n\tlog_likelihood += gsl_sf_lngamma(pov_summary->revert_count\n\t\t\t\t\t + revision_assignment_header->psi_alpha);\n\tlog_likelihood += gsl_sf_lngamma(pov_summary->norevert_count\n\t\t\t\t\t + revision_assignment_header->psi_beta);\n\tlog_likelihood -= gsl_sf_lngamma(pov_summary->revert_count\n\t\t\t\t\t + pov_summary->norevert_count\n\t\t\t\t\t + revision_assignment_header->psi_alpha\n\t\t\t\t\t + revision_assignment_header->psi_beta);\n }\n }\n }\n log_likelihood += 2 * revision_assignment_header->num_topics\n * gsl_sf_lngamma(revision_assignment_header->gamma_alpha + revision_assignment_header->gamma_beta);\n log_likelihood -= 2 * revision_assignment_header->num_topics \n * gsl_sf_lngamma(revision_assignment_header->gamma_alpha);\n log_likelihood -= 2 * revision_assignment_header->num_topics\n * gsl_sf_lngamma(revision_assignment_header->gamma_beta);\n \n log_likelihood += revision_assignment_header->pov_per_topic \n * (revision_assignment_header->pov_per_topic - 1) \n * revision_assignment_header->num_topics\n * gsl_sf_lngamma(revision_assignment_header->psi_alpha + revision_assignment_header->psi_beta);\n log_likelihood -= revision_assignment_header->pov_per_topic\n * (revision_assignment_header->pov_per_topic - 1)\n * revision_assignment_header->num_topics \n * gsl_sf_lngamma(revision_assignment_header->psi_alpha);\n log_likelihood -= revision_assignment_header->pov_per_topic\n * (revision_assignment_header->pov_per_topic - 1)\n * revision_assignment_header->num_topics\n * gsl_sf_lngamma(revision_assignment_header->psi_beta);\n\n return log_likelihood;\n}\n", "meta": {"hexsha": "1fc1561359513e0248373b6283e2b662604383db", "size": 14806, "ext": "c", "lang": "C", "max_stars_repo_path": "src/probability.c", "max_stars_repo_name": "allenlavoie/topic-pov", "max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z", "max_issues_repo_path": "src/probability.c", "max_issues_repo_name": "allenlavoie/topic-pov", "max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "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/probability.c", "max_forks_repo_name": "allenlavoie/topic-pov", "max_forks_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "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.0138504155, "max_line_length": 103, "alphanum_fraction": 0.7252465217, "num_tokens": 3687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.453954804516636}} {"text": "/* specfunc/zeta.c\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/* This file was taken from the GNU Scientific Library. Some modifications\n * were done in order to make it independent from the rest of GSL\n */\n\n/*\n#include \n#include \n#include \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\n#include \n#include \n#include \"error.h\"\n\n/*-*-*-*-*-*-*-*-*-*- From gsl_machine.h -*-*-*-*-*-*-*-*-*-*-*-*-*/\n\n#define GSL_LOG_DBL_MIN (-7.0839641853226408e+02)\n#define GSL_LOG_DBL_MAX 7.0978271289338397e+02\n#define GSL_DBL_EPSILON 2.2204460492503131e-16\n\n/*-*-*-*-*-*-*-*-*-* From gsl_sf_result.h *-*-*-*-*-*-*-*-*-*-*-*/\n\nstruct gsl_sf_result_struct {\n double val;\n double err;\n};\ntypedef struct gsl_sf_result_struct gsl_sf_result;\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* coefficients for Maclaurin summation in hzeta()\n * B_{2j}/(2j)!\n */\nstatic double hzeta_c[15] = {\n 1.00000000000000000000000000000,\n 0.083333333333333333333333333333,\n -0.00138888888888888888888888888889,\n 0.000033068783068783068783068783069,\n -8.2671957671957671957671957672e-07,\n 2.0876756987868098979210090321e-08,\n -5.2841901386874931848476822022e-10,\n 1.3382536530684678832826980975e-11,\n -3.3896802963225828668301953912e-13,\n 8.5860620562778445641359054504e-15,\n -2.1748686985580618730415164239e-16,\n 5.5090028283602295152026526089e-18,\n -1.3954464685812523340707686264e-19,\n 3.5347070396294674716932299778e-21,\n -8.9535174270375468504026113181e-23\n};\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nstatic int gsl_sf_hzeta_e(const double s, const double q, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(s <= 1.0 || q <= 0.0) {\n\tPLFIT_ERROR(\"s must be larger than 1.0 and q must be larger than zero\", PLFIT_EINVAL);\n }\n else {\n const double max_bits = 54.0;\n const double ln_term0 = -s * log(q); \n\n if(ln_term0 < GSL_LOG_DBL_MIN + 1.0) {\n\t PLFIT_ERROR(\"underflow\", PLFIT_UNDRFLOW);\n }\n else if(ln_term0 > GSL_LOG_DBL_MAX - 1.0) {\n\t PLFIT_ERROR(\"overflow\", PLFIT_OVERFLOW);\n }\n else if((s > max_bits && q < 1.0) || (s > 0.5*max_bits && q < 0.25)) {\n result->val = pow(q, -s);\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return PLFIT_SUCCESS;\n }\n else if(s > 0.5*max_bits && q < 1.0) {\n const double p1 = pow(q, -s);\n const double p2 = pow(q/(1.0+q), s);\n const double p3 = pow(q/(2.0+q), s);\n result->val = p1 * (1.0 + p2 + p3);\n result->err = GSL_DBL_EPSILON * (0.5*s + 2.0) * fabs(result->val);\n return PLFIT_SUCCESS;\n }\n else {\n /* Euler-Maclaurin summation formula \n * [Moshier, p. 400, with several typo corrections]\n */\n const int jmax = 12;\n const int kmax = 10;\n int j, k;\n const double pmax = pow(kmax + q, -s);\n double scp = s;\n double pcp = pmax / (kmax + q);\n double ans = pmax*((kmax+q)/(s-1.0) + 0.5);\n\n for(k=0; kval = ans;\n result->err = 2.0 * (jmax + 1.0) * GSL_DBL_EPSILON * fabs(ans);\n return PLFIT_SUCCESS;\n }\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\ndouble gsl_sf_hzeta(const double s, const double a)\n{\n gsl_sf_result result;\n gsl_sf_hzeta_e(s, a, &result);\n return result.val;\n}\n\n", "meta": {"hexsha": "c0bf6a451081675797c8abd610ff5c21a6bddb45", "size": 4616, "ext": "c", "lang": "C", "max_stars_repo_path": "igraph/src/zeta.c", "max_stars_repo_name": "jmazon/haskell-igraph", "max_stars_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "igraph/src/zeta.c", "max_issues_repo_name": "jmazon/haskell-igraph", "max_issues_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "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": "igraph/src/zeta.c", "max_forks_repo_name": "jmazon/haskell-igraph", "max_forks_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-05T06:24:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-05T06:24:02.000Z", "avg_line_length": 29.7806451613, "max_line_length": 87, "alphanum_fraction": 0.6306325823, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.45385881538259093}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"LSAbundance.h\"\n\nstatic int verbose = FALSE;\n\nstatic int nLines = 9;\n\nstatic char *usage[] = {\"LSAbundance - \\n\",\n \"Required parameters:\\n\",\n\t\t\t\" -a abundance data\\n\",\n\t\t\t\" -in filename parameter file \\n\",\n \"Optional:\\n\",\n\t\t\t\" -b integer length of sample file to ignore\\n\",\n\t\t\t\" -s integer sampling frequency\\n\",\n\t\t\t\" -seed long seed random number generator\\n\",\n\t\t\t\" -v verbose\\n\"};\n\nvoid updateExpectations(double* adExpect, int nMax, double dMDash, double dV, double dNu, int nS, t_Data *ptData)\n{\n int i = 0;\n\n for(i = 1; i <= nMax; i++){\n int nA = i;\n double dLog = 0.0, dP = 0.0;\n \n if(nA < MAX_QUAD){\n dLog = logLikelihoodQuad(nA, dMDash, dV, dNu);\n }\n else{\n dLog = logLikelihoodRampal(nA, dMDash, dV, dNu);\n }\n\n dP = exp(dLog);\n\n adExpect[i - 1]+= dP*nS;\n }\n}\n\n\nint main(int argc, char* argv[]){\n t_Params tParams;\n t_LSParams* atLSParams;\n int i = 0, nSamples = 0, nMax = 0; \n t_Data tData;\n double* adExpect = NULL;\n\n gsl_set_error_handler_off();\n\n getCommandLineParams(&tParams, argc, argv);\n\n /*allocate memory for samples*/\n atLSParams = (t_LSParams *) malloc(MAX_SAMPLES*sizeof(t_LSParams));\n if(!atLSParams)\n goto memoryError;\n \n /*read in Monte-Carlo samples*/\n readSamples(&tParams, atLSParams, &nSamples);\n\n readAbundanceData(tParams.szAbundFile, &tData);\n\n nMax = tData.aanAbund[tData.nNA - 1][0];\n nMax = floor(pow(2.0,ceil(log((double) nMax)/log(2.0)) + 2.0) + 1.0e-7);\n\n adExpect = (double *) malloc(sizeof(double)*nMax);\n\n for(i = 0; i < nMax; i++){\n adExpect[i] = 0.0;\n }\n\n for(i = 0; i < nSamples; i++){\n updateExpectations(adExpect, nMax, \n\t\t atLSParams[i].dMDash, \n\t\t atLSParams[i].dV,\n\t\t atLSParams[i].dNu,\n\t\t atLSParams[i].nS, \n\t\t &tData);\n }\n\n for(i = 1; i <= nMax; i++){\n printf(\"%d %f\\n\",i,adExpect[i - 1]/((double) nSamples));\n }\n\n free(adExpect);\n exit(EXIT_SUCCESS);\n \n memoryError:\n fprintf(stderr, \"Failed to allocate memory in main aborting ...\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nint intCompare(const void *pvA, const void *pvB)\n{\n int* pnA = (int *) pvA, *pnB = (int *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nint doubleCompare(const void *pvA, const void *pvB)\n{\n double* pnA = (double *) pvA, *pnB = (double *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nvoid writeUsage(FILE* ofp)\n{\n int i = 0;\n char *line;\n\n for(i = 0; i < nLines; i++){\n line = usage[i];\n fputs(line,ofp);\n }\n}\n\nchar *extractParameter(int argc, char **argv, char *param,int when)\n{\n int i = 0;\n\n while((i < argc) && (strcmp(param,argv[i]))){\n i++;\n }\n\n if(i < argc - 1){\n return(argv[i + 1]);\n }\n\n if((i == argc - 1) && (when == OPTION)){\n return \"\";\n }\n\n if(when == ALWAYS){\n fprintf(stdout,\"Can't find asked option %s\\n\",param);\n }\n\n return (char *) NULL;\n}\n\nvoid getCommandLineParams(t_Params *ptParams,int argc,char *argv[])\n{\n char *szTemp = NULL;\n char *cError = NULL;\n\n /*get parameter file name*/\n ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS); \n if(ptParams->szInputFile == NULL)\n goto error;\n\n /*get abundance file name*/\n ptParams->szAbundFile = extractParameter(argc,argv, ABUND_FILE,ALWAYS); \n if(ptParams->szAbundFile == NULL)\n goto error;\n\n /*get long seed*/\n szTemp = extractParameter(argc,argv,SEED,OPTION); \n if(szTemp != NULL){\n ptParams->lSeed = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->lSeed = 0;\n }\n\n /*get burn*/\n szTemp = extractParameter(argc, argv, BURN, OPTION); \n if(szTemp != NULL){\n ptParams->nBurn = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nBurn = DEF_BURN;\n }\n\n /*get long seed*/\n szTemp = extractParameter(argc, argv, SAMPLE, OPTION); \n if(szTemp != NULL){\n ptParams->nSample = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nSample = DEF_SAMPLE;\n }\n \n /*verbosity*/\n szTemp = extractParameter(argc, argv, VERBOSE, OPTION);\n if(szTemp != NULL){\n verbose = TRUE;\n }\n\n return;\n\n error:\n writeUsage(stdout);\n exit(EXIT_FAILURE);\n}\n\nvoid readSamples(t_Params *ptParams, t_LSParams *atLSParams, int *pnSamples)\n{\n int nSamples = 0;\n char *szInputFile = ptParams->szInputFile;\n char szLine[MAX_LINE_LENGTH];\n FILE *ifp = NULL;\n\n ifp = fopen(szInputFile, \"r\");\n\n if(ifp){\n while(fgets(szLine, MAX_LINE_LENGTH, ifp)){\n char *szTok = NULL, *szBrk = NULL, *pcError = NULL;\n int nTime = 0;\n\n /*remove trailing new line*/\n szBrk = strpbrk(szLine, \"\\n\"); (*szBrk) = '\\0';\n \n szTok = strtok(szLine, DELIM);\n\n nTime = strtol(szTok, &pcError, 10);\n if(*pcError != '\\0') goto fileFormatError;\n\n if(nTime > ptParams->nBurn && nTime % ptParams->nSample == 0){\n\t\n\tszTok = strtok(NULL,DELIM);\n\tatLSParams[nSamples].dMDash = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatLSParams[nSamples].dV = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatLSParams[nSamples].dNu = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatLSParams[nSamples].nS = strtol(szTok, &pcError, 10);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tnSamples++;\n }\n }\n\n fclose(ifp);\n }\n else{\n fprintf(stderr, \"Failed to open file %s aborting\\n\", szInputFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n (*pnSamples) = nSamples;\n return;\n\n fileFormatError:\n fprintf(stderr, \"Incorrectly formatted input file aborting\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\ndouble f1(double x, void *pvParams)\n{\n t_LSParams *ptLSParams = (t_LSParams *) pvParams;\n double dMDash = ptLSParams->dMDash, dV = ptLSParams->dV, dNu = ptLSParams->dNu;\n int n = ptLSParams->n;\n double t = ((x - dMDash)*(x - dMDash))/dV;\n double dExp = x*((double) n) - exp(x);\n double dF = pow(1.0 + t/dNu, -0.5*(dNu + 1.0));\n \n return exp(dExp)*dF;\n}\n\ndouble f1Log(double x, void *pvParams)\n{\n t_LNParams *ptLNParams = (t_LNParams *) pvParams;\n double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV;\n int n = ptLNParams->n;\n double dTemp = (x - dMDash);\n double dExp = x*((double) n) - exp(x) - 0.5*((dTemp*dTemp)/dV);\n double dRet = exp(dExp);\n\n return dRet;\n}\n\ndouble derivExponent(double x, void *pvParams)\n{\n t_LNParams *ptLNParams = (t_LNParams *) pvParams;\n double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;\n double dTemp = (x - dMDash)/dV, dRet = 0.0;\n\n dRet = ((double) n) - exp(x) - dTemp;\n\n return dRet;\n}\n\ndouble logStirlingsGamma(double dZ)\n{\n return 0.5*log(2.0*M_PI) + (dZ - 0.5)*log(dZ) - dZ; \n}\n\ndouble logLikelihoodQuad(int n, double dMDash, double dV, double dNu)\n{\n gsl_integration_workspace *ptGSLWS = \n gsl_integration_workspace_alloc(1000);\n double dLogFac1 = 0.0, dLogFacN = 0.0;\n double dN = (double) n, dResult = 0.0, dError = 0.0, dPrecision = 0.0;\n gsl_function tGSLF;\n t_LSParams tLSParams;\n double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;\n\n tLSParams.n = n; tLSParams.dMDash = dMDash; tLSParams.dV = dV; tLSParams.dNu = dNu;\n\n tGSLF.function = &f1;\n tGSLF.params = (void *) &tLSParams;\n\n if(dNu < MAX_MU_GAMMA){\n dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);\n }\n else{\n dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;\n }\n \n if(n < 50){\n dLogFacN = gsl_sf_fact(n);\n dLogFacN = log(dLogFacN);\n }\n else if(n < 100){\n dLogFacN = gsl_sf_lngamma(dN + 1.0);\n }\n else{\n dLogFacN = logStirlingsGamma(dN + 1.0);\n }\n\n dA = -100.0; dB = 100.0;\n\n if(n < 10){\n dPrecision = HI_PRECISION;\n }\n else{\n dPrecision = LO_PRECISION;\n }\n\n gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);\n \n //printf(\"%f %f\\n\", dResult, dError);\n\n gsl_integration_workspace_free(ptGSLWS);\n\n return log(dResult) - dLogFacN + dLogFac1 - 0.5*log(dV);\n}\n\nint solveF(double x_lo, double x_hi, double (*f)(double, void*), \n\t void* params, double tol, double *xsolve)\n{\n int status, iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double r = 0;\n gsl_function F;\n t_LNParams *ptLNParams = (t_LNParams *) params;\n F.function = f;\n F.params = params;\n \n //printf(\"%f %f %d %f %f\\n\",ptLNParams->dMDash, ptLNParams->dV, ptLNParams->n, x_lo, x_hi);\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc (T);\n gsl_root_fsolver_set (s, &F, x_lo, x_hi);\n \n do{\n iter++;\n status = gsl_root_fsolver_iterate (s);\n r = gsl_root_fsolver_root (s);\n x_lo = gsl_root_fsolver_x_lower (s);\n x_hi = gsl_root_fsolver_x_upper (s);\n \n status = gsl_root_test_interval (x_lo, x_hi, 0, tol); \n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n (*xsolve) = gsl_root_fsolver_root (s);\n gsl_root_fsolver_free (s);\n \n return status;\n}\n\ndouble logLikelihoodLNQuad(int n, double dMDash, double dV)\n{\n gsl_integration_workspace *ptGSLWS = \n gsl_integration_workspace_alloc(1000);\n double dLogFac1 = 0.0, dLogFacN = 0.0;\n double dResult = 0.0, dError = 0.0, dPrecision = 0.0;\n gsl_function tGSLF;\n t_LNParams tLNParams;\n double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;\n\n tLNParams.n = n; tLNParams.dMDash = dMDash; tLNParams.dV = dV;\n\n tGSLF.function = &f1Log;\n tGSLF.params = (void *) &tLNParams;\n\n dLogFac1 = log(2.0*M_PI*dV);\n \n if(n < 50){\n dLogFacN = gsl_sf_fact(n);\n dLogFacN = log(dLogFacN);\n }\n else{\n dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);\n }\n\n if(dEst > dV){\n double dMax = 0.0;\n double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);\n double dVar = 0.0;\n\n if(fabs(dUpper) > 1.0e-7){\n solveF(0.0, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);\n }\n\n dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));\n\n dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;\n }\n else{\n double dMax = 0.0;\n double dLower = dEst - dV;\n double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);\n double dVar = 0.0;\n\n if(fabs(dUpper - dLower) > 1.0e-7){\n solveF(dLower, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);\n }\n else{\n dMax = 0.5*(dLower + dUpper);\n }\n dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));\n\n dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;\n }\n \n if(n < 10){\n dPrecision = HI_PRECISION;\n }\n else{\n dPrecision = LO_PRECISION;\n }\n\n gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);\n \n gsl_integration_workspace_free(ptGSLWS);\n\n return log(dResult) - dLogFacN -0.5*dLogFac1;\n}\n\ndouble logLikelihoodLNRampal(int n, double dMDash, double dV)\n{\n double dN = (double) n;\n double dLogLik = 0.0, dTemp = gsl_pow_int(log(dN) - dMDash,2), dTemp3 = gsl_pow_int(log(dN) - dMDash,3); \n\n dLogLik = -0.5*log(2.0*M_PI*dV) - log(dN) - (dTemp/(2.0*dV));\n\n dLogLik += log(1.0 + 1.0/(2.0*dN*dV)*(dTemp/dV + log(dN) - dMDash - 1.0) \n\t\t + 1.0/(6.0*dN*dN*dV*dV*dV)*(3.0*dV*dV - (3.0*dV - 2.0*dV*dV)*(dMDash - log(dN)) \n\t\t - 3.0*dV*dTemp + dTemp3));\n\n return dLogLik;\n}\n\ndouble logLikelihoodRampal(int n, double dMDash, double dV, double dNu)\n{\n double dGamma = 0.5*(dNu + 1.0), dN = (double) n, dRN = 1.0/dN, dRSV = 1.0/(sqrt(dV)*sqrt(dNu));\n double dZ = (log(dN) - dMDash)*dRSV;\n double dDZDX = dRN*dRSV, dDZDX2 = -dRN*dRN*dRSV; \n double dF = (1.0 + dZ*dZ);\n double dA = 0.0, dB = 0.0, dTemp = 0.0;\n double dLogFac1 = 0.0;\n\n if(dNu < MAX_MU_GAMMA){\n dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);\n }\n else{\n dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;\n } \n \n dA = 4.0*dZ*dZ*dDZDX*dDZDX*dGamma*(dGamma + 1.0);\n dA /= dF*dF;\n\n dB = -2.0*dGamma*(dDZDX*dDZDX + dZ*dDZDX2);\n dB /= dF;\n\n dTemp = dRN + dA + dB;\n \n return -dGamma*log(dF) + log(dTemp) + dLogFac1 - 0.5*log(dV);\n}\n\nvoid readAbundanceData(const char *szFile, t_Data *ptData)\n{\n int **aanAbund = NULL;\n int i = 0, nNA = 0, nA = 0, nC = 0;\n int nL = 0, nJ = 0;\n char szLine[MAX_LINE_LENGTH];\n FILE* ifp = NULL;\n\n ifp = fopen(szFile, \"r\");\n\n if(ifp){\n char* szTok = NULL;\n char* pcError = NULL;\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n \n nNA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n goto formatError;\n }\n \n aanAbund = (int **) malloc(nNA*sizeof(int*));\n\n for(i = 0; i < nNA; i++){\n aanAbund[i] = (int *) malloc(sizeof(int)*2);\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n\n nA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n\n szTok = strtok(NULL, DELIM2);\n\n nC = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n \n nL += nC;\n nJ += nC*nA;\n\n aanAbund[i][0] = nA;\n aanAbund[i][1] = nC; \n }\n }\n else{\n fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n ptData->nJ = nJ;\n ptData->nL = nL;\n ptData->aanAbund = aanAbund;\n ptData->nNA = nNA;\n return;\n\n formatError:\n fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n", "meta": {"hexsha": "14bae4124d495fb83d6369136e157fee70a071dd", "size": 14116, "ext": "c", "lang": "C", "max_stars_repo_path": "LSAbundance/LSAbundance.c", "max_stars_repo_name": "chrisquince/DiversityEstimates", "max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z", "max_issues_repo_path": "LSAbundance/LSAbundance.c", "max_issues_repo_name": "chrisquince/DiversityEstimates", "max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "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": "LSAbundance/LSAbundance.c", "max_forks_repo_name": "chrisquince/DiversityEstimates", "max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "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.7243697479, "max_line_length": 113, "alphanum_fraction": 0.6007367526, "num_tokens": 5156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.45384577142389504}} {"text": "/* linalg/qr_band.c\n * \n * Copyright (C) 2020 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Factorise a (p,q) banded M x N matrix A into\n * \n * A = Q R\n *\n * where Q is orthogonal (M x M) and R is upper triangular (M x N).\n *\n * Example with M = 7, N = 6, (p,q) = (2,1)\n *\n * A = [ A11 A12 0 0 0 0 ]\n * [ A21 A22 A23 0 0 0 ]\n * [ A31 A32 A33 A34 0 0 ]\n * [ 0 A42 A43 A44 A45 0 ]\n * [ 0 0 A53 A54 A55 A56 ]\n * [ 0 0 0 A64 A65 A66 ]\n * [ 0 0 0 0 A75 A76 ]\n *\n * AB has dimensions N-by-(2p + q + 1)\n *\n * INPUT: OUTPUT:\n *\n * AB = [ * * * A11 A21 A31 ] AB = [ * * * R11 V21 V31 ]\n * [ * * A12 A22 A32 A42 ] [ * * R12 R22 V32 V42 ]\n * [ * 0 A23 A33 A43 A53 ] [ * R13 R23 R33 V43 V53 ]\n * [ 0 0 A34 A44 A54 A64 ] [ R14 R24 R34 R44 V54 V64 ]\n * [ 0 0 A45 A55 A65 A75 ] [ R25 R35 R45 R55 V65 V75 ]\n * [ 0 0 A56 A66 A76 * ] [ R36 R46 R56 R66 V76 * ]\n * -p-- -q- -1- ---p--- ---p--- -q- -1- ---p---\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\nint\ngsl_linalg_QR_band_decomp_L2 (const size_t M, const size_t p, const size_t q, gsl_matrix * AB, gsl_vector * tau)\n{\n const size_t N = AB->size1;\n\n if (tau->size != N)\n {\n GSL_ERROR (\"tau must have length N\", GSL_EBADLEN);\n }\n else if (AB->size2 != 2*p + q + 1)\n {\n GSL_ERROR (\"dimensions of AB are inconsistent with (p,q)\", GSL_EBADLEN);\n }\n else\n {\n const size_t minMN = GSL_MIN(M, N);\n size_t j;\n\n /* set AB(:,1:p) to zero */\n if (p > 0)\n {\n gsl_matrix_view m = gsl_matrix_submatrix(AB, 0, 0, N, p);\n gsl_matrix_set_zero(&m.matrix);\n }\n\n for (j = 0; j < minMN; ++j)\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 size_t k1 = GSL_MIN(p + 1, M - j); /* number of non-zero elements of this column, including diagonal element */\n size_t k2 = GSL_MIN(p + q, N - j - 1); /* number of columns to update */\n gsl_vector_view c = gsl_matrix_subrow(AB, j, p + q, k1);\n double tau_j = gsl_linalg_householder_transform (&(c.vector));\n double * ptr = gsl_vector_ptr(&(c.vector), 0);\n\n gsl_vector_set (tau, j, tau_j);\n\n /* apply the transformation to the remaining columns */\n if (k2 > 0)\n {\n gsl_matrix_view m = gsl_matrix_submatrix (AB, j + 1, p + q - 1, k2, k1);\n gsl_vector_view work = gsl_vector_subvector(tau, j + 1, k2);\n double tmp = *ptr;\n\n m.matrix.tda -= 1; /* unskew matrix */\n\n /* we want to compute H*A(j:j+k1-1,j+1:j+k2), but due to our using row-major order, the\n * matrix m contains A(j:j+k1-1,j+1:j+k2)^T. So therefore we apply H from the right,\n *\n * [H*A]^T = A^T H^T = A^T H\n */\n\n *ptr = 1.0;\n gsl_linalg_householder_right(tau_j, &(c.vector), &(m.matrix), &(work.vector));\n *ptr = tmp;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_QR_band_unpack_L2 (const size_t p, const size_t q, const gsl_matrix * QRB, const gsl_vector * tau,\n gsl_matrix * Q, gsl_matrix * R)\n{\n const size_t M = Q->size1;\n const size_t N = QRB->size1;\n\n if (Q->size2 != M)\n {\n GSL_ERROR (\"Q matrix must be square\", GSL_ENOTSQR);\n }\n else if (R->size1 != M || R->size2 != N)\n {\n GSL_ERROR (\"R matrix must be M x N\", GSL_ENOTSQR);\n }\n else if (tau->size < GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be at least MIN(M,N)\", GSL_EBADLEN);\n }\n else if (QRB->size2 != 2*p + q + 1)\n {\n GSL_ERROR (\"dimensions of QRB are inconsistent with (p,q)\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* form matrix Q */\n gsl_matrix_set_identity (Q);\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n size_t k1 = GSL_MIN(p + 1, M - i); /* number of non-zero elements of this column, including diagonal element */\n gsl_vector_const_view h = gsl_matrix_const_subrow(QRB, i, p + q, k1);\n gsl_matrix_view m = gsl_matrix_submatrix (Q, i, i, k1, M - i);\n double ti = gsl_vector_get (tau, i);\n gsl_vector_view work = gsl_matrix_subcolumn(R, 0, 0, M - i);\n double * ptr = gsl_vector_ptr((gsl_vector *) &h.vector, 0);\n double tmp = *ptr;\n\n *ptr = 1.0;\n gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector);\n *ptr = tmp;\n }\n\n /* form matrix R */\n gsl_matrix_set_zero(R);\n\n for (i = 0; i <= GSL_MIN(p + q, N - 1); ++i)\n {\n gsl_vector_const_view src = gsl_matrix_const_subcolumn(QRB, p + q - i, i, GSL_MIN(M, N - i));\n gsl_vector_view dest = gsl_matrix_superdiagonal(R, i);\n gsl_vector_memcpy(&dest.vector, &src.vector);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "968c14fb4ad23025d33f53bf390aa5f492958f2b", "size": 6153, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_band.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_band.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_band.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": 32.5555555556, "max_line_length": 125, "alphanum_fraction": 0.5485129205, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.453677255512245}} {"text": "#include \n#include \n\n#include \n\nint main(void) {\n double x = 5.0;\n printf(\"J0(%g) = %.18e\\n\", x, gsl_sf_bessel_J0(x));\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "165f235c4380500eb245d56c4f9101ed467b9271", "size": 192, "ext": "c", "lang": "C", "max_stars_repo_path": "awesome/c_cpp/cpp-cheat/cmake/shared_lib_external/main.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/cmake/shared_lib_external/main.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/cmake/shared_lib_external/main.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.4545454545, "max_line_length": 55, "alphanum_fraction": 0.625, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6150878555160664, "lm_q1q2_score": 0.45341702632393965}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Fit\n *\n * y = X c\n *\n * where X is an n x p matrix of n observations for p variables.\n *\n * The solution includes a possible standard form Tikhonov regularization:\n *\n * c = (X^T X + lambda^2 I)^{-1} X^T y\n *\n * where lambda^2 is the Tikhonov regularization parameter.\n *\n * The function multifit_linear_svd() must first be called to\n * compute the SVD decomposition of X\n *\n * Inputs: X - least squares matrix\n * y - right hand side vector\n * tol - singular value tolerance\n * lambda - Tikhonov regularization parameter lambda;\n * ignored if <= 0\n * rank - (output) effective rank\n * c - (output) model coefficient vector\n * rnorm - (output) residual norm ||y - X c||\n * snorm - (output) solution norm ||c||\n * work - workspace\n *\n * Notes:\n * 1) The dimensions of X must match work->n and work->p which are set\n * by multifit_linear_svd()\n * 2) On input:\n * work->A contains U\n * work->Q contains Q\n * work->S contains singular values\n * 3) If this function is called from gsl_multifit_wlinear(), then\n * the input y points to work->t, which contains sqrt(W) y. Since\n * work->t is also used as scratch workspace by this function, we\n * do the necessary computations with y first to avoid problems.\n * 4) When lambda <= 0, singular values are truncated when:\n * s_j <= tol * s_0\n */\n\nstatic int\nmultifit_linear_solve (const gsl_matrix * X,\n const gsl_vector * y,\n const double tol,\n const double lambda,\n size_t * rank,\n gsl_vector * c,\n double *rnorm,\n double *snorm,\n gsl_multifit_linear_workspace * work)\n{\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (n != work->n || p != work->p)\n {\n GSL_ERROR(\"observation matrix does not match workspace\", GSL_EBADLEN);\n }\n else if (n != y->size)\n {\n GSL_ERROR(\"number of observations in y does not match matrix\",\n GSL_EBADLEN);\n }\n else if (p != c->size)\n {\n GSL_ERROR (\"number of parameters c does not match matrix\",\n GSL_EBADLEN);\n }\n else if (tol <= 0)\n {\n GSL_ERROR (\"tolerance must be positive\", GSL_EINVAL);\n }\n else\n {\n const double lambda_sq = lambda * lambda;\n\n double rho_ls = 0.0; /* contribution to rnorm from OLS */\n\n size_t j, p_eff;\n\n /* these inputs are previously computed by multifit_linear_svd() */\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_matrix_view Q = gsl_matrix_submatrix(work->Q, 0, 0, p, p);\n gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n\n /* workspace */\n gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p);\n gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p);\n gsl_vector_view D = gsl_vector_subvector(work->D, 0, p);\n gsl_vector_view t = gsl_vector_subvector(work->t, 0, n);\n\n /*\n * Solve y = A c for c\n * c = Q diag(s_i / (s_i^2 + lambda_i^2)) U^T y\n */\n\n /* compute xt = U^T y */\n gsl_blas_dgemv (CblasTrans, 1.0, &A.matrix, y, 0.0, &xt.vector);\n\n if (n > p)\n {\n /*\n * compute OLS residual norm = || y - U U^T y ||;\n * for n = p, U U^T = I, so no need to calculate norm\n */\n gsl_vector_memcpy(&t.vector, y);\n gsl_blas_dgemv(CblasNoTrans, -1.0, &A.matrix, &xt.vector, 1.0, &t.vector);\n rho_ls = gsl_blas_dnrm2(&t.vector);\n }\n\n if (lambda > 0.0)\n {\n /* xt <-- [ s(i) / (s(i)^2 + lambda^2) ] .* U^T y */\n for (j = 0; j < p; ++j)\n {\n double sj = gsl_vector_get(&S.vector, j);\n double f = (sj * sj) / (sj * sj + lambda_sq);\n double *ptr = gsl_vector_ptr(&xt.vector, j);\n\n /* use D as workspace for residual norm */\n gsl_vector_set(&D.vector, j, (1.0 - f) * (*ptr));\n\n *ptr *= sj / (sj*sj + lambda_sq);\n }\n\n /* compute regularized solution vector */\n gsl_blas_dgemv (CblasNoTrans, 1.0, &Q.matrix, &xt.vector, 0.0, c);\n\n /* compute solution norm */\n *snorm = gsl_blas_dnrm2(c);\n\n /* compute residual norm */\n *rnorm = gsl_blas_dnrm2(&D.vector);\n\n if (n > p)\n {\n /* add correction to residual norm (see eqs 6-7 of [1]) */\n *rnorm = sqrt((*rnorm) * (*rnorm) + rho_ls * rho_ls);\n }\n\n /* reset D vector */\n gsl_vector_set_all(&D.vector, 1.0);\n }\n else\n {\n /* Scale the matrix Q, QSI = Q S^{-1} */\n\n gsl_matrix_memcpy (&QSI.matrix, &Q.matrix);\n\n {\n double s0 = gsl_vector_get (&S.vector, 0);\n p_eff = 0;\n\n for (j = 0; j < p; j++)\n {\n gsl_vector_view column = gsl_matrix_column (&QSI.matrix, j);\n double sj = gsl_vector_get (&S.vector, j);\n double alpha;\n\n if (sj <= tol * s0)\n {\n alpha = 0.0;\n }\n else\n {\n alpha = 1.0 / sj;\n p_eff++;\n }\n\n gsl_vector_scale (&column.vector, alpha);\n }\n\n *rank = p_eff;\n }\n\n gsl_blas_dgemv (CblasNoTrans, 1.0, &QSI.matrix, &xt.vector, 0.0, c);\n\n /* Unscale the balancing factors */\n gsl_vector_div (c, &D.vector);\n\n *snorm = gsl_blas_dnrm2(c);\n *rnorm = rho_ls;\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "f65b06660806a68281a11e46b1ccf18d9d19c3cf", "size": 6012, "ext": "c", "lang": "C", "max_stars_repo_path": "C/AFMapTSComposite/linear_common.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/linear_common.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/linear_common.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": 30.5177664975, "max_line_length": 84, "alphanum_fraction": 0.5159680639, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4534122895441309}} {"text": "/*\n** Implementation of LISA algorithm\n** for statistical inference of fMRI images\n**\n** generic plug-in.\n** A file containing a list of all 3D permutation images must be supplied.\n**\n** G.Lohmann, April 2017\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern void VIsolatedVoxels(VImage src,float threshold);\nextern void VHistogram(gsl_histogram *histogram,VString filename);\nextern void VCheckImage(VImage src);\nextern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double alpha);\nextern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);\nextern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);\nextern double VImageVar(VImage src);\nextern void VImageCount(VImage src);\nextern void VGetHistRange(VImage src,double *hmin,double *hmax);\nextern float VGetMode(VImage src);\nextern void VZScale(VImage src,float mode,float stddev);\nextern void HistoUpdate(VImage,gsl_histogram *);\n\n\n\n\n/* make sure all input images are in float and have the same number of pixels */\nvoid CheckImageTypes(VImage zmap,VImage *permimages,int numperm)\n{\n size_t npixels = VImageNPixels(zmap);\n int i;\n for (i=0; i 0) {\n int tstperm = 30;\n if (tstperm > numperm) tstperm = numperm;\n double varsum=0,nx=0;\n for (nperm = 0; nperm < tstperm; nperm++) {\n zvar = VImageVar(zmap[nperm]);\n varsum += zvar;\n nx++;\n }\n double meanvar = varsum/nx;\n stddev = sqrt(meanvar);\n }\n\n\n /* get non-permuted hotspot map */\n float mode=0;\n if (centering) mode = VGetMode(zmap1);\n if (numperm > 0) VZScale(zmap1,mode,stddev);\n\n VImage dst1 = VCreateImageLike(zmap1);\n VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n\n\n /* ini histograms */\n VGetHistRange(dst1,&hmin,&hmax);\n size_t nbins = 20000;\n gsl_histogram *hist0 = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);\n gsl_histogram *histz = gsl_histogram_alloc (nbins);\n gsl_histogram_set_ranges_uniform (histz,hmin,hmax);\n HistoUpdate(dst1,histz);\n\n\n /* omp-stuff */\n#ifdef _OPENMP\n int num_procs=omp_get_num_procs();\n if (nproc > 0 && nproc < num_procs) num_procs = nproc;\n fprintf(stderr,\" using %d cores\\n\",(int)num_procs);\n omp_set_num_threads(num_procs);\n#endif /* _OPENMP */\n\n /* do random permutations */\n#pragma omp parallel for shared(zmap) schedule(dynamic)\n for (nperm = 0; nperm < numperm; nperm++) {\n if (nperm%20 == 0) fprintf(stderr,\" perm %4d of %d\\r\",nperm,(int)numperm);\n\n float mode=0;\n if (centering) mode = VGetMode(zmap[nperm]);\n VZScale(zmap[nperm],mode,stddev);\n\n VImage dst = VCreateImageLike (zmap1);\n VBilateralFilter(zmap[nperm],dst,(int)radius,(double)rvar,(double)svar,(int)numiter);\n\n #pragma omp critical\n {\n HistoUpdate(dst,hist0);\n }\n VDestroyImage(dst);\n }\n\n\n /* apply fdr */\n VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);\n if (numperm > 0) {\n FDR(dst1,fdrimage,hist0,histz,(double)alpha);\n\n if (cleanup && alpha < 1.0) {\n VIsolatedVoxels(fdrimage,(float)(1.0-alpha));\n }\n }\n\n\n /* output */\n VAttrList out_list = VCreateAttrList ();\n VHistory(VNumber(options),options,prg_name,&list,&out_list);\n VSetGeoInfo(geolist,out_list);\n VAppendAttr (out_list,\"image\",NULL,VImageRepn,fdrimage);\n if (! VWriteFile (out_file, out_list)) exit (1);\n fprintf (stderr, \"\\n%s: done.\\n\", argv[0]);\n exit(0);\n}\n", "meta": {"hexsha": "fbd22e3c8cdd006d52daa5987a7ada1c2434c3ba", "size": 6476, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_generic/vlisa_generic.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_generic/vlisa_generic.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_generic/vlisa_generic.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": 32.5427135678, "max_line_length": 121, "alphanum_fraction": 0.7032118592, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.45320963819081034}} {"text": "#include \n#include \n#include \n\n/* #include */\n#include \n\n#include \n#include \"org_bitbucket_ioplus_openblas_Lapacke.h\"\n\n\n/*\n * Class: org_bitbucket_ioplus_openblas_Lapacke\n * Method: sgetrf\n * Signature: (II[FI[I)V\n */\n JNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sgetrf\n (JNIEnv * env, jclass class,\n jint m, jint n, jfloatArray a, jint lda, jintArray ipiv){\n\n float *A;\n A = (*env)->GetPrimitiveArrayCritical(env, a, 0);\n int *IPIV;\n IPIV = (*env)->GetPrimitiveArrayCritical(env, ipiv, 0);\n\n LAPACKE_sgetrf(LAPACK_ROW_MAJOR,\n m, n, A, lda, IPIV);\n\n (*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, ipiv, IPIV, 0);\n\n\n }\n\n/*\n * Class: org_bitbucket_ioplus_openblas_Lapacke\n * Method: sgetri\n * Signature: (I[FI[I)V\n */\n JNIEXPORT void JNICALL\n Java_org_bitbucket_ioplus_openblas_Lapacke_sgetri\n (JNIEnv * env, jclass class,\n jint n, jfloatArray a, jint lda, jintArray ipiv){\n\n float *A;\n A = (*env)->GetPrimitiveArrayCritical(env, a, 0);\n int *IPIV;\n IPIV = (*env)->GetPrimitiveArrayCritical(env, ipiv, 0);\n\n LAPACKE_sgetri(LAPACK_ROW_MAJOR,\n n, A, lda, IPIV);\n\n (*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, ipiv, IPIV, 0);\n\n }\n\n\n\n/*\n * Class: org_bitbucket_ioplus_openblas_Lapacke\n * Method: sdeev\n * Signature: (CCI[FI[F[F[FI[FI)V\n */\nJNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sdeev\n(JNIEnv * env, jclass class,\n jchar jobvl,\n jchar jobvr,\n jint n,\n jfloatArray a,\n jint lda,\n jfloatArray wr,\n jfloatArray wi,\n jfloatArray vl,\n jint ldvl,\n jfloatArray vr,\n jint ldvr){\n /* jni args -> c mapping */\n\n float *A;\n float *WR;\n float *WI;\n float *VL;\n float *VR;\n\n A = (*env)->GetPrimitiveArrayCritical(env, a, 0);\n WR = (*env)->GetPrimitiveArrayCritical(env, wr, 0);\n WI = (*env)->GetPrimitiveArrayCritical(env, wi, 0);\n VL = (*env)->GetPrimitiveArrayCritical(env, vl, 0);\n VR = (*env)->GetPrimitiveArrayCritical(env, vr, 0);\n\n LAPACKE_sgeev(LAPACK_ROW_MAJOR,\n jobvl,\n jobvr,\n n,\n A,\n lda,\n WR, // values\n WI,\n VL,\n ldvl,\n VR, // vectors\n ldvr);\n\n (*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, wr, WR, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, wi, WI, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, vr, VR, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, vl, VL, 0);\n\n}\n\n\n\n/*\n * Class: org_bitbucket_ioplus_openblas_Lapacke\n * Method: sgehrd\n * Signature: (III[FI[F)V\n */\nJNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sgehrd\n(JNIEnv * env, jclass class,\n jint n,\n jint ilo,\n jint ihi,\n jfloatArray a,\n jint lda,\n jfloatArray tau\n ){\n float *A = (*env)->GetPrimitiveArrayCritical(env, a, NULL);\n float *TAU = (*env)->GetPrimitiveArrayCritical(env, tau, NULL);\n LAPACKE_sgehrd(LAPACK_ROW_MAJOR,n, ilo, ihi, A, lda, TAU);\n (*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, tau, TAU, 0);\n}\n\n/*\n * Class: org_bitbucket_ioplus_openblas_Lapacke\n * Method: shseqr\n * Signature: (CCIII[FI[F[F[FI)V\n */\nJNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_shseqr\n(JNIEnv * env, jclass class,\n jchar job,\n jchar compz,\n jint n,\n jint ilo,\n jint ihi,\n jfloatArray h,\n jint ldh,\n jfloatArray wr,\n jfloatArray wi,\n jfloatArray z,\n jint ldz){\n\n float *H = (*env)->GetPrimitiveArrayCritical(env, h, 0);\n float *WR = (*env)->GetPrimitiveArrayCritical(env, wr, 0);\n float *WI = (*env)->GetPrimitiveArrayCritical(env, wi, 0);\n float *Z = (*env)->GetPrimitiveArrayCritical(env, z, 0);\n\n LAPACKE_shseqr(LAPACK_ROW_MAJOR,\n job,\n compz,\n n,\n ilo,\n ihi,\n H,\n ldh,\n WR,\n WI,\n Z,\n ldz);\n\n (*env)->ReleasePrimitiveArrayCritical(env, h, H, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, wr, WR, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, wi, WI, 0);\n (*env)->ReleasePrimitiveArrayCritical(env, z, Z, 0);\n\n\n}\n", "meta": {"hexsha": "40b53c567591e9673697bb1afc581c88904c4b70", "size": 4617, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main/c/Lapacke.c", "max_stars_repo_name": "sidec/openblas-java", "max_stars_repo_head_hexsha": "026183a9dae6ffb01f4c2b2b4f185ffa96236057", "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/main/c/Lapacke.c", "max_issues_repo_name": "sidec/openblas-java", "max_issues_repo_head_hexsha": "026183a9dae6ffb01f4c2b2b4f185ffa96236057", "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/main/c/Lapacke.c", "max_forks_repo_name": "sidec/openblas-java", "max_forks_repo_head_hexsha": "026183a9dae6ffb01f4c2b2b4f185ffa96236057", "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.65, "max_line_length": 76, "alphanum_fraction": 0.6006064544, "num_tokens": 1340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4529757759769664}} {"text": "/* bspline/bspline.c\n * \n * Copyright (C) 2006 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n\n/*\n * This module contains routines related to calculating B-splines.\n * The algorithms used are described in\n *\n * [1] Carl de Boor, \"A Practical Guide to Splines\", Springer\n * Verlag, 1978.\n */\n\nstatic int bspline_eval_all(const double x, gsl_vector *B, size_t *idx,\n gsl_bspline_workspace *w);\n\nstatic inline size_t bspline_find_interval(const double x, int *flag,\n gsl_bspline_workspace *w);\n\n/*\ngsl_bspline_alloc()\n Allocate space for a bspline workspace. The size of the\nworkspace is O(5k + nbreak)\n\nInputs: k - spline order (cubic = 4)\n nbreak - number of breakpoints\n\nReturn: pointer to workspace\n*/\n\ngsl_bspline_workspace *\ngsl_bspline_alloc(const size_t k, const size_t nbreak)\n{\n if (k == 0)\n {\n GSL_ERROR_NULL(\"k must be at least 1\", GSL_EINVAL);\n }\n else if (nbreak < 2)\n {\n GSL_ERROR_NULL(\"nbreak must be at least 2\", GSL_EINVAL);\n }\n else\n {\n gsl_bspline_workspace *w;\n\n w = (gsl_bspline_workspace *)\n calloc(1, sizeof(gsl_bspline_workspace));\n if (w == 0)\n {\n GSL_ERROR_NULL(\"failed to allocate space for workspace\", GSL_ENOMEM);\n }\n\n w->k = k;\n w->km1 = k - 1;\n w->nbreak = nbreak;\n w->l = nbreak - 1;\n w->n = w->l + k - 1;\n\n w->knots = gsl_vector_alloc(w->n + k);\n if (w->knots == 0)\n {\n gsl_bspline_free(w);\n GSL_ERROR_NULL(\"failed to allocate space for knots vector\", GSL_ENOMEM);\n }\n\n w->deltal = gsl_vector_alloc(k);\n w->deltar = gsl_vector_alloc(k);\n if (!w->deltal || !w->deltar)\n {\n gsl_bspline_free(w);\n GSL_ERROR_NULL(\"failed to allocate space for delta vectors\", GSL_ENOMEM);\n }\n\n w->B = gsl_vector_alloc(k);\n if (w->B == 0)\n {\n gsl_bspline_free(w);\n GSL_ERROR_NULL(\"failed to allocate space for temporary spline vector\", GSL_ENOMEM);\n }\n\n return (w);\n }\n} /* gsl_bspline_alloc() */\n\n/* Return number of coefficients */\nsize_t\ngsl_bspline_ncoeffs (gsl_bspline_workspace * w)\n{\n return w->n;\n}\n\n/* Return order */\nsize_t\ngsl_bspline_order (gsl_bspline_workspace * w)\n{\n return w->k;\n}\n\n/* Return number of breakpoints */\nsize_t\ngsl_bspline_nbreak (gsl_bspline_workspace * w)\n{\n return w->nbreak;\n}\n\ndouble\ngsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w)\n{\n size_t j = i + w->k - 1;\n return gsl_vector_get(w->knots, j);\n}\n\n/*\ngsl_bspline_free()\n Free a bspline workspace\n\nInputs: w - workspace to free\n\nReturn: none\n*/\n\nvoid\ngsl_bspline_free(gsl_bspline_workspace *w)\n{\n if (!w)\n return;\n\n if (w->knots)\n gsl_vector_free(w->knots);\n\n if (w->deltal)\n gsl_vector_free(w->deltal);\n\n if (w->deltar)\n gsl_vector_free(w->deltar);\n\n if (w->B)\n gsl_vector_free(w->B);\n\n free(w);\n} /* gsl_bspline_free() */\n\n/*\ngsl_bspline_knots()\n Compute the knots from the given breakpoints:\n\nknots(1:k) = breakpts(1)\nknots(k+1:k+l-1) = breakpts(i), i = 2 .. l\nknots(n+1:n+k) = breakpts(l + 1)\n\nwhere l is the number of polynomial pieces (l = nbreak - 1) and\nn = k + l - 1\n(using matlab syntax for the arrays)\n\nThe repeated knots at the beginning and end of the interval\ncorrespond to the continuity condition there. See pg. 119\nof [1].\n\nInputs: breakpts - breakpoints\n w - bspline workspace\n\nReturn: success or error\n*/\n\nint\ngsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w)\n{\n if (breakpts->size != w->nbreak)\n {\n GSL_ERROR(\"breakpts vector has wrong size\", GSL_EBADLEN);\n }\n else\n {\n size_t i; /* looping */\n\n for (i = 0; i < w->k; ++i)\n gsl_vector_set(w->knots, i, gsl_vector_get(breakpts, 0));\n\n for (i = 1; i < w->l; ++i)\n {\n gsl_vector_set(w->knots, w->k - 1 + i,\n gsl_vector_get(breakpts, i));\n }\n\n for (i = w->n; i < w->n + w->k; ++i)\n gsl_vector_set(w->knots, i, gsl_vector_get(breakpts, w->l));\n\n return GSL_SUCCESS;\n }\n} /* gsl_bspline_knots() */\n\n/*\ngsl_bspline_knots_uniform()\n Construct uniformly spaced knots on the interval [a,b] using\nthe previously specified number of breakpoints. 'a' is the position\nof the first breakpoint and 'b' is the position of the last\nbreakpoint.\n\nInputs: a - left side of interval\n b - right side of interval\n w - bspline workspace\n\nReturn: success or error\n\nNotes: 1) w->knots is modified to contain the uniformly spaced\n knots\n\n 2) The knots vector is set up as follows (using octave syntax):\n\n knots(1:k) = a\n knots(k+1:k+l-1) = a + i*delta, i = 1 .. l - 1\n knots(n+1:n+k) = b\n*/\n\nint\ngsl_bspline_knots_uniform(const double a, const double b,\n gsl_bspline_workspace *w)\n{\n size_t i; /* looping */\n double delta; /* interval spacing */\n double x;\n\n delta = (b - a) / (double) w->l;\n\n for (i = 0; i < w->k; ++i)\n gsl_vector_set(w->knots, i, a);\n\n x = a + delta;\n for (i = 0; i < w->l - 1; ++i)\n {\n gsl_vector_set(w->knots, w->k + i, x);\n x += delta;\n }\n\n for (i = w->n; i < w->n + w->k; ++i)\n gsl_vector_set(w->knots, i, b);\n\n return GSL_SUCCESS;\n} /* gsl_bspline_knots_uniform() */\n\n/*\ngsl_bspline_eval()\n Evaluate the basis functions B_i(x) for all i. This is\nbasically a wrapper function for bspline_eval_all()\nwhich formats the output in a nice way.\n\nInputs: x - point for evaluation\n B - (output) where to store B_i(x) values\n the length of this vector is\n n = nbreak + k - 2 = l + k - 1 = w->n\n w - bspline workspace\n\nReturn: success or error\n\nNotes: The w->knots vector must be initialized prior to calling\n this function (see gsl_bspline_knots())\n*/\n\nint\ngsl_bspline_eval(const double x, gsl_vector *B,\n gsl_bspline_workspace *w)\n{\n if (B->size != w->n)\n {\n GSL_ERROR(\"B vector length does not match n\", GSL_EBADLEN);\n }\n else\n {\n size_t i; /* looping */\n size_t idx = 0;\n size_t start; /* first non-zero spline */\n\n /* find all non-zero B_i(x) values */\n bspline_eval_all(x, w->B, &idx, w);\n\n /* store values in appropriate part of given vector */\n\n start = idx - w->k + 1;\n for (i = 0; i < start; ++i)\n gsl_vector_set(B, i, 0.0);\n\n for (i = start; i <= idx; ++i)\n gsl_vector_set(B, i, gsl_vector_get(w->B, i - start));\n\n for (i = idx + 1; i < w->n; ++i)\n gsl_vector_set(B, i, 0.0);\n\n return GSL_SUCCESS;\n }\n} /* gsl_bspline_eval() */\n\n/****************************************\n * INTERNAL ROUTINES *\n ****************************************/\n\n/*\nbspline_eval_all()\n Evaluate all non-zero B-splines B_i(x) using algorithm (8)\nof chapter X of [1]\n\nThe idea is something like this. Given x \\in [t_i, t_{i+1}]\nwith t_i < t_{i+1} and the t_i are knots, the values of the\nB-splines not automatically zero fit into a triangular\narray as follows:\n 0\n 0\n0 B_{i-2,3}\n B_{i-1,2}\nB_{i,1} B_{i-1,3} ...\n B_{i,2}\n0 B_{i,3}\n 0\n 0\n\nwhere B_{i,k} is the ith B-spline of order k. The boundary 0s\nindicate that those B-splines not in the table vanish at x.\n\nTo compute the non-zero B-splines of a given order k, we use\nEqs. (4) and (5) of chapter X of [1]:\n\n(4) B_{i,1}(x) = { 1, t_i <= x < t_{i+1}\n 0, else }\n\n(5) B_{i,k}(x) = (x - t_i)\n ----------------- B_{i,k-1}(x)\n (t_{i+k-1} - t_i)\n\n t_{i+k} - x\n + ----------------- B_{i+1,k-1}(x)\n t_{i+k} - t_{i+1}\n\nSo (4) gives us the first column of the table and we can use\nthe recurrence relation (5) to get the rest of the columns.\n\nInputs: x - point at which to evaluate splines\n B - (output) where to store B-spline values (length k)\n idx - (output) B-spline function index of last output\n value (B_{idx}(x) is stored in the last slot of 'B')\n w - bspline workspace\n\nReturn: success or error\n\nNotes: 1) the w->knots vector must be initialized before calling\n this function\n\n 2) On output, B contains:\n\n B = [B_{i-k+1,k}, B_{i-k+2,k}, ..., B_{i-1,k}, B_{i,k}]\n\n where 'i' is stored in 'idx' on output\n\n 3) based on PPPACK bsplvb\n*/\n\nstatic int\nbspline_eval_all(const double x, gsl_vector *B, size_t *idx,\n gsl_bspline_workspace *w)\n{\n if (B->size != w->k)\n {\n GSL_ERROR(\"B vector not of length k\", GSL_EBADLEN);\n }\n else\n {\n size_t i; /* spline index */\n size_t j; /* looping */\n size_t ii; /* looping */\n int flag = 0; /* error flag */\n double saved;\n double term;\n\n i = bspline_find_interval(x, &flag, w);\n\n if (flag == -1)\n {\n GSL_ERROR(\"x outside of knot interval\", GSL_EINVAL);\n }\n else if (flag == 1)\n {\n if (x <= gsl_vector_get(w->knots, i) + GSL_DBL_EPSILON)\n {\n --i;\n }\n else\n {\n GSL_ERROR(\"x outside of knot interval\", GSL_EINVAL);\n }\n }\n\n *idx = i;\n\n gsl_vector_set(B, 0, 1.0);\n\n for (j = 0; j < w->k - 1; ++j)\n {\n gsl_vector_set(w->deltar, j,\n gsl_vector_get(w->knots, i + j + 1) - x);\n gsl_vector_set(w->deltal, j,\n x - gsl_vector_get(w->knots, i - j));\n\n saved = 0.0;\n\n for (ii = 0; ii <= j; ++ii)\n {\n term = gsl_vector_get(B, ii) /\n (gsl_vector_get(w->deltar, ii) +\n gsl_vector_get(w->deltal, j - ii));\n\n gsl_vector_set(B, ii,\n saved +\n gsl_vector_get(w->deltar, ii) * term);\n\n saved = gsl_vector_get(w->deltal, j - ii) * term;\n }\n\n gsl_vector_set(B, j + 1, saved);\n }\n\n return GSL_SUCCESS;\n }\n} /* bspline_eval_all() */\n\n/*\nbspline_find_interval()\n Find knot interval such that\n\n t_i <= x < t_{i + 1}\n\nwhere the t_i are knot values.\n\nInputs: x - x value\n flag - (output) error flag\n w - bspline workspace\n\nReturn: i (index in w->knots corresponding to left limit of interval)\n\nNotes: The error conditions are reported as follows:\n\nCondition Return value Flag\n--------- ------------ ----\nx < t_0 0 -1\nt_i <= x < t_{i+1} i 0\nt_{n+k-1} <= x l+k-1 +1\n*/\n\nstatic inline size_t\nbspline_find_interval(const double x, int *flag,\n gsl_bspline_workspace *w)\n{\n size_t i;\n\n if (x < gsl_vector_get(w->knots, 0))\n {\n *flag = -1;\n return 0;\n }\n\n /* find i such that t_i <= x < t_{i+1} */\n for (i = w->k - 1; i < w->k + w->l - 1; ++i)\n {\n const double ti = gsl_vector_get(w->knots, i);\n const double tip1 = gsl_vector_get(w->knots, i + 1);\n\n if (tip1 < ti)\n {\n GSL_ERROR(\"knots vector is not increasing\", GSL_EINVAL);\n }\n\n if (ti <= x && x < tip1)\n break;\n }\n\n if (i == w->k + w->l - 1)\n *flag = 1;\n else\n *flag = 0;\n\n return i;\n} /* bspline_find_interval() */\n", "meta": {"hexsha": "847a4984038702a5d283cba7d124b60510e30b14", "size": 12306, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/bspline/bspline.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/bspline/bspline.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/bspline/bspline.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.7108433735, "max_line_length": 93, "alphanum_fraction": 0.5555826426, "num_tokens": 3587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45258750103530154}} {"text": "#ifndef NumericalApproximation_h\n#define NumericalApproximation_h\n/** This is free and unencumbered software released into the public domain.\nThe authors of ISIS do not claim copyright on the contents of this file.\nFor more details about the LICENSE terms and the AUTHORS, you will\nfind files of those names at the top level of this repository. **/\n\n/* SPDX-License-Identifier: CC0-1.0 */\n\n#include \n#include \n#include \n#include \n#include \n#include \"IException.h\"\n\nusing namespace std;\n\nnamespace Isis {\n /**\n * @brief NumericalApproximation provides various numerical\n * analysis methods of interpolation, extrapolation and\n * approximation of a tabulated set of @a x, @a y data.\n *\n * This class contains a merged version of the Isis classes\n * @b DataInterp and @b NumericalMethods. In addition,\n * some methods from @b AtmosModel were moved to this class, the\n * @a CubicNeighborhood interpolation type was\n * adapted from the IDL routine called @b interpol (using the\n * \"/spline\" keyword), and several differentiation and\n * integration approximation methods were created.\n *\n * NumericalApproximation contains 9 types of data interpolation\n * routines. These routines act on x, y pairs of data points.\n * The following forms of data interpolation are supported:\n *\n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n *
NameType (enum)MinPointsDescription
Linear@a Linear2\n * Linear interpolation approximates a curve by\n * concatinating line segments between known data\n * points. This results in a continuous curve with a\n * discontinuities of the derivative at the known data\n * points. This interpolation type uses the GSL\n * library routines.\n *\n *
Polynomial@a Polynomial3\n * Computes a polynomial interpolation. This method\n * should only be used for interpolating small numbers\n * of points because polynomial interpolation introduces\n * large oscillations, even for well-behaved datasets.\n * The number of terms in the interpolating polynomial\n * is equal to the number of points. This interpolation\n * type uses the GSL library routines.\n *
Neville's Algorithm for Polynomial Interpolation@a PolynomialNeville3\n * Polynomial interpolation using Neville's algorithm. This\n * first fits a polynomial of degree 0 through each point.\n * On the second iteration, the polynomial of adjoining\n * indices are combined to fit through pairs of points.\n * This process repeats until a pyramid of approximations is\n * reached. This is based on the Newton form of the\n * interpolating polynomial and the recursion relation of\n * the divided differences.\n *
Natural Cubic Spline@a CubicNatural3\n * Cubic spline with natural boundary conditions. The\n * resulting curve is piecewise cubic on each interval\n * with matching first and second derivatives at the\n * supplied data points. The second derivative is chosen\n * to be zero at the endpoints, i.e. the first and last\n * points of the data set. This is also refered to as\n * free boundary condtions. This interpolation type uses\n * the GSL\n * library routines.\n *
Clamped Cubic Spline@a CubicClamped3\n * Cubic Spline interpolation with clamped boundary\n * conditions. The resulting curve is piecewise cubic on\n * each interval. For this type of boundary condition to\n * hold, it is necessary to have either the values of the\n * derivative at the endpoints or an accurate approximation\n * to those values. In general, clamped boundary conditions\n * lead to more accurate approximations since they include\n * more information about the function.\n *
Periodic Natural Cubic Spline@a CubicNatPeriodic2\n * Cubic spline with periodic boundary conditions. The\n * resulting curve is piecewise cubic on each interval\n * with matching first and second derivatives at the\n * supplied data points. The derivatives at the first\n * and last points are also matched. Note that the last\n * point in the data must have the same y-value as the\n * first point, otherwise the resulting periodic\n * interpolation will have a discontinuity at the\n * boundary. This interpolation type uses the GSL\n * library routines.\n *
Cubic Spline about 4-point Neighborhood@a CubicNeighborhood4\n * Cubic Spline interpolation using 4-pt Neighborhoods\n * with natural boundary conditions. This interpolation\n * type is adapted from the IDL interpol.pro application\n * using the \"/spline\" keyword on an irregular grid.\n * This type of cubic spline fits a natural cubic spline\n * to the 4-point neighborhood of known data points\n * surrounding the @a x value at which we wish to\n * evaluate. For example, suppose {@a x0,\n * @a x1, ..., @a xn} is the\n * array of known domain values in the data set and @f$\n * x_i \\leq u < x_{i+1} @f$ for some @e i such that\n * @f$ 0 \\leq i \\leq n @f$, then to evaluate the\n * @a y value at @e u, this method of interpolation\n * evaluates the ordinary cubic spline consisting of the\n * data set {@a xi-1, @a xi,\n * @a xi+1, @a xi+2} at\n * @e u.\n *
Cubic Spline using Hermite cubic polynomial@a CubicHermite2\n * Cubic Spline interpolation using the Hermite cubic\n * polynomial (also called the unique Hermite\n * interpolating fundamental polynomial of degree 3).\n * This method requires the input of the slopes of the\n * tangent lines of the curve (i.e. velocities, or first\n * derivatives) at each of the data points. This ensures\n * that the approximation has the same \"shape\" as the\n * curve at the known data points. This interpolation type\n * uses piecewise Hermite cubic polynomials for each\n * interval, (@a x0, @a x1), using\n * the known data points, (@a\n * x0,@a f(@a x0)) and\n * (@a x1,@a f(@a x1)), and their\n * derivatives,\n * @a f '(@a x0) and @a f '(@a\n * x1). The Hermite cubic polynomial is defined\n * @f[ H_3(x) =\n * f(x_0)h_0(x)+f(x_1)h_1(x)\n * +f\\prime(x_0)\\hat{h}_0(x)+f\\prime(x_1)\\hat{h}_1(x)\n * @f]\n * where\n * @f$ h_k(x) =\n * [1-2(x-x_k)L\\prime_k(x_k)](L_k(x))^2\n * @f$\n * and\n * @f$ \\hat{h}_k(x) =\n * (x-x_k)(L_k(x))^2\n * @f$\n * for the kth-Lagrange coefficient polynomials of degree\n * n = 1,\n * @f$ L_0(x) = \\frac{x- x_1}{x_0-x_1}@f$ and\n * @f$ L_1(x) = \\frac{x- x_0}{x_1-x_0}@f$.\n *\n *
Akima@a Akima5\n * Non-rounded Akima spline with natural boundary\n * conditions. This method uses non-rounded corner\n * algorithm of Wodicka. This interpolation type uses the\n * GSL library routines.\n *
Periodic Akima@a AkimaPeriodic5\n * Non-rounded Akima spline with periodic boundary\n * conditions. This method uses non-rounded corner\n * algorithm of Wodicka. This interpolation type uses\n * the GSL library routines.\n *
\n *\n *\n * Numerical analysis approximation methods for differentiating\n * and integrating unknown functions represented by a data set\n * are implemented by using the interpolations on the data set\n * created with a NumericalApproximation object. The Lagrange polynomial,\n * @f[ L(x) =\n * \\sum_{k=0}^{n} \\left(f(x_k) \\prod_{i=0,i \\neq k}^{n}\n * \\frac{x- x_i}{x_k-x_i}\\right)\n * @f]\n * is used to determine formulas for numerical differentiation\n * and integration.\n * @n\n * @b Numerical Differentiation\n * @n\n * The differentiation methods use difference formulas to\n * approximate first and second derivatives at a domain value\n * for a given a set of known (@a x,@a y) data points. Once all\n * of the data points are added, a Isis::NumericalApproximation\n * interpolation is used on the dataset to estimate the\n * function, @f$f:x \\to y@f$, mapping @a x values to\n * corresponding @a y values. Then, the derivative of\n * @e f evaluated at @a x0 is approximated.\n * To do so, a uniform step size of @a h is chosen to\n * determine the distance between @a xi and @a\n * xi+1.\n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n *
Differentiation methods require the parameters\n * @a a (domain value at which the derivative will be\n * evaluated), @a n (number of points used in the difference\n * formula), and @a h (step size of points). Note: @a a\n * is denoted @a x0 in the above formulas.\n *
Numerical Differentiation TypeDifference FormulasMethods AvailableDescription
Backward Difference \n *
    \n *
  • 2-point backward difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{h}[f(x_0) - f(x_0 - h)]\n * @f]\n *
  • 3-point backward difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{2h}[3f(x_0) - 4f(x_0 - h) +\n * f(x_0 - 2h)]\n * @f]\n *
  • 3-point backward second difference.\n * @f[\n * f\\prime\\prime(x_0) \\approx \\frac{1}{h^2}[f(x_0)\n * - 2f(x_0 - h) + f(x_0 - 2h)]\n * @f]\n *
\n *
\n *
    \n *
  • BackwardFirstDifference()\n *
  • BackwardSecondDifference()\n *
\n *
\n * Backward difference formulas use a uniform step-size\n * moving in the negative direction from the\n * given @a x0. These formulas are derived\n * by differentiating the Lagrange polynomials for\n * @a xi = @a x0 - @a ih\n * and evaluating them at@a x0.\n *
Forward Difference \n *
    \n *
  • 2-point forward difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{h}[f(x_0 + h) - f(x_0)]\n * @f]\n *
  • 3-point forward difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{2h}[-f(x_0 + 2h) +\n * 4f(x_0 + h) - 3f(x_0)]\n * @f]\n *
  • 3-point forward second difference.\n * @f[\n * f\\prime\\prime(x_0) \\approx \\frac{1}{h^2}[f(x_0 +\n * 2h) - 2f(x_0 + h) + f(x_0)]\n * @f]\n *
\n *
\n *
    \n *
  • ForwardFirstDifference()\n *
  • ForwardSecondDifference()\n *
\n *
\n * Forward difference formulas use a uniform step-size\n * moving in the positive direction from\n * @a x0. These formulas are derived by\n * differentiating the Lagrange polynomials for\n * @a xi = @a x0 + @a ih\n * and evaluating them at@a x0.\n *
Center Difference \n *
    \n *
  • 3-point center difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{2h}[f(x_0 + h) -\n * f(x_0 - h)]\n * @f]\n *
  • 5-point center difference.\n * @f[\n * f\\prime(x_0) \\approx \\frac{1}{12h}[-f(x_0 + 2h) +\n * 8f(x_0 +h) - 8f(x_0 - h) + f(x_0 - 2h)]\n * @f]\n *
  • 3-point center second difference.\n * @f[\n * f\\prime\\prime(x_0) \\approx \\frac{1}{h^2}[f(x_0 + h)\n * - 2f(x_0) + f(x_0 - h)]\n * @f]\n *
  • 5-point center second difference.\n * @f[\n * f\\prime\\prime(x_0) \\approx \\frac{1}{12h^2}[-f(x_0 +\n * 2h) + 16f(x_0 +h) - 30f(x_0) + 16f(x_0 - h) - f(x_0\n * - 2h)]\n * @f]\n *
\n *
\n *
    \n *
  • CenterFirstDifference()\n *
  • CenterSecondDifference()\n *
\n *
\n * Center difference formulas use a uniform step-size\n * moving in both directions from @a x0 so this\n * point stays centered. These formulas are derived by\n * differentiating the Lagrange polynomials for\n * @a xi = @a x0\n * + (@e i - (@a n - 1)/2)@a h and evaluating them\n * at @a x0.\n *
GSL Differentiation Unknown \n *
    \n *
  • GslFirstDerivative()\n *
  • GslSecondDerivative()\n *
\n *
\n * No documentation was found about the algorithms used\n * for these methods. They may only be called when\n * interpolation type is one of the following: @a Linear,\n * @a Polynomial, @a CubicNatural, @a CubicNatPeriodic, @a Akima, or\n * @a AkimaPeriodic.\n *
\n * @n\n * @b Numerical Integration\n * @n\n * The integration methods were derived using\n * @b Newton-Cotes, or @a quadrature, formulas for\n * approximating integrals given a set of known (@a x,@a y)\n * data points. The @a x values may be irregularly spaced, but\n * must be unique and added to the dataset in ascending order.\n * Once all of the data points are added, a\n * Isis::NumericalApproximation interpolation is used on\n * the dataset to estimate the function, @f$f:x \\to y@f$,\n * mapping @a x values to corresponding @a y values.\n * Then, the integral of @e f on the interval from @a a\n * to @a b is approximated. To do so, an algorithm for creating\n * a composite formula by applying the original formula to\n * segments that share a boundary point is used. The\n * NumericalApproximation::InterpType chosen for\n * interpolation computation seems to have little affect on the\n * error between the actual integral and the return values of\n * the integration methods. The BoolesRule() method varies the\n * most in error. Although errors are not high for any of the\n * interpolation types,\n * @a CubicNatural spline interpolations seem to\n * have the smallest error most often with BoolesRule(). For any\n * other numerical integration method, the errors appear to be\n * identical for any NumericalApproximation::InterpType except\n * @a Polynomial, which usually has a slightly larger\n * error than the other interpolation types. Note: A portion of\n * this algorithm is derived from the IDL function int_tabulated\n * for Boole's Method.\n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n * \n *
Integration methods require the parameters @a a,\n * @a b (interval of domain over which to integrate).\n *
Numerical Integration TypeIntegration FormulasMethods AvailableDescription
Trapezoidal Rule\n *
    \n *
  • 2-point Newton-Cotes trapezoidal rule:\n * @f[\n * \\int_{a}^b f(x)dx \\approx \\frac{h}{2}[f(a) + f(b)]\n * @f]\n * where @e h = @a b - @a a.\n *
\n *
\n *
    \n *
  • TrapezoidalRule()\n *
\n *
\n * The 2-point closed rule, known as the trapezoidal\n * rule, uses straight line segments between known data\n * points to estimate the area under the curve (integral).\n * This Newton-Cotes formula uses a uniform step-size of\n * @e h = @a b - @a a and is derived by integrating the\n * Lagrange polynomials over the closed interval [@a a,\n * @a a+h] for @a xi =\n * @a x0 + @e ih.\n *
Simpson's Rule, or Simpson's 3-Point Rule \n *
    \n *
  • 3-point Newton-Cotes, Simpson's Rule\n * @f[\n * \\int_{a}^b f(x)dx \\approx \\frac{h}{3}[f(a) +\n * 4f(a+h) + f(a+2h)]\n * @f]\n * where @e h = (@a b - @a a)/2.\n *
\n *
\n *
    \n *
  • Simpsons3PointRule()\n *
\n *
\n * The 3-point closed rule, known as Simpson's Rule or\n * Simpson's 3-Point Rule, uses parabolic arcs between\n * known data points to estimate the area under the curve\n * (integral). This Newton-Cotes formula uses a uniform\n * step-size of @e h = (@a b - @a a)/2 and is derived by\n * integrating the Lagrange polynomials over the closed\n * interval [@a a, @a a+2h] for @a xi =\n * @a x0 + @e ih.\n *
Simpson's 3/8 Rule, or Simpson's 4-Point Rule \n *
    \n *
  • 4-point Newton-Cotes, Simpson's 3/8 Rule\n * @f[\n * \\int_{a}^b f(x)dx \\approx \\frac{3h}{8}[f(a) +\n * 3f(a+h) + 3f(a+2h) + f(a+3h)]\n * @f]\n * where @e h = (@a b - @a a)/3.\n *
\n *
\n *
    \n *
  • Simpsons4PointRule()\n *
\n *
\n * The 4-point closed rule, known as Simpson's 3/8 Rule or\n * Simpson's 4-Point Rule, uses cubic curves between\n * known data points to estimate the area under the curve\n * (integral). This Newton-Cotes formula uses a uniform\n * step-size of @e h = (@a b - @a a)/3 and is derived by\n * integrating the Lagrange polynomials over the closed\n * interval [@a a, @a a+3h] for @a xi =\n * @a x0 + @e ih.\n *
Boole's Rule \n *
    \n *
  • 5-point Newton-Cotes, Boole's Rule\n * @f[\n * \\int_{a}^b f(x)dx \\approx \\frac{2h}{45}[7f(a) +\n * 32f(a+h) + 12f(a+2h) + 32f(a+3h) + 7f(a+4h)]\n * @f]\n * where @e h = (@a b - @a a)/4.\n *
\n *
\n *
    \n *
  • BoolesRule()\n *
\n *
\n * The 5-point closed rule, known as Boole's Rule, uses\n * quartic curves between known data points to estimate\n * the area under the curve (integral). This Newton-Cotes\n * formula uses a uniform step-size of @e h = (@a b -\n * @a a)/4 and is derived by integrating the Lagrange\n * polynomials over the closed interval [@a a, @a a+4h]\n * for @a xi = @a x0 +\n * @a ih.\n *
Refinements of Extended Trapezoidal Rule \n *
    \n *
  • Extended closed trapezoidal rule\n * @f[\n * \\int_{a}^b f(x)dx \\approx h[\\frac12 f(x_0) +\n * f(x_1) + ... + f(x_{n-2} + \\frac12\n * f(x_{n-1})]\n * @f]\n * where @e h = (@a b - @a a)/4, @a x0 =\n * @a a, and @a xn-1 = @a b.\n *
\n *
\n *
    \n *
  • RefineExtendedTrap()\n *
\n *
\n * The extended (or composite) trapezoidal rule can be\n * used to with a series of refinements to approximate the\n * integral. The first stage of refinement returns the\n * ordinary trapezoidal estimate of the integral.\n * Subsequent stages will improve the accuracy, where, for\n * the @a nth stage 2@a n-2 interior\n * points are added.\n *
Romberg's Method \n *
    \n *
  • Romberg's Method for Integration
\n *
    \n *
  • RombergsMethod()\n *
\n *
\n * Romberg's Method is a potent numerical integration\n * tool. It uses the extended trapezoidal rule and\n * Neville's algorithm for polynomial interpolation.\n *
GSL Integration Unknown \n *
    \n *
  • GslIntegral()\n *
\n *
\n * No documentation was found about the algorithm used for\n * this methods. They may only be called when\n * interpolation type is one of the following: @a Linear,\n * @a Polynomial, @a CubicNatural, @a CubicNatPeriodic, @a Akima, or\n * @a AkimaPeriodic.\n *
\n *\n *\n * Below is an example demonstating the use of this class:\n * @code\n * inline double f(double x) { return (x + cos ((x * x))); }\n *\n * NumericalApproximation\n * spline(NumericalApproximation::CubicClamped);\n * for (int x = 0; x < 200 ; x++) {\n * spline.addPoint(x, f(x));\n * }\n * spline.SetCubicClampedEndptDeriv(0,0);\n * double yinterp = spline.Evaluate(50.7);\n * double yextrap =\n * spline.Evaluate(201,NumericalApproximation::Extrapolate);\n * double deriv = spline.CenterFirstDifference(10);\n * double integ =\n * spline.RombergsMethod(spline.DomainMinimum(),spline.DomainMaximum());\n * @endcode\n *\n * To compute the same data set using the Akima spline, just use the following:\n * @code\n * spline.Reset(NumericalApproximation::Akima);\n * double yinterp = spline.Evaluate(50.7);\n * double yextrap =\n * spline.Evaluate(201,NumericalApproximation::NearestEndpoint);\n * double deriv = spline.CenterFirstDifference(10);\n * double integ =\n * spline.RombergsMethod(spline.DomainMinimum(),spline.DomainMaximum());\n * @endcode\n *\n *

Caveats

\n * When using this class, there are some important details that\n * require consideration. Several interpolation types of this\n * class use the GSL library. In addition, the GSL library\n * default error handling scheme has implications when used in\n * C++ objects. The default behavior is to terminate the\n * application when an error occurs. Options for developers are\n * to turn off error trapping within the GSL, which means users\n * of the library must do their own error checking, or a\n * specific handler can be specified to replace the default\n * mode. Neither option is well suited in object-oriented\n * implementations because they apply globally, to all users of\n * the library. The approach used here is to turn off error\n * handling and require users to handle their own error\n * checking. This is not entirely safe as any user that does\n * not follow this strategy could change this behavior at\n * runtime. Other options should be explored. An additional\n * option is that the default behavior can be altered prior to\n * building GSL but this is also problematic since this behavior\n * cannot be guaranteed universally.\n *\n * For these types, interpolation is strictly adhered to and\n * extrapolation is not handled well. If the input to be\n * evaluated is outside of the\n * minimum and maximum @a x values of the original data\n * points, then the @a y value corresponding to the\n * @a x value that is nearest to that input is returned.\n * However, for sufficiently close values, the clamped cubic and\n * polynomial Neville's types are fairly accurate in their\n * extrapolation techniques. All differentiation and\n * integration methods throw an error if the value passed is\n * outside of the domain.\n *\n * @ingroup Math\n * @author 2008-11-05 Janet Barrett, Kris Becker, K Teal\n * Thompson, Jeannie Walldren\n * @internal\n * @history 1999-08-11 K Teal Thompson - Original version of\n * NumericalMethods subroutines in Isis2.\n * @history 2006-06-14 Kris Becker - Created DataInterp class\n * @history 2007-02-20 Janet Barrett - Created NumericalMethods\n * class from Isis2 subroutines\n * @history 2007-02-20 Janet Barrett - Created AtmosModel class\n * from Isis2 subroutines\n * @history 2008-06-18 Christopher Austin - Fixed documentation\n * for DataInterp\n * @history 2008-06-18 Steven Koechle - Updated NumericalMethods\n * unitTest.\n * @history 2008-11-05 Jeannie Walldren - Merged DataInterp\n * class, NumericalMethods class, and methods from\n * AtmosModel. Modified methods from various classes\n * to be able to function similarly. Added InterpType\n * @a CubicNeighborhood, difference formula methods, and\n * integration methods. Created new unitTest.\n * @history 2008-11-12 Jeannie Walldren - Fixed documentation.\n * @history 2008-12-18 Jeannie Walldren - Added address\n * operator (&) to input variables of type vector,\n * NumericalApproximation::InterpType, and\n * NumericalApproximation::ExtrapType in\n * Constructors, AddData(), Evaluate(),\n * ValueToExtrapolate(), EvaluateCubicNeighborhood(),\n * @history 2009-01-26 Jeannie Walldren - Fixed error\n * documentation.\n * @history 2009-02-12 Jeannie Walldren - Fixed documentation\n * to include weblinks.\n * @history 2009-07-17 Steven Lambright - Added algorithm include,\n * removed macro MAX\n * @history 2009-06-10 Jeannie Walldren - Added interpolation\n * type CubicHermite. This involved modifying some\n * methods, as well as adding variable p_fprimeOfx\n * and methods AddCubicHermiteDeriv() and\n * EvaluateCubicHermite(). Added Contains() method.\n * @history 2009-07-02 Jeannie Walldren - Replaced Hermite\n * interpolation algorithm with simpler version and\n * added methods EvaluateCubicHermiteFirstDeriv and\n * EvaluateCubicHermiteSecDeriv\n * @history 2009-07-09 Debbie Cook - Finished Jeannie's\n * modifications.\n * @history 2009-08-03 Jeannie Walldren - Clean up code,\n * documentation and check in changes from\n * 2009-06-10, 2009-07-02, 2009-07-09\n * @history 2010-07-21 Sharmila Prasad - Remove doxygen documentation\n * warnings\n * @history 2010-12-06 Steven Lambright - Optimized AddData(vector, vector),\n * AddCubicHermiteDeriv(vector), and Init() which causes a\n * very significant increase in performance when constructing a lot\n * or adding a lot of data.\n */\n\n class NumericalApproximation {\n public:\n /**\n * This enum defines the types of interpolation supported in this class\n */\n enum InterpType { Linear, //!< Linear interpolation.\n Polynomial, //!< Polynomial interpolation.\n PolynomialNeville, //!< Polynomial interpolation using Neville's algorithm.\n CubicNatural, //!< Cubic Spline interpolation with natural boundary conditions.\n CubicClamped, //!< Cubic Spline interpolation with clamped boundary conditions.\n CubicNatPeriodic, //!< Cubic Spline interpolation with periodic boundary conditions.\n CubicNeighborhood, //!< Cubic Spline interpolation using 4-pt Neighborhoods with natural boundary conditions.\n CubicHermite, //!< Cubic Spline interpolation using the Hermite cubic polynomial.\n Akima, //!< Non-rounded Akima Spline interpolation with natural boundary conditions.\n AkimaPeriodic //!< Non-rounded Akima Spline interpolation with periodic boundary conditions.\n };\n\n // CONSTRUCTORS\n NumericalApproximation(const NumericalApproximation::InterpType &itype = CubicNatural);\n NumericalApproximation(unsigned int n, double *x, double *y,\n const NumericalApproximation::InterpType &itype = CubicNatural);\n NumericalApproximation(const vector &x, const vector &y,\n const NumericalApproximation::InterpType &itype = CubicNatural);\n NumericalApproximation(const NumericalApproximation &dint);\n // ASSIGNMENT OPERATOR\n NumericalApproximation &operator=(const NumericalApproximation &numApMeth);\n // DESTRUCTOR\n virtual ~NumericalApproximation();\n\n\n // ACCESSOR METHODS FOR OBJECT PROPERTIES\n string Name() const;\n /**\n * @brief Returns the enumerated type of interpolation chosen\n *\n * This method can be selected after all the points are added in the\n * interpolation by using Compute() method.\n * Note that this prints out as an integer representaion of the\n * enumerated type:\n *
    \n *
  • Linear = 0\n *
  • Polynomial = 1\n *
  • PolynomialNeville = 2\n *
  • CubicNatural = 3\n *
  • CubicClamped = 4\n *
  • CubicNatPeriodic = 5\n *
  • CubicNeighborhood = 6\n *
  • CubicHermite = 7\n *
  • Akima = 8\n *
  • AkimaPeriodic = 9\n *
\n *\n * @return NumericalApproximation::InterpType Currently assigned\n * interpolation type\n */\n inline InterpType InterpolationType() {\n return (p_itype);\n }\n int MinPoints();\n int MinPoints(NumericalApproximation::InterpType itype);\n\n // ADD DATA TO OBJECT\n void AddData(const double x, const double y);\n void AddData(unsigned int n, double *x, double *y);\n void AddData(const vector &x, const vector &y);\n void SetCubicClampedEndptDeriv(const double yp1, const double ypn);\n void AddCubicHermiteDeriv(unsigned int n, double *fprimeOfx);\n void AddCubicHermiteDeriv(const vector &fprimeOfx);\n void AddCubicHermiteDeriv(const double fprimeOfx);\n\n //ACCESSOR METHODS AFTER DATA IS ENTERED\n double DomainMinimum();\n double DomainMaximum();\n bool Contains(double x);\n /**\n * Returns the number of the coordinates added to the data set.\n *\n * @return @b unsigned @b int Size of data set.\n */\n inline unsigned int Size() {\n return(p_x.size());\n }\n\n /**\n * This enum defines the manner in which a value outside of the\n * domain should be handled if passed to the Evaluate() method.\n */\n enum ExtrapType { ThrowError, //!< Evaluate() throws an error if @a a is outside of the domain.\n Extrapolate, //!< Evaluate() attempts to extrapolate if @a a is outside of the domain.\n //!< This is only valid for NumericalApproximation::InterpType @a CubicClamped or @a PolynomialNeville\n //!< and the result will be accurate only if sufficiently close to the domain boundary.\n NearestEndpoint //!< Evaluate() returns the y-value of the nearest endpoint if @a a is outside of the domain.\n };\n // INTERPOLATION AND EXTRAPOLATION RESULTS\n double Evaluate(const double a, const ExtrapType &etype = ThrowError);\n vector Evaluate(const vector &a, const ExtrapType &etype = ThrowError);\n vector PolynomialNevilleErrorEstimate();\n vector CubicClampedSecondDerivatives();\n double EvaluateCubicHermiteFirstDeriv(const double a);\n double EvaluateCubicHermiteSecDeriv(const double a);\n\n // DIFFERENTIATION METHODS\n double GslFirstDerivative(const double a);\n double BackwardFirstDifference(const double a, const unsigned int n = 3,\n const double h = 0.1);\n double ForwardFirstDifference(const double a, const unsigned int n = 3,\n const double h = 0.1);\n double CenterFirstDifference(const double a, const unsigned int n = 5,\n const double h = 0.1);\n\n double GslSecondDerivative(const double a);\n double BackwardSecondDifference(const double a, const unsigned int n = 3,\n const double h = 0.1);\n double ForwardSecondDifference(const double a, const unsigned int n = 3,\n const double h = 0.1);\n double CenterSecondDifference(const double a, const unsigned int n = 5,\n const double h = 0.1);\n\n // INTERGRATION METHODS\n double GslIntegral(const double a, const double b);\n double TrapezoidalRule(const double a, const double b);\n double Simpsons3PointRule(const double a, const double b);\n double Simpsons4PointRule(const double a, const double b);\n double BoolesRule(const double a, const double b);\n double RefineExtendedTrap(double a, double b, double s, unsigned int n);\n double RombergsMethod(double a, double b);\n\n // ASSIGNMENT OPERATORS\n void Reset();\n void Reset(NumericalApproximation::InterpType itype);\n void SetInterpType(NumericalApproximation::InterpType itype);\n\n protected:\n // == CLASS VARIABLES\n // VARIABLES FOR ALL INTERP TYPES\n InterpType p_itype; //!< Interpolation type\n vector p_x; //!< List of X values\n vector p_y; //!< List of Y values\n bool p_dataValidated; //!< Flag variable to determine whether ValidateDataSet() has been called\n // GSL INTERP VARIABLES\n typedef const gsl_interp_type *InterpFunctor; //!< GSL Interpolation specs\n typedef map FunctorList; //!< Set up a std::map of GSL interpolator functors. List of function types\n typedef FunctorList::const_iterator FunctorConstIter; //!< GSL Iterator\n gsl_interp_accel *p_acc; //!< Lookup accelorator\n gsl_spline *p_interp; //!< Currently active interpolator\n static FunctorList p_interpFunctors; //!< Maintains list of interpolator options\n // CUBIC CLAMPED VARIABLES\n bool p_clampedEndptsSet; //!< Flag variable to determine whether SetCubicClampedEndptDeriv() has been called after all data was added for @a CubicClamped interpolation.\n bool p_clampedComputed; //!< Flag variable to determine whether ComputeCubicClamped() has been called.\n double p_clampedDerivFirstPt; //!< First derivative of first x-value, p_x[0]. This is only used for the @a CubicClamped interpolation type.\n double p_clampedDerivLastPt; //!< First derivative of last x-value, p_x[n-1]. This is only used for the @a CubicClamped interpolation type.\n vector p_clampedSecondDerivs; //!< List of second derivatives evaluated at p_x values. This is only used for the @a CubicClamped interpolation type.\n // POLYNOMIAL NEVILLE VARIABLES\n vector p_polyNevError; //!< Estimate of error for interpolation evaluated at x. This is only used for the @a PolynomialNeville interpolation type. 91 taken from AtmosModel.\n // CUBIC HERMITE VARIABLES\n vector p_fprimeOfx; //!< List of first derivatives corresponding to each x value in the data set (i.e. each value in p_x)\n\n\n // == PROTECTED METHODS\n // CREATING, DESTROYING OBJECT\n void Init(NumericalApproximation::InterpType itype);\n bool GslInterpType(NumericalApproximation::InterpType itype) const;\n void GslAllocation(unsigned int npoints);\n void GslDeallocation();\n InterpFunctor GslFunctor(NumericalApproximation::InterpType itype) const;\n // VERIFICATION METHODS\n void GslIntegrityCheck(int gsl_status, const char *src,\n int line);\n void ValidateDataSet();\n bool InsideDomain(const double a);\n // COMPUTATION AND EVALUATION METHODS\n bool GslComputed() const;\n void ComputeGsl();\n void ComputeCubicClamped();\n double ValueToExtrapolate(const double a, const ExtrapType &etype);\n double EvaluateCubicNeighborhood(const double a);\n vector EvaluateCubicNeighborhood(const vector &a, const ExtrapType &etype);\n double EvaluateCubicClamped(const double a);\n double EvaluateCubicHermite(const double a);\n double EvaluatePolynomialNeville(const double a);\n vector EvaluateForIntegration(const double a, const double b,\n const unsigned int n);\n int FindIntervalLowerIndex(const double a);\n // STANDARDIZE ERRORS\n void ReportException(IException::ErrorType type, const string &method,\n const string &message, const char *filesrc,\n int lineno) const;\n };\n};\n\n#endif\n", "meta": {"hexsha": "d6a6f7060fb097a14169d99d5d010efb5689b22c", "size": 39603, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h", "max_stars_repo_name": "kdl222/ISIS3", "max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 134.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z", "max_issues_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h", "max_issues_repo_name": "kdl222/ISIS3", "max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3825.0, "max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z", "max_forks_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h", "max_forks_repo_name": "jlaura/isis3", "max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 164.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z", "avg_line_length": 43.187568157, "max_line_length": 210, "alphanum_fraction": 0.5738706664, "num_tokens": 10969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45258750103530154}} {"text": "/* robust_wfun.c\n * \n * Copyright (C) 2013 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n/* default tuning constants */\n#define TUNING_BISQUARE (4.685)\n#define TUNING_CAUCHY (2.385)\n#define TUNING_FAIR (1.4)\n#define TUNING_HUBER (1.345)\n#define TUNING_OLS (1.0)\n#define TUNING_WELSCH (2.985)\n\n/*\n * Note: for each of the weighting functions below, it\n * is safe to call them with in-place parameters, so that\n * input/output vectors are the same\n */\n\nstatic int\nbisquare(const gsl_vector *r, gsl_vector *w)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n if (fabs(ri) < 1.0)\n gsl_vector_set(w, i, (1.0 - ri*ri)*(1.0 - ri*ri));\n else\n gsl_vector_set(w, i, 0.0);\n }\n\n return GSL_SUCCESS;\n} /* bisquare() */\n\nstatic int\nbisquare_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n if (fabs(ri) < 1.0)\n gsl_vector_set(dpsi, i, (1.0 - ri*ri)*(1.0 - 5.0*ri*ri));\n else\n gsl_vector_set(dpsi, i, 0.0);\n }\n\n return GSL_SUCCESS;\n} /* bisquare_dpsi() */\n\nstatic const gsl_multifit_robust_type bisquare_type = {\n \"bisquare\",\n &bisquare,\n &bisquare_dpsi,\n TUNING_BISQUARE\n};\n\nstatic int\ncauchy(const gsl_vector *r, gsl_vector *w)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n gsl_vector_set(w, i, 1.0 / (1.0 + ri*ri));\n }\n\n return GSL_SUCCESS;\n} /* cauchy() */\n\nstatic int\ncauchy_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n double rsq = ri * ri;\n\n gsl_vector_set(dpsi, i, (1 - rsq) / (1.0 + rsq) / (1.0 + rsq));\n }\n\n return GSL_SUCCESS;\n} /* cauchy_dpsi() */\n\nstatic const gsl_multifit_robust_type cauchy_type = {\n \"cauchy\",\n &cauchy,\n &cauchy_dpsi,\n TUNING_CAUCHY\n};\n\nstatic int\nfair(const gsl_vector *r, gsl_vector *w)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n gsl_vector_set(w, i, 1.0 / (1.0 + fabs(ri)));\n }\n\n return GSL_SUCCESS;\n} /* fair() */\n\nstatic int\nfair_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n gsl_vector_set(dpsi, i, 1.0 / (1.0 + fabs(ri)) / (1.0 + fabs(ri)));\n }\n\n return GSL_SUCCESS;\n} /* fair_dpsi() */\n\nstatic const gsl_multifit_robust_type fair_type = {\n \"fair\",\n &fair,\n &fair_dpsi,\n TUNING_FAIR\n};\n\nstatic int\nhuber(const gsl_vector *r, gsl_vector *w)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double absri = fabs(gsl_vector_get(r, i));\n\n if (absri <= 1.0)\n gsl_vector_set(w, i, 1.0);\n else\n gsl_vector_set(w, i, 1.0 / absri);\n }\n\n return GSL_SUCCESS;\n} /* huber() */\n\nstatic int\nhuber_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n if (fabs(ri) <= 1.0)\n gsl_vector_set(dpsi, i, 1.0);\n else\n gsl_vector_set(dpsi, i, 0.0);\n }\n\n return GSL_SUCCESS;\n} /* huber_dpsi() */\n\nstatic const gsl_multifit_robust_type huber_type = {\n \"huber\",\n &huber,\n &huber_dpsi,\n TUNING_HUBER\n};\n\nstatic int\nols(const gsl_vector *r, gsl_vector *w)\n{\n gsl_vector_set_all(w, 1.0);\n\n return GSL_SUCCESS;\n}\n\nstatic int\nols_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n gsl_vector_set_all(dpsi, 1.0);\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_multifit_robust_type ols_type = {\n \"ols\",\n &ols,\n &ols_dpsi,\n TUNING_OLS\n};\n\nstatic int\nwelsch(const gsl_vector *r, gsl_vector *w)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n gsl_vector_set(w, i, exp(-ri*ri));\n }\n\n return GSL_SUCCESS;\n} /* welsch() */\n\nstatic int\nwelsch_dpsi(const gsl_vector *r, gsl_vector *dpsi)\n{\n size_t i;\n size_t n = r->size;\n\n for (i = 0; i < n; ++i)\n {\n double ri = gsl_vector_get(r, i);\n\n gsl_vector_set(dpsi, i, (1.0 - 2.0*ri*ri) * exp(-ri*ri));\n }\n\n return GSL_SUCCESS;\n} /* welsch_dpsi() */\n\nstatic const gsl_multifit_robust_type welsch_type = {\n \"welsch\",\n &welsch,\n &welsch_dpsi,\n TUNING_WELSCH\n};\n\nconst gsl_multifit_robust_type *gsl_multifit_robust_default = &bisquare_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_bisquare = &bisquare_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_cauchy = &cauchy_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_fair = &fair_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_huber = &huber_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_ols = &ols_type;\nconst gsl_multifit_robust_type *gsl_multifit_robust_welsch = &welsch_type;\n", "meta": {"hexsha": "af8d2c3e97eeb52fd870f0159760994da34c7573", "size": 5769, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/robust_wfun.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/robust_wfun.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/robust_wfun.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.8267148014, "max_line_length": 81, "alphanum_fraction": 0.6365054602, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.45258749301065787}} {"text": "/* fft/gsl_fft_real_float.h\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#ifndef __GSL_FFT_REAL_FLOAT_H__\n#define __GSL_FFT_REAL_FLOAT_H__\n\n#include \n\n#include \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\nint gsl_fft_real_float_radix2_transform (float data[], const size_t stride, const size_t n) ;\n\ntypedef struct\n {\n size_t n;\n size_t nf;\n size_t factor[64];\n gsl_complex_float *twiddle[64];\n gsl_complex_float *trig;\n }\ngsl_fft_real_wavetable_float;\n\ntypedef struct\n {\n size_t n;\n float *scratch;\n }\ngsl_fft_real_workspace_float;\n\ngsl_fft_real_wavetable_float * gsl_fft_real_wavetable_float_alloc (size_t n);\n\nvoid gsl_fft_real_wavetable_float_free (gsl_fft_real_wavetable_float * wavetable);\n\ngsl_fft_real_workspace_float * gsl_fft_real_workspace_float_alloc (size_t n);\n\nvoid gsl_fft_real_workspace_float_free (gsl_fft_real_workspace_float * workspace);\n\nint gsl_fft_real_float_transform (float data[], const size_t stride, const size_t n,\n const gsl_fft_real_wavetable_float * wavetable,\n gsl_fft_real_workspace_float * work);\n\n\nint gsl_fft_real_float_unpack (const float real_float_coefficient[],\n\t\t\t float complex_coefficient[],\n\t\t\t const size_t stride, const size_t n);\n\n__END_DECLS\n\n#endif /* __GSL_FFT_REAL_FLOAT_H__ */\n", "meta": {"hexsha": "a99cab5c12734f3803c52e79ac8665f6a7b402f1", "size": 2313, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/fft/gsl_fft_real_float.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/fft/gsl_fft_real_float.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/fft/gsl_fft_real_float.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": 28.9125, "max_line_length": 93, "alphanum_fraction": 0.7423259836, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4525292550369162}} {"text": "#include \n#include \n\nint\nmain (void)\n{\n double P, Q;\n double x = 2.0;\n\n P = gsl_cdf_ugaussian_P (x);\n printf (\"prob(x < %f) = %f\\n\", x, P);\n\n Q = gsl_cdf_ugaussian_Q (x);\n printf (\"prob(x > %f) = %f\\n\", x, Q);\n\n x = gsl_cdf_ugaussian_Pinv (P);\n printf (\"Pinv(%f) = %f\\n\", P, x);\n\n x = gsl_cdf_ugaussian_Qinv (Q);\n printf (\"Qinv(%f) = %f\\n\", Q, x);\n\n return 0;\n}\n", "meta": {"hexsha": "968eb96dfaac2ece0583e9b4d98343d1d1162d53", "size": 397, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/cdf.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/cdf.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/cdf.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 16.5416666667, "max_line_length": 39, "alphanum_fraction": 0.5491183879, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4524913262658595}} {"text": "/* movstat/movSn.c\n *\n * Compute moving \"S_n\" statistic from Croux and Rousseeuw, 1992\n * \n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\ngsl_movstat_Sn()\n Calculate moving S_n statistic for input vector\n\nInputs: endtype - how to handle end points\n x - input vector, size n\n xscale - (output) vector of \"S_n\" statistics, size n\n xscale_i = (S_n)_i for i-th window:\n w - workspace\n*/\n\nint\ngsl_movstat_Sn(const gsl_movstat_end_t endtype, const gsl_vector * x,\n gsl_vector * xscale, gsl_movstat_workspace * w)\n{\n int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_Sn, NULL, xscale, NULL, w);\n return status;\n}\n", "meta": {"hexsha": "53d3479e56f80d58ca302ae9b030add4e7b87b06", "size": 1640, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/movstat/movSn.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/movstat/movSn.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/movSn.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 32.8, "max_line_length": 96, "alphanum_fraction": 0.7091463415, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4523976142370452}} {"text": "\n#include \"allelefreq.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid P_update_simple(const uint8_t* G, const double* zetabeta, const double* zetagamma, const double* xi, const double* beta, const double* gamma, double* var_beta, double* var_gamma, long N, long L, long K)\n{\n uint8_t genotype;\n long idx, n, l, k;\n double theta_beta_sum, theta_gamma_sum;\n double *var_beta_tmp, *var_gamma_tmp;\n\n var_beta_tmp = (double*) malloc(K * sizeof(double));\n var_gamma_tmp = (double*) malloc(K * sizeof(double));\n\n //printf(\"\\n----------- Beginning P_update_simple.\\n\");\n // loop over loci\n for (l=0; l and are the priors.\n idx = l * K + k;\n var_beta[idx] = beta[idx] + zetabeta[idx] * var_beta_tmp[k];\n var_gamma[idx] = gamma[idx] + zetagamma[idx] * var_gamma_tmp[k];\n }\n }\n\n free( var_beta_tmp );\n free( var_gamma_tmp );\n}\n\nvoid P_update_logistic(const double* Dvarbeta, const double* Dvargamma, const double* mu, const double* Lambda, double* var_beta, double* var_gamma, double mintol, long L, long K)\n{\n /*\n `Dvarbeta` and `Dvargamma` are a function of the values of `var_beta` and `var_gamma`. This\n dependence, however, is explicit on a set of latent populations assignments which in-turn\n depend on the variational parameters estimated at the previous step. So, the variables\n `Dvarbeta` and `Dvargamma` do not have to be updated.\n */\n\n long l, k, idx, numvar, update;\n long iter = 0;\n double tol = 10.0;\n double tmptol;\n double beta, gamma;\n double A, pbetagamma, pbeta, pgamma, ppbeta, ppgamma;\n double A_1, B_1, C_1, A_2, B_2, C_2;\n\n /*\n Iterate until succesive estimates are sufficiently similar\n or the number of iterations exceeds 1000.\n */\n while (tol>mintol && iter<1000) {\n\n numvar = 0;\n tol = 0.0;\n\n // loop over loci\n for (l=0; l\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\n#ifdef _OPENMP\n#include \n#endif /*_OPENMP*/\n\n#define SQR(x) ((x) * (x))\n\n\n/* check if matrix is irreducible. \n** If it is not, then Perron-Frobenius theorem does not apply\n*/\nvoid CheckReducibility(float *A,size_t nvox)\n{\n size_t i,j,k,n;\n float umin = 99999;\n \n n=0;\n for (i=0; i 0) n++;\n if (A[k] > 0 && A[k] < umin) umin = A[k];\n }\n for (j=i+1; j 0) n++;\n }\n }\n \n if (n < nvox) {\n VWarning(\" matrix is not irreducible, correction term is applied.\");\n for (i=0; i 2 && d < 1.0e-6) break;\n }\n VFree(y);\n}\n\n\n\nfloat CorrMetric(float z,int type)\n{\n switch (type) {\n case 1: /* add */\n z += 1.0;\n break;\n case 2: /* pos */\n if (z < 0) z = 0;\n break;\n case 3: /* abs */\n z = fabs(z);\n break;\n case 4: /* neg */\n if (z < 0) z = -z;\n else z = 0;\n break;\n default:\n VError(\"illegal type\");\n }\n return z;\n}\n\n\ndouble ECMcorrelation(const float *arr1,const float *arr2,size_t nt,int type)\n{\n size_t i;\n double sum=0,z=0,kx=(double)nt;\n\n if ((type > 0 && type < 5) || (type==6)) {\n sum=0;\n for (i=0; isize1;\n size_t nt = X->size2;\n\n \n /* compute similarity matrix */\n size_t m = (nvox*(nvox+1))/2;\n float *A = (float *) calloc(m,sizeof(float));\n if (!A) VError(\" err allocating correlation matrix (too big)\");\n memset(A,0,m*sizeof(float));\n size_t progress=0;\n \n\n#pragma omp parallel for shared(progress) private(j) schedule(guided) firstprivate(X,A)\n for (i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Fisher matrix calculation for surveys with velocity and density field measurements. This extended version includes the extra parameters\n// associated with primordial non-Gaussianity, scale-dependent density and velocity bias, and zero-point offsets, as per Howlett 2017a.\n// ASSUMPTIONS:\n// - Uncorrelated shot-noise between the density and velocity fields\n// - I use the trapezium rule to integrate over r. There will be some error due to this, but this makes the most sense as \n// we are binning the number density anyway, and it makes hella difference in the speed of the code.\n// - The redshift dependence of the non-linear matter and velocity divergence power spectra is captured using linear interpolation.\n// - The PV error scales as a fixed pecentage of H0*r.\n// - Flat LCDM cosmology (but not necessarily GR as gammaval can be changed).\n// - The damping of the velocity and density fields due to non-linear RSD is redshift independent\n// - The scale dependence of the scale-dependent bias is redshift independent\n\n// The parameters necessary for the calculation\nstatic int nparams = 2; // The number of free parameters (we can use any of beta, fsigma8, r_g, sigma_g, sigma_u, fnl, Rv, Rd, zp_err)\nstatic int Data[2] = {0,1}; // A vector of flags for the parameters we are interested in (0=beta, 1=fsigma8, 2=r_g, 3=sigma_g, 4=sigma_u, 5=fnl, 6=Rv, 7=Rd, 8=zp_err). MAKE SURE THE LENGTH OF THIS VECTOR, NPARAMS AND THE ENTRIES AGREE/MAKE SENSE, OR YOU MIGHT GET NONSENSE RESULTS!!\nstatic int nziter = 1; // Now many bins in redshift between zmin and zmax we are considering\nstatic double zmin = 0.0; // The minimum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)\nstatic double zmax = 0.4; // The maximum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)\nstatic double Om = 0.3121; // The matter density at z=0\nstatic double c = 299792.458; // The speed of light in km/s\nstatic double gammaval = 0.55; // The value of gammaval to use in the forecasts (where f(z) = Om(z)^gammaval)\nstatic double r_g = 1.0; // The cross correlation coefficient between the velocity and density fields\nstatic double beta0 = 0.493; // The value of beta (at z=0, we'll modify this by the redshift dependent value of bias and f as required)\nstatic double sigma80 = 0.8150; // The value of sigma8 at z=0\nstatic double sigma_u = 13.00; // The value of the velocity damping parameter in Mpc/h. I use the values from Jun Koda's paper\nstatic double sigma_g = 4.24; // The value of the density damping parameter in Mpc/h. I use the values from Jun Koda's paper\nstatic double fnl = 0.0; // The value of fnl contributing to primordial non-Gaussianity\nstatic double Rd = 0.0; // Scale-dependent bias following the parameterisation in Howlett2017a\nstatic double Rv = 0.0; // Velocity bias following the parameterisation in Howlett2017a\nstatic double zp_err = 0.05; // The error in the zeropoint offset if we are interested in the systematic bias caused by such an error (sigma_m in Eq. 34 of Howlett 2017a)\nstatic double do_bias = 0; // Whether or not to calculate the systematic parameter bias due to neglecting scale-dependent biases.\nstatic double do_zp_bias = 1; // Whether or not to calculate the systematic parameter bias due to having a zero-point offset.\nstatic double kmax = 0.2; // The maximum k to evaluate for dd, dv and vv correlations (Typical values are 0.1 - 0.2, on smaller scales the models are likely to break down).\nstatic double survey_area[3] = {0.0, 0.0, 1.65}; // We need to know the survey area for each survey and the overlap area between the surveys (redshift survey only first, then PV survey only, then overlap. \n // For fully overlapping we would have {0, 0, size_overlap}. For redshift larger than PV, we would have {size_red-size_overlap, 0, size_overlap}). Units are pi steradians, such that full sky is 4.0, half sky is 2.0 etc.\nstatic double error_rand = 300.0; // The observational error due to random non-linear velocities (I normally use 300km/s as in Jun Koda's paper)\nstatic double error_dist = 0.20; // The percentage error on the distance indicator (Typically 0.05 - 0.10 for SNe IA, 0.2 or more for Tully-Fisher or Fundamental Plane) \nstatic double verbosity = 2; // How much output to give: 0 = only percentage errors on fsigma8, 1 = other useful info and nuisance parameters, 2 = full fisher and covariance matrices\n\n// The number of redshifts and the redshifts themselves of the input matter and velocity divergence power spectra. \n// These numbers are multiplied by 100, converted to ints and written in the form _z0p%02d which is then appended to the filename Pvel_file. See routine read_power. \nstatic double nzin = 11;\nstatic double zin[11] = {0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50};\nchar * Pvel_file = \"./example_files/example_pk\"; // The file containing the velocity divergence power spectrum. Don't include .dat as we'll append the redshifts on read in\nchar * Trans_file = \"./example_files/example_transfer.dat\"; // The file containing the transfer function. Only used for primordial non-Gaussianity and must be normalised to 1 as k->0\n\n\n// The files containing the number density of the surveys. First is the PV survey, then the redshift survey. These files MUST have the same binning and redshift range, \n// so that the sum over redshift bins works (would be fine if we used splines), i.e., if one survey is shallower then that file must contain rows with n(z)=0.\n// I also typically save nbar x 10^6 in the input file to make sure I don't lose precision when outputting small nbar values to files. This is corrected when the nbar file\n// is read in, so see the read_nz() routine!\nchar * nbar_file[300] = {\"./example_files/taipan_vel_nbar_final_reformat.dat\",\n \"./example_files/taipan_red_nbar_final_reformat.dat\"}; \n\n// Other global parameters and arrays\nint NK, * NRED;\ndouble pkkmin; // The minimum kmin to integrate over, based on the input power spectrum file\ndouble pkkmax; // The maximum k in the input power spectrum. The maximum k to integrate over is the smallest of this or kmax\ndouble * zarray;\ndouble * rarray;\ndouble * ezarray;\ndouble * deltararray;\ndouble * growtharray;\ndouble ** nbararray;\ndouble * karray, * deltakarray;\ndouble ** pmmarray, ** pmtarray, ** pttarray;\ngsl_spline * growth_spline, * r_spline;\ngsl_interp_accel * growth_acc, * r_acc;\ngsl_spline * Trans_spline, * growth_spline, * r_spline;\ngsl_interp_accel * Trans_acc, * growth_acc, * r_acc;\n\n// Prototypes\ndouble zeff_integrand(double mu, void * pin);\ndouble mu_integrand(double mu, void * pin);\ndouble ezinv(double x, void *p);\ndouble rz(double red);\ndouble growthfunc(double x, void *p);\ndouble growthz(double red);\nvoid read_nz();\nvoid read_power();\nvoid read_transfer();\ndouble calc_zeff(double kmin, double zmin_iter, double zmax_iter);\nvoid calc_fisher(double kmin, double zmin_iter, double zmax_iter, double z_eff, double bias_flag, gsl_matrix * Covariance, double * Sys);\n\n// Calculates the fished matrix for a velocity survey.\nint main(int argc, char **argv) {\n \n int i, j;\n\n // Read in the velocity divergence power spectrum output from the COPTER code (Carlson 2009)\n read_power();\n\n // Read in the transfer function\n read_transfer();\n\n // Read in the number densities of the surveys\n read_nz();\n\n // Run some checks\n if (!((survey_area[0] > 0.0) || (survey_area[2] > 0.0))) {\n for (i=0; i 0.0) || (survey_area[2] > 0.0))) {\n for (i=0; i 0) printf(\"Evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\\n\", kmin, kmax, zmin_iter, zmax_iter);\n\n // Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields)\n // *********************************************************************************************************\n double z_eff = calc_zeff(kmin, zmin_iter, zmax_iter);\n\n // Fisher matrix using the TRUE covariance matrix (i.e., with scale-dependent biases). This routine changes based on whether do_zp_bias is true or false.\n // In the former case, this Fisher Matrix DOESN'T include a zero-point offset, as we compute the systematically biased case later. If do_zp_bias is false\n // we are not interested in the bias caused by an offset, and so we treat whatever value is in zp_err as real and the Fisher Matrix DOES include a potential zero-point offset\n // ******************************************************************************************************************\n calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 0, Covariance, Sys);\n\n // Bias vector (i.e., Eq. 50 from Howlett 2017a, which uses computes the parameter offset due to neglecting scale-dependent biases or adding a zero-point offset)\n // ******************************************************************************************************************\n if (do_bias || do_zp_bias) calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 1, Covariance, Sys);\n\n // Fisher matrix using the INCORRECT covariance matrix (i.e., without scale-dependent biases, and with zero-point offsets). This is used for comparing the \n // magnitude of any bias with respect to the errors (as the errors could also be biased too small!)\n // ******************************************************************************************************************\n if (do_bias || do_zp_bias) calc_fisher(kmin, zmin_iter, zmax_iter, z_eff, 2, Covariance, Sys);\n\n }\n\n // Now the full Fisher matrix over all redshifts if we had more than 1 redshift bin. This is equivalent to assuming a single measurement from all data\n // and NOT the same as summing the individual matrices above (which is equivalent to making separate measurements at each redshift, then marginalising over\n // all redshift-dependent quantities, and so may be different for things like fnl).\n if (nziter > 1) {\n double rzmax = gsl_spline_eval(r_spline, zmax, r_acc);\n double kmin = M_PI/rzmax;\n\n if (verbosity > 0) printf(\"Finally, evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\\n\", kmin, kmax, zmin, zmax);\n\n // Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields)\n // *********************************************************************************************************\n double z_eff = calc_zeff(kmin, zmin, zmax);\n\n // Fisher matrix using the TRUE covariance matrix (i.e., with scale-dependent biases). This routine changes based on whether do_zp_bias is true or false.\n // In the former case, this Fisher Matrix DOESN'T include a zero-point offset, as we compute the systematically biased case later. If do_zp_bias is false\n // we are not interested in the bias caused by an offset, and so we treat whatever value is in zp_err as real and the Fisher Matrix DOES include a potential zero-point offset\n // ******************************************************************************************************************\n calc_fisher(kmin, zmin, zmax, z_eff, 0, Covariance, Sys);\n\n // Bias vector (i.e., Eq. 50 from Howlett 2017a, which uses computes the parameter offset due to neglecting scale-dependent biases or adding a zero-point offset)\n // ******************************************************************************************************************\n if (do_bias || do_zp_bias) calc_fisher(kmin, zmin, zmax, z_eff, 1, Covariance, Sys);\n\n // Fisher matrix using the INCORRECT covariance matrix (i.e., without scale-dependent biases, and with zero-point offsets). This is used for comparing the \n // magnitude of any bias with respect to the errors (as the errors could also be biased too small!)\n // ******************************************************************************************************************\n if (do_bias || do_zp_bias) calc_fisher(kmin, zmin, zmax, z_eff, 2, Covariance, Sys);\n\n }\n \n free(Sys);\n gsl_matrix_free(Covariance);\n gsl_spline_free(growth_spline);\n gsl_interp_accel_free(growth_acc);\n gsl_spline_free(Trans_spline);\n gsl_interp_accel_free(Trans_acc);\n\n return 0;\n}\n\ndouble calc_zeff(double kmin, double zmin_iter, double zmax_iter) {\n\n int numk;\n double k_sum1 = 0.0, k_sum2 = 0.0;\n for (numk=0; numk kmax) continue;\n\n double result, error;\n double params[4] = {numk, k, zmin_iter, zmax_iter};\n\n size_t nevals = 1000;\n gsl_function F;\n F.function = &zeff_integrand;\n F.params = ¶ms;\n gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n\n gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);\n gsl_integration_workspace_free(w);\n\n k_sum1 += k*k*deltak*result;\n k_sum2 += k*k*deltak;\n\n }\n double z_eff = k_sum1/k_sum2;\n if (verbosity > 0) printf(\"Effective redshift z_eff = %lf\\n\", z_eff);\n\n return z_eff;\n\n}\n\n// Calculate the fisher matrix, integrating over k, then mu, then r (r is last as it means we are effectively integrating over effective volume).\n// As the input spectra are tabulated we'll just use the trapezium rule to integrate over k\nvoid calc_fisher(double kmin, double zmin_iter, double zmax_iter, double z_eff, double bias_flag, gsl_matrix * Covariance, double * Sys) {\n\n int i, j, numk;\n\n double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc);\n\n double sigma8 = sigma80 * growth_eff;\n double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff);\n double f = pow(Omz, gammaval);\n double beta = f*beta0*growth_eff/pow(Om,0.55);\n\n if (verbosity > 0) {\n if (do_zp_bias) {\n if (bias_flag == 0) {\n printf(\"TRUE Fisher matrix without zero-point offset:\\n\");\n } else if (bias_flag == 1) {\n printf(\"BIAS vector:\\n\");\n } else if (bias_flag == 2) {\n printf(\"INCORRECT Fisher matrix:\\n\");\n }\n } else {\n if (bias_flag == 0) {\n printf(\"TRUE Fisher matrix with potential zero-point offset set by zp_err:\\n\");\n } else if (bias_flag == 1) {\n printf(\"BIAS vector:\\n\");\n } else if (bias_flag == 2) {\n printf(\"INCORRECT Fisher matrix:\\n\");\n }\n }\n }\n\n double * Bias = (double *)malloc(nparams*sizeof(double*));\n gsl_matrix * Fisher = gsl_matrix_alloc(nparams, nparams);\n for (i=0; i kmax) continue;\n\n double result, error;\n double params[7] = {numk, k, Data[i], Data[j], zmin_iter, zmax_iter, bias_flag};\n\n size_t nevals = 1000;\n gsl_function F;\n F.function = &mu_integrand;\n F.params = ¶ms;\n gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n\n gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);\n gsl_integration_workspace_free(w);\n\n k_sum += k*k*deltak*result;\n\n }\n //printf(\"%d, %d, %lf\\n\", i, j, k_sum/(4.0*M_PI));\n if (bias_flag == 1) {\n Bias[i] = k_sum/(4.0*M_PI);\n } else {\n gsl_matrix_set(Fisher, i, j, k_sum/(4.0*M_PI));\n gsl_matrix_set(Fisher, j, i, k_sum/(4.0*M_PI));\n }\n }\n }\n\n if (bias_flag == 1) {\n\n for (i=0; i 0) {\n for (i=0; i 0) {\n printf(\"Parameter constraints\\n======================================================\\n\");\n for (i=0; i 1) {\n double * Pmm_array = (double *)malloc(nzin*sizeof(double));\n double * Pmt_array = (double *)malloc(nzin*sizeof(double));\n double * Ptt_array = (double *)malloc(nzin*sizeof(double));\n for (j=0; j zmaxval) break;\n\n double r_sum = 0.0;\n double r = rarray[i];\n double deltar = deltararray[i];\n\n double dd_prefac=0.0, vv_prefac=0.0;\n double P_gg=0.0, P_uu=0.0;\n\n double Ak = Ak0/growtharray[i];\n double sigma8 = sigma80 * growtharray[i];\n\n // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift\n double Pmm, Pmt, Ptt;\n Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);\n Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);\n Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);\n\n double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);\n double f = pow(Omz, gammaval);\n double beta = f*beta0*growtharray[i]/pow(Om,0.55);\n double bv = 1.0 - Rv*Rv*k*k;\n double bsd = Rd*k*k;\n double beta_sd = 1.0/beta + bsd/f;\n\n vv_prefac = 1.0e2*bv*f*mu*veldamp/k;\n dd_prefac = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd*beta_sd) + 2.0*bv*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd + bv*bv*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd/f - 2.0*bv*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp;\n P_gg = dd_prefac*Pmm;\n P_uu = vv_prefac*vv_prefac*Ptt;\n\n // We need to do the overlapping and non-overlapping parts of the redshifts and PV surveys separately\n for (surv=0; surv<3; surv++) {\n double surv_sum = 0.0;\n if (survey_area[surv] > 0.0) {\n double error_obs, error_noise, n_g = 0.0, n_u = 0.0;\n\n // Set the nbar for each section.\n if (surv == 0) {\n n_g = nbararray[1][i];\n } else if (surv == 1) {\n error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}\n n_u = nbararray[0][i]/error_noise; \n } else {\n error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n error_noise = error_rand*error_rand + error_obs*error_obs; // Error_noise is in km^{2}s^{-2}\n n_u = nbararray[0][i]/error_noise; \n n_g = nbararray[1][i];\n }\n\n double value1 = n_g/(1.0 + n_g*P_gg);\n double value2 = n_u/(1.0 + n_u*P_uu);\n surv_sum += value1*value1 + value2*value2;\n\n surv_sum *= survey_area[surv];\n r_sum += surv_sum;\n }\n }\n\n dVeff += r*r*deltar*r_sum;\n zdVeff += zval*r*r*deltar*r_sum;\n\n }\n\n gsl_spline_free(Pmm_spline);\n gsl_spline_free(Pmt_spline);\n gsl_spline_free(Ptt_spline);\n gsl_interp_accel_free(Pmm_acc);\n gsl_interp_accel_free(Pmt_acc);\n gsl_interp_accel_free(Ptt_acc);\n\n return zdVeff/dVeff;\n\n}\n\n// The integrand for the integral over mu in the Fisher matrix calculation.\n// For each mu we need to create a 2x2 matrix of the relevant power spectra derivatives and the inverse of the power spectrum matrix.\n// Because there are some regions where the number density goes to zero we have to work directly with the inverse as it is difficult to invert numerically\n// but if we deal with the inverse only then we can just set the relevant parts to zero when the number density is zero.\ndouble mu_integrand(double mu, void * pin) {\n\n int i, j, m, q, u, surv;\n double * p = (double *)pin;\n double result, error;\n\n int numk = (int)p[0];\n double k = p[1];\n double zminval = p[4];\n double zmaxval = p[5];\n gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc;\n gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline;\n double * Pmm_array = (double *)malloc(nzin*sizeof(double));\n double * Pmt_array = (double *)malloc(nzin*sizeof(double));\n double * Ptt_array = (double *)malloc(nzin*sizeof(double));\n for (j=0; j zmaxval) break;\n\n double dd_prefac=0.0, dv_prefac=0.0, vv_prefac=0.0;\n double dd_prefac_bias=0.0, dv_prefac_bias=0.0, vv_prefac_bias=0.0;\n double P_gg=0.0, P_ug=0.0, P_uu=0.0;\n double P_gg_bias=0.0, P_ug_bias=0.0, P_uu_bias=0.0;\n\n double Ak = Ak0/growtharray[i];\n double sigma8 = sigma80 * growtharray[i];\n\n // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift\n double Pmm, Pmt, Ptt;\n Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);\n Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);\n Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);\n\n double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);\n double f = pow(Omz, gammaval);\n double beta = f*beta0*growtharray[i]/pow(Om,0.55);\n double bv = 1.0 - Rv*Rv*k*k;\n double bsd = Rd*k*k;\n double beta_sd = 1.0/beta + bsd/f;\n\n // If p[6] (bias_flag) == 2 this means we are computing the Fisher matrix INCLUDING systematics, and so we need the covariance matrix without scale-dependent bias\n if ((int)p[6] == 2) {\n bv = 1.0;\n beta_sd = 1.0/beta;\n }\n\n // In the presence of a zero-point offset we have to calculate the additional velocity recieved. \n // This is redshift dependent if we assume a fixed offset in the logarithmic distance ratio\n double zp_err_prefac = c*log(10.0)/(1.0 - ((c*(1.0 + zval)*(1.0 + zval))/(100.0*ez*r)))/5.0;\n double zp_err_v = zp_err*zp_err_prefac;\n\n vv_prefac = 1.0e2*bv*f*mu*veldamp/k;\n dd_prefac = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd*beta_sd) + 2.0*bv*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd + bv*bv*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd/f - 2.0*bv*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp;\n dv_prefac = (r_g*(1.0+fnl*Ak)*beta_sd - r_g*fnl*Ak/f + bv*mu*mu)*f*dendamp;\n\n P_gg = dd_prefac*Pmm;\n P_ug = vv_prefac*dv_prefac*Pmt;\n P_uu = vv_prefac*vv_prefac*Ptt;\n\n // And now the derivatives. Need to create a matrix of derivatives for each of the two parameters of interest\n gsl_matrix * dPdt1 = gsl_matrix_calloc(2, 2);\n gsl_matrix * dPdt2 = gsl_matrix_calloc(2, 2);\n double value;\n switch((int)p[2]) {\n // Differential w.r.t betaA\n case 0:\n value = -2.0*((1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak)/f)*f*f*dendamp*dendamp*Pmm/(beta*beta);\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = -(vv_prefac*f*r_g*(1.0+fnl*Ak)*dendamp*Pmt)/(beta*beta);\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n break;\n // Differential w.r.t fsigma8\n case 1:\n value = 2.0*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd/beta + f*r_g*bv*mu*mu*(1.0+fnl*Ak)*(2.0/beta + bsd/f) + f*bv*bv*mu*mu*mu*mu - fnl*Ak*(1.0+fnl*Ak)/beta - bv*r_g*mu*mu*fnl*Ak)*dendamp*dendamp*Pmm/sigma8;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = vv_prefac*(r_g*(1.0+fnl*Ak)*(2.0/beta + bsd/f) - r_g*fnl*Ak/f + bv*mu*mu)*dendamp*Pmt/sigma8;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n value = (2.0*P_uu)/(f*sigma8); \n gsl_matrix_set(dPdt1, 1, 1, value);\n break;\n // Differential w.r.t r_g\n case 2:\n value = 2.0*bv*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = vv_prefac*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n break;\n // Differential w.r.t sigma_g\n case 3:\n value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n break;\n // Differential w.r.t sigma_u\n case 4:\n value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n gsl_matrix_set(dPdt1, 1, 1, value);\n break;\n // Differential w.r.t fnl\n case 5:\n value = 2.0*Ak*((1.0+fnl*Ak)*beta_sd*beta_sd + bv*r_g*mu*mu*(beta_sd - 1.0/f) - (1.0+2.0*fnl*Ak)*beta_sd/f + fnl*Ak/(f*f))*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = vv_prefac*r_g*Ak*(beta_sd - 1.0/f)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n break; \n // Differential w.r.t Rv\n case 6:\n value = -4.0*Rv*k*k*(r_g*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f) + bv*mu*mu*mu*mu)*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = -2.0*Rv*k*k*vv_prefac*(r_g*(1.0+fnl*Ak)*beta_sd/bv - r_g*fnl*Ak/(f*bv) + 2.0*mu*mu)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n value = -4.0*Rv*k*k*P_uu/bv; \n gsl_matrix_set(dPdt1, 1, 1, value);\n break;\n // Differential w.r.t Rd\n case 7:\n value = 2.0*k*k*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*f*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak))*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt1, 0, 0, value);\n value = vv_prefac*k*k*r_g*(1.0+fnl*Ak)*dendamp*Pmt;\n gsl_matrix_set(dPdt1, 0, 1, value);\n gsl_matrix_set(dPdt1, 1, 0, value);\n break;\n // Differential w.r.t. zp_err\n case 8:\n if (nbararray[0][i] > 0.0) {\n value = 2.0*zp_err_v*zp_err_prefac/nbararray[0][i];\n gsl_matrix_set(dPdt1, 1, 1, value);\n }\n break;\n default:\n break;\n }\n // If we want to calculate the Bias vector and look at systematics from scale-dependent bias or zero-point offsets, we simply have to replace dPdt2 with the difference between the models with and without bias. \n // The subscript \"bias\" is the systematically biased covariance matrix, which, in the most confusing way possible, is the one which doesn't have the velocity/scale-dependent bias included or does have the zero-point offset\n if ((int)p[6] == 1) {\n // Calculate the model without scale-dependent biases\n if (do_bias) {\n double bv_bias = 1.0;\n double beta_sd_bias = 1.0/beta;\n vv_prefac_bias = 1.0e2*bv_bias*f*mu*veldamp/k;\n dd_prefac_bias = ((1.0+fnl*Ak)*(1.0+fnl*Ak)*(beta_sd_bias*beta_sd_bias) + 2.0*bv_bias*r_g*mu*mu*(1.0+fnl*Ak)*beta_sd_bias + bv_bias*bv_bias*mu*mu*mu*mu - 2.0*fnl*Ak*(1.0+fnl*Ak)*beta_sd_bias/f - 2.0*bv_bias*r_g*mu*mu*fnl*Ak/f + fnl*fnl*Ak*Ak/(f*f))*f*f*dendamp*dendamp;\n dv_prefac_bias = (r_g*(1.0+fnl*Ak)*beta_sd_bias - r_g*fnl*Ak/f + bv_bias*mu*mu)*f*dendamp;\n P_gg_bias = dd_prefac_bias*Pmm;\n P_ug_bias = vv_prefac_bias*dv_prefac_bias*Pmt;\n P_uu_bias = vv_prefac_bias*vv_prefac_bias*Ptt;\n gsl_matrix_set(dPdt2, 0, 0, P_gg - P_gg_bias);\n gsl_matrix_set(dPdt2, 0, 1, P_ug - P_ug_bias);\n gsl_matrix_set(dPdt2, 1, 0, P_ug - P_ug_bias);\n gsl_matrix_set(dPdt2, 1, 1, P_uu - P_uu_bias);\n //printf(\"%lf, %lf, %lf, %lf\\n\",bvA, P_uuAA, P_uuAA_bias, gsl_matrix_get(dPdt2, 1, 1));\n }\n if (do_zp_bias) {\n if (nbararray[0][i] > 0.0) {\n gsl_matrix_set(dPdt2, 1, 1, zp_err_v*zp_err_v/nbararray[0][i]);\n }\n }\n } else {\n switch((int)p[3]) {\n // Differential w.r.t betaA\n case 0:\n value = -2.0*((1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak)/f)*f*f*dendamp*dendamp*Pmm/(beta*beta);\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = -(vv_prefac*f*r_g*(1.0+fnl*Ak)*dendamp*Pmt)/(beta*beta);\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n break;\n // Differential w.r.t fsigma8\n case 1:\n value = 2.0*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd/beta + f*r_g*bv*mu*mu*(1.0+fnl*Ak)*(2.0/beta + bsd/f) + f*bv*bv*mu*mu*mu*mu - fnl*Ak*(1.0+fnl*Ak)/beta - bv*r_g*mu*mu*fnl*Ak)*dendamp*dendamp*Pmm/sigma8;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = vv_prefac*(r_g*(1.0+fnl*Ak)*(2.0/beta + bsd/f) - r_g*fnl*Ak/f + bv*mu*mu)*dendamp*Pmt/sigma8;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n value = (2.0*P_uu)/(f*sigma8); \n gsl_matrix_set(dPdt2, 1, 1, value);\n break;\n // Differential w.r.t r_g\n case 2:\n value = 2.0*bv*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = vv_prefac*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n break;\n // Differential w.r.t sigma_g\n case 3:\n value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n break;\n // Differential w.r.t sigma_u\n case 4:\n value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n gsl_matrix_set(dPdt2, 1, 1, value);\n break;\n // Differential w.r.t fnl\n case 5:\n value = 2.0*Ak*((1.0+fnl*Ak)*beta_sd*beta_sd + bv*r_g*mu*mu*(beta_sd - 1.0/f) - (1.0+2.0*fnl*Ak)*beta_sd/f + fnl*Ak/(f*f))*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = vv_prefac*r_g*Ak*(beta_sd - 1.0/f)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n break; \n // Differential w.r.t Rv\n case 6:\n value = -4.0*Rv*k*k*(r_g*mu*mu*((1.0+fnl*Ak)*beta_sd - fnl*Ak/f) + bv*mu*mu*mu*mu)*f*f*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = -2.0*Rv*k*k*vv_prefac*(r_g*(1.0+fnl*Ak)*beta_sd/bv - r_g*fnl*Ak/(f*bv) + 2.0*mu*mu)*f*dendamp*Pmt;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n value = -4.0*Rv*k*k*P_uu/bv; \n gsl_matrix_set(dPdt2, 1, 1, value);\n break;\n // Differential w.r.t Rd\n case 7:\n value = 2.0*k*k*(f*(1.0+fnl*Ak)*(1.0+fnl*Ak)*beta_sd + bv*r_g*f*mu*mu*(1.0+fnl*Ak) - fnl*Ak*(1.0+fnl*Ak))*dendamp*dendamp*Pmm;\n gsl_matrix_set(dPdt2, 0, 0, value);\n value = vv_prefac*k*k*r_g*(1.0+fnl*Ak)*dendamp*Pmt;\n gsl_matrix_set(dPdt2, 0, 1, value);\n gsl_matrix_set(dPdt2, 1, 0, value);\n break;\n // Differential w.r.t. zp_err\n case 8:\n if (nbararray[0][i] > 0.0) {\n value = 2.0*zp_err_v*zp_err_prefac/nbararray[0][i];\n gsl_matrix_set(dPdt2, 1, 1, value);\n }\n break;\n default:\n break;\n }\n }\n\n // If we are looking at the bias from the zero-point error, then once we have calculated dPdt2 we want the covariance matrix without\n // systematics and so without a zero-point offset. The same is true if we want the TRUE covariance matrix\n if (do_zp_bias) {\n if (((int)p[6] == 0) || ((int)p[6] == 1)) zp_err_v = 0.0;\n }\n\n // We need to do the overlapping and non-overlapping parts of the surveys separately\n for (surv=0; surv<3; surv++) {\n double surv_sum = 0.0;\n if (survey_area[surv] > 0.0) {\n double error_obs, error_noise, n_g = 0.0, n_u = 0.0;\n\n // Set the nbar for each section.\n if (surv == 0) {\n n_g = nbararray[1][i];\n } else if (surv == 1) {\n error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n error_noise = error_rand*error_rand + error_obs*error_obs + zp_err_v*zp_err_v; // Error_noise is in km^{2}s^{-2}\n n_u = nbararray[0][i]/error_noise; \n } else {\n error_obs = 100.0*error_dist*r; // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n error_noise = error_rand*error_rand + error_obs*error_obs + zp_err_v*zp_err_v; // Error_noise is in km^{2}s^{-2}\n n_u = nbararray[0][i]/error_noise; \n n_g = nbararray[1][i];\n }\n\n //printf(\"%lf, %lf, %lf\\n\", r, n_g, 1.0e6*n_u);\n\n if (!((n_u > 0.0) || (n_g > 0.0))) continue;\n\n // First we need the determinant.\n double det = 1.0 + n_u*n_g*(P_gg*P_uu - P_ug*P_ug) + n_u*P_uu + n_g*P_gg;\n\n // Now the inverse matrix.\n gsl_matrix * iP = gsl_matrix_calloc(2, 2);\n value = n_u*n_g*P_uu + n_g;\n gsl_matrix_set(iP, 0, 0, value);\n value = n_g*n_u*P_gg + n_u;\n gsl_matrix_set(iP, 1, 1, value);\n value = - n_g*n_u*P_ug;\n gsl_matrix_set(iP, 0, 1, value);\n gsl_matrix_set(iP, 1, 0, value);\n \n // Finally we need to compute the Fisher integrand by summing over the inverse and differential matrices\n for (j=0; j<2; j++) {\n for (m=0; m<2; m++) {\n for (u=0; u<2; u++) {\n for (q=0; q<2; q++) {\n value = gsl_matrix_get(dPdt1, j, q)*gsl_matrix_get(iP, q, u)*gsl_matrix_get(dPdt2, u, m)*gsl_matrix_get(iP, m, j);\n surv_sum += value;\n }\n }\n }\n }\n surv_sum /= det*det;\n surv_sum *= survey_area[surv];\n r_sum += surv_sum;\n gsl_matrix_free(iP);\n //printf(\"%d, %lf, %lf, %lf, %lf, %lf\\n\", surv, k, mu, r, r_sum, surv_sum);\n\n }\n }\n //printf(\"%lf, %lf, %lf, %lf\\n\", k, mu, r, r_sum);\n\n result_sum += r*r*deltar*r_sum;\n\n gsl_matrix_free(dPdt1);\n gsl_matrix_free(dPdt2);\n }\n\n gsl_spline_free(Pmm_spline);\n gsl_spline_free(Pmt_spline);\n gsl_spline_free(Ptt_spline);\n gsl_interp_accel_free(Pmm_acc);\n gsl_interp_accel_free(Pmt_acc);\n gsl_interp_accel_free(Ptt_acc);\n\n return result_sum;\n}\n\n// Routine to read in the number density as a function of redshift. We need a file containing the left-most edge of each redshift bin and teh number density in that bin.\n// From this we create arrays to store the bin centre, the bin width, the comoving distance and growth factor at the bin centre and the number density.\n// The last bin width and bin centre is constructed from the last row of the input and the value of zmax at the top of the code. \n// ITS VERY IMPORTANT THAT THE NUMBER OF ROWS AND THE REDSHIFTS OF BOTH THE DENSITY AND PV NUMBER DENSITIES MATCH AS THE INTEGRATION OVER Z IS DONE USING THE TRAPEZIUM RULE.\n// ALSO MAKE NOTE OF THE FACTOR OF 1.0e-6 ON LINE 827. THIS IS BECAUSE I TYPICALLY SAVE THE VALUE OF NBAR x 10^6 IN THE INPUT FILES< SO THAT I DON'T LOSE PRECISION\n// WHEN SMALL VALUES OF THE NUMBER DENSITY ARE WRITTEN TO A FILE!\nvoid read_nz() {\n\n FILE * fp;\n char buf[500];\n int i, nsamp;\n\n NRED = (int *)calloc(2, sizeof(int));\n nbararray = (double **)calloc(2, sizeof(double*));\n double * zinarray;\n\n for (nsamp = 0; nsamp < 2; nsamp++) {\n\n if(!(fp = fopen(nbar_file[nsamp], \"r\"))) {\n printf(\"\\nERROR: Can't open nbar file '%s'.\\n\\n\", nbar_file[nsamp]);\n exit(0);\n }\n\n NRED[nsamp] = 0;\n while(fgets(buf,500,fp)) {\n if(strncmp(buf,\"#\",1)!=0) {\n double tz, tnbar;\n if(sscanf(buf, \"%lf %lf\\n\", &tz, &tnbar) != 2) {printf(\"nbar read error\\n\"); exit(0);};\n if (tz > zmax) break;\n NRED[nsamp]++;\n }\n }\n fclose(fp);\n\n if (nsamp == 0) zinarray = (double *)calloc(NRED[nsamp], sizeof(double));\n nbararray[nsamp] = (double *)calloc(NRED[nsamp], sizeof(double));\n\n NRED[nsamp] = 0;\n fp = fopen(nbar_file[nsamp], \"r\");\n while(fgets(buf,500,fp)) {\n if(strncmp(buf,\"#\",1)!=0) {\n double tz, tnbar;\n if(sscanf(buf, \"%lf %lf\\n\", &tz, &tnbar) != 2) {printf(\"nbar read error\\n\"); exit(0);};\n if (tz > zmax) break;\n if (nsamp == 0) zinarray[NRED[nsamp]] = tz;\n nbararray[nsamp][NRED[nsamp]] = 1.0e-6*tnbar;\n NRED[nsamp]++;\n }\n }\n fclose(fp);\n }\n\n if (NRED[1] != NRED[0]) {\n printf(\"ERROR: The number of redshift bins for each sample must match\\n\");\n exit(0);\n } \n\n zarray = (double *)calloc(NRED[0], sizeof(double));\n rarray = (double *)calloc(NRED[0], sizeof(double));\n ezarray = (double *)calloc(NRED[0], sizeof(double));\n deltararray = (double *)calloc(NRED[0], sizeof(double));\n growtharray = (double *)calloc(NRED[0], sizeof(double));\n\n for (i=0; i\n#include \n#include \n#include \n#include\n#include \n\ndouble epsl = 0.01;\n\ntypedef struct {\n double x, y, z;\n} position;\n\ntypedef struct _vertex {\n position pos;\n gsl_matrix_view *C;\n struct _vertex *p,*l,*r;\n} vertex;\n\nvoid usage(char *exec) {\n printf(\"%s -s \\n\", exec);\n printf(\"%s -c \\n\", exec);\n printf(\"%s -show \\n\", exec);\n}\n\nint* ddd(char *fileName, int len){\n FILE *file = NULL;\n if ((file = fopen(fileName, \"r\")) == NULL) {\n /* error openning the file */\n perror(\"fopen: \");\n return NULL;\n }\n int n, i, j = 0, k = 0;\n char buff[6], buffFloat[17];\n memset(buff, 0, sizeof(buff));\n memset(buffFloat, 0, sizeof(buffFloat));\n if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, \"E = [\")) {\n perror(\"file out of params: \");\n return NULL;\n }\n \n double **mat = (double **)calloc(len, sizeof(double *));\n for (i = 0; i < len; i++) {\n mat[i] = (double *)calloc(3, sizeof(double *));\n }\n i = 0;\n while ((n = fread(buff, sizeof(char), 1, file)) == 1) {\n if (buff[0] == ' ') {\n if (k > 0) {\n mat[i][j] = atof(buffFloat);\n memset(buffFloat, 0, sizeof(buffFloat));\n k = 0;\n j++;\n }\n continue;\n }\n else if (buff[0] == ';') {\n if (k) {\n mat[i][j] = atof(buffFloat);\n memset(buffFloat, 0, sizeof(buffFloat));\n k = 0;\n }\n j = 0;\n i++;\n }\n else {\n buffFloat[k++] = buff[0];\n }\n }\n fclose(file);\n\n int current = 0; \n for (i = 0; i < len; i++) {\n \n for (j = 0; j < len; j++) {\n printf(\" %f \", sqrt(pow(mat[i][0] - mat[j][0], 2) + pow(mat[i][1] - mat[j][1], 2) + pow(mat[i][2] - mat[j][2], 2)));\n fflush(stdout);\n }\n printf(\"\\n\");\n }\n}\n\nvoid printMat(double **mat, int len) {\n int i, j;\n for (i = 0; i < len; i++) {\n for (j = 0; j < len; j++) {\n //if (mat[i][j] != 0) {\n printf(\" %f \", mat[i][j]);\n fflush(stdout);\n //}\n }\n printf(\"\\n\");\n }\n}\n\ndouble **matrixConstruct(char *fileName, int len){\n FILE *file = NULL;\n if ((file = fopen(fileName, \"r\")) == NULL) {\n /* error openning the file */\n perror(\"fopen: \");\n return NULL;\n }\n int n, i, j = 0, k = 0;\n char buff[6], buffFloat[17];\n memset(buff, 0, sizeof(buff));\n memset(buffFloat, 0, sizeof(buffFloat));\n if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, \"E = [\")) {\n perror(\"file out of params: \");\n return NULL;\n }\n \n double **mat = (double **)calloc(len, sizeof(double *));\n for (i = 0; i < len; i++) {\n mat[i] = (double *)calloc(len, sizeof(double *));\n }\n i = 0;\n while ((n = fread(buff, sizeof(char), 1, file)) == 1) {\n if (buff[0] == ' ') {\n if (k > 0) {\n mat[i][j] = atof(buffFloat);\n memset(buffFloat, 0, sizeof(buffFloat));\n k = 0;\n j++;\n }\n continue;\n }\n else if (buff[0] == ';') {\n if (k) {\n mat[i][j] = atof(buffFloat);\n memset(buffFloat, 0, sizeof(buffFloat));\n k = 0;\n }\n j = 0;\n i++;\n }\n else {\n buffFloat[k++] = buff[0];\n }\n }\n fclose(file);\n for (i = 0; i < len; i++)\n {\n for (j = 0; j < len; j++)\n {\n if(pow(mat[i][j] - mat[j][i],2) > 0.0000001) return NULL; \n }\n }\n \n return mat;\n}\n\ndouble dis(double **m, int i){\n if (i-1 < 0) return -1;\n return m[i][i-1];\n}\n\ndouble theta(double **m, int i){\n if (i-1 < 0) return -1000;\n return acos((pow(m[i][i+1],2) + pow(m[i][i-1],2) - pow(m[i+1][i-1],2))/(2*m[i][i+1]*m[i][i-1]));\n}\n\ndouble cosO(double **m, int i){\n //printf(\"%f %f\\n\", pow(m[i][i+1], 2) + pow(m[i+1][i+3],2) - 2*m[i][i+1]*m[i+1][i+3]*cos(theta(m, i+1))*cos(theta(m, i+2)) - pow(m[i][i+3],2), 2*m[i][i+1]*m[i+1][i+3]*sin(theta(m, i+1))*sin(theta(m, i+2)) );\n double theta2 = acos((pow(m[i+1][i+2],2) + pow(m[i+1][i+3],2) - pow(m[i+2][i+3],2))/(2*m[i+1][i+3]*m[i+1][i+2]));\n double res = (pow(m[i][i+1], 2) + pow(m[i+1][i+3],2) - 2*m[i][i+1]*m[i+1][i+3]*cos(theta(m, i+1))*cos(theta2) - pow(m[i][i+3],2))/\n (2*m[i][i+1]*m[i+1][i+3]*sin(theta(m, i+1))*sin(theta2));\n if (res > 1) return 1;\n if (res < -1) return -1;\n return res;\n}\n\ndouble cosOmega(double **m, int i){\n if (i-3 < 0) return 1000;\n\n double Ai = (2*pow(m[i-2][i-1],2))*(pow(m[i-3][i-2],2) + pow(m[i-2][i] ,2) - pow(m[i-3][i] ,2));\n double Bi = pow(m[i-3][i-2],2) + pow(m[i-2][i-1],2) - pow(m[i-3][i-1],2);\n double Ci = pow(m[i-2][i-1],2) + pow(m[i-2][i],2) - pow(m[i-1][i],2);\n double Di = sqrt(\n 4*pow(m[i-3][i-2],2)\n *pow(m[i-2][i-1],2)\n -pow(Bi,2) );\n double Ei = sqrt(4*pow(m[i-2][i-1],2)*pow(m[i-2][i],2)-pow(Ci,2) );\n double res = (Ai - Bi*Ci)/(Di*Ei);\n if (res > 1) return 1;\n if (res < -1) return -1;\n return res;\n}\n\nint isFeasible(double **mat, int len, vertex *v, int i){\n if (!v) return 0;\n int j = i-1;\n double pos[i][3];\n vertex *aux = v->p;\n while (aux)\n {\n //printf(\"\\n\\tj = %d {%f, %f, %f}\\n\", j, aux->pos.x, aux->pos.y, aux->pos.z);\n pos[j][0] = aux->pos.x;\n pos[j][1] = aux->pos.y;\n pos[j--][2] = aux->pos.z;\n aux = aux->p;\n }\n for (j = 0; j < i-3; j++)\n {\n if (mat[i][j] > 0)\n { \n double dij = pow(v->pos.x - pos[j][0],2)+pow(v->pos.y - pos[j][1],2)+pow(v->pos.z - pos[j][2],2);\n double diff = pow(mat[i][j],2)- dij;\n if (diff < 0) diff = diff*(-1);\n double dist = sqrt(diff);//pow(diff,2);\n //printf(\"{%d,%d} {%f, %f, %f}-{%f, %f, %f} \\n\\t%.20f- %.20f = %.20f \\n %.20f \\n\", i, j, v->pos.x, v->pos.y, v->pos.z, pos[j][0], pos[j][1], pos[j][2], mat[i][j], dij, diff, dist);\n if (dist > epsl)\n {\n return 0;\n }\n }\n }\n return 1;\n}\n\ndouble LDE(double **mat, double **m, int len){\n int i, j, count = 0;\n double dij = 0;\n for (i = 0; i < len; i++)\n {\n for (j = i+1; j < len; j++)\n {\n if (mat[i][j]>0){\n dij = dij + pow((pow(mat[i][j],2) - (pow(m[i][0] - m[j][0], 2) + pow(m[i][1] - m[j][1], 2) + pow(m[i][2] - m[j][2], 2))),2)/mat[i][j];\n count++;\n }\n }\n }\n return dij/count;\n \n}\n\nint qtd = 0;\nint BranchAndPrune(double **mat, int len, vertex *v, int i){\n if(i < len){\n double thetai = theta(mat,i-1);\n double cti = cos(thetai);\n double sti = sin(thetai);\n double cwi = cosOmega(mat, i);\n //double cwi2 = cosO(mat, i-3);\n //printf(\"%f %f \\n\", cwi, cwi2 );\n //printf(\"%f %f \\n\", acos(cwi)*57.295779513, acos(cwi2)*57.295779513 );\n if (cwi*cwi > 1){\n printf(\"\\n %f Error cwi\", cwi);\n getchar();\n } \n double swi = sqrt(1-pow(cwi, 2));\n double di = dis(mat,i);\n double bi1[] = {0-cti,0-sti,0,0-di*cti,\n sti*cwi,0-cti*cwi,0-swi,di*sti*cwi,\n sti*swi,0-cti*swi,cwi,di*sti*swi,\n 0,0,0,1};\n int j;\n //for (j = 0; j < 16; j++)\n //{\n // printf(\"%f \", bi1[j]);\n //}\n // printf(\"\\n\");\n \n gsl_matrix_view Bi1 = gsl_matrix_view_array(bi1, 4, 4);\n\n swi = 0-swi;\n double bi2[] = {0-cti,0-sti,0,0-di*cti,\n sti*cwi,0-cti*cwi,0-swi,di*sti*cwi,\n sti*swi,0-cti*swi,cwi,di*sti*swi,\n 0,0,0,1};\n \n //for (j = 0; j < 16; j++)\n //{\n // printf(\"%f \", bi2[j]);\n //}\n //printf(\"\\n\");\n\n gsl_matrix_view Bi2 = gsl_matrix_view_array(bi2, 4, 4);\n \n vertex *rv = (vertex*)calloc(1, sizeof(vertex));\n rv->p = v;\n rv->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view));\n *(rv->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4);\n\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,\n 1.0, &(v->C->matrix), &Bi1.matrix,\n 0.0, &(rv->C->matrix));\n\n vertex *lv = (vertex*)calloc(1, sizeof(vertex));\n lv->p = v;\n lv->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view));\n *(lv->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4);\n\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,\n 1.0, &(v->C->matrix), &Bi2.matrix,\n 0.0, &(lv->C->matrix));\n \n gsl_matrix_view *Xi = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view));\n *Xi = gsl_matrix_view_array((double*)calloc(4,sizeof(double)), 4, 1);\n\n double *y = (double*)calloc(4,sizeof(double));\n y[3] = 1;\n gsl_matrix_view *Y = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view));\n *Y = gsl_matrix_view_array(y, 4, 1);\n\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,\n 1.0, &(rv->C->matrix), &(Y->matrix),\n 0.0, &(Xi->matrix));\n rv->pos.x = Xi->matrix.data[0];\n rv->pos.y = Xi->matrix.data[1];\n rv->pos.z = Xi->matrix.data[2];\n \n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,\n 1.0, &(lv->C->matrix), &(Y->matrix),\n 0.0, &(Xi->matrix));\n lv->pos.x = Xi->matrix.data[0];\n lv->pos.y = Xi->matrix.data[1];\n lv->pos.z = Xi->matrix.data[2];\n free(y);\n free(Y);\n free(Xi->matrix.data);\n free(Xi);\n\n //printf(\"[ %f, %f\", rv->pos.x, rv->pos.y);\n //printf(\" %f]\\n\", rv->pos.z);\n //printf(\"[ %f, %f\", lv->pos.x, lv->pos.y);\n //printf(\" %f ]\\n\", lv->pos.z);\n\n\n //getchar();\n int s;\n //printf(\"\\n\");\n if (isFeasible(mat, len, rv, i)){\n v->r = rv;\n //for (s = 0; s < i; s++)\n //{\n // printf(\">\");\n //}\n \n //printf(\"1\\n\");\n fflush(stdout);\n BranchAndPrune(mat, len, rv, i+1);\n }else {\n //for (s = 0; s < i; s++)\n //{\n // printf(\"<\");\n //}\n //\n //printf(\"2\\n\");\n free(rv->C->matrix.data);\n free(rv->C);\n free(rv);\n v->r = NULL;\n }\n \n if (isFeasible(mat, len, lv, i)){\n v->l = lv;\n\n //for (s = 0; s < i; s++)\n //{\n // printf(\">\");\n //}\n //\n //printf(\"3\\n\");\n fflush(stdout);\n BranchAndPrune(mat, len, lv, i+1);\n }else {\n\n //for (s = 0; s < i; s++)\n //{\n // printf(\"<\");\n //}\n //\n //printf(\"4\\n\");\n free(lv->C->matrix.data);\n free(lv->C);\n free(lv);\n v->l = NULL;\n }\n }else{\n //printf(\" ---------------- ue\\n\");\n //fflush(stdout);\n qtd++;\n double **mat2 = calloc(len, sizeof(double*));\n int i;\n for (i = 0; i < len; i++)\n {\n mat2[i] = calloc(3, sizeof(double));\n }\n i = len-1;\n printf(\"\\n[\");\n while (v)\n {\n mat2[i][0] = v->pos.x;\n mat2[i][1] = v->pos.y;\n mat2[i--][2] = v->pos.z;\n //printf(\"%f %f %f; \", v->pos.x, v->pos.y, v->pos.z);\n v = v->p;\n }\n\n double lde = LDE(mat, mat2, len);\n \n printf(\"\\n \\t LDE = %.20f\\n\", lde);\n\n for (i = 0; i < len; i++)\n {\n printf(\"%f %f %f; \", mat[i][0], mat[i][1], mat[i][2]);\n }\n \n printf(\"]\\n\");\n return 0;\n }\n}\n\n\nint printGrafo(int len, vertex *v, int i){\n int j = -1;\n if (v->l){\n printf(\"(%d, %d),\", i, i+1);\n j = printGrafo(len, v->l, i+1); \n }\n if (v->r){\n if (j != -1){\n printf(\"(%d, %d),\", i, j); \n j = printGrafo(len, v->r, j); \n }else\n {\n printf(\"(%d, %d),\", i, i+1);\n return printGrafo(len, v->r, i+1); \n }\n }\n if (j == -1) return i+1;\n return j;\n}\n\nvertex *resul[10];\n\nint solve(char *fileName, int len) {\n double **mat = matrixConstruct(fileName, len);\n if(mat == NULL){\n printf(\"Error when construct matrix\\n\");\n fflush(stdout);\n return 0;\n }\n\n double b1[] = {1,0,0,0,\n 0,1,0,0,\n 0,0,1,0,\n 0,0,0,1};\n gsl_matrix_view B1 = gsl_matrix_view_array(b1, 4, 4);\n \n double b2[] = {-1,0,0,0-dis(mat,1),\n 0,1,0,0,\n 0,0,-1,0,\n 0,0,0,1};\n gsl_matrix_view B2 = gsl_matrix_view_array(b2, 4, 4);\n\n double theta2 = theta(mat,1);\n //printf(\"[ cos %f\\n\", theta2);\n\n double ct2 = cos(theta2);\n double st2 = sin(theta2);\n double b3[] = {0-ct2,0-st2,0,0-dis(mat,2)*ct2,\n st2,0-ct2,0,dis(mat,2)*st2,\n 0,0,1,0,\n 0,0,0,1};\n gsl_matrix_view B3 = gsl_matrix_view_array(b3, 4, 4);\n\n vertex *v = (vertex*)calloc(1, sizeof(vertex));\n v->C = &B1;\n //printf(\"[ %f, %f %f\\n\", v->pos.x, v->pos.y, v->pos.z);\n\n\n vertex *v2 = (vertex*)calloc(1, sizeof(vertex));\n v->r = v2;\n v2->C = &B2;\n v2->p = v;\n v2->pos.x = 0-dis(mat,1);\n\n // printf(\"[ %f, %f %f\\n\", v2->pos.x, v2->pos.y, v2->pos.z);\n vertex *v3 = (vertex*)calloc(1, sizeof(vertex));\n v2->r = v3;\n v3->C = (gsl_matrix_view*)calloc(1, sizeof(gsl_matrix_view));\n *(v3->C) = gsl_matrix_view_array((double*)calloc(16,sizeof(double)), 4, 4);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,\n 1.0, &B2.matrix, &(B3.matrix),\n 0.0, &(v3->C->matrix));\n v3->p = v2;\n v3->pos.x = dis(mat,2)*ct2 -dis(mat,1);\n v3->pos.y = dis(mat,2)*st2;\n\n //printf(\"[ %f, %f\", v3->pos.x, v3->pos.y);\n // printf(\" %f]\\n\", v3->pos.z);\n\n BranchAndPrune(mat, len, v3, 3);\n printf(\"%d\", qtd);\n //printf(\"[\");\n //printGrafo(len, v, 0);\n //printf(\"]\");\n return 1;\n}\n\nint countCols(char *fileName) {\n FILE *file = NULL;\n if ((file = fopen(fileName, \"r\")) == NULL) {\n /* error openning the file */\n perror(\"fopen: \");\n return 1;\n }\n\n int n, j = 0, k = 0;\n char buff[6];\n memset(buff, 0, sizeof(buff));\n if (fread(buff, sizeof(char), 5, file) < 5 || strcmp(buff, \"E = [\")) {\n fclose(file);\n perror(\"file out of params: \");\n return 1;\n }\n \n while ((n = fread(buff, sizeof(char), 1, file)) == 1) {\n if (buff[0] == ' ') {\n if (k > 0) {\n k = 0;\n j++;\n }\n continue;\n }\n else if (buff[0] == ';') {\n if (k) j++;\n break;\n }\n else {\n k++;\n }\n }\n fclose(file);\n return j;\n}\n\nint main(int argc, char **argv) {\n double time_spent = 0.0;\n\n\tclock_t begin = clock();\n\n if (argc < 3) {\n usage(argv[0]);\n }\n else {\n if (!strcmp(argv[1], \"-s\")) {\n int len;\n if (argc < 4) {\n len = countCols(argv[2]);\n }else {\n if ((len = atoi(argv[3])) == 0){\n /* error openning the file */\n perror(\"count_vertex param error: \");\n return 1;\n }\n }\n \n solve(argv[2], len);\n } else if (!strcmp(argv[1], \"-c\")) {\n printf(\"%d\\n\",countCols(argv[2]));\n } else if (!strcmp(argv[1], \"-show\")) {\n printMat(matrixConstruct(argv[2], countCols(argv[2])), countCols(argv[2]));\n } else if (!strcmp(argv[1], \"-d\")) {\n ddd(argv[2],10);\n } else {\n usage(argv[0]);\n }\n }\n\n //getchar();\n \n clock_t end = clock();\n\n\t// calculate elapsed time by finding difference (end - begin) and\n\t// divide by CLOCKS_PER_SEC to convert to seconds\n\ttime_spent += (double)(end - begin) / CLOCKS_PER_SEC;\n\n\tprintf(\"\\nTime elpased is %.20f seconds\", time_spent);\n fflush(stdout);\n}", "meta": {"hexsha": "e3b9850935fbdbb344b3e9a99e38be4e3ca00816", "size": 16689, "ext": "c", "lang": "C", "max_stars_repo_path": "BP.c", "max_stars_repo_name": "caomem/BP", "max_stars_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "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": "BP.c", "max_issues_repo_name": "caomem/BP", "max_issues_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "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": "BP.c", "max_forks_repo_name": "caomem/BP", "max_forks_repo_head_hexsha": "12b9625340ddfe77daf5ce2692f5d84d0189e7c5", "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.6260720412, "max_line_length": 211, "alphanum_fraction": 0.4195577926, "num_tokens": 5459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059316231898, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.45195351798776984}} {"text": "#include \n#include \n#include \n#include \n\n/**\n * C BLAS function wrappers.\n */\n\ninline void copy_vector_cblas(\n const double* const x, double* const y,\n const unsigned int rows )\n{\n cblas_dcopy( rows, x, 1, y, 1 );\n}\n\ninline double inner_product_cblas(\n const double* const x, const double* const y,\n const unsigned int rows )\n{\n return cblas_ddot( rows, x, 1, y, 1 );\n}\n\ninline void outer_product_cblas(\n const double* const x, const double* const y,\n const double alpha, const unsigned int rows_x, const unsigned int rows_y,\n double* m )\n{\n cblas_dger( CblasRowMajor, rows_x, rows_y, alpha, x, 1, y, 1, m, rows_y);\n}\n\ninline void vector_vector_sum_cblas(\n const double* const x, double* const y,\n const double alpha, const unsigned int rows )\n{\n cblas_daxpy( rows, alpha, x, 1, y, 1);\n}\n\n/**\n * Helper functions.\n */\n\ninline void copy_matrix(\n const double* const m0, double* const m1,\n const unsigned int rows, const unsigned int cols )\n{\n for ( unsigned int i = 0; i < rows; ++i )\n {\n for ( unsigned int j = 0; j < cols; ++j )\n {\n m1[ i * cols + j ] = m0[ i * cols + j ];\n }\n }\n}\n\ninline void matrix_matrix_sum(\n const double* const m0, const double* const m1,\n const double alpha, const unsigned int rows, const unsigned int cols,\n double* m2 )\n{\n for ( unsigned int i = 0; i < rows; ++i )\n {\n for ( unsigned int j = 0; j < cols; ++j )\n {\n m2[ i * cols + j ] = m0[ i * cols + j ] + alpha * m1[ i * cols + j ];\n }\n }\n}\n\ninline void zero_vector(\n const unsigned int rows,\n double* x )\n{\n memset(x, 0, rows * sizeof( double ) );\n}\n\ninline void zero_matrix(\n const unsigned int rows, const unsigned int cols,\n double* m )\n{\n memset(m, 0, rows * cols * sizeof( double ) );\n}\n\ninline void zero_diagonal(\n const unsigned int rows, const unsigned int cols,\n double* m )\n{\n for ( unsigned int i = 0; i < rows; ++i )\n {\n m[ i * cols + i ] = 0;\n }\n}\n\ninline double rand_double( void )\n{\n return ( double ) rand() / ( double )( RAND_MAX );\n}\n\ninline unsigned int rand_int( const unsigned int max )\n{\n return rand() % max;\n}\n\ninline unsigned int logistic( const double h )\n{\n return 1. / ( 1. + exp( -h ) ) > rand_double();\n}\n\n/**\n * Train a fully visible Boltzmann machine with CD-1.\n */\nvoid ctrain(\n double* W, double* b, unsigned int rows, unsigned int cols,\n double* data, unsigned int episodes,\n double epsilon_w, double epsilon_b,\n unsigned int batchsize, unsigned int seed,\n const double momentum_constant, const double decay_constant )\n{\n double dW[ rows * cols ];\n double db[ cols ];\n double dW_minus[ rows * cols ];\n double db_minus[ cols ];\n double u;\n\n const double effective_epsilon_w = 1 / ( double )( batchsize ) * epsilon_w;\n const double effective_epsilon_b = 1 / ( double )( batchsize ) * epsilon_b;\n\n srand( seed );\n\n // initialize momentum terms to zero at start of learning\n zero_matrix( rows, cols, dW_minus );\n zero_vector( rows, db_minus );\n\n for ( unsigned int i = 0; i < episodes / batchsize; ++i )\n {\n // initialize weights and bias change to zero at start of batch\n zero_matrix( rows, cols, dW );\n zero_vector( rows, db );\n\n for ( unsigned int j = 0; j < batchsize; ++j )\n {\n // compute \\Delta W += _0\n outer_product_cblas( &data[ i * batchsize * cols + j * cols], &data[ i * batchsize * cols + j * cols], 1., rows, cols, dW );\n\n // compute \\Delta b += _0\n vector_vector_sum_cblas( &data[ i * batchsize * cols + j * cols], db, 1, rows );\n\n // perform a single Gibbs step (update all units once) directly\n // on data vector to avoid copying\n for ( unsigned int k = 0; k < cols; ++k )\n {\n u = inner_product_cblas( &W[ k * cols ], &data[ i * batchsize * cols + j * cols], cols );\n data[ i * batchsize * cols + j * cols + k ] = logistic( u + b[ k ] );\n }\n\n // compute \\Delta W -= _1\n outer_product_cblas( &data[ i * batchsize * cols + j * cols ], &data[ i * batchsize * cols + j * cols ], -1., rows, cols, dW );\n\n // compute \\Delta b -= _1\n vector_vector_sum_cblas( &data[ i * batchsize * cols + j * cols ], db, -1, rows );\n }\n\n // add momentum\n if ( momentum_constant > 0. )\n {\n matrix_matrix_sum( dW, dW_minus, momentum_constant, rows, cols, dW );\n vector_vector_sum_cblas( db_minus, db, momentum_constant, rows );\n copy_matrix( dW, dW_minus, rows, cols );\n copy_vector_cblas( db, db_minus, rows );\n }\n\n // decay weights\n if ( decay_constant > 0. )\n {\n // need to devide by learning rate, since dW is multiplied by it\n // below\n matrix_matrix_sum( dW, W, -decay_constant / effective_epsilon_w, rows, cols, dW );\n }\n\n // updates weights and biases\n matrix_matrix_sum( W, dW, effective_epsilon_w, rows, cols, W );\n vector_vector_sum_cblas( db, b, effective_epsilon_b, rows );\n\n // set diagonal of weight matrix to zero\n zero_diagonal( rows, cols, W );\n }\n}\n\n/**\n * Sample from a fully visible Boltzmann machine.\n */\nvoid csample(\n const double* W, const double* b, const unsigned int rows, const unsigned int cols,\n const unsigned int episodes, const unsigned int seed,\n double* s, double* samples )\n{\n double u;\n srand( seed );\n\n unsigned int i = 0;\n while(1)\n {\n // perform a single Gibbs step (update all units once on average)\n for ( unsigned int k = 0; k < cols; ++k )\n {\n const unsigned int j = rand_int( cols );\n u = inner_product_cblas( &W[ j * cols ], s, cols );\n s[ j ] = logistic( u + b[ j ] );\n }\n copy_vector_cblas( s, &samples[ i * rows], rows );\n ++i;\n if( i == episodes)\n {\n return;\n }\n }\n}\n", "meta": {"hexsha": "39c7335acb79bd77f463317880c72f88d75fd728", "size": 5689, "ext": "h", "lang": "C", "max_stars_repo_path": "vbm.h", "max_stars_repo_name": "jakobj/python-vbm", "max_stars_repo_head_hexsha": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-17T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-17T14:31:52.000Z", "max_issues_repo_path": "vbm.h", "max_issues_repo_name": "jakobj/python-vbm", "max_issues_repo_head_hexsha": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6", "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": "vbm.h", "max_forks_repo_name": "jakobj/python-vbm", "max_forks_repo_head_hexsha": "46eaff859e49e3682e4ca2f4a2f8c494d5ac4ba6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0963302752, "max_line_length": 133, "alphanum_fraction": 0.6168043593, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4517885107490766}} {"text": "#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#if HAVE_MPI\n#include \n#endif\n#include \"genetic/genetic.h\"\n\n#define N_SIMULATIONS 10000\n#define SEED 707l\nint ntasks = 1;\nunsigned int nthreads = 1;\nGMutex mutex[1];\nGeneticVariable v[2];\n\ndouble\nevaluate (Entity * entity)\n{\n double x, y, e1, e2;\n x = genetic_get_variable (entity, v);\n y = genetic_get_variable (entity, v + 1);\n e1 = x + y - 3.;\n e2 = x - y - 1.;\n e1 = e1 * e1 + e2 * e2;\n return e1;\n}\n\nint\nmain (int argn, char **argc)\n{\n FILE *file;\n double *best_variables;\n char *best_genome;\n double xgenerations, mutation_ratio, reproduction_ratio, adaptation_ratio,\n evolution_ratio, best_objective;\n int rank;\n unsigned int ngenerations;\n#if HAVE_MPI\n MPI_Init (&argn, &argc);\n MPI_Comm_size (MPI_COMM_WORLD, &ntasks);\n MPI_Comm_rank (MPI_COMM_WORLD, &rank);\n#else\n rank = 0;\n#endif\n nthreads = 4;\n v[0].maximum = 10.;\n v[0].minimum = -10.;\n v[0].nbits = 30;\n v[1].maximum = 10.;\n v[1].minimum = -10.;\n v[1].nbits = 30;\n file = fopen (argc[1], \"r\");\n if (fscanf (file, \"%*s%lf%*s%lf%*s%lf%*s%lf\", &xgenerations,\n &mutation_ratio, &reproduction_ratio, &adaptation_ratio) != 4)\n return 1;\n fclose (file);\n ngenerations = xgenerations;\n evolution_ratio = mutation_ratio + reproduction_ratio + adaptation_ratio;\n genetic_algorithm_default (2, v,\n N_SIMULATIONS\n / (1 + (ngenerations - 1) * evolution_ratio),\n ngenerations, mutation_ratio, reproduction_ratio,\n adaptation_ratio, SEED, 0., &evaluate,\n &best_genome, &best_variables, &best_objective);\n if (rank == 0)\n {\n file = fopen (argc[2], \"w\");\n fprintf (file, \"%.14le\", best_objective);\n printf (\"objective=%.14le\\n\", best_objective);\n fclose (file);\n g_free (best_genome);\n g_free (best_variables);\n }\n#if HAVE_MPI\n MPI_Finalize ();\n#endif\n return 0;\n}\n", "meta": {"hexsha": "b123f6bd2797ce5ef33c17669c0ef9b7f7166df4", "size": 2048, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/test2/simulator.c", "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_issues_repo_path": "tests/test2/simulator.c", "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_forks_repo_path": "tests/test2/simulator.c", "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2839506173, "max_line_length": 78, "alphanum_fraction": 0.61328125, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.45116574372525}} {"text": "/* integration/fixed.c\n * \n * Copyright (C) 2017 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* the code in this module performs fixed-point quadrature calculations for\n * integrands and is based on IQPACK */\n\n#include \n#include \n#include \n#include \n\nstatic int fixed_compute(const double a, const double b, const double alpha, const double beta,\n gsl_integration_fixed_workspace * w);\nstatic int imtqlx ( const int n, double d[], double e[], double z[] );\n\ngsl_integration_fixed_workspace *\ngsl_integration_fixed_alloc(const gsl_integration_fixed_type * type, const size_t n,\n const double a, const double b, const double alpha, const double beta)\n{\n int status;\n gsl_integration_fixed_workspace *w;\n\n /* check inputs */\n if (n < 1)\n {\n GSL_ERROR_VAL (\"workspace size n must be at least 1\", GSL_EDOM, 0);\n }\n\n w = calloc(1, sizeof(gsl_integration_fixed_workspace));\n if (w == NULL)\n {\n GSL_ERROR_VAL (\"unable to allocate workspace\", GSL_ENOMEM, 0);\n }\n\n w->weights = malloc(n * sizeof(double));\n if (w->weights == NULL)\n {\n gsl_integration_fixed_free(w);\n GSL_ERROR_VAL (\"unable to allocate weights\", GSL_ENOMEM, 0);\n }\n\n w->x = malloc(n * sizeof(double));\n if (w->x == NULL)\n {\n gsl_integration_fixed_free(w);\n GSL_ERROR_VAL (\"unable to allocate x\", GSL_ENOMEM, 0);\n }\n\n w->diag = malloc(n * sizeof(double));\n if (w->diag == NULL)\n {\n gsl_integration_fixed_free(w);\n GSL_ERROR_VAL (\"unable to allocate diag\", GSL_ENOMEM, 0);\n }\n\n w->subdiag = malloc(n * sizeof(double));\n if (w->subdiag == NULL)\n {\n gsl_integration_fixed_free(w);\n GSL_ERROR_VAL (\"unable to allocate subdiag\", GSL_ENOMEM, 0);\n }\n\n w->n = n;\n w->type = type;\n\n /* compute quadrature weights and nodes */\n status = fixed_compute(a, b, alpha, beta, w);\n if (status)\n {\n gsl_integration_fixed_free(w);\n GSL_ERROR_VAL (\"error in integration parameters\", GSL_EDOM, 0);\n }\n\n return w;\n}\n\nvoid\ngsl_integration_fixed_free(gsl_integration_fixed_workspace * w)\n{\n if (w->weights)\n free(w->weights);\n\n if (w->x)\n free(w->x);\n\n if (w->diag)\n free(w->diag);\n\n if (w->subdiag)\n free(w->subdiag);\n\n free(w);\n}\n\nsize_t\ngsl_integration_fixed_n(const gsl_integration_fixed_workspace * w)\n{\n return w->n;\n}\n\ndouble *\ngsl_integration_fixed_nodes(const gsl_integration_fixed_workspace * w)\n{\n return w->x;\n}\n\ndouble *\ngsl_integration_fixed_weights(const gsl_integration_fixed_workspace * w)\n{\n return w->weights;\n}\n\nint\ngsl_integration_fixed(const gsl_function * func, double * result,\n const gsl_integration_fixed_workspace * w)\n{\n const size_t n = w->n;\n size_t i;\n double sum = 0.0;\n\n for (i = 0; i < n; ++i)\n {\n double fi = GSL_FN_EVAL(func, w->x[i]);\n sum += w->weights[i] * fi;\n }\n\n *result = sum;\n\n return GSL_SUCCESS;\n}\n\n/*\nfixed_compute()\n Compute quadrature weights and nodes\n*/\n\nstatic int\nfixed_compute(const double a, const double b, const double alpha, const double beta,\n gsl_integration_fixed_workspace * w)\n{\n int s;\n const size_t n = w->n;\n gsl_integration_fixed_params params;\n size_t i;\n\n params.a = a;\n params.b = b;\n params.alpha = alpha;\n params.beta = beta;\n\n /* check input parameters */\n s = (w->type->check)(n, ¶ms);\n if (s)\n return s;\n\n /* initialize Jacobi matrix */\n s = (w->type->init)(n, w->diag, w->subdiag, ¶ms);\n if (s)\n return s;\n\n if (params.zemu <= 0.0)\n {\n GSL_ERROR(\"zeroth moment must be positive\", GSL_EINVAL);\n }\n\n for ( i = 0; i < n; i++ )\n {\n w->x[i] = w->diag[i];\n }\n\n w->weights[0] = sqrt (params.zemu);\n\n for ( i = 1; i < n; i++ )\n {\n w->weights[i] = 0.0;\n }\n\n /* diagonalize the Jacobi matrix */\n s = imtqlx (n, w->x, w->subdiag, w->weights);\n if (s)\n return s;\n\n for (i = 0; i < n; i++)\n {\n w->weights[i] = w->weights[i] * w->weights[i];\n }\n\n /*\n * The current weights and nodes are valid for a = 0, b = 1.\n * Now scale them for arbitrary a,b\n */\n {\n double p = pow ( params.slp, params.al + params.be + 1.0 );\n size_t k;\n\n for ( k = 0; k < n; k++ )\n {\n w->x[k] = params.shft + params.slp * w->x[k];\n w->weights[k] = w->weights[k] * p;\n }\n }\n\n return GSL_SUCCESS;\n}\n\n/******************************************************************************/\n/*\n Purpose:\n\n IMTQLX diagonalizes a symmetric tridiagonal matrix.\n\n Discussion:\n\n This routine is a slightly modified version of the EISPACK routine to \n perform the implicit QL algorithm on a symmetric tridiagonal matrix. \n\n The authors thank the authors of EISPACK for permission to use this\n routine. \n\n It has been modified to produce the product Q' * Z, where Z is an input \n vector and Q is the orthogonal matrix diagonalizing the input matrix. \n The changes consist (essentially) of applying the orthogonal transformations\n directly to Z as they are generated.\n\n Licensing:\n\n This code is distributed under the GNU LGPL license. \n\n Modified:\n\n 11 January 2010\n\n Author:\n\n Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.\n C version by John Burkardt.\n\n Reference:\n\n Sylvan Elhay, Jaroslav Kautsky,\n Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of \n Interpolatory Quadrature,\n ACM Transactions on Mathematical Software,\n Volume 13, Number 4, December 1987, pages 399-415.\n\n Roger Martin, James Wilkinson,\n The Implicit QL Algorithm,\n Numerische Mathematik,\n Volume 12, Number 5, December 1968, pages 377-383.\n\n Parameters:\n\n Input, int N, the order of the matrix.\n\n Input/output, double D(N), the diagonal entries of the matrix.\n On output, the information in D has been overwritten.\n\n Input/output, double E(N), the subdiagonal entries of the \n matrix, in entries E(1) through E(N-1). On output, the information in\n E has been overwritten.\n\n Input/output, double Z(N). On input, a vector. On output,\n the value of Q' * Z, where Q is the matrix that diagonalizes the\n input symmetric tridiagonal matrix.\n*/\n\nstatic int\nimtqlx ( const int n, double d[], double e[], double z[] )\n{\n double b;\n double c;\n double f;\n double g;\n int i;\n int ii;\n int itn = 30;\n int j;\n int k;\n int l;\n int m;\n int mml;\n double p;\n double r;\n double s;\n\n if ( n == 1 )\n {\n return GSL_SUCCESS;\n }\n\n e[n-1] = 0.0;\n\n for ( l = 1; l <= n; l++ )\n {\n j = 0;\n for ( ; ; )\n {\n for ( m = l; m <= n; m++ )\n {\n if ( m == n )\n {\n break;\n }\n\n if ( fabs ( e[m-1] ) <= GSL_DBL_EPSILON * ( fabs ( d[m-1] ) + fabs ( d[m] ) ) )\n {\n break;\n }\n }\n p = d[l-1];\n if ( m == l )\n {\n break;\n }\n if ( itn <= j )\n {\n return GSL_EMAXITER;\n }\n j = j + 1;\n g = ( d[l] - p ) / ( 2.0 * e[l-1] );\n r = sqrt ( g * g + 1.0 );\n g = d[m-1] - p + e[l-1] / ( g + fabs ( r ) * GSL_SIGN ( g ) );\n s = 1.0;\n c = 1.0;\n p = 0.0;\n mml = m - l;\n\n for ( ii = 1; ii <= mml; ii++ )\n {\n i = m - ii;\n f = s * e[i-1];\n b = c * e[i-1];\n\n if ( fabs ( g ) <= fabs ( f ) )\n {\n c = g / f;\n r = sqrt ( c * c + 1.0 );\n e[i] = f * r;\n s = 1.0 / r;\n c = c * s;\n }\n else\n {\n s = f / g;\n r = sqrt ( s * s + 1.0 );\n e[i] = g * r;\n c = 1.0 / r;\n s = s * c;\n }\n g = d[i] - p;\n r = ( d[i-1] - g ) * s + 2.0 * c * b;\n p = s * r;\n d[i] = g + p;\n g = c * r - b;\n f = z[i];\n z[i] = s * z[i-1] + c * f;\n z[i-1] = c * z[i-1] - s * f;\n }\n d[l-1] = d[l-1] - p;\n e[l-1] = g;\n e[m-1] = 0.0;\n }\n }\n/*\n Sorting.\n*/\n for ( ii = 2; ii <= m; ii++ )\n {\n i = ii - 1;\n k = i;\n p = d[i-1];\n\n for ( j = ii; j <= n; j++ )\n {\n if ( d[j-1] < p )\n {\n k = j;\n p = d[j-1];\n }\n }\n\n if ( k != i )\n {\n d[k-1] = d[i-1];\n d[i-1] = p;\n p = z[i-1];\n z[i-1] = z[k-1];\n z[k-1] = p;\n }\n }\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "746e5fb3491b92b44a77a74100f8e3586edc329e", "size": 9041, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/integration/fixed.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/integration/fixed.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/integration/fixed.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": 22.0512195122, "max_line_length": 98, "alphanum_fraction": 0.557018029, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4511351734991332}} {"text": "/* 生成sample for Regression */\n/* theta12, m21 fixed */\n/* theta23, theta13, m31 flat distribution in 3 sigma range */\n/* deltacp flat distribution in 0~360 */\n\n/* 使用方式(產100K組) : ./sample_regression */\n/* Caution: `num` should not greater than 1000. */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include /* GLoBES library */\n\n#include /* GNU Scientific library (required for root finding) */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hdf5.h\"\n\n#define degree M_PI/180\n\n/***************************************************************************\n * M A I N P R O G R A M *\n ***************************************************************************/\n\nfloat keithRandom() {\n\t// Random number function based on the GNU Scientific Library\n\t// Returns a random float between 0 and 1, exclusive; e.g., (0,1)\n\tconst \tgsl_rng_type * T;\n\tgsl_rng * r;\n\tgsl_rng_env_setup();\n\tstruct \ttimeval tv; // Seed generation based on time\n\tgettimeofday(&tv,0);\n\tunsigned long mySeed = tv.tv_sec + tv.tv_usec;\n\tT = gsl_rng_default; // Generator setup\n\tr = gsl_rng_alloc (T);\n\tgsl_rng_set(r, mySeed);\n\tdouble u = gsl_rng_uniform(r); // Generate it!\n\tgsl_rng_free (r);\n\treturn (float)u;\n}\n\n\ndouble randn (double mu, double sigma) {\n\t/*mu is the central value, sigma is the width of gaussian distribution. */\n\tdouble U1, U2, W, mult;\n\tstatic double X1, X2;\n\tstatic int call = 0;\n \n\tif (call == 1) {\n\t\tcall = !call;\n\t\treturn (mu + sigma * (double) X2);\n\t}\n \n\tdo{\n\t\tU1 = -1 + ((double) rand () / RAND_MAX) * 2;\n\t\tU2 = -1 + ((double) rand () / RAND_MAX) * 2;\n\t\tW = pow (U1, 2) + pow (U2, 2);\n\t} while (W >= 1 || W == 0);\n \n\tmult = sqrt ((-2 * log (W)) / W);\n\tX1 = U1 * mult;\n\tX2 = U2 * mult;\n\n\tcall = !call;\n\n\treturn (mu + sigma * (double) X1);\n}\n\ndouble TCRandom(double mu, double sigma) {\n\t// Random number function based on the GNU Scientific Library\n\t// Returns a random float between 0 and 1, exclusive; e.g., (0,1)\n\tconst \tgsl_rng_type * T;\n\tgsl_rng * r;\n\tgsl_rng_env_setup();\n\tstruct \ttimeval tv; // Seed generation based on time\n\tgettimeofday(&tv,0);\n\tunsigned long mySeed = tv.tv_sec + tv.tv_usec;\n\tT = gsl_rng_default; // Generator setup\n\tr = gsl_rng_alloc (T);\n\tgsl_rng_set(r, mySeed);\n\tdouble u = mu + gsl_ran_gaussian(r, sigma); // Generate it!\n\tgsl_rng_free (r);\n\n\treturn u;\n}\n\nint case_judger (int mode, double value) {\n\t/*\n\t * mode 1: Octant;\n\t * mode 2: CPV;\n\t * mode 3: MO;\n\t */\n\tint result;\n\tswitch (mode){\n\t\tcase 1:\n\t\t\tif ((value == 0) || (value==180)){\n\t\t\t\tresult = 0;\n\t\t\t} else {\n\t\t\t\tresult = 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif (value > 45) {\n\t\t\t\tresult = 1;\n\t\t\t} else if (value == 45) {\n\t\t\t\tresult = 0;\n\t\t\t} else {\n\t\t\t\tresult = -1;\n\t\t\t}\n\t\t\tbreak;\n\tcase 3:\n\t\tresult = value > 0 ? 1 : -1;\n\t\tbreak;\n\t}\n\treturn result;\n}\n\nint main(int argc, char *argv[]) { \n\n\t/* Initialize GLoBES and define chi^2 functions */\n\tglbInit(argv[0]); \n\n\t/*\n\t * Read the prefix of file name and add suffix to two child string.\n\t */\n\tchar \tfilename[32],\n\t \t \tGroup_name[32],\n\t\t \tchannel_info_dset_name[] = \"/Spectrum/expr_0/channel_0\\0\",\n\t\t \tsize_info_dset_name[] = \"/Spectrum/expr_0/channel_0/Bin_ize\\0\",\n\t\t \tenergy_info_dset_name[] = \"/Spectrum/expr_0/channel_0/Bin_energy\\0\",\n\t\t \texpr_info_dset_name[] = \"/Spectrum/expr_0\\0\";\n\tstrcpy(filename, argv[1]);\n\n\tint \tTOTALsample = atof(argv[2]);\n\n /*\n * Declare the variables for hdf5.\n */\n hid_t\tfile_id, \n\t\t\tspace_id, \n\t\t\tdset_id,\n\t\t\tgroup_id,\n\t\t\tsub_group_id,\n\t\t\tsub2_group_id,\n\t\t\tsub3_group_id;\n herr_t \tstatus;\n hsize_t\tdims[2];\n\n\t/*\n\t * Initialize experiment parameters.\n\t */\n\tglbInitExperiment(\"./DUNE2021/DUNE_GLoBES.glb\",&glb_experiment_list[0],&glb_num_of_exps);\n\tglbInitExperiment(\"./HK_globes/HK_combined_coarse.glb\",&glb_experiment_list[0],&glb_num_of_exps);\n\tglb_params true_values = glbAllocParams();\n\n\t/* Set standard oscillation parameters (cf. hep-ph/0405172v5) */\n\tdouble theta12_c = 33.44; \n\t// double theta13_c = 8.57;\n\t// double theta23_c = 45;\n\tdouble sdm_c = 7.42;\n\t// double ldm_c = 2.514;\n\n\n\tdouble delta_12 = (35.86 - 31.27)/2;\n\tdouble delta_13 = (8.97 - 8.20)/2;\n\tdouble delta_23 = (51.80 - 39.60)/2;\n\tdouble delta_sdm = (8.04 - 6.82)/2;\n\tdouble delta_ldm = (2.598 - 2.431)/2;\n\n\tint num_simulatiom;\n\n\tint ew_low, ew_high;\n\tint i, j, num_expriment, channel;\n \n\tfile_id = H5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\tgroup_id = H5Gcreate(file_id, \"/Spectrum\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tfor ( num_expriment = 0; num_expriment < 2; num_expriment++){\n\t\tdouble *bin_c_energy = glbGetBinCentersListPtr( num_expriment );\n\t\tdouble *bin_size = glbGetBinSizeListPtr( num_expriment );\n\t\tint channel_max = glbGetNumberOfRules( num_expriment );\n\t\t\n\t\texpr_info_dset_name[15] = num_expriment+'0';\n\t\tsub_group_id = H5Gcreate(file_id, expr_info_dset_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\t\tfor(channel=0;channel360){\n\t\t\tdeltacp=180;\n\t\t}\n\n\t\t//double deltacp = keithRandom() * 360.0;\n\n\t\tint octant = case_judger(1, theta23);\n\t\tint cpv = case_judger(2, deltacp);\n\t\tint mo = case_judger(3, ldm);\n\n\t\tglbDefineParams(true_values,theta12_c*degree,theta13*degree,theta23*degree,deltacp*degree,1e-5*sdm_c,1e-3*ldm);\n\t\tglbSetDensityParams(true_values,1.0,GLB_ALL);\n\n\t\tglbSetOscillationParameters(true_values);\n\t\tglbSetRates();\n\t \n\t\tnum_expriment = 0;\n\t\tchannel = 0; \n\n\t\tfor ( num_expriment = 0; num_expriment < 2; num_expriment++){\n\t\t\tint channel_max = glbGetNumberOfRules( num_expriment );\t\t\n\t\t\tfor ( channel = 0; channel < channel_max ; channel++){\n\t\t\t\tglbGetEnergyWindowBins( num_expriment, channel, &ew_low, &ew_high);\n\t\t\t\tdouble *true_rates = glbGetRuleRatePtr( num_expriment, channel );\n\t\t\t\tint count = 0;\n\t\t\t\tfor (i=ew_low; i <= ew_high; i++){\n\t\t\t\t\tTRUE_RATE[num_simulatiom][num_expriment][channel][count] = true_rates[i];\n\t\t\t\t\tcount += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t \tdouble tmp_array[9] = {theta12_c, theta13, theta23, deltacp, sdm_c, ldm, octant, cpv, mo};\n\t\tint count = 0;\n\t\tfor ( count = 0; count < 9; count++){\n\t\t\tdataset[num_simulatiom][count] = tmp_array[count];\n\t\t}\n\t}\n\tint k, l;\n\tfor ( i = 0; i < TOTALsample; i++){\n\t\tfor ( j = 0; j < 2; j++){\n\t\t\tfor ( k = 0; k < 4; k++){\n\t\t\t\tfor ( l = 0; l < 8; l++){\n\t\t\t \t\tTRUE_RATE_PRIME[j][k][l][i] = TRUE_RATE[i][j][k][l];\n\t\t\t \t}\n\t\t\t}\n\t\t}\n\t}\n\n\tchar \tchannel_spec_true_name[] = \"/Parameter/true/expr_0/channel_0\\0\",\n\t\t \texpr_spec_true_name[] = \"/Parameter/true/expr_0\\0\", \n\t\t \texpr_spec_sim_name[] = \"/Parameter/simulation\\0\";\n \n\thsize_t dims_s[2] = {TOTALsample, 8};\n\tgroup_id \t\t = H5Gcreate(file_id, \"/Parameter\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tsub_group_id \t\t = H5Gcreate(file_id, \"/Parameter/true/\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tfor ( i = 0; i < 2; i ++){\n\t\texpr_spec_true_name[21] = i+'0';\n\t\tsub2_group_id = H5Gcreate(file_id, expr_spec_true_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\t\tfor ( j = 0; j < 4; j++){\n\t\t\tchannel_spec_true_name[21] = i+'0';\n\t\t\tchannel_spec_true_name[31] = j+'0';\n\t\t\tspace_id = H5Screate_simple(2, dims_s, NULL);\n\t\t\tdset_id = H5Dcreate(sub2_group_id, channel_spec_true_name, H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT,\n\t\t\t\t H5P_DEFAULT);\n\t\t\tstatus = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, TRUE_RATE_PRIME[i][j]);\n\t\t\tstatus = H5Dclose(dset_id);\n\t\t\tstatus = H5Sclose(space_id);\n\t\t}\n\t\tstatus = H5Gclose(sub2_group_id);\n\t}\n status = H5Gclose(sub_group_id);\n \n\thsize_t dims_d[2] = \t{TOTALsample, 9};\n\tsub_group_id \t\t = H5Gcreate(file_id, \"/Parameter/simulation/\", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tspace_id \t\t = H5Screate_simple(2, dims_d, NULL);\n\tdset_id \t\t = H5Dcreate(sub_group_id, \"/Parameter/simulation/dataset\", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT,\n\t\t H5P_DEFAULT);\n\tstatus \t\t = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, dataset);\n\tstatus \t\t = H5Dclose(dset_id);\n\tstatus \t\t = H5Sclose(space_id);\n\tstatus \t\t = H5Gclose(sub_group_id); \n\tstatus \t\t = H5Gclose(group_id);\n\n\t/* Clean up */\n\tglbFreeParams(true_values);\n\n\tstatus = H5Fclose(file_id);\n\treturn 0; \n}\n", "meta": {"hexsha": "220db0958479fe160b00cea89050cfc03d188791", "size": 11269, "ext": "c", "lang": "C", "max_stars_repo_path": "script/simulation/sample_classification.c", "max_stars_repo_name": "davidho27941/ML4NO", "max_stars_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "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": "script/simulation/sample_classification.c", "max_issues_repo_name": "davidho27941/ML4NO", "max_issues_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "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": "script/simulation/sample_classification.c", "max_forks_repo_name": "davidho27941/ML4NO", "max_forks_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T16:25:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T16:25:35.000Z", "avg_line_length": 32.382183908, "max_line_length": 132, "alphanum_fraction": 0.6348389387, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.45081224250652985}} {"text": "#include \n#include \n#include \n\n#include \"icp.h\"\n#include \"../csm_all.h\"\n\n\nval compute_C_k(val p_j1, val p_j2);\nval dC_drho(val p1, val p2);\n\n\nvoid compute_covariance_exact(\n\tLDP laser_ref, LDP laser_sens, const gsl_vector*x,\n\t\tval *cov0_x, val *dx_dy1, val *dx_dy2)\n{\n\tegsl_push_named(\"compute_covariance_exact\");\n\t\n\tval d2J_dxdy1 = zeros(3,(size_t)laser_ref ->nrays);\n\tval d2J_dxdy2 = zeros(3,(size_t)laser_sens->nrays);\n\t\n\t/* the three pieces of d2J_dx2 */\n\tval d2J_dt2 = zeros(2,2);\n\tval d2J_dt_dtheta = zeros(2,1);\n\tval d2J_dtheta2 = zeros(1,1);\n\t\n\tdouble theta = x->data[2];\n\tval t = egsl_vFa(2,x->data);\n\t\n\tint i; \n\tfor(i=0;inrays;i++) {\n\t\tif(!ld_valid_corr(laser_sens,i)) continue;\n\t\tegsl_push_named(\"compute_covariance_exact iteration\");\n\n\t\tint j1 = laser_sens->corr[i].j1;\n\t\tint j2 = laser_sens->corr[i].j2;\n\n\t\tval p_i = egsl_vFa(2, laser_sens->points[i].p);\n\t\tval p_j1 = egsl_vFa(2, laser_ref ->points[j1].p);\n\t\tval p_j2 = egsl_vFa(2, laser_ref ->points[j2].p);\n\t\t\n\t\t/* v1 := rot(theta+M_PI/2)*p_i */\n\t\tval v1 = m(rot(theta+M_PI/2), p_i);\t\t\n\t\t/* v2 := (rot(theta)*p_i+t-p_j1) */\n\t\tval v2 = sum3( m(rot(theta),p_i), t, minus(p_j1));\n\t\t/* v3 := rot(theta)*v_i */\n\t\tval v3 = vers(theta + laser_sens->theta[i]);\n\t\t/* v4 := rot(theta+PI/2)*v_i; */\n\t\tval v4 = vers(theta + laser_sens->theta[i] + M_PI/2);\n\t\t\n\t\tval C_k = compute_C_k(p_j1, p_j2);\n\t\t\n\t\tval d2J_dt2_k = sc(2.0, C_k);\n\t\tval d2J_dt_dtheta_k = sc(2.0,m(C_k,v1));\n\t\t\n\t\tval v_new = m(rot(theta+M_PI), p_i);\n\t\tval d2J_dtheta2_k = sc(2.0, sum( m3(tr(v2),C_k, v_new), m3(tr(v1),C_k,v1)));\n\t\tadd_to(d2J_dt2, d2J_dt2_k);\n\t\tadd_to(d2J_dt_dtheta, d2J_dt_dtheta_k ); \n\t\tadd_to(d2J_dtheta2, d2J_dtheta2_k);\n\t\t\n\t\t/* for measurement rho_i in the second scan */\n\t\tval d2Jk_dtdrho_i = sc(2.0, m(C_k,v3)); \n\t\tval d2Jk_dtheta_drho_i = sc(2.0, sum( m3(tr(v2),C_k,v4), m3(tr(v3),C_k,v1)));\n \t\tadd_to_col(d2J_dxdy2, (size_t)i, comp_col(d2Jk_dtdrho_i, d2Jk_dtheta_drho_i));\n\t\t\n\t\t/* for measurements rho_j1, rho_j2 in the first scan */\n\t\t\n\t\tval dC_drho_j1 = dC_drho(p_j1, p_j2);\n\t\tval dC_drho_j2 = dC_drho(p_j2, p_j1);\n\t\n\t\t\n\t\tval v_j1 = vers(laser_ref->theta[j1]);\n\t\t\n\t\tval d2Jk_dt_drho_j1 = sum(sc(-2.0,m(C_k,v_j1)), sc(2.0,m(dC_drho_j1,v2)));\n\t\tval d2Jk_dtheta_drho_j1 = sum( sc(-2.0, m3(tr(v_j1),C_k,v1)), m3(tr(v2),dC_drho_j1,v1));\n\t\tadd_to_col(d2J_dxdy1, (size_t)j1, comp_col(d2Jk_dt_drho_j1, d2Jk_dtheta_drho_j1));\n\t\t\n\t\t/* for measurement rho_j2*/\n\t\tval d2Jk_dt_drho_j2 = sc(2.0, m( dC_drho_j2,v2));\n\t\tval d2Jk_dtheta_drho_j2 = sc(2.0, m3( tr(v2), dC_drho_j2, v1));\n\t\tadd_to_col(d2J_dxdy1, (size_t)j2, comp_col(d2Jk_dt_drho_j2, d2Jk_dtheta_drho_j2));\n\n\t\tegsl_pop_named(\"compute_covariance_exact iteration\");\n\t}\n\n\t/* composes matrix d2J_dx2 from the pieces*/\n\tval d2J_dx2 = comp_col( comp_row( d2J_dt2 , d2J_dt_dtheta),\n\t comp_row(tr(d2J_dt_dtheta), d2J_dtheta2));\n\t\n\tval edx_dy1 = sc(-1.0, m(inv(d2J_dx2), d2J_dxdy1));\n\tval edx_dy2 = sc(-1.0, m(inv(d2J_dx2), d2J_dxdy2));\n\n\tval ecov0_x = sum(m(edx_dy1,tr(edx_dy1)),m(edx_dy2,tr(edx_dy2)) );\n\n\t/* With the egsl_promote we save the matrix in the previous\n\t context */\n\t*cov0_x = egsl_promote(ecov0_x);\n\t*dx_dy1 = egsl_promote(edx_dy1);\n\t*dx_dy2 = egsl_promote(edx_dy2);\n\t\n\tegsl_pop_named(\"compute_covariance_exact\");\t\n\t/* now edx_dy1 is not valid anymore, but *dx_dy1 is. */\n}\n\n\nval compute_C_k(val p_j1, val p_j2) {\t\n\tval d = sub(p_j1, p_j2);\n\tdouble alpha = M_PI/2 + atan2( atv(d,1), atv(d,0));\n\tdouble c = cos(alpha); double s = sin(alpha);\n\tdouble m[2*2] = {\n\t\tc*c, c*s,\n\t\tc*s, s*s\n\t};\n\treturn egsl_vFda(2,2,m);\n}\n\n\nval dC_drho(val p1, val p2) {\n\tdouble eps = 0.001;\n\n\tval C_k = compute_C_k(p1, p2);\t\n\tval p1b = sum(p1, sc(eps/egsl_norm(p1),p1));\n\tval C_k_eps = compute_C_k(p1b,p2);\n\treturn sc(1/eps, sub(C_k_eps,C_k));\n}\n\n\n", "meta": {"hexsha": "3d4db6447add915f705ddcedaccb954a4c5c4af1", "size": 3838, "ext": "c", "lang": "C", "max_stars_repo_path": "src/csm/sm/csm/icp/icp_covariance.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/icp/icp_covariance.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/icp/icp_covariance.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": 29.7519379845, "max_line_length": 90, "alphanum_fraction": 0.6578947368, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4508122425065298}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Compute cumulative comoving mass function\ntypedef struct mass_function_cumulative_params_struct mass_function_cumulative_params;\nstruct mass_function_cumulative_params_struct {\n cosmo_info **cosmo;\n double z;\n int mode;\n double * P;\n};\ndouble mass_function_cumulative_integrand(double lM, void *params_in);\ndouble mass_function_cumulative_integrand(double lM, void *params_in) {\n mass_function_cumulative_params *params;\n params = (mass_function_cumulative_params *)params_in;\n double M = take_alog10(lM);\n double r_val = mass_function(M, params->z, params->cosmo, params->mode, params->P);\n return (r_val);\n}\ndouble mass_function_cumulative(double M_interp, double z, cosmo_info **cosmo, int mode, ...) {\n va_list vargs;\n va_start(vargs, mode);\n\n // Get passed parameters (if mode specifies they are there).\n double *P = NULL;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS))\n P = (double *)va_arg(vargs, double *);\n\n // Initialize integral\n if(!ADaPS_exist((*cosmo), \"lk_P\"))\n init_power_spectrum_TF(cosmo);\n double *lk_P = (double *)ADaPS_fetch((*cosmo), \"lk_P\");\n double limit_lo = take_log10(M_interp);\n double limit_hi = take_log10(M_of_k(take_alog10(lk_P[0]), (*cosmo)));\n\n // Perform integral\n int n_int = 5000;\n double rel_accuracy = 1e-4;\n double r_val = 0.;\n if(limit_lo < limit_hi) {\n double abs_error;\n mass_function_cumulative_params params;\n gsl_function integrand;\n gsl_integration_workspace * wspace;\n params.z = z;\n params.cosmo = cosmo;\n params.mode = mode;\n params.P = P;\n integrand.function = mass_function_cumulative_integrand;\n integrand.params = (void *)(¶ms);\n wspace = gsl_integration_workspace_alloc(n_int);\n\n // Integrate mass function\n gsl_integration_qag(&integrand, limit_lo, limit_hi, 0, rel_accuracy, n_int, GSL_INTEG_GAUSS61, wspace, &r_val, &abs_error);\n\n // Clean-up\n gsl_integration_workspace_free(wspace);\n }\n\n va_end(vargs);\n return (r_val);\n}\n", "meta": {"hexsha": "bd965e2ecefbd99704919a5df49d027283704c2c", "size": 2485, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/mass_function_cumulative.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 35.0, "max_line_length": 131, "alphanum_fraction": 0.6519114688, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.45076479472510084}} {"text": "//This does CELL (~soma) stage of GRU (gated recurrent unit) model.\n//This requires each neuron to have 3 input time series, X, Xr, Xz,\n//where X is the usual input and Xr, Xz the inputs for the reset and update gates,\n//stacked into X = [X; Xr; Xz] for dim=0, or X = [X Xr Xz] for dim=1.\n\n//For dim=0, R[:,t] = sig{Xr[:,t] + Ur*Y[:,t-1]} \\n\";\n// Z[:,t] = sig{Xz[:,t] + Uz*Y[:,t-1]} \\n\";\n// H[:,t] = R[:,t].*Y[:,t-1] \\n\";\n// Y[:,t] = Z[:,t].*Y[:,t-1] + (1-Z[:,t]).*tanh{X[:,t] + U*H[:,t]} \\n\";\n//with sizes X, Xr, Xz: N x T \\n\";\n// U, Ur, Uz: N x N \\n\";\n// Y : N x T \\n\";\n//\n//For dim=1, R[t,:] = sig{Xr[t,:] + Y[t-1,:]*Ur} \\n\";\n// Z[t,:] = sig{Xz[t,:] + Y[t-1,:]*Uz} \\n\";\n// H[t,:] = R[t,:].*Y[t-1,:] \\n\";\n// Y[t,:] = Z[t,:].*Y[t-1,:] + (1-Z[t,:]).*tanh{X[t,:] + H[t,:]*U} \\n\";\n//with sizes X, Xr, Xz: T x N \\n\";\n// U, Ur, Uz: N x N \\n\";\n// Y : T x N \\n\";\n//\n//where sig is the logistic (sigmoid) nonlinearity = 1/(1+exp(-x)),\n//R is the reset gate, Z is the update gate, H is an intermediate (hidden) vector,\n//U, Ur, Uz are NxN matrices, and Y is the output.\n\n//Note that, the neurons of a layer are independent only if U, Ur, Uz are diagonal matrices.\n//This is only really a CELL (~soma) stage in that case.\n\n#include \n#include \n#include \n#include \n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint gru_s (float *Y, const float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru_d (double *Y, const double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\nint gru_inplace_s (float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\nint gru_inplace_d (double *X, const double *U, const double *Ur, const double *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim);\n\n\nint gru_s (float *Y, const float *X, const float *U, const float *Ur, const float *Uz, const size_t N, const size_t T, const char iscolmajor, const size_t dim)\n{\n const float o = 1.0f;\n const size_t N2 = 2*N, NT = N*T, NT2 = 2*N*T;\n size_t nT, tN, tN3;\n\n float *R, *Z, *H;\n if (!(R=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(Z=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru_s: problem with malloc. \"); perror(\"malloc\"); return 1; }\n if (!(H=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,\"error in gru_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\n#include \n#include \n#include \n#include \n\nstruct refine_offset_params {\n meta_parameters *meta;\n double x_off, y_off;\n};\n\nstatic double err_at_pixel(struct refine_offset_params *p, double off_t,\n double off_x, double line, double samp)\n{\n const double huge_err = 999999.9;\n\n meta_parameters *meta = p->meta;\n double line_out, samp_out;\n double lat, lon;\n int bad=0;\n\n double saved_timeOffset = meta->sar->time_shift;\n double saved_slant = meta->sar->slant_shift;\n\n // converting the pixel's location back to lat/lon is done before\n // applying the prospective slant and range shifts. \n bad = meta_get_latLon(meta, line, samp, 0.0, &lat, &lon);\n if (bad) { printf(\"bad: meta_get_latLon\\n\"); return huge_err; }\n\n meta->sar->time_shift += off_t;\n meta->sar->slant_shift += off_x;\n\n bad = meta_get_lineSamp(meta, lat, lon, 0.0, &line_out, &samp_out);\n\n meta->sar->time_shift = saved_timeOffset;\n meta->sar->slant_shift = saved_slant;\n\n // meta_get_lineSamp returns a non-zero value if, for the specified\n // lat&lon, we weren't able to determine a line & sample. In this case,\n // we just return a giant error value.\n if (bad) { printf(\"bad: meta_get_lineSamp\\n\"); return huge_err; }\n\n //printf(\"trying %f,%f\\n\",off_t,off_x);\n //printf(\"at %7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f,%7.3f -> %7.3f\\n\",\n // off_t, off_x, line, samp, line_out, samp_out, p->y_off, p->x_off,\n // fabs(line-line_out-p->y_off)+fabs(samp-samp_out-p->x_off));\n double xdiff = line_out - line - p->y_off;\n double ydiff = samp_out - samp - p->x_off;\n return sqrt(xdiff*xdiff + ydiff*ydiff);\n}\n\nstatic int\ngetObjective(const gsl_vector *x, void *params, gsl_vector *f)\n{\n double off_t = gsl_vector_get(x,0);\n double off_x = gsl_vector_get(x,1);\n\n if (!meta_is_valid_double(off_x) ||\n !meta_is_valid_double(off_t)) {\n // This does happen sometimes, when we've already found the root\n\treturn GSL_FAILURE;\n }\n\n struct refine_offset_params *p = (struct refine_offset_params *)params;\n meta_parameters *meta = p->meta;\n\n int nl = meta->general->line_count;\n int ns = meta->general->sample_count;\n\n double err = 0.0;\n\n err += err_at_pixel(p, off_t, off_x, nl/8, ns/8); \n err += err_at_pixel(p, off_t, off_x, 7*nl/8, ns/8);\n err += err_at_pixel(p, off_t, off_x, nl/8, 7*ns/8); \n err += err_at_pixel(p, off_t, off_x, 7*nl/8, 7*ns/8); \n\n err += err_at_pixel(p, off_t, off_x, nl/8, ns/2); \n err += err_at_pixel(p, off_t, off_x, 7*nl/8, ns/2);\n err += err_at_pixel(p, off_t, off_x, nl/2, 7*ns/8); \n err += err_at_pixel(p, off_t, off_x, nl/2, ns/8); \n\n err += err_at_pixel(p, off_t, off_x, nl/2, ns/2); \n \n gsl_vector_set(f,0,err);\n gsl_vector_set(f,1,err);\n return GSL_SUCCESS;\n}\n\n/*\nstatic void print_state(int iter, gsl_multiroot_fsolver *s)\n{\n printf(\"iter = %3d x = (%.3f %.3f) f(x) = %.8f\\n\", iter,\n gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1),\n gsl_vector_get(s->f, 0));\n}\n*/\n\nstatic void coarse_search(double t_extent_min, double t_extent_max,\n double x_extent_min, double x_extent_max,\n double *t_min, double *x_min,\n struct refine_offset_params *params)\n{\n double the_min = 9999999;\n double min_t=99, min_x=99;\n int i,j,k=6;\n double t_extent = t_extent_max - t_extent_min;\n double x_extent = x_extent_max - x_extent_min;\n gsl_vector *v = gsl_vector_alloc(2);\n gsl_vector *u = gsl_vector_alloc(2);\n //printf(\" \");\n //for (j = 0; j <= k; ++j) {\n // double x = x_extent_min + ((double)j)/k*x_extent;\n // printf(\"%9.3f \", x);\n //}\n //printf(\"\\n \");\n //for (j = 0; j <= k; ++j)\n // printf(\"--------- \");\n //printf(\"\\n\");\n for (i = 0; i <= k; ++i) {\n double t = t_extent_min + ((double)i)/k*t_extent;\n //printf(\"%9.3f | \", t);\n\n for (j = 0; j <= k; ++j) {\n double x = x_extent_min + ((double)j)/k*x_extent;\n\n gsl_vector_set(v, 0, t);\n gsl_vector_set(v, 1, x);\n getObjective(v,(void*)params, u);\n double n = gsl_vector_get(u,0);\n //printf(\"%9.3f \", n);\n if (nf, 1e-8);\n } while (status == GSL_CONTINUE && iter < max_iter);\n\n *out_t = gsl_vector_get(s->x, 0);\n *out_x = gsl_vector_get(s->x, 1);\n\n gsl_vector *retrofit = gsl_vector_alloc(n);\n gsl_vector_set(retrofit, 0, *out_t);\n gsl_vector_set(retrofit, 1, *out_x);\n gsl_vector *output = gsl_vector_alloc(n);\n getObjective(retrofit, (void*)¶ms, output);\n //double val= gsl_vector_get(output,0);\n //printf(\"GSL Result: %f at (%f,%f)\\n\", val, *out_t, *out_x);\n gsl_vector_free(retrofit);\n gsl_vector_free(output);\n\n gsl_multiroot_fsolver_free(s);\n gsl_vector_free(x);\n gsl_set_error_handler(prev);\n}\n\n", "meta": {"hexsha": "eb86850f5725bae2db0c91acea875da4f5c30ea6", "size": 7456, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_sar/refine_offset.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/libasf_sar/refine_offset.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/libasf_sar/refine_offset.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": 30.1862348178, "max_line_length": 78, "alphanum_fraction": 0.5971030043, "num_tokens": 2236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4506170902755016}} {"text": "/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n/* */\n/* Linear Algebra Data and Routines File */\n/* */\n/* Generated by KPP-2.2 symbolic chemistry Kinetics PreProcessor */\n/* (http://www.cs.vt.edu/~asandu/Software/KPP) */\n/* KPP is distributed under GPL, the general public licence */\n/* (http://www.gnu.org/copyleft/gpl.html) */\n/* (C) 1995-1997, V. Damian & A. Sandu, CGRER, Univ. Iowa */\n/* (C) 1997-2005, A. Sandu, Michigan Tech, Virginia Tech */\n/* With important contributions from: */\n/* M. Damian, Villanova University, USA */\n/* R. Sander, Max-Planck Institute for Chemistry, Mainz, Germany */\n/* */\n/* File : saprc99_LinearAlgebra.c */\n/* Time : Wed Jun 11 10:09:48 2008 */\n/* Working directory : /Users/jlinford/workspace/saprc99 */\n/* Equation file : saprc99.kpp */\n/* Output root filename : saprc99 */\n/* */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n#define USE_SDK_BLAS 0\n\n#include \n#include \n#include \n#include \n#include \"saprc99_Parameters.h\"\n#include \"saprc99_Global.h\"\n#include \"saprc99_Sparse.h\"\n\n#if DO_CHEMISTRY == 1\n\n/* For SPU-optimized BLAS */\n#if USE_SDK_BLAS == 1\n#include \n#endif\n\n\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n/* */\n/* SPARSE_UTIL - SPARSE utility functions */\n/* Arguments : */\n/* */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n\nint KppDecomp( double *JVS )\n{\ndouble W[74];\ndouble a;\nint k, kk, j, jj;\n \n for( k = 0; k < 74; k++ ) {\n if( JVS[ LU_DIAG[k] ] == 0.0 ) return k+1;\n for( kk = LU_CROW[k]; kk < LU_CROW[k+1]; kk++ )\n W[ LU_ICOL[kk] ] = JVS[kk];\n for( kk = LU_CROW[k]; kk < LU_DIAG[k]; kk++ ) {\n j = LU_ICOL[kk];\n a = -W[j] / JVS[ LU_DIAG[j] ];\n W[j] = -a;\n for( jj = LU_DIAG[j]+1; jj < LU_CROW[j+1]; jj++ )\n W[ LU_ICOL[jj] ] += a*JVS[jj];\n }\n for( kk = LU_CROW[k]; kk < LU_CROW[k+1]; kk++ )\n JVS[kk] = W[ LU_ICOL[kk] ];\n }\n return 0;\n}\n\n/* End of SPARSE_UTIL function */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n/* */\n/* KppSolve - sparse back substitution */\n/* Arguments : */\n/* JVS - sparse Jacobian of variables */\n/* X - Vector for variables */\n/* */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\nvoid KppSolve( \n double JVS[], /* sparse Jacobian of variables */\n double X[] /* Vector for variables */\n)\n{\n X[21] = X[21]-JVS[91]*X[20];\n X[31] = X[31]-JVS[125]*X[23]-JVS[126]*X[30];\n X[32] = X[32]-JVS[129]*X[23]-JVS[130]*X[30];\n X[33] = X[33]-JVS[133]*X[23]-JVS[134]*X[30];\n X[34] = X[34]-JVS[138]*X[23]-JVS[139]*X[30];\n X[35] = X[35]-JVS[143]*X[27];\n X[37] = X[37]-JVS[154]*X[23]-JVS[155]*X[30];\n X[38] = X[38]-JVS[161]*X[30];\n X[39] = X[39]-JVS[167]*X[19]-JVS[168]*X[29]-JVS[169]*X[31]-JVS[170]\n *X[32]-JVS[171]*X[34];\n X[40] = X[40]-JVS[190]*X[23]-JVS[191]*X[30]-JVS[192]*X[31]-JVS[193]\n *X[32]-JVS[194]*X[33];\n X[41] = X[41]-JVS[202]*X[19]-JVS[203]*X[20]-JVS[204]*X[21]-JVS[205]\n *X[22]-JVS[206]*X[29];\n X[42] = X[42]-JVS[216]*X[17]-JVS[217]*X[33]-JVS[218]*X[35]-JVS[219]\n *X[37]-JVS[220]*X[38]-JVS[221]*X[40];\n X[44] = X[44]-JVS[242]*X[19]-JVS[243]*X[23]-JVS[244]*X[30]-JVS[245]\n *X[31]-JVS[246]*X[32]-JVS[247]*X[34]-JVS[248]*X[38]-JVS[249]\n *X[43];\n X[45] = X[45]-JVS[259]*X[33]-JVS[260]*X[38];\n X[47] = X[47]-JVS[276]*X[20]-JVS[277]*X[22]-JVS[278]*X[29]-JVS[279]\n *X[31]-JVS[280]*X[32]-JVS[281]*X[41]-JVS[282]*X[46];\n X[49] = X[49]-JVS[310]*X[46];\n X[51] = X[51]-JVS[322]*X[46];\n X[53] = X[53]-JVS[334]*X[46]-JVS[335]*X[52];\n X[54] = X[54]-JVS[341]*X[10]-JVS[342]*X[20]-JVS[343]*X[22]-JVS[344]\n *X[29]-JVS[345]*X[43]-JVS[346]*X[50]-JVS[347]*X[51]-JVS[348]\n *X[52];\n X[55] = X[55]-JVS[363]*X[19]-JVS[364]*X[20]-JVS[365]*X[22]-JVS[366]\n *X[25]-JVS[367]*X[26]-JVS[368]*X[28]-JVS[369]*X[29]-JVS[370]\n *X[41]-JVS[371]*X[43]-JVS[372]*X[44]-JVS[373]*X[45]-JVS[374]\n *X[46]-JVS[375]*X[48]-JVS[376]*X[49]-JVS[377]*X[50]-JVS[378]\n *X[51]-JVS[379]*X[52]-JVS[380]*X[53];\n X[56] = X[56]-JVS[399]*X[21]-JVS[400]*X[48]-JVS[401]*X[50]-JVS[402]\n *X[51]-JVS[403]*X[52];\n X[57] = X[57]-JVS[412]*X[9]-JVS[413]*X[43]-JVS[414]*X[46]-JVS[415]\n *X[48]-JVS[416]*X[49]-JVS[417]*X[50]-JVS[418]*X[52]-JVS[419]\n *X[53];\n X[58] = X[58]-JVS[426]*X[19]-JVS[427]*X[20]-JVS[428]*X[22]-JVS[429]\n *X[29]-JVS[430]*X[31]-JVS[431]*X[32]-JVS[432]*X[34]-JVS[433]\n *X[36]-JVS[434]*X[43]-JVS[435]*X[48]-JVS[436]*X[49]-JVS[437]\n *X[50]-JVS[438]*X[51]-JVS[439]*X[52]-JVS[440]*X[53]-JVS[441]\n *X[56]-JVS[442]*X[57];\n X[59] = X[59]-JVS[454]*X[20]-JVS[455]*X[22]-JVS[456]*X[29]-JVS[457]\n *X[49]-JVS[458]*X[50]-JVS[459]*X[51]-JVS[460]*X[52]-JVS[461]\n *X[53]-JVS[462]*X[56]-JVS[463]*X[57];\n X[60] = X[60]-JVS[474]*X[22]-JVS[475]*X[29]-JVS[476]*X[30]-JVS[477]\n *X[46]-JVS[478]*X[48]-JVS[479]*X[50]-JVS[480]*X[51]-JVS[481]\n *X[52]-JVS[482]*X[53]-JVS[483]*X[56]-JVS[484]*X[57];\n X[61] = X[61]-JVS[497]*X[34]-JVS[498]*X[43]-JVS[499]*X[46]-JVS[500]\n *X[48]-JVS[501]*X[49]-JVS[502]*X[50]-JVS[503]*X[51]-JVS[504]\n *X[52]-JVS[505]*X[53]-JVS[506]*X[57];\n X[62] = X[62]-JVS[517]*X[8]-JVS[518]*X[16]-JVS[519]*X[18]-JVS[520]\n *X[19]-JVS[521]*X[23]-JVS[522]*X[24]-JVS[523]*X[25]-JVS[524]\n *X[26]-JVS[525]*X[27]-JVS[526]*X[28]-JVS[527]*X[30]-JVS[528]\n *X[31]-JVS[529]*X[32]-JVS[530]*X[34]-JVS[531]*X[35]-JVS[532]\n *X[36]-JVS[533]*X[39]-JVS[534]*X[40]-JVS[535]*X[43]-JVS[536]\n *X[44]-JVS[537]*X[45]-JVS[538]*X[46]-JVS[539]*X[48]-JVS[540]\n *X[49]-JVS[541]*X[50]-JVS[542]*X[51]-JVS[543]*X[52]-JVS[544]\n *X[53]-JVS[545]*X[54]-JVS[546]*X[55]-JVS[547]*X[56]-JVS[548]\n *X[57]-JVS[549]*X[58]-JVS[550]*X[59]-JVS[551]*X[60]-JVS[552]\n *X[61];\n X[63] = X[63]-JVS[565]*X[19]-JVS[566]*X[20]-JVS[567]*X[22]-JVS[568]\n *X[23]-JVS[569]*X[29]-JVS[570]*X[30]-JVS[571]*X[46]-JVS[572]\n *X[48]-JVS[573]*X[50]-JVS[574]*X[51]-JVS[575]*X[52]-JVS[576]\n *X[53]-JVS[577]*X[56]-JVS[578]*X[57]-JVS[579]*X[58]-JVS[580]\n *X[59]-JVS[581]*X[60]-JVS[582]*X[61]-JVS[583]*X[62];\n X[64] = X[64]-JVS[595]*X[15]-JVS[596]*X[46]-JVS[597]*X[49]-JVS[598]\n *X[51]-JVS[599]*X[52]-JVS[600]*X[53]-JVS[601]*X[57]-JVS[602]\n *X[61]-JVS[603]*X[62]-JVS[604]*X[63];\n X[65] = X[65]-JVS[615]*X[21]-JVS[616]*X[25]-JVS[617]*X[29]-JVS[618]\n *X[41]-JVS[619]*X[43]-JVS[620]*X[46]-JVS[621]*X[48]-JVS[622]\n *X[50]-JVS[623]*X[52]-JVS[624]*X[53]-JVS[625]*X[54]-JVS[626]\n *X[56]-JVS[627]*X[57]-JVS[628]*X[58]-JVS[629]*X[59]-JVS[630]\n *X[60]-JVS[631]*X[61]-JVS[632]*X[62]-JVS[633]*X[63]-JVS[634]\n *X[64];\n X[66] = X[66]-JVS[644]*X[14]-JVS[645]*X[37]-JVS[646]*X[52]-JVS[647]\n *X[57]-JVS[648]*X[61]-JVS[649]*X[62]-JVS[650]*X[63]-JVS[651]\n *X[64]-JVS[652]*X[65];\n X[67] = X[67]-JVS[661]*X[10]-JVS[662]*X[19]-JVS[663]*X[20]-JVS[664]\n *X[22]-JVS[665]*X[23]-JVS[666]*X[29]-JVS[667]*X[30]-JVS[668]\n *X[31]-JVS[669]*X[32]-JVS[670]*X[33]-JVS[671]*X[34]-JVS[672]\n *X[36]-JVS[673]*X[38]-JVS[674]*X[43]-JVS[675]*X[45]-JVS[676]\n *X[46]-JVS[677]*X[48]-JVS[678]*X[49]-JVS[679]*X[50]-JVS[680]\n *X[51]-JVS[681]*X[52]-JVS[682]*X[53]-JVS[683]*X[56]-JVS[684]\n *X[57]-JVS[685]*X[58]-JVS[686]*X[59]-JVS[687]*X[60]-JVS[688]\n *X[61]-JVS[689]*X[62]-JVS[690]*X[63]-JVS[691]*X[64]-JVS[692]\n *X[65]-JVS[693]*X[66];\n X[68] = X[68]-JVS[701]*X[18]-JVS[702]*X[26]-JVS[703]*X[47]-JVS[704]\n *X[48]-JVS[705]*X[50]-JVS[706]*X[52]-JVS[707]*X[53]-JVS[708]\n *X[55]-JVS[709]*X[56]-JVS[710]*X[57]-JVS[711]*X[59]-JVS[712]\n *X[60]-JVS[713]*X[61]-JVS[714]*X[62]-JVS[715]*X[63]-JVS[716]\n *X[64]-JVS[717]*X[65]-JVS[718]*X[66]-JVS[719]*X[67];\n X[69] = X[69]-JVS[726]*X[12]-JVS[727]*X[13]-JVS[728]*X[14]-JVS[729]\n *X[15]-JVS[730]*X[17]-JVS[731]*X[18]-JVS[732]*X[21]-JVS[733]\n *X[24]-JVS[734]*X[26]-JVS[735]*X[27]-JVS[736]*X[35]-JVS[737]\n *X[42]-JVS[738]*X[44]-JVS[739]*X[45]-JVS[740]*X[46]-JVS[741]\n *X[47]-JVS[742]*X[48]-JVS[743]*X[49]-JVS[744]*X[50]-JVS[745]\n *X[51]-JVS[746]*X[52]-JVS[747]*X[53]-JVS[748]*X[54]-JVS[749]\n *X[55]-JVS[750]*X[56]-JVS[751]*X[57]-JVS[752]*X[58]-JVS[753]\n *X[59]-JVS[754]*X[60]-JVS[755]*X[61]-JVS[756]*X[62]-JVS[757]\n *X[63]-JVS[758]*X[64]-JVS[759]*X[65]-JVS[760]*X[66]-JVS[761]\n *X[67]-JVS[762]*X[68];\n X[70] = X[70]-JVS[768]*X[17]-JVS[769]*X[24]-JVS[770]*X[33]-JVS[771]\n *X[35]-JVS[772]*X[37]-JVS[773]*X[38]-JVS[774]*X[40]-JVS[775]\n *X[42]-JVS[776]*X[43]-JVS[777]*X[44]-JVS[778]*X[45]-JVS[779]\n *X[46]-JVS[780]*X[47]-JVS[781]*X[48]-JVS[782]*X[49]-JVS[783]\n *X[50]-JVS[784]*X[51]-JVS[785]*X[52]-JVS[786]*X[53]-JVS[787]\n *X[54]-JVS[788]*X[55]-JVS[789]*X[56]-JVS[790]*X[57]-JVS[791]\n *X[58]-JVS[792]*X[59]-JVS[793]*X[60]-JVS[794]*X[61]-JVS[795]\n *X[62]-JVS[796]*X[63]-JVS[797]*X[64]-JVS[798]*X[65]-JVS[799]\n *X[66]-JVS[800]*X[67]-JVS[801]*X[68]-JVS[802]*X[69];\n X[71] = X[71]-JVS[807]*X[11]-JVS[808]*X[12]-JVS[809]*X[23]-JVS[810]\n *X[29]-JVS[811]*X[31]-JVS[812]*X[32]-JVS[813]*X[40]-JVS[814]\n *X[41]-JVS[815]*X[48]-JVS[816]*X[49]-JVS[817]*X[50]-JVS[818]\n *X[51]-JVS[819]*X[52]-JVS[820]*X[53]-JVS[821]*X[54]-JVS[822]\n *X[56]-JVS[823]*X[57]-JVS[824]*X[58]-JVS[825]*X[59]-JVS[826]\n *X[60]-JVS[827]*X[61]-JVS[828]*X[62]-JVS[829]*X[63]-JVS[830]\n *X[64]-JVS[831]*X[65]-JVS[832]*X[66]-JVS[833]*X[67]-JVS[834]\n *X[68]-JVS[835]*X[69]-JVS[836]*X[70];\n X[72] = X[72]-JVS[840]*X[13]-JVS[841]*X[44]-JVS[842]*X[45]-JVS[843]\n *X[48]-JVS[844]*X[49]-JVS[845]*X[51]-JVS[846]*X[52]-JVS[847]\n *X[53]-JVS[848]*X[57]-JVS[849]*X[58]-JVS[850]*X[59]-JVS[851]\n *X[60]-JVS[852]*X[61]-JVS[853]*X[62]-JVS[854]*X[63]-JVS[855]\n *X[64]-JVS[856]*X[65]-JVS[857]*X[66]-JVS[858]*X[67]-JVS[859]\n *X[68]-JVS[860]*X[69]-JVS[861]*X[70]-JVS[862]*X[71];\n X[73] = X[73]-JVS[865]*X[8]-JVS[866]*X[9]-JVS[867]*X[10]-JVS[868]\n *X[16]-JVS[869]*X[18]-JVS[870]*X[19]-JVS[871]*X[20]-JVS[872]\n *X[22]-JVS[873]*X[23]-JVS[874]*X[24]-JVS[875]*X[25]-JVS[876]\n *X[28]-JVS[877]*X[29]-JVS[878]*X[30]-JVS[879]*X[31]-JVS[880]\n *X[32]-JVS[881]*X[33]-JVS[882]*X[34]-JVS[883]*X[36]-JVS[884]\n *X[37]-JVS[885]*X[38]-JVS[886]*X[39]-JVS[887]*X[40]-JVS[888]\n *X[41]-JVS[889]*X[42]-JVS[890]*X[43]-JVS[891]*X[44]-JVS[892]\n *X[45]-JVS[893]*X[46]-JVS[894]*X[48]-JVS[895]*X[49]-JVS[896]\n *X[50]-JVS[897]*X[51]-JVS[898]*X[52]-JVS[899]*X[53]-JVS[900]\n *X[54]-JVS[901]*X[55]-JVS[902]*X[56]-JVS[903]*X[57]-JVS[904]\n *X[58]-JVS[905]*X[59]-JVS[906]*X[60]-JVS[907]*X[61]-JVS[908]\n *X[62]-JVS[909]*X[63]-JVS[910]*X[64]-JVS[911]*X[65]-JVS[912]\n *X[66]-JVS[913]*X[67]-JVS[914]*X[68]-JVS[915]*X[69]-JVS[916]\n *X[70]-JVS[917]*X[71]-JVS[918]*X[72];\n X[73] = X[73]/JVS[919];\n X[72] = (X[72]-JVS[864]*X[73])/(JVS[863]);\n X[71] = (X[71]-JVS[838]*X[72]-JVS[839]*X[73])/(JVS[837]);\n X[70] = (X[70]-JVS[804]*X[71]-JVS[805]*X[72]-JVS[806]*X[73])\n /(JVS[803]);\n X[69] = (X[69]-JVS[764]*X[70]-JVS[765]*X[71]-JVS[766]*X[72]-JVS[767]\n *X[73])/(JVS[763]);\n X[68] = (X[68]-JVS[721]*X[69]-JVS[722]*X[70]-JVS[723]*X[71]-JVS[724]\n *X[72]-JVS[725]*X[73])/(JVS[720]);\n X[67] = (X[67]-JVS[695]*X[68]-JVS[696]*X[69]-JVS[697]*X[70]-JVS[698]\n *X[71]-JVS[699]*X[72]-JVS[700]*X[73])/(JVS[694]);\n X[66] = (X[66]-JVS[654]*X[67]-JVS[655]*X[68]-JVS[656]*X[69]-JVS[657]\n *X[70]-JVS[658]*X[71]-JVS[659]*X[72]-JVS[660]*X[73])\n /(JVS[653]);\n X[65] = (X[65]-JVS[636]*X[66]-JVS[637]*X[67]-JVS[638]*X[68]-JVS[639]\n *X[69]-JVS[640]*X[70]-JVS[641]*X[71]-JVS[642]*X[72]-JVS[643]\n *X[73])/(JVS[635]);\n X[64] = (X[64]-JVS[606]*X[65]-JVS[607]*X[66]-JVS[608]*X[67]-JVS[609]\n *X[68]-JVS[610]*X[69]-JVS[611]*X[70]-JVS[612]*X[71]-JVS[613]\n *X[72]-JVS[614]*X[73])/(JVS[605]);\n X[63] = (X[63]-JVS[585]*X[64]-JVS[586]*X[65]-JVS[587]*X[66]-JVS[588]\n *X[67]-JVS[589]*X[68]-JVS[590]*X[69]-JVS[591]*X[70]-JVS[592]\n *X[71]-JVS[593]*X[72]-JVS[594]*X[73])/(JVS[584]);\n X[62] = (X[62]-JVS[554]*X[63]-JVS[555]*X[64]-JVS[556]*X[65]-JVS[557]\n *X[66]-JVS[558]*X[67]-JVS[559]*X[68]-JVS[560]*X[69]-JVS[561]\n *X[70]-JVS[562]*X[71]-JVS[563]*X[72]-JVS[564]*X[73])\n /(JVS[553]);\n X[61] = (X[61]-JVS[508]*X[62]-JVS[509]*X[64]-JVS[510]*X[66]-JVS[511]\n *X[68]-JVS[512]*X[69]-JVS[513]*X[70]-JVS[514]*X[71]-JVS[515]\n *X[72]-JVS[516]*X[73])/(JVS[507]);\n X[60] = (X[60]-JVS[486]*X[61]-JVS[487]*X[63]-JVS[488]*X[65]-JVS[489]\n *X[66]-JVS[490]*X[67]-JVS[491]*X[68]-JVS[492]*X[69]-JVS[493]\n *X[70]-JVS[494]*X[71]-JVS[495]*X[72]-JVS[496]*X[73])\n /(JVS[485]);\n X[59] = (X[59]-JVS[465]*X[60]-JVS[466]*X[61]-JVS[467]*X[63]-JVS[468]\n *X[65]-JVS[469]*X[67]-JVS[470]*X[68]-JVS[471]*X[69]-JVS[472]\n *X[70]-JVS[473]*X[73])/(JVS[464]);\n X[58] = (X[58]-JVS[444]*X[59]-JVS[445]*X[60]-JVS[446]*X[61]-JVS[447]\n *X[62]-JVS[448]*X[63]-JVS[449]*X[67]-JVS[450]*X[68]-JVS[451]\n *X[69]-JVS[452]*X[70]-JVS[453]*X[73])/(JVS[443]);\n X[57] = (X[57]-JVS[421]*X[61]-JVS[422]*X[68]-JVS[423]*X[69]-JVS[424]\n *X[70]-JVS[425]*X[73])/(JVS[420]);\n X[56] = (X[56]-JVS[405]*X[57]-JVS[406]*X[61]-JVS[407]*X[63]-JVS[408]\n *X[68]-JVS[409]*X[69]-JVS[410]*X[70]-JVS[411]*X[73])\n /(JVS[404]);\n X[55] = (X[55]-JVS[382]*X[56]-JVS[383]*X[57]-JVS[384]*X[59]-JVS[385]\n *X[60]-JVS[386]*X[61]-JVS[387]*X[62]-JVS[388]*X[63]-JVS[389]\n *X[64]-JVS[390]*X[65]-JVS[391]*X[66]-JVS[392]*X[67]-JVS[393]\n *X[68]-JVS[394]*X[69]-JVS[395]*X[70]-JVS[396]*X[71]-JVS[397]\n *X[72]-JVS[398]*X[73])/(JVS[381]);\n X[54] = (X[54]-JVS[350]*X[56]-JVS[351]*X[57]-JVS[352]*X[58]-JVS[353]\n *X[59]-JVS[354]*X[60]-JVS[355]*X[61]-JVS[356]*X[64]-JVS[357]\n *X[66]-JVS[358]*X[68]-JVS[359]*X[70]-JVS[360]*X[71]-JVS[361]\n *X[72]-JVS[362]*X[73])/(JVS[349]);\n X[53] = (X[53]-JVS[337]*X[57]-JVS[338]*X[61]-JVS[339]*X[70]-JVS[340]\n *X[73])/(JVS[336]);\n X[52] = (X[52]-JVS[330]*X[57]-JVS[331]*X[61]-JVS[332]*X[70]-JVS[333]\n *X[73])/(JVS[329]);\n X[51] = (X[51]-JVS[324]*X[52]-JVS[325]*X[57]-JVS[326]*X[61]-JVS[327]\n *X[70]-JVS[328]*X[73])/(JVS[323]);\n X[50] = (X[50]-JVS[318]*X[57]-JVS[319]*X[61]-JVS[320]*X[70]-JVS[321]\n *X[73])/(JVS[317]);\n X[49] = (X[49]-JVS[312]*X[52]-JVS[313]*X[57]-JVS[314]*X[61]-JVS[315]\n *X[70]-JVS[316]*X[73])/(JVS[311]);\n X[48] = (X[48]-JVS[306]*X[57]-JVS[307]*X[61]-JVS[308]*X[70]-JVS[309]\n *X[73])/(JVS[305]);\n X[47] = (X[47]-JVS[284]*X[48]-JVS[285]*X[50]-JVS[286]*X[52]-JVS[287]\n *X[53]-JVS[288]*X[56]-JVS[289]*X[57]-JVS[290]*X[59]-JVS[291]\n *X[60]-JVS[292]*X[61]-JVS[293]*X[62]-JVS[294]*X[63]-JVS[295]\n *X[64]-JVS[296]*X[65]-JVS[297]*X[66]-JVS[298]*X[67]-JVS[299]\n *X[68]-JVS[300]*X[69]-JVS[301]*X[70]-JVS[302]*X[71]-JVS[303]\n *X[72]-JVS[304]*X[73])/(JVS[283]);\n X[46] = (X[46]-JVS[272]*X[57]-JVS[273]*X[61]-JVS[274]*X[70]-JVS[275]\n *X[73])/(JVS[271]);\n X[45] = (X[45]-JVS[262]*X[62]-JVS[263]*X[64]-JVS[264]*X[66]-JVS[265]\n *X[68]-JVS[266]*X[69]-JVS[267]*X[70]-JVS[268]*X[71]-JVS[269]\n *X[72]-JVS[270]*X[73])/(JVS[261]);\n X[44] = (X[44]-JVS[251]*X[45]-JVS[252]*X[48]-JVS[253]*X[51]-JVS[254]\n *X[57]-JVS[255]*X[61]-JVS[256]*X[62]-JVS[257]*X[70]-JVS[258]\n *X[73])/(JVS[250]);\n X[43] = (X[43]-JVS[238]*X[57]-JVS[239]*X[61]-JVS[240]*X[70]-JVS[241]\n *X[73])/(JVS[237]);\n X[42] = (X[42]-JVS[223]*X[44]-JVS[224]*X[45]-JVS[225]*X[49]-JVS[226]\n *X[51]-JVS[227]*X[52]-JVS[228]*X[53]-JVS[229]*X[54]-JVS[230]\n *X[55]-JVS[231]*X[58]-JVS[232]*X[61]-JVS[233]*X[62]-JVS[234]\n *X[69]-JVS[235]*X[70]-JVS[236]*X[73])/(JVS[222]);\n X[41] = (X[41]-JVS[208]*X[48]-JVS[209]*X[50]-JVS[210]*X[52]-JVS[211]\n *X[56]-JVS[212]*X[61]-JVS[213]*X[69]-JVS[214]*X[70]-JVS[215]\n *X[73])/(JVS[207]);\n X[40] = (X[40]-JVS[196]*X[49]-JVS[197]*X[51]-JVS[198]*X[53]-JVS[199]\n *X[61]-JVS[200]*X[70]-JVS[201]*X[73])/(JVS[195]);\n X[39] = (X[39]-JVS[173]*X[40]-JVS[174]*X[43]-JVS[175]*X[44]-JVS[176]\n *X[46]-JVS[177]*X[48]-JVS[178]*X[49]-JVS[179]*X[50]-JVS[180]\n *X[51]-JVS[181]*X[52]-JVS[182]*X[53]-JVS[183]*X[54]-JVS[184]\n *X[55]-JVS[185]*X[57]-JVS[186]*X[58]-JVS[187]*X[61]-JVS[188]\n *X[70]-JVS[189]*X[73])/(JVS[172]);\n X[38] = (X[38]-JVS[163]*X[45]-JVS[164]*X[62]-JVS[165]*X[70]-JVS[166]\n *X[73])/(JVS[162]);\n X[37] = (X[37]-JVS[157]*X[52]-JVS[158]*X[61]-JVS[159]*X[70]-JVS[160]\n *X[73])/(JVS[156]);\n X[36] = (X[36]-JVS[150]*X[62]-JVS[151]*X[63]-JVS[152]*X[67]-JVS[153]\n *X[73])/(JVS[149]);\n X[35] = (X[35]-JVS[145]*X[45]-JVS[146]*X[62]-JVS[147]*X[69]-JVS[148]\n *X[70])/(JVS[144]);\n X[34] = (X[34]-JVS[141]*X[61]-JVS[142]*X[73])/(JVS[140]);\n X[33] = (X[33]-JVS[136]*X[70]-JVS[137]*X[73])/(JVS[135]);\n X[32] = (X[32]-JVS[132]*X[73])/(JVS[131]);\n X[31] = (X[31]-JVS[128]*X[73])/(JVS[127]);\n X[30] = (X[30]-JVS[124]*X[73])/(JVS[123]);\n X[29] = (X[29]-JVS[122]*X[73])/(JVS[121]);\n X[28] = (X[28]-JVS[117]*X[63]-JVS[118]*X[65]-JVS[119]*X[67]-JVS[120]\n *X[73])/(JVS[116]);\n X[27] = (X[27]-JVS[112]*X[35]-JVS[113]*X[62]-JVS[114]*X[69]-JVS[115]\n *X[70])/(JVS[111]);\n X[26] = (X[26]-JVS[108]*X[55]-JVS[109]*X[62]-JVS[110]*X[68])\n /(JVS[107]);\n X[25] = (X[25]-JVS[104]*X[62]-JVS[105]*X[65]-JVS[106]*X[73])\n /(JVS[103]);\n X[24] = (X[24]-JVS[100]*X[62]-JVS[101]*X[69]-JVS[102]*X[73])\n /(JVS[99]);\n X[23] = (X[23]-JVS[98]*X[73])/(JVS[97]);\n X[22] = (X[22]-JVS[96]*X[73])/(JVS[95]);\n X[21] = (X[21]-JVS[93]*X[69]-JVS[94]*X[73])/(JVS[92]);\n X[20] = (X[20]-JVS[90]*X[73])/(JVS[89]);\n X[19] = (X[19]-JVS[88]*X[73])/(JVS[87]);\n X[18] = (X[18]-JVS[85]*X[68]-JVS[86]*X[73])/(JVS[84]);\n X[17] = (X[17]-JVS[82]*X[69]-JVS[83]*X[70])/(JVS[81]);\n X[16] = (X[16]-JVS[79]*X[62]-JVS[80]*X[73])/(JVS[78]);\n X[15] = (X[15]-JVS[76]*X[64]-JVS[77]*X[69])/(JVS[75]);\n X[14] = (X[14]-JVS[73]*X[66]-JVS[74]*X[69])/(JVS[72]);\n X[13] = (X[13]-JVS[70]*X[69]-JVS[71]*X[72])/(JVS[69]);\n X[12] = (X[12]-JVS[67]*X[69]-JVS[68]*X[71])/(JVS[66]);\n X[11] = (X[11]-JVS[62]*X[23]-JVS[63]*X[48]-JVS[64]*X[61]-JVS[65]\n *X[73])/(JVS[61]);\n X[10] = (X[10]-JVS[60]*X[73])/(JVS[59]);\n X[9] = (X[9]-JVS[58]*X[61])/(JVS[57]);\n X[8] = (X[8]-JVS[56]*X[73])/(JVS[55]);\n X[7] = (X[7]-JVS[52]*X[27]-JVS[53]*X[37]-JVS[54]*X[69])/(JVS[51]);\n X[6] = (X[6]-JVS[49]*X[27]-JVS[50]*X[69])/(JVS[48]);\n X[5] = (X[5]-JVS[44]*X[62]-JVS[45]*X[64]-JVS[46]*X[66]-JVS[47]*X[72])\n /(JVS[43]);\n X[4] = (X[4]-JVS[41]*X[62]-JVS[42]*X[71])/(JVS[40]);\n X[3] = (X[3]-JVS[27]*X[46]-JVS[28]*X[48]-JVS[29]*X[50]-JVS[30]*X[51]\n -JVS[31]*X[52]-JVS[32]*X[61]-JVS[33]*X[62]-JVS[34]*X[63]\n -JVS[35]*X[64]-JVS[36]*X[65]-JVS[37]*X[66]-JVS[38]*X[67]\n -JVS[39]*X[72])/(JVS[26]);\n X[2] = (X[2]-JVS[18]*X[50]-JVS[19]*X[52]-JVS[20]*X[61]-JVS[21]*X[62]\n -JVS[22]*X[63]-JVS[23]*X[65]-JVS[24]*X[67]-JVS[25]*X[71])\n /(JVS[17]);\n X[1] = (X[1]-JVS[4]*X[19]-JVS[5]*X[26]-JVS[6]*X[43]-JVS[7]*X[46]\n -JVS[8]*X[48]-JVS[9]*X[49]-JVS[10]*X[50]-JVS[11]*X[51]-JVS[12]\n *X[52]-JVS[13]*X[53]-JVS[14]*X[61]-JVS[15]*X[68]-JVS[16]*X[73])\n /(JVS[3]);\n X[0] = (X[0]-JVS[1]*X[8]-JVS[2]*X[73])/(JVS[0]);\n}\n\n/* End of KppSolve function */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n/* */\n/* BLAS_UTIL - BLAS-LIKE utility functions */\n/* Arguments : */\n/* */\n/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n\n/*--------------------------------------------------------------\n \n BLAS/LAPACK-like subroutines used by the integration algorithms\n It is recommended to replace them by calls to the optimized\n BLAS/LAPACK library for your machine\n \n (C) Adrian Sandu, Aug. 2004\n \n--------------------------------------------------------------*/\n\n#define ZERO (double)0.0\n#define ONE (double)1.0\n#define HALF (double)0.5\n#define TWO (double)2.0\n#define MOD(A,B) (int)((A)%(B))\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\nvoid WCOPY(int N, double X[], int incX, volatile double Y[], int incY)\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n copies a vector, x, to a vector, y: y <- x\n only for incX=incY=1\n after BLAS\n replace this by the function from the optimized BLAS implementation:\n CALL SCOPY(N,X,1,Y,1) or CALL DCOPY(N,X,1,Y,1)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n{\n#if USE_SDK_BLAS == 1\n dcopy_spu(X, Y, N);\n#else\n int i, M;\n if (N <= 0) return;\n\n M = MOD(N,8);\n if( M != 0 ) {\n for ( i = 0; i < M; i++ )\n Y[i] = X[i];\n if( N < 8 ) return;\n } \t\n for ( i = M; i\n#include \"math.h\"\n#include \n#include \n\n//! TODO\nclass muParserScript: public Script\n{\n Q_OBJECT\n\n public:\n muParserScript(ScriptingEnv *env, const QString &code, QObject *context=0, const QString &name=\"\", bool checkMultilineCode = true);\n\n public slots:\n bool compile(bool asFunction=true);\n QVariant eval();\r\n double evalSingleLine();\r\n QString evalSingleLineToString(const QLocale& locale, char f, int prec);\n bool exec();\n bool setQObject(QObject *val, const char *name);\n bool setInt(int val, const char* name);\n bool setDouble(double val, const char* name);\r\n double* defineVariable(const char *name, double val = 0.0);\r\n int codeLines(){return muCode.size();};\r\n\n private:\n double col(const QString &arg);\n double tablecol(const QString &arg);\n double cell(int row, int col);\n double tableCell(int col, int row);\n double *addVariable(const char *name);\n double *addVariableR(const char *name);\n static double *mu_addVariableR(const char *name) { return current->addVariableR(name); }\n static double mu_col(const char *arg) { return current->col(arg); }\n static double mu_cell(double row, double col) { return current->cell(qRound(row), qRound(col)); }\n static double mu_tableCell(double col, double row) { return current->tableCell(qRound(col), qRound(row)); }\n static double mu_tablecol(const char *arg) { return current->tablecol(arg); }\n static double *mu_addVariable(const char *name, void *){ return current->addVariable(name); }\n static double *mu_addVariableR(const char *name, void *) { return current->addVariableR(name); }\n static QString compileColArg(const QString& in);\n\n mu::Parser parser, rparser;\n Q3AsciiDict variables, rvariables;\n QStringList muCode;\r\n\t//! Flag telling is the parser should warn users on multiline code input\n\tbool d_warn_multiline_code;\r\n\n public:\n static muParserScript *current;\n};\n\n#endif\n", "meta": {"hexsha": "685d6737580789bd6b94c8221ab93cd9b36811d9", "size": 3998, "ext": "h", "lang": "C", "max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/muParserScript.h", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 45.4318181818, "max_line_length": 142, "alphanum_fraction": 0.5512756378, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.45013022802554775}}