{"text": "// --------------------------------------------------------------\n// File: ex10.c\n// Description: Example with the sections directive\n// Software stack: Exercises suite for V. Keller lecture\n// Version: 1.0\n// License: BSD\n// Author: Vincent Keller (Vincent.Keller@epfl.ch), CADMOS, 2012\n//\n// COMPILATION AND LINKING\n//\n// WITHOUT MKL : gcc -O3 -ftree-vectorize dgemm.c -lgsl -lgslcblas -lm -o dgemm\n// WITH MKL : export MKLROOT=/software/intel/mkl; icc -DMKLINUSE -DMKL_ILP64 -openmp -I${MKLROOT}/include -O3 -xHost dgemm.c -L${MKLROOT}/lib/intel64 -lmkl_intel_ilp64 -lmkl_core -lmkl_intel_thread -lpthread -lm -o dgemm\n// --------------------------------------------------------------\n\n#include \n#include \n#include \n\n#if defined(MKLINUSE)\n#include \"mkl.h\"\n#else\n#include \n#endif\n\n\ndouble verification(double ** array, int N){\n double ret;\n int i,j;\n for (i=0;i\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"enorm.c\"\n\n/* Broyden's method. It is not an efficient or modern algorithm but\n gives an example of a rank-1 update.\n\n C.G. Broyden, \"A Class of Methods for Solving Nonlinear\n Simultaneous Equations\", Mathematics of Computation, vol 19 (1965),\n p 577-593\n\n */\n\ntypedef struct\n {\n gsl_matrix *H;\n gsl_matrix *lu;\n gsl_permutation *permutation;\n gsl_vector *v;\n gsl_vector *w;\n gsl_vector *y;\n gsl_vector *p;\n gsl_vector *fnew;\n gsl_vector *x_trial;\n double phi;\n }\nbroyden_state_t;\n\nstatic int broyden_alloc (void *vstate, size_t n);\nstatic int broyden_set (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\nstatic int broyden_iterate (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\nstatic void broyden_free (void *vstate);\n\n\nstatic int\nbroyden_alloc (void *vstate, size_t n)\n{\n broyden_state_t *state = (broyden_state_t *) vstate;\n gsl_vector *v, *w, *y, *fnew, *x_trial, *p;\n gsl_permutation *perm;\n gsl_matrix *m, *H;\n\n m = gsl_matrix_calloc (n, n);\n\n if (m == 0)\n {\n GSL_ERROR (\"failed to allocate space for lu\", GSL_ENOMEM);\n }\n\n state->lu = m;\n\n perm = gsl_permutation_calloc (n);\n\n if (perm == 0)\n {\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for permutation\", GSL_ENOMEM);\n }\n\n state->permutation = perm;\n\n H = gsl_matrix_calloc (n, n);\n\n if (H == 0)\n {\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for d\", GSL_ENOMEM);\n }\n\n state->H = H;\n\n v = gsl_vector_calloc (n);\n\n if (v == 0)\n {\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for v\", GSL_ENOMEM);\n }\n\n state->v = v;\n\n w = gsl_vector_calloc (n);\n\n if (w == 0)\n {\n gsl_vector_free (v);\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for w\", GSL_ENOMEM);\n }\n\n state->w = w;\n\n y = gsl_vector_calloc (n);\n\n if (y == 0)\n {\n gsl_vector_free (w);\n gsl_vector_free (v);\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for y\", GSL_ENOMEM);\n }\n\n state->y = y;\n\n fnew = gsl_vector_calloc (n);\n\n if (fnew == 0)\n {\n gsl_vector_free (y);\n gsl_vector_free (w);\n gsl_vector_free (v);\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for fnew\", GSL_ENOMEM);\n }\n\n state->fnew = fnew;\n\n x_trial = gsl_vector_calloc (n);\n\n if (x_trial == 0)\n {\n gsl_vector_free (fnew);\n gsl_vector_free (y);\n gsl_vector_free (w);\n gsl_vector_free (v);\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for x_trial\", GSL_ENOMEM);\n }\n\n state->x_trial = x_trial;\n\n p = gsl_vector_calloc (n);\n\n if (p == 0)\n {\n gsl_vector_free (x_trial);\n gsl_vector_free (fnew);\n gsl_vector_free (y);\n gsl_vector_free (w);\n gsl_vector_free (v);\n gsl_matrix_free (H);\n gsl_permutation_free (perm);\n gsl_matrix_free (m);\n\n GSL_ERROR (\"failed to allocate space for p\", GSL_ENOMEM);\n }\n\n state->p = p;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nbroyden_set (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx)\n{\n broyden_state_t *state = (broyden_state_t *) vstate;\n size_t i, j, n = function->n;\n int signum = 0;\n\n GSL_MULTIROOT_FN_EVAL (function, x, f);\n\n gsl_multiroot_fdjacobian (function, x, f, GSL_SQRT_DBL_EPSILON, state->lu);\n gsl_linalg_LU_decomp (state->lu, state->permutation, &signum);\n gsl_linalg_LU_invert (state->lu, state->permutation, state->H);\n\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n gsl_matrix_set(state->H,i,j,-gsl_matrix_get(state->H,i,j));\n\n for (i = 0; i < n; i++)\n {\n gsl_vector_set (dx, i, 0.0);\n }\n\n state->phi = enorm (f);\n\n return GSL_SUCCESS;\n}\n\nstatic int\nbroyden_iterate (void *vstate, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx)\n{\n broyden_state_t *state = (broyden_state_t *) vstate;\n\n double phi0, phi1, t, lambda;\n\n gsl_matrix *H = state->H;\n gsl_vector *p = state->p;\n gsl_vector *y = state->y;\n gsl_vector *v = state->v;\n gsl_vector *w = state->w;\n gsl_vector *fnew = state->fnew;\n gsl_vector *x_trial = state->x_trial;\n gsl_matrix *lu = state->lu;\n gsl_permutation *perm = state->permutation;\n\n size_t i, j, iter;\n\n size_t n = function->n;\n\n /* p = H f */\n\n for (i = 0; i < n; i++)\n {\n double sum = 0;\n\n for (j = 0; j < n; j++)\n {\n sum += gsl_matrix_get (H, i, j) * gsl_vector_get (f, j);\n }\n gsl_vector_set (p, i, sum);\n }\n\n t = 1;\n iter = 0;\n\n phi0 = state->phi;\n\nnew_step:\n\n for (i = 0; i < n; i++)\n {\n double pi = gsl_vector_get (p, i);\n double xi = gsl_vector_get (x, i);\n gsl_vector_set (x_trial, i, xi + t * pi);\n }\n\n { \n int status = GSL_MULTIROOT_FN_EVAL (function, x_trial, fnew);\n\n if (status != GSL_SUCCESS) \n {\n return GSL_EBADFUNC;\n }\n }\n\n phi1 = enorm (fnew);\n\n iter++ ;\n\n if (phi1 > phi0 && iter < 10 && t > 0.1)\n {\n /* full step goes uphill, take a reduced step instead */\n \n double theta = phi1 / phi0;\n t *= (sqrt (1.0 + 6.0 * theta) - 1.0) / (3.0 * theta);\n goto new_step;\n }\n\n if (phi1 > phi0)\n {\n /* need to recompute Jacobian */\n int signum = 0;\n \n gsl_multiroot_fdjacobian (function, x, f, GSL_SQRT_DBL_EPSILON, lu);\n \n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n gsl_matrix_set(lu,i,j,-gsl_matrix_get(lu,i,j));\n \n gsl_linalg_LU_decomp (lu, perm, &signum);\n gsl_linalg_LU_invert (lu, perm, H);\n \n gsl_linalg_LU_solve (lu, perm, f, p); \n\n t = 1;\n\n for (i = 0; i < n; i++)\n {\n double pi = gsl_vector_get (p, i);\n double xi = gsl_vector_get (x, i);\n gsl_vector_set (x_trial, i, xi + t * pi);\n }\n \n {\n int status = GSL_MULTIROOT_FN_EVAL (function, x_trial, fnew);\n \n if (status != GSL_SUCCESS) \n {\n return GSL_EBADFUNC;\n }\n }\n \n phi1 = enorm (fnew);\n }\n \n /* y = f' - f */\n\n for (i = 0; i < n; i++)\n {\n double yi = gsl_vector_get (fnew, i) - gsl_vector_get (f, i);\n gsl_vector_set (y, i, yi);\n }\n\n /* v = H y */\n\n for (i = 0; i < n; i++)\n {\n double sum = 0;\n\n for (j = 0; j < n; j++)\n {\n sum += gsl_matrix_get (H, i, j) * gsl_vector_get (y, j);\n }\n\n gsl_vector_set (v, i, sum);\n }\n\n /* lambda = p . v */\n\n lambda = 0;\n\n for (i = 0; i < n; i++)\n {\n lambda += gsl_vector_get (p, i) * gsl_vector_get (v, i);\n }\n\n if (lambda == 0)\n {\n GSL_ERROR (\"approximation to Jacobian has collapsed\", GSL_EZERODIV) ;\n }\n\n /* v' = v + t * p */\n\n for (i = 0; i < n; i++)\n {\n double vi = gsl_vector_get (v, i) + t * gsl_vector_get (p, i);\n gsl_vector_set (v, i, vi);\n }\n\n /* w^T = p^T H */\n\n for (i = 0; i < n; i++)\n {\n double sum = 0;\n\n for (j = 0; j < n; j++)\n {\n sum += gsl_matrix_get (H, j, i) * gsl_vector_get (p, j);\n }\n\n gsl_vector_set (w, i, sum);\n }\n\n /* Hij -> Hij - (vi wj / lambda) */\n\n for (i = 0; i < n; i++)\n {\n double vi = gsl_vector_get (v, i);\n\n for (j = 0; j < n; j++)\n {\n double wj = gsl_vector_get (w, j);\n double Hij = gsl_matrix_get (H, i, j) - vi * wj / lambda;\n gsl_matrix_set (H, i, j, Hij);\n }\n }\n\n /* copy fnew into f */\n\n gsl_vector_memcpy (f, fnew);\n\n /* copy x_trial into x */\n\n gsl_vector_memcpy (x, x_trial);\n\n for (i = 0; i < n; i++)\n {\n double pi = gsl_vector_get (p, i);\n gsl_vector_set (dx, i, t * pi);\n }\n\n state->phi = phi1;\n\n return GSL_SUCCESS;\n}\n\n\nstatic void\nbroyden_free (void *vstate)\n{\n broyden_state_t *state = (broyden_state_t *) vstate;\n\n gsl_matrix_free (state->H);\n\n gsl_matrix_free (state->lu);\n gsl_permutation_free (state->permutation);\n \n gsl_vector_free (state->v);\n gsl_vector_free (state->w);\n gsl_vector_free (state->y);\n gsl_vector_free (state->p);\n\n gsl_vector_free (state->fnew);\n gsl_vector_free (state->x_trial);\n \n}\n\n\nstatic const gsl_multiroot_fsolver_type broyden_type =\n{\"broyden\", /* name */\n sizeof (broyden_state_t),\n &broyden_alloc,\n &broyden_set,\n &broyden_iterate,\n &broyden_free};\n\nconst gsl_multiroot_fsolver_type *gsl_multiroot_fsolver_broyden = &broyden_type;\n", "meta": {"hexsha": "65c96478d7ef7296a84752bb2c703f624b46bce1", "size": 9933, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/multiroots/broyden.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/multiroots/broyden.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/multiroots/broyden.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 21.7352297593, "max_line_length": 126, "alphanum_fraction": 0.5881405416, "num_tokens": 3081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6985119039995301}} {"text": "static char help[] =\n\"Unstructured 2D FEM solution of nonlinear Poisson problem. Option prefix un_.\\n\"\n\"Equation is\\n\"\n\" - div( a(u,x,y) grad u ) = f(u,x,y)\\n\"\n\"on arbitrary 2D polygonal domain, with boundary data g_D(x,y), g_N(x,y).\\n\"\n\"Functions a(), f(), g_D(), g_N(), and u_exact() are given as formulas.\\n\"\n\"Input files in PETSc binary format contain node coordinates, elements, Neumann\\n\"\n\"boundary segments and boundary flags. Allows non-homogeneous Dirichlet and/or\\n\"\n\"Neumann boundary conditions. Five different solution cases are implemented.\\n\\n\";\n\n#include \n#include \"../quadrature.h\"\n#include \"um.h\"\n#include \"cases.h\"\n\n//STARTCTX\ntypedef struct {\n UM *mesh;\n int solncase,\n quaddegree;\n double (*a_fcn)(double, double, double);\n double (*f_fcn)(double, double, double);\n double (*gD_fcn)(double, double);\n double (*gN_fcn)(double, double);\n double (*uexact_fcn)(double, double);\n PetscLogStage readstage, setupstage, solverstage, resstage, jacstage; //STRIP\n} unfemCtx;\n//ENDCTX\n\n//STARTFEM\ndouble chi(int L, double xi, double eta) {\n const double z[3] = {1.0 - xi - eta, xi, eta};\n return z[L];\n}\n\nconst double dchi[3][2] = {{-1.0,-1.0},{ 1.0, 0.0},{ 0.0, 1.0}};\n\n// evaluate v(xi,eta) on reference element using local node numbering\ndouble eval(const double v[3], double xi, double eta) {\n double sum = 0.0;\n int L;\n for (L = 0; L < 3; L++)\n sum += v[L] * chi(L,xi,eta);\n return sum;\n}\n\ndouble InnerProd(const double V[2], const double W[2]) {\n return V[0] * W[0] + V[1] * W[1];\n}\n//ENDFEM\n\nextern PetscErrorCode FillExact(Vec, unfemCtx*);\nextern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);\nextern PetscErrorCode FormPicard(SNES, Vec, Mat, Mat, void*);\nextern PetscErrorCode Preallocation(Mat, unfemCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n PetscBool viewmesh = PETSC_FALSE,\n viewsoln = PETSC_FALSE,\n noprealloc = PETSC_FALSE,\n savepintbinary = PETSC_FALSE,\n savepintmatlab = PETSC_FALSE;\n char root[256] = \"\", nodesname[256], issname[256], solnname[256],\n pintname[256] = \"\";\n int savepintlevel = -1, levels;\n UM mesh;\n unfemCtx user;\n SNES snes;\n KSP ksp;\n PC pc;\n PCType pctype;\n Mat A;\n Vec r, u, uexact;\n double err, h_max;\n\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = PetscLogStageRegister(\"Read mesh \", &user.readstage); CHKERRQ(ierr); //STRIP\n ierr = PetscLogStageRegister(\"Set-up \", &user.setupstage); CHKERRQ(ierr); //STRIP\n ierr = PetscLogStageRegister(\"Solver \", &user.solverstage); CHKERRQ(ierr); //STRIP\n ierr = PetscLogStageRegister(\"Residual eval \", &user.resstage); CHKERRQ(ierr); //STRIP\n ierr = PetscLogStageRegister(\"Jacobian eval \", &user.jacstage); CHKERRQ(ierr); //STRIP\n\n user.quaddegree = 1;\n user.solncase = 0;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"un_\", \"options for unfem\", \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-case\",\n \"exact solution cases: 0=linear, 1=nonlinear, 2=nonhomoNeumann, 3=chapter3, 4=koch\",\n \"unfem.c\",user.solncase,&(user.solncase),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-gamg_save_pint_binary\",\n \"filename under which to save interpolation operator (Mat) in PETSc binary format\",\n \"unfem.c\",pintname,pintname,sizeof(pintname),&savepintbinary); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-gamg_save_pint_matlab\",\n \"filename under which to save interpolation operator (Mat) in ascii Matlab format\",\n \"unfem.c\",pintname,pintname,sizeof(pintname),&savepintmatlab); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-gamg_save_pint_level\",\n \"saved interpolation operator is between L-1 and L where this option sets L; defaults to finest levels\",\n \"unfem.c\",savepintlevel,&savepintlevel,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-mesh\",\n \"file name root of mesh stored in PETSc binary with .vec,.is extensions\",\n \"unfem.c\",root,root,sizeof(root),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-noprealloc\",\n \"do not perform preallocation before matrix assembly\",\n \"unfem.c\",noprealloc,&noprealloc,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-quaddegree\",\n \"quadrature degree (1,2,3)\",\n \"unfem.c\",user.quaddegree,&(user.quaddegree),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-view_mesh\",\n \"view loaded mesh (nodes and elements) at stdout\",\n \"unfem.c\",viewmesh,&viewmesh,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-view_solution\",\n \"view solution u(x,y) to binary file; uses root name of mesh plus .soln\\nsee petsc2tricontour.py to view graphically\",\n \"unfem.c\",viewsoln,&viewsoln,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n // determine filenames\n if (strlen(root) == 0) {\n SETERRQ(PETSC_COMM_WORLD,4,\"no mesh name root given; rerun with '-un_mesh foo'\");\n }\n strcpy(nodesname, root);\n strncat(nodesname, \".vec\", 4);\n strcpy(issname, root);\n strncat(issname, \".is\", 3);\n\n // set source/boundary functions and exact solution\n user.a_fcn = &a_lin;\n user.f_fcn = &f_lin;\n user.uexact_fcn = &uexact_lin;\n user.gD_fcn = &gD_lin;\n user.gN_fcn = &gN_lin;\n switch (user.solncase) {\n case 0 :\n break;\n case 1 :\n user.a_fcn = &a_nonlin;\n user.f_fcn = &f_nonlin;\n break;\n case 2 :\n user.gN_fcn = &gN_linneu;\n break;\n case 3 :\n user.a_fcn = &a_square;\n user.f_fcn = &f_square;\n user.uexact_fcn = &uexact_square;\n user.gD_fcn = &gD_square;\n user.gN_fcn = NULL; // seg fault if ever called\n break;\n case 4 :\n user.a_fcn = &a_koch;\n user.f_fcn = &f_koch;\n user.uexact_fcn = NULL; // seg fault if ever called\n user.gD_fcn = &gD_koch;\n user.gN_fcn = NULL; // seg fault if ever called\n break;\n default :\n SETERRQ(PETSC_COMM_WORLD,1,\"other solution cases not implemented\");\n }\n\n PetscLogStagePush(user.readstage);\n//STARTREADMESH\n // read mesh object of type UM\n ierr = UMInitialize(&mesh); CHKERRQ(ierr);\n ierr = UMReadNodes(&mesh,nodesname); CHKERRQ(ierr);\n ierr = UMReadISs(&mesh,issname); CHKERRQ(ierr);\n ierr = UMStats(&mesh, &h_max, NULL, NULL, NULL); CHKERRQ(ierr);\n user.mesh = &mesh;\n//ENDREADMESH\n PetscLogStagePop();\n\n if (viewmesh) {\n PetscViewer stdoutviewer;\n ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&stdoutviewer); CHKERRQ(ierr);\n ierr = UMViewASCII(&mesh,stdoutviewer); CHKERRQ(ierr);\n }\n\n PetscLogStagePush(user.setupstage);\n//STARTMAININITIAL\n // configure Vecs and SNES\n ierr = VecCreate(PETSC_COMM_WORLD,&r); CHKERRQ(ierr);\n ierr = VecSetSizes(r,PETSC_DECIDE,mesh.N); CHKERRQ(ierr);\n ierr = VecSetFromOptions(r); CHKERRQ(ierr);\n ierr = VecDuplicate(r,&u); CHKERRQ(ierr);\n ierr = VecSet(u,0.0); CHKERRQ(ierr);\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetFunction(snes,r,FormFunction,&user); CHKERRQ(ierr);\n\n // reset default KSP and PC\n ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);\n ierr = KSPSetType(ksp,KSPCG); CHKERRQ(ierr);\n ierr = KSPGetPC(ksp,&pc); CHKERRQ(ierr);\n ierr = PCSetType(pc,PCICC); CHKERRQ(ierr);\n\n // setup matrix for Picard iteration, including preallocation\n ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);\n ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,mesh.N,mesh.N); CHKERRQ(ierr);\n ierr = MatSetFromOptions(A); CHKERRQ(ierr);\n ierr = MatSetOption(A,MAT_SYMMETRIC,PETSC_TRUE); CHKERRQ(ierr);\n if (noprealloc) {\n ierr = MatSetUp(A); CHKERRQ(ierr);\n } else {\n ierr = Preallocation(A,&user); CHKERRQ(ierr);\n }\n ierr = SNESSetJacobian(snes,A,A,FormPicard,&user); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n PetscLogStagePop(); //STRIP\n\n // solve\n PetscLogStagePush(user.solverstage); //STRIP\n ierr = SNESSolve(snes,NULL,u);CHKERRQ(ierr);\n//ENDMAININITIAL\n PetscLogStagePop();\n\n // report if PC is GAMG\n ierr = PCGetType(pc,&pctype); CHKERRQ(ierr);\n if (strcmp(pctype,\"gamg\") == 0) {\n ierr = PCMGGetLevels(pc,&levels); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" PC is GAMG with %d levels\\n\",levels); CHKERRQ(ierr);\n }\n\n // save Pint from GAMG if requested\n if (strlen(pintname) > 0) {\n Mat pint;\n PetscViewer viewer;\n if (strcmp(pctype,\"gamg\") != 0) {\n SETERRQ(PETSC_COMM_WORLD,2,\"option -un_gamg_save_pint set but PC is not of type PCGAMG\");\n }\n if (savepintlevel >= levels) {\n SETERRQ(PETSC_COMM_WORLD,3,\"invalid level given in -un_gamg_save_pint_level\");\n }\n if (savepintbinary && savepintmatlab) {\n SETERRQ(PETSC_COMM_WORLD,4,\"only one of -un_gamg_save_pint_binary OR -un_gamg_save_pint_matlab is allowed\");\n }\n if (savepintlevel <= 0) {\n savepintlevel = levels - 1;\n }\n ierr = PCMGGetInterpolation(pc,savepintlevel,&pint); CHKERRQ(ierr);\n if (savepintbinary) {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" saving interpolation operator on levels %d->%d in binary format to %s ...\\n\",\n savepintlevel-1,savepintlevel,pintname); CHKERRQ(ierr);\n ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,pintname,FILE_MODE_WRITE,&viewer); CHKERRQ(ierr);\n ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr);\n } else {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \" saving interpolation operator on levels %d->%d in ascii format to %s ...\\n\",\n savepintlevel-1,savepintlevel,pintname); CHKERRQ(ierr);\n ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD,pintname,&viewer); CHKERRQ(ierr);\n ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr);\n }\n ierr = MatView(pint,viewer); CHKERRQ(ierr);\n }\n\n // if exact solution available, report numerical error\n if (user.uexact_fcn) {\n ierr = VecDuplicate(r,&uexact); CHKERRQ(ierr);\n ierr = FillExact(uexact,&user); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecNorm(u,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"case %d result for N=%d nodes with h = %.3e : |u-u_ex|_inf = %.2e\\n\",\n user.solncase,mesh.N,h_max,err); CHKERRQ(ierr);\n VecDestroy(&uexact);\n } else {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"case %d result for N=%d nodes with h = %.3e ... done\\n\",\n user.solncase,mesh.N,h_max); CHKERRQ(ierr);\n }\n\n // save solution in PETSc binary if requested\n if (viewsoln) {\n strcpy(solnname, root);\n strncat(solnname, \".soln\", 5);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"writing solution in binary format to %s ...\\n\",solnname); CHKERRQ(ierr);\n ierr = UMViewSolutionBinary(&mesh,solnname,u); CHKERRQ(ierr);\n }\n\n // clean-up\n VecDestroy(&u); VecDestroy(&r);\n MatDestroy(&A); SNESDestroy(&snes); UMDestroy(&mesh);\n return PetscFinalize();\n}\n\nPetscErrorCode FillExact(Vec uexact, unfemCtx *ctx) {\n PetscErrorCode ierr;\n const Node *aloc;\n double *auexact;\n int i;\n ierr = UMGetNodeCoordArrayRead(ctx->mesh,&aloc); CHKERRQ(ierr);\n ierr = VecGetArray(uexact,&auexact); CHKERRQ(ierr);\n for (i = 0; i < ctx->mesh->N; i++) {\n auexact[i] = ctx->uexact_fcn(aloc[i].x,aloc[i].y);\n }\n ierr = VecRestoreArray(uexact,&auexact); CHKERRQ(ierr);\n ierr = UMRestoreNodeCoordArrayRead(ctx->mesh,&aloc); CHKERRQ(ierr);\n return 0;\n}\n\n//STARTRESIDUAL\nPetscErrorCode FormFunction(SNES snes, Vec u, Vec F, void *ctx) {\n PetscErrorCode ierr;\n unfemCtx *user = (unfemCtx*)ctx;\n const Quad2DTri q = symmgauss[user->quaddegree-1];\n const int *ae, *ans, *abf, *en;\n const Node *aloc;\n const double *au;\n int p, na, nb, k, l, r;\n double *aF, unode[3], gradu[2], gradpsi[3][2], uquad[4],\n aquad[4], fquad[4], dx, dy, dx1, dx2, dy1, dy2,\n detJ, ls, xmid, ymid, sint, xx, yy, psi, ip, sum;\n\n PetscLogStagePush(user->resstage); //STRIP\n ierr = VecSet(F,0.0); CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF); CHKERRQ(ierr);\n ierr = UMGetNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr);\n ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n\n // Neumann boundary segment contributions (if any)\n if (user->mesh->P > 0) {\n ierr = ISGetIndices(user->mesh->ns,&ans); CHKERRQ(ierr);\n for (p = 0; p < user->mesh->P; p++) {\n na = ans[2*p+0]; nb = ans[2*p+1]; // nodes at end of segment\n dx = aloc[na].x-aloc[nb].x; dy = aloc[na].y-aloc[nb].y;\n ls = sqrt(dx * dx + dy * dy); // length of segment\n // midpoint rule; psi_na=psi_nb=0.5 at midpoint of segment\n xmid = 0.5*(aloc[na].x+aloc[nb].x);\n ymid = 0.5*(aloc[na].y+aloc[nb].y);\n sint = 0.5 * ls * user->gN_fcn(xmid,ymid);\n // nodes could be Dirichlet\n if (abf[na] != 2)\n aF[na] -= sint;\n if (abf[nb] != 2)\n aF[nb] -= sint;\n }\n ierr = ISRestoreIndices(user->mesh->ns,&ans); CHKERRQ(ierr);\n }\n\n // element contributions and Dirichlet node residuals\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n for (k = 0; k < user->mesh->K; k++) {\n // element geometry and hat function gradients\n en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k\n dx1 = aloc[en[1]].x - aloc[en[0]].x;\n dx2 = aloc[en[2]].x - aloc[en[0]].x;\n dy1 = aloc[en[1]].y - aloc[en[0]].y;\n dy2 = aloc[en[2]].y - aloc[en[0]].y;\n detJ = dx1 * dy2 - dx2 * dy1;\n for (l = 0; l < 3; l++) {\n gradpsi[l][0] = ( dy2 * dchi[l][0] - dy1 * dchi[l][1]) / detJ;\n gradpsi[l][1] = (-dx2 * dchi[l][0] + dx1 * dchi[l][1]) / detJ;\n }\n // u and grad u on element\n gradu[0] = 0.0;\n gradu[1] = 0.0;\n for (l = 0; l < 3; l++) {\n if (abf[en[l]] == 2) // enforces symmetry\n unode[l] = user->gD_fcn(aloc[en[l]].x,aloc[en[l]].y);\n else\n unode[l] = au[en[l]];\n gradu[0] += unode[l] * gradpsi[l][0];\n gradu[1] += unode[l] * gradpsi[l][1];\n }\n // function values at quadrature points on element\n for (r = 0; r < q.n; r++) {\n uquad[r] = eval(unode,q.xi[r],q.eta[r]);\n xx = aloc[en[0]].x + dx1 * q.xi[r] + dx2 * q.eta[r];\n yy = aloc[en[0]].y + dy1 * q.xi[r] + dy2 * q.eta[r];\n aquad[r] = user->a_fcn(uquad[r],xx,yy);\n fquad[r] = user->f_fcn(uquad[r],xx,yy);\n }\n // residual contribution for each node of element\n for (l = 0; l < 3; l++) {\n if (abf[en[l]] == 2) { // set Dirichlet residual\n xx = aloc[en[l]].x; yy = aloc[en[l]].y;\n aF[en[l]] = au[en[l]] - user->gD_fcn(xx,yy);\n } else {\n sum = 0.0;\n for (r = 0; r < q.n; r++) {\n psi = chi(l,q.xi[r],q.eta[r]);\n ip = InnerProd(gradu,gradpsi[l]);\n sum += q.w[r] * ( aquad[r] * ip - fquad[r] * psi );\n }\n aF[en[l]] += fabs(detJ) * sum;\n }\n }\n }\n\n ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n ierr = UMRestoreNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr);\n PetscLogStagePop(); //STRIP\n return 0;\n}\n//ENDRESIDUAL\n\nPetscErrorCode FormPicard(SNES snes, Vec u, Mat A, Mat P, void *ctx) {\n PetscErrorCode ierr;\n unfemCtx *user = (unfemCtx*)ctx;\n const Quad2DTri q = symmgauss[user->quaddegree-1];\n const int *ae, *abf, *en;\n const Node *aloc;\n const double *au;\n double unode[3], gradpsi[3][2], uquad[4], aquad[4], v[9],\n dx1, dx2, dy1, dy2, detJ, xx, yy, sum;\n int n, k, l, m, r, cr, cv, row[3];\n\n PetscLogStagePush(user->jacstage); //STRIP\n ierr = MatZeroEntries(P); CHKERRQ(ierr);\n ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n for (n = 0; n < user->mesh->N; n++) {\n if (abf[n] == 2) {\n v[0] = 1.0;\n ierr = MatSetValues(P,1,&n,1,&n,v,ADD_VALUES); CHKERRQ(ierr);\n }\n }\n ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = UMGetNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr);\n for (k = 0; k < user->mesh->K; k++) {\n en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k\n // geometry of element\n dx1 = aloc[en[1]].x - aloc[en[0]].x;\n dx2 = aloc[en[2]].x - aloc[en[0]].x;\n dy1 = aloc[en[1]].y - aloc[en[0]].y;\n dy2 = aloc[en[2]].y - aloc[en[0]].y;\n detJ = dx1 * dy2 - dx2 * dy1;\n // gradients of hat functions and u on element\n for (l = 0; l < 3; l++) {\n gradpsi[l][0] = ( dy2 * dchi[l][0] - dy1 * dchi[l][1]) / detJ;\n gradpsi[l][1] = (-dx2 * dchi[l][0] + dx1 * dchi[l][1]) / detJ;\n if (abf[en[l]] == 2)\n unode[l] = user->gD_fcn(aloc[en[l]].x,aloc[en[l]].y);\n else\n unode[l] = au[en[l]];\n }\n // function values at quadrature points on element\n for (r = 0; r < q.n; r++) {\n uquad[r] = eval(unode,q.xi[r],q.eta[r]);\n xx = aloc[en[0]].x + dx1 * q.xi[r] + dx2 * q.eta[r];\n yy = aloc[en[0]].y + dy1 * q.xi[r] + dy2 * q.eta[r];\n aquad[r] = user->a_fcn(uquad[r],xx,yy);\n }\n // generate 3x3 element stiffness matrix (3x3 is max size but may be smaller)\n cr = 0; cv = 0; // cr = count rows; cv = value counter for all entries\n for (l = 0; l < 3; l++) {\n if (abf[en[l]] != 2) {\n row[cr++] = en[l];\n for (m = 0; m < 3; m++) {\n if (abf[en[m]] != 2) {\n sum = 0.0;\n for (r = 0; r < q.n; r++) {\n sum += q.w[r] * aquad[r] * InnerProd(gradpsi[l],gradpsi[m]);\n }\n v[cv++] = fabs(detJ) * sum;\n }\n }\n }\n }\n // insert element stiffness matrix\n ierr = MatSetValues(P,cr,row,cr,row,v,ADD_VALUES); CHKERRQ(ierr);\n }\n ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = UMRestoreNodeCoordArrayRead(user->mesh,&aloc); CHKERRQ(ierr);\n\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (A != P) {\n ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n ierr = MatSetOption(P,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE); CHKERRQ(ierr);\n PetscLogStagePop(); //STRIP\n return 0;\n}\n\n\n/* Note that nnz[n] is the number of nonzeros in row n. It equals one for\nDirichlet rows, one more than the number of incident triangles for an\ninterior point, and two more than the number of incident triangles for\nNeumann boundary nodes. */\n//STARTPREALLOC\nPetscErrorCode Preallocation(Mat J, unfemCtx *user) {\n PetscErrorCode ierr;\n const int *ae, *abf, *en;\n int *nnz, n, k, l;\n\n nnz = (int *)malloc(sizeof(int)*(user->mesh->N));\n ierr = ISGetIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n for (n = 0; n < user->mesh->N; n++)\n nnz[n] = (abf[n] == 1) ? 2 : 1;\n ierr = ISGetIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n for (k = 0; k < user->mesh->K; k++) {\n en = ae + 3*k; // en[0], en[1], en[2] are nodes of element k\n for (l = 0; l < 3; l++)\n if (abf[en[l]] != 2)\n nnz[en[l]] += 1;\n }\n ierr = ISRestoreIndices(user->mesh->e,&ae); CHKERRQ(ierr);\n ierr = ISRestoreIndices(user->mesh->bf,&abf); CHKERRQ(ierr);\n ierr = MatSeqAIJSetPreallocation(J,-1,nnz); CHKERRQ(ierr);\n free(nnz);\n return 0;\n}\n//ENDPREALLOC\n\n", "meta": {"hexsha": "37fdead61538d62835913426be4c4aa1d7f5e0e0", "size": 21127, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch10/unfem.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch10/unfem.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch10/unfem.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.263671875, "max_line_length": 129, "alphanum_fraction": 0.5718275193, "num_tokens": 6473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.6985104224321385}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include /* pow */\n#include \n#include \n#include \n\n// Common functions to all .cpps\n\n\n/* LCDM Hubble in 1/s */\ndouble hubble(double om, double orad, double a){\n\tdouble a3 = pow(a,3);\n\tdouble a4 = a*a3;\n\tdouble ol = 1.-om-orad;\n\treturn h0 * sqrt(om/a3+ orad/a4 + ol);\n}\n\n\n// Reheating time as a function of temperature --- Trh should be given in Kelvin\ndouble timeofrh(double Trh){\n\treturn sqrt(5./pow(M_PI,3)/gstar) * pow(10,lgmp)/pow(Trh*keltgev,2) *kgtgev / gevtds ;\n}\n\n/* Critical density in kg/m^3 */\ndouble rhoc(double a){\n\treturn 3.*pow(hubble(om, orad, a),2.)/(8.*M_PI*gnewton);\n}\n\n/* Omega_x for LCDM */\ndouble omegalcdm(double ox, double a){\n\treturn ox/pow(a,3.) * pow(h0/hubble(om,orad,a),2.);\n}\n\n\n/* Log10 of Mass spectrum in units 1/kg */\n// hi mass - Eq.2.5 of draft\n// Psi = 10^psihilg as a function of Log10[M] = lgm and omega_pbh\ndouble psihilg(double lgm, double opbh){\n\tdouble fpbh = opbh/oc;\n\treturn -12.2764 + log10(fpbh) - 3./2. * lgm;\n}\n\n// low mass - Eq.2.2 of draft\n// Psi = 10^psilowlg as a function of Log10[M] = lgm and peak mass\ndouble psilowlg(double lgm, double peakm){\n\tdouble aofmf = (peakm+2.723)/(-0.6576);\n\tdouble expt = 2.85*(lgm-peakm);\n\treturn 2.85*(aofmf + lgm) - pow(10,expt)/2.3026;\n}\n\n// full spectrum - polychromatic\n// Psi = 10^psibroadlg as a function of Log10[M] = lgm and peak mass\ndouble psibroadlg(double lgm, double peakm){\n\t// if mass is less than planck mass, set to 0\n\tif(lgmp>lgm){\n\t\t return -100.;\n\t\t}\n\t// if above peak mass, set to hi spectrum\n\telse if(lgm>peakm){\n\t\treturn psihilg(lgm,oc);\n\t\t}\n\t// if below peak mass, set to low spectrum\n\telse{\n\t\treturn psilowlg(lgm,peakm);\n\t}\n}\n\n\n\n// calculate volume fration given number density\ndouble epsilon(double lgni, double lgmass){\n\tdouble radius = 2. * gnewton * pow(10,lgmass)/pow(sofl,2);\n\tprintf(\"%e \\n\", radius);\n\treturn pow(10.,lgni) * 4. * M_PI * pow(radius,3) / 3.;\n}\n\n/* Entropy density */\n// Temperature given in Kelvin\ndouble entropy(double Trh, double a, double arh){\n\treturn 2.*pow(M_PI,2)/45 * gstar * pow(Trh*keltgev*arh/a,3.);\n}\n\n// absolute maximum theoretical number density\n// Some notes: A bh of mass 10^-5.96 kg has a volume of 1.76 x 10^-98 m^3 and so we can have number densities mathematically up to 10^98 x 0.74 where 0.74 is the close packing ratio (max ratio of cube to volume of packed spheres)\ndouble maxn0(double lgmass){\n\tdouble rsch = 2.*gnewton*pow(10.,lgmass)/pow(sofl,2); // schwarzschild radius in m\n\tdouble volume =4./3. * M_PI * pow(rsch,3);\n\treturn 1./volume * 0.74;\n}\n", "meta": {"hexsha": "c93752c15fc62b9c0bb40c51983bdcf6275eccc8", "size": 2852, "ext": "h", "lang": "C", "max_stars_repo_path": "gfuncs.h", "max_stars_repo_name": "nebblu/PBH", "max_stars_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gfuncs.h", "max_issues_repo_name": "nebblu/PBH", "max_issues_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gfuncs.h", "max_forks_repo_name": "nebblu/PBH", "max_forks_repo_head_hexsha": "b896bb65d0f204603e26b3579265d4cd613c48e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6893203883, "max_line_length": 230, "alphanum_fraction": 0.6746143058, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6981750974579698}} {"text": "#include \n#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n#define deg 180.0/M_PI;\n\n/*!\n * @brief Returns the angle between two vectors, in degrees.\n *\n * @param[in] n Length of vectors.\n * @param[in] va Initial vector. This is an array of dimension [n].\n * @param[in] vb Rotate vector. This is an array of dimension [n].\n *\n * @result Rotation angle in degrees between va and vb.\n *\n * @author Ben Baker\n *\n * @copyright MIT\n *\n */\ndouble compearth_matlab_fangle(const int n,\n const double *__restrict__ va,\n const double *__restrict__ vb)\n{\n double angle, magVa, magVb, xden, xnum;\n xnum = cblas_ddot(n, va, 1, vb, 1); \n magVa = cblas_dnrm2(n, va, 1);\n magVb = cblas_dnrm2(n, vb, 1);\n xden = magVa*magVb;\n angle = (double) NAN;\n if (xden > 0.0){angle = acos(xnum/xden)*deg;}\n return angle;\n}\n", "meta": {"hexsha": "97a161f4f758df8ca0b5babc648a503da44219da", "size": 1224, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/fangle.c", "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_issues_repo_path": "c_src/fangle.c", "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_forks_repo_path": "c_src/fangle.c", "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "avg_line_length": 25.5, "max_line_length": 70, "alphanum_fraction": 0.6519607843, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9546474194456935, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6979031743652725}} {"text": "/* poly/zsolve_cubic.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* zsolve_cubic.c - finds the complex roots of x^3 + a x^2 + b x + c = 0 */\n\n#include \n#include \n#include \n#include \n#include \n\n#define SWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)\n\nint\ngsl_poly_complex_solve_cubic (double a, double b, double c, \n gsl_complex *z0, gsl_complex *z1, \n gsl_complex *z2)\n{\n double q = (a * a - 3 * b);\n double r = (2 * a * a * a - 9 * a * b + 27 * c);\n\n double Q = q / 9;\n double R = r / 54;\n\n double Q3 = Q * Q * Q;\n double R2 = R * R;\n\n double CR2 = 729 * r * r;\n double CQ3 = 2916 * q * q * q;\n\n if (R == 0 && Q == 0)\n {\n GSL_REAL (*z0) = -a / 3;\n GSL_IMAG (*z0) = 0;\n GSL_REAL (*z1) = -a / 3;\n GSL_IMAG (*z1) = 0;\n GSL_REAL (*z2) = -a / 3;\n GSL_IMAG (*z2) = 0;\n return 3;\n }\n else if (CR2 == CQ3) \n {\n /* this test is actually R2 == Q3, written in a form suitable\n for exact computation with integers */\n\n /* Due to finite precision some double roots may be missed, and\n will be considered to be a pair of complex roots z = x +/-\n epsilon i close to the real axis. */\n\n double sqrtQ = sqrt (Q);\n\n if (R > 0)\n\t{\n\t GSL_REAL (*z0) = -2 * sqrtQ - a / 3;\n\t GSL_IMAG (*z0) = 0;\n\t GSL_REAL (*z1) = sqrtQ - a / 3;\n\t GSL_IMAG (*z1) = 0;\n\t GSL_REAL (*z2) = sqrtQ - a / 3;\n\t GSL_IMAG (*z2) = 0;\n\t}\n else\n\t{\n\t GSL_REAL (*z0) = -sqrtQ - a / 3;\n\t GSL_IMAG (*z0) = 0;\n\t GSL_REAL (*z1) = -sqrtQ - a / 3;\n\t GSL_IMAG (*z1) = 0;\n\t GSL_REAL (*z2) = 2 * sqrtQ - a / 3;\n\t GSL_IMAG (*z2) = 0;\n\t}\n return 3;\n }\n else if (CR2 < CQ3) /* equivalent to R2 < Q3 */\n {\n double sqrtQ = sqrt (Q);\n double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;\n double theta = acos (R / sqrtQ3);\n double norm = -2 * sqrtQ;\n double r0 = norm * cos (theta / 3) - a / 3;\n double r1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;\n double r2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;\n\n /* Sort r0, r1, r2 into increasing order */\n\n if (r0 > r1)\n\tSWAP (r0, r1);\n\n if (r1 > r2)\n\t{\n\t SWAP (r1, r2);\n\n\t if (r0 > r1)\n\t SWAP (r0, r1);\n\t}\n\n GSL_REAL (*z0) = r0;\n GSL_IMAG (*z0) = 0;\n\n GSL_REAL (*z1) = r1;\n GSL_IMAG (*z1) = 0;\n\n GSL_REAL (*z2) = r2;\n GSL_IMAG (*z2) = 0;\n\n return 3;\n }\n else\n {\n double sgnR = (R >= 0 ? 1 : -1);\n double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0 / 3.0);\n double B = Q / A;\n\n if (A + B < 0)\n\t{\n\t GSL_REAL (*z0) = A + B - a / 3;\n\t GSL_IMAG (*z0) = 0;\n\n\t GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;\n\t GSL_IMAG (*z1) = -(sqrt (3.0) / 2.0) * fabs(A - B);\n\n\t GSL_REAL (*z2) = -0.5 * (A + B) - a / 3;\n\t GSL_IMAG (*z2) = (sqrt (3.0) / 2.0) * fabs(A - B);\n\t}\n else\n\t{\n\t GSL_REAL (*z0) = -0.5 * (A + B) - a / 3;\n\t GSL_IMAG (*z0) = -(sqrt (3.0) / 2.0) * fabs(A - B);\n\n\t GSL_REAL (*z1) = -0.5 * (A + B) - a / 3;\n\t GSL_IMAG (*z1) = (sqrt (3.0) / 2.0) * fabs(A - B);\n\n\t GSL_REAL (*z2) = A + B - a / 3;\n\t GSL_IMAG (*z2) = 0;\n\t}\n\n return 3;\n }\n}\n", "meta": {"hexsha": "4fcf2931a1aab06d12037733853eb47426818ad0", "size": 3947, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/poly/zsolve_cubic.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/poly/zsolve_cubic.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/poly/zsolve_cubic.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.6298701299, "max_line_length": 75, "alphanum_fraction": 0.5181150241, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.6972516627967188}} {"text": "/*\nPierwszy program stosuje metode Brenta\ngsl_root_fsolver_brent \ndla rownania\nx^2 - 5 = 0\n\nrozwiazaniem jest x = \\sqrt 5 = 2.236068...\n*/\n#include \n#include \n#include \n#include \n#include \n\n#include \"demo_fn.h\"\n\nint\nmain (int argc, char *argv[])\n{\n int status;\n int iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double r = 0, r_expected = sqrt (5.0);\n double x_lo = 0.0, x_hi = 5.0;\n gsl_function F;\n struct quadratic_params params = {1.0, -2.0, 1.0};\n\n F.function = &quadratic;\n F.params = ¶ms;\n\n if (argc < 2) {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n char *method = argv[1];\n if (0 == strcmp(\"bisection\", method)) {\n T = gsl_root_fsolver_bisection;\n } else if (0 == strcmp(\"secant\", method)) {\n T = gsl_root_fsolver_brent;\n } else if (0 == strcmp(\"steffenson\", method)) {\n T = gsl_root_fsolver_falsepos;\n } else {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n\n T = gsl_root_fsolver_bisection;\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\", \n gsl_root_fsolver_name (s));\n\n printf (\"%5s [%9s, %9s] %9s %10s %9s\\n\",\n \"iter\", \"lower\", \"upper\", \"root\", \n \"err\", \"err(est)\");\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,\n 0, 0.001);\n\n if (status == GSL_SUCCESS)\n printf (\"Converged:\\n\");\n\n printf (\"%5d [%.7f, %.7f] %.7f %+.7f %.7f\\n\",\n iter, x_lo, x_hi,\n r, r - r_expected, \n x_hi - x_lo);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n return status;\n}\n\n\n", "meta": {"hexsha": "499c11d61de298465288a94e19e76377a933e16d", "size": 1938, "ext": "c", "lang": "C", "max_stars_repo_path": "lab5/root_finding_modified.c", "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab5/root_finding_modified.c", "max_issues_repo_name": "mistyfiky/agh-mownit", "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab5/root_finding_modified.c", "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0714285714, "max_line_length": 52, "alphanum_fraction": 0.5737874097, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770431, "lm_q2_score": 0.8056321913146127, "lm_q1q2_score": 0.6970523736247186}} {"text": "#include \n#include \n#include \n#include \n\nunsigned int k;\nunsigned int n1;\nunsigned int n2;\nunsigned int t;\n\nstatic void usage(int argc, char *argv[]) {\n printf (\n \"Usage: %s k n1 n2 t\\n\"\n \"\\n\"\n \"If a population contains n1 elements of \\\"type 1\\\" and n2 elements\\n\"\n \"of \\\"type 2\\\" then the hypergeometric distribution gives the probability\\n\"\n \"of obtaining k elements of \\\"type 1\\\" in t samples from the population\\n\"\n \"without replacement.\\n\"\n \"This program computes the Pvalue of such a distribution\\n\", argv[0]);\n exit (-1);\n}\n\nint main(int argc, char *argv[]) {\n\n if (argc != 5)\n usage(argc, argv);\n\n k = atoi(argv[1]);\n n1 = atoi(argv[2]);\n n2 = atoi(argv[3]);\n t = atoi(argv[4]);\n\n double Q = gsl_cdf_hypergeometric_Q (k, n1, n2, t);\n double P = gsl_cdf_hypergeometric_P (k, n1, n2, t);\n\n printf(\"%g\\n\", Q);\n if (P < Q)\n fprintf(stderr, \"Warning: P < Q, %g < %g\\n\", P, Q);\n\n}\n", "meta": {"hexsha": "439e3e5037e11f26df5087894065726888665575", "size": 949, "ext": "c", "lang": "C", "max_stars_repo_path": "randomizzatore/hyper.c", "max_stars_repo_name": "scovit/nust-helico", "max_stars_repo_head_hexsha": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3", "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": "randomizzatore/hyper.c", "max_issues_repo_name": "scovit/nust-helico", "max_issues_repo_head_hexsha": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3", "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": "randomizzatore/hyper.c", "max_forks_repo_name": "scovit/nust-helico", "max_forks_repo_head_hexsha": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3", "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.1463414634, "max_line_length": 78, "alphanum_fraction": 0.6311907271, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6967788628306247}} {"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: Expi.c\n *\n * Description: Calculation of the exponential integrals (w/o the GSL special\n * \t\t\tfunctions). \n *\n * Version: 1.0\n * Created: 15/04/2013 11:54:19\n * Revision: none\n * Compiler: gcc\n *\n * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n * Organization: \n *\n * =====================================================================================\n */\n\n#include \"funcs.h\"\n#include \n/* #include */\n\ndouble fu ( double t, void* params ) \n{\n\tdouble f = -exp(-t)/t ;\n\treturn f ;\n}\n\ndouble ex ( double t, void* params )\n{\n\tdouble e = exp(-t) ;\n\treturn e ;\n}\n\nint expi ( double x, double* result, double* abserr )\n{\n\tdouble r, err ;\n\n\tgsl_integration_workspace* expi_ws =\n\t \tgsl_integration_workspace_alloc (WS_SZ) ;\n\n\tgsl_function F ;\n\tF.function = &fu ;\n\n\tint status ;\n\tstatus = gsl_integration_qagiu ( &F, x, 10e-9, .001 , WS_SZ, expi_ws, &r,\n\t\t\t\t&err) ;\n\n\t*result = r ; *abserr = err ;\n\n/*\tUsing the GSL special functions, it is simply:\n *\n * *result = - gsl_sf_expint_E1(x) ;\n */\n\n\tgsl_integration_workspace_free (expi_ws) ;\n\n\treturn status;\n}\n\nint expi_plus ( double x, double* result, double* abserr )\n{\n\tdouble r, err ;\n\n\tgsl_integration_workspace *expi_ws =\n\t \tgsl_integration_workspace_alloc (WS_SZ) ;\n\n\tgsl_function F ;\n\tF.function = &ex ;\n\n\tint status ;\n\tstatus = gsl_integration_qawc ( &F, -x, x, 0, 1e-9, .001, WS_SZ,\n\t\t\texpi_ws, &r, &err ) ;\n\n\tdouble R , EXPI , ERREXPI ;\n\tint s = expi ( x , &EXPI, &ERREXPI ) ;\n\tR = - (r - EXPI) ; /* The minus (-) sign because of the def.\n\t\t\t\t\t\t\tof ex \t\t\t\t*/\n\tdouble ERR ;\n\tERR = err + ERREXPI ;\n\n\t*result = R ; \n\t*abserr = ERR ;\n\n/* \tUsing the GSL exponential integral, it is simply:\n *\n * \tR = gsl_sf_expint_Ei(x) ;\n * \n */\n\tgsl_integration_workspace_free (expi_ws) ;\n\n\treturn status + s ;\n}\n\n\n", "meta": {"hexsha": "1734c7a62d3da2552c818291065651c2705fc013", "size": 3431, "ext": "c", "lang": "C", "max_stars_repo_path": "Expi.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": "Expi.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": "Expi.c", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.448, "max_line_length": 88, "alphanum_fraction": 0.6385893326, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6967393384116553}} {"text": "/* poly/demo.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\nint\nmain ()\n{\n int i;\n double a[6] = { -1, 0, 0, 0, 0, 1 }; /* P(x) = x^5 - 1 */\n double z[10];\n\n gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc (6) ;\n \n gsl_poly_complex_solve (a, 6, w, z) ;\n\n gsl_poly_complex_workspace_free (w) ;\n\n for (i = 0; i < 5 ; i++)\n {\n printf(\"z%d = %+.18f %+.18f\\n\", i, z[2*i], z[2*i+1]) ;\n }\n}\n", "meta": {"hexsha": "17dc6937a661422d3f9118313b6134dae540ce59", "size": 1223, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/poly/demo.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 29.8292682927, "max_line_length": 81, "alphanum_fraction": 0.6672117743, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114836, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6965621310808098}} {"text": "#include \n#include \n#include \"function.h\"\n\nextern double f (double, void*);\n\nint\nmain (void)\n{\n /* Claim memory needed for adaptive integration */\n gsl_integration_workspace * w \n = gsl_integration_workspace_alloc (1000);\n \n /* Construct GSL function object to describe solution */\n gsl_function F;\n F.function = &f;\n double alpha = 1.0;\n F.params = NULL;\n\n /* Parameters to control quadrature routine */\n double a, b, tol_abs, tol_rel;\n int limit;\n a = 0.0;\n b = 3.0;\n tol_abs = 0;\n tol_rel = 1.0e-7;\n limit = 1000;\n\n // Test that the function is implemented properly\n //double test = GSL_FN_EVAL(&F,2);\n //printf(\"TEST RESULT: %.18f\\n\", test);\n\n\n /* Actual call to quadrature routine */\n double result, error;\n gsl_integration_qag (&F, a, b, tol_abs, tol_rel, limit,\n GSL_INTEG_GAUSS15, w, &result, &error); \n double mathematica_result = 1.29646778572437307899;\n\n printf (\"result = % .18f\\n\", result);\n printf (\"mathematica result = % .18f\\n\", mathematica_result);\n printf (\"estimated error = % .18f\\n\", error);\n printf (\"error vs. mathematica = % .18f\\n\", \n fabs(result - mathematica_result));\n printf (\"# intervals = %d\\n\", (int) w->size);\n\n /* Return memory allocated for solver */\n gsl_integration_workspace_free (w);\n\n return 0;\n}\n", "meta": {"hexsha": "b70d7a82c887bd8f8de56ed83fb1c924a0ce48c9", "size": 1364, "ext": "c", "lang": "C", "max_stars_repo_path": "Assignment-03/question-2/main.c", "max_stars_repo_name": "gnu-user/mcsc-6030-assignments", "max_stars_repo_head_hexsha": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "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": "Assignment-03/question-2/main.c", "max_issues_repo_name": "gnu-user/mcsc-6030-assignments", "max_issues_repo_head_hexsha": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "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": "Assignment-03/question-2/main.c", "max_forks_repo_name": "gnu-user/mcsc-6030-assignments", "max_forks_repo_head_hexsha": "42825cdbc4532d9da6ebdba549b65fb1e36456a0", "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.2307692308, "max_line_length": 66, "alphanum_fraction": 0.6400293255, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6963804001267488}} {"text": "#include \n#include \n#include \n#include \n#include \n \n\ndouble ar1_ts (double * params, int n, gsl_rng * r)\n{\n double beta = params[0];\n double alpha = params[1];\n double s = params[2];\n\n int i;\n double x = beta / (1 - alpha); // Start at mean of stationary dist\n double sum = 0;\n for (i = 1; i <= n; i++) {\n sum += x;\n x = beta + alpha * x + gsl_ran_gaussian(r, s);\n }\n\n return sum / n;\n}\n\nint main(void)\n{\n clock_t start, end;\n double cpu_time_used;\n\n int N = 1e7;\n double beta = 1.0;\n double alpha = 0.9;\n double s = 1;\n double params[3] = {beta, alpha, s};\n\n /* create a generator via GSL_RNG_TYPE */\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 gsl_rng_set(r, 1); \n\n start = clock();\n double sample_mean = ar1_ts(params, N, r);\n end = clock();\n cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n\n gsl_rng_free (r);\n\n printf(\"mean = %g\\n\", sample_mean);\n printf(\"time elapsed = %g seconds\\n\", cpu_time_used);\n return 0;\n}\n\n", "meta": {"hexsha": "9434d58079b4dea15732c9d35e7464b4b441b33a", "size": 1168, "ext": "c", "lang": "C", "max_stars_repo_path": "john/fast_loop_examples/ar1_sample_mean.c", "max_stars_repo_name": "QuantEcon/RBA_RBNZ_Workshops", "max_stars_repo_head_hexsha": "20a9f2feb9b54a73d6d2c79e0824eb528f7e1f11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2017-02-07T22:07:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T09:01:00.000Z", "max_issues_repo_path": "john/fast_loop_examples/ar1_sample_mean.c", "max_issues_repo_name": "tomas-rampas/RBA_RBNZ_Workshops", "max_issues_repo_head_hexsha": "20a9f2feb9b54a73d6d2c79e0824eb528f7e1f11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-11-27T09:38:18.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-27T09:38:18.000Z", "max_forks_repo_path": "john/fast_loop_examples/ar1_sample_mean.c", "max_forks_repo_name": "tomas-rampas/RBA_RBNZ_Workshops", "max_forks_repo_head_hexsha": "20a9f2feb9b54a73d6d2c79e0824eb528f7e1f11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-01-08T18:46:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-31T21:50:48.000Z", "avg_line_length": 20.8571428571, "max_line_length": 71, "alphanum_fraction": 0.5727739726, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6962967891894893}} {"text": "#include \"lah.h\"\n\n#ifdef HAVE_LAPACK\n#include \n#include \n\n/* Input Matrix P has to be symmetric positive semi-definite, \n * e.g. real covarianz matrix */\nlah_Return lah_matSqrt(lah_mat *P, lah_mat *Psqrt, lah_mat *Work)\n{\n lah_Return res = lahReturnOk;\n lah_index i, j;\n lah_value temp;\n lah_value *S;\n lah_mat *Z;\n \n if (P == NULL || P->nR != P->nC\n || Psqrt == NULL || P->nR != Psqrt->nR || P->nC != Psqrt->nC)\n {\n return lahReturnParameterError;\n }\n if (LAH_ISTYPE(P, lahTypeDiagonal))\n {\n for (j = 0; j < P->nC; j++)\n LAH_ENTRY(P, j, j) = sqrt(LAH_ENTRY(P, j, j));\n return lahReturnOk;\n }\n \n /* allocate space for the output parameters and workspace arrays */\n S = malloc(P->nR * sizeof(lah_value));\n Z = lah_matAlloc(P->nR, P->nR, 1);\n res = lah_eigenValue(P, S, Z);\n if(res != lahReturnOk)\n return res;\n \n /* Calculate Workspace = Z*D */\n for (j = 0; j < P->nC; ++j) \n {\n temp = S[j];\n if (temp < 0)\n return lahReturnMathError; /*Not positive semi definite*/\n else \n temp = sqrt(temp);\n for (i = 0; i< P->nR; ++i) \n {\n LAH_ENTRY(Work, i, j) = LAH_ENTRY(Z, i, j) * temp;\n }\n }\n\n /* Calculate End result P_sqrt = W*Z^T */\n res = lah_matMul(lahNorm, lahTrans, 0, 1, Psqrt, Work, Z);\n \n lah_matFree(Z);\n free(S);\n return res;\n}\n#endif\n", "meta": {"hexsha": "3d35e9463405b8c776904a6ff4933de7524041ab", "size": 1475, "ext": "c", "lang": "C", "max_stars_repo_path": "Source/lah_matSqrt.c", "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "Source/lah_matSqrt.c", "max_issues_repo_name": "maj0e/linear-algebra-helpers", "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "Source/lah_matSqrt.c", "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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.4310344828, "max_line_length": 71, "alphanum_fraction": 0.5308474576, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6956709075290592}} {"text": "#include \"lah.h\"\n\n#ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */\n#include \nlah_Return lah_chol(lah_mat *P, lah_index setZero)\n{\n lah_index i, j;\n lapack_int res;\n if (P == NULL || !LAH_ISTYPE(P, lahTypeSquare))\n return lahReturnParameterError;\n \n res = POTRF(LAH_LAPACK_LAYOUT, 'L' , P->nR, P->data, P->nR);\n \n /* Set rest of matrix to zero, if setZero == 1 */\n if (setZero)\n {\n for (i = 0; i < P->nR; i++)\n {\n for(j = i + 1; j < P->nC; ++j)\n {\n LAH_ENTRY(P, i, j) = 0.0;\n }\n }\n }\n return (res == 0) ? lahReturnOk : lahReturnExternError;\n}\n\n#else /* fallback to primitive linear algebra subroutines */\n#include \n\nlah_Return lah_chol(lah_mat *P, lah_index setZero)\n{\n lah_index i, j, k, N;\n lah_value *diag, *value;\n\n if (P == NULL)\n {\n return lahReturnParameterError;\n }\n\n N = P->nR;\n\n /* see https://de.wikipedia.org/wiki/Cholesky-Zerlegung#Pseudocode */\n for (i = 0; i < N; i++)\n {\n /* Pointer to diagonal element */\n diag = P->data + i * (P->incRow + P->incCol);\n /* check if positive */\n if (*diag < 0.00001 )\n {\n return lahReturnMathError;\n }\n /* square root of diagonal element in place */\n *diag = sqrt(*diag);\n \n /* divide elements below diagonal by diagonal element */\n for (k = 1; k < N - i; k++)\n {\n *(diag + k * P->incRow) /= *diag;\n }\n /* compute upper right submatrix */\n for (j = i + 1; j < N; j++)\n {\n value = P->data + j * P->incRow + j * P->incCol;\n for (k = j; k < N; k++)\n {\n *value -= LAH_ENTRY(P, k, i) * LAH_ENTRY(P, j, i);\n value += P->incRow;\n }\n }\n }\n /* Set rest of matrix to zero, if setZero == 1 */\n if (setZero)\n {\n for (i = 0; i < N; i++)\n {\n for(j = i + 1; j < N; ++j)\n {\n LAH_ENTRY(P, i, j) = 0.0;\n }\n }\n }\n\n return lahReturnOk;\n}\n#endif /* endif primitive implementation */\n", "meta": {"hexsha": "0e01cb15c7605ec5c64e174b300b34d41d5408a3", "size": 2192, "ext": "c", "lang": "C", "max_stars_repo_path": "Source/lah_chol.c", "max_stars_repo_name": "maj0e/linear-algebra-helpers", "max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "Source/lah_chol.c", "max_issues_repo_name": "maj0e/linear-algebra-helpers", "max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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": "Source/lah_chol.c", "max_forks_repo_name": "maj0e/linear-algebra-helpers", "max_forks_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa", "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.1954022989, "max_line_length": 73, "alphanum_fraction": 0.4708029197, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522813, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6956626421286645}} {"text": "static char help[] = \"Solve a 2-variable polynomial optimization problem.\\n\"\n\"Implements an objective function and its gradient (the residual). The \\n\"\n\"Jacobian (Hessian) is not implemented. Usage is either objective-only\\n\"\n\" ./cartoon -snes_[fd|mf] -snes_fd_function\\n\"\n\"or with gradient\\n\"\n\" ./cartoon -snes_[fd|mf]\\n\\n\";\n\n#include \n\nPetscErrorCode FormObjective(SNES snes, Vec x, PetscReal *Phi, void *ctx) {\n PetscErrorCode ierr;\n const PetscReal *ax;\n\n ierr = VecGetArrayRead(x,&ax); CHKERRQ(ierr);\n *Phi = 0.25 * (pow(ax[0],4.0) + pow(ax[1],4.0)) - 2.0 * ax[0] + 2.0 * ax[1];\n ierr = VecRestoreArrayRead(x,&ax); CHKERRQ(ierr);\n return 0;\n}\n\n// residual F = grad Phi\nPetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {\n PetscErrorCode ierr;\n const PetscReal *ax;\n PetscReal *aF;\n\n ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF);CHKERRQ(ierr);\n aF[0] = ax[0]*ax[0]*ax[0] - 2.0;\n aF[1] = ax[1]*ax[1]*ax[1] + 2.0;\n ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr);\n return 0;\n}\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n SNES snes;\n Vec x, r, xexact;\n const PetscInt ix[2] = {0,1};\n PetscReal iv[2], err;\n\n PetscInitialize(&argc,&argv,NULL,help);\n\n ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);\n ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(x); CHKERRQ(ierr);\n\n iv[0] = 0.5; iv[1] = 0.5; // initial iterate corresponds to nonsingular Hessian\n ierr = VecSetValues(x,2,ix,iv,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecAssemblyBegin(x); CHKERRQ(ierr);\n ierr = VecAssemblyEnd(x); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetObjective(snes,FormObjective,NULL); CHKERRQ(ierr);\n ierr = VecDuplicate(x,&r); CHKERRQ(ierr);\n ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr);\n\n iv[0] = pow(2.0,1.0/3.0); iv[1] = - iv[0]; // exact soln\n ierr = VecDuplicate(x,&xexact); CHKERRQ(ierr);\n ierr = VecSetValues(xexact,2,ix,iv,ADD_VALUES); CHKERRQ(ierr); // note ADD_VALUES\n ierr = VecAssemblyBegin(xexact); CHKERRQ(ierr);\n ierr = VecAssemblyEnd(xexact); CHKERRQ(ierr);\n ierr = VecAXPY(x,-1.0,xexact); CHKERRQ(ierr); // x <-- x + (-1.0) xexact\n ierr = VecNorm(x,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"numerical error |x-x_exact|_inf = %g\\n\",err); CHKERRQ(ierr);\n\n VecDestroy(&x); VecDestroy(&r); VecDestroy(&xexact);\n SNESDestroy(&snes);\n PetscFinalize();\n return 0;\n}\n\n", "meta": {"hexsha": "2fcd0aa4a1f4cf8f47e4c2327473768fc12fe4db", "size": 2790, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch9/solns/cartoon.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/ch9/solns/cartoon.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/ch9/solns/cartoon.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 37.2, "max_line_length": 101, "alphanum_fraction": 0.6451612903, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6952029419105472}} {"text": "static const char help[] =\n\"Solves obstacle problem in 2D using SNESVI. Option prefix -obs_.\\n\"\n\"The obstacle problem is a free boundary problem for the Poisson equation\\n\"\n\"in which the solution u(x,y) is constrained to be above the obstacle psi(x,y):\\n\"\n\" - Lap u = f, u >= psi.\\n\"\n\"Equivalently it is a variational inequality (VI), complementarity problem\\n\"\n\"(CP), or an inequality-constrained minimization. The example here is\\n\"\n\"on the square (-2,2)^2 and has known exact solution. Because of the\\n\"\n\"constraint, the problem is nonlinear but the code reuses the residual and\\n\"\n\"Jacobian evaluation code for the Poisson equation in ch6/.\\n\\n\";\n\n#include \n#include \"../ch6/poissonfunctions.h\"\n\n// z = psi(x,y) is the hemispherical obstacle, but made C^1 with \"skirt\" at r=r0\nPetscReal psi(PetscReal x, PetscReal y) {\n const PetscReal r = x * x + y * y,\n r0 = 0.9,\n psi0 = PetscSqrtReal(1.0 - r0*r0),\n dpsi0 = - r0 / psi0;\n if (r <= r0) {\n return PetscSqrtReal(1.0 - r);\n } else {\n return psi0 + dpsi0 * (r - r0);\n }\n}\n\n/* This exact solution solves a 1D radial free-boundary problem for the\nLaplace equation, on the interval 0 < r < 2, with hemispherical obstacle\n psi(r) = / sqrt(1 - r^2), r < 1\n \\ -1, otherwise\nThe Laplace equation applies where u(r) > psi(r),\n u''(r) + r^-1 u'(r) = 0\nwith boundary conditions including free b.c.s at an unknown location r = a:\n u(a) = psi(a), u'(a) = psi'(a), u(2) = 0\nThe solution is u(r) = - A log(r) + B on r > a. The boundary conditions\ncan then be reduced to a root-finding problem for a:\n a^2 (log(2) - log(a)) = 1 - a^2\nThe solution is a = 0.697965148223374 (giving residual 1.5e-15). Then\nA = a^2*(1-a^2)^(-0.5) and B = A*log(2) are as given below in the code. */\nPetscReal u_exact(PetscReal x, PetscReal y) {\n const PetscReal afree = 0.697965148223374,\n A = 0.680259411891719,\n B = 0.471519893402112;\n PetscReal r;\n r = PetscSqrtReal(x * x + y * y);\n return (r <= afree) ? psi(x,y) // active set; on the obstacle\n : - A * PetscLogReal(r) + B; // solves laplace eqn\n}\n\n// boundary conditions from exact solution\nPetscReal g_fcn(PetscReal x, PetscReal y, PetscReal z, void *ctx) {\n return u_exact(x,y);\n}\n\n// we solve Laplace's equation with f = 0\nPetscReal zero(PetscReal x, PetscReal y, PetscReal z, void *ctx) {\n return 0.0;\n}\n\nextern PetscErrorCode FormUExact(DMDALocalInfo*, Vec);\nextern PetscErrorCode GetActiveSet(SNES, DMDALocalInfo*, Vec, Vec,\n PetscInt*, PetscReal*);\nextern PetscErrorCode FormBounds(SNES, Vec, Vec);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da, da_after;\n SNES snes;\n KSP ksp;\n Vec u_initial, u, u_exact, Xl, Xu;\n PoissonCtx user;\n const PetscReal aexact = 0.697965148223374;\n SNESConvergedReason reason;\n PetscInt snesit, kspit;\n PetscReal error1,errorinf,actarea,exactarea,areaerr;\n DMDALocalInfo info;\n char dumpname[256] = \"dump.dat\";\n PetscBool dumpbinary = PETSC_FALSE;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\n\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"obs_\",\"options to obstacle\",\"\");CHKERRQ(ierr);\n ierr = PetscOptionsString(\"-dump_binary\",\n \"filename for saving solution AND OBSTACLE in PETSc binary format\",\n \"obstacle.c\",dumpname,dumpname,sizeof(dumpname),&dumpbinary); CHKERRQ(ierr);\n ierr = PetscOptionsEnd();CHKERRQ(ierr);\n\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,\n 3,3, // override with -da_grid_x,_y\n PETSC_DECIDE,PETSC_DECIDE, // num of procs in each dim\n 1,1,NULL,NULL, // dof = 1 and stencil width = 1\n &da);CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da,-2.0,2.0,-2.0,2.0,-1.0,-1.0);CHKERRQ(ierr);\n\n user.cx = 1.0;\n user.cy = 1.0;\n user.cz = 1.0;\n user.g_bdry = &g_fcn;\n user.f_rhs = &zero;\n user.addctx = NULL;\n ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da);CHKERRQ(ierr);\n ierr = SNESSetApplicationContext(snes,&user);CHKERRQ(ierr);\n\n // set the SNES type to a variational inequality (VI) solver of reduced-space\n // (RS) type\n ierr = SNESSetType(snes,SNESVINEWTONRSLS);CHKERRQ(ierr);\n ierr = SNESVISetComputeVariableBounds(snes,&FormBounds);CHKERRQ(ierr);\n\n // reuse residual and jacobian from ch6/\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)Poisson2DFunctionLocal,&user); CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr);\n ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);\n ierr = KSPSetType(ksp,KSPCG); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);\n\n // initial iterate is zero for simplicity\n ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr);\n ierr = VecSet(u_initial,0.0); CHKERRQ(ierr);\n\n /* solve and get solution, DM after solution*/\n ierr = SNESSolve(snes,NULL,u_initial);CHKERRQ(ierr);\n ierr = VecDestroy(&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); /* do not destroy u */\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n ierr = VecDuplicate(u,&Xl); CHKERRQ(ierr);\n ierr = VecDuplicate(u,&Xu); CHKERRQ(ierr);\n ierr = FormBounds(snes,Xl,Xu); CHKERRQ(ierr);\n\n /* save solution to binary file if requested */\n if (dumpbinary) {\n PetscViewer dumpviewer;\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"writing u,psi in binary format to %s ...\\n\",dumpname); CHKERRQ(ierr);\n ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,dumpname,FILE_MODE_WRITE,&dumpviewer); CHKERRQ(ierr);\n ierr = VecView(u,dumpviewer); CHKERRQ(ierr);\n ierr = VecView(Xl,dumpviewer); CHKERRQ(ierr);\n ierr = PetscViewerDestroy(&dumpviewer); CHKERRQ(ierr);\n }\n\n /* compute final performance measures */\n ierr = SNESGetConvergedReason(snes,&reason); CHKERRQ(ierr);\n if (reason <= 0) {\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"WARNING: SNES not converged ... use -snes_converged_reason to check\\n\"); CHKERRQ(ierr);\n }\n ierr = SNESGetIterationNumber(snes,&snesit); CHKERRQ(ierr);\n ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);\n ierr = KSPGetIterationNumber(ksp,&kspit); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %d x %d grid ... %s, SNES iters = %d, last KSP iters = %d\\n\",\n info.mx,info.my,SNESConvergedReasons[reason],snesit,kspit); CHKERRQ(ierr);\n\n /* compare to exact */\n ierr = GetActiveSet(snes,&info,u,Xl,NULL,&actarea); CHKERRQ(ierr);\n exactarea = PETSC_PI * aexact * aexact;\n areaerr = PetscAbsReal(actarea - exactarea) / exactarea;\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n ierr = FormUExact(&info,u_exact); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); /* u <- u - u_exact */\n ierr = VecNorm(u,NORM_1,&error1); CHKERRQ(ierr);\n error1 /= (PetscReal)info.mx * (PetscReal)info.my;\n ierr = VecNorm(u,NORM_INFINITY,&errorinf); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"errors: av |u-uexact| = %.3e, |u-uexact|_inf = %.3e, active area error = %.3f%%\\n\",\n error1,errorinf,100.0*areaerr); CHKERRQ(ierr);\n\n VecDestroy(&u_exact); VecDestroy(&Xl); VecDestroy(&Xu);\n SNESDestroy(&snes);\n return PetscFinalize();\n}\n\n\nPetscErrorCode GetActiveSet(SNES snes, DMDALocalInfo *info, Vec u, Vec Xl,\n PetscInt *act, PetscReal *actarea) {\n PetscErrorCode ierr;\n Vec F;\n const PetscReal *au, *aXl, *aF, zerotol = 1.0e-8; // see petsc/src/snes/impls/vi/vi.c for value\n PetscReal dx, dy;\n PetscInt i,n,lact,gact;\n\n dx = 4.0 / (PetscReal)(info->mx-1);\n dy = 4.0 / (PetscReal)(info->my-1);\n ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr);\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecGetArrayRead(Xl,&aXl); CHKERRQ(ierr);\n ierr = SNESGetFunction(snes,&F,NULL,NULL); CHKERRQ(ierr); /* do not destroy F */\n ierr = VecGetArrayRead(F,&aF); CHKERRQ(ierr);\n lact = 0;\n for (i=0; i 0.0))\n lact++;\n }\n ierr = VecRestoreArrayRead(u,&au);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(Xl,&aXl);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(F,&aF); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lact,&gact,1,MPIU_INT,MPIU_SUM,PetscObjectComm((PetscObject)snes));CHKERRQ(ierr);\n if (act) {\n *act = gact;\n }\n if (actarea) {\n *actarea = dx * dy * gact;\n }\n return 0;\n}\n\n\nPetscErrorCode FormUExact(DMDALocalInfo *info, Vec u) {\n PetscErrorCode ierr;\n PetscInt i,j;\n PetscReal **au, dx, dy, x, y;\n dx = 4.0 / (PetscReal)(info->mx-1);\n dy = 4.0 / (PetscReal)(info->my-1);\n ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);\n for (j=info->ys; jys+info->ym; j++) {\n y = -2.0 + j * dy;\n for (i=info->xs; ixs+info->xm; i++) {\n x = -2.0 + i * dx;\n au[j][i] = u_exact(x,y);\n }\n }\n ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);\n return 0;\n}\n\n//STARTBOUNDS\n// for call-back: tell SNESVI we want psi <= u < +infinity\nPetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {\n PetscErrorCode ierr;\n DM da;\n DMDALocalInfo info;\n PetscInt i, j;\n PetscReal **aXl, dx, dy, x, y;\n ierr = SNESGetDM(snes,&da);CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n dx = 4.0 / (PetscReal)(info.mx-1);\n dy = 4.0 / (PetscReal)(info.my-1);\n ierr = DMDAVecGetArray(da, Xl, &aXl);CHKERRQ(ierr);\n for (j=info.ys; j\n#include \n#include \n//#include \n#include \n#include \n#include \n\nvoid least_square_solver(double *matA, int n_row, int n_col, double *y, double *sol_x) {\n \n int i, j, k, tmp;\n double sum;\n gsl_matrix * A = gsl_matrix_alloc (n_row,n_col);\n gsl_matrix * V = gsl_matrix_alloc (n_col,n_col);\n gsl_vector * S = gsl_vector_alloc (n_col);\n gsl_vector * work = gsl_vector_alloc (n_col);\n// gsl_matrix * U = gsl_matrix_alloc (n_row-1,n_col_ids);\n gsl_vector * b = gsl_vector_alloc (n_row);\n gsl_vector * x = gsl_vector_alloc (n_col);\n \n // need to copy matA to A, y to b!\n for (i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"myfun.h\"\n\nusing namespace std;\n\n#ifndef MyEPS_\n#define MyEPS_\nstatic double EPS = numeric_limits::epsilon();\n#endif\n// =====================================================================\ntemplate\nstruct brace {\n\tT first, second;\n};\n\ntemplate brace make_brace(const T &m1, const T &m2) {\n\tbrace ans;\n\tans.first = m1;\n\tans.second = m2;\n\treturn ans;\n}\n\ntemplate\nstruct triplet {\n\tT first, second, third;\n};\n\ntemplate triplet make_triplet(const T &m1, const T &m2, \n\t\tconst T &m3) {\n\ttriplet ans;\n\tans.first = m1;\n\tans.second = m2;\n\tans.third = m3;\n\treturn ans;\n}\n// =====================================================================\nclass Matrix;\nMatrix column_vector(const vector &vec);\nMatrix row_vector(const vector &vec);\nMatrix identityMatrix(const size_t &N);\nMatrix diagonalMatrix(const vector &vec);\n\nclass Matrix { // Matrix A_mXn\n\tfriend Matrix operator+(const double &lhs, const Matrix &rhs); \n\tfriend Matrix operator-(const double &lhs, const Matrix &rhs);\n\tfriend Matrix operator*(const double &lhs, const Matrix &rhs); \n\tfriend Matrix operator/(const double &lhs, const Matrix &rhs);\n\tfriend ostream& operator<<(ostream &os, const Matrix& M);\n protected:\n\tvector elements;\n\tvoid badConvergence(const string &str) const;\n\tvoid invalidArgument(const int &errid, const string &str) const;\n\tvoid checkDim(const size_t &i_, const string &str = \"\") const;\n\tvoid checkDim(const size_t &i_, const size_t &j_, \n\t\tconst string &str = \"\") const;\n\tvoid checkSize(const size_t &i_, const size_t &j_, \n\t\tconst string &str = \"\") const;\n\tvoid ensureSquare(const string &str = \"\") const;\n\tvoid ensureSameSize(const Matrix &B, const string &str = \"\") const;\n\tvoid ensureNonSingularity(const string &str = \"\") const;\n\tvoid ensureVector(const string &str) const;\n public:\n\tsize_t m; // number of rows of the matrix\n\tsize_t n; // number of columns of the matrix\n\tMatrix(); //constructor\n Matrix(const size_t &m_, const size_t &n_, const double &cns = 0.);\n Matrix(const size_t &m_, const size_t &n_, const double *elem, \n\t\tconst size_t &sz_elem);\n\tMatrix(const size_t &m_, const size_t &n_, \n\t\tconst vector &elem);\n void swap(Matrix &);\n ~Matrix() {};//destructor\n void print() const;\n string str() const;\n double& at(const size_t &i_);\n const double& at(const size_t &i_) const;\n double& at(const size_t &i_, const size_t &j_);\n const double& at(const size_t &i_, const size_t &j_) const;\n vector as_vector() const;\n vector row(const size_t &r_) const;\n void assign2row(const size_t &r_, const double &value);\n void assign2row(const size_t &r_, const vector &values);\n void assign2row(const size_t &r_, const double *values, \n\t\tconst size_t &sz);\n vector column(const size_t &c_) const;\n void assign2column(const size_t &c_, const double &value);\n void assign2column(const size_t &c_, const vector &values);\n void assign2column(const size_t &c_, const double *values, \n\t\tconst size_t &sz);\n vector diagonal() const;\n void assign2diagonal(const double &value);\n void assign2diagonal(const vector &values);\n void assign2diagonal(const double *values, const size_t &sz);\n\tvoid swap_rows(const size_t &r1, const size_t &r2);\n\tvoid swap_columns(const size_t &c1, const size_t &c2);\n\n void self_concat_row(const double &cte);\n void self_concat_row(const vector &values);\n\tvoid self_concat_row(const Matrix &B);\n\tvoid self_concat_column(const double &cte);\n\tvoid self_concat_column(const vector &values);\n\tvoid self_concat_column(const Matrix &B);\n\tvoid self_delete_row(const size_t &r_);\n\tvoid self_delete_column(const size_t &c_);\n\t\n\tMatrix concat_row(const double &cte) const;\n Matrix concat_row(const vector &values) const;\n\tMatrix concat_row(const Matrix &B) const;\n\tMatrix concat_column(const double &cte) const;\n\tMatrix concat_column(const vector &values) const;\n\tMatrix concat_column(const Matrix &B) const;\n\tMatrix delete_row(const size_t &r_) const;\n\tMatrix delete_column(const size_t &c_) const;\n\n\tsize_t rank() const;\n\tdouble determinant() const;\n\tdouble trace() const;\n\tdouble norm() const;\n\tdouble infinity_norm() const;\n\tdouble frobenius_norm() const;\n\tdouble condition_number() const;\n\tdouble cofactor(const size_t &r_, const size_t &c_) const;\n\tdouble highest_eigenvalue() const;\n Matrix transpose() const;\n Matrix adjoint() const;\n Matrix inverse() const;\n brace eigen() const;\n triplet lu_p_factorization() const;\n brace qr_factorization() const;\n brace lq_factorization() const;\n triplet svd() const;\n Matrix pseudoinverse() const;\n \n Matrix operator+(const double &value) const;\n void operator+=(const double &value);\n Matrix operator-(const double &value) const;\n void operator-=(const double &value);\n Matrix operator*(const double &value) const;\n void operator*=(const double &value);\n Matrix operator/(const double &value) const;\n void operator/=(const double &value);\n Matrix operator+(const Matrix &value) const;\n void operator+=(const Matrix &value);\n Matrix operator-(const Matrix &value) const;\n void operator-=(const Matrix &value);\n Matrix operator*(const Matrix &value) const;\n void operator*=(const Matrix &value);\n bool operator==(const Matrix &B) const;\n bool operator!=(const Matrix &B) const;\n \n double min_all(const bool &absolute) const;\n double max_all(const bool &absolute) const;\n \n bool isFullRank() const;\n bool isOrthogonal() const;\n bool isDiagonal() const;\n bool isPositiveDefinite() const;\n bool isSingular() const;\n bool isSymmetric() const;\n bool isSkewSymmetric() const;\n bool isValid() const;\n \n void adjust_elements(const double &tol);\n \n void saveAs(const string &namefile) const;\n};\n\nMatrix::Matrix() : m(0), n(0) {\n}\n\nMatrix::Matrix(const size_t &m_, const size_t &n_, const double &cns) :\n\t\tm(m_), n(n_) {\n\tthis->elements.assign(m*n,cns);\n}\n\nMatrix::Matrix(const size_t &m_, const size_t &n_, const double *elem, \n\t\tconst size_t &sz_elem) : m(m_), n(n_) {\n\tthis->checkSize(this->m*this->n, sz_elem,\"(CONSTRUCTOR)\");\n\tthis->elements.assign(elem, elem+sz_elem);\n}\n\nMatrix::Matrix(const size_t &m_, const size_t &n_, const vector \n\t\t&elem) : m(m_), n(n_) {\n\tthis->checkSize(this->m*this->n, elem.size(),\"(CONSTRUCTOR)\");\n\tthis->elements = elem;\n}\n\nvoid Matrix::swap(Matrix &other) {\n // need to swap all data members\n std::swap(this->elements, other.elements);\n std::swap(this->m, other.m);\n std::swap(this->n, other.n);\n}\n// =====================================================================\nvoid Matrix::badConvergence(const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"the algorithm failed to converge.\";\n\tthrow std::runtime_error(MSG.c_str());\n}\n\nvoid Matrix::invalidArgument(const int &errid, const string &str) \n\t\tconst {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"invalid argument\";\n\tcerr << \"[ \" << errid << \" ] \";\n\tthrow std::invalid_argument(MSG.c_str());\n}\n\nvoid Matrix::checkDim(const size_t &i_, const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"index exceeds matrix dimension\";\n\tif(i_ >= this->elements.size()) \n\t\tthrow std::out_of_range(MSG.c_str());\n}\n\nvoid Matrix::checkDim(const size_t &i_, const size_t &j_, \n\t\tconst string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"index exceeds matrix dimension\";\n\tif(i_ >= this->m || j_ >= this->n) \n\t\tthrow std::out_of_range(MSG.c_str());\n}\n\nvoid Matrix::checkSize(const size_t &i_, const size_t &j_, \n\t\tconst string &str) \tconst {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"sizes of matrices don't match\";\n\tif(i_ != j_) \n\t\tthrow std::invalid_argument(MSG.c_str());\n}\n\nvoid Matrix::ensureSquare(const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"exclusive to square matrices\";\n\tif(this->m != this->n) \n\t\tthrow std::invalid_argument(MSG.c_str());\n}\n\nvoid Matrix::ensureSameSize(const Matrix &B, const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"matrices must be of same size\";\n\tif(this->m != B.m || this->n != B.n) \n\t\tthrow std::invalid_argument(MSG.c_str());\n}\n\nvoid Matrix::ensureNonSingularity(const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"matrix is singular\";\n\tif(this->isSingular()) \n\t\tthrow std::invalid_argument(MSG.c_str());\n}\n\nvoid Matrix::ensureVector(const string &str) const {\n\tstring MSG = (str.empty() ? \"\" : \"in \") + str + \n\t\t(str.empty() ? \"\" : \", \") + \n\t\t\"matrices must be row or column vectors\";\n\tif(this->m != 1 && this->n != 1) \n\t\tthrow std::invalid_argument(MSG.c_str());\n}\n// =====================================================================\nvoid Matrix::print() const {\n\tcout << endl << \">> Matrix_\" << this->m << \"X\" << this->n \n\t\t << \" =\" << endl;\n\tfor(size_t i = 0; i < this->m; i++) {\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tcout << this->elements.at(i*this->n + j) << '\\t';\n\t\tcout << endl;\n\t}\n\tcout << endl;\n}\n\nstring Matrix::str() const {\n\tstring ST = \"\";\n\tfor(size_t i = 0; i < this->m; i++) {\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tST += my::num2str(this->elements.at(i*this->n + j)) \n\t\t\t\t+ ((j == this->n-1) ? '\\0' : '\\t');\n\t\tST += '\\n';\n\t}\n\treturn ST;\n}\n\nostream& operator<<(ostream &os, const Matrix& M) {\n\treturn os << M.str();\n}\n\ndouble& Matrix::at(const size_t &i_) {\n\tthis->checkDim(i_,\"AT\");\n\treturn this->elements.at(i_);\n}\n\nconst double& Matrix::at(const size_t &i_) const {\n\tthis->checkDim(i_,\"AT\");\n\treturn this->elements.at(i_);\n}\n\ndouble& Matrix::at(const size_t &i_, const size_t &j_) {\n\tthis->checkDim(i_,j_,\"AT\");\n\treturn this->elements.at(i_*(this->n)+j_);\n}\n\nconst double& Matrix::at(const size_t &i_, const size_t &j_) const {\n\tthis->checkDim(i_,j_,\"AT\");\n\treturn this->elements.at(i_*(this->n)+j_);\n}\n\nvector Matrix::as_vector() const {\n\treturn this->elements;\n}\n\nvector Matrix::row(const size_t &r_) const {\n\tthis->checkDim(r_,0,\"ROW\");\n\tvector row_(this->elements.begin()+(r_*this->n),\n\t\tthis->elements.begin()+(r_*this->n+this->n));\n\treturn row_;\n}\n\nvoid Matrix::assign2row(const size_t &r_, const double &value) {\n\tthis->checkDim(r_,0,\"ASSIGN2ROW\");\n\tfor(size_t i = 0; i < this->n; i++)\n\t\tthis->elements.at(r_*this->n+i) = value;\n}\n\nvoid Matrix::assign2row(const size_t &r_, \n\t\tconst vector &values) {\n\tthis->checkDim(r_,0,\"ASSIGN2ROW\");\n\tthis->checkSize(this->n,values.size(),\"ASSIGN2ROW\");\n\tfor(size_t i = 0; i < this->n; i++)\n\t\tthis->elements.at(r_*this->n+i) = values.at(i);\n}\n\nvoid Matrix::assign2row(const size_t &r_, const double *values, \n\t\tconst size_t &sz) {\n\tvector vec(values,values+sz);\n\tthis->assign2row(r_,vec);\n}\n\nvector Matrix::column(const size_t &c_) const {\n\tthis->checkDim(0,c_,\"COLUMN\");\n\tvector column_(this->m,0.);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tcolumn_.at(i) = this->elements.at(i*this->n+c_);\n\treturn column_;\n}\n\nvoid Matrix::assign2column(const size_t &c_, const double &value) {\n\tthis->checkDim(0,c_,\"ASSIGN2COLUMN\");\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tthis->elements.at(i*this->n+c_) = value;\n}\n\nvoid Matrix::assign2column(const size_t &c_, \n\t\tconst vector &values) {\n\tthis->checkDim(0,c_,\"ASSIGN2COLUMN\");\n\tthis->checkSize(this->m,values.size(),\"ASSIGN2COLUMN\");\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tthis->elements.at(i*this->n+c_) = values.at(i);\n}\n\nvoid Matrix::assign2column(const size_t &c_, const double *values, \n\t\tconst size_t &sz) {\n\tvector vec(values,values+sz);\n\tthis->assign2column(c_,vec);\n}\n\nvector Matrix::diagonal() const {\n\tsize_t dim = min(this->m,this->n);\n\tvector diag_(dim,0.);\n\tfor(size_t i = 0; i < dim; i++)\n\t\tdiag_.at(i) = this->elements.at(i*this->n+i);\n\treturn diag_;\n}\n\nvoid Matrix::assign2diagonal(const double &value) {\n\tsize_t dim = min(this->m,this->n);\n\tfor(size_t i = 0; i < dim; i++)\n\t\tthis->elements.at(i*this->n+i) = value;\n}\n\nvoid Matrix::assign2diagonal(const vector &values) {\n\tsize_t dim = min(this->m,this->n);\n\tthis->checkSize(dim,values.size(),\"ASSIGN2DIAGONAL\");\n\tfor(size_t i = 0; i < dim; i++)\n\t\tthis->elements.at(i*this->n+i) = values.at(i);\n}\n\nvoid Matrix::assign2diagonal(const double *values, const size_t &sz) {\n\tvector vec(values,values+sz);\n\tthis->assign2diagonal(vec);\n}\n\nvoid Matrix::swap_rows(const size_t &r1, const size_t &r2) {\n\tthis->checkDim(r1,0,\"SWAP_ROW\");\n\tthis->checkDim(r2,0,\"SWAP_ROW\");\n\tdouble aux;\n\tfor(size_t j = 0; j < this->n; j++) {\n\t\taux = this->elements.at(r1*this->n+j);\n\t\tthis->elements.at(r1*this->n+j) = \n\t\t\tthis->elements.at(r2*this->n+j);\n\t\tthis->elements.at(r2*this->n+j) = aux;\n\t}\n}\n\nvoid Matrix::swap_columns(const size_t &c1, const size_t &c2) {\n\tthis->checkDim(0,c1,\"SWAP_COLUMN\");\n\tthis->checkDim(0,c2,\"SWAP_COLUMN\");\n\tdouble aux;\n\tfor(size_t i = 0; i < this->m; i++) {\n\t\taux = this->elements.at(i*this->n+c1);\n\t\tthis->elements.at(i*this->n+c1) = \n\t\t\tthis->elements.at(i*this->n+c2);\n\t\tthis->elements.at(i*this->n+c2) = aux;\n\t}\n}\n\nvoid Matrix::self_concat_row(const double &cte) {\n\tMatrix M(this->concat_row(cte));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_concat_row(const vector &values) {\n\tMatrix M(this->concat_row(values));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_concat_row(const Matrix &B) {\n\tMatrix M(this->concat_row(B));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_concat_column(const double &cte) {\n\tMatrix M(this->concat_column(cte));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_concat_column(const vector &values) {\n\tMatrix M(this->concat_column(values));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_concat_column(const Matrix &B) {\n\tMatrix M(this->concat_column(B));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_delete_row(const size_t &r_) {\n\tMatrix M(this->delete_row(r_));\n\tthis->swap(M);\n}\n\nvoid Matrix::self_delete_column(const size_t &c_) {\n\tMatrix M(this->delete_column(c_));\n\tthis->swap(M);\n}\n\nMatrix Matrix::concat_row(const double &cte) const {\n\tvector values(this->n,cte);\n\treturn concat_row(values);\n}\n\nMatrix Matrix::concat_row(const vector &values) const {\n\tthis->checkSize(this->n,values.size(),\"CONCAT_ROW\");\n\tMatrix M(this->m+1,this->n);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < M.n; j++)\n\t\t\tM.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);\n\tfor(size_t j = 0; j < M.n; j++)\n\t\tM.elements.at(this->m*M.n+j) = values.at(j);\n\treturn M;\n}\n\nMatrix Matrix::concat_row(const Matrix &B) const {\n\tthis->checkSize(this->n,B.n,\"CONCAT_ROW\");\n\tMatrix M(this->m+B.m,this->n);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < M.n; j++)\n\t\t\tM.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);\n\tfor(size_t i = 0; i < B.m; i++)\n\t\tfor(size_t j = 0; j < M.n; j++)\n\t\t\tM.elements.at((this->m+i)*M.n+j) = \n\t\t\t\tB.elements.at(i*B.n+j);\n\treturn M;\n}\n\nMatrix Matrix::concat_column(const double &cte) const {\n\tvector values(this->m,cte);\n\treturn concat_column(values);\n}\n\nMatrix Matrix::concat_column(const vector &values) const {\n\tthis->checkSize(this->m,values.size(),\"CONCAT_COLUMN\");\n\tMatrix M(this->m,this->n+1);\n\tfor(size_t i = 0; i < M.m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tM.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);\n\tfor(size_t i = 0; i < M.m; i++)\n\t\tM.elements.at(i*M.n+this->n) = values.at(i);\n\treturn M;\n}\n\nMatrix Matrix::concat_column(const Matrix &B) const {\n\tthis->checkSize(this->m,B.m,\"CONCAT_COLUMN\");\n\tMatrix M(this->m,this->n+B.n);\n\tfor(size_t i = 0; i < M.m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tM.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);\n\tfor(size_t i = 0; i < M.m; i++)\n\t\tfor(size_t j = 0; j < B.n; j++)\n\t\t\tM.elements.at(i*M.n+(this->n+j)) = B.elements.at(i*B.n+j);\n\treturn M;\n}\n\nMatrix Matrix::delete_row(const size_t &r_) const {\n\tthis->checkDim(r_,0,\"DELETE_ROW\");\n\tMatrix M(this->m-1,this->n);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tif(i != r_)\n\t\t\t\tM.elements.at(((ielements.at(i*this->n+j);\n\treturn M;\n}\n\nMatrix Matrix::delete_column(const size_t &c_) const {\n\tthis->checkDim(0,c_,\"DELETE_COLUMN\");\n\tMatrix M(this->m,this->n-1);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tif(j != c_)\n\t\t\t\tM.elements.at(i*M.n+((jelements.at(i*this->n+j);\n\treturn M;\n}\n// ===================================\nsize_t Matrix::rank() const {\n\tsize_t rk = 0;\n\tthis->checkSize((this->m)*(this->n),this->elements.size(),\"RANK\");\n\tlapack_int m = this->m, n = this->n;\n\tlapack_int lda = n, ldu = m, ldvt = n, info;\n\tdouble *superb = new double[min(m,n)-1];\n\tdouble *a = new double[m*n],\n\t\t *s = new double[min(m,n)], \n\t\t *u = new double[m*m], \n\t\t *vt = new double[n*n];\n\tfor(size_t i = 0; i < this->elements.size(); i ++)\n\t\ta[i] = this->elements.at(i);\n\tinfo = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'N', 'N', m, n, a, lda,\n\t\ts, u, ldu, vt, ldvt, superb );\n if(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"RANK\");\n\tif(info > 0) \t// Check for convergence\n\t\tthis->badConvergence(\"RANK\");\n\tfor(int i = 0; i < min(m,n); i++)\n\t\trk += (my::isLikelyZero(s[i],max(this->m,this->n))) ? 0 : 1;\n\tdelete [] superb;\n\tdelete [] a;\n\tdelete [] s;\n\tdelete [] u;\n\tdelete [] vt;\n\treturn rk;\n}\n\ndouble Matrix::determinant() const {\n\tthis->ensureSquare(\"DETERMINANT\");\n\tdouble det;\n\tswitch(this->m) {\n\t\tcase 1:\n\t\t\tdet = this->elements.at(0);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tdet = this->elements.at(0)*this->elements.at(3) -\n\t\t\t\tthis->elements.at(1)*this->elements.at(2);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tdet = this->elements.at(0)*this->elements.at(4)*\n\t\t\t\t\tthis->elements.at(8) \n\t\t\t\t+ this->elements.at(1)*this->elements.at(5)*\n\t\t\t\t\tthis->elements.at(6) \n\t\t\t\t+ this->elements.at(2)*this->elements.at(3)*\n\t\t\t\t\tthis->elements.at(7) \n\t\t\t\t- this->elements.at(2)*this->elements.at(4)*\n\t\t\t\t\tthis->elements.at(6)\n\t\t\t\t- this->elements.at(0)*this->elements.at(5)*\n\t\t\t\t\tthis->elements.at(7)\n\t\t\t\t- this->elements.at(1)*this->elements.at(3)*\n\t\t\t\t\tthis->elements.at(8);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdet = 0;\n\t\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\t\tdet += this->cofactor(0,j)*this->elements.at(j); // i=0 \n\t}\n\treturn det;\n}\n\ndouble Matrix::trace() const {\n\tthis->ensureSquare(\"TRACE\");\n\tvector diag(this->diagonal());\n\tdouble total(0.);\n\tfor(vector::iterator it = diag.begin(); \n\t\tit < diag.end(); it++) total += *it;\n\treturn total;\n}\n\ndouble Matrix::norm() const {\n\t// for square matrices, this is the same as the \"spectral norm\",\n\t// the \"induced matrix 2-norm\" or the \"Euclidean norm\"\n\tif(this->m != 1 && this->n != 1) {\n\t\tthis->checkSize((this->m)*(this->n),this->elements.size(),\n\t\t\t\"NORM\");\n\t\tlapack_int m = this->m, n = this->n;\n\t\tlapack_int lda = n, ldu = m, ldvt = n, info;\n\t\tdouble *superb = new double[min(m,n)-1];\n\t\tdouble *a = new double[m*n],\n\t\t\t *s = new double[min(m,n)], \n\t\t\t *u = new double[m*m], \n\t\t\t *vt = new double[n*n];\n\t\tfor(size_t i = 0; i < this->elements.size(); i ++)\n\t\t\ta[i] = this->elements.at(i);\n\t\tinfo = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'N', 'N', m, n, a, lda,\n\t\t\ts, u, ldu, vt, ldvt, superb );\n\t\tif(info < 0) \t// Check for invalid (NaN)\n\t\t\tthis->invalidArgument((int)info,\"NORM\");\n\t\tif(info > 0) \t// Check for convergence\n\t\t\tthis->badConvergence(\"NORM\");\n\t\tdouble hSingVal = s[0];\n\t\tfor(int i = 1; i < min(m,n); i++)\n\t\t\tif(s[i] > hSingVal)\n\t\t\t\thSingVal = s[i];\n\t\tdelete [] superb;\n\t\tdelete [] a;\n\t\tdelete [] s;\n\t\tdelete [] u;\n\t\tdelete [] vt;\n\t\treturn hSingVal;\n\t} else\n\t\treturn sqrt(((this->m == 1) ? (*this)*(this->transpose()) :\n\t\t\t(this->transpose())*(*this)).elements.at(0));\n}\n\ndouble Matrix::infinity_norm() const {\n\t// Maximum absolute row sum norm\n\tdouble infnorm = 0., sum_;\n\tfor(size_t i = 0; i < this->m; i++) {\n\t\tsum_ = 0.;\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tsum_ += abs(this->elements.at(i*this->n+j));\n\t\tif(sum_ > infnorm)\n\t\t\tinfnorm = sum_;\n\t}\n\treturn infnorm;\n}\n\ndouble Matrix::frobenius_norm() const {\n\tthis->checkSize((this->m)*(this->n),this->elements.size(),\n\t\t\"FRBNORM\");\n\tdouble sum = 0.;\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tsum += pow(this->elements.at(i*this->n+j),2.);\n\treturn sqrt(sum);\n}\n\ndouble Matrix::condition_number() const\n{\n\ttriplet SVD = this->svd();\n\tvector singular_values = SVD.second.diagonal();\n\treturn my::max(singular_values)/my::min(singular_values);\n}\ndouble Matrix::cofactor(const size_t &r_, const size_t &c_) const {\n\tthis->ensureSquare(\"COFACTOR\");\n\tMatrix CF(*this);\n\tCF.self_delete_row(r_);\n\tCF.self_delete_column(c_);\n\treturn (((r_+c_)%2)?-1:1)*CF.determinant();\n}\n\nMatrix Matrix::transpose() const {\n\tMatrix T(this->n,this->m);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tT.elements.at(j*this->m+i) = this->elements.at(i*this->n+j);\n\treturn T;\n}\n\nMatrix Matrix::adjoint() const {\n\tthis->ensureSquare(\"ADJOINT\");\n\tMatrix A(this->m,this->n);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tA.elements.at(i*this->n+j) = cofactor(i,j);\n\treturn A.transpose();\n}\n\nMatrix Matrix::inverse() const {\n\tthis->ensureSquare(\"INVERSE\");\n\tthis->ensureNonSingularity(\"INVERSE\");\n\treturn this->adjoint()/this->determinant();\n}\n\nbrace Matrix::eigen() const {\n\tthis->checkSize((this->n)*(this->n),this->elements.size(),\"EIGEN\");\n\tthis->ensureSquare(\"EIGEN\");\n\tlapack_int n = this->n, info;\n\tdouble *a = new double[n*n],\n\t\t *b = new double[n*n],\n\t\t *alphar = new double[n],\n\t\t *alphai = new double[n],\n\t\t *beta = new double[n],\n\t\t *vl = new double,\n\t\t *vr = new double[n*n];\n\tfor(size_t i = 0; i < this->elements.size(); i ++) {\n\t\ta[i] = this->elements.at(i);\n\t\tb[i] = (i%(n+1) == 0) ? 1. : 0.;\n\t}\n\tinfo = LAPACKE_dggev( LAPACK_ROW_MAJOR, 'N', 'V', n, a, n, b, n, \n\t\talphar, alphai, beta, vl, 1, vr, n );\n\tif(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"EIGEN\");\n\tif(info > 0) \t// Check for convergence\n\t\tthis->badConvergence(\"EIGEN\");\n\tMatrix EVAL(n,n),\n\t\t EVEC(n,n,vr,n*n);\n\tvector lambda(n,0.);\n\tfor(int i = 0; i < n; i++) {\n\t\tlambda.at(i) = (abs(alphai[i]) <= EPS) ? ((abs(beta[i]) <= EPS) \n\t\t\t? NAN : alphar[i]/beta[i] ) : -NAN;\n\t}\n\tEVAL.assign2diagonal(lambda);\n\tdelete [] a;\n\tdelete [] b;\n\tdelete [] alphar;\n\tdelete [] alphai;\n\tdelete [] beta;\n\tdelete vl;\n\tdelete [] vr;\n\treturn make_brace(EVAL,EVEC);\n}\n\ntriplet Matrix::lu_p_factorization() const {\n\tlapack_int m = this->m, n = this->n, info;\n\tdouble *a = new double[m*n];\n\tlapack_int *ipiv = new lapack_int[max(1,min(m,n))];\n\tfor(size_t i = 0; i < this->elements.size(); i ++) {\n\t\ta[i] = this->elements.at(i);\n\t}\n\tinfo = LAPACKE_dgetrf( LAPACK_ROW_MAJOR, m, n, a, n, ipiv );\n\tif(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"LU_P_FACTORIZATION\");\n\tif(info > 0) \t// Check for convergence\n\t\tcerr << \">> Warning! Matrix U is singular.\" << endl;\n\tMatrix L(m,min(m,n)), \n\t\t U(min(m,n),n), \n\t\t P(m,m);\n\tvector ones(min(m,n),1.);\n\tL.assign2diagonal(ones);\n\tfor(int i = 0; i < m; i++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tif(j >= i)\n\t\t\t\tU.at(i,j) = a[i*n+j];\n\t\t\telse\n\t\t\t\tL.at(i,j) = a[i*n+j];\n\tvector seq;\n\tsize_t aux;\n\tfor(int i = 0; i < m; i++)\n\t\tseq.push_back(i);\n\tfor(int i = 0; i < min(m,n); i++) {\n\t\taux = seq.at(i);\n\t\tseq.at(i) = seq.at(ipiv[i]-1);\n\t\tseq.at(ipiv[i]-1) = aux;\n\t}\n\tfor(int i = 0; i < m; i++)\n\t\tP.at(i,seq.at(i)) = 1;\n\tdelete [] a;\n\tdelete [] ipiv;\n\treturn make_triplet(L,U,P);\n}\n\nbrace Matrix::qr_factorization() const {\n\tlapack_int m = this->m, n = this->n, info;\n\tdouble *a = new double[m*n];\n\tdouble *tau = new double[max(1,min(m,n))];\n\tfor(size_t i = 0; i < this->elements.size(); i ++) {\n\t\ta[i] = this->elements.at(i);\n\t}\n info = LAPACKE_dgeqrf( LAPACK_ROW_MAJOR, m, n, a, n, tau );\n\tif(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"QR_FACTORIZATION\");\n\t/* The matrix Q is represented as a product of elementary reflectors\n\t*\n\t* Q = H(1) H(2) . . . H(k), where k = min(m,n).\n\t*\n\t* Each H(i) has the form\n\t*\n\t* H(i) = I - tau * v * v'\n\t*\n\t* where tau is a real scalar, and v is a real vector with\n\t* v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in \n\t* A(i+1:m,i), and tau in TAU(i).*/\t\n\tMatrix Q(m,min(m,n)), \n\t\t R(min(m,n),n), \n\t\t H(identityMatrix(m)),\n\t\t v(m,1);\n\tvector ones(min(m,n),1.);\n\tQ.assign2diagonal(ones);\n\tfor(int i = 0; i < m; i++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tif(j >= i)\n\t\t\t\tR.at(i,j) = a[i*n+j];\n\t\t\telse\n\t\t\t\tQ.at(i,j) = a[i*n+j];\n\tfor(int i = 0; i < min(m,n); i++) {\n\t\tv = column_vector(Q.column(i));\n\t\tH *= identityMatrix(m)-(v*v.transpose())*tau[i];\n\t}\n\tQ = H;\n\tif(m > n)\n\t\tfor(int i = n; i < m; i++)\n\t\t\tQ.self_delete_column(Q.n-1);\n\tdelete [] a;\n\tdelete [] tau;\n\treturn make_brace(Q,R);\n}\n\nbrace Matrix::lq_factorization() const {\n\tlapack_int m = this->m, n = this->n, info;\n\tdouble *a = new double[m*n];\n\tdouble *tau = new double[max(1,min(m,n))];\n\tfor(size_t i = 0; i < this->elements.size(); i ++) {\n\t\ta[i] = this->elements.at(i);\n\t}\n info = LAPACKE_dgelqf( LAPACK_ROW_MAJOR, m, n, a, n, tau );\n\tif(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"LQ_FACTORIZATION\");\n\tMatrix L(m,min(m,n)), \n\t\t Q(min(m,n),n), \n\t\t H(identityMatrix(n)),\n\t\t v(n,1);\n\tvector ones(min(m,n),1.);\n\tQ.assign2diagonal(ones);\n\tfor(int i = 0; i < m; i++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tif(j <= i)\n\t\t\t\tL.at(i,j) = a[i*n+j];\n\t\t\telse\n\t\t\t\tQ.at(i,j) = a[i*n+j];\n\tfor(int i = 0; i < min(m,n); i++) {\n\t\tv = row_vector(Q.row(i));\n\t\tH *= identityMatrix(n)-(v.transpose()*v)*tau[i];\n\t}\n\tQ = H.transpose();\n\tif(m < n)\n\t\tfor(int i = m; i < n; i++)\n\t\t\tQ.self_delete_row(Q.m-1);\n\tdelete [] a;\n\tdelete [] tau;\n\treturn make_brace(L,Q);\n}\n\ntriplet Matrix::svd() const {\n\tthis->checkSize((this->m)*(this->n),this->elements.size(),\"SVD\");\n\tlapack_int m = this->m, n = this->n;\n\tlapack_int lda = n, ldu = m, ldvt = n, info;\n\tdouble *superb = new double[min(m,n)-1];\n\tdouble *a = new double[m*n],\n\t\t *s = new double[min(m,n)], \n\t\t *u = new double[m*m], \n\t\t *vt = new double[n*n];\n\tfor(size_t i = 0; i < this->elements.size(); i ++)\n\t\ta[i] = this->elements.at(i);\n\tinfo = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'A', 'A', m, n, a, lda,\n\t\ts, u, ldu, vt, ldvt, superb );\n if(info < 0) \t// Check for invalid (NaN)\n\t\tthis->invalidArgument((int)info,\"SVD\");\n\tif(info > 0) \t// Check for convergence\n\t\tthis->badConvergence(\"SVD\");\n\t// Adjust zeros\n\tfor(size_t i = 0; i < min(this->m,this->n); i++)\n\t\tif(my::isLikelyZero(s[i],max(this->m,this->n)))\n\t\t\ts[i] = 0.;\n\tfor(int i = 0; i < m*m; i++)\n\t\tif(my::isLikelyZero(u[i],max(this->m,this->n)))\n\t\t\tu[i] = 0.;\n\tfor(int i = 0; i < n*n; i++)\n\t\tif(my::isLikelyZero(vt[i],max(this->m,this->n)))\n\t\t\tvt[i] = 0.;\n\t// Create matrices\n\tMatrix S(m,n),\n\t\t U(m,m,u,m*m),\n\t\t VT(n,n,vt,n*n);\n\tS.assign2diagonal(s,min(m,n));\n\tdelete [] superb;\n\tdelete [] a;\n\tdelete [] s;\n\tdelete [] u;\n\tdelete [] vt;\n\t// Return matrices U, Sigma and V\n\t// To retrieve original matrix: U*Sigma*V.transpose()\n\treturn make_triplet(U,S,VT.transpose());\n}\n\nMatrix Matrix::pseudoinverse() const {\n\ttriplet SVD = this->svd();\n\tvector sv = SVD.second.diagonal();\n\tdouble maxsv = 0;\n\tfor(size_t i = 0; i < sv.size(); i++)\n\t\tif(maxsv < sv.at(i))\n\t\t\tmaxsv = sv.at(i);\n\tfor(size_t i = 0; i < sv.size(); i++) {\n\t\tif(sv.at(i) <= this->m*this->n*EPS)\n\t\t\tsv.at(i) = 0.;\n\t\telse\n\t\t\tsv.at(i) = 1./sv.at(i);\n\t}\n\tSVD.second.assign2diagonal(sv);\n\treturn (SVD.first*SVD.second*SVD.third.transpose()).transpose();\n}\n// =========\ndouble Matrix::min_all(const bool &absolute) const\n{\n\tdouble minelem = (absolute)? abs(this->elements.front()) : \n\t\tthis->elements.front();\n\tfor(size_t i = 1; i < this->elements.size(); i++)\n\t\tif((absolute)? abs(this->elements.at(i)) < minelem : \n\t\t\tthis->elements.at(i) < minelem)\n\t\t\t\tminelem = (absolute)? abs(this->elements.at(i)) : \n\t\t\t\t\tthis->elements.at(i);\n\treturn minelem;\n}\ndouble Matrix::max_all(const bool &absolute) const\n{\n\tdouble maxelem = (absolute)? abs(this->elements.front()) : \n\t\tthis->elements.front();\n\tfor(size_t i = 1; i < this->elements.size(); i++)\n\t\tif((absolute)? abs(this->elements.at(i)) > maxelem : \n\t\t\tthis->elements.at(i) > maxelem)\n\t\t\t\tmaxelem = (absolute)? abs(this->elements.at(i)) : \n\t\t\t\t\tthis->elements.at(i);\n\treturn maxelem;\n}\n// =========\nMatrix Matrix::operator+(const double &value) const {\n\tMatrix A(*this);\n\tA += value;\n\treturn A;\n}\n\nvoid Matrix::operator+=(const double &value) {\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) += value;\n}\n\nMatrix Matrix::operator-(const double &value) const {\n\tMatrix A(*this);\n\tA -= value;\n\treturn A;\n}\n\nvoid Matrix::operator-=(const double &value) {\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) -= value;\n}\n\nMatrix Matrix::operator*(const double &value) const {\n\tMatrix A(*this);\n\tA *= value;\n\treturn A;\n}\n\nvoid Matrix::operator*=(const double &value) {\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) *= value;\n}\n\nMatrix Matrix::operator/(const double &value) const {\n\tMatrix A(*this);\n\tA /= value;\n\treturn A;\n}\n\nvoid Matrix::operator/=(const double &value) {\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) /= value;\n}\n\nMatrix Matrix::operator+(const Matrix &B) const {\n\tMatrix A(*this);\n\tA += B;\n\treturn A;\n}\n\nvoid Matrix::operator+=(const Matrix &B) {\n\tthis->ensureSameSize(B,\"OPERATOR+\");\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) += B.elements.\n\t\t\t\tat(i*this->n+j);\n}\n\nMatrix Matrix::operator-(const Matrix &B) const {\n\tMatrix A(*this);\n\tA -= B;\n\treturn A;\n}\n\nvoid Matrix::operator-=(const Matrix &B) {\n\tthis->ensureSameSize(B,\"OPERATOR-\");\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tthis->elements.at(i*this->n+j) -= B.elements.\n\t\t\t\tat(i*this->n+j);\n}\n\nMatrix Matrix::operator*(const Matrix &B) const {\n\tthis->checkSize(this->n,B.m,\"OPERATOR*\");\n\tMatrix R(this->m,B.n);\n\tfor(size_t i = 0; i < this->m; i++)\n\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\tfor(size_t k = 0; k < B.n; k++) {\n\t\t\t\tR.elements.at(i*B.n+k) += this->elements.\n\t\t\t\t\tat(i*this->n+j)*B.elements.at(j*B.n+k);\n\t\t\t\tif(abs(R.elements.at(i*B.n+k)) <= this->m*EPS) \n\t\t\t\t\tR.elements.at(i*B.n+k) = 0.;\n\t\t\t}\n\treturn R;\n}\n\nvoid Matrix::operator*=(const Matrix &B) {\n\tMatrix A = (*this)*B;\n\tthis->swap(A);\n}\n\nbool Matrix::operator==(const Matrix &B) const {\n\tif(this->m != B.m || this->n != B.n)\n\t\treturn false;\n\telse {\n\t\tbool chk = true;\n\t\tfor(size_t i = 0; i < this->m; i++) {\n\t\t\tfor(size_t j = 0; j < this->n; j++) {\n\t\t\t\tif(abs(this->elements.at(i*this->n+j)-\n\t\t\t\t\t\tB.elements.at(i*B.n+j)) > 0.5*EPS) {\n\t\t\t\t\tchk = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!chk) break;\n\t\t}\n\t\treturn chk;\n\t}\n}\n\nbool Matrix::operator!=(const Matrix &B) const {\n\treturn !((*this) == B);\n}\n// ======\nMatrix operator+(const double &lhs, const Matrix &rhs) {\n\treturn rhs+lhs;\n}\nMatrix operator-(const double &lhs, const Matrix &rhs) {\n\treturn rhs*(-1.)+lhs;\n}\nMatrix operator*(const double &lhs, const Matrix &rhs) {\n\treturn rhs*lhs;\n}\nMatrix operator/(const double &lhs, const Matrix &rhs) {\n\t// This is not an inverse! It's an element-wise division\n\tMatrix result(rhs);\n\tfor(size_t i = 0; i < result.m; i++)\n\t\tfor(size_t j = 0; j < result.n; j++)\n\t\t\tresult.at(i,j) = lhs/result.at(i,j);\n\treturn result;\n}\n// ======\nbool Matrix::isFullRank() const {\n\treturn this->rank() == min(this->m,this->n);\n}\n\nbool Matrix::isOrthogonal() const {\n\tMatrix O = (*this)*(this->transpose());\n\treturn (O == identityMatrix(O.m));\n}\n\nbool Matrix::isDiagonal() const {\n\tMatrix D = diagonalMatrix(this->diagonal());\n\tif(this->m != this->n) {\n\t\tif(this->m > this->n) {\n\t\t\tvector zeros(this->n,0.);\n\t\t\tfor(size_t i = this->n; i < this->m; i++)\n\t\t\t\tD.self_concat_row(zeros);\n\t\t} else {\n\t\t\tvector zeros(this->m,0.);\n\t\t\tfor(size_t i = this->m; i < this->n; i++)\n\t\t\t\tD.self_concat_column(zeros);\n\t\t}\n\t}\n\treturn (*this == D);\n}\n\nbool Matrix::isPositiveDefinite() const {\n\t//real symmetric matrix\n\tif(!(this->isSymmetric()))\n\t\treturn false;\n\telse {\n\t\t// if all its eigenvalues are positive.\n\t\tcout << \"not implemented yet!\" << endl;\n\t\treturn false;\n\t}\n}\n\nbool Matrix::isSingular() const {\n\treturn (my::isLikelyZero(this->determinant()));\n}\n\nbool Matrix::isSymmetric() const {\n\treturn (*this == this->transpose());\n}\n\nbool Matrix::isSkewSymmetric() const {\n\treturn (*this == this->transpose()*(-1.));\n}\n\nbool Matrix::isValid() const {\n\tbool chk = true;\n\tfor(vector::const_iterator it = this->elements.begin();\n\t\tit != this->elements.end(); it++)\n\t{\n\t\tif(std::isnan(*it) || my::isinf(*it))\n\t\t{\n\t\t\tchk = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn chk;\n}\n\nvoid Matrix::adjust_elements(const double &tol)\n{\n\tfor(size_t i = 0; i < this->elements.size(); i++)\n\t\tif(my::isLikelyZero(this->elements.at(i),this->m*this->n) || \n\t\t\t\tabs(this->elements.at(i)) < tol) \n\t\t\tthis->elements.at(i) = 0.;\n}\n\nvoid Matrix::saveAs(const string &namefile) const\n{\n\tofstream matrixfile;\n\tmatrixfile.open(namefile);\n\tif (matrixfile.is_open())\n\t{\n\t\tfor(size_t i = 0; i < this->m; i++)\n\t\t{\n\t\t\tfor(size_t j = 0; j < this->n; j++)\n\t\t\t\tmatrixfile << this->elements.at(i*(this->n)+j) \n\t\t\t\t\t\t << ((j+1 == this->n) ? \"\" : \"\\t\");\n\t\t\tmatrixfile << endl;\n\t\t}\n\t}\n\telse\n\t{\n\t\tcerr << \"Unable to open \" << namefile << \" file!\" << endl;\n\t}\n\tmatrixfile.close();\n}\n// =====================================================================\nMatrix column_vector(const vector &vec) {\n\tMatrix A(vec.size(),1,vec);\n\treturn A;\n}\n\nMatrix column_vector(const size_t &qty, const double &val) {\n\tvector vec(qty,val);\n\tMatrix A(qty,1,vec);\n\treturn A;\n}\n\nMatrix row_vector(const vector &vec) {\n\tMatrix A(1,vec.size(),vec);\n\treturn A;\n}\n\nMatrix row_vector(const size_t &qty, const double &val) {\n\tvector vec(qty,val);\n\tMatrix A(1,qty,vec);\n\treturn A;\n}\n\nMatrix subMatrix(const Matrix &M, const size_t &fstr, \n\t\tconst size_t &fstc, const size_t &lstr, const size_t &lstc) {\n\tcout << \"row: \" << fstr << \" \" << lstr << endl;\n\tcout << \"col: \" << fstc << \" \" << lstc << endl;\n\tcout << \"M: \" << M.m << \" \" << M.n << endl;\n\tif(fstr > lstr || lstr >= M.m || fstc > lstc || lstc >= M.n) {\n\t\tstring MSG = \"in SUBMATRIX, index exceeds matrix dimension\";\n\t\tthrow std::out_of_range(MSG.c_str());\n\t}\n\tMatrix A(lstr-fstr+1,lstc-fstc+1);\n\tcout << A.m << \" \" << A.n << endl;\n\tfor(size_t i = 0; i < A.m; i++)\n\t\tfor(size_t j = 0; j < A.n; j++)\n\t\t\tA.at(i,j) = M.at(i+fstr,j+fstc);\n\treturn A;\n}\n\nMatrix identityMatrix(const size_t &N) {\n\tMatrix A(N,N);\n\tA.assign2diagonal(1.);\n\treturn A;\n}\n\nMatrix diagonalMatrix(const vector &vec) {\n\tMatrix A(vec.size(),vec.size());\n\tA.assign2diagonal(vec);\n\treturn A;\n}\n\nMatrix linear_AASTtoRowVector_VAR(const AAST &tree, const size_t &n_var) \n{\n\tMatrix A, b(n_var, 1);\n\tvector aux(n_var, 0.);\n\tdouble cnst = tree.eval_with_variables(aux);\n\taux.at(0) = 1.;\n\tA = row_vector(aux);\n\tb.at(0) = tree.eval_with_variables(aux) - cnst;\n\tfor(size_t i = 1; i < n_var; i++)\n\t{\n\t\taux.assign(n_var, 0.);\n\t\taux.at(i) = 1.;\n\t\tA.self_concat_row(row_vector(aux));\n\t\tb.at(i) = tree.eval_with_variables(aux) - cnst;\n\t}\n\treturn ((A.pseudoinverse()*b).transpose()).concat_column(cnst);\n}\n\nMatrix linear_AASTtoRowVector_UNK(const AAST &tree, const size_t &n_unk) \n{\n\tMatrix A, b(n_unk, 1);\n\tvector aux(n_unk, 0.);\n\tdouble cnst = tree.eval_with_unknowns(aux);\n\taux.at(0) = 1.;\n\tA = row_vector(aux);\n\tb.at(0) = tree.eval_with_unknowns(aux) - cnst;\n\tfor(size_t i = 1; i < n_unk; i++)\n\t{\n\t\taux.assign(n_unk, 0.);\n\t\taux.at(i) = 1.;\n\t\tA.self_concat_row(row_vector(aux));\n\t\tb.at(i) = tree.eval_with_unknowns(aux) - cnst;\n\t}\n\treturn ((A.pseudoinverse()*b).transpose()).concat_column(cnst);\n}\n// =====================================================================\n#endif\n", "meta": {"hexsha": "6e39a15043b1c4db644bb6621f8d601960348d59", "size": 36548, "ext": "h", "lang": "C", "max_stars_repo_path": "cMatrix.h", "max_stars_repo_name": "iperetta/system-modelling", "max_stars_repo_head_hexsha": "e99c12019c7b8730ab478e5ca5c956fca36371ee", "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": "cMatrix.h", "max_issues_repo_name": "iperetta/system-modelling", "max_issues_repo_head_hexsha": "e99c12019c7b8730ab478e5ca5c956fca36371ee", "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": "cMatrix.h", "max_forks_repo_name": "iperetta/system-modelling", "max_forks_repo_head_hexsha": "e99c12019c7b8730ab478e5ca5c956fca36371ee", "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.6650980392, "max_line_length": 73, "alphanum_fraction": 0.6131388858, "num_tokens": 11383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6926119370320306}} {"text": "static char help[] =\n\"Simple ODE system to test implicit and IMEX methods when *both* RHSFunction()\\n\"\n\"and IFunction() are supplied. Jacobians are supplied as well. The problem\\n\"\n\"has form\\n\"\n\" F(t,u,dudt) = G(t,u)\\n\"\n\"where u(t) = (x(t),y(t)) and dF/d(dudt) is invertible, so the problem is a\\n\"\n\"2D ODE IVP. Functions F (IFunction) and G (RHSFunction) are actually linear,\\n\"\n\"but the ProblemType is set to TS_NONLINEAR type. By default the system is\\n\"\n\" x' + y' + x + 2y = x + 8y\\n\"\n\" y' + 3x + 4y = 4x + 4y\\n\"\n\"The implicit methods like BEULER, THETA, CN, BDF should be able to handle\\n\"\n\"this system. Apparently ROSW can also handle it. However, ARKIMEX and EIMEX\\n\"\n\"require dF/d(dudt) to be the identity. (But consider option\\n\"\n\"-ts_arkimex_fully_implicit.) If option -identity_in_F is given then an\\n\"\n\"equivalent system is formed,\\n\"\n\" x' + x + 2y = 8y\\n\"\n\" y' + 3x + 4y = 4x + 4y\\n\"\n\"Both of these systems are trivial transformations of the system\\n\"\n\"x'=6y-x, y'=x. With the initial conditions chosen below, x(0)=1 and y(0)=3,\\n\"\n\"the exact solution to the above systems is x(t) = -3 e^{-3t} + 4 e^{2t},\\n\"\n\"y(t) = e^{-3t} + 2 e^{2t}, and we compute the final numerical error\\n\"\n\"accordingly. Default type is BDF. See the manual pages for the various\\n\"\n\"methods (e.g. TSROSW, TSARKIMEX, TSEIMEX, ...) for further information.\\n\\n\";\n\n#include \n\ntypedef struct {\n PetscBool identity_in_F;\n} Ctx;\n\nextern PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec F,void*);\nextern PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);\nextern PetscErrorCode FormRHSFunction(TS,PetscReal,Vec,Vec,void*);\nextern PetscErrorCode FormRHSJacobian(TS,PetscReal,Vec,Mat,Mat,void*);\n\nint main(int argc,char **argv)\n{\n PetscErrorCode ierr;\n TS ts;\n Vec u, uexact;\n Mat JF,JG;\n Ctx user;\n PetscReal tf,xf,yf,errnorm;\n PetscInt steps;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n user.identity_in_F = PETSC_FALSE;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"\",\n \"Simple F(t,u,u')=G(t,u) ODE system.\",\"TS\"); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-identity_in_F\",\"set up system so the dF/d(dudt) = I\",\n \"ex54.c\",user.identity_in_F,&(user.identity_in_F),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr);\n ierr = VecSetSizes(u,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(u); CHKERRQ(ierr);\n\n ierr = MatCreate(PETSC_COMM_WORLD,&JF); CHKERRQ(ierr);\n ierr = MatSetSizes(JF,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr);\n ierr = MatSetFromOptions(JF); CHKERRQ(ierr);\n ierr = MatSetUp(JF); CHKERRQ(ierr);\n ierr = MatDuplicate(JF,MAT_DO_NOT_COPY_VALUES,&JG); CHKERRQ(ierr);\n\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);\n\n ierr = TSSetIFunction(ts,NULL,FormIFunction,&user); CHKERRQ(ierr);\n ierr = TSSetIJacobian(ts,JF,JF,FormIJacobian,&user); CHKERRQ(ierr);\n\n ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,&user); CHKERRQ(ierr);\n ierr = TSSetRHSJacobian(ts,JG,JG,FormRHSJacobian,&user); CHKERRQ(ierr);\n\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n // helps with ARKIMEX if you also set -ts_arkimex_fully_implicit:\n // ierr = TSSetEquationType(ts,TS_EQ_IMPLICIT); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSBDF); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,1.0); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,0.01); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n\n ierr = VecSetValue(u,0,1.0,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecSetValue(u,1,3.0,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecAssemblyBegin(u); CHKERRQ(ierr);\n ierr = VecAssemblyEnd(u); CHKERRQ(ierr);\n ierr = TSSolve(ts,u); CHKERRQ(ierr);\n\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);\n xf = -3.0 * PetscExpReal(-3.0*tf) + 4.0 * PetscExpReal(2.0*tf);\n yf = PetscExpReal(-3.0*tf) + 2.0 * PetscExpReal(2.0*tf);\n //ierr = PetscPrintf(PETSC_COMM_WORLD,\n // \"xf = %.6f, yf = %.6f\\n\",xf,yf); CHKERRQ(ierr);\n ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr);\n ierr = VecSetValue(uexact,0,xf,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecSetValue(uexact,1,yf,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecAssemblyBegin(uexact); CHKERRQ(ierr);\n ierr = VecAssemblyEnd(uexact); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecNorm(u,NORM_2,&errnorm); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"error norm at tf = %.6f from %d steps: |u-u_exact| = %.5e\\n\",\n tf,steps,errnorm); CHKERRQ(ierr);\n\n VecDestroy(&u); VecDestroy(&uexact);\n MatDestroy(&JF); MatDestroy(&JG);\n TSDestroy(&ts);\n return PetscFinalize();\n}\n\n\nPetscErrorCode FormIFunction(TS ts, PetscReal t, Vec u, Vec dudt,\n Vec F, void *user) {\n PetscErrorCode ierr;\n const PetscReal *au, *adudt;\n PetscReal *aF;\n PetscBool flag = ((Ctx*)user)->identity_in_F;\n\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecGetArrayRead(dudt,&adudt); CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF);\n if (flag) {\n aF[0] = adudt[0] + au[0] + 2.0 * au[1];\n aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1];\n } else {\n aF[0] = adudt[0] + adudt[1] + au[0] + 2.0 * au[1];\n aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1];\n }\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(dudt,&adudt); CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr);\n return 0;\n}\n\n// computes J = dF/du + a dF/d(dudt)\nPetscErrorCode FormIJacobian(TS ts, PetscReal t, Vec u, Vec dudt,\n PetscReal a, Mat J, Mat P, void *user) {\n PetscErrorCode ierr;\n PetscInt row[2] = {0, 1}, col[2] = {0, 1};\n PetscReal v[4];\n PetscBool flag = ((Ctx*)user)->identity_in_F;\n\n if (flag) {\n v[0] = a + 1.0; v[1] = 2.0;\n v[2] = 3.0; v[3] = a + 4.0;\n } else {\n v[0] = a + 1.0; v[1] = a + 2.0;\n v[2] = 3.0; v[3] = a + 4.0;\n }\n ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\nPetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec u,\n Vec G, void *user) {\n PetscErrorCode ierr;\n const PetscReal *au;\n PetscReal *aG;\n PetscBool flag = ((Ctx*)user)->identity_in_F;\n\n ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecGetArray(G,&aG); CHKERRQ(ierr);\n if (flag) {\n aG[0] = 8.0 * au[1];\n aG[1] = 4.0 * au[0] + 4.0 * au[1];\n } else {\n aG[0] = au[0] + 8.0 * au[1];\n aG[1] = 4.0 * au[0] + 4.0 * au[1];\n }\n ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);\n ierr = VecRestoreArray(G,&aG); CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FormRHSJacobian(TS ts, PetscReal t, Vec u, Mat J, Mat P,\n void *user) {\n PetscErrorCode ierr;\n PetscInt row[2] = {0, 1}, col[2] = {0, 1};\n PetscReal v[4];\n PetscBool flag = ((Ctx*)user)->identity_in_F;\n\n if (flag) {\n v[0] = 0.0; v[1] = 8.0;\n v[2] = 4.0; v[3] = 4.0;\n } else {\n v[0] = 1.0; v[1] = 8.0;\n v[2] = 4.0; v[3] = 4.0;\n }\n ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\n", "meta": {"hexsha": "008d1953f4fed75ebcf691d67d764f2a2b2a9924", "size": 8198, "ext": "c", "lang": "C", "max_stars_repo_path": "c/fix-arkimex/ex54.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/fix-arkimex/ex54.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/fix-arkimex/ex54.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": 39.6038647343, "max_line_length": 82, "alphanum_fraction": 0.6225908758, "num_tokens": 2813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.692078276274762}} {"text": "#ifndef __MATH_VECTOROPS_INCLUDED\n#define __MATH_VECTOROPS_INCLUDED\n\n#include \n#include \n#include \n#include \n<<<<<<< vectorops.h\n#include \n#include \"math/specialfunc.h\"\n=======\n#include \n#include \"specialfunc.h\"\n>>>>>>> 1.27\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifndef isnan\n# define isnan(x) ((x) != (x))\n#endif\n\n/* \n * take the exponent of a vector\n *\n * If the exponent is infinite, then we replace the value with a\n * suitably large max_val\n */\nvoid vexp(const gsl_vector* v, \n gsl_vector* exp_v, \n double max_val = std::numeric_limits::infinity()) {\n assert(exp_v->size >= v->size);\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double val = exp(gsl_vector_get(v, ii));\n if (val == std::numeric_limits::infinity() || val > max_val) {\n val = max_val;\n }\n gsl_vector_set(exp_v, ii, val);\n }\n}\n\n/* take the exponent of a matrix */\nvoid mexp(const gsl_matrix* m, gsl_matrix* exp_m) {\n for (unsigned int ii = 0; ii < m->size1; ++ii) {\n for (unsigned int jj = 0; jj < m->size2; ++jj) {\n double val = exp(gsl_matrix_get(m, ii, jj));\n assert(!isnan(val));\n gsl_matrix_set(exp_m, ii, jj, val);\n }\n }\n}\n\n/* like vexp except that it also computes sum x log x */\ndouble vexp_entropy(const gsl_vector* v, gsl_vector* exp_v) {\n double entropy = 0.0;\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double logval = gsl_vector_get(v, ii);\n double val = exp(logval);\n assert(!isnan(val));\n gsl_vector_set(exp_v, ii, val);\n if (val != 0) {\n entropy -= val * logval;\n }\n }\n return entropy;\n}\n\ndouble ventropy(const gsl_vector* v) {\n double entropy = 0.0;\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double val = gsl_vector_get(v, ii);\n if (val != 0) {\n entropy -= val * log(val);\n }\n }\n return entropy;\n}\n\ndouble lgamma(double x) {\n double x0,x2,xp,gl,gl0;\n int n=0,k=0;\n static double a[] = {\n 8.333333333333333e-02,\n -2.777777777777778e-03,\n 7.936507936507937e-04,\n -5.952380952380952e-04,\n 8.417508417508418e-04,\n -1.917526917526918e-03,\n 6.410256410256410e-03,\n -2.955065359477124e-02,\n 1.796443723688307e-01,\n -1.39243221690590};\n \n x0 = x;\n if (x <= 0.0) return 1e308;\n else if ((x == 1.0) || (x == 2.0)) return 0.0;\n else if (x <= 7.0) {\n n = (int)(7-x);\n x0 = x+n;\n }\n x2 = 1.0/(x0*x0);\n xp = 2.0*M_PI;\n gl0 = a[9];\n for (k=8;k>=0;k--) {\n gl0 = gl0*x2 + a[k];\n }\n gl = gl0/x0+0.5*log(xp)+(x0-0.5)*log(x0)-x0;\n if (x <= 7.0) {\n for (k=1;k<=n;k++) {\n gl -= log(x0-1.0);\n x0 -= 1.0;\n }\n }\n return gl;\n}\n\nvoid mlog(const gsl_matrix* m, gsl_matrix* log_m) {\n for (unsigned int ii = 0; ii < m->size1; ++ii) {\n for (unsigned int jj = 0; jj < m->size2; ++jj) {\n gsl_matrix_set(log_m, ii, jj, log(gsl_matrix_get(m, ii, jj)));\n }\n }\n}\n\nvoid vlog(const gsl_vector* v, gsl_vector* log_v) {\n for (unsigned int ii = 0; ii < v->size; ++ii)\n gsl_vector_set(log_v, ii, log(gsl_vector_get(v, ii)));\n}\n\nvoid vlogit(const gsl_vector* v, gsl_vector* log_v) {\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double p = gsl_vector_get(v, ii);\n assert(p >= 0.0);\n assert(p <= 1.0);\n gsl_vector_set(log_v, ii, log(p / (1 - p)));\n }\n}\n\n\nvoid vsigmoid(const gsl_vector* v, gsl_vector* sig_v) {\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double p = gsl_vector_get(v, ii);\n gsl_vector_set(sig_v, ii, 1. / (1. + exp(-p)));\n }\n}\n\n\ndouble vlog_entropy(const gsl_vector* v, gsl_vector* log_v) {\n double entropy = 0;\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double val = gsl_vector_get(v, ii);\n entropy -= val * log(val);\n gsl_vector_set(log_v, ii, log(val));\n }\n return entropy;\n}\n\ndouble entropy(const gsl_vector* v) {\n double entropy = 0;\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n double val = gsl_vector_get(v, ii);\n entropy -= val * log(val);\n }\n return entropy;\n}\n\nvoid vdigamma(const gsl_vector* v, gsl_vector* digamma_v) {\n for (unsigned int ii = 0; ii < v->size; ++ii)\n // gsl_sf_psi throws an error when its argument is 0, whereas digamma returns inf.\n // gsl_vector_set(digamma_v, ii, gsl_sf_psi(gsl_vector_get(v, ii)));\n gsl_vector_set(digamma_v, ii, digamma(gsl_vector_get(v, ii)));\n}\n\nvoid vlgamma(const gsl_vector* v, gsl_vector* lgamma_v) {\n for (unsigned int ii = 0; ii < v->size; ++ii)\n gsl_vector_set(lgamma_v, ii, lgamma(gsl_vector_get(v, ii)));\n}\n\ndouble gsl_blas_dsum(const gsl_vector* v) {\n double sum = 0;\n for (unsigned int ii = 0; ii < v->size; ++ii) {\n sum += gsl_vector_get(v, ii);\n }\n return sum;\n}\n\ndouble gsl_blas_dsum(const gsl_matrix* v) {\n double sum = 0;\n for (unsigned int ii = 0; ii < v->size1; ++ii) {\n for (unsigned int jj = 0; jj < v->size2; ++jj) {\n sum += gsl_matrix_get(v, ii, jj);\n }\n }\n return sum;\n}\n\ndouble gsl_matrix_rowsum(const gsl_matrix* m, const int row) {\n double sum = 0;\n for(unsigned int i=0; i < m->size2; i++) {\n sum += gsl_matrix_get(m, row, i);\n }\n return sum;\n}\n\ndouble dot_product(const gsl_vector* a, const gsl_vector* b) {\n assert(a->size == b->size);\n double val = 0;\n for(unsigned i=0; isize; i++) {\n val += gsl_vector_get(a, i) * gsl_vector_get(b, i);\n }\n return val;\n}\n\nvoid uniform(gsl_vector* v) {\n\tgsl_vector_set_all(v, 1.0 / (double)v->size);\n}\n\ndouble normalize(gsl_vector* v) {\n double sum = gsl_blas_dsum(v);\n gsl_blas_dscal(1 / sum, v);\n return sum;\n}\n\n/*\n This function takes as input a multinomial parameter vector and\n computes the \"total\" variance, i.e., the sum of the diagonal of the\n covariance matrix. \n\n If the multinomial parameter is unnormalized, then the variance of\n the normalized multinomial vector will be computed and then\n multiplied by the scale of the vector.\n */\ndouble MultinomialTotalVariance(const gsl_vector* v) {\n double scale = gsl_blas_dsum(v);\n double variance = 0.0;\n for (size_t ii = 0; ii < v->size; ++ii) {\n double val = gsl_vector_get(v, ii) / scale;\n variance += val * (1. - val);\n }\n return variance * scale;\n}\n\n/*\n Computes covariance using the renormalization above and adds it to\n an existing matrix.\n*/\nvoid MultinomialCovariance(double alpha,\n\t\t\t const gsl_vector* v, \n\t\t\t gsl_matrix* m) {\n double scale = gsl_blas_dsum(v);\n gsl_blas_dger(-alpha / scale, v, v, m);\n gsl_vector_view diag = gsl_matrix_diagonal(m);\n gsl_blas_daxpy(alpha, v, &diag.vector);\n}\n\ndouble MatrixProductSum(const gsl_matrix* m1,\n\t\t\tconst gsl_matrix* m2) {\n double val = 0;\n assert(m1->size1 == m2->size1);\n assert(m1->size2 == m2->size2);\n for (size_t ii = 0; ii < m1->size1; ++ii) {\n for (size_t jj = 0; jj < m2->size2; ++jj) {\n val += gsl_matrix_get(m1, ii, jj) * \n\tgsl_matrix_get(m2, ii, jj);\n }\n }\n return val;\n}\n\ndouble MatrixProductProductSum(const gsl_matrix* m1,\n\t\t\t const gsl_matrix* m2,\n\t\t\t const gsl_matrix* m3) {\n double val = 0;\n assert(m1->size1 == m2->size1);\n assert(m1->size2 == m2->size2);\n assert(m1->size1 == m3->size1);\n assert(m1->size2 == m3->size2);\n for (size_t ii = 0; ii < m1->size1; ++ii) {\n for (size_t jj = 0; jj < m2->size2; ++jj) {\n for (size_t kk = 0; kk < m3->size2; ++kk) {\n\tval += gsl_matrix_get(m1, ii, jj) * \n\t gsl_matrix_get(m2, ii, jj) *\n\t gsl_matrix_get(m3, ii, jj);\n }\n }\n }\n return val;\n}\n\ndouble SumLGamma(const gsl_vector* v) {\n double s = 0.0;\n for (size_t ii = 0; ii < v->size; ++ii) {\n s += lgamma(gsl_vector_get(v, ii));\n }\n return s;\n}\n\nvoid mtx_fprintf(const char* filename, const gsl_matrix * m)\n{\n FILE* fileptr;\n fileptr = fopen(filename, \"w\");\n gsl_matrix_fprintf(fileptr, m, \"%20.17e\");\n fclose(fileptr);\n}\n\n\nvoid mtx_fscanf(const char* filename, gsl_matrix * m)\n{\n FILE* fileptr;\n fileptr = fopen(filename, \"r\");\n gsl_matrix_fscanf(fileptr, m);\n fclose(fileptr);\n}\n\ndouble mtx_accum(const int i,\n const int j,\n const double contribution,\n gsl_matrix* m) {\n\n double new_val = gsl_matrix_get(m, i, j) + contribution;\n gsl_matrix_set(m, i, j, new_val);\n return new_val;\n}\n\nvoid vct_fscanf(const char* filename, gsl_vector* v)\n{\n FILE* fileptr;\n fileptr = fopen(filename, \"r\");\n gsl_vector_fscanf(fileptr, v);\n fclose(fileptr);\n}\n\nvoid vct_fprintf(const char* filename, gsl_vector* v)\n{\n FILE* fileptr;\n fileptr = fopen(filename, \"w\");\n gsl_vector_fprintf(fileptr, v, \"%20.17e\");\n fclose(fileptr);\n}\n\n#endif\n", "meta": {"hexsha": "e31484893d4d9004c4e2ffc6063869de6fabdae0", "size": 8675, "ext": "h", "lang": "C", "max_stars_repo_path": "DTM/dtm-master/lib/math/vectorops.h", "max_stars_repo_name": "boomsbloom/dtm-fmri", "max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "DTM/dtm-master/lib/math/vectorops.h", "max_issues_repo_name": "boomsbloom/dtm-fmri", "max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DTM/dtm-master/lib/math/vectorops.h", "max_forks_repo_name": "boomsbloom/dtm-fmri", "max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 25.2915451895, "max_line_length": 86, "alphanum_fraction": 0.6082997118, "num_tokens": 2839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6914964766262995}} {"text": "// mathematical routines\n\n#include \"../include/bjutils.h\"\n\n\ndouble integrate_qag(double (*func)(double, void*),void *par,double low,double up,double *error)\n{\n const int lim=2000;\n const int key=5;\n const double eabs=0.0;\n const double erel=1.e-4;\n double res,err;\n\n gsl_integration_workspace *work=gsl_integration_workspace_alloc(lim);\n\n gsl_function F;\n F.function=func;\n F.params=par;\n\n gsl_integration_qag(&F,low,up,eabs,erel,lim,key,work,&res,&err);\n\n gsl_integration_workspace_free(work);\n if (error!=NULL) *error=err; \n return(res);\n}\n\n\ndouble findroot(double (*func)(double, void*),void *par,double low,double hig,double tol,double *error)\n{\n #include \n int status,iter=0;\n double root,rnext;\n const int max_iter=1000; // maximum no. of iterations\n\n gsl_function F;\n F.function=func;\n F.params=par;\n \n const gsl_root_fsolver_type *T=gsl_root_fsolver_brent;\n gsl_root_fsolver *solv=gsl_root_fsolver_alloc(T);\n gsl_root_fsolver_set(solv,&F,low,hig);\n \n do {\n iter++;\n status=gsl_root_fsolver_iterate(solv);\n root=gsl_root_fsolver_root(solv);\n low=gsl_root_fsolver_x_lower(solv);\n hig=gsl_root_fsolver_x_upper(solv);\n status=gsl_root_test_interval(low,hig,0.0,tol);\n if (status==GSL_SUCCESS) printf (\"Root finder converged after %i iterations\\n\",iter); \n } while (status==GSL_CONTINUE && itera[u])) {\n printf(\"Error: index out of range: %g not in %g-%g\\n\",x,a[l],a[u]);\n exit(-1);\n }\n while (u-l>1) {\n m=(u+l)/2;\n if (x>a[m]) l=m;\n else u=m;\n }\n *erg=l;\n}\n\n// 1D linear interpolation + extrapolation\ndouble interpol_linear_extra_1D(double *ax,int NX,double *z,double x)\n{\n if (NX==1) return(z[0]); // assume z constant if only one data point\n if (x<=ax[0]) return((z[1]-z[0])/(ax[1]-ax[0])*(x-ax[0])+z[0]);\n else if (x>=ax[NX-1]) return((z[NX-1]-z[NX-2])/(ax[NX-1]-ax[NX-2])*(x-ax[NX-1])+z[NX-1]);\n else {\n int ix;\n bisect_interpol(ax,NX,x,&ix);\n double t=(x-ax[ix])/(ax[ix+1]-ax[ix]);\n return((1-t)*z[ix]+t*z[ix+1]);\n }\n}\n\n\n// 2D linear interpolation + extrapolation\ndouble interpol_linear_extra_2D(double *ax,int NX,double *ay,int NY,double **z,double x,double y)\n{\n if ((x<=ax[0])&&(y>ay[0])&&(y=ax[NX-1])&&(y>ay[0])&&(yax[0])&&(x=ay[NY-1])&&(x>ax[0])&&(xay[0])&&(yaz[0])&&(z=ax[NX-1])&&(y>ay[0])&&(yaz[0])&&(zax[0])&&(xaz[0])&&(z=ay[NY-1])&&(x>ax[0])&&(xaz[0])&&(zax[0])&&(xay[0])&&(y=az[NZ-1])&&(x>ax[0])&&(xay[0])&&(yax[NX-1]))&&((yay[NY-1])||(zaz[NZ-1])||(waw[NW-1]))) {\n printf(\"Error in routine 'interpol_linear_extra_4D': attempt extrapolation in more than one dimension.\\n\");\n exit(-1);\n }\n\n if (x<=ax[0]) {\n f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[0],y,z,w);\n f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[1],y,z,w);\n return((f2-f1)/(ax[1]-ax[0])*(x-ax[0])+f1);\n }\n else if (x>=ax[NX-1]) {\n f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[NX-2],y,z,w);\n f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[NX-1],y,z,w);\n return((f2-f1)/(ax[NX-1]-ax[NX-2])*(x-ax[NX-1])+f2);\n }\n else {\n bisect_interpol(ax,NX,x,&ix);\n\n f1=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[ix],y,z,w);\n f2=interpol_linear_extra_3D(ay,NY,az,NZ,aw,NW,f[ix+1],y,z,w);\n\n t=(x-ax[ix])/(ax[ix+1]-ax[ix]);\n return((1-t)*f1+t*f2);\n }\n}\n\n\n\n\nvoid mattimesmat_gen(gsl_matrix *a,gsl_matrix *b,gsl_matrix *erg,int dim1,int dim2,int dim3)\n{\n int i,j,k;\n double sum;\n for (i=0;i1.e-2) {\n\t printf(\"Problematic matrix inversion: %g\\n\",elem);\n\t flag=2;\n\t break;\n\t}\n }\n }\n }\n\n gsl_matrix_free(u);\n gsl_matrix_free(v);\n gsl_matrix_free(id);\n gsl_vector_free(work);\n gsl_vector_free(s);\n return(flag);\n}\n\n\ngsl_matrix *pseudoinvers(gsl_matrix *m,double thresh,double *eigen)\n{\n int i,j,k;\n double sum;\n\n const int dim=(int)m->size1;\n if (m->size1!=m->size2) {\n printf(\"Error in 'pseudoinvers': non-square matrix - not implemented yet.\\n\");\n exit(-1);\n }\n\n gsl_matrix *res=gsl_matrix_alloc(dim,dim);\n gsl_matrix *v=gsl_matrix_alloc(dim,dim);\n gsl_matrix *cov=gsl_matrix_alloc(dim,dim);\n gsl_vector *work=gsl_vector_alloc(dim);\n gsl_vector *s=gsl_vector_alloc(dim);\n gsl_vector *invs=gsl_vector_alloc(dim);\n\n gsl_matrix_memcpy(cov,m);\n gsl_linalg_SV_decomp(cov,v,s,work);\n\n for (i=0;i\n gsl_set_error_handler_off();\n const int DOCHECK=1;\n\n int i,flag=0;\n gsl_matrix *check=gsl_matrix_alloc(DIM,DIM);\n gsl_vector *b=gsl_vector_alloc(DIM);\n\n gsl_matrix_memcpy(check,m);\n\n flag=gsl_linalg_cholesky_decomp(check);\n\n if (!flag) {\n for (i=0;i1.e-6) {\n\t printf(\"Problematic matrix inversion: %g\\n\",elem);\n\t flag=2;\n\t break;\n\t }\n\t}\n }\n gsl_matrix_free(id);\n }\n }\n\n gsl_matrix_free(check);\n gsl_vector_free(b);\n return(flag);\n}\n\ndouble matrix_trace(gsl_matrix *a,int N)\n{\n int i;\n double sum=0.0;\n for (i=0;isize1;i++) {\n for (j=0;jsize2;j++) {\n fprintf(dat,\"%15.10g\\t\",gsl_matrix_get(a,i,j));\n }\n fprintf(dat,\"\\n\");\n }\n fclose(dat);\n return;\n}\n\n\nvoid vector_print(gsl_vector *v,char *file)\n{\n int i;\n FILE *dat;\n if ((dat=fopen(file,\"w\"))==NULL) {\n printf(\"Error in routine 'vector_print': could not open file %s\\n\",file);\n exit(-1);\n }\n for (i=0;isize;i++) {\n fprintf(dat,\"%15.10g\\n\",gsl_vector_get(v,i));\n }\n fclose(dat);\n return;\n}\n\n\nvoid solve_lse(gsl_matrix *m,gsl_vector *in,gsl_vector *res)\n{\n if (m->size1!=res->size) {\n printf(\"Error in routine 'solve_lse': matrix row dimension does not match dimension of solution vector: %zu - %zu\\n\",m->size1,res->size);\n exit(-1);\n }\n if (m->size2!=in->size) {\n printf(\"Error in routine 'solve_lse': matrix column dimension does not match dimension of input vector: %zu - %zu\\n\",m->size2,in->size);\n exit(-1);\n }\n\n gsl_matrix *v=gsl_matrix_alloc(m->size2,m->size2);\n gsl_matrix *u=gsl_matrix_alloc(m->size1,m->size2);\n gsl_vector *work=gsl_vector_alloc(m->size2);\n gsl_vector *s=gsl_vector_alloc(m->size2);\n\n gsl_matrix_memcpy(u,m);\n gsl_linalg_SV_decomp(u,v,s,work);\n gsl_linalg_SV_solve(u,v,s,in,res);\n\n gsl_matrix_free(u);\n gsl_matrix_free(v);\n gsl_vector_free(work);\n gsl_vector_free(s);\n return;\n}\n\n\n\n// inverse of symmetric matrix via Cholesky decomposition\nint inverse_symm(gsl_matrix *in,gsl_matrix *out)\n{\n #include\n gsl_set_error_handler_off();\n\n int i,flag=0;\n const int dim=(int)in->size1;\n gsl_matrix *check=gsl_matrix_alloc(dim,dim);\n gsl_vector *b=gsl_vector_alloc(dim);\n gsl_matrix_memcpy(check,in); // do not overwrite 'in'\n\n flag=gsl_linalg_cholesky_decomp(check);\n\n if (!flag) {\n for (i=0;isize1;\n gsl_matrix *inv=gsl_matrix_alloc(dim,dim);\n gsl_matrix *sub=gsl_matrix_alloc(2,2);\n gsl_matrix *v=gsl_matrix_alloc(2,2);\n gsl_vector *work=gsl_vector_alloc(2);\n gsl_vector *s=gsl_vector_alloc(2);\n\n // invert Fisher matrix\n flag=inverse_symm(fisher,inv);\n\n // get ellipse plotting parameters\n gsl_matrix_set(sub,0,0,gsl_matrix_get(inv,index1,index1));\n gsl_matrix_set(sub,0,1,gsl_matrix_get(inv,index1,index2));\n gsl_matrix_set(sub,1,0,gsl_matrix_get(inv,index2,index1));\n gsl_matrix_set(sub,1,1,gsl_matrix_get(inv,index2,index2));\n\n gsl_linalg_SV_decomp(sub,v,s,work);\n *semi_major=sqrt(gsl_vector_get(s,0));\n *semi_minor=sqrt(gsl_vector_get(s,1));\n *angle=atan(gsl_matrix_get(v,1,0)/gsl_matrix_get(v,0,0)); \n\n // clean up\n gsl_vector_free(work);\n gsl_matrix_free(v);\n gsl_matrix_free(inv);\n gsl_matrix_free(sub);\n gsl_vector_free(s);\n return(flag);\n}\n\n\n\n// provides KDE in 1D with Gaussians, using Silverman's rule if width<=0 on call\nvoid kde_1D(double *dp,int nd,int nstep,double step_min,double step_max,double h,double *steps,double *func)\n{\n int i,j;\n double width=1.;\n const double gauss_norm=1./sqrt(2.*PI);\n\n // set binning\n for (i=0;i\n#include \n#include \n#include \n\nnamespace sens_loc::math {\n\n/// This class is a small wrapper to clarify the mathematical notation\n/// of ranges. It does NOT distinguish between \\f$[min, max)\\f$,\n/// \\f$[min, max]\\f$, \\f$(min, max)\\f$.\n/// \\tparam Real underlying type of the range, integer type for example\n/// \\warning this struct does not ensure that \\p min is always smaller \\p max.\ntemplate \nstruct numeric_range {\n static_assert(std::is_arithmetic_v);\n\n Real min; ///< lower bound of the range\n Real max; ///< uppoer bound of the range\n};\n\n/// This function scales \\p value from the range \\p source_range to the\n/// new range \\p target_range.\n/// \\note \\p value is clamped to \\p source_range\n/// \\pre the ranges are well formed (\\p min is smaller \\p max)\n/// \\returns the scaled value that is clamped to \\p target_range.\ntemplate \ninline constexpr Real scale(const numeric_range& source_range,\n const numeric_range& target_range,\n Real value) noexcept {\n static_assert(std::is_arithmetic_v);\n\n Expects(source_range.min < source_range.max);\n Expects(target_range.min < target_range.max);\n\n const Real clamped = std::clamp(value, source_range.min, source_range.max);\n\n Ensures(clamped <= source_range.max);\n Ensures(clamped >= source_range.min);\n\n const Real scaled =\n ((target_range.max - target_range.min) * (value - source_range.min)) /\n (source_range.max - source_range.min) +\n target_range.min;\n\n const Real target_clamped =\n std::clamp(scaled, target_range.min, target_range.max);\n\n Ensures(target_clamped <= target_range.max);\n Ensures(target_clamped >= target_range.min);\n\n return target_clamped;\n}\n} // namespace sens_loc::math\n\n#endif /* end of include guard: SCALING_H_SAL4XICS */\n", "meta": {"hexsha": "46acabd53ffa1abf917485df0420cbe23c99183a", "size": 2009, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/math/scaling.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/math/scaling.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/math/scaling.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0508474576, "max_line_length": 79, "alphanum_fraction": 0.6824290692, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.6909845591588762}} {"text": "#include \n#include \n#include \n#include \n#include \n\n// y' = exp(x)\n// https://www.wolframalpha.com/input/?i=y%27+%3D+2y+%2B+x%2C+y%280%29+%3D+1%2C+y%281%29\n// https://www.wolframalpha.com/input/?i=1%2F4+*+%285+*+e%5E2+-+3%29\nint odefunc (double x, const double y[], double f[], void *params)\n{\n // f[0] = x+2*y[0];\n\t// pow(): 멱급수(a, b) = a^b (a의 b승)\n\t// math.h에 있으며 pow를 활용하기 위해서는 -lm 옵션이 추가로 필요합니다.\n\t// GSL 라이브러리를 활용하기 위해선 -lgsl 옵션이 필요합니다.\n\tf[0] = pow(M_E, x);\n\n return GSL_SUCCESS;\n}\n\nint * jac;\n\nint main(void)\n{\n int dim = 1;\n\t// 미방을 풀기 위한 데이터 타입\n gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};\n\n\t// 드라이버는 미방을 쉽게 풀 수 있도록 시간에 따른 변화, 제어, 스텝에 대한 래퍼\n\t// gsl_odeiv2_step_rkf45는 룬게쿠타 4-5차를 의미함\n\t// 다음 인자는 미분방정식의 시작지점\n\t// 절대적인 에러 바운드와 상대적인 에러 바운드\n gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);\n int i;\n double x0 = 0.0, xf = 10.0; /* start and end of integration interval */\n double x = x0;\n double y[1] = { 1 }; /* initial value */\n\tdouble tmp = 0.0;\n\n for (i = 0; tmp <= xf; tmp += 0.1)\n {\n\t\t// for문을 포함하여 아래 한 줄을 통해 상황에 따라\n\t\t// 간소화된 형태로 결과를 출력할 수도 있고\n\t\t// 시간이 좀 더 오래걸리더라도 더 정확한 데이터를 산출할 수도 있음\n double xi = x0 + tmp * (xf-x0) / xf;\n int status = gsl_odeiv2_driver_apply (d, &x, xi, y);\n\n if (status != GSL_SUCCESS)\n {\n printf (\"error, return value=%d\\n\", status);\n break;\n }\n\n printf (\"%.8e %.8e\\n\", x, y[0]);\n }\n\n gsl_odeiv2_driver_free (d);\n return 0;\n}\n", "meta": {"hexsha": "072a2d9a14265b879ac74dd230ba149b986e6d18", "size": 1601, "ext": "c", "lang": "C", "max_stars_repo_path": "ch4/src/main/detail_yprime_exp_x.c", "max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z", "max_issues_repo_path": "ch4/src/main/detail_yprime_exp_x.c", "max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/src/main/detail_yprime_exp_x.c", "max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z", "avg_line_length": 26.6833333333, "max_line_length": 105, "alphanum_fraction": 0.5815115553, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6907862734125872}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"matrixUtils.h\"\n#include \"../mcmc/mvnormMCMC/mvrandist.h\"\n\n/*A collection of matrix functions*/\n/*Alexander G. Shanku*/\n/*Wed 12/05/2012 12:44:41 EST*/\n\n//// Makes a matrix filled with random U(0,1) elements ////\ngsl_matrix fill_rand_matrix(gsl_matrix *X, gsl_rng *r_num){\n\tint i,j;\n\t/*int step = 0;*/\n\tint n = X->size1;\n\tint m = X->size2;\n\tfor (i = 0; i < m; ++i){\n\t\tfor (j = 0; j < n; ++j){\n\t\t\tgsl_matrix_set(X, i, j, gsl_rng_uniform(r_num));\t\t\t\t\t\t\n\t\t}\n\t}\n\treturn(*X);\t\n}\n\n//// Makes a matrix filled with sequential elements, starting with 0 ////\ngsl_matrix fill_matrix(gsl_matrix *X){\n\tint i,j;\n\tint n = X->size1;\n\tint m = X->size2;\n\tfor (i = 0; i < m; ++i){\n\t\tfor (j = 0; j < n; ++j){\n\t\t\tgsl_matrix_set(X, i, j, i+(j*m));\n\t\t}\n\t}\n\treturn(*X);\t\n}\n\n//// Do LU decomp, get determinant and keep input matrix untouched ////\ndouble matrix_determ(gsl_matrix *X){\n\tint s;\n\tint n = X->size1;\n\tint m = X->size2;\n\tgsl_matrix *a_copy = gsl_matrix_alloc(m, n);\n\tgsl_matrix_memcpy(a_copy, X );\n\tgsl_permutation *P = gsl_permutation_alloc(n);\n\tgsl_linalg_LU_decomp(a_copy, P, &s);\n\tdouble my_det = gsl_linalg_LU_det (a_copy, s);\n\treturn(my_det);\n}\n\n//// Get trace of given matrix ////\ndouble matrix_trace(gsl_matrix *X){\n\tint i, m;\n\tm = X->size1;\n\tdouble trace = 0.0;\n\tfor(i=0;isize1;\n\tint n = X->size2;\n\t\n\t// Allocate matrix for inv(X)\n\tgsl_matrix *for_mult = gsl_matrix_alloc(m, n);\n\t\n\t// Get determinant of X and Scale matrix\n\tX_det = matrix_determ(X);\n\tscale_det = matrix_determ(Scale);\n\t\n\t// Invert X\n\tinv_matrix(X,inv);\n\t\n\t// Multiple Scale * inv(X)\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Scale, inv, 1.0, for_mult);\n\t\n\t// Get trace of above.\n\ttrace = matrix_trace(for_mult);\n\n\tnumerator = pow(scale_det, dof / 2.0) * pow(X_det, (-dof-m-1)/ 2.0) * exp(-0.5 * trace);\n\tdenom = pow(2,dof * m / 2) * mv_gamma(dof/2, m);\n\n\tpdf = (numerator/denom);\n\n\treturn(pdf);\n}\n\n//// Invert a matrix and keep input matrix untouched ////\ngsl_matrix inv_matrix(gsl_matrix *X, gsl_matrix *inv){\n\tint s;\n\tint n = X->size1;\n\tint m = X->size2;\n\tgsl_matrix *a_copy = gsl_matrix_alloc(m, n);\n\tgsl_matrix_memcpy( a_copy, X );\n\tgsl_permutation *P = gsl_permutation_alloc(n);\n\tgsl_linalg_LU_decomp(a_copy, P, &s);\n\tgsl_linalg_LU_invert(a_copy, P, inv);\n\treturn(*inv);\n}\n\n//// Print a matrix to stdout ////\nvoid print_matrix(gsl_matrix *X){\n\tint i, j;\n\tint n = X->size1;\n\tint m = X->size2;\n\tprintf(\"\\n\");\n\tfor(i=0; isize;\n\t\tfor (i = 0; i < n; ++i){\n\t\t\t\n\t\t\t\tgsl_vector_set(dest, i, src[i]);\n\t\t\t}\n\treturn(*dest);\t\n}\t\n\n///// Transform user supplied matrix into a gsl matrix ////\ngsl_matrix mdarray_to_gsl_mat(gsl_matrix *dest, double src[3][3]){\n\tint i, j;\n\tint n = dest->size1;\n\tint m = dest->size2;\n\t\tfor (i = 0; i < m; ++i){\n\t\t\tfor (j = 0; j < n; ++j){\n\t\t\t\tgsl_matrix_set(dest, i, j, src[i][j]);\n\t\t\t}\n\t\t}\n\treturn(*dest);\t\n}\t\n\n//// Print a vector to stdout ////\nvoid print_vector(gsl_vector *src){\n\tint i;\n\tint n = src->size;\n\tprintf(\"\\n\");\n\tfor (i = 0; i < n; ++i){\n\t\tprintf(\"%05.4f \", gsl_vector_get(src,i));\n\t}\n\tprintf(\"\\n\");\n}\n\n//// Do cholesky decomp to matrix ////\ngsl_matrix get_chol(gsl_matrix *src, gsl_matrix *dest){\n\tgsl_matrix_memcpy(dest, src);\n\tgsl_linalg_cholesky_decomp(dest);\n\treturn(*dest);\n}\n\n//// Add gaussian noise to chol decomp matrix ////\ngsl_matrix mat_noise(gsl_matrix *src, gsl_rng *r_num){\n\tint i,j;\n\tint n = src->size1;\n\tint m = src->size2;\n\tdouble tmp;\n\n\tfor(i = 0; i < n; i++){\n\t\tfor(j = 0; j < m; j++){\n\t\t\tif(i >= j){\n\t\t\t\ttmp = gsl_matrix_get(src,i,j) + gsl_ran_gaussian(r_num,0.05);\n\t\t\t\tgsl_matrix_set(src, i, j, tmp);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\t\n\treturn(*src);\n}\n\n//// Transform cholesky decomp matrix into vector ////\nvoid fill_chol_vec(gsl_matrix *src, gsl_vector *dest){\n\tint i, j, count = 0;\n\t\n\tfor(i = 0; i < src->size1; i++){\n\t\tfor(j=0;jsize2;j++){\n\t\t\tif(i<=j){\n\t\t\t\t gsl_vector_set(dest,count++, gsl_matrix_get(src,i,j));\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\t\n}\n\n//// Add gaussian noise to each element in vector ////\ngsl_vector vec_noise(gsl_rng *r_num, gsl_vector *src, gsl_vector *dest){\n\tint i; \n\tint n = src->size;\n\tdouble tmp;\n\t\n\tfor(i=0;isize1; i++){\n\t\tfor(j = 0; j < src->size2; j++){\n\t\t\tif(iwinv, \n\t\t\tp2->work,p2->work2, p2->means, p2->xm, p2->covMat);\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", "meta": {"hexsha": "1ac4a12fac1f94e6f2bc2c04b4045d861c8ba7bf", "size": 6838, "ext": "c", "lang": "C", "max_stars_repo_path": "matrixUtils.c", "max_stars_repo_name": "andrewkern/pgLib", "max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z", "max_issues_repo_path": "matrixUtils.c", "max_issues_repo_name": "andrewkern/pgLib", "max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "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": "matrixUtils.c", "max_forks_repo_name": "andrewkern/pgLib", "max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z", "avg_line_length": 21.8466453674, "max_line_length": 93, "alphanum_fraction": 0.6392219947, "num_tokens": 2279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6907862687035699}} {"text": "/*\n** Kendall's coefficient of concordance - Kendall's W\n** \n** G.Lohmann, July 2010\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\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\ndouble kendall(size_t **xrank,double *r,int n,int m,int otype)\n{\n int i,j;\n double S,W,R,chi_square=0;\n double nx=0,mx=0;\n\n nx = (double)n;\n mx = (double)m;\n\n for (i=0; isize1;\n n = nvoxels;\n\n if (vec == NULL) {\n r = (double *) calloc(data->size2,sizeof(double));\n vec = gsl_vector_calloc(data->size2);\n perm = gsl_permutation_alloc(data->size2);\n rank = gsl_permutation_alloc(data->size2);\n\n xrank = (size_t **) calloc(m,sizeof(size_t *));\n for (i=0; isize2,sizeof(size_t));\n }\n\n gsl_vector_set_all (vec,9999);\n for (i=0; idata[j];\n }\n\n /* Kendall's W of measured data */\n W0 = kendall(xrank,r,n,m,otype);\n return W0;\n}\n", "meta": {"hexsha": "1df96400e106de0939ebb4b264e12d3e6f978078", "size": 2119, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nets/vccm/Kendall.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/vccm/Kendall.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/vccm/Kendall.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": 23.0326086957, "max_line_length": 81, "alphanum_fraction": 0.6073619632, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6907820109291413}} {"text": "#pragma once\n\n#include \n\n#include \n\nbool to_fraction(double num, long& numerator, long& denominator){\n double sign = num < 0 ? -1 : 1;\n double g = std::abs(num);\n long a = 0, b = 1, c = 1, d = 0;\n long s;\n int iter = 0;\n numerator = 0, denominator = 1;\n while (iter++ < 1e6){\n s = (long) std::floor(g);\n numerator = a + s*c;\n denominator = b + s*d;\n a = c;\n b = d;\n c = numerator;\n d = denominator;\n g = 1.0/(g-s);\n if(gsl_fcmp(sign*numerator, num*denominator, 1e-13) == 0){\n numerator *= sign;\n return true;\n }\n }\n return false;\n}\n", "meta": {"hexsha": "1dfa3017a97e49ab2474b5ce53831c5f683b7583", "size": 674, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Utils/Fraction.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "MathEngine/Utils/Fraction.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "MathEngine/Utils/Fraction.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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.4666666667, "max_line_length": 66, "alphanum_fraction": 0.4910979228, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6900702635007305}} {"text": "/*solver/integration.c\n*\n* Function for numerical integration\n* using quadrature and Monte Carlo\n* methods.\n*\n* Author: Benjamin Vatter.\n* email: benjaminvatterj@gmail.com\n* date: 15 August 2015\n*/\n\n#include \n#include \n#include \n#include \n#include \"integration.h\"\n#include \"dbg.h\"\n#include \n#include \n#include \n#include \n\n\ntypedef struct {\n\tint dims;\n\tint depth;\n\tdouble *lb;\n\tdouble *ub;\n\tdouble *real_x;\n\tdouble epsabs;\n\tdouble epsrel;\n\tsize_t limit;\n\tgsl_integration_workspace * workspace;\n\tdouble * abserr;\n\tnquad_function *f;\n} nquad_params;\n\nvoid gsl_error (const char * reason, const char * file, int line, int gsl_errno)\n{\n gsl_stream_printf (\"NQUAD ERROR\", file, line, reason);\n\n\n if (gsl_errno != GSL_EROUND) {\n\t fflush (stderr);\n\t fflush (stdout);\n\t abort ();\n } else {\n \tlog_warn(\"NQUAD ERROR: rounding error detected. This result might be unreliable.\");\n \tfflush (stderr);\n \treturn;\n }\n}\n\n/*\nSUbroutine for recursive multidimensional integration\n*/\ndouble nquad_f(double x, void * params)\n{\n\tnquad_params *in_pars = (nquad_params *) params;\n\tdouble result;\n\tdouble abserr;\n\tint step = in_pars->depth;\n\t// Add value\n\tif (step>0) {\n\t \tin_pars->real_x[step-1] = x;\n\t}\n\tif (in_pars->dims == in_pars->depth){\n\t\tresult = in_pars->f->function(in_pars->real_x, in_pars->dims, in_pars->f->params);\n\t\treturn result;\n\t} else {\n\t\t// Consistency\n\t\tassert((step+1) <= in_pars->dims);\n\t\t// increase depth\n\t\tin_pars->depth += 1;\n\t\tgsl_integration_workspace *w = gsl_integration_workspace_alloc(in_pars->limit);\n\t\tgsl_function F = {.function = &nquad_f, .params = in_pars};\n\t\tgsl_integration_qags(&F, in_pars->lb[step], in_pars->ub[step], in_pars->epsabs, in_pars->epsrel, in_pars->limit, w,&result, &abserr);\n\t\t//gsl_integration_qag(&F, in_pars->lb[step], in_pars->ub[step], in_pars->epsabs, in_pars->epsrel, in_pars->limit, 2, w,&result, &abserr);\n\t\tin_pars->abserr[step] = abserr;\n\t\tgsl_integration_workspace_free(w);\n\t\tin_pars->depth -= 1;\n\t\treturn result;\n\t}\n}\n\n/*\nAn extension of gsl_integration_qags\nto n dimensions. The first parameter is\nthe number or dimensions. the signature of\nf must be\nf(double *x, void * params)\n\nParameters:\nn - dimensions\nf - function and parameters\nlb - lower bounds to integrals\nub - upper bounds to integrals\nepsabs - desired absolute error in each integral (only in nested-quadrature)\nepsrel - desired relative error in each integral (only in nested-quadrature)\nlimit - max number of iterations\nresult - on out contains result\nabserr - on out contains estimated error\n*/\nvoid nquad(int n, nquad_function *f, double *lb, double *ub,\n double epsabs, double epsrel, size_t limit, double * result, double *abserr)\n{\n\tassert(n>=1);\n\tnquad_params *new_params = malloc(sizeof(nquad_params));\n\tnew_params->dims = n;\n\tnew_params->depth = 0;\n\tnew_params->lb = lb;\n\tnew_params->ub = ub;\n\tnew_params->epsabs = epsabs;\n\tnew_params->epsrel = epsrel;\n\tnew_params->limit = limit;\n\tnew_params->abserr = malloc(sizeof(double) * n);\n\tnew_params->f = f;\n\tnew_params->real_x = malloc(sizeof(double) * n);\n\n\t// Set error handle\n\tgsl_error_handler_t *old_handler = gsl_set_error_handler(&gsl_error);\n\n\t// integrate\n\tresult[0] = nquad_f(0.0, new_params);\n\tabserr[0] = 1.0;\n\tint i;\n\tdouble err = 0.0;\n\tfor (i = 0; iabserr[i])? new_params->abserr[i]: err;\n\t}\n\t*abserr = err;\n\n\t// release real x\n\tfree(new_params->real_x);\n\tfree(new_params->abserr);\n\tfree(new_params);\n\t// recover error handle\n\tgsl_set_error_handler(old_handler);\n}\n\n\n/* Monte Carlo integration routine\n* It has the same signature as the nquad function\n* but it doesn't really use the epsrel value. It is\n* done so to allow interchanging those two functions\n* during runtime.\n*\n* This is based on the Monte Carlo plain routine found\n* in GSL, written by Michael Booth\n*/\nvoid mcint(int n, nquad_function *f, double *lb, double *ub, double epsabs,\n double epsrel, size_t limit, double *result, double *abserr)\n{\n\tdouble vol=1.0, m = 0, q = 0;\n\tdouble *x = malloc(sizeof(double)*n);\n\tsize_t i, j;\n\tconst gsl_rng_type *T;\n\tgsl_rng *r;\n\tgsl_rng_env_setup ();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\n\t/* Sanity check */\n\tfor(i=0; i= ub[i]) {\n\t\t\tGSL_ERROR(\"Lower bound is higher than upper bound. Null feasible region.\", GSL_EINVAL);\n\t\t}\n\t\tif(ub[i] - lb[i] > GSL_DBL_MAX) {\n\t\t\tGSL_ERROR(\"Range of integration is too large, please rescale\",\n GSL_EINVAL);\n\t\t}\n\t\tvol *= ub[i] - lb[i];\n\t}\n\n\tj=0;\n\n\tdo\n\t{\n\t\tfor (i=0; i < n; i++) {\n\t\t\tx[i] = lb[i] + gsl_rng_uniform_pos(r) * (ub[i] - lb[i]);\n\t\t}\n\t\tdouble fval = (f->function)(x, n, f->params);\n\t\tdouble d = fval - m;\n\t\tm += d / (n + 1.0);\n\t\tq += d * d * (n/(n +1.0));\n\n\t\tif (j < 2){ *abserr = GSL_POSINF;}\n\t\telse {\n\t\t\t*abserr = vol * sqrt(q / (limit * (limit - 1.0)));\n\t\t}\n\t\tj++;\n\t} while((*abserr > epsabs) && j < limit);\n\n\t*result = vol * m;\n\tif (*abserr > epsabs){\n\t\tlog_warn(\"Monte Carlo integration max evaluation %d was insufficient\"\n\t\t\"to achieve the desired absolute error of %e\", (int)limit, epsabs);\n\t}\n\n\tfree(x);\n\tgsl_rng_free (r);\n}\n\n\n\n", "meta": {"hexsha": "33b9c3174628f435eecf85663a579c41dd85de96", "size": 5180, "ext": "c", "lang": "C", "max_stars_repo_path": "integration.c", "max_stars_repo_name": "benjaminvatterj/multidim_integration", "max_stars_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integration.c", "max_issues_repo_name": "benjaminvatterj/multidim_integration", "max_issues_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integration.c", "max_forks_repo_name": "benjaminvatterj/multidim_integration", "max_forks_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.145631068, "max_line_length": 139, "alphanum_fraction": 0.6760617761, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.817574478416099, "lm_q1q2_score": 0.6899470918892645}} {"text": "#include \n\nint main(int argc, char **argv) {\n \n PetscErrorCode ierr;\n PetscMPIInt rank;\n PetscInt i;\n PetscReal localval, globalsum;\n PetscReal x = 1; // default value\n \n ierr = PetscInitialize(&argc, &argv, NULL,\n \"Compute e in parallel with PETSc.\\n\\n\"); \n if (ierr) return ierr;\n \n ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr);\n\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, NULL, \n \"Maclaurin Series for exp(x)\",\n NULL); CHKERRQ(ierr); \n ierr = PetscOptionsReal(\"-x\", \"input to exp(x) function\", \n NULL, x, &x, NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n // compute x^n / n! where n = (rank of process) + 1\n localval = 1.;\n for (i = 1; i < rank+1; i++) localval *= x/i;\n \n // sum the contributions over all processes\n ierr = MPI_Allreduce(&localval, &globalsum, 1, MPIU_REAL, MPIU_SUM,\n PETSC_COMM_WORLD); CHKERRQ(ierr);\n \n // output estimate of e and report on work from each process\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"exp(x) is about %17.15f\\n\", \n globalsum); CHKERRQ(ierr);\n\n ierr = PetscPrintf(PETSC_COMM_SELF,\n \"rank %d did %d flops\\n\", \n rank, (rank > 0) ? rank-1 : 0); CHKERRQ(ierr);\n\n return PetscFinalize();\n}", "meta": {"hexsha": "bd0bfbda11beb96af26922d2744f7dfd30783399", "size": 1485, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch1/expx.c", "max_stars_repo_name": "LeilaGhaffari/p4pdes", "max_stars_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "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/ch1/expx.c", "max_issues_repo_name": "LeilaGhaffari/p4pdes", "max_issues_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "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/ch1/expx.c", "max_forks_repo_name": "LeilaGhaffari/p4pdes", "max_forks_repo_head_hexsha": "f7781d4c1bd0868ac31543badf1a6c4afedaf4b0", "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.3571428571, "max_line_length": 71, "alphanum_fraction": 0.538047138, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6892892147432291}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define X y[0]\n#define V_X y[1]\n#define Y y[2]\n#define V_Y y[3]\n\nconst double g = 9.81; /* m/s^2 */\nconst double v_0 = 700.0; /* m/s */\nconst double B2_m = 4.0e-5; /* 1/m */\nconst double y_d = 1.0e4; /* m */\n\nint func(double t, const double y[], double f[], void *params);\n\nint main(int argc, char *argv[]) {\n gsl_odeiv2_system sys = {func, NULL, 4, NULL};\n gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new(\n &sys, gsl_odeiv2_step_rkf45, 1.0e-6, 1.0e-6, 0.0\n );\n int i = 1;\n double t = 0.0;\n double alpha = argc > 1 ? strtod(argv[1], NULL) : 1.0;\n double y[4];\n X = Y = 0.0;\n V_X = v_0*cos(alpha);\n V_Y = v_0*sin(alpha);\n while (Y >= 0.0) {\n double t_i = i/50.0;\n int status = gsl_odeiv2_driver_apply(driver, &t, t_i, y);\n if (status != GSL_SUCCESS) {\n warnx(\"apply status = %d\", status);\n break;\n }\n printf(\"%.12le %.12le %.12le %.12le %.12le\\n\", t, X, Y, V_X, V_Y);\n i++;\n }\n gsl_odeiv2_driver_free(driver);\n return EXIT_SUCCESS;\n}\n\n#define DX_DT f[0]\n#define DVX_DT f[1]\n#define DY_DT f[2]\n#define DVY_DT f[3]\n\nint func(double t, const double y[], double f[], void *params) {\n double v = sqrt(V_X*V_X + V_Y*V_Y);\n double corr = exp(-Y/y_d);\n DX_DT = V_X;\n DVX_DT = -B2_m*corr*v*V_X;\n DY_DT = V_Y;\n DVY_DT = -g - B2_m*corr*v*V_Y;\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "88ec89e597463e54c21416fe85c7a350af7c70ff", "size": 1555, "ext": "c", "lang": "C", "max_stars_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 25.9166666667, "max_line_length": 74, "alphanum_fraction": 0.5665594855, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6892892111685167}} {"text": "/* roots/falsepos.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* falsepos.c -- falsepos root finding algorithm \n\n The false position algorithm uses bracketing by linear interpolation.\n\n If a linear interpolation step would decrease the size of the\n bracket by less than a bisection step would then the algorithm\n takes a bisection step instead.\n \n The last linear interpolation estimate of the root is used. If a\n bisection step causes it to fall outside the brackets then it is\n replaced by the bisection estimate (x_upper + x_lower)/2.\n\n*/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"roots.h\"\n\ntypedef struct\n {\n double f_lower, f_upper;\n }\nfalsepos_state_t;\n\nstatic int falsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper);\nstatic int falsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper);\n\nstatic int\nfalsepos_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper)\n{\n falsepos_state_t * state = (falsepos_state_t *) vstate;\n\n double f_lower, f_upper ;\n\n *root = 0.5 * (x_lower + x_upper);\n\n SAFE_FUNC_CALL (f, x_lower, &f_lower);\n SAFE_FUNC_CALL (f, x_upper, &f_upper);\n \n state->f_lower = f_lower;\n state->f_upper = f_upper;\n\n if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0))\n {\n GSL_ERROR (\"endpoints do not straddle y=0\", GSL_EINVAL);\n }\n\n return GSL_SUCCESS;\n\n}\n\nstatic int\nfalsepos_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper)\n{\n falsepos_state_t * state = (falsepos_state_t *) vstate;\n\n double x_linear, f_linear;\n double x_bisect, f_bisect;\n\n double x_left = *x_lower ;\n double x_right = *x_upper ;\n\n double f_lower = state->f_lower; \n double f_upper = state->f_upper;\n\n double w ;\n\n if (f_lower == 0.0)\n {\n *root = x_left ;\n *x_upper = x_left;\n return GSL_SUCCESS;\n }\n \n if (f_upper == 0.0)\n {\n *root = x_right ;\n *x_lower = x_right;\n return GSL_SUCCESS;\n }\n \n /* Draw a line between f(*lower_bound) and f(*upper_bound) and\n note where it crosses the X axis; that's where we will\n split the interval. */\n \n x_linear = x_right - (f_upper * (x_left - x_right) / (f_lower - f_upper));\n\n SAFE_FUNC_CALL (f, x_linear, &f_linear);\n \n if (f_linear == 0.0)\n {\n *root = x_linear;\n *x_lower = x_linear;\n *x_upper = x_linear;\n return GSL_SUCCESS;\n }\n \n /* Discard the half of the interval which doesn't contain the root. */\n \n if ((f_lower > 0.0 && f_linear < 0.0) || (f_lower < 0.0 && f_linear > 0.0))\n {\n *root = x_linear ;\n *x_upper = x_linear;\n state->f_upper = f_linear;\n w = x_linear - x_left ;\n }\n else\n {\n *root = x_linear ;\n *x_lower = x_linear;\n state->f_lower = f_linear;\n w = x_right - x_linear;\n }\n\n if (w < 0.5 * (x_right - x_left)) \n {\n return GSL_SUCCESS ;\n }\n\n x_bisect = 0.5 * (x_left + x_right);\n\n SAFE_FUNC_CALL (f, x_bisect, &f_bisect);\n\n if ((f_lower > 0.0 && f_bisect < 0.0) || (f_lower < 0.0 && f_bisect > 0.0))\n {\n *x_upper = x_bisect;\n state->f_upper = f_bisect;\n if (*root > x_bisect)\n *root = 0.5 * (x_left + x_bisect) ;\n }\n else\n {\n *x_lower = x_bisect;\n state->f_lower = f_bisect;\n if (*root < x_bisect)\n *root = 0.5 * (x_bisect + x_right) ;\n }\n\n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_root_fsolver_type falsepos_type =\n{\"falsepos\", /* name */\n sizeof (falsepos_state_t),\n &falsepos_init,\n &falsepos_iterate};\n\nconst gsl_root_fsolver_type * gsl_root_fsolver_falsepos = &falsepos_type;\n", "meta": {"hexsha": "d264f697a404dc274f981406006441ebfe070d2b", "size": 4651, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/roots/falsepos.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/roots/falsepos.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/roots/falsepos.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.9832402235, "max_line_length": 113, "alphanum_fraction": 0.6493227263, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.6886820360263057}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#define MAX(A,B) (((A)>(B))?(A):(B))\n\nvoid reoshift(gsl_vector *v, int h)\n{\n if ( h > 0 ) {\n gsl_vector *temp = gsl_vector_alloc(v->size);\n gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h);\n gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h);\n gsl_vector_memcpy(&p1.vector, &p.vector);\n p = gsl_vector_subvector(temp, 0, h);\n gsl_vector_set_zero(&p.vector);\n gsl_vector_memcpy(v, temp);\n gsl_vector_free(temp);\n }\n}\n\ngsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r)\n{\n gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL;\n int gn, gt, gd;\n\n if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) {\n nt = gsl_vector_alloc(n->size); assert(nt != NULL);\n dt = gsl_vector_alloc(n->size); assert(dt != NULL);\n rt = gsl_vector_alloc(n->size); assert(rt != NULL);\n d2 = gsl_vector_alloc(n->size); assert(d2 != NULL);\n gsl_vector_memcpy(nt, n);\n gsl_vector_set_zero(dt); gsl_vector_set_zero(rt);\n gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size);\n gsl_vector_memcpy(&p.vector, d);\n gsl_vector_memcpy(d2, dt);\n gn = n->size - 1;\n gd = d->size - 1;\n gt = 0;\n\n while( gsl_vector_get(d, gd) == 0 ) gd--;\n\n while ( gn >= gd ) {\n reoshift(dt, gn-gd);\n double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn);\n gsl_vector_set(rt, gn-gd, v);\n gsl_vector_scale(dt, v);\n gsl_vector_sub(nt, dt);\n gt = MAX(gt, gn-gd);\n while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--;\n gsl_vector_memcpy(dt, d2);\n }\n\n q = gsl_vector_alloc(gt+1); assert(q != NULL);\n p = gsl_vector_subvector(rt, 0, gt+1);\n gsl_vector_memcpy(q, &p.vector);\n if ( r != NULL ) {\n if ( (gn+1) > 0 ) {\n\t*r = gsl_vector_alloc(gn+1); assert( *r != NULL );\n\tp = gsl_vector_subvector(nt, 0, gn+1);\n\tgsl_vector_memcpy(*r, &p.vector);\n } else {\n\t*r = gsl_vector_alloc(1); assert( *r != NULL );\n\tgsl_vector_set_zero(*r);\n }\n }\n gsl_vector_free(nt); gsl_vector_free(dt);\n gsl_vector_free(rt); gsl_vector_free(d2);\n return q;\n } else {\n q = gsl_vector_alloc(1); assert( q != NULL );\n gsl_vector_set_zero(q);\n if ( r != NULL ) {\n *r = gsl_vector_alloc(n->size); assert( *r != NULL );\n gsl_vector_memcpy(*r, n);\n }\n return q;\n }\n}\n\nvoid poly_print(gsl_vector *p)\n{\n int i;\n for(i=p->size-1; i >= 0; i--) {\n if ( i > 0 )\n printf(\"%lfx^%d + \",\n\t gsl_vector_get(p, i), i);\n else\n printf(\"%lf\\n\", gsl_vector_get(p, i));\n }\n}\n\ngsl_vector *create_poly(int d, ...)\n{\n va_list al;\n int i;\n gsl_vector *r = NULL;\n\n va_start(al, d);\n r = gsl_vector_alloc(d); assert( r != NULL );\n\n for(i=0; i < d; i++)\n gsl_vector_set(r, i, va_arg(al, double));\n\n return r;\n}\n", "meta": {"hexsha": "9ecd573fae548736443921b67d25613f7addf351", "size": 2891, "ext": "c", "lang": "C", "max_stars_repo_path": "lang/C/polynomial-long-division-1.c", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_issues_repo_path": "lang/C/polynomial-long-division-1.c", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C/polynomial-long-division-1.c", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 26.7685185185, "max_line_length": 71, "alphanum_fraction": 0.5849187132, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6884225433835369}} {"text": "#include \r\n\r\n#include \r\n#include \r\n\r\n#include \"regional.h\"\r\n\r\nvoid init_weights(t_stochasticity_grid *g) {\r\n /* The weights will be normalized s.t. the sum of squared weights is one */\r\n g->weights[0] = 1.0;\r\n double sum = 1.0;\r\n for (int i = 1; idepth; i++) {\r\n double val = g->weights[i-1] / g->weight_factor;\r\n g->weights[i] = val;\r\n sum += val*val;\r\n }\r\n double N = sqrt(sum);\r\n for (int i = 0; i < g->depth; i++) {\r\n g->weights[i] /= N;\r\n }\r\n}\r\n\r\n/*\r\n 'arr' should point to a double array of size at least height*width.\r\n*/\r\nt_stochasticity_grid *create_stochasticity_grid(double *arr, int height, int width, double weight_factor, double mean, double stddev, long int seed) {\r\n t_stochasticity_grid *g = malloc( sizeof(t_stochasticity_grid) );\r\n g->arr = arr;\r\n g->height = height;\r\n g->width = width;\r\n\r\n /* It is best to use array dimensions of power of 2 */\r\n\r\n int d = height > width ? height : width; // Take the max \r\n g->depth = ceil(log2(d)) + 1;\r\n g->stddev = stddev;\r\n g->mean = mean;\r\n g->weight_factor = weight_factor;\r\n\r\n g->rng = gsl_rng_alloc(gsl_rng_mt19937);\r\n gsl_rng_set(g->rng, seed);\r\n\r\n g->weights = malloc( sizeof(double) * g->depth );\r\n init_weights(g);\r\n\r\n return g;\r\n}\r\n\r\nvoid free_stochasticity_grid(t_stochasticity_grid *g) {\r\n gsl_rng_free(g->rng);\r\n free(g->weights);\r\n g->weights = NULL;\r\n g->arr = NULL; \r\n free(g);\r\n}\r\n\r\nstatic inline double gaussian(const gsl_rng *rng, double stddev) {\r\n return gsl_ran_gaussian_ziggurat(rng, stddev);\r\n}\r\n\r\nvoid fill_quadrant(const t_stochasticity_grid *g, int y0, int x0, int y1, int x1, int level) {\r\n double weight = g->weights[level];\r\n double rval = gaussian(g->rng, g->stddev);\r\n for(int i = y0; i < y1; i++) {\r\n for(int j = x0; j < x1; j++) {\r\n int offset = i * g->width + j;\r\n double val = rval*weight;\r\n g->arr[offset] += val;\r\n }\r\n }\r\n}\r\n\r\nvoid recursive_division(const t_stochasticity_grid *g, int level, int y0, int x0, int y1, int x1) {\r\n if (level >= g->depth) return;\r\n if (x1-x0 == 1 && y1-y0 == 1) return; // Skip 1x1 grids\r\n\r\n if (y0 >= y1) return;\r\n if (x0 >= x1) return; \r\n //printf(\"Depth: %i. (%i, %i, %i, %i)\\n\", level, y0, x0, y1, x1);\r\n\r\n fill_quadrant(g, y0, x0, y1, x1, level);\r\n\r\n if (level + 1 == g->depth) return; // Avoid unnecessary recursion; skip level with 1x1 grids\r\n\r\n int ydist = (y1-y0)/2.0 + 0.5;\r\n int xdist = (x1-x0)/2.0 + 0.5;\r\n int ymid = y0+ydist;\r\n int xmid = x0+xdist;\r\n\r\n /* Upper left */\r\n recursive_division(g, level+1, y0, x0, ymid, xmid);\r\n\r\n /* Upper right */\r\n recursive_division(g, level+1, ymid, x0, y1, xmid);\r\n\r\n /* Bottom left */\r\n recursive_division(g, level+1, y0, xmid, ymid, x1);\r\n\r\n /* Bottom right */\r\n recursive_division(g, level+1, ymid, xmid, y1, x1);\r\n}\r\n\r\n/**\r\n Generate spatially autocorrelated coefficients using a recursive quadtree subdivision. \r\n The pointer 'arr' is a 2-dimensional output array of size 'height' * 'width'. \r\n The variable 'variance' gives the variance of the log-norm distribution with mean and cut-off at 1.0.\r\n*/\r\nvoid generate_stochasticity(t_stochasticity_grid *g) {\r\n /* Initialize the array by generating the last level (i.e., 1x1 grids) */\r\n for(int i = 0; i < g->height; i++) {\r\n for(int j = 0; j < g->width; j++) {\r\n double weight = g->weights[g->depth-1];\r\n g->arr[i*g->width + j] = weight*gaussian(g->rng, g->stddev);\r\n }\r\n }\r\n\r\n recursive_division(g, 0, 0, 0, g->height, g->width);\r\n\r\n for(int i = 0; i < g->height; i++) {\r\n for(int j = 0; j < g->width; j++) {\r\n double y = g->arr[i*g->width + j];\r\n y = exp(y + g->mean);\r\n if (y > 1.0) y = 1.0;\r\n g->arr[i*g->width + j] = y;\r\n }\r\n }\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "b873455e0f118fa1d6d577cfa59ee13101e2e346", "size": 3961, "ext": "c", "lang": "C", "max_stars_repo_path": "passive/spom/model/src/regional.c", "max_stars_repo_name": "rybicki/corridor-spom", "max_stars_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "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": "passive/spom/model/src/regional.c", "max_issues_repo_name": "rybicki/corridor-spom", "max_issues_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "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": "passive/spom/model/src/regional.c", "max_forks_repo_name": "rybicki/corridor-spom", "max_forks_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070", "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.4692307692, "max_line_length": 151, "alphanum_fraction": 0.5639989902, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6875560917017753}} {"text": "/* randist/nbinomial.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The negative binomial distribution has the form,\n\n prob(k) = Gamma(n + k)/(Gamma(n) Gamma(k + 1)) p^n (1-p)^k \n\n for k = 0, 1, ... . Note that n does not have to be an integer.\n\n This is the Leger's algorithm (given in the answers in Knuth) */\n\nunsigned int\ngsl_ran_negative_binomial (const gsl_rng * r, double p, double n)\n{\n double X = gsl_ran_gamma (r, n, 1.0) ;\n unsigned int k = gsl_ran_poisson (r, X*(1-p)/p) ;\n return k ;\n}\n\ndouble\ngsl_ran_negative_binomial_pdf (const unsigned int k, const double p, double n)\n{\n double P;\n\n double f = gsl_sf_lngamma (k + n) ;\n double a = gsl_sf_lngamma (n) ;\n double b = gsl_sf_lngamma (k + 1.0) ;\n\n P = exp(f-a-b) * pow (p, n) * pow (1 - p, (double)k);\n \n return P;\n}\n", "meta": {"hexsha": "7542f360e5e5610201189e2a6e6a4e94fda36e99", "size": 1691, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/randist/nbinomial.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/randist/nbinomial.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/randist/nbinomial.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 30.7454545455, "max_line_length": 81, "alphanum_fraction": 0.6901241869, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7879312031126512, "lm_q1q2_score": 0.6873497112325335}} {"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 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/* Modified for standalone use in polynomial directory, B.Gough 2001 */\n\n#include \n#include \n#include \n\nint\ngsl_poly_dd_init (double dd[], const double xa[], const double ya[],\n size_t size)\n{\n size_t i, j;\n\n /* Newton's divided differences */\n\n dd[0] = ya[0];\n\n for (j = size - 1; j >= 1; j--)\n {\n dd[j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]);\n }\n\n for (i = 2; i < size; i++)\n {\n for (j = size - 1; j >= i; j--)\n {\n dd[j] = (dd[j] - dd[j - 1]) / (xa[j] - xa[j - i]);\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_poly_dd_taylor (double c[], double xp, \n const double dd[], const double xa[], size_t size,\n double w[])\n{\n size_t i, j;\n\n for (i = 0; i < size; i++)\n {\n c[i] = 0.0;\n w[i] = 0.0;\n }\n\n w[size - 1] = 1.0;\n\n c[0] = dd[0];\n\n for (i = size - 1; i-- > 0;)\n {\n w[i] = -w[i + 1] * (xa[size - 2 - i] - xp);\n\n for (j = i + 1; j < size - 1; j++)\n {\n w[j] = w[j] - w[j + 1] * (xa[size - 2 - i] - xp);\n }\n\n for (j = i; j < size; j++)\n {\n c[j - i] += w[j] * dd[size - i - 1];\n }\n }\n\n return GSL_SUCCESS;\n} \n", "meta": {"hexsha": "54f8024cff1af884d912c354e1aafcf3e12f96cd", "size": 2042, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/poly/dd.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/poly/dd.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/poly/dd.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": 23.7441860465, "max_line_length": 81, "alphanum_fraction": 0.5396669931, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6870154673873112}} {"text": "#include \n#include \n#include \n\nint\nmain (void)\n{\n double data[] = { -1.0, 1.0, -1.0, 1.0,\n -8.0, 4.0, -2.0, 1.0,\n 27.0, 9.0, 3.0, 1.0,\n 64.0, 16.0, 4.0, 1.0 };\n\n gsl_matrix_view m \n = gsl_matrix_view_array (data, 4, 4);\n\n gsl_vector_complex *eval = gsl_vector_complex_alloc (4);\n gsl_matrix_complex *evec = gsl_matrix_complex_alloc (4, 4);\n\n gsl_eigen_nonsymmv_workspace * w = \n gsl_eigen_nonsymmv_alloc (4);\n \n gsl_eigen_nonsymmv (&m.matrix, eval, evec, w);\n\n gsl_eigen_nonsymmv_free (w);\n\n gsl_eigen_nonsymmv_sort (eval, evec, \n GSL_EIGEN_SORT_ABS_DESC);\n \n {\n int i, j;\n\n for (i = 0; i < 4; i++)\n {\n gsl_complex eval_i \n = gsl_vector_complex_get (eval, i);\n gsl_vector_complex_view evec_i \n = gsl_matrix_complex_column (evec, i);\n\n printf (\"eigenvalue = %g + %gi\\n\",\n GSL_REAL(eval_i), GSL_IMAG(eval_i));\n printf (\"eigenvector = \\n\");\n for (j = 0; j < 4; ++j)\n {\n gsl_complex z = \n gsl_vector_complex_get(&evec_i.vector, j);\n printf(\"%g + %gi\\n\", GSL_REAL(z), GSL_IMAG(z));\n }\n }\n }\n\n gsl_vector_complex_free(eval);\n gsl_matrix_complex_free(evec);\n\n return 0;\n}\n", "meta": {"hexsha": "eb1a4e59d61d780812a593b5c7fc0d501a9560d3", "size": 1350, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/eigen_nonsymm.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/eigen_nonsymm.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/eigen_nonsymm.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.1071428571, "max_line_length": 61, "alphanum_fraction": 0.5466666667, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380483, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6869024355139762}} {"text": "/**\n *\n * @generated d Tue Jan 7 11:45:26 2014\n *\n **/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"auxiliary.h\"\n\n/*-------------------------------------------------------------------\n * Check the orthogonality of Q\n */\n\nint d_check_orthogonality(int M, int N, int LDQ, double *Q)\n{\n double alpha, beta;\n double normQ;\n int info_ortho;\n int i;\n int minMN = min(M, N);\n double eps;\n double *work = (double *)malloc(minMN*sizeof(double));\n\n eps = LAPACKE_dlamch_work('e');\n alpha = 1.0;\n beta = -1.0;\n\n /* Build the idendity matrix USE DLASET?*/\n double *Id = (double *) malloc(minMN*minMN*sizeof(double));\n memset((void*)Id, 0, minMN*minMN*sizeof(double));\n for (i = 0; i < minMN; i++)\n Id[i*minMN+i] = (double)1.0;\n\n /* Perform Id - Q'Q */\n if (M >= N)\n cblas_dsyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N);\n else\n cblas_dsyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M);\n\n normQ = LAPACKE_dlansy_work(LAPACK_COL_MAJOR, 'i', 'u', minMN, Id, minMN, work);\n\n printf(\"============\\n\");\n printf(\"Checking the orthogonality of Q \\n\");\n printf(\"||Id-Q'*Q||_oo / (N*eps) = %e \\n\",normQ/(minMN*eps));\n\n if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) {\n printf(\"-- Orthogonality is suspicious ! \\n\");\n info_ortho=1;\n }\n else {\n printf(\"-- Orthogonality is CORRECT ! \\n\");\n info_ortho=0;\n }\n\n free(work); free(Id);\n\n return info_ortho;\n}\n\n/*------------------------------------------------------------\n * Check the factorization QR\n */\n\nint d_check_QRfactorization(int M, int N, double *A1, double *A2, int LDA, double *Q)\n{\n double Anorm, Rnorm;\n double alpha, beta;\n int info_factorization;\n int i,j;\n double eps;\n\n eps = LAPACKE_dlamch_work('e');\n\n double *Ql = (double *)malloc(M*N*sizeof(double));\n double *Residual = (double *)malloc(M*N*sizeof(double));\n double *work = (double *)malloc(max(M,N)*sizeof(double));\n\n alpha=1.0;\n beta=0.0;\n\n if (M >= N) {\n /* Extract the R */\n double *R = (double *)malloc(N*N*sizeof(double));\n memset((void*)R, 0, N*N*sizeof(double));\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N);\n\n /* Perform Ql=Q*R */\n memset((void*)Ql, 0, M*N*sizeof(double));\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M);\n free(R);\n }\n else {\n /* Extract the L */\n double *L = (double *)malloc(M*M*sizeof(double));\n memset((void*)L, 0, M*M*sizeof(double));\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M);\n\n /* Perform Ql=LQ */\n memset((void*)Ql, 0, M*N*sizeof(double));\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M);\n free(L);\n }\n\n /* Compute the Residual */\n for (i = 0; i < M; i++)\n for (j = 0 ; j < N; j++)\n Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i];\n\n Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work);\n Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, A2, LDA, work);\n\n if (M >= N) {\n printf(\"============\\n\");\n printf(\"Checking the QR Factorization \\n\");\n printf(\"-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n }\n else {\n printf(\"============\\n\");\n printf(\"Checking the LQ Factorization \\n\");\n printf(\"-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n }\n\n if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) {\n printf(\"-- Factorization is suspicious ! \\n\");\n info_factorization = 1;\n }\n else {\n printf(\"-- Factorization is CORRECT ! \\n\");\n info_factorization = 0;\n }\n\n free(work); free(Ql); free(Residual);\n\n return info_factorization;\n}\n\n/*------------------------------------------------------------------------\n * Check the factorization of the matrix A2\n */\n\nint d_check_LLTfactorization(int N, double *A1, double *A2, int LDA, int uplo)\n{\n double Anorm, Rnorm;\n double alpha;\n int info_factorization;\n int i,j;\n double eps;\n\n eps = LAPACKE_dlamch_work('e');\n\n double *Residual = (double *)malloc(N*N*sizeof(double));\n double *L1 = (double *)malloc(N*N*sizeof(double));\n double *L2 = (double *)malloc(N*N*sizeof(double));\n double *work = (double *)malloc(N*sizeof(double));\n\n memset((void*)L1, 0, N*N*sizeof(double));\n memset((void*)L2, 0, N*N*sizeof(double));\n\n alpha= 1.0;\n\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N);\n\n /* Dealing with L'L or U'U */\n if (uplo == PlasmaUpper){\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N);\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N);\n cblas_dtrmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N);\n }\n else{\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N);\n LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N);\n cblas_dtrmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N);\n }\n\n /* Compute the Residual || A -L'L|| */\n for (i = 0; i < N; i++)\n for (j = 0; j < N; j++)\n Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i];\n\n Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work);\n Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work);\n\n printf(\"============\\n\");\n printf(\"Checking the Cholesky Factorization \\n\");\n printf(\"-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n\n if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){\n printf(\"-- Factorization is suspicious ! \\n\");\n info_factorization = 1;\n }\n else{\n printf(\"-- Factorization is CORRECT ! \\n\");\n info_factorization = 0;\n }\n\n free(Residual); free(L1); free(L2); free(work);\n\n return info_factorization;\n}\n\n/*--------------------------------------------------------------\n * Check the gemm\n */\ndouble d_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n double alpha, double *A, int LDA,\n double *B, int LDB,\n double beta, double *Cplasma,\n double *Cref, int LDC,\n double *Cinitnorm, double *Cplasmanorm, double *Clapacknorm )\n{\n double beta_const = -1.0;\n double Rnorm;\n double *work = (double *)malloc(max(K,max(M, N))* sizeof(double));\n\n *Cinitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n *Cplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work);\n\n cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K,\n (alpha), A, LDA, B, LDB, (beta), Cref, LDC);\n\n *Clapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n cblas_daxpy(LDC * N, (beta_const), Cplasma, 1, Cref, 1);\n\n Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the trsm\n */\ndouble d_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag,\n int M, int NRHS, double alpha,\n double *A, int LDA,\n double *Bplasma, double *Bref, int LDB,\n double *Binitnorm, double *Bplasmanorm, double *Blapacknorm )\n{\n double beta_const = -1.0;\n double Rnorm;\n double *work = (double *)malloc(max(M, NRHS)* sizeof(double));\n /*double eps = LAPACKE_dlamch_work('e');*/\n\n *Binitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work);\n *Bplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work);\n\n cblas_dtrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, NRHS,\n (alpha), A, LDA, Bref, LDB);\n\n *Blapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n\n cblas_daxpy(LDB * NRHS, (beta_const), Bplasma, 1, Bref, 1);\n\n Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n Rnorm = Rnorm / *Blapacknorm; \n /* max(M,NRHS) * eps);*/\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the solution\n */\n\ndouble d_check_solution(int M, int N, int NRHS, double *A, int LDA,\n double *B, double *X, int LDB,\n double *anorm, double *bnorm, double *xnorm )\n{\n/* int info_solution; */\n double Rnorm = -1.00;\n double zone = 1.0;\n double mzone = -1.0;\n double *work = (double *)malloc(max(M, N)* sizeof(double));\n\n *anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work);\n *xnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work);\n *bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB);\n\n Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n free(work);\n\n return Rnorm;\n}\n", "meta": {"hexsha": "d876b72ad494500510399d6ecf8357313efe0f91", "size": 9711, "ext": "c", "lang": "C", "max_stars_repo_path": "timing/dauxiliary.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timing/dauxiliary.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "timing/dauxiliary.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": 32.5872483221, "max_line_length": 114, "alphanum_fraction": 0.5562763876, "num_tokens": 3153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6867917314264335}} {"text": "#include \n#include \n#include \n#include \n#include \"SimulationSteps.h\"\n#include \n#include \n\nvoid eval_NUBspline_1d_d(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val);\n\nvoid eval_NUBspline_1d_d_vg(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val, double* restrict grad);\n\nvoid eval_NUBspline_1d_d_vgl(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val, double* restrict grad, double* restrict lapl);\n\n\nvoid InterpolateWithSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* NodalX, double *func, double *NodalFunc, double* NodalDeriv)\n{\n\n\tNUgrid* myGrid = create_general_grid(x, NumPointsToInterpolate);\n\tBCtype_d myBC;\n\tmyBC.lCode = NATURAL;\n\tmyBC.rCode = NATURAL;\n\tNUBspline_1d_d *mySpline = create_NUBspline_1d_d(myGrid, myBC, func);\n\tfor(int i =0; i < NumPointsToEvaluate; i++)\n\t{\n\t\tif (NodalDeriv != NULL)\n\t\t\teval_NUBspline_1d_d_vg(mySpline, NodalX[i], &NodalFunc[i], &NodalDeriv[i]);\n\t\telse\n\t\t\teval_NUBspline_1d_d(mySpline, NodalX[i], &NodalFunc[i]);\n\t}\n\n}\n\nvoid InterpolateWithGSLSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* NodalX, double* func, double* NodalFunc, double* NodalDeriv)\n{\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n\tgsl_spline* spline = gsl_spline_alloc(gsl_interp_cspline, NumPointsToInterpolate);\n\tgsl_spline_init(spline, x, func, NumPointsToInterpolate);\n\n\tfor(int j = 0; j < NumPointsToEvaluate; j++)\n\t{\n\t\tNodalFunc[j] = gsl_spline_eval(spline, NodalX[j], acc);\n\t\tif (NodalDeriv != NULL)\n\t\t\tNodalDeriv[j] = gsl_spline_eval_deriv(spline, NodalX[j], acc);\n\t}\n\n}\n", "meta": {"hexsha": "bcde33b00f2dac74ed0a3515b1de3aa2c23869ed", "size": 1684, "ext": "c", "lang": "C", "max_stars_repo_path": "1DCode/SplineInterpolation.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/SplineInterpolation.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/SplineInterpolation.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": 33.0196078431, "max_line_length": 163, "alphanum_fraction": 0.7583135392, "num_tokens": 547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6859707483104235}} {"text": "#pragma once\n\n#include \"shapes3D.h\"\n\n#include \n\n\nnamespace ad {\n\n\ntemplate \nstd::vector make_pyramid(float aBaseRadius, float aHeight)\n{\n std::vector result;\n // There are twice the number of edges in the pyramid, each edge being two vertices\n constexpr std::size_t ElementsCount{N_baseEdges*2*2};\n result.reserve(ElementsCount);\n\n Vec<3> topPosition = {0.0f, 0.0f, aHeight};\n\n auto getBasePosition = [](int aId, float aRadius) -> Vec<3>\n {\n return {\n std::cos(2*pi<>*aId/N_baseEdges) * aRadius,\n std::sin(2*pi<>*aId/N_baseEdges) * aRadius,\n 0.0f,\n };\n };\n\n Vec<3> position_prev = getBasePosition(-1, aBaseRadius);\n for(int i=0; i position_a = getBasePosition(i, aBaseRadius);\n Vec<3> position_b = getBasePosition(i+1, aBaseRadius);\n\n // The base segment\n {\n // The normal of BA vector (not AB)\n Vec<3> ba = (position_a - position_b).normalize();\n Vec<3> base_normal = {-ba.y(), ba.x(), 0.0f};\n\n result.emplace_back(vertex3D::Data{{position_a}, {base_normal}});\n result.emplace_back(vertex3D::Data{{position_b}, {base_normal}});\n }\n\n // The segment connecting base vertex \"i\" to the top\n {\n float teta = std::atan(aBaseRadius/aHeight); // angle between Z and a side edge\n Vec<3> b_prev = (position_prev - position_b).normalize();\n Vec<3> side_normal = {\n -b_prev.y() * std::cos(teta),\n b_prev.x() * std::cos(teta),\n std::sin(teta),\n };\n result.emplace_back(vertex3D::Data{{position_a}, {side_normal}});\n result.emplace_back(vertex3D::Data{{topPosition}, {side_normal}});\n }\n\n position_prev = position_a;\n }\n\n Expects(result.size() == ElementsCount);\n return result;\n}\n\n} // namespace ad\n", "meta": {"hexsha": "e0360f39230f262503d8906709f275c4baeeb447", "size": 1992, "ext": "h", "lang": "C", "max_stars_repo_path": "src/app/shmurp/Shaper.h", "max_stars_repo_name": "FranzPoize/shmurp", "max_stars_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T08:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T08:48:31.000Z", "max_issues_repo_path": "src/app/shmurp/Shaper.h", "max_issues_repo_name": "FranzPoize/shmurp", "max_issues_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "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/app/shmurp/Shaper.h", "max_forks_repo_name": "FranzPoize/shmurp", "max_forks_repo_head_hexsha": "354a70fd89d0cdd9b4336961ad01d1567ac22474", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-31T13:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T13:17:54.000Z", "avg_line_length": 29.7313432836, "max_line_length": 91, "alphanum_fraction": 0.5813253012, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6858742458247926}} {"text": "/* fit/linear.c\n * \n * Copyright (C) 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\n/* Fit the data (x_i, y_i) to the linear relationship \n\n Y = c0 + c1 x\n\n returning, \n\n c0, c1 -- coefficients\n cov00, cov01, cov11 -- variance-covariance matrix of c0 and c1,\n sumsq -- sum of squares of residuals \n\n This fit can be used in the case where the errors for the data are\n uknown, but assumed equal for all points. The resulting\n variance-covariance matrix estimates the error in the coefficients\n from the observed variance of the points around the best fit line.\n*/\n\nint\ngsl_fit_linear (const double *x, const size_t xstride,\n const double *y, const size_t ystride,\n const size_t n,\n double *c0, double *c1,\n double *cov_00, double *cov_01, double *cov_11, double *sumsq)\n{\n double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n m_x += (x[i * xstride] - m_x) / (i + 1.0);\n m_y += (y[i * ystride] - m_y) / (i + 1.0);\n }\n\n for (i = 0; i < n; i++)\n {\n const double dx = x[i * xstride] - m_x;\n const double dy = y[i * ystride] - m_y;\n\n m_dx2 += (dx * dx - m_dx2) / (i + 1.0);\n m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);\n }\n\n /* In terms of y = a + b x */\n\n {\n double s2 = 0, d2 = 0;\n double b = m_dxdy / m_dx2;\n double a = m_y - m_x * b;\n\n *c0 = a;\n *c1 = b;\n\n /* Compute chi^2 = \\sum (y_i - (a + b * x_i))^2 */\n\n for (i = 0; i < n; i++)\n {\n const double dx = x[i * xstride] - m_x;\n const double dy = y[i * ystride] - m_y;\n const double d = dy - b * dx;\n d2 += d * d;\n }\n\n s2 = d2 / (n - 2.0); /* chisq per degree of freedom */\n\n *cov_00 = s2 * (1.0 / n) * (1 + m_x * m_x / m_dx2);\n *cov_11 = s2 * 1.0 / (n * m_dx2);\n\n *cov_01 = s2 * (-m_x) / (n * m_dx2);\n\n *sumsq = d2;\n }\n\n return GSL_SUCCESS;\n}\n\n\n/* Fit the weighted data (x_i, w_i, y_i) to the linear relationship \n\n Y = c0 + c1 x\n\n returning, \n\n c0, c1 -- coefficients\n s0, s1 -- the standard deviations of c0 and c1,\n r -- the correlation coefficient between c0 and c1,\n chisq -- weighted sum of squares of residuals */\n\nint\ngsl_fit_wlinear (const double *x, const size_t xstride,\n const double *w, const size_t wstride,\n const double *y, const size_t ystride,\n const size_t n,\n double *c0, double *c1,\n double *cov_00, double *cov_01, double *cov_11,\n double *chisq)\n{\n\n /* compute the weighted means and weighted deviations from the means */\n\n /* wm denotes a \"weighted mean\", wm(f) = (sum_i w_i f_i) / (sum_i w_i) */\n\n double W = 0, wm_x = 0, wm_y = 0, wm_dx2 = 0, wm_dxdy = 0;\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n W += wi;\n wm_x += (x[i * xstride] - wm_x) * (wi / W);\n wm_y += (y[i * ystride] - wm_y) * (wi / W);\n }\n }\n\n W = 0; /* reset the total weight */\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n const double dx = x[i * xstride] - wm_x;\n const double dy = y[i * ystride] - wm_y;\n\n W += wi;\n wm_dx2 += (dx * dx - wm_dx2) * (wi / W);\n wm_dxdy += (dx * dy - wm_dxdy) * (wi / W);\n }\n }\n\n /* In terms of y = a + b x */\n\n {\n double d2 = 0;\n double b = wm_dxdy / wm_dx2;\n double a = wm_y - wm_x * b;\n\n *c0 = a;\n *c1 = b;\n\n *cov_00 = (1 / W) * (1 + wm_x * wm_x / wm_dx2);\n *cov_11 = 1 / (W * wm_dx2);\n\n *cov_01 = -wm_x / (W * wm_dx2);\n\n /* Compute chi^2 = \\sum w_i (y_i - (a + b * x_i))^2 */\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n const double dx = x[i * xstride] - wm_x;\n const double dy = y[i * ystride] - wm_y;\n const double d = dy - b * dx;\n d2 += wi * d * d;\n }\n }\n\n *chisq = d2;\n }\n\n return GSL_SUCCESS;\n}\n\n\n\nint\ngsl_fit_linear_est (const double x,\n const double c0, const double c1,\n const double c00, const double c01, const double c11,\n double *y, double *y_err)\n{\n *y = c0 + c1 * x;\n *y_err = sqrt (c00 + x * (2 * c01 + c11 * x));\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_fit_mul (const double *x, const size_t xstride,\n const double *y, const size_t ystride,\n const size_t n, \n double *c1, double *cov_11, double *sumsq)\n{\n double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n m_x += (x[i * xstride] - m_x) / (i + 1.0);\n m_y += (y[i * ystride] - m_y) / (i + 1.0);\n }\n\n for (i = 0; i < n; i++)\n {\n const double dx = x[i * xstride] - m_x;\n const double dy = y[i * ystride] - m_y;\n\n m_dx2 += (dx * dx - m_dx2) / (i + 1.0);\n m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);\n }\n\n /* In terms of y = b x */\n\n {\n double s2 = 0, d2 = 0;\n double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2);\n\n *c1 = b;\n\n /* Compute chi^2 = \\sum (y_i - b * x_i)^2 */\n\n for (i = 0; i < n; i++)\n {\n const double dx = x[i * xstride] - m_x;\n const double dy = y[i * ystride] - m_y;\n const double d = (m_y - b * m_x) + dy - b * dx;\n d2 += d * d;\n }\n\n s2 = d2 / (n - 1.0); /* chisq per degree of freedom */\n\n *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2));\n\n *sumsq = d2;\n }\n\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_fit_wmul (const double *x, const size_t xstride,\n const double *w, const size_t wstride,\n const double *y, const size_t ystride,\n const size_t n, \n double *c1, double *cov_11, double *chisq)\n{\n\n /* compute the weighted means and weighted deviations from the means */\n\n /* wm denotes a \"weighted mean\", wm(f) = (sum_i w_i f_i) / (sum_i w_i) */\n\n double W = 0, wm_x = 0, wm_y = 0, wm_dx2 = 0, wm_dxdy = 0;\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n W += wi;\n wm_x += (x[i * xstride] - wm_x) * (wi / W);\n wm_y += (y[i * ystride] - wm_y) * (wi / W);\n }\n }\n\n W = 0; /* reset the total weight */\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n const double dx = x[i * xstride] - wm_x;\n const double dy = y[i * ystride] - wm_y;\n\n W += wi;\n wm_dx2 += (dx * dx - wm_dx2) * (wi / W);\n wm_dxdy += (dx * dy - wm_dxdy) * (wi / W);\n }\n }\n\n /* In terms of y = b x */\n\n {\n double d2 = 0;\n double b = (wm_x * wm_y + wm_dxdy) / (wm_x * wm_x + wm_dx2);\n\n *c1 = b;\n\n *cov_11 = 1 / (W * (wm_x * wm_x + wm_dx2));\n\n /* Compute chi^2 = \\sum w_i (y_i - b * x_i)^2 */\n\n for (i = 0; i < n; i++)\n {\n const double wi = w[i * wstride];\n\n if (wi > 0)\n {\n const double dx = x[i * xstride] - wm_x;\n const double dy = y[i * ystride] - wm_y;\n const double d = (wm_y - b * wm_x) + (dy - b * dx);\n d2 += wi * d * d;\n }\n }\n\n *chisq = d2;\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_fit_mul_est (const double x, \n const double c1, const double c11, \n double *y, double *y_err)\n{\n *y = c1 * x;\n *y_err = sqrt (c11) * fabs (x);\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "ef5ae5ed055198b360ecfc0889f8646b34705ff7", "size": 8395, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/fit/linear.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/fit/linear.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/fit/linear.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.1930835735, "max_line_length": 81, "alphanum_fraction": 0.4975580703, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6858403315788569}} {"text": "/* interpolation/interp_poly.c\n * \n * Copyright (C) 2001 DAN, HO-JIN\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/* Modified for standalone use in polynomial directory, B.Gough 2001 */\n\n#include \n#include \n#include \n\nint\ngsl_poly_dd_init (double dd[], const double xa[], const double ya[],\n size_t size)\n{\n size_t i, j;\n\n /* Newton's divided differences */\n\n dd[0] = ya[0];\n\n for (j = size - 1; j >= 1; j--)\n {\n dd[j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]);\n }\n\n for (i = 2; i < size; i++)\n {\n for (j = size - 1; j >= i; j--)\n {\n dd[j] = (dd[j] - dd[j - 1]) / (xa[j] - xa[j - i]);\n }\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_poly_dd_taylor (double c[], double xp, \n const double dd[], const double xa[], size_t size,\n double w[])\n{\n size_t i, j;\n\n for (i = 0; i < size; i++)\n {\n c[i] = 0.0;\n w[i] = 0.0;\n }\n\n w[size - 1] = 1.0;\n\n c[0] = dd[0];\n\n for (i = size - 1; i-- > 0;)\n {\n w[i] = -w[i + 1] * (xa[size - 2 - i] - xp);\n\n for (j = i + 1; j < size - 1; j++)\n {\n w[j] = w[j] - w[j + 1] * (xa[size - 2 - i] - xp);\n }\n\n for (j = i; j < size; j++)\n {\n c[j - i] += w[j] * dd[size - i - 1];\n }\n }\n\n return GSL_SUCCESS;\n}\n\n/*\ngsl_poly_dd_hermite_init()\n Compute divided difference representation of data\nfor Hermite polynomial interpolation\n\nInputs: dd - (output) array of size 2*size containing\n divided differences, dd[k] = f[z_0,z_1,...,z_k]\n za - (output) array of size 2*size containing\n z values\n xa - x data\n ya - y data\n dya - dy/dx data\n size - size of xa,ya,dya arrays\n\nReturn: success\n*/\n\nint\ngsl_poly_dd_hermite_init (double dd[], double za[], const double xa[], const double ya[],\n const double dya[], const size_t size)\n{\n const size_t N = 2 * size;\n size_t i, j;\n\n /* Hermite divided differences */\n\n dd[0] = ya[0];\n\n /* compute: dd[j] = f[z_{j-1},z_j] for j \\in [1,N-1] */\n for (j = 0; j < size; ++j)\n {\n za[2*j] = xa[j];\n za[2*j + 1] = xa[j];\n\n if (j != 0)\n {\n dd[2*j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]);\n dd[2*j - 1] = dya[j - 1];\n }\n }\n\n dd[N - 1] = dya[size - 1];\n\n for (i = 2; i < N; i++)\n {\n for (j = N - 1; j >= i; j--)\n {\n dd[j] = (dd[j] - dd[j - 1]) / (za[j] - za[j - i]);\n }\n }\n\n return GSL_SUCCESS;\n} /* gsl_poly_dd_hermite_init() */\n", "meta": {"hexsha": "73b2bf91f908d8224ce9dfd2e722a326b05034e0", "size": 3318, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/poly/dd.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/poly/dd.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/poly/dd.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": 23.5319148936, "max_line_length": 89, "alphanum_fraction": 0.52079566, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6854898520190474}} {"text": "/* integration/integration.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/* Created: [GJ] Tue Apr 23 21:26:53 EDT 1996\n */\n#include \n#include \n#include \n#include \n#include \n#include \n/* #include \"interpolation.h\" */\n#include \n#if 0\n\n\nstatic char * info_string = 0;\n\nvoid set_integ_info(const char * mess)\n{\n if(info_string != 0) free(info_string);\n info_string = 0;\n if(mess != 0) {\n info_string = (char *)malloc((strlen(mess)+1) * sizeof(char));\n strcpy(info_string, mess);\n }\n}\n\n\n/* Integration function for use with open_romberg(). */\n#define FUNC(x) ((*func)(x))\nstatic double midpnt(double (*func)(double), double a, double b, int n)\n{\n double x,tnm,sum,del,ddel;\n static double s;\n static int it;\n int j;\n\n if (n == 1) {\n it=1;\n return (s=(b-a)*FUNC(0.5*(a+b)));\n }\n else {\n tnm=it;\n del=(b-a)/(3.0*tnm);\n ddel=del+del;\n x=a+0.5*del;\n sum=0.0;\n for (j=1;j<=it;j++) {\n sum += FUNC(x);\n x += ddel;\n sum += FUNC(x);\n x += del;\n }\n it *= 3;\n s=(s+(b-a)*sum/tnm)/3.0;\n return s;\n }\n}\n#undef FUNC\n\n\n#define JMAX 10\n#define JMAXP JMAX+1\n#define K 5\ndouble open_romberg(double(*func)(double), double a, double b, double eps)\n{\n int j;\n double ss,dss,h[JMAXP+1],s[JMAXP+1];\n\n h[1]=1.0;\n for (j=1;j<=JMAX;j++) {\n s[j]=midpnt(func,a,b,j);\n if (j >= K) {\n /* local_polint(&h[j-K],&s[j-K],K,0.0,&ss,&dss); */\n interp_poly(&h[j-K]+1,&s[j-K]+1,K,0.0,&ss,&dss);\n if (fabs(dss) < eps * fabs(ss)) return ss;\n }\n s[j+1]=s[j];\n h[j+1]=h[j]/9.0;\n }\n\n push_error(\"open_romberg: too many steps\", Error_ConvFail_);\n push_generic_error(\"open_romberg:\", info_string);\n\n return 0.;\n}\n#undef JMAX\n#undef JMAXP\n#undef K\n\n\ndouble gauss_legendre_10(double (*func)(double), double a, double b)\n{\n int j;\n static double x[] = {0., \n 0.1488743389,\n 0.4333953941,\n 0.6794095682,\n 0.8650633666,\n 0.9739065285};\n static double w[] = {0.,\n 0.2955242247,\n 0.2692667193,\n 0.2190863625,\n 0.1494513491,\n 0.0666713443};\n \n double xm = 0.5 * (b + a);\n double xr = 0.5 * (b - a);\n \n double s = 0.;\n double dx;\n double result;\n \n for(j=1; j<=5; j++){\n dx = xr * x[j];\n s += w[j] * ((*func)(xm+dx) + (*func)(xm-dx));\n }\n result = s * xr;\n \n return result;\n}\n\n\n/************************************************************************\n * *\n * Trapezoid rule. *\n * *\n * The original trapzd() function from the Numerical Recipes worked *\n * by side-effects; it tried to remember the value of the integral *\n * at the current level of refinement. This is REAL BAD, because if *\n * you try to use it to do a double integral you will get a surprise. *\n * You cannot tell which \"integral\" it is remembering. This stems from *\n * the stupid fact that there was only one, essentially global, *\n * variable that was doing this memory job. *\n * *\n * The solution is simple: pass the current refinement to the function *\n * so that it can be remembered by an external environment, making it *\n * easy to avoid confusion. *\n * *\n * So the new-method code-fragment for doing an integral looks like: *\n * *\n * double answer; *\n * for(j=1; j<=M+1; j++) *\n * trapezoid_rule(func, a, b, j, &answer); *\n * *\n ************************************************************************/\nvoid trapezoid_rule(double(*f)(double), double a, double b, int n, double *s)\n{\n double x, tnm, sum, del;\n int it, j;\n\n if(n==1){\n *s = 0.5 * (b-a) * (f(b) + f(a));\n }\n else {\n for(it=1, j=1; j < n-1; j++) it <<= 1;\n tnm = (double) it;\n del = (b-a) / tnm;\n x = a + 0.5 * del;\n \n for(sum=0., j=1; j<=it; j++, x+=del) { sum += f(x); }\n\n *s = 0.5 * (*s + del * sum);\n }\n}\n\n\n/************************************************************************\n * *\n * Trapezoid rule. *\n * This version produces a tracing output. *\n * *\n ************************************************************************/\n#define FUNC(x) ((*func)(x))\n\nvoid test_trapezoid_rule(double(*func)(double), double a, double b, int n,\n double *s)\n{\n double x, tnm, sum, del;\n int it, j;\n\n if(n==1){\n printf(\"t: a= %g b= %g f(a)= %g f(b)= %g\\n\",\n a, b, FUNC(a), FUNC(b));\n }\n\n if(n==1){\n *s = 0.5 * (b-a) * (FUNC(b) + FUNC(a));\n printf(\"s= %g\\n\", *s);\n }\n else {\n for(it=1, j=1; j < n-1; j++) it <<= 1;\n tnm = (double) it;\n del = (b-a) / tnm;\n x = a + 0.5 * del;\n \n for(sum=0., j=1; j<=it; j++, x+=del) sum += FUNC(x);\n\n *s = 0.5 * (*s + del * sum);\n\n printf(\"sum= %g tnm= %g del= %g s= %g\\n\", sum, tnm, del, *s);\n }\n}\n#undef FUNC\n\n\n\n/* This is fixed to use the non-side-effecting version of the\n * trapezoidal rule, as implemented in trapezoid_rule() above.\n * See the discussion there for explanation of the original problem.\n */\n#define JMAX 20\ndouble gsl_integ_simpson(double (*func)(double), double a, double b, double eps)\n{\n int j;\n double s, st, ost, os;\n\n ost = os = -1.e50;\n\n for(j=1; j<=JMAX; j++){\n\n trapezoid_rule(func, a, b, j, &st);\n s = (4.*st - ost) / 3.;\n \n if(fabs(s-os) < eps * fabs(os))\n return s;\n\n os = s;\n ost = st;\n }\n \n GSL_MESSAGE(\"simpson: too many steps\");\n\n return 0.;\n}\n#undef JMAX\n\n\ndouble gsl_integ_simpson_table(const double * x, const double * y, int n)\n{\n int i;\n double result = 0.;\n for(i=0; i\n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, const char *argv[]) {\n // create random input and output data\n int size = 2000;\n gsl_vector *x = gsl_vector_alloc(size);\n gsl_vector *y = gsl_vector_alloc(size);\n for (int i = 0; i < size; i++) {\n double x_tmp = 2 * M_PI / (double)(size - 1) * (double)i - M_PI;\n gsl_vector_set(x, i, x_tmp);\n gsl_vector_set(y, i, sin(x_tmp));\n }\n\n // randomly init weights\n int w_size = 4;\n gsl_vector *w = gsl_vector_alloc(w_size);\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n for (int i = 0; i < w_size; i++) {\n gsl_vector_set(w, i, gsl_ran_gaussian(r, 1.0));\n }\n gsl_rng_free(r);\n\n double learning_rate = 1e-6;\n for(int t = 0; t < 2000; t++) {\n // forward pass, compute predicted y & compute loss\n gsl_vector *y_pred = gsl_vector_alloc(size);\n double loss = 0;\n for (int i = 0; i < size; i++) {\n double w_tmp = gsl_poly_eval(w->data, w_size, gsl_vector_get(x, i));\n gsl_vector_set(y_pred, i, w_tmp);\n loss += gsl_pow_2(gsl_vector_get(y_pred, i) - gsl_vector_get(y, i));\n }\n if (t % 100 == 99) {\n printf(\"t: %d, loss: %.4f\\n\", t, loss);\n }\n\n // compute gradients of w with respect to loss\n gsl_vector *grad_y_pred = gsl_vector_alloc(size);\n gsl_vector_memcpy(grad_y_pred, y_pred);\n gsl_vector_sub(grad_y_pred, y);\n gsl_vector_scale(grad_y_pred, 2);\n gsl_vector *grad_w = gsl_vector_alloc(w_size);\n gsl_vector_set_all(grad_w, 0.0);\n for(int i = 0; i < size; i++) {\n gsl_vector *grad_y_pred_tmp = gsl_vector_alloc(size);\n gsl_vector *x_tmp = gsl_vector_alloc(size);\n \n gsl_vector_set(grad_w, 0, gsl_vector_get(grad_w, 0) + gsl_vector_get(grad_y_pred, i));\n\n gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred);\n gsl_vector_mul(grad_y_pred_tmp, x);\n gsl_vector_set(grad_w, 1, gsl_vector_get(grad_w, 1) + gsl_vector_get(grad_y_pred_tmp, i));\n \n gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred);\n gsl_vector_memcpy(x_tmp, x);\n gsl_vector_mul(x_tmp, x);\n gsl_vector_mul(grad_y_pred_tmp, x_tmp);\n gsl_vector_set(grad_w, 2, gsl_vector_get(grad_w, 2) + gsl_vector_get(grad_y_pred_tmp, i));\n\n gsl_vector_memcpy(grad_y_pred_tmp, grad_y_pred);\n gsl_vector_memcpy(x_tmp, x);\n gsl_vector_mul(x_tmp, x);\n gsl_vector_mul(x_tmp, x);\n gsl_vector_mul(grad_y_pred_tmp, x_tmp);\n gsl_vector_set(grad_w, 3, gsl_vector_get(grad_w, 3) + gsl_vector_get(grad_y_pred_tmp, i));\n \n gsl_vector_free(grad_y_pred_tmp);\n gsl_vector_free(x_tmp);\n }\n\n gsl_vector_scale(grad_w, learning_rate);\n gsl_vector_sub(w, grad_w);\n\n // free\n gsl_vector_free(y_pred);\n gsl_vector_free(grad_y_pred);\n gsl_vector_free(grad_w);\n }\n\n printf(\"Result: y = %.4f + %.4f * x + %.4f * x^2 + %.4f * x^3\\n\", gsl_vector_get(w, 0), gsl_vector_get(w, 1), gsl_vector_get(w, 2), gsl_vector_get(w, 3));\n\n // free\n gsl_vector_free(x);\n gsl_vector_free(y);\n gsl_vector_free(w);\n\n return 0;\n}", "meta": {"hexsha": "cc4e53675a37d4f243ada229d3257fc3a06e22d2", "size": 3641, "ext": "c", "lang": "C", "max_stars_repo_path": "nn-gsl/nn.c", "max_stars_repo_name": "mizu-bai/Data-Science-Demos", "max_stars_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-27T12:01:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-27T12:01:57.000Z", "max_issues_repo_path": "nn-gsl/nn.c", "max_issues_repo_name": "mizu-bai/Data-Science-Demos", "max_issues_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "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": "nn-gsl/nn.c", "max_forks_repo_name": "mizu-bai/Data-Science-Demos", "max_forks_repo_head_hexsha": "be9dd44c7a2d3433faa049e1217969d08dbac432", "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.3495145631, "max_line_length": 158, "alphanum_fraction": 0.6094479539, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6847830877057347}} {"text": "/* cdf/exponential.c\n * \n * Copyright (C) 2003, 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\n/* The exponential distribution has the form\n\n p(x) dx = exp(-x/mu) dx/mu\n\n for x = 0 ... +infty */\n\ndouble\ngsl_cdf_exponential_P (const double x, const double mu)\n{\n if (x < 0)\n {\n return 0;\n }\n else\n {\n double P = -expm1 (-x / mu);\n\n return P;\n }\n}\n\ndouble\ngsl_cdf_exponential_Q (const double x, const double mu)\n{\n if (x < 0)\n {\n return 1;\n }\n else\n {\n double Q = exp (-x / mu);\n\n return Q;\n }\n}\n", "meta": {"hexsha": "d6d822617c2adfbcf5ca3626c48266bcfc1169c9", "size": 1345, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/cdf/exponential.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/cdf/exponential.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/cdf/exponential.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 22.4166666667, "max_line_length": 81, "alphanum_fraction": 0.6579925651, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.684783083049488}} {"text": "/* specfunc/gsl_sf_legendre.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_LEGENDRE_H__\n#define __GSL_SF_LEGENDRE_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/* P_l(x) l >= 0; |x| <= 1\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Pl_e(const int l, const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_Pl(const int l, const double x);\n\n\n/* P_l(x) for l=0,...,lmax; |x| <= 1\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Pl_array(\n const int lmax, const double x,\n double * result_array\n );\n\n\n/* P_l(x) and P_l'(x) for l=0,...,lmax; |x| <= 1\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Pl_deriv_array(\n const int lmax, const double x,\n double * result_array,\n double * result_deriv_array\n );\n\n\n/* P_l(x), l=1,2,3\n *\n * exceptions: none\n */\nint gsl_sf_legendre_P1_e(double x, gsl_sf_result * result);\nint gsl_sf_legendre_P2_e(double x, gsl_sf_result * result);\nint gsl_sf_legendre_P3_e(double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_P1(const double x);\ndouble gsl_sf_legendre_P2(const double x);\ndouble gsl_sf_legendre_P3(const double x);\n\n\n/* Q_0(x), x > -1, x != 1\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Q0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_Q0(const double x);\n\n\n/* Q_1(x), x > -1, x != 1\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Q1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_Q1(const double x);\n\n\n/* Q_l(x), x > -1, x != 1, l >= 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_Ql_e(const int l, const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_Ql(const int l, const double x);\n\n\n/* P_l^m(x) m >= 0; l >= m; |x| <= 1.0\n *\n * Note that this function grows combinatorially with l.\n * Therefore we can easily generate an overflow for l larger\n * than about 150.\n *\n * There is no trouble for small m, but when m and l are both large,\n * then there will be trouble. Rather than allow overflows, these\n * functions refuse to calculate when they can sense that l and m are\n * too big.\n *\n * If you really want to calculate a spherical harmonic, then DO NOT\n * use this. Instead use legendre_sphPlm() below, which uses a similar\n * recursion, but with the normalized functions.\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_legendre_Plm_e(const int l, const int m, const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_Plm(const int l, const int m, const double x);\n\n\n/* P_l^m(x) m >= 0; l >= m; |x| <= 1.0\n * l=|m|,...,lmax\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_legendre_Plm_array(\n const int lmax, const int m, const double x,\n double * result_array\n );\n\n\n/* P_l^m(x) and d(P_l^m(x))/dx; m >= 0; lmax >= m; |x| <= 1.0\n * l=|m|,...,lmax\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_legendre_Plm_deriv_array(\n const int lmax, const int m, const double x,\n double * result_array,\n double * result_deriv_array\n );\n\n\n/* P_l^m(x), normalized properly for use in spherical harmonics\n * m >= 0; l >= m; |x| <= 1.0\n *\n * There is no overflow problem, as there is for the\n * standard normalization of P_l^m(x).\n *\n * Specifically, it returns:\n *\n * sqrt((2l+1)/(4pi)) sqrt((l-m)!/(l+m)!) P_l^m(x)\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_sphPlm_e(const int l, int m, const double x, gsl_sf_result * result);\ndouble gsl_sf_legendre_sphPlm(const int l, const int m, const double x);\n\n\n/* sphPlm(l,m,x) values\n * m >= 0; l >= m; |x| <= 1.0\n * l=|m|,...,lmax\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_sphPlm_array(\n const int lmax, int m, const double x,\n double * result_array\n );\n\n\n/* sphPlm(l,m,x) and d(sphPlm(l,m,x))/dx values\n * m >= 0; l >= m; |x| <= 1.0\n * l=|m|,...,lmax\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_sphPlm_deriv_array(\n const int lmax, const int m, const double x,\n double * result_array,\n double * result_deriv_array\n );\n\n\n\n/* size of result_array[] needed for the array versions of Plm\n * (lmax - m + 1)\n */\nint gsl_sf_legendre_array_size(const int lmax, const int m);\n\n/* Irregular Spherical Conical Function\n * P^{1/2}_{-1/2 + I lambda}(x)\n *\n * x > -1.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_half_e(const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_half(const double lambda, const double x);\n\n\n/* Regular Spherical Conical Function\n * P^{-1/2}_{-1/2 + I lambda}(x)\n *\n * x > -1.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_mhalf_e(const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_mhalf(const double lambda, const double x);\n\n\n/* Conical Function\n * P^{0}_{-1/2 + I lambda}(x)\n *\n * x > -1.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_0_e(const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_0(const double lambda, const double x);\n\n\n/* Conical Function\n * P^{1}_{-1/2 + I lambda}(x)\n *\n * x > -1.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_1_e(const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_1(const double lambda, const double x);\n\n\n/* Regular Spherical Conical Function\n * P^{-1/2-l}_{-1/2 + I lambda}(x)\n *\n * x > -1.0, l >= -1\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_sph_reg_e(const int l, const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_sph_reg(const int l, const double lambda, const double x);\n\n\n/* Regular Cylindrical Conical Function\n * P^{-m}_{-1/2 + I lambda}(x)\n *\n * x > -1.0, m >= -1\n * exceptions: GSL_EDOM\n */\nint gsl_sf_conicalP_cyl_reg_e(const int m, const double lambda, const double x, gsl_sf_result * result);\ndouble gsl_sf_conicalP_cyl_reg(const int m, const double lambda, const double x);\n\n\n/* The following spherical functions are specializations\n * of Legendre functions which give the regular eigenfunctions\n * of the Laplacian on a 3-dimensional hyperbolic space.\n * Of particular interest is the flat limit, which is\n * Flat-Lim := {lambda->Inf, eta->0, lambda*eta fixed}.\n */\n \n/* Zeroth radial eigenfunction of the Laplacian on the\n * 3-dimensional hyperbolic space.\n *\n * legendre_H3d_0(lambda,eta) := sin(lambda*eta)/(lambda*sinh(eta))\n * \n * Normalization:\n * Flat-Lim legendre_H3d_0(lambda,eta) = j_0(lambda*eta)\n *\n * eta >= 0.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_H3d_0_e(const double lambda, const double eta, gsl_sf_result * result);\ndouble gsl_sf_legendre_H3d_0(const double lambda, const double eta);\n\n\n/* First radial eigenfunction of the Laplacian on the\n * 3-dimensional hyperbolic space.\n *\n * legendre_H3d_1(lambda,eta) :=\n * 1/sqrt(lambda^2 + 1) sin(lam eta)/(lam sinh(eta))\n * (coth(eta) - lambda cot(lambda*eta))\n * \n * Normalization:\n * Flat-Lim legendre_H3d_1(lambda,eta) = j_1(lambda*eta)\n *\n * eta >= 0.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_H3d_1_e(const double lambda, const double eta, gsl_sf_result * result);\ndouble gsl_sf_legendre_H3d_1(const double lambda, const double eta);\n\n\n/* l'th radial eigenfunction of the Laplacian on the\n * 3-dimensional hyperbolic space.\n *\n * Normalization:\n * Flat-Lim legendre_H3d_l(l,lambda,eta) = j_l(lambda*eta)\n *\n * eta >= 0.0, l >= 0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_legendre_H3d_e(const int l, const double lambda, const double eta, gsl_sf_result * result);\ndouble gsl_sf_legendre_H3d(const int l, const double lambda, const double eta);\n\n\n/* Array of H3d(ell), 0 <= ell <= lmax\n */\nint gsl_sf_legendre_H3d_array(const int lmax, const double lambda, const double eta, double * result_array);\n\n/* associated legendre P_{lm} routines */\n\ntypedef enum\n{\n GSL_SF_LEGENDRE_SCHMIDT,\n GSL_SF_LEGENDRE_SPHARM,\n GSL_SF_LEGENDRE_FULL,\n GSL_SF_LEGENDRE_NONE\n} gsl_sf_legendre_t;\n\nint gsl_sf_legendre_array(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n double result_array[]);\nint gsl_sf_legendre_array_e(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n const double csphase,\n double result_array[]);\nint gsl_sf_legendre_deriv_array(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n double result_array[],\n double result_deriv_array[]);\nint gsl_sf_legendre_deriv_array_e(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n const double csphase,\n double result_array[],\n double result_deriv_array[]);\nint gsl_sf_legendre_deriv_alt_array(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n double result_array[],\n double result_deriv_array[]);\nint gsl_sf_legendre_deriv_alt_array_e(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n const double csphase,\n double result_array[],\n double result_deriv_array[]);\nint gsl_sf_legendre_deriv2_array(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n double result_array[],\n double result_deriv_array[],\n double result_deriv2_array[]);\nint gsl_sf_legendre_deriv2_array_e(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n const double csphase,\n double result_array[],\n double result_deriv_array[],\n double result_deriv2_array[]);\nint gsl_sf_legendre_deriv2_alt_array(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n double result_array[],\n double result_deriv_array[],\n double result_deriv2_array[]);\nint gsl_sf_legendre_deriv2_alt_array_e(const gsl_sf_legendre_t norm,\n const size_t lmax, const double x,\n const double csphase,\n double result_array[],\n double result_deriv_array[],\n double result_deriv2_array[]);\nsize_t gsl_sf_legendre_array_n(const size_t lmax);\nsize_t gsl_sf_legendre_array_index(const size_t l, const size_t m);\nsize_t gsl_sf_legendre_nlm(const size_t lmax);\n\n__END_DECLS\n\n#endif /* __GSL_SF_LEGENDRE_H__ */\n", "meta": {"hexsha": "962872aec13cba6f58de97fef1f2c8ff32216d66", "size": 11891, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.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": 31.625, "max_line_length": 108, "alphanum_fraction": 0.6483895383, "num_tokens": 3156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6844256788578625}} {"text": "/* randist/dirichlet.c\n * \n * Copyright (C) 2007 Brian Gough\n * Copyright (C) 2002 Gavin E. Crooks \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\n/* The Dirichlet probability distribution of order K-1 is \n\n p(\\theta_1,...,\\theta_K) d\\theta_1 ... d\\theta_K = \n (1/Z) \\prod_i=1,K \\theta_i^{alpha_i - 1} \\delta(1 -\\sum_i=1,K \\theta_i)\n\n The normalization factor Z can be expressed in terms of gamma functions:\n\n Z = {\\prod_i=1,K \\Gamma(\\alpha_i)} / {\\Gamma( \\sum_i=1,K \\alpha_i)} \n\n The K constants, \\alpha_1,...,\\alpha_K, must be positive. The K parameters, \n \\theta_1,...,\\theta_K are nonnegative and sum to 1.\n\n The random variates are generated by sampling K values from gamma\n distributions with parameters a=\\alpha_i, b=1, and renormalizing. \n See A.M. Law, W.D. Kelton, Simulation Modeling and Analysis (1991).\n\n Gavin E. Crooks (2002)\n*/\n\nstatic void ran_dirichlet_small (const gsl_rng * r, const size_t K, const double alpha[], double theta[]);\n\nvoid\ngsl_ran_dirichlet (const gsl_rng * r, const size_t K,\n const double alpha[], double theta[])\n{\n size_t i;\n double norm = 0.0;\n\n for (i = 0; i < K; i++)\n {\n theta[i] = gsl_ran_gamma (r, alpha[i], 1.0);\n }\n \n for (i = 0; i < K; i++)\n {\n norm += theta[i];\n }\n\n if (norm < GSL_SQRT_DBL_MIN) /* Handle underflow */\n {\n ran_dirichlet_small (r, K, alpha, theta);\n return;\n }\n\n for (i = 0; i < K; i++)\n {\n theta[i] /= norm;\n }\n}\n\n\n/* When the values of alpha[] are small, scale the variates to avoid\n underflow so that the result is not 0/0. Note that the Dirichlet\n distribution is defined by a ratio of gamma functions so we can\n take out an arbitrary factor to keep the values in the range of\n double precision. */\n\nstatic void \nran_dirichlet_small (const gsl_rng * r, const size_t K,\n const double alpha[], double theta[])\n{\n size_t i;\n double norm = 0.0, umax = 0;\n\n for (i = 0; i < K; i++)\n {\n double u = log(gsl_rng_uniform_pos (r)) / alpha[i];\n \n theta[i] = u;\n\n if (u > umax || i == 0) {\n umax = u;\n }\n }\n \n for (i = 0; i < K; i++)\n {\n theta[i] = exp(theta[i] - umax);\n }\n \n for (i = 0; i < K; i++)\n {\n theta[i] = theta[i] * gsl_ran_gamma (r, alpha[i] + 1.0, 1.0);\n }\n\n for (i = 0; i < K; i++)\n {\n norm += theta[i];\n }\n\n for (i = 0; i < K; i++)\n {\n theta[i] /= norm;\n }\n}\n\n\n\n\n\ndouble\ngsl_ran_dirichlet_pdf (const size_t K,\n const double alpha[], const double theta[])\n{\n return exp (gsl_ran_dirichlet_lnpdf (K, alpha, theta));\n}\n\ndouble\ngsl_ran_dirichlet_lnpdf (const size_t K,\n const double alpha[], const double theta[])\n{\n /*We calculate the log of the pdf to minimize the possibility of overflow */\n size_t i;\n double log_p = 0.0;\n double sum_alpha = 0.0;\n\n for (i = 0; i < K; i++)\n {\n log_p += (alpha[i] - 1.0) * log (theta[i]);\n }\n\n for (i = 0; i < K; i++)\n {\n sum_alpha += alpha[i];\n }\n\n log_p += gsl_sf_lngamma (sum_alpha);\n\n for (i = 0; i < K; i++)\n {\n log_p -= gsl_sf_lngamma (alpha[i]);\n }\n\n return log_p;\n}\n", "meta": {"hexsha": "b6c7713e826bba6c694aa25b891e707f0373f3b4", "size": 4077, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/dirichlet.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/dirichlet.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/dirichlet.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.8597560976, "max_line_length": 106, "alphanum_fraction": 0.6060829041, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.754914997895581, "lm_q1q2_score": 0.6839452995157242}} {"text": "#include \n#include \n#include \n#include \n\ndouble w[] = {\t52.21, 53.12, 54.48, 55.84, 57.20,\n\t\t58.57, 59.93, 61.29, 63.11, 64.47,\n\t\t66.28, 68.10, 69.92, 72.19, 74.46 };\ndouble h[] = {\t1.47, 1.50, 1.52, 1.55, 1.57,\n\t\t1.60, 1.63, 1.65, 1.68, 1.70,\n\t\t1.73, 1.75, 1.78, 1.80, 1.83\t};\n\nint main()\n{\n\tint n = sizeof(h)/sizeof(double);\n\tgsl_matrix *X = gsl_matrix_calloc(n, 3);\n\tgsl_vector *Y = gsl_vector_alloc(n);\n\tgsl_vector *beta = gsl_vector_alloc(3);\n\n\tfor (int i = 0; i < n; i++) {\n\t\tgsl_vector_set(Y, i, w[i]);\n\n\t\tgsl_matrix_set(X, i, 0, 1);\n\t\tgsl_matrix_set(X, i, 1, h[i]);\n\t\tgsl_matrix_set(X, i, 2, h[i] * h[i]);\n\t}\n\n\tdouble chisq;\n\tgsl_matrix *cov = gsl_matrix_alloc(3, 3);\n\tgsl_multifit_linear_workspace * wspc = gsl_multifit_linear_alloc(n, 3);\n\tgsl_multifit_linear(X, Y, beta, cov, &chisq, wspc);\n\n\tprintf(\"Beta:\");\n\tfor (int i = 0; i < 3; i++)\n\t\tprintf(\" %g\", gsl_vector_get(beta, i));\n\tprintf(\"\\n\");\n\n\tgsl_matrix_free(X);\n\tgsl_matrix_free(cov);\n\tgsl_vector_free(Y);\n\tgsl_vector_free(beta);\n\tgsl_multifit_linear_free(wspc);\n\n}\n", "meta": {"hexsha": "7e35f5e206e0965dfc454a2c6a3d1ef77241c92b", "size": 1097, "ext": "c", "lang": "C", "max_stars_repo_path": "lang/C/multiple-regression.c", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_issues_repo_path": "lang/C/multiple-regression.c", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C/multiple-regression.c", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 24.3777777778, "max_line_length": 72, "alphanum_fraction": 0.6298997265, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7853085834000791, "lm_q1q2_score": 0.6836875181123167}} {"text": "#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n#include \"haloprofs.h\"\n\ndouble fourierTransformNFW(double k, double m, double rvir, double c)\n{\n double rs,rhos;\n double ukm;\n \n rs = rvir/c;\n rhos = m/4.0/M_PI/rs/rs/rs/(log(1.0+c) - c/(1.0+c));\n \n if(k > 0)\n ukm = 4.0*M_PI*rhos*rs*rs*rs/m\n *(sin(k*rs)*(gsl_sf_Si((1.0+c)*k*rs) - gsl_sf_Si(k*rs)) - sin(c*k*rs)/(1.0+c)/k/rs + cos(k*rs)*(gsl_sf_Ci((1.0+c)*k*rs) - gsl_sf_Ci(k*rs)));\n else\n ukm = 1.0;\n \n return ukm;\n}\n\ndouble NFWprof(double r, double m, double rvir, double c)\n{\n double rs,rhos;\n \n rs = rvir/c;\n rhos = m/4.0/M_PI/rs/rs/rs/(log(1.0+c) - c/(1.0+c));\n \n return rhos/(r/rs)/(1+r/rs)/(1+r/rs);\n}\n\ndouble NFWprof_menc(double r, double m, double rvir, double c)\n{\n double mc = log(1+c) - c/(1.0+c);\n double mr = c*r/rvir;\n mr = log(1.0 + mr) - mr/(1.0+mr);\n \n return mr/mc*m;\n}\n\ninline double _duffy2008_concNFW(double m, double a)\n{\n return 6.71/pow(1.0/a,0.44)*pow(m/2e12,-0.091);\n}\n\ndouble concNFW(double m, double a)\n{\n return _duffy2008_concNFW(m,a);\n}\n\ndouble duffy2008_concNFW(double m, double a)\n{\n return _duffy2008_concNFW(m,a);\n}\n\n/*\ndouble bh2012_concNFW(double m, double a)\n{\n double nu = DELTAC/sigmaMtophat(m,a);\n \n\n}\n\ndouble prada2011_concNFW(double m, double a)\n{\n\n\n}\n*/\n\n\n", "meta": {"hexsha": "5a6efae920394e27870e647fabce371ed8230a4c", "size": 1358, "ext": "c", "lang": "C", "max_stars_repo_path": "src/haloprofs.c", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/haloprofs.c", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/haloprofs.c", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 17.8684210526, "max_line_length": 146, "alphanum_fraction": 0.6200294551, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6834942641640752}} {"text": "/* roots/secant.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* secant.c -- secant root finding algorithm \n\n The secant algorithm is a variant of the Newton algorithm with the\n derivative term replaced by a numerical estimate from the last two\n function evaluations.\n\n x[i+1] = x[i] - f(x[i]) / f'_est\n\n where f'_est = (f(x[i]) - f(x[i-1])) / (x[i] - x[i-1])\n\n The exact derivative is used for the initial value of f'_est.\n\n*/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"roots.h\"\n\ntypedef struct\n {\n double f;\n double df;\n }\nsecant_state_t;\n\nstatic int secant_init (void * vstate, gsl_function_fdf * fdf, double * root);\nstatic int secant_iterate (void * vstate, gsl_function_fdf * fdf, double * root);\n\nstatic int\nsecant_init (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n secant_state_t * state = (secant_state_t *) vstate;\n\n const double x = *root;\n\n GSL_FN_FDF_EVAL_F_DF (fdf, x, &(state->f), &(state->df));\n \n return GSL_SUCCESS;\n\n}\n\nstatic int\nsecant_iterate (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n secant_state_t * state = (secant_state_t *) vstate;\n \n const double x = *root ;\n const double f = state->f;\n const double df = state->df;\n\n double x_new, f_new, df_new;\n\n if (state->df == 0.0)\n {\n GSL_ERROR(\"derivative is zero\", GSL_EZERODIV);\n }\n\n x_new = x - (f / df);\n\n f_new = GSL_FN_FDF_EVAL_F(fdf, x_new) ;\n df_new = (f_new - f) / (x_new - x) ;\n\n *root = x_new ;\n\n state->f = f_new ;\n state->df = df_new ;\n\n if (!finite (f_new))\n {\n GSL_ERROR (\"function value is not finite\", GSL_EBADFUNC);\n }\n\n if (!finite (df_new))\n {\n GSL_ERROR (\"derivative value is not finite\", GSL_EBADFUNC);\n }\n \n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_root_fdfsolver_type secant_type =\n{\"secant\", /* name */\n sizeof (secant_state_t),\n &secant_init,\n &secant_iterate};\n\nconst gsl_root_fdfsolver_type * gsl_root_fdfsolver_secant = &secant_type;\n", "meta": {"hexsha": "c44eea59945de36829fbfb65365125eaab3f7b0a", "size": 2901, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/roots/secant.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/roots/secant.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/roots/secant.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.5847457627, "max_line_length": 81, "alphanum_fraction": 0.6739055498, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6832910810722581}} {"text": "#include \"linearwaves.h\"\n#include \ntypedef struct GSL_params {\n double x;\n int m;\n} GSL_params;\n\n\nvoid init_params(void) {\n\n params.mp = 1e-5;\n params.softening = .6*.05;\n params.softening2 = params.softening*params.softening;\n params.a = 1;\n params.indirect = TRUE;\n return;\n\n}\n\ndouble potential(double phi, double x) {\n double res = -pow(x*x + params.a*params.a + params.softening2 - 2*params.a*x*cos(phi),-.5);\n if (params.indirect) {\n res += cos(phi)*params.a/(x*x);\n }\n return res;\n}\n\ndouble dr_potential(double phi, double x) {\n double res = ( x - params.a*cos(phi)) * pow(x*x + params.a*params.a + params.softening2 - 2*params.a*x*cos(phi),-1.5);\n\n if (params.indirect) {\n res -= 2* cos(phi)*params.a/(x*x*x);\n }\n return res;\n}\n\ndouble dp_potential(double phi, double x) {\n double res = params.a*x*sin(phi)* pow(x*x + params.a*params.a + params.softening2 - 2*params.a*x*cos(phi),-1.5);\n\n if (params.indirect) {\n res += sin(phi)*params.a/(x*x);\n }\n return res;\n}\n\ndouble pfunc(double phi, void *params) {\n GSL_params p = *(GSL_params *)params;\n double x = p.x;\n int m = p.m;\n return cos(m*phi) * potential(phi,x);\n}\ndouble dpfunc(double phi, void *params) {\n GSL_params p = *(GSL_params *)params;\n double x = p.x;\n int m = p.m;\n return cos(m*phi) * dr_potential(phi,x);\n}\n\nvoid force(double x, int m, double complex *res) {\n int nspace = 1000;\n int gsl_order = 5;\n gsl_integration_workspace *w = gsl_integration_workspace_alloc(nspace);\n \n gsl_function F1, F2;\n F1.function = &pfunc;\n F2.function = &dpfunc;\n GSL_params p;\n p.x = x;\n p.m = m;\n F1.params = &p;\n F2.params = &p;\n \n double tol = params.tol;\n double error;\n\n double res_r, dr_res_r;\n gsl_integration_qag(&F1,0,M_PI, tol, tol, nspace, gsl_order , w, &res_r, &error);\n gsl_integration_qag(&F2,0,M_PI, tol, tol, nspace, gsl_order , w, &dr_res_r, &error);\n res_r *= params.mp/M_PI;\n dr_res_r *= params.mp/M_PI;\n\n res[0] = dr_res_r;// *-1;\n res[1] = res_r ;//* -I * m/x;\n res[2] = 0;\n gsl_integration_workspace_free(w); \n return;\n}\n", "meta": {"hexsha": "cd9e4caad627acdccd05fe1050851600772d9e5f", "size": 2203, "ext": "c", "lang": "C", "max_stars_repo_path": "src/planet.c", "max_stars_repo_name": "adamdempsey90/linearwaves", "max_stars_repo_head_hexsha": "6551cb210311962d734dcaae292534fc27ce1490", "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/planet.c", "max_issues_repo_name": "adamdempsey90/linearwaves", "max_issues_repo_head_hexsha": "6551cb210311962d734dcaae292534fc27ce1490", "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/planet.c", "max_forks_repo_name": "adamdempsey90/linearwaves", "max_forks_repo_head_hexsha": "6551cb210311962d734dcaae292534fc27ce1490", "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.0340909091, "max_line_length": 122, "alphanum_fraction": 0.6050839764, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6831076432065584}} {"text": "//\n// Created by Harold on 2020/9/16.\n//\n\n#ifndef M_MATH_M_INTERP_H\n#define M_MATH_M_INTERP_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace M_MATH {\n class Interpolation1D {\n public:\n enum InterpType {\n LINEAR,\n POLYNOMIAL,\n CSPLINE,\n CSPLINE_PERIODIC,\n AKIMA,\n AKIMA_PERIODIC,\n STEFFEN\n };\n\n static bool interpolate(double const* x,\n double const* y,\n size_t length,\n InterpType type,\n double const* n_x,\n size_t n_length,\n double* n_y);\n\n // this will create tmp var inside, better to use former one if possible\n template\n static bool interpolate(IT_X x_begin, IT_X x_end,\n IT_Y y_begin, IT_Y y_end,\n InterpType type,\n IT_NX nx_begin, IT_NX nx_end,\n IT_NY ny_begin);\n\n private:\n static const gsl_interp_type* InterpType2GSL(InterpType type);\n };\n\n class Interpolation2D {\n public:\n enum InterpType {\n BI_LINEAR,\n BI_CUBIC\n };\n\n static bool interpolate(double const* x,\n double const* y,\n double const* z,\n size_t x_length,\n size_t y_length,\n InterpType type,\n double const* n_x,\n double const* n_y,\n size_t n_x_length,\n size_t n_y_length,\n double* n_z);\n\n // this will create tmp var inside, better to use former one if possible\n template\n static bool interpolate(IT_X x_begin, IT_X x_end,\n IT_Y y_begin, IT_Y y_end,\n IT_Z z_begin, IT_Z z_end,\n InterpType type,\n IT_NX nx_begin, IT_NX nx_end,\n IT_NY ny_begin, IT_NY ny_end,\n IT_NZ nz_begin);\n\n private:\n static const gsl_interp2d_type* InterpType2GSL(InterpType type);\n };\n\n const gsl_interp_type *Interpolation1D::InterpType2GSL(Interpolation1D::InterpType type) {\n switch (type) {\n case LINEAR:\n return gsl_interp_linear;\n case POLYNOMIAL:\n return gsl_interp_polynomial;\n case CSPLINE:\n return gsl_interp_cspline;\n case CSPLINE_PERIODIC:\n return gsl_interp_cspline_periodic;\n case AKIMA:\n return gsl_interp_akima;\n case AKIMA_PERIODIC:\n return gsl_interp_akima_periodic;\n case STEFFEN:\n return gsl_interp_steffen;\n }\n return nullptr;\n }\n\n bool Interpolation1D::interpolate(const double *x,\n const double *y,\n size_t length,\n Interpolation1D::InterpType type,\n const double *n_x,\n size_t n_length,\n double* n_y) {\n gsl_spline* spl = gsl_spline_alloc(InterpType2GSL(type), length);\n if (spl == nullptr)\n return false;\n gsl_interp_accel* acc = gsl_interp_accel_alloc();\n if (acc == nullptr) {\n return false;\n }\n gsl_spline_init(spl, x, y, length);\n for (auto i = 0; i < n_length; ++i)\n n_y[i] = gsl_spline_eval(spl, n_x[i], acc);\n gsl_spline_free(spl);\n gsl_interp_accel_free(acc);\n return true;\n }\n\n template\n bool Interpolation1D::interpolate(const IT_X x_begin, const IT_X x_end,\n const IT_Y y_begin, const IT_Y y_end,\n Interpolation1D::InterpType type,\n const IT_NX nx_begin, const IT_NX nx_end,\n IT_NY ny_begin) {\n auto len = std::min(std::distance(x_begin, x_end), std::distance(y_begin, y_end));\n auto n_len = std::distance(nx_begin, nx_end);\n std::vector x_tmp(len), y_tmp(len);\n std::copy(x_begin, x_begin+len, x_tmp.begin());\n std::copy(y_begin, y_begin+len, y_tmp.begin());\n\n gsl_spline* spl = gsl_spline_alloc(InterpType2GSL(type), len);\n if (spl == nullptr)\n return false;\n gsl_interp_accel* acc = gsl_interp_accel_alloc();\n if (acc == nullptr) {\n return false;\n }\n gsl_spline_init(spl, x_tmp.data(), y_tmp.data(), len);\n for (auto i = 0; i < n_len; ++i)\n *(ny_begin+i) = gsl_spline_eval(spl, *(nx_begin+i), acc);\n gsl_spline_free(spl);\n gsl_interp_accel_free(acc);\n return true;\n }\n\n const gsl_interp2d_type *Interpolation2D::InterpType2GSL(Interpolation2D::InterpType type) {\n switch (type) {\n case BI_LINEAR:\n return gsl_interp2d_bilinear;\n case BI_CUBIC:\n return gsl_interp2d_bicubic;\n }\n return nullptr;\n }\n\n bool Interpolation2D::interpolate(const double *x,\n const double *y,\n const double *z,\n size_t x_length,\n size_t y_length,\n Interpolation2D::InterpType type,\n const double *n_x,\n const double *n_y,\n size_t n_x_length,\n size_t n_y_length,\n double *n_z) {\n gsl_spline2d* spl = gsl_spline2d_alloc(InterpType2GSL(type), x_length, y_length);\n if (spl == nullptr)\n return false;\n gsl_interp_accel *x_acc = gsl_interp_accel_alloc();\n if (x_acc == nullptr)\n return false;\n gsl_interp_accel *y_acc = gsl_interp_accel_alloc();\n if (y_acc == nullptr)\n return false;\n // zij = z[j * x_length + i]\n gsl_spline2d_init(spl, x, y, z, x_length, y_length);\n for (auto i = 0; i < n_x_length; ++i)\n for (auto j = 0; j < n_y_length; ++j)\n n_z[j * n_x_length + i] = gsl_spline2d_eval(spl, n_x[i], n_y[j], x_acc, y_acc);\n gsl_spline2d_free(spl);\n gsl_interp_accel_free(x_acc);\n gsl_interp_accel_free(y_acc);\n return true;\n }\n\n template\n bool Interpolation2D::interpolate(const IT_X x_begin, const IT_X x_end,\n const IT_Y y_begin, const IT_Y y_end,\n const IT_Z z_begin, const IT_Z z_end,\n Interpolation2D::InterpType type,\n const IT_NX nx_begin, const IT_NX nx_end,\n const IT_NY ny_begin, const IT_NY ny_end,\n const IT_NZ nz_begin) {\n auto x_length = std::distance(x_begin, x_end);\n auto y_length = std::distance(y_begin, y_end);\n auto z_length = std::distance(z_begin, z_end);\n auto n_x_length = std::distance(nx_begin, nx_end);\n auto n_y_length = std::distance(ny_begin, ny_end);\n std::vector x_tmp(x_length), y_tmp(y_length), z_tmp(z_length);\n std::copy(x_begin, x_end, x_tmp.begin());\n std::copy(y_begin, y_end, y_tmp.begin());\n std::copy(z_begin, z_end, z_tmp.begin());\n\n gsl_spline2d* spl = gsl_spline2d_alloc(InterpType2GSL(type), x_length, y_length);\n if (spl == nullptr)\n return false;\n gsl_interp_accel *x_acc = gsl_interp_accel_alloc();\n if (x_acc == nullptr)\n return false;\n gsl_interp_accel *y_acc = gsl_interp_accel_alloc();\n if (y_acc == nullptr)\n return false;\n // zij = z[j * x_length + i]\n gsl_spline2d_init(spl, x_tmp.data(), y_tmp.data(), z_tmp.data(), x_length, y_length);\n for (auto i = 0; i < n_x_length; ++i)\n for (auto j = 0; j < n_y_length; ++j)\n *(nz_begin + j * n_x_length + i) = gsl_spline2d_eval(spl, *(nx_begin + i), *(ny_begin + j), x_acc, y_acc);\n gsl_spline2d_free(spl);\n gsl_interp_accel_free(x_acc);\n gsl_interp_accel_free(y_acc);\n return true;\n }\n}\n\n#endif //M_MATH_M_INTERP_H\n", "meta": {"hexsha": "50e75a5bc14d2dd71a8e7a7b627669389d13c648", "size": 9326, "ext": "h", "lang": "C", "max_stars_repo_path": "include/m_interp.h", "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_issues_repo_path": "include/m_interp.h", "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_forks_repo_path": "include/m_interp.h", "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "avg_line_length": 40.3722943723, "max_line_length": 122, "alphanum_fraction": 0.5091143041, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6823101994006978}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../ellipsoid/ellipsoid.h\"\n\n#undef __FUNCT__\n#define __FUNCT__ \"TestNormalizationMPFR\"\nPetscErrorCode TestNormalizationMPFR()\n{\n PetscErrorCode ierr;\n EllipsoidalSystem e;\n const PetscInt prec = 128;\n PetscReal xA = 3.0;\n PetscReal yB = 2.0;\n PetscReal zC = 1.0;\n mpfr_t a, b, c;\n mpfr_t a2, b2, c2;\n mpfr_t a3, b3, c3;\n mpfr_t temp1, temp2, temp3;\n mpfr_t pi;\n\n \n PetscFunctionBegin;\n mpfr_set_default_prec(4*prec);\n\n \n mpfr_inits(a, b, c, NULL);\n mpfr_inits(a2, b2, c2, NULL);\n mpfr_inits(a3, b3, c3, NULL);\n mpfr_inits(temp1, temp2, temp3, pi, NULL);\n \n mpfr_set_d(a, xA, MPFR_RNDN);\n mpfr_set_d(b, yB, MPFR_RNDN);\n mpfr_set_d(c, zC, MPFR_RNDN);\n\n\n //init ellipsoidal system\n printf(\"initEllipsoidalSystem...\\n\");\n ierr = initEllipsoidalSystem(&e, xA, yB, zC, prec);CHKERRQ(ierr);\n printf(\"done.\\n\");\n\n \n mpfr_mul(a2, a, a, MPFR_RNDN);\n mpfr_mul(a3, a2, a, MPFR_RNDN);\n mpfr_mul(b2, b, b, MPFR_RNDN);\n mpfr_mul(b3, b2, b, MPFR_RNDN);\n mpfr_mul(c2, c, c, MPFR_RNDN);\n mpfr_mul(c3, c2, c, MPFR_RNDN);\n\n mpfr_t firstTerm, secondTerm, LambdaD, LambdaDprime;\n mpfr_inits(firstTerm, secondTerm, LambdaD, LambdaDprime, NULL); \n\n //Dassios (B14)\n //firstTerm = (a*a + b*b + c*c)/3.0;\n mpfr_add(firstTerm, a2, b2, MPFR_RNDN);\n mpfr_add(firstTerm, firstTerm, c2, MPFR_RNDN);\n mpfr_div_d(firstTerm, firstTerm, 3.0, MPFR_RNDN);\n\n //double secondTerm = sqrt((a*a*a*a - b*b*c*c) + (b*b*b*b - a*a*c*c) + (c*c*c*c - a*a*b*b))/3.0;\n mpfr_mul(temp1, a3, a, MPFR_RNDN);\n mpfr_mul(temp2, b2, c2, MPFR_RNDN);\n mpfr_sub(temp1, temp1, temp2, MPFR_RNDN);\n mpfr_mul(temp2, b3, b, MPFR_RNDN);\n mpfr_mul(temp3, a2, c2, MPFR_RNDN);\n mpfr_sub(temp2, temp2, temp3, MPFR_RNDN);\n mpfr_add(temp1, temp1, temp2, MPFR_RNDN);\n mpfr_mul(temp2, c3, c, MPFR_RNDN);\n mpfr_mul(temp3, a2, b2, MPFR_RNDN);\n mpfr_sub(temp2, temp2, temp3, MPFR_RNDN);\n mpfr_add(temp1, temp1, temp2, MPFR_RNDN);\n mpfr_sqrt(secondTerm, temp1, MPFR_RNDN);\n\n //double LambdaD = firstTerm + secondTerm;\n mpfr_add(LambdaD, firstTerm, secondTerm, MPFR_RNDN);\n\n //double LambdaDprime = firstTerm - secondTerm;\n mpfr_sub(LambdaDprime, firstTerm, secondTerm, MPFR_RNDN);\n\n mpfr_t hx, hy, hz;\n mpfr_inits(hx, hy, hz, NULL);\n\n //Dassios (B16)-(B20)\n //double hx = sqrt(b*b - c*c);\n mpfr_sub(temp1, b2, c2, MPFR_RNDN);\n mpfr_sqrt(hx, temp1, MPFR_RNDN);\n\n //double hy = e.k;\n mpfr_set(hy, e.hp_k, MPFR_RNDN);\n //double hz = e.h;\n mpfr_set(hz, e.hp_h, MPFR_RNDN);\n\n //set pi\n mpfr_const_pi(pi, MPFR_RNDN);\n\n mpfr_t analytic[9];\n mpfr_t approx[9], doubleApprox[9];\n for(PetscInt k=0; k < 9; ++k)\n mpfr_inits(analytic[k], approx[k], doubleApprox[k], NULL);\n\n //analytic[0] = 4*PETSC_PI\n mpfr_mul_d(analytic[0], pi, 4.0, MPFR_RNDN);\n printf(\"analytic[0] = %4.4e\\n\", mpfr_get_d(analytic[0], MPFR_RNDN));\n \n //analytic[1] = 4*PETSC_PI/3 * hy*hy*hz*hz\n mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN);\n mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN);\n mpfr_mul(temp2, hy, hy, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hz, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hz, MPFR_RNDN);\n mpfr_mul(analytic[1], temp1, temp2, MPFR_RNDN);\n\n //analytic[2] = 4*PETSC_PI/3 * hx*hx*hz*hz\n mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN);\n mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN);\n mpfr_mul(temp2, hx, hx, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hz, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hz, MPFR_RNDN);\n mpfr_mul(analytic[2], temp1, temp2, MPFR_RNDN);\n\n //analytic[3] = 4*PETSC_PI/3 * hx*hx*hy*hy\n mpfr_div_d(temp1, pi, 3.0, MPFR_RNDN);\n mpfr_mul_d(temp1, temp1, 4.0, MPFR_RNDN);\n mpfr_mul(temp2, hx, hx, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hy, MPFR_RNDN);\n mpfr_mul(temp2, temp2, hy, MPFR_RNDN);\n mpfr_mul(analytic[3], temp1, temp2, MPFR_RNDN);\n \n //analytic[4] = -8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaD - a*a)*(LambdaD - b*b)*(LambdaD - c*c)\n\n //analytic[5] = 8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaDprime - a*a)*(LambdaDprime - b*b)*(LambdaDprime - c*c),\n\n\n\n ierr = calcNormalizationMPFR(&e, 0, 0, approx+0);CHKERRQ(ierr);\n ierr = calcNormalization (&e, 0, 0, doubleApprox+0);CHKERRQ(ierr);\n ierr = calcNormalizationMPFR(&e, 1, 0, approx+1);CHKERRQ(ierr);\n ierr = calcNormalizationMPFR(&e, 1, 1, approx+2);CHKERRQ(ierr);\n mpfr_t err[9];\n for(PetscInt k=0; k < 4; ++k) {\n mpfr_init(err[k]);\n mpfr_sub(err[k], approx[k], analytic[k], MPFR_RNDN);\n mpfr_div(err[k], err[k], analytic[k], MPFR_RNDN);\n mpfr_abs(err[k], err[k], MPFR_RNDN);\n mpfr_log10(err[k], err[k], MPFR_RNDN);\n printf(\"the error is %2.2f\\n\", mpfr_get_d(err[k], MPFR_RNDN));\n }\n \n\n for(PetscInt k=0; k < 9; ++k)\n mpfr_clears(analytic[k], approx[k], err[k], doubleApprox[k], NULL);\n mpfr_clears(hx, hy, hz, NULL);\n mpfr_clears(temp1, temp2, temp3, pi, NULL);\n mpfr_clears(a3, b3, c3, NULL);\n mpfr_clears(a2, b2, c2, NULL);\n mpfr_clears(a, b, c, NULL);\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT __ \"main\"\nPetscErrorCode main(int argc, char **argv)\n{\n PetscErrorCode ierr;\n \n PetscFunctionBeginUser;\n\n ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr);\n\n ierr = TestNormalizationMPFR();\n \n ierr = PetscFinalize();\n\n}\n", "meta": {"hexsha": "ecee96e2d317560cf7c704b855b8122261a7e4dc", "size": 5267, "ext": "c", "lang": "C", "max_stars_repo_path": "src/tests/testEllMPFR.c", "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_issues_repo_path": "src/tests/testEllMPFR.c", "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/testEllMPFR.c", "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4245810056, "max_line_length": 121, "alphanum_fraction": 0.6667932409, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6819103233148062}} {"text": "static char help[] = \"A structured-grid Poisson solver using DMDA+KSP.\\n\\n\";\n\n#include \n\nextern PetscErrorCode formMatrix(DM, Mat);\nextern PetscErrorCode formExact(DM, Vec);\nextern PetscErrorCode formRHS(DM, Vec);\n\n//STARTMAIN\nint main(int argc,char **args) {\n PetscErrorCode ierr;\n DM da;\n Mat A;\n Vec b,u,uexact;\n KSP ksp;\n PetscReal errnorm;\n DMDALocalInfo info;\n\n ierr = PetscInitialize(&argc,&args,NULL,help); if (ierr) return ierr;\n\n // change default 9x9 size using -da_grid_x M -da_grid_y N\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,\n 9,9,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);\n\n // create linear system matrix A\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMCreateMatrix(da,&A); CHKERRQ(ierr);\n ierr = MatSetFromOptions(A); CHKERRQ(ierr);\n\n // create RHS b, approx solution u, exact solution uexact\n ierr = DMCreateGlobalVector(da,&b); CHKERRQ(ierr);\n ierr = VecDuplicate(b,&u); CHKERRQ(ierr);\n ierr = VecDuplicate(b,&uexact); CHKERRQ(ierr);\n\n // fill vectors and assemble linear system\n ierr = formExact(da,uexact); CHKERRQ(ierr);\n ierr = formRHS(da,b); CHKERRQ(ierr);\n ierr = formMatrix(da,A); CHKERRQ(ierr);\n\n // create and solve the linear system\n ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr);\n ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr);\n ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n ierr = KSPSolve(ksp,b,u); CHKERRQ(ierr);\n\n // report on grid and numerical error\n ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uxact\n ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"on %d x %d grid: error |u-uexact|_inf = %g\\n\",\n info.mx,info.my,errnorm); CHKERRQ(ierr);\n\n VecDestroy(&u); VecDestroy(&uexact); VecDestroy(&b);\n MatDestroy(&A); KSPDestroy(&ksp); DMDestroy(&da);\n return PetscFinalize();\n}\n//ENDMAIN\n\n//STARTMATRIX\nPetscErrorCode formMatrix(DM da, Mat A) {\n PetscErrorCode ierr;\n DMDALocalInfo info;\n MatStencil row, col[5];\n PetscReal hx, hy, v[5];\n PetscInt i, j, ncols;\n\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);\n for (j = info.ys; j < info.ys+info.ym; j++) {\n for (i = info.xs; i < info.xs+info.xm; i++) {\n row.j = j; // row of A corresponding to (x_i,y_j)\n row.i = i;\n col[0].j = j; // diagonal entry\n col[0].i = i;\n ncols = 1;\n if (i==0 || i==info.mx-1 || j==0 || j==info.my-1) {\n v[0] = 1.0; // on boundary: trivial equation\n } else {\n v[0] = 2*(hy/hx + hx/hy); // interior: build a row\n if (i-1 > 0) {\n col[ncols].j = j; col[ncols].i = i-1;\n v[ncols++] = -hy/hx;\n }\n if (i+1 < info.mx-1) {\n col[ncols].j = j; col[ncols].i = i+1;\n v[ncols++] = -hy/hx;\n }\n if (j-1 > 0) {\n col[ncols].j = j-1; col[ncols].i = i;\n v[ncols++] = -hx/hy;\n }\n if (j+1 < info.my-1) {\n col[ncols].j = j+1; col[ncols].i = i;\n v[ncols++] = -hx/hy;\n }\n }\n ierr = MatSetValuesStencil(A,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);\n }\n }\n ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n return 0;\n}\n//ENDMATRIX\n\n//STARTEXACT\nPetscErrorCode formExact(DM da, Vec uexact) {\n PetscErrorCode ierr;\n PetscInt i, j;\n PetscReal hx, hy, x, y, **auexact;\n DMDALocalInfo info;\n\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);\n ierr = DMDAVecGetArray(da, uexact, &auexact);CHKERRQ(ierr);\n for (j = info.ys; j < info.ys+info.ym; j++) {\n y = j * hy;\n for (i = info.xs; i < info.xs+info.xm; i++) {\n x = i * hx;\n auexact[j][i] = x*x * (1.0 - x*x) * y*y * (y*y - 1.0);\n }\n }\n ierr = DMDAVecRestoreArray(da, uexact, &auexact);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode formRHS(DM da, Vec b) {\n PetscErrorCode ierr;\n PetscInt i, j;\n PetscReal hx, hy, x, y, f, **ab;\n DMDALocalInfo info;\n\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n hx = 1.0/(info.mx-1); hy = 1.0/(info.my-1);\n ierr = DMDAVecGetArray(da, b, &ab);CHKERRQ(ierr);\n for (j=info.ys; j\n#include \n#include \n#include \n#include \n\nstatic void\ncentral_deriv (const gsl_function * f, double x, double h,\n double *result, double *abserr_round, double *abserr_trunc)\n{\n /* Compute the derivative using the 5-point rule (x-h, x-h/2, x,\n x+h/2, x+h). Note that the central point is not used. \n\n Compute the error using the difference between the 5-point and\n the 3-point rule (x-h,x,x+h). Again the central point is not\n used. */\n\n double fm1 = GSL_FN_EVAL (f, x - h);\n double fp1 = GSL_FN_EVAL (f, x + h);\n\n double fmh = GSL_FN_EVAL (f, x - h / 2);\n double fph = GSL_FN_EVAL (f, x + h / 2);\n\n double r3 = 0.5 * (fp1 - fm1);\n double r5 = (4.0 / 3.0) * (fph - fmh) - (1.0 / 3.0) * r3;\n\n double e3 = (fabs (fp1) + fabs (fm1)) * GSL_DBL_EPSILON;\n double e5 = 2.0 * (fabs (fph) + fabs (fmh)) * GSL_DBL_EPSILON + e3;\n\n /* The next term is due to finite precision in x+h = O (eps * x) */\n\n double dy = GSL_MAX (fabs (r3 / h), fabs (r5 / h)) *(fabs (x) / h) * GSL_DBL_EPSILON;\n\n /* The truncation error in the r5 approximation itself is O(h^4).\n However, for safety, we estimate the error from r5-r3, which is\n O(h^2). By scaling h we will minimise this estimated error, not\n the actual truncation error in r5. */\n\n *result = r5 / h;\n *abserr_trunc = fabs ((r5 - r3) / h); /* Estimated truncation error O(h^2) */\n *abserr_round = fabs (e5 / h) + dy; /* Rounding error (cancellations) */\n}\n\nint\ngsl_deriv_central (const gsl_function * f, double x, double h,\n double *result, double *abserr)\n{\n double r_0, round, trunc, error;\n central_deriv (f, x, h, &r_0, &round, &trunc);\n error = round + trunc;\n\n if (round < trunc && (round > 0 && trunc > 0))\n {\n double r_opt, round_opt, trunc_opt, error_opt;\n\n /* Compute an optimised stepsize to minimize the total error,\n using the scaling of the truncation error (O(h^2)) and\n rounding error (O(1/h)). */\n\n double h_opt = h * pow (round / (2.0 * trunc), 1.0 / 3.0);\n central_deriv (f, x, h_opt, &r_opt, &round_opt, &trunc_opt);\n error_opt = round_opt + trunc_opt;\n\n /* Check that the new error is smaller, and that the new derivative \n is consistent with the error bounds of the original estimate. */\n\n if (error_opt < error && fabs (r_opt - r_0) < 4.0 * error)\n {\n r_0 = r_opt;\n error = error_opt;\n }\n }\n\n *result = r_0;\n *abserr = error;\n\n return GSL_SUCCESS;\n}\n\n\nstatic void\nforward_deriv (const gsl_function * f, double x, double h,\n double *result, double *abserr_round, double *abserr_trunc)\n{\n /* Compute the derivative using the 4-point rule (x+h/4, x+h/2,\n x+3h/4, x+h).\n\n Compute the error using the difference between the 4-point and\n the 2-point rule (x+h/2,x+h). */\n\n double f1 = GSL_FN_EVAL (f, x + h / 4.0);\n double f2 = GSL_FN_EVAL (f, x + h / 2.0);\n double f3 = GSL_FN_EVAL (f, x + (3.0 / 4.0) * h);\n double f4 = GSL_FN_EVAL (f, x + h);\n\n double r2 = 2.0*(f4 - f2);\n double r4 = (22.0 / 3.0) * (f4 - f3) - (62.0 / 3.0) * (f3 - f2) +\n (52.0 / 3.0) * (f2 - f1);\n\n /* Estimate the rounding error for r4 */\n\n double e4 = 2 * 20.67 * (fabs (f4) + fabs (f3) + fabs (f2) + fabs (f1)) * GSL_DBL_EPSILON;\n\n /* The next term is due to finite precision in x+h = O (eps * x) */\n\n double dy = GSL_MAX (fabs (r2 / h), fabs (r4 / h)) * fabs (x / h) * GSL_DBL_EPSILON;\n\n /* The truncation error in the r4 approximation itself is O(h^3).\n However, for safety, we estimate the error from r4-r2, which is\n O(h). By scaling h we will minimise this estimated error, not\n the actual truncation error in r4. */\n\n *result = r4 / h;\n *abserr_trunc = fabs ((r4 - r2) / h); /* Estimated truncation error O(h) */\n *abserr_round = fabs (e4 / h) + dy;\n}\n\nint\ngsl_deriv_forward (const gsl_function * f, double x, double h,\n double *result, double *abserr)\n{\n double r_0, round, trunc, error;\n forward_deriv (f, x, h, &r_0, &round, &trunc);\n error = round + trunc;\n\n if (round < trunc && (round > 0 && trunc > 0))\n {\n double r_opt, round_opt, trunc_opt, error_opt;\n\n /* Compute an optimised stepsize to minimize the total error,\n using the scaling of the estimated truncation error (O(h)) and\n rounding error (O(1/h)). */\n\n double h_opt = h * pow (round / (trunc), 1.0 / 2.0);\n forward_deriv (f, x, h_opt, &r_opt, &round_opt, &trunc_opt);\n error_opt = round_opt + trunc_opt;\n\n /* Check that the new error is smaller, and that the new derivative \n is consistent with the error bounds of the original estimate. */\n\n if (error_opt < error && fabs (r_opt - r_0) < 4.0 * error)\n {\n r_0 = r_opt;\n error = error_opt;\n }\n }\n\n *result = r_0;\n *abserr = error;\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_deriv_backward (const gsl_function * f, double x, double h,\n double *result, double *abserr)\n{\n return gsl_deriv_forward (f, x, -h, result, abserr);\n}\n", "meta": {"hexsha": "2cec7941d58b19eb85b0c02221019758ca7de8e7", "size": 5912, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/deriv/deriv.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/deriv/deriv.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/deriv/deriv.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 33.0279329609, "max_line_length": 92, "alphanum_fraction": 0.6200947226, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6808906177526373}} {"text": "#include \n#include \n\nint\nmain (void)\n{\n double c = GSL_CONST_MKSA_SPEED_OF_LIGHT;\n double au = GSL_CONST_MKSA_ASTRONOMICAL_UNIT;\n double minutes = GSL_CONST_MKSA_MINUTE;\n\n /* distance stored in meters */\n double r_earth = 1.00 * au; \n double r_mars = 1.52 * au;\n\n double t_min, t_max;\n\n t_min = (r_mars - r_earth) / c;\n t_max = (r_mars + r_earth) / c;\n\n printf (\"light travel time from Earth to Mars:\\n\");\n printf (\"minimum = %.1f minutes\\n\", t_min / minutes);\n printf (\"maximum = %.1f minutes\\n\", t_max / minutes);\n\n return 0;\n}\n", "meta": {"hexsha": "47718c51d3cfc27f0f1b29303c8186065b3f7ca5", "size": 577, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/const.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/const.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/const.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.1923076923, "max_line_length": 55, "alphanum_fraction": 0.6655112652, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6808832625403222}} {"text": "#include \n#include \n#include \n#include \n#include \"SE_trans.h\"\n\n#define ALPHA 0.99\n#define DOMD 3.14\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 J(int j, double h, double x)\n{\n return h * (0.5 + M_1_PI * gsl_sf_Si(M_PI * (x / h - j)));\n}\n\ndouble Fapp(double t, int m)\n{\n double h = sqrt(M_PI*DOMD / (ALPHA*m));\n\n int j;\n double sum1 = 0;\n double sum2 = 0;\n\n for (j = -m; j < 0; j++) {\n sum1 += G(j*h) * J(j, h, SE_trans_inv(-1, 1, t));\n }\n for (j = m; j >= 0; j--) {\n sum2 += G(j*h) * J(j, h, SE_trans_inv(-1, 1, t));\n }\n\n return (sum1 + sum2);\n}\n\nint main()\n{\n int i;\n int n;\n double t;\n double err, maxerr;\n clock_t start, end;\n double time;\n\n int STEP = 1000;\n\n for (n = 3; n <= 150; n += 6) {\n start = clock();\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(t, n));\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\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7f730e569d99cd4b20465e9f8ab7d35c80905c5c", "size": 1254, "ext": "c", "lang": "C", "max_stars_repo_path": "Ex2SE1.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": "Ex2SE1.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": "Ex2SE1.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.4166666667, "max_line_length": 75, "alphanum_fraction": 0.5223285486, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475778774728, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6808547111564831}} {"text": "/*\n This section is aimed to calculate the gaussian integrals that occurs in everywhere\n\n This part is greatly inspired by May, Andrew James. Density fitting in explicitly correlated electronic structure theory. Diss. University of Bristol, 2006.\n */\n\n/*\n\nHere is the table of the relation between the names and the definition:\n\nS \nJ (a|b) = \nG (a|e^{-\\gamma r_{12}^2}|b)\nF (a|f_{12}|b) = (a|c_i exp(-\\gamma_i r_{12}^2)|b)\nGJ (a|e^{-\\gamma r_{12}^2 r_12^{-1}}|b)\nFJ (a|f_{12} r_{12}^{-1}|b)\nFF (a|f_{12}^2|b)\nFT (ab|[\\hat{t}_1, f_{12}]|c) = (ab|[- \\frac{1}{2} \\nabla ^2, f_{12}]|c)\nFTF (a|\\frac{1}{2}[f_12,[\\hat{t}_1 + \\hat{t}_2, f_{12}]]|b)\nF-F (a|f_{12}|b|f_{23}|c)\nJ-F (a|r_{12}^{-1}|b|f_{23}|c)\nX (ab|[\\hat{t}_1,r_{12}]|c)\nY (ab|[\\hat{t}_1,r_{12}^{-1}])\nZ (a|\\frac{1}{r_{1Z}}|b)\n\nCurrently only S integrals and J integrals are supported.\n\n */\n\n#ifndef __BASIS_H__\n#define __BASIS_H__\n#include \"basis.h\"\n#endif\n\n#include \n\n#include \n#include \n#include \n\ntypedef struct gaussian_chain{\n double R[3];\n int a[3];\n \n double exponent;\n\n double coefficient;\n\n gaussian_chain * NEXT;\n\n}gaussian_chain;\n\ngaussian_chain * gaussian_chain_calloc();\n\nvoid gaussian_chain_free(gaussian_chain * HEAD);\n\ndouble gaussian_chain_get(gaussian_chain * HEAD,double x, double y, double z);\ndouble orbital_get(orbital * orbital,double x, double y, double z);\n\ndouble Gamma(double z);\ndouble Boys(double x, int n);\ndouble Binomials(int n, int k);\n\ndouble f(int k, int a, int b, double PA, double PB);\ndouble tranformation_coefficient(int a[3], int b[3], int p[3], double PA[3], double PB[3], double xi, double AB);\n\ndouble SIntegral(double ra[3], double rb[3], int ax, int ay, int az, int bx, int by, int bz, double alpha,double beta);\ndouble JIntegral(double ra[3], double rb[3], int ax, int ay, int az, int bx, int by, int bz, double alpha,double beta, int m);\ndouble ZIntegral(double ra[3], double rb[3], double rz[3], int ax, int ay, int az, int bx, int by, int bz, double alpha, double beta, int m);\n\ndouble gaussian_chain_SIntegral(gaussian_chain * a, gaussian_chain * b);\ndouble gaussian_chain_JIntegral(gaussian_chain * a, gaussian_chain * b);\ndouble gaussian_chain_ZIntegral(gaussian_chain * a, gaussian_chain * b, double rz[3]);\ndouble gaussian_chain_full_SIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD);\ndouble gaussian_chain_full_JIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD);\ndouble gaussian_chain_full_ZIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD, double rz[3]);\n\nvoid gaussian_chain_derivative(gaussian_chain * dest, gaussian_chain * src, int key);\nvoid gaussian_chain_second_derivative(gaussian_chain * dest, gaussian_chain * src, int key);\nvoid gaussian_chain_laplacian(gaussian_chain * dest, gaussian_chain * src);\n\ndouble gaussian_chain_kinetic_energy(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD);\n\nvoid single_electron_transform(gaussian_chain * HEAD, orbital * a);\nvoid two_electron_transform(gaussian_chain * HEAD, orbital * a, orbital * b);\n\ndouble orbital_SIntegral(orbital * a,orbital * b);\ndouble orbital_JIntegral(orbital * a,orbital * b);\ndouble orbital_ZIntegral(orbital * a,orbital * b, double rz[3]);\n//double orbital_GIntegral(orbital *,orbital *);\n//double orbital_FIntegral(orbital *,orbital *);\n//double orbital_GJIntegral(orbital *,orbital *);\n//double orbital_FJIntegral(orbital *,orbital *);\n//double orbital_FFIntegral(orbital *,orbital *);\n\ndouble two_electron_JIntegral(orbital * a_1, orbital * b_1, orbital * c_2, orbital * d_2);\n\ndouble orbital_kinetic_energy(orbital * a, orbital * b);\n\nvoid orbital_S_matrix(gsl_matrix * dest, orbital * HEAD);", "meta": {"hexsha": "b06615368f409383ce1369aa91e16f123d51952f", "size": 3731, "ext": "h", "lang": "C", "max_stars_repo_path": "include/integral.h", "max_stars_repo_name": "Walter-Feng/Hartree-Fock", "max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z", "max_issues_repo_path": "include/integral.h", "max_issues_repo_name": "Walter-Feng/Hartree-Fock", "max_issues_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "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/integral.h", "max_forks_repo_name": "Walter-Feng/Hartree-Fock", "max_forks_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z", "avg_line_length": 37.31, "max_line_length": 160, "alphanum_fraction": 0.7212543554, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6802194855068471}} {"text": "/* \n * Calculation of Integral\n */\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"timer.h\"\n\ndouble g (double *t, size_t dim, void *params);\n\nint main (void)\n{\n double res, err;\n double dist, dmin = 1.001, dmax = 4.;\n size_t dim = 6;\n int np = 20;\n double vegas[20], vegaserr[20];\n double time1, time2; \n\n double dstep = (dmax - dmin) / (np - 1);\n\n double xl[] = { 0., 0., 0., 0., 0., 0. };\n double xu[] = { 1., 1., 1., 1., 1., 1. };\n\n gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);\n unsigned long seed = 1UL;\n\n gsl_rng_set (r, seed);\n\n size_t calls = 1000000;\n\n gsl_monte_function G = { &g, dim, &dist };\n\n gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim);\n\n gsl_monte_vegas_init (sv);\n\n dist = dmin;\n\n// Vegas algorithm calculation\n\n timer_start ();\n\n // printf (\"# Dist Energy ErrEst Dipole\\n\");\n for (int i = 0; i < np; i++)\n {\n gsl_monte_vegas_integrate (&G, xl, xu, dim, calls / 5, r, sv, &res,\n &err);\n\n do\n {\n gsl_monte_vegas_integrate (&G, xl, xu, dim, calls, r, sv, &res,\n &err);\n }\n\n while (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2);\n\n\n //printf (\"% .6f % .6f % .6f % .6f\\n\", dist, res, err,\n // -2. / pow (dist, 3.));\n\n //fflush (stdout);\n vegas[i] = res;\n vegaserr[i] = err;\n\n dist += dstep;\n }\n\n time1 = timer_stop ();\n\n gsl_monte_vegas_free (sv);\n\n dist = dmin;\n printf (\"# Dist HMC Vegas Verr Dipole Difference\\n\");\n\n double t[6];\n \n// Calculation using homemade Monte Carlo algorithm\n \n timer_start ();\n\n for (int i = 0; i < np; i++)\n {\n double sum = 0.;\n\n for (int j = 0; j < (int) calls; j++)\n {\n for (int m = 0; m < (int) dim; m++)\n {\n t[m] = gsl_rng_uniform (r);\n }\n sum += g (t, dim, &dist);\n }\n double energy = sum / calls;\n double difference = fabs (energy - vegas[i]);\n\n printf (\"% .6f % .6f % .6f % .6f % .6f % .6f\\n\", \n dist, energy, vegas[i], vegaserr[i], -2./pow(dist, 3.), difference );\n dist += dstep;\n \n }\n\n time2 = timer_stop ();\n printf (\"Time Vegas: %.2f Time HMC: %.2f\\n\", time1, time2);\n printf (\"Speedup: %.2f\\n\", time1 / time2);\n \n gsl_rng_free (r);\n \n\n return 0;\n}\n", "meta": {"hexsha": "b70a80e9238f0a2dc6257ed2de81c5f5a67c132d", "size": 2549, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "matthewignal/fin2", "max_stars_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.c", "max_issues_repo_name": "matthewignal/fin2", "max_issues_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.c", "max_forks_repo_name": "matthewignal/fin2", "max_forks_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "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.7863247863, "max_line_length": 83, "alphanum_fraction": 0.4986269125, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6798667112982721}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef gauge_config\n#include \"config.h\"\n#define gauge_config 1\n\n#define sq(x) ((x)*(x))\n#define cb(x) ((x)*(x)*(x))\n#endif\n\n\n// SU(2) Matrix\n// only the first row carries useful information (Lang p.80)\n// note that for the first row must be normalized, i.e. |a|^2+ |b|^2 = 1\n// use su2_normalize() for this\ntypedef struct{\n gsl_complex a;\n gsl_complex b;\n} su2_matrix;\n\n// SU(2) matrix methods --------------------------------------\n\n// print matrix\nvoid su2_print(const su2_matrix A){\n printf(\"%f + i*%f \\t\", GSL_REAL(A.a), GSL_IMAG(A.a));\n printf(\"%f + i*%f \\n\", GSL_REAL(A.b), GSL_IMAG(A.b));\n}\n\n// the identity matrix\nsu2_matrix su2_unit(){\n su2_matrix u;\n u.a=GSL_COMPLEX_ONE;\n u.b=GSL_COMPLEX_ZERO;\n return u;\n}\n\n// normalize matrix\nsu2_matrix su2_norm(const su2_matrix A){\n su2_matrix result;\n double norm = sqrt(gsl_complex_abs2(A.a)+gsl_complex_abs2(A.b));\n result.a = gsl_complex_div(A.a,gsl_complex_rect(norm,0));\n result.b = gsl_complex_div(A.b,gsl_complex_rect(norm,0));\n return result;\n}\n\n// multiply matrices\nsu2_matrix su2_mul(const su2_matrix A, const su2_matrix B){\n su2_matrix result;\n result.a = gsl_complex_sub(gsl_complex_mul(A.a,B.a), gsl_complex_mul(A.b,gsl_complex_conjugate(B.b))); // ac-bd*\n result.b = gsl_complex_add(gsl_complex_mul(A.a,B.b), gsl_complex_mul(A.b,gsl_complex_conjugate(B.a))); // ad+bc*\n return result;\n}\n\n// inverse matrix\nsu2_matrix su2_inv(const su2_matrix A){\n su2_matrix result;\n result.a = gsl_complex_conjugate(A.a);\n result.b = gsl_complex_sub(GSL_COMPLEX_ZERO,A.b);\n return result;\n}\n\n// generate random matrix\nsu2_matrix su2_rand(const gsl_rng* r){\n su2_matrix result;\n result.a = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1));\n result.b = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));\n return su2_norm(result);\n}\n\ndouble su2_trace(const su2_matrix A){\n return 2*GSL_REAL(A.a);\n}\n\n// end of SU(2) matrix methods ---------------------------------------------\n", "meta": {"hexsha": "7ab95266004f3ec729f29db1700cfdc8bdf945f0", "size": 2190, "ext": "c", "lang": "C", "max_stars_repo_path": "su2/su2_matrix.c", "max_stars_repo_name": "uchuutamashi/lqcd", "max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "su2/su2_matrix.c", "max_issues_repo_name": "uchuutamashi/lqcd", "max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z", "max_forks_repo_path": "su2/su2_matrix.c", "max_forks_repo_name": "uchuutamashi/lqcd", "max_forks_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3855421687, "max_line_length": 114, "alphanum_fraction": 0.6863013699, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6798592239554784}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nint\nmain()\n{\n const size_t n = 1000; /* number of observations */\n const size_t p = 2; /* number of model parameters */\n size_t i;\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n gsl_matrix *X = gsl_matrix_alloc(n, p);\n gsl_vector *y = gsl_vector_alloc(n);\n\n for (i = 0; i < n; ++i)\n {\n /* generate first random variable u */\n double ui = 5.0 * gsl_ran_gaussian(r, 1.0);\n\n /* set v = u + noise */\n double vi = ui + gsl_ran_gaussian(r, 0.001);\n\n /* set y = u + v + noise */\n double yi = ui + vi + gsl_ran_gaussian(r, 1.0);\n\n /* since u =~ v, the matrix X is ill-conditioned */\n gsl_matrix_set(X, i, 0, ui);\n gsl_matrix_set(X, i, 1, vi);\n\n /* rhs vector */\n gsl_vector_set(y, i, yi);\n }\n\n {\n const size_t npoints = 200; /* number of points on L-curve and GCV curve */\n gsl_multifit_linear_workspace *w =\n gsl_multifit_linear_alloc(n, p);\n gsl_vector *c = gsl_vector_alloc(p); /* OLS solution */\n gsl_vector *c_lcurve = gsl_vector_alloc(p); /* regularized solution (L-curve) */\n gsl_vector *c_gcv = gsl_vector_alloc(p); /* regularized solution (GCV) */\n gsl_vector *reg_param = gsl_vector_alloc(npoints);\n gsl_vector *rho = gsl_vector_alloc(npoints); /* residual norms */\n gsl_vector *eta = gsl_vector_alloc(npoints); /* solution norms */\n gsl_vector *G = gsl_vector_alloc(npoints); /* GCV function values */\n double lambda_l; /* optimal regularization parameter (L-curve) */\n double lambda_gcv; /* optimal regularization parameter (GCV) */\n double G_gcv; /* G(lambda_gcv) */\n size_t reg_idx; /* index of optimal lambda */\n double rcond; /* reciprocal condition number of X */\n double chisq, rnorm, snorm;\n\n /* compute SVD of X */\n gsl_multifit_linear_svd(X, w);\n\n rcond = gsl_multifit_linear_rcond(w);\n fprintf(stderr, \"matrix condition number = %e\\n\\n\", 1.0 / rcond);\n\n /* unregularized (standard) least squares fit, lambda = 0 */\n gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0);\n\n fprintf(stderr, \"=== Unregularized fit ===\\n\");\n fprintf(stderr, \"best fit: y = %g u + %g v\\n\",\n gsl_vector_get(c, 0), gsl_vector_get(c, 1));\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* calculate L-curve and find its corner */\n gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w);\n gsl_multifit_linear_lcorner(rho, eta, ®_idx);\n\n /* store optimal regularization parameter */\n lambda_l = gsl_vector_get(reg_param, reg_idx);\n\n /* regularize with lambda_l */\n gsl_multifit_linear_solve(lambda_l, X, y, c_lcurve, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0) + pow(lambda_l * snorm, 2.0);\n\n fprintf(stderr, \"\\n=== Regularized fit (L-curve) ===\\n\");\n fprintf(stderr, \"optimal lambda: %g\\n\", lambda_l);\n fprintf(stderr, \"best fit: y = %g u + %g v\\n\",\n gsl_vector_get(c_lcurve, 0), gsl_vector_get(c_lcurve, 1));\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* calculate GCV curve and find its minimum */\n gsl_multifit_linear_gcv(y, reg_param, G, &lambda_gcv, &G_gcv, w);\n\n /* regularize with lambda_gcv */\n gsl_multifit_linear_solve(lambda_gcv, X, y, c_gcv, &rnorm, &snorm, w);\n chisq = pow(rnorm, 2.0) + pow(lambda_gcv * snorm, 2.0);\n\n fprintf(stderr, \"\\n=== Regularized fit (GCV) ===\\n\");\n fprintf(stderr, \"optimal lambda: %g\\n\", lambda_gcv);\n fprintf(stderr, \"best fit: y = %g u + %g v\\n\",\n gsl_vector_get(c_gcv, 0), gsl_vector_get(c_gcv, 1));\n fprintf(stderr, \"residual norm = %g\\n\", rnorm);\n fprintf(stderr, \"solution norm = %g\\n\", snorm);\n fprintf(stderr, \"chisq/dof = %g\\n\", chisq / (n - p));\n\n /* output L-curve and GCV curve */\n for (i = 0; i < npoints; ++i)\n {\n printf(\"%e %e %e %e\\n\",\n gsl_vector_get(reg_param, i),\n gsl_vector_get(rho, i),\n gsl_vector_get(eta, i),\n gsl_vector_get(G, i));\n }\n\n /* output L-curve corner point */\n printf(\"\\n\\n%f %f\\n\",\n gsl_vector_get(rho, reg_idx),\n gsl_vector_get(eta, reg_idx));\n\n /* output GCV curve corner minimum */\n printf(\"\\n\\n%e %e\\n\",\n lambda_gcv,\n G_gcv);\n\n gsl_multifit_linear_free(w);\n gsl_vector_free(c);\n gsl_vector_free(c_lcurve);\n gsl_vector_free(reg_param);\n gsl_vector_free(rho);\n gsl_vector_free(eta);\n gsl_vector_free(G);\n }\n\n gsl_rng_free(r);\n gsl_matrix_free(X);\n gsl_vector_free(y);\n\n return 0;\n}\n", "meta": {"hexsha": "72082067f3a0e799aa8e51e73eba83cd330e7149", "size": 5077, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/fitreg.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/fitreg.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/fitreg.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": 36.0070921986, "max_line_length": 98, "alphanum_fraction": 0.5952334056, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6798234316610973}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\ngsl_spline *cosmocalc_aexpn2comvdist_spline = NULL;\ngsl_interp_accel *cosmocalc_aexpn2comvdist_acc = NULL; \ngsl_spline *cosmocalc_comvdist2aexpn_spline = NULL;\ngsl_interp_accel *cosmocalc_comvdist2aexpn_acc = NULL; \ndouble DH_sqrtok;\n\n/* function for integration using gsl integration */\nstatic double comvdist_integ_funct(double a, void *p)\n{\n return 1.0/a/a/hubble_noscale(a);\n}\n\ndouble comvdist_exact(double a)\n{\n#define WORKSPACE_NUM 100000\n#define ABSERR 0.0\n#define RELERR 1e-8\n\n gsl_integration_workspace *workspace;\n gsl_function F;\n double result,abserr;\n \n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n \n F.function = &comvdist_integ_funct;\n gsl_integration_qag(&F,a,1.0,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);\n \n gsl_integration_workspace_free(workspace);\n\n#undef ABSERR\n#undef RELERR\n#undef WORKSPACE_NUM\n \n return result*DH;\n}\n\n/* init function - some help from Gadget-2 applied here */\nvoid init_cosmocalc_comvdist_table(void)\n{\n#define WORKSPACE_NUM 100000\n#define ABSERR 0.0\n#define RELERR 1e-8\n\n static int initFlag = 1;\n static int currCosmoNum;\n \n gsl_integration_workspace *workspace;\n gsl_function F;\n long i;\n double result,abserr,afact;\n double comvdist_table[COSMOCALC_COMVDIST_TABLE_LENGTH];\n double aexpn_table[COSMOCALC_COMVDIST_TABLE_LENGTH];\n size_t sindex[COSMOCALC_COMVDIST_TABLE_LENGTH];\n double tmpDouble[COSMOCALC_COMVDIST_TABLE_LENGTH];\n \n if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)\n {\n initFlag = 0;\n currCosmoNum = cosmoData.cosmoNum;\n \n if(cosmoData.OmegaK != 0.0)\n\tDH_sqrtok = DH/sqrt(fabs(cosmoData.OmegaK));\n else\n\tDH_sqrtok = 1.0;\n \n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n \n for(i=0;i 0.0)\n return DH_sqrtok*sinh(cd/DH_sqrtok)*a;\n else if(cosmoData.OmegaK < 0)\n return DH_sqrtok*sin(cd/DH_sqrtok)*a;\n else\n return cd*a;\n}\n\ndouble lumdist(double a)\n{\n double cd;\n cd = comvdist(a);\n \n if(cosmoData.OmegaK > 0.0)\n return DH_sqrtok*sinh(cd/DH_sqrtok)/a;\n else if(cosmoData.OmegaK < 0)\n return DH_sqrtok*sin(cd/DH_sqrtok)/a;\n else\n return cd/a;\n}\n\ndouble angdistdiff(double amin, double amax)\n{\n double cdmin,cdmax;\n assert(amin <= amax);\n cdmin = comvdist(amin);\n cdmax = comvdist(amax);\n \n if(cosmoData.OmegaK > 0.0)\n return DH_sqrtok*sinh((cdmin-cdmax)/DH_sqrtok)*amin;\n else if(cosmoData.OmegaK < 0)\n return DH_sqrtok*sin((cdmin-cdmax)/DH_sqrtok)*amin;\n else\n return (cdmin-cdmax)*amin;\n}\n\n", "meta": {"hexsha": "d53a6e990c0d09002a6a3e310725fbf375905c72", "size": 5794, "ext": "c", "lang": "C", "max_stars_repo_path": "src/distances.c", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.c", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/distances.c", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 28.97, "max_line_length": 125, "alphanum_fraction": 0.7404211253, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6796021958013655}} {"text": "/*\n * Reinforcement Learning Book / Exercise 4.7\n *\n * $ sudo apt-get install libgsl-dev libgsl2 \n * $ gcc car_rental2.c -lgsl -lgslcblas -lm -o car_rental2\n */\n\n\n#include \n#include \n#include \n\n#define Size 20\n#define Iteration 100\n#define Rent1_mean 3\n#define Rent2_mean 4\n#define Return1_mean 3\n#define Return2_mean 2\n\n// Global variables\nfloat value[Size + 1][Size + 1];\nint policy[Size + 1][Size + 1];\n\n\nvoid show_value(){\n printf(\"[\");\n for (int c1 = 0; c1 <= Size; c1++) {\n printf(\"[\");\n for (int c2 = 0; c2 <= Size; c2++) {\n printf(\"%3.0f\", value[c1][c2]);\n if (c2 < Size) {\n printf(\", \");\n }\n }\n printf(\"]\");\n if (c1 < Size) {\n printf(\",\\n \");\n }\n }\n printf(\"]\\n\");\n}\n\n\nvoid show_policy(){\n printf(\"[\");\n for (int c1 = 0; c1 <= Size; c1++) {\n printf(\"[\");\n for (int c2 = 0; c2 <= Size; c2++) {\n printf(\"%2d\", policy[c1][c2]);\n if (c2 < Size) {\n printf(\", \");\n }\n }\n printf(\"]\");\n if (c1 < Size) {\n printf(\",\\n \");\n }\n }\n printf(\"]\\n\");\n}\n\n\nfloat calc_q_val(int c1, int c2, int a){\n float q_val = 0;\n int _c1, _c2;\n float c1_rent_prob, c2_rent_prob, c1_return_prob, c2_return_prob, prob;\n\n // Moving cars\n c1 -= a;\n c2 += a;\n if (a > 0) {\n q_val -= 2*(a-1);\n } else {\n q_val -= 2*abs(a);\n }\n if (c1 > 10) q_val -= 4;\n if (c2 > 10) q_val -= 4;\n\n for (int c1_rent = 0; c1_rent <= c1; c1_rent++) {\n for (int c2_rent = 0; c2_rent <= c2; c2_rent++) {\n for (int c1_return = 0; c1_return <= Size-(c1-c1_rent); c1_return++) {\n for (int c2_return = 0; c2_return <= Size-(c2-c2_rent); c2_return++) {\n _c1 = c1 - c1_rent + c1_return;\n _c2 = c2 - c2_rent + c2_return;\n\n if (c1_rent == c1) {\n c1_rent_prob = 1;\n for (int n = 0; n < c1_rent; n++) {\n c1_rent_prob -= gsl_ran_poisson_pdf(n, Rent1_mean);\n }\n } else {\n c1_rent_prob = gsl_ran_poisson_pdf(c1_rent, Rent1_mean);\n }\n\n if (c2_rent == c2) {\n c2_rent_prob = 1;\n for (int n = 0; n < c2_rent; n++) {\n c2_rent_prob -= gsl_ran_poisson_pdf(n, Rent2_mean);\n }\n } else {\n c2_rent_prob = gsl_ran_poisson_pdf(c2_rent, Rent2_mean);\n }\n\n if (c1_return == Size-(c1-c1_rent)) {\n c1_return_prob = 1;\n for (int n = 0; n < c1_return; n++) {\n c1_return_prob -= gsl_ran_poisson_pdf(n, Return1_mean);\n }\n } else {\n c1_return_prob = gsl_ran_poisson_pdf(c1_return, Return1_mean);\n }\n\n if (c2_return == Size-(c2-c2_rent)) {\n c2_return_prob = 1;\n for (int n = 0; n < c2_return; n++) {\n c2_return_prob -= gsl_ran_poisson_pdf(n, Return2_mean);\n }\n } else {\n c2_return_prob = gsl_ran_poisson_pdf(c2_return, Return2_mean);\n }\n\n prob = c1_rent_prob * c2_rent_prob * c1_return_prob * c2_return_prob;\n q_val += prob * (10 * (c1_rent + c2_rent) + 0.9 * value[_c1][_c2]);\n }\n }\n }\n }\n return q_val;\n}\n\n\nint min(int a, int b){\n if (a < b) {\n return a;\n } else {\n return b;\n }\n}\n\n\nvoid run() {\n float q_val;\n float value_update;\n int policy_update;\n\n for (int c1 = 0; c1 <= Size; c1++) {\n for (int c2 = 0; c2 <= Size; c2++) {\n value[c1][c2] = 0;\n policy[c1][c2] = 0;\n }\n }\n\n printf(\"# Iteration 0\\n\");\n show_policy();\n show_value();\n\n for (int i = 1; i < Iteration; i++) {\n for (int c1 = 0; c1 <= Size; c1++) {\n for (int c2 = 0; c2 <= Size; c2++) {\n int update = 0;\n for (int a = -min(c2, 5); a <= min(c1, 5); a++) {\n q_val = calc_q_val(c1, c2, a);\n if (update == 0 || q_val > value_update) {\n value_update = q_val;\n policy_update = a;\n update = 1;\n }\n }\n value[c1][c2] = value_update;\n policy[c1][c2] = policy_update;\n }\n }\n printf(\"# Iteration %d\\n\", i);\n show_policy();\n show_value();\n }\n}\n\n\nint main() {\n run();\n}\n", "meta": {"hexsha": "085c0253e5e4263108ad663e0d3a6a62e8ecae9c", "size": 4950, "ext": "c", "lang": "C", "max_stars_repo_path": "Chapter04/car_rental2.c", "max_stars_repo_name": "enakai00/rl_book_solutions", "max_stars_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T13:36:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T17:40:11.000Z", "max_issues_repo_path": "Chapter04/car_rental2.c", "max_issues_repo_name": "enakai00/rl_book_solutions", "max_issues_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "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": "Chapter04/car_rental2.c", "max_forks_repo_name": "enakai00/rl_book_solutions", "max_forks_repo_head_hexsha": "350ccd3fdb161853a2ef69a05632abe080fdd423", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T06:19:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T12:46:22.000Z", "avg_line_length": 27.0491803279, "max_line_length": 89, "alphanum_fraction": 0.4175757576, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6792293790463322}} {"text": "static char help[] = \"Stiff ODE system. Compare odejac.c.\\n\\n\";\n\n#include \n\n/* PYTHON:\nimport numpy as np\nfrom scipy.linalg import expm\nB = np.array([[0, 1, 0], [-1, 0, 0.1], [0, 0, -101]])\ny = np.dot(expm(10*B),np.array([1.0,1.0,1.0]).transpose())\nprint y\nRESULT:\n[-1.383623 -0.29588643 0. ]\n*/\n\nextern PetscErrorCode FormRHSFunction(TS, double, Vec, Vec, void*);\nPetscErrorCode FormRHSJacobian(TS, double, Vec, Mat, Mat, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n const int N = 3;\n int steps;\n Vec y;\n Mat J;\n TS ts;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr);\n ierr = VecSetSizes(y,PETSC_DECIDE,N); CHKERRQ(ierr);\n ierr = VecSetFromOptions(y); CHKERRQ(ierr);\n ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr);\n ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,N,N); CHKERRQ(ierr);\n ierr = MatSetFromOptions(J); CHKERRQ(ierr);\n ierr = MatSetUp(J); CHKERRQ(ierr);\n\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr);\n ierr = TSSetRHSJacobian(ts,J,J,FormRHSJacobian,NULL); CHKERRQ(ierr);\n\n ierr = TSSetType(ts,TSRK); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,10.0); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,1.0); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts); CHKERRQ(ierr); // can override defaults\n\n ierr = VecSet(y,1.0); CHKERRQ(ierr);\n ierr = TSSolve(ts,y); CHKERRQ(ierr);\n\n ierr = VecView(y,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"total steps = %d\\n\",steps); CHKERRQ(ierr);\n\n VecDestroy(&y); TSDestroy(&ts); MatDestroy(&J);\n PetscFinalize();\n return 0;\n}\n\nPetscErrorCode FormRHSFunction(TS ts, double t, Vec y, Vec g, void *ptr) {\n const double *ay;\n double *ag;\n VecGetArrayRead(y,&ay);\n VecGetArray(g,&ag);\n ag[0] = ay[1];\n ag[1] = - ay[0] + 0.1 * ay[2];\n ag[2] = - 101.0 * ay[2];\n VecRestoreArrayRead(y,&ay);\n VecRestoreArray(g,&ag);\n return 0;\n}\n\nPetscErrorCode FormRHSJacobian(TS ts, double t, Vec y, Mat J, Mat P,\n void *ptr) {\n PetscErrorCode ierr;\n int j[3] = {0, 1, 2};\n double v[9] = { 0.0, 1.0, 0.0,\n -1.0, 0.0, 0.1,\n 0.0, 0.0, -101.0};\n ierr = MatSetValues(P,3,j,3,j,v,INSERT_VALUES); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\n", "meta": {"hexsha": "bbc8093c6fb2b27eb3355b1837d18f4df6603404", "size": 2957, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/solns/stiff.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch5/solns/stiff.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch5/solns/stiff.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4945054945, "max_line_length": 76, "alphanum_fraction": 0.6371322286, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7879311981328135, "lm_q1q2_score": 0.6788328447989627}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* number of data points to fit */\n#define N 200\n\n/* number of fit coefficients */\n#define NCOEFFS 12\n\n/* nbreak = ncoeffs + 2 - k = ncoeffs - 2 since k = 4 */\n#define NBREAK (NCOEFFS - 2)\n\nint\nmain (void)\n{\n const size_t n = N;\n const size_t ncoeffs = NCOEFFS;\n const size_t nbreak = NBREAK;\n size_t i, j;\n gsl_bspline_workspace *bw;\n gsl_vector *B;\n double dy;\n gsl_rng *r;\n gsl_vector *c, *w;\n gsl_vector *x, *y;\n gsl_matrix *X, *cov;\n gsl_multifit_linear_workspace *mw;\n double chisq, Rsq, dof, tss;\n\n gsl_rng_env_setup();\n r = gsl_rng_alloc(gsl_rng_default);\n\n /* allocate a cubic bspline workspace (k = 4) */\n bw = gsl_bspline_alloc(4, nbreak);\n B = gsl_vector_alloc(ncoeffs);\n\n x = gsl_vector_alloc(n);\n y = gsl_vector_alloc(n);\n X = gsl_matrix_alloc(n, ncoeffs);\n c = gsl_vector_alloc(ncoeffs);\n w = gsl_vector_alloc(n);\n cov = gsl_matrix_alloc(ncoeffs, ncoeffs);\n mw = gsl_multifit_linear_alloc(n, ncoeffs);\n\n /* this is the data to be fitted */\n for (i = 0; i < n; ++i)\n {\n double sigma;\n double xi = (15.0 / (N - 1)) * i;\n double yi = cos(xi) * exp(-0.1 * xi);\n\n sigma = 0.1 * yi;\n dy = gsl_ran_gaussian(r, sigma);\n yi += dy;\n\n gsl_vector_set(x, i, xi);\n gsl_vector_set(y, i, yi);\n gsl_vector_set(w, i, 1.0 / (sigma * sigma));\n\n printf(\"%f %f\\n\", xi, yi);\n }\n\n /* use uniform breakpoints on [0, 15] */\n gsl_bspline_knots_uniform(0.0, 15.0, bw);\n\n /* construct the fit matrix X */\n for (i = 0; i < n; ++i)\n {\n double xi = gsl_vector_get(x, i);\n\n /* compute B_j(xi) for all j */\n gsl_bspline_eval(xi, B, bw);\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(X, i, j, Bj);\n }\n }\n\n /* do the fit */\n gsl_multifit_wlinear(X, w, y, c, cov, &chisq, mw);\n\n dof = n - ncoeffs;\n tss = gsl_stats_wtss(w->data, 1, y->data, 1, y->size);\n Rsq = 1.0 - chisq / tss;\n\n fprintf(stderr, \"chisq/dof = %e, Rsq = %f\\n\", \n chisq / dof, Rsq);\n\n printf(\"\\n\\n\");\n\n /* output the smoothed curve */\n {\n double xi, yi, yerr;\n\n for (xi = 0.0; xi < 15.0; xi += 0.1)\n {\n gsl_bspline_eval(xi, B, bw);\n gsl_multifit_linear_est(B, c, cov, &yi, &yerr);\n printf(\"%f %f\\n\", xi, yi);\n }\n }\n\n gsl_rng_free(r);\n gsl_bspline_free(bw);\n gsl_vector_free(B);\n gsl_vector_free(x);\n gsl_vector_free(y);\n gsl_matrix_free(X);\n gsl_vector_free(c);\n gsl_vector_free(w);\n gsl_matrix_free(cov);\n gsl_multifit_linear_free(mw);\n\n return 0;\n} /* main() */\n", "meta": {"hexsha": "311be68f7e0d206d12e29a2b11a042d899cb003b", "size": 2813, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/bspline.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/bspline.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/bspline.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 22.504, "max_line_length": 56, "alphanum_fraction": 0.5858514042, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6787601936751363}} {"text": "/* randist/cauchy.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The Cauchy probability distribution is \n\n p(x) dx = (1/(pi a)) (1 + (x/a)^2)^(-1) dx\n\n It is also known as the Lorentzian probability distribution */\n\ndouble\ngsl_ran_cauchy (const gsl_rng * r, const double a)\n{\n double u;\n do\n {\n u = gsl_rng_uniform (r);\n }\n while (u == 0.5);\n\n return a * tan (M_PI * u);\n}\n\ndouble\ngsl_ran_cauchy_pdf (const double x, const double a)\n{\n double u = x / a;\n double p = (1 / (M_PI * a)) / (1 + u * u);\n return p;\n}\n", "meta": {"hexsha": "7fffd6826f0fba5a4ec8c26c4467b313666c99c8", "size": 1416, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/cauchy.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/cauchy.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/cauchy.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.2307692308, "max_line_length": 81, "alphanum_fraction": 0.6836158192, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6783700376613574}} {"text": "/* expfit.c -- model functions for exponential + background */\n\n#include \n#include \n#include \n#include \n\nstruct usertype {\n size_t n;\n double * y;\n double * sigma;\n};\n\nint expb_f (const gsl_vector * x, void *data, \n gsl_vector * f) {\n size_t n = ((struct usertype *)data)->n;\n double *y = ((struct usertype *)data)->y;\n double *sigma = ((struct usertype *) data)->sigma;\n\n double A = gsl_vector_get (x, 0);\n double lambda = gsl_vector_get (x, 1);\n double b = gsl_vector_get (x, 2);\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n /* Model Yi = A * exp(-lambda * i) + b */\n double t = i;\n double Yi = A * exp (-lambda * t) + b;\n gsl_vector_set (f, i, (Yi - y[i])/sigma[i]);\n }\n\n return GSL_SUCCESS;\n}\n\nint expb_df (const gsl_vector * x, void *params, \n gsl_matrix * J) {\n\n struct usertype *myparams = (struct usertype *) params;\n \n int n = myparams->n;\n double *sigma = myparams->sigma;\n\n\n double A = gsl_vector_get (x, 0);\n double lambda = gsl_vector_get (x, 1);\n\n size_t i;\n \n /*for (i = 0; i<10; i++){\n printf(\"sigma[%z] = %5.3f\\n\",i,sigma[i]);\n }*/\n \n for (i = 0; i < n; i++)\n {\n /* Jacobian matrix J(i,j) = dfi / dxj, */\n /* where fi = (Yi - yi)/sigma[i], */\n /* Yi = A * exp(-lambda * i) + b */\n /* and the xj are the parameters (A,lambda,b) */\n double t = i;\n double s = sigma[i];\n double e = exp(-lambda * t);\n gsl_matrix_set (J, i, 0, e/s); \n gsl_matrix_set (J, i, 1, -t * A * e/s);\n gsl_matrix_set (J, i, 2, 1/s);\n }\n return GSL_SUCCESS;\n}\n\nint expb_fdf (const gsl_vector * x, void *data,\n gsl_vector * f, gsl_matrix * J) {\n\n expb_f (x, data, f);\n expb_df (x, data, J);\n\n return GSL_SUCCESS;\n}\n\nvoid eval_F ( int fstatus, const int n, const int m, \n\t const double *x, double *f, const void *params){\n \n // first, convert x from an array into a gsl_vector... \n gsl_vector * x_gsl = gsl_vector_alloc(n);\n int i;\n for (i = 0; i < n; i++) {\n gsl_vector_set(x_gsl,i,x[i]);\n }\n\n // then call the expb_f function\n gsl_vector * f_gsl = gsl_vector_alloc(m);\n\n expb_f ( x_gsl, params, f_gsl);\n \n // then convert f back into an array...\n // f = f_gsl->data;\n for (i = 0; i < m; i++){\n f[i] = gsl_vector_get( f_gsl,i);\n // f[i] = f_gsl->data[i];\n }\n \n gsl_vector_free(x_gsl);\n gsl_vector_free(f_gsl);\n\n}\n\n\nvoid eval_J ( int fstatus, const int n, const int m, \n\t const double *x, double *J, const void *params){\n\n // first, convert x from an array into a gsl_vector...\n gsl_vector * x_gsl = gsl_vector_alloc(n);\n int i;\n int jj;\n for (i = 0; i < n; i++) {\n gsl_vector_set(x_gsl,i,x[i]);\n }\n \n // then call the expb_f function\n gsl_matrix * J_gsl = gsl_matrix_alloc(40,3);\n expb_df (x_gsl, params, J_gsl);\n \n // then convert J into an array...\n // (find better way...)\n gsl_matrix * J_gsl_t = gsl_matrix_alloc(3,40);\n gsl_matrix_transpose_memcpy(J_gsl_t, J_gsl);\n for ( i = 0; i < m*n; i++){\n J[i] = J_gsl_t->data[i];\n }\n // the following code loses the pointer to J (maybe...)\n // J = J_gsl_t->data;\n gsl_vector_free(x_gsl);\n gsl_matrix_free(J_gsl);\n gsl_matrix_free(J_gsl_t);\n \n \n \n}\n\nvoid eval_HF ( int fstatus, const int n, const int m, \n\t const double *x, const double *f, double *hf, const void *params){\n \n}\n", "meta": {"hexsha": "1b30ae586c6cfee536151788f72468f4d26792cd", "size": 3393, "ext": "c", "lang": "C", "max_stars_repo_path": "libRALFit/example/C/expfit.c", "max_stars_repo_name": "andpic/RALFit", "max_stars_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-04-02T12:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:45.000Z", "max_issues_repo_path": "libRALFit/example/C/expfit.c", "max_issues_repo_name": "andpic/RALFit", "max_issues_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 95.0, "max_issues_repo_issues_event_min_datetime": "2016-09-13T15:16:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-23T14:08:27.000Z", "max_forks_repo_path": "libRALFit/example/C/expfit.c", "max_forks_repo_name": "andpic/RALFit", "max_forks_repo_head_hexsha": "d8bd77217b5163f79069eaf7c5238a854f4843e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-04-02T12:24:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-23T17:12:42.000Z", "avg_line_length": 23.5625, "max_line_length": 74, "alphanum_fraction": 0.5764809903, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6783566590804112}} {"text": "#include \n#include \n#include \"linterp.h\"\n#include \"qspline.h\"\n#include \"cspline.h\"\n#include \n\n#define NUM_DATAPOINTS 9\n\n\n/** Read a txt file with two columns seperated by tab and read all the items \n * into the arrays x and y.\n **/\nvoid read_data(double *x, double *y){\n FILE *infile = fopen(\"xy_data.txt\", \"r\");\n for (int i = 0; i < NUM_DATAPOINTS; ++i){\n int items = fscanf(infile, \"%lf\\t%lf\\n\", &x[i], &y[i]);\n if (items == EOF){\n break;\n }\n }\n fclose(infile);\n}\n\nvoid exerciseA(){\n FILE *outfile = fopen(\"out1.txt\", \"w\");\n double *x, *y;\n x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n read_data(x, y);\n\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n gsl_spline *spline = gsl_spline_alloc (gsl_interp_linear, NUM_DATAPOINTS);\n\n gsl_spline_init (spline, x, y, NUM_DATAPOINTS);\n\n double val = 0.1;\n do {\n double interp_val = linterp(NUM_DATAPOINTS, x, y, val);\n double interp_val_integ = linterp_integ(NUM_DATAPOINTS, x, y, val);\n double y_gsl = gsl_spline_eval(spline, val, acc);\n fprintf(outfile, \"%f\\t%f\\t%f\\t%f\\n\", val, interp_val, interp_val_integ, y_gsl);\n val += 0.1;\n } while (val < 8);\n gsl_spline_free (spline);\n gsl_interp_accel_free (acc);\n free(x), free(y);\n fclose(outfile);\n}\n\n\nvoid exerciseB(){\n FILE *outfile = fopen(\"out2.txt\", \"w\");\n double *x, *y;\n x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n read_data(x, y);\n\n double val = 0.1;\n do {\n double interp_val = qspline_eval(NUM_DATAPOINTS, x, y, val);\n double interp_val_integ = qspline_integ(NUM_DATAPOINTS, x, y, val);\n double interp_val_deriv = qspline_deriv(NUM_DATAPOINTS, x, y, val);\n fprintf(outfile, \"%f\\t%f\\t%f\\t%f\\n\", val, interp_val, interp_val_integ, interp_val_deriv);\n val += 0.1;\n } while (val < 8);\n free(x), free(y);\n fclose(outfile);\n}\n\n\nvoid exerciseC(){\n FILE *outfile = fopen(\"out3.txt\", \"w\");\n double *x, *y;\n x = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n y = (double *) malloc(sizeof(double *) * NUM_DATAPOINTS);\n read_data(x, y);\n\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, NUM_DATAPOINTS);\n\n gsl_spline_init (spline, x, y, NUM_DATAPOINTS);\n\n double val = 0.1;\n do {\n double interp_val = cspline_eval(NUM_DATAPOINTS, x, y, val);\n double interp_val_integ = cspline_integ(NUM_DATAPOINTS, x, y, val);\n double y_gsl = gsl_spline_eval(spline, val, acc);\n fprintf(outfile, \"%f\\t%f\\t%f\\t%f\\n\", val, interp_val, interp_val_integ, y_gsl);\n val += 0.1;\n } while (val < 8);\n gsl_spline_free (spline);\n gsl_interp_accel_free (acc);\n free(x), free(y);\n fclose(outfile);\n}\n\n\nint main(){\n exerciseA();\n exerciseB();\n exerciseC(); \n return 0;\n}", "meta": {"hexsha": "632e773c55ada69f7d78c1d39ce08ac379e9dd58", "size": 3076, "ext": "c", "lang": "C", "max_stars_repo_path": "homeworks/splines/c/main.c", "max_stars_repo_name": "mads-hb/ppnm-2022", "max_stars_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "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": "homeworks/splines/c/main.c", "max_issues_repo_name": "mads-hb/ppnm-2022", "max_issues_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "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": "homeworks/splines/c/main.c", "max_forks_repo_name": "mads-hb/ppnm-2022", "max_forks_repo_head_hexsha": "5311e70625223f94f23007205e718d3bc13f04e0", "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.5769230769, "max_line_length": 98, "alphanum_fraction": 0.616710013, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6780916976156212}} {"text": "#include \n#include \n#include \n#include \r\n#ifndef NOMPI\n#include \r\n#endif\n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n/*! \\file driftfac.c\n * \\brief compute loop-up tables for prefactors in cosmological integration\n */\n\nstatic double logTimeBegin;\nstatic double logTimeMax;\n\n\n/*! This function computes look-up tables for factors needed in\n * cosmological integrations. The (simple) integrations are carried out\n * with the GSL library. Separate factors are computed for the \"drift\",\n * and the gravitational and hydrodynamical \"kicks\". The lookup-table is\n * used for reasons of speed.\n */\nvoid init_drift_table(void)\n{\n#define WORKSIZE 100000\n int i;\n double result, abserr;\n gsl_function F;\n gsl_integration_workspace *workspace;\n\n logTimeBegin = log(All.TimeBegin);\n logTimeMax = log(All.TimeMax);\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n\n for(i = 0; i < DRIFT_TABLE_LENGTH; i++)\n {\n F.function = &drift_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n DriftTable[i] = result;\n\n\n F.function = &gravkick_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n GravKickTable[i] = result;\n\n\n F.function = &hydrokick_integ;\n gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,\n\t\t\t 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n HydroKickTable[i] = result;\n }\n\n gsl_integration_workspace_free(workspace);\n}\n\n\n/*! This function integrates the cosmological prefactor for a drift step\n * between time0 and time1. The value returned is * \\f[ \\int_{a_0}^{a_1}\n * \\frac{{\\rm d}a}{H(a)} * \\f]\n */\ndouble get_drift_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * DriftTable[0];\n else\n df1 = DriftTable[i1 - 1] + (DriftTable[i1] - DriftTable[i1 - 1]) * (u1 - i1);\n\n\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * DriftTable[0];\n else\n df2 = DriftTable[i2 - 1] + (DriftTable[i2] - DriftTable[i2 - 1]) * (u2 - i2);\n\n return df2 - df1;\n}\n\n\n/*! This function integrates the cosmological prefactor for a kick step of\n * the gravitational force.\n */\ndouble get_gravkick_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * GravKickTable[0];\n else\n df1 = GravKickTable[i1 - 1] + (GravKickTable[i1] - GravKickTable[i1 - 1]) * (u1 - i1);\n\n\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * GravKickTable[0];\n else\n df2 = GravKickTable[i2 - 1] + (GravKickTable[i2] - GravKickTable[i2 - 1]) * (u2 - i2);\n\n return df2 - df1;\n}\n\n/*! This function integrates the cosmological prefactor for a kick step of\n * the hydrodynamical force.\n */\ndouble get_hydrokick_factor(int time0, int time1)\n{\n double a1, a2, df1, df2, u1, u2;\n int i1, i2;\n\n /* note: will only be called for cosmological integration */\n\n a1 = logTimeBegin + time0 * All.Timebase_interval;\n a2 = logTimeBegin + time1 * All.Timebase_interval;\n\n u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i1 = (int) u1;\n if(i1 >= DRIFT_TABLE_LENGTH)\n i1 = DRIFT_TABLE_LENGTH - 1;\n\n if(i1 <= 1)\n df1 = u1 * HydroKickTable[0];\n else\n df1 = HydroKickTable[i1 - 1] + (HydroKickTable[i1] - HydroKickTable[i1 - 1]) * (u1 - i1);\n\n\n u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;\n i2 = (int) u2;\n if(i2 >= DRIFT_TABLE_LENGTH)\n i2 = DRIFT_TABLE_LENGTH - 1;\n\n if(i2 <= 1)\n df2 = u2 * HydroKickTable[0];\n else\n df2 = HydroKickTable[i2 - 1] + (HydroKickTable[i2] - HydroKickTable[i2 - 1]) * (u2 - i2);\n\n return df2 - df1;\n}\n\n\n/*! Integration kernel for drift factor computation.\n */\ndouble drift_integ(double a, void *param)\n{\n double h;\n\n h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;\n h = All.Hubble * sqrt(h);\n\n return 1 / (h * a * a * a);\n}\n\n/*! Integration kernel for gravitational kick factor computation.\n */\ndouble gravkick_integ(double a, void *param)\n{\n double h;\n\n h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;\n h = All.Hubble * sqrt(h);\n\n return 1 / (h * a * a);\n}\n\n\n/*! Integration kernel for hydrodynamical kick factor computation.\n */\ndouble hydrokick_integ(double a, void *param)\n{\n double h;\n\n h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;\n h = All.Hubble * sqrt(h);\n\n return 1 / (h * pow(a, 3 * GAMMA_MINUS1) * a);\n}\n\ndouble growthfactor_integ(double a, void *param)\n{\n double s;\n\n s = All.Omega0 + (1 - All.Omega0 - All.OmegaLambda) * a + All.OmegaLambda * a * a * a;\n s = sqrt(s);\n\n return pow(sqrt(a) / s, 3);\n}\n\n\n", "meta": {"hexsha": "533cb797f87ba7ac8d7feadc1c0845fff839dc78", "size": 6089, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/gadget2/src/driftfac.c", "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/gadget2/src/driftfac.c", "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/gadget2/src/driftfac.c", "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.8237885463, "max_line_length": 133, "alphanum_fraction": 0.6564296272, "num_tokens": 2052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6779568775185624}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n/*\n * convert_concentration_single finds the concentration c'\n * for a mass definition with overdensity Delta' given\n * the concentration c for a mass definition with overdensity\n * Delta assuming an NFW density profile.\n *\n * To do so, it solves the following equation numerically:\n * c^3 * f(c) = Delta' f(c')\n * where f(x) = x^3 * (x + 1) / ((1+x) * log(x + 1) - x).\n * \n * The equation is solved using a Newton-Raphson approach.\n * The functions nfw_fx, nfw_f, nfw_df and nfw_fdf implement\n * the function whose zero we try to find and its derivative.\n *\n * ccl_convert_concentration does the same thing for an\n * array of input concentrations.\n */\n\nstatic double nfw_fx(double x)\n{\n if(x>0.01) {\n double xp1=1+x;\n double lxp1=log(xp1);\n double den=1./(xp1*lxp1-x);\n return xp1*x*x*x*den;\n }\n else {\n return 2*x;\n }\n}\n\nstatic double nfw_f(double x,void *params)\n{\n double offset = *((double *)params);\n return nfw_fx(x)-offset;\n}\n\nstatic double nfw_df(double x,void *params)\n{\n if(x>0.01) {\n double xp1=1+x;\n double lxp1=log(xp1);\n double den=1./(xp1*lxp1-x);\n return x*x*(3*xp1*xp1*lxp1-x*(4*x+3))*den*den;\n }\n else {\n return 2;\n }\n}\n\nstatic void nfw_fdf(double x,void *params,\n\t\t double *y, double *dy)\n{\n double offset = *((double *)params);\n if(x>0.01) {\n double xp1=1+x;\n double lxp1=log(xp1);\n double den=1./(xp1*lxp1-x);\n *y=xp1*x*x*x*den-offset;\n *dy=x*x*(3*xp1*xp1*lxp1-x*(4*x+3))*den*den;\n }\n else {\n *y=2*x-offset;\n *dy=2;\n }\n}\n\nstatic int convert_concentration_single(double d_factor, double c_old,\n\t\t\t\t\tdouble *c_new, double c_start)\n{\n double c0, offset = d_factor * nfw_fx(c_old);\n int status, iter=0, max_iter=100;\n gsl_function_fdf FDF;\n gsl_root_fdfsolver *s=NULL;\n FDF.f = &nfw_f;\n FDF.df = &nfw_df;\n FDF.fdf = &nfw_fdf;\n FDF.params = &offset;\n \n s=gsl_root_fdfsolver_alloc(gsl_root_fdfsolver_newton);\n if (s==NULL)\n return CCL_ERROR_MEMORY;\n \n gsl_root_fdfsolver_set (s, &FDF, c_start);\n *c_new = c_start;\n do\n {\n iter++;\n c0 = *c_new;\n status = gsl_root_fdfsolver_iterate (s);\n *c_new = gsl_root_fdfsolver_root (s);\n status = gsl_root_test_delta (*c_new, c0, 0, 1e-4);\n\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n gsl_root_fdfsolver_free (s);\n\n return status;\n}\n\nvoid ccl_convert_concentration(ccl_cosmology *cosmo,\n\t\t\t double delta_old, int nc, double c_old[],\n\t\t\t double delta_new, double c_new[],int *status)\n{\n if(nc<=0)\n return;\n\n int ii,st=0;\n double d_factor = delta_old/delta_new;\n for(ii=0;ii\n#include\n#include \n#include \n#include \n#include \n\nvoid *xcalloc(int items, int size)\n{\n\tvoid *ptr = calloc(items, size);\n\tif (ptr == NULL)\n\t{\n\t\tprintf(\"Unable to allocate memory\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\treturn ptr;\n}\n\nvoid GetLGLPoints(int N, double *x)\n{\n\tif (N == 0)\n\t{\n\t\tprintf(\"Support for constants doesn't exist\\n\");\n\t\texit(1);\n\t}\n\telse if (N == 1)\n\t{\n\t\tx[0] = -1.0;\n\t\tx[1] = 1.0;\n\t}\n\telse if (N==2)\n\t{\n\t\tx[0] = -1.0;\n\t\tx[1] = 0.0;\n\t\tx[2] = 1.0;\n\t}\n\telse if (N==3)\n\t{\n\t\tx[0] = -1.0;\n\t\tx[1] = -0.4472;\n\t\tx[2] = 0.4472;\n\t\tx[3] = 1.0;\n\t}\n\telse if (N==4)\n\t{\n\t\tx[0] = -1.0;\n\t\tx[1] = -0.6547;\n\t\tx[2] = 0;\n\t\tx[3] = 0.6547;\n\t\tx[4] = 1.0;\n\t}\n\telse\n\t{\n\t\tprintf(\"Currently only have up to fourth order polynomial encoded for LGL points\\n\");\n\t\texit(1);\n\t}\n}\n\nvoid GetLGLWeights(int N, double *w)\n{\n\tif (N == 0)\n\t{\n\t\tprintf(\"Support for constants doesn't exist\\n\");\n\t\texit(1);\n\t}\n\telse if (N == 1)\n\t{\n\t\tw[0] = 1.0;\n\t\tw[1] = 1.0;\n\t}\n\telse if (N==2)\n\t{\n\t\tw[0] = 0.3333333333333;\n\t\tw[1] = 1.3333333333333;\n\t\tw[2] = 0.3333333333333;\n\t}\n\telse if (N==3)\n\t{\n\t\tw[0] = 0.16666666666667;\n\t\tw[1] = 0.83333333333333;\n\t\tw[2] = 0.83333333333333;\n\t\tw[3] = 0.16666666666667;\n\t}\n\telse if (N==4)\n\t{\n\t\tw[0] = 0.1;\n\t\tw[1] = 0.5444444;\n\t\tw[2] = 0.7111111;\n\t\tw[3] = 0.5444444;\n\t\tw[4] = 0.1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Currently only have up to fourth order polynomial encoded for LGL points\\n\");\n\t\texit(1);\n\t}\n\n}\n\nvoid calculateNodalCoordinates(int N, int NumEl, double* X, double* Xnodes)\n{\n\tdouble r[N+1];\n\tGetLGLPoints(N, r);\n\tfor(int i = 0; i < NumEl; i++)\n\t{\n\t\tfor (int j = 0; j < N+1; j++)\n\t\t{\n\t\t\tXnodes[i*(N+1)+j] = X[i] + 0.5*(r[j]+1)*(X[i+1]-X[i]);\n\t\t}\n\t}\n\n}\n\nvoid LegendrePoly(double *x, int Np, int N, double* P)\n{\n\t// Purpose: Evaluates the normalized Legendre polynomials \n\t// \t\t\t\t\tat points x for order N and returns the values in the\n\t// \t\t\t\t\tarray P that is Np long\n\t\n\tdouble aold = 0.0, anew=0.0;\n\n\tdouble **PL = xcalloc(N+1, sizeof(double*));\n\tfor (int i =0; i < N+1; i++)\n\t{\n\t\tPL[i] = xcalloc(Np, sizeof(double));\n\t}\n\n\t// Initial values P_0(x) and P_1(x)\n\tif (N==0)\n\t{\n\t\tdouble constVal = 1.0/sqrt(2);\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tP[j] = constVal;\n\t\t}\n\t\t\n\t\tfree(PL[0]);\n\t\tfree(PL); \n\t\treturn;\n\t}\n\telse\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tPL[0][j] = 1.0/sqrt(2);\n\t\t}\n\t}\n\t\n\tdouble *prow = xcalloc(Np, sizeof(double));\n\tdouble coeff = sqrt(1.5);\n\tfor (int i = 0; i < Np; i++)\n\t{\n\t\tprow[i] = coeff*x[i];\n\t}\n\n\tif(N==1)\n\t{\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tP[i] = prow[i];\n\t\t}\n\t\tfree(prow);\n\t\tfree(PL[0]);\n\t\tfree(PL[1]);\n\t\tfree(PL);\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tfor (int j =0; j < Np; j++)\n\t\t{\n\t\t\tPL[1][j] = coeff*x[j];\n\t\t}\n\n\t}\n\n\t// Repeat value in recurrence\n\taold = sqrt(1.0/3);\n\n\t// Forward recurrence\n\tfor (int i = 2; i <= N; i++)\n\t{\n\t\tanew = sqrt(i*i/((2.0*i+1)*(2*i-1)));\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tPL[i][j] = (x[j]*PL[i-1][j]-aold*PL[i-2][j])/anew;\n\t\t}\n\t\taold = anew;\n\t}\n\n\tfor (int j = 0; j < Np; j++)\n\t{\n\t\tP[j] = PL[N][j];\n\t}\n\n\tfor (int i =0; i < N; i++)\n\t{\n\t\tfree(PL[i]);\n\t}\n\tfree(PL);\n\n\treturn;\n}\n\nvoid Vandermonde1D(double *x, int Np, int N, gsl_matrix** V1D)\n{\n\t// Purpose: Evaluates the Vandermonde matrix V_{ij} = phi_i(r_j);\n\t\n\t*V1D = gsl_matrix_alloc(Np, N+1);\n\tdouble V1DT[Np];\n\tfor(int i = 0; i < N+1; i++)\n\t{\n\t\t\tLegendrePoly(x, Np, i, V1DT);\n\t\t\tfor (int j = 0; j < Np; j++)\n\t\t\t{\n\t\t\t\tgsl_matrix_set(*V1D, i, j, V1DT[j]);\n\t\t\t\t//gsl_matrix_set(*V1D, j, i, V1DT[j]);\n\t\t\t}\n\t}\n}\n\nvoid GradLegendrePoly(double *x, int Np, int N, double* DP)\n{\n\t// Purpose: Evaluates the derivatives of normalized Legendre polynomial \n\t// \t\t\t\t\tat points x for order N and returns the values in the\n\t// \t\t\t\t\tarray P that is Np long\n\t//\n\t\n\tdouble aold, anew;\n\n\tdouble **DPL = xcalloc(N+1, sizeof(double*));\n\tfor (int i =0; i < N+1; i++)\n\t{\n\t\tDPL[i] = xcalloc(Np, sizeof(double));\n\t}\n\n\t// Initial values P_0(x) and P_1(x)\n\tif (N==0)\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tDP[0] = 0;\n\t\t}\n\t\tfree(DPL[0]);\n\t\tfree(DPL); \n\t\treturn;\n\t}\n\telse\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tDPL[0][j] = 0;\n\t\t}\n\t}\n\t\n\tdouble *dprow = xcalloc(Np, sizeof(double));\n\tdouble deriv = sqrt(1.5);\n\tfor (int i = 0; i < Np; i++)\n\t{\n\t\tdprow[i] = deriv;\n\t}\n\n\tif(N==1)\n\t{\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tDP[i] = deriv;\n\t\t}\n\t\tfree(dprow);\n\t\tfree(DPL[0]);\n\t\tfree(DPL[1]);\n\t\tfree(DPL);\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tfor (int j =0; j < Np; j++)\n\t\t{\n\t\t\tDPL[1][j] = deriv;\n\t\t}\n\n\t}\n\n\t// Repeat value in recurrence\n\taold = sqrt(1.0/3);\n\n\t// Forward recurrence\n\tfor (int i = 2; i <= N; i++)\n\t{\n\t\tanew = sqrt(i*i/((2.0*i+1)*(2*i-1)));\n\t\tdouble P[Np];\n\t\tLegendrePoly(x, Np, i-1, P);\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tDPL[i][j] = 1.0/(anew)*(P[j] + x[j]*DPL[i-1][j] - aold*DPL[i-2][j]);\n\t\t}\n\t\taold = anew;\n\t}\n\n\tfor (int j = 0; j < Np; j++)\n\t{\n\t\tDP[j] = DPL[N][j];\n\t}\n\n\tfor (int i =0; i < N; i++)\n\t{\n\t\tfree(DPL[i]);\n\t}\n\tfree(DPL);\n\n\treturn;\n\n}\n\nvoid GradVandermonde1D(double *r, int Np, int N, gsl_matrix** GV)\n{\n\t// Purpose: Evaluates the gradient of modal basis (i) at (r)\n\t// \t\t\t\t\tat order N and return them in GV whose size is\n\t// \t\t\t\t\tixNp\n\t//\n\t*GV = gsl_matrix_alloc(Np, N+1);\n\tdouble GVT[Np];\n\tfor (int i =0; i < N+1; i++)\n\t{\n\t\tGradLegendrePoly(r, Np, i, GVT);\n\t\tfor (int j = 0; j < Np; j++)\n\t\t\tgsl_matrix_set(*GV,i,j, GVT[j]);\n\t\t\t//gsl_matrix_set(*GV,j,i,GVT[j]);\n\t}\n\n}\n\n\nvoid VolIntMat1D(double *x, int N, gsl_matrix* V, gsl_matrix *Vr, gsl_matrix** VolMat)\n{\n\t\n\tgsl_permutation *p = gsl_permutation_alloc(N+1);\n\tgsl_matrix *Vcopy = gsl_matrix_alloc(N+1, N+1);\n\tgsl_matrix_memcpy(Vcopy, V);\n\n\tgsl_matrix *Vinv = gsl_matrix_alloc(N+1, N+1);\n\t\n\tint s;\n\tgsl_linalg_LU_decomp(Vcopy, p, &s);\n\tgsl_linalg_LU_invert(Vcopy, p, Vinv); \n\n\tgsl_matrix *tmp1 = gsl_matrix_alloc(N+1, N+1);\n\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, Vinv, Vinv, 0.0, tmp1);\n\n\tgsl_matrix *tmp2 = gsl_matrix_alloc(N+1, N+1);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Vr, tmp1, 0.0, tmp2);\n\n\t*VolMat = gsl_matrix_alloc(N+1, N+1);\n\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, tmp2, 0.0, *\nVolMat);\n\t//gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Vr, Vinv, 0.0, *Dr);\n\n\tgsl_permutation_free(p);\n\tgsl_matrix_free(Vcopy);\n\tgsl_matrix_free(Vinv);\n\tgsl_matrix_free(tmp1);\n\tgsl_matrix_free(tmp2);\n\n}\n\nvoid Lift1D(int Np, gsl_matrix *V, gsl_matrix **LIFT)\n{\n\t*LIFT = gsl_matrix_alloc(Np,2);\n\t\n\tgsl_matrix *EMAT = gsl_matrix_calloc(Np, 2);\n\tgsl_matrix_set(EMAT, 0, 0, 1.0);\n\tgsl_matrix_set(EMAT, Np-1, 1, -1.0);\n\t\n\tgsl_matrix *tmp = gsl_matrix_alloc(Np,2);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, V, EMAT, 0.0, tmp);\n\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, tmp, 0.0, *LIFT);\n\n\tgsl_matrix_free(EMAT);\n\tgsl_matrix_free(tmp);\n\n}\n\nvoid calculateMassMatrix(int Np, gsl_matrix* V, gsl_matrix** MassMatrix)\n{\n\t*MassMatrix = gsl_matrix_alloc(Np,Np);\n\tgsl_matrix *MassMatrixInv = gsl_matrix_alloc(Np,Np);\n\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, V, V, 0.0, MassMatrixInv);\n\t\n\tint s = 0;\t\n\tgsl_permutation *p = gsl_permutation_alloc(Np);\n\tgsl_linalg_LU_decomp(MassMatrixInv, p, &s);\n\tgsl_linalg_LU_invert(MassMatrixInv, p, *MassMatrix);\n\n\tgsl_matrix_free(MassMatrixInv);\n\tgsl_permutation_free(p);\n\n}\n\nvoid calculateLIFTVolMat(int N, int Np, gsl_matrix **LIFT, gsl_matrix **VolMat,gsl_matrix **MassMatrix)\n{\n\tdouble r[Np];\n\tGetLGLPoints(N,r);\n\t\n\tgsl_matrix *V; \n\tgsl_matrix *GV;\n\n\tVandermonde1D(r,Np,N,&V);\n\tGradVandermonde1D(r, Np, N, &GV);\n\tVolIntMat1D(r, N, V, GV, VolMat);\n\tLift1D(Np, V, LIFT);\n\tcalculateMassMatrix(Np, V,MassMatrix);\n\n\tgsl_matrix_free(V);\n\tgsl_matrix_free(GV);\n\n}\n\n\n\n\n", "meta": {"hexsha": "8c64a3908598db0dda55e6e1c8d1fa35b6e1811c", "size": 7546, "ext": "c", "lang": "C", "max_stars_repo_path": "1DCode/BasisFunctionRoutines.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/BasisFunctionRoutines.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/BasisFunctionRoutines.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": 17.9239904988, "max_line_length": 103, "alphanum_fraction": 0.5805724887, "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.677366283596601}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\ndouble weff(double a) \n{\n if(a != 1.0)\n return cosmoData.w0 + cosmoData.wa - cosmoData.wa*(a - 1.0)/log(a);\n else\n return cosmoData.w0;\n}\n\ndouble hubble_noscale(double a)\n{\n return sqrt(cosmoData.OmegaM/a/a/a + cosmoData.OmegaK/a/a + cosmoData.OmegaL/pow(a,3.0*(1.0 + weff(a))));\n}\n", "meta": {"hexsha": "493f3ba62b7b48934d4d067a659f4ede698079a3", "size": 419, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hubble.c", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hubble.c", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/hubble.c", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 19.9523809524, "max_line_length": 107, "alphanum_fraction": 0.6634844869, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9553191309994468, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6773395427495558}} {"text": "/** @file */\n#ifndef __CCL_UTILS_H_INCLUDED__\n#define __CCL_UTILS_H_INCLUDED__\n\n#include \n\n#define CCL_MIN(a, b) (((a) < (b)) ? (a) : (b))\n#define CCL_MAX(a, b) (((a) > (b)) ? (a) : (b))\n\nCCL_BEGIN_DECLS\n\n/**\n * Compute bin edges of N-1 linearly spaced bins on the interval [xmin,xmax]\n * @param xmin minimum value of spacing\n * @param xmax maximum value of spacing\n * @param N number of bins plus one (number of bin edges)\n * @return x, bin edges in range [xmin, xmax]\n */\ndouble * ccl_linear_spacing(double xmin, double xmax, int N);\n\n/**\n * Compute bin edges of N-1 logarithmically and then linearly spaced bins on the interval [xmin,xmax]\n * @param xminlog minimum value of spacing\n * @param xmin value when logarithmical ends and linear spacing begins\n * @param xmax maximum value of spacing\n * @param Nlin number of linear bins plus one (number of bin edges)\n * @param Nlog number of logarithmic bins plus one (number of bin edges)\n * @return x, bin edges in range [xminlog, xmax]\n */\ndouble * ccl_linlog_spacing(double xminlog, double xmin, double xmax, int Nlin, int Nlog);\n\n/**\n * Compute bin edges of N-1 logarithmically spaced bins on the interval [xmin,xmax]\n * @param xmin minimum value of spacing\n * @param xmax maximum value of spacing\n * @param N number of bins plus one (number of bin edges)\n * @return x, bin edges in range [xmin, xmax]\n */\ndouble * ccl_log_spacing(double xmin, double xmax, int N);\n//Returns array of N logarithmically-spaced values between xmin and xmax\n\ndouble ccl_j_bessel(int l,double x);\n//Spherical Bessel function of order l (adapted from CAMB)\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "9b74e4ad7a7f124f539f54c7232adf9f45417c89", "size": 1631, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_utils.h", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ccl_utils.h", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ccl_utils.h", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 33.9791666667, "max_line_length": 101, "alphanum_fraction": 0.7222562845, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6765733486288666}} {"text": "/* multimin/test_funcs.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n\n#include \"test_funcs.h\"\n\ngsl_multimin_function_fdf rosenbrock =\n{&rosenbrock_f,\n &rosenbrock_df,\n &rosenbrock_fdf,\n 2, 0};\n\ngsl_multimin_function rosenbrock_fmin =\n{&rosenbrock_f,\n 2, 0};\n\nvoid rosenbrock_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, -1.2);\n gsl_vector_set (x, 1, 1.0);\n}\n\ndouble rosenbrock_f (const gsl_vector * x, void *params)\n{\n double u = gsl_vector_get(x,0);\n double v = gsl_vector_get(x,1);\n double a = u - 1;\n double b = u * u - v;\n fcount++;\n return a * a + 10 * b * b;\n}\n\nvoid rosenbrock_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n double u = gsl_vector_get(x,0);\n double v = gsl_vector_get(x,1);\n double b = u * u - v;\n gcount++;\n gsl_vector_set(df,0,2 * (u - 1) + 40 * u * b);\n gsl_vector_set(df,1,-20 * b); \n}\n\nvoid rosenbrock_fdf (const gsl_vector * x, void *params, double * f,\n gsl_vector * df) \n{\n double u = gsl_vector_get(x,0);\n double v = gsl_vector_get(x,1);\n double a = u - 1;\n double b = u * u - v;\n gcount++;\n *f = a * a + 10 * b * b;\n gsl_vector_set(df,0,2 * (u - 1) + 40 * u * b);\n gsl_vector_set(df,1,-20 * b); \n}\n\ngsl_multimin_function_fdf roth =\n{&roth_f,\n &roth_df,\n &roth_fdf,\n 2, 0};\n\ngsl_multimin_function roth_fmin =\n{&roth_f,\n 2, 0};\n\nvoid roth_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, 4.5);\n gsl_vector_set (x, 1, 3.5);\n}\n\ndouble roth_f (const gsl_vector * x, void *params)\n{\n double u = gsl_vector_get(x,0);\n double v = gsl_vector_get(x,1);\n double a = -13.0 + u + ((5.0 - v)*v - 2.0)*v;\n double b = -29.0 + u + ((v + 1.0)*v - 14.0)*v;\n fcount++;\n return a * a + b * b;\n}\n\nvoid roth_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n double u = gsl_vector_get(x,0);\n double v = gsl_vector_get(x,1);\n double a = -13.0 + u + ((5.0 - v)*v - 2.0)*v;\n double b = -29.0 + u + ((v + 1.0)*v - 14.0)*v;\n double c = -2 + v * (10 - 3 * v);\n double d = -14 + v * (2 + 3 * v);\n gcount++;\n gsl_vector_set(df,0,2 * a + 2 * b);\n gsl_vector_set(df,1,2 * a * c + 2 * b * d);\n}\n\nvoid roth_fdf (const gsl_vector * x, void *params, double * f,\n gsl_vector * df) \n{\n *f = roth_f (x,params);\n roth_df(x,params,df);\n}\n\ngsl_multimin_function_fdf wood =\n{&wood_f,\n &wood_df,\n &wood_fdf,\n 4, 0};\n\ngsl_multimin_function wood_fmin =\n{&wood_f,\n 4, 0};\n\nvoid\nwood_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, -3.0);\n gsl_vector_set (x, 1, -1.0);\n gsl_vector_set (x, 2, -3.0);\n gsl_vector_set (x, 3, -1.0);\n}\n\ndouble wood_f (const gsl_vector * x, void *params)\n{\n double u1 = gsl_vector_get(x,0);\n double u2 = gsl_vector_get(x,1);\n double u3 = gsl_vector_get(x,2);\n double u4 = gsl_vector_get(x,3);\n\n double t1 = u1 * u1 - u2;\n double t2 = u3 * u3 - u4;\n fcount++;\n return 100 * t1 * t1 + (1 - u1) * (1 - u1)\n + 90 * t2 * t2 + (1 - u3) * (1 - u3)\n + 10.1 * ( (1 - u2) * (1 - u2) + (1 - u4) * (1 - u4) )\n + 19.8 * (1 - u2) * (1 - u4);\n}\n\nvoid wood_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n double u1 = gsl_vector_get(x,0);\n double u2 = gsl_vector_get(x,1);\n double u3 = gsl_vector_get(x,2);\n double u4 = gsl_vector_get(x,3);\n\n double t1 = u1 * u1 - u2;\n double t2 = u3 * u3 - u4;\n gcount++;\n gsl_vector_set(df,0, 400 * u1 * t1 - 2 * (1 - u1) );\n gsl_vector_set(df,1, -200 * t1 - 20.2 * (1 - u2) - 19.8 * (1 - u4) );\n gsl_vector_set(df,2, 360 * u3 * t2 - 2 * (1 - u3) );\n gsl_vector_set(df,3, -180 * t2 - 20.2 * (1 - u4) - 19.8 * (1 - u2) );\n \n}\n\nvoid wood_fdf (const gsl_vector * x, void *params, double * f, gsl_vector * df)\n{\n wood_df(x,params,df);\n *f=wood_f(x,params);\n}\n\n\ngsl_multimin_function_fdf Nrosenbrock =\n{&rosenbrock_f,\n &Nrosenbrock_df,\n &Nrosenbrock_fdf,\n 2, 0};\n\nvoid Nrosenbrock_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n gsl_multimin_function F ;\n F.f = rosenbrock_f;\n F.params = params;\n F.n = x->size;\n gsl_multimin_diff (&F, x, df);\n}\n\nvoid Nrosenbrock_fdf (const gsl_vector * x, void *params, double * f,\n gsl_vector * df) \n{\n *f = rosenbrock_f (x, params);\n Nrosenbrock_df (x, params, df);\n}\n\ngsl_multimin_function_fdf Nroth =\n{&roth_f,\n &Nroth_df,\n &Nroth_fdf,\n 2, 0};\n\nvoid Nroth_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n gsl_multimin_function F ;\n F.f = roth_f;\n F.params = params;\n F.n = x->size;\n gsl_multimin_diff (&F, x, df);\n}\n\nvoid Nroth_fdf (const gsl_vector * x, void *params, double * f,\n gsl_vector * df) \n{\n *f = roth_f (x, params);\n Nroth_df (x, params, df);\n}\n\n\ngsl_multimin_function_fdf Nwood =\n{&wood_f,\n &Nwood_df,\n &Nwood_fdf,\n 4, 0};\n\nvoid Nwood_df (const gsl_vector * x, void *params, gsl_vector * df)\n{\n gsl_multimin_function F ;\n F.f = wood_f;\n F.params = params;\n F.n = x->size;\n gsl_multimin_diff (&F, x, df);\n}\n\nvoid Nwood_fdf (const gsl_vector * x, void *params, double * f,\n gsl_vector * df) \n{\n *f = wood_f (x, params);\n Nwood_df (x, params, df);\n}\n", "meta": {"hexsha": "34081af1881d4d1a93378b347a0f7834ae8b97ca", "size": 5778, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/multimin/test_funcs.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/multimin/test_funcs.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/multimin/test_funcs.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.5836734694, "max_line_length": 81, "alphanum_fraction": 0.6161301488, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.675898444363362}} {"text": "#include \n#include \n#include \n//#include \n#include \n#include \n\nextern void* xcalloc(int NumPoints, int size);\n\n/*void eval_NUBspline_1d_d(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val);\n\nvoid eval_NUBspline_1d_d_vg(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val, double* restrict grad);\n\nvoid eval_NUBspline_1d_d_vgl(NUBspline_1d_d * restrict spline, double x, \n\tdouble* restrict val, double* restrict grad, double* restrict lapl);\n\n\nvoid InterpolateWithSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* y, double* NodalX, double* NodalY, double *func, double *NodalFunc, double* NodalDeriv)\n{\n\n\tdouble *s = xcalloc(NumPointsToInterpolate, sizeof(double));\n\tdouble *NodalS = xcalloc(NumPointsToEvaluate, sizeof(double));\n\tfor (int j = 0; j < NumPointsToInterpolate; j++)\n\t{\n\t\ts[i] = sqrt(pow(x[j]-x[0],2)+pow(y[j]-y[0],2));\n\n\t}\n\n\tfor(int j = 0; j < NumPointsToEvaluate, j++)\n\t{\n\t\tNodalS[i] = sqrt(pow(NodalX[j] -x[0],2) + pow(NodalY[j]-y[0],2));\n\t}\n\n\tNUgrid* myGrid = create_general_grid(s, NumPointsToInterpolate);\n\tBCtype_d myBC;\n\tmyBC.lCode = NATURAL;\n\tmyBC.rCode = NATURAL;\n\tNUBspline_1d_d *mySpline = create_NUBspline_1d_d(myGrid, myBC, func);\n\tfor(int i =0; i < NumPointsToEvaluate; i++)\n\t{\n\t\tif (NodalDeriv != NULL)\n\t\t\teval_NUBspline_1d_d_vg(mySpline, NodalS[i], &NodalFunc[i], &NodalDeriv[i]);\n\t\telse\n\t\t\teval_NUBspline_1d_d(mySpline, NodalS[i], &NodalFunc[i]);\n\t}\n\n\tfree(s);\n\tfree(NodalS);\n\n}\n*/\n\nvoid InterpolateWithGSLSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* y, double* NodalX, double* NodalY, double* func, double* NodalFunc, double* NodalDeriv)\n{\n\tdouble *s = xcalloc(NumPointsToInterpolate, sizeof(double));\n\tdouble *NodalS = xcalloc(NumPointsToEvaluate, sizeof(double));\n\tfor (int j = 0; j < NumPointsToInterpolate; j++)\n\t{\n\t\ts[j] = sqrt(pow(x[j]-x[0],2)+pow(y[j]-y[0],2));\n\n\t}\n\n\tfor(int j = 0; j < NumPointsToEvaluate; j++)\n\t{\n\t\tNodalS[j] = sqrt(pow(NodalX[j] -x[0],2) + pow(NodalY[j]-y[0],2));\n\t}\n\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n\tgsl_spline* spline = gsl_spline_alloc(gsl_interp_cspline, NumPointsToInterpolate);\n\tgsl_spline_init(spline, s, func, NumPointsToInterpolate);\n\n\tfor(int j = 0; j < NumPointsToEvaluate; j++)\n\t{\n\t\tNodalFunc[j] = gsl_spline_eval(spline, NodalS[j], acc);\n\t\tif (NodalDeriv != NULL)\n\t\t\tNodalDeriv[j] = gsl_spline_eval_deriv(spline, NodalS[j], acc);\n\t}\n\n\tgsl_interp_accel_free(acc);\n\tgsl_spline_free(spline);\n\tfree(s);\n\tfree(NodalS);\n\n}\n", "meta": {"hexsha": "e626c85af63af82620f11411651bedd19e36a6c1", "size": 2581, "ext": "c", "lang": "C", "max_stars_repo_path": "DGSHED/spline_interpolation.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": "DGSHED/spline_interpolation.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": "DGSHED/spline_interpolation.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": 29.6666666667, "max_line_length": 190, "alphanum_fraction": 0.7125145293, "num_tokens": 877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.675809399189416}} {"text": "/* randist/exppow.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006 James Theiler, Brian Gough\n * Copyright (C) 2006 Giulio Bottazzi\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\n/* The exponential power probability distribution is \n\n p(x) dx = (1/(2 a Gamma(1+1/b))) * exp(-|x/a|^b) dx\n\n for -infty < x < infty. For b = 1 it reduces to the Laplace\n distribution. \n\n The exponential power distribution is related to the gamma\n distribution by E = a * pow(G(1/b),1/b), where E is an exponential\n power variate and G is a gamma variate.\n\n We use this relation for b < 1. For b >=1 we use rejection methods\n based on the laplace and gaussian distributions which should be\n faster. For b>4 we revert to the gamma method.\n\n See P. R. Tadikamalla, \"Random Sampling from the Exponential Power\n Distribution\", Journal of the American Statistical Association,\n September 1980, Volume 75, Number 371, pages 683-686.\n \n*/\n\ndouble\ngsl_ran_exppow (const gsl_rng * r, const double a, const double b)\n{\n if (b < 1 || b > 4)\n {\n double u = gsl_rng_uniform (r);\n double v = gsl_ran_gamma (r, 1 / b, 1.0);\n double z = a * pow (v, 1 / b);\n\n if (u > 0.5)\n {\n return z;\n }\n else\n {\n return -z;\n }\n }\n else if (b == 1)\n {\n /* Laplace distribution */\n return gsl_ran_laplace (r, a);\n }\n else if (b < 2)\n {\n /* Use laplace distribution for rejection method, from Tadikamalla */\n\n double x, h, u;\n\n double B = pow (1 / b, 1 / b);\n\n do\n {\n x = gsl_ran_laplace (r, B);\n u = gsl_rng_uniform_pos (r);\n h = -pow (fabs (x), b) + fabs (x) / B - 1 + (1 / b);\n }\n while (log (u) > h);\n\n return a * x;\n }\n else if (b == 2)\n {\n /* Gaussian distribution */\n return gsl_ran_gaussian (r, a / sqrt (2.0));\n }\n else\n {\n /* Use gaussian for rejection method, from Tadikamalla */\n\n double x, h, u;\n\n double B = pow (1 / b, 1 / b);\n\n do\n {\n x = gsl_ran_gaussian (r, B);\n u = gsl_rng_uniform_pos (r);\n h = -pow (fabs (x), b) + (x * x) / (2 * B * B) + (1 / b) - 0.5;\n }\n while (log (u) > h);\n\n return a * x;\n }\n}\n\ndouble\ngsl_ran_exppow_pdf (const double x, const double a, const double b)\n{\n double p;\n double lngamma = gsl_sf_lngamma (1 + 1 / b);\n p = (1 / (2 * a)) * exp (-pow (fabs (x / a), b) - lngamma);\n return p;\n}\n", "meta": {"hexsha": "c307e4c11677f7661076e1d7d6551e97cc4ba3d1", "size": 3316, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/exppow.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/exppow.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/exppow.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.9593495935, "max_line_length": 81, "alphanum_fraction": 0.5962002413, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6753389431151147}} {"text": "/* linalg/qr.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"givens.c\"\n#include \"apply_givens.c\"\n\n/* Factorise a general 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 * Q is stored as a packed set of Householder transformations in the\n * strict lower triangular part of the input matrix.\n *\n * R is stored in the diagonal and upper triangle of the input matrix.\n *\n * The full matrix for Q can be obtained as the product\n *\n * Q = Q_k .. Q_2 Q_1\n *\n * where k = MIN(M,N) and\n *\n * Q_i = (I - tau_i * v_i * v_i')\n *\n * and where v_i is a Householder vector\n *\n * v_i = [1, m(i+1,i), m(i+2,i), ... , m(M,i)]\n *\n * This storage scheme is the same as in LAPACK. */\n\nint\ngsl_linalg_QR_decomp (gsl_matrix * A, gsl_vector * tau)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n /* Compute the Householder transformation to reduce the j-th\n column of the matrix to a multiple of the j-th unit vector */\n\n gsl_vector_view c_full = gsl_matrix_column (A, i);\n gsl_vector_view c = gsl_vector_subvector (&(c_full.vector), i, M-i);\n\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 and\n update the norms */\n\n if (i + 1 < N)\n {\n gsl_matrix_view m = gsl_matrix_submatrix (A, i, i + 1, M - i, N - (i + 1));\n gsl_linalg_householder_hm (tau_i, &(c.vector), &(m.matrix));\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* Solves the system A x = b using the QR factorisation,\n\n * R x = Q^T b\n *\n * to obtain x. Based on SLATEC code. \n */\n\nint\ngsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x)\n{\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (QR->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_memcpy (x, b);\n\n /* Solve for x */\n\n gsl_linalg_QR_svx (QR, tau, x);\n\n return GSL_SUCCESS;\n }\n}\n\n/* Solves the system A x = b in place using the QR factorisation,\n\n * R x = Q^T b\n *\n * to obtain x. Based on SLATEC code. \n */\n\nint\ngsl_linalg_QR_svx (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * x)\n{\n\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match x/rhs size\", GSL_EBADLEN);\n }\n else\n {\n /* compute rhs = Q^T b */\n\n gsl_linalg_QR_QTvec (QR, tau, x);\n\n /* Solve R x = rhs, storing x in-place */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Find the least squares solution to the overdetermined system \n *\n * A x = b \n * \n * for M >= N using the QR factorization A = Q R. \n */\n\nint\ngsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau, const gsl_vector * b, gsl_vector * x, gsl_vector * residual)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"QR matrix must have M>=N\", GSL_EBADLEN);\n }\n else if (M != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (N != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else if (M != residual->size)\n {\n GSL_ERROR (\"matrix size must match residual size\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view R = gsl_matrix_const_submatrix (QR, 0, 0, N, N);\n gsl_vector_view c = gsl_vector_subvector(residual, 0, N);\n\n gsl_vector_memcpy(residual, b);\n\n /* compute rhs = Q^T b */\n\n gsl_linalg_QR_QTvec (QR, tau, residual);\n\n /* Solve R x = rhs */\n\n gsl_vector_memcpy(x, &(c.vector));\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &(R.matrix), x);\n\n /* Compute residual = b - A x = Q (Q^T b - R x) */\n \n gsl_vector_set_zero(&(c.vector));\n\n gsl_linalg_QR_Qvec(QR, tau, residual);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_QR_Rsolve (const gsl_matrix * QR, const gsl_vector * b, gsl_vector * x)\n{\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (QR->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match x size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_memcpy (x, b);\n\n /* Solve R x = b, storing x in-place */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_QR_Rsvx (const gsl_matrix * QR, gsl_vector * x)\n{\n if (QR->size1 != QR->size2)\n {\n GSL_ERROR (\"QR matrix must be square\", GSL_ENOTSQR);\n }\n else if (QR->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match rhs size\", GSL_EBADLEN);\n }\n else\n {\n /* Solve R x = b, storing x in-place */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_R_solve (const gsl_matrix * R, const gsl_vector * b, gsl_vector * x)\n{\n if (R->size1 != R->size2)\n {\n GSL_ERROR (\"R matrix must be square\", GSL_ENOTSQR);\n }\n else if (R->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (R->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_memcpy (x, b);\n\n /* Solve R x = b, storing x inplace in b */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_R_svx (const gsl_matrix * R, gsl_vector * x)\n{\n if (R->size1 != R->size2)\n {\n GSL_ERROR (\"R matrix must be square\", GSL_ENOTSQR);\n }\n else if (R->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Solve R x = b, storing x inplace in b */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\n\n/* Form the product Q^T v from a QR factorized matrix \n */\n\nint\ngsl_linalg_QR_QTvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (v->size != M)\n {\n GSL_ERROR (\"vector size must be N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q^T v */\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n gsl_vector_const_view c = gsl_matrix_const_column (QR, i);\n gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector), i, M - i);\n gsl_vector_view w = gsl_vector_subvector (v, i, M - i);\n double ti = gsl_vector_get (tau, i);\n gsl_linalg_householder_hv (ti, &(h.vector), &(w.vector));\n }\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_QR_Qvec (const gsl_matrix * QR, const gsl_vector * tau, gsl_vector * v)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (v->size != M)\n {\n GSL_ERROR (\"vector size must be N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q^T v */\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n gsl_vector_const_view c = gsl_matrix_const_column (QR, i);\n gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector), \n i, M - i);\n gsl_vector_view w = gsl_vector_subvector (v, i, M - i);\n double ti = gsl_vector_get (tau, i);\n gsl_linalg_householder_hv (ti, &h.vector, &w.vector);\n }\n return GSL_SUCCESS;\n }\n}\n\n/* Form the product Q^T A from a QR factorized matrix */\n\nint\ngsl_linalg_QR_QTmat (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * A)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (A->size1 != M)\n {\n GSL_ERROR (\"matrix must have M rows\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute Q^T A */\n\n for (i = 0; i < GSL_MIN (M, N); i++)\n {\n gsl_vector_const_view c = gsl_matrix_const_column (QR, i);\n gsl_vector_const_view h = gsl_vector_const_subvector (&(c.vector), i, M - i);\n gsl_matrix_view m = gsl_matrix_submatrix(A, i, 0, M - i, A->size2);\n double ti = gsl_vector_get (tau, i);\n gsl_linalg_householder_hm (ti, &(h.vector), &(m.matrix));\n }\n return GSL_SUCCESS;\n }\n}\n\n\n/* Form the orthogonal matrix Q from the packed QR matrix */\n\nint\ngsl_linalg_QR_unpack (const gsl_matrix * QR, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * R)\n{\n const size_t M = QR->size1;\n const size_t N = QR->size2;\n\n if (Q->size1 != M || Q->size2 != M)\n {\n GSL_ERROR (\"Q matrix must be M x M\", GSL_ENOTSQR);\n }\n else if (R->size1 != M || R->size2 != N)\n {\n GSL_ERROR (\"R matrix must be M x N\", GSL_ENOTSQR);\n }\n else if (tau->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau must be MIN(M,N)\", GSL_EBADLEN);\n }\n else\n {\n size_t i, j;\n\n /* Initialize Q to the identity */\n\n gsl_matrix_set_identity (Q);\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n gsl_vector_const_view c = gsl_matrix_const_column (QR, i);\n gsl_vector_const_view h = gsl_vector_const_subvector (&c.vector,\n i, M - i);\n gsl_matrix_view m = gsl_matrix_submatrix (Q, i, i, M - i, M - i);\n double ti = gsl_vector_get (tau, i);\n gsl_linalg_householder_hm (ti, &h.vector, &m.matrix);\n }\n\n /* Form the right triangular matrix R from a packed QR matrix */\n\n for (i = 0; i < M; i++)\n {\n for (j = 0; j < i && j < N; j++)\n gsl_matrix_set (R, i, j, 0.0);\n\n for (j = i; j < N; j++)\n gsl_matrix_set (R, i, j, gsl_matrix_get (QR, i, j));\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/* Update a QR factorisation for A= Q R , A' = A + u v^T,\n\n * Q' R' = QR + u v^T\n * = Q (R + Q^T u v^T)\n * = Q (R + w v^T)\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_QR_update (gsl_matrix * Q, gsl_matrix * R,\n gsl_vector * w, const gsl_vector * v)\n{\n const size_t M = R->size1;\n const size_t N = R->size2;\n\n if (Q->size1 != M || Q->size2 != M)\n {\n GSL_ERROR (\"Q matrix must be M x M if R is M x N\", GSL_ENOTSQR);\n }\n else if (w->size != M)\n {\n GSL_ERROR (\"w must be length M if R is M x N\", GSL_EBADLEN);\n }\n else if (v->size != N)\n {\n GSL_ERROR (\"v must be length N if R is M x N\", GSL_EBADLEN);\n }\n else\n {\n size_t j, k;\n double w0;\n\n /* Apply Given's rotations to reduce w to (|w|, 0, 0, ... , 0)\n\n J_1^T .... J_(n-1)^T w = +/- |w| e_1\n\n simultaneously applied to R, H = J_1^T ... J^T_(n-1) R\n so that H is upper Hessenberg. (12.5.2) */\n\n for (k = M - 1; k > 0; k--) /* loop from k = M-1 to 1 */\n {\n double c, s;\n double wk = gsl_vector_get (w, k);\n double wkm1 = gsl_vector_get (w, k - 1);\n\n create_givens (wkm1, wk, &c, &s);\n apply_givens_vec (w, k - 1, k, c, s);\n apply_givens_qr (M, N, Q, R, k - 1, k, c, s);\n }\n\n w0 = gsl_vector_get (w, 0);\n\n /* Add in w v^T (Equation 12.5.3) */\n\n for (j = 0; j < N; j++)\n {\n double r0j = gsl_matrix_get (R, 0, j);\n double vj = gsl_vector_get (v, j);\n gsl_matrix_set (R, 0, j, r0j + w0 * vj);\n }\n\n /* Apply Givens transformations R' = G_(n-1)^T ... G_1^T H\n Equation 12.5.4 */\n\n for (k = 1; k < GSL_MIN(M,N+1); k++)\n {\n double c, s;\n double diag = gsl_matrix_get (R, k - 1, k - 1);\n double offdiag = gsl_matrix_get (R, k, k - 1);\n\n create_givens (diag, offdiag, &c, &s);\n apply_givens_qr (M, N, Q, R, k - 1, k, c, s);\n\n gsl_matrix_set (R, k, k - 1, 0.0); /* exact zero of G^T */\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_QR_QRsolve (gsl_matrix * Q, gsl_matrix * R, const gsl_vector * b, gsl_vector * x)\n{\n const size_t M = R->size1;\n const size_t N = R->size2;\n\n if (M != N)\n {\n return GSL_ENOTSQR;\n }\n else if (Q->size1 != M || b->size != M || x->size != M)\n {\n return GSL_EBADLEN;\n }\n else\n {\n /* compute sol = Q^T b */\n\n gsl_blas_dgemv (CblasTrans, 1.0, Q, b, 0.0, x);\n\n /* Solve R x = sol, storing x in-place */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, R, x);\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "126a382305932a2d53827b9530e155121ad03d5d", "size": 14773, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/linalg/qr.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/linalg/qr.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/linalg/qr.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.6627712855, "max_line_length": 130, "alphanum_fraction": 0.5669803019, "num_tokens": 4550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.674575340765785}} {"text": "/* randist/tdist.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/* The t-distribution has the form\n\n p(x) dx = (Gamma((nu + 1)/2)/(sqrt(pi nu) Gamma(nu/2))\n * (1 + (x^2)/nu)^-((nu + 1)/2) dx\n\n The method used here is the one described in Knuth */\n\ndouble\ngsl_ran_tdist (const gsl_rng * r, const double nu)\n{\n if (nu <= 2)\n {\n double Y1 = gsl_ran_ugaussian (r);\n double Y2 = gsl_ran_chisq (r, nu);\n\n double t = Y1 / sqrt (Y2 / nu);\n\n return t;\n }\n else\n {\n double Y1, Y2, Z, t;\n do\n\t{\n\t Y1 = gsl_ran_ugaussian (r);\n\t Y2 = gsl_ran_exponential (r, 1 / (nu/2 - 1));\n\n\t Z = Y1 * Y1 / (nu - 2);\n\t}\n while (1 - Z < 0 || exp (-Y2 - Z) > (1 - Z));\n\n /* Note that there is a typo in Knuth's formula, the line below\n\t is taken from the original paper of Marsaglia, Mathematics of\n\t Computation, 34 (1980), p 234-256 */\n\n t = Y1 / sqrt ((1 - 2 / nu) * (1 - Z));\n return t;\n }\n}\n\ndouble\ngsl_ran_tdist_pdf (const double x, const double nu)\n{\n double p;\n\n double lg1 = gsl_sf_lngamma (nu / 2);\n double lg2 = gsl_sf_lngamma ((nu + 1) / 2);\n\n p = ((exp (lg2 - lg1) / sqrt (M_PI * nu)) \n * pow ((1 + x * x / nu), -(nu + 1) / 2));\n return p;\n}\n\n\n", "meta": {"hexsha": "1faae4c69586957a5d6640e85669fd9dd3c35ff1", "size": 2100, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/tdist.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/randist/tdist.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/randist/tdist.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.9259259259, "max_line_length": 72, "alphanum_fraction": 0.6228571429, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6741172058554917}} {"text": "/* specfunc/gsl_sf_bessel.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_BESSEL_H__\n#define __GSL_SF_BESSEL_H__\n\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\n\n/* Regular Bessel Function J_0(x)\n *\n * exceptions: none\n */\nint gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_J0(const double x);\n\n\n/* Regular Bessel Function J_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_J1(const double x);\n\n\n/* Regular Bessel Function J_n(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Jn(const int n, const double x);\n\n\n/* Regular Bessel Function J_n(x), nmin <= n <= nmax\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array);\n\n\n/* Irregular Bessel function Y_0(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Y0(const double x);\n\n\n/* Irregular Bessel function Y_1(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Y1(const double x);\n\n\n/* Irregular Bessel function Y_n(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Yn(const int n,const double x);\n\n\n/* Irregular Bessel function Y_n(x), nmin <= n <= nmax\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array);\n\n\n/* Regular modified Bessel function I_0(x)\n *\n * exceptions: GSL_EOVRFLW\n */\nint gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_I0(const double x);\n\n\n/* Regular modified Bessel function I_1(x)\n *\n * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_I1(const double x);\n\n\n/* Regular modified Bessel function I_n(x)\n *\n * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_In(const int n, const double x);\n\n\n/* Regular modified Bessel function I_n(x) for n=nmin,...,nmax\n *\n * nmin >=0, nmax >= nmin\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_In_array(const int nmin, const int nmax, const double x, double * result_array);\n\n\n/* Scaled regular modified Bessel function\n * exp(-|x|) I_0(x)\n *\n * exceptions: none\n */\nint gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_I0_scaled(const double x);\n\n\n/* Scaled regular modified Bessel function\n * exp(-|x|) I_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_I1_scaled(const double x);\n\n\n/* Scaled regular modified Bessel function\n * exp(-|x|) I_n(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_In_scaled(const int n, const double x);\n\n\n/* Scaled regular modified Bessel function\n * exp(-|x|) I_n(x) for n=nmin,...,nmax\n *\n * nmin >=0, nmax >= nmin\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_In_scaled_array(const int nmin, const int nmax, const double x, double * result_array);\n\n\n/* Irregular modified Bessel function K_0(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_K0(const double x);\n\n\n/* Irregular modified Bessel function K_1(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_K1(const double x);\n\n\n/* Irregular modified Bessel function K_n(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Kn(const int n, const double x);\n\n\n/* Irregular modified Bessel function K_n(x) for n=nmin,...,nmax\n *\n * x > 0.0, nmin >=0, nmax >= nmin\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array);\n\n\n/* Scaled irregular modified Bessel function\n * exp(x) K_0(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_K0_scaled(const double x);\n\n\n/* Scaled irregular modified Bessel function\n * exp(x) K_1(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result); \ndouble gsl_sf_bessel_K1_scaled(const double x);\n\n\n/* Scaled irregular modified Bessel function\n * exp(x) K_n(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Kn_scaled(const int n, const double x);\n\n\n/* Scaled irregular modified Bessel function exp(x) K_n(x) for n=nmin,...,nmax\n *\n * x > 0.0, nmin >=0, nmax >= nmin\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array);\n\n\n/* Regular spherical Bessel function j_0(x) = sin(x)/x\n *\n * exceptions: none\n */\nint gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_j0(const double x);\n\n\n/* Regular spherical Bessel function j_1(x) = (sin(x)/x - cos(x))/x\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_j1(const double x);\n\n\n/* Regular spherical Bessel function j_2(x) = ((3/x^2 - 1)sin(x) - 3cos(x)/x)/x\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_j2(const double x);\n\n\n/* Regular spherical Bessel function j_l(x)\n *\n * l >= 0, x >= 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_jl(const int l, const double x);\n\n\n/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_jl_array(const int lmax, const double x, double * result_array);\n\n\n/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax\n * Uses Steed's method.\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_jl_steed_array(const int lmax, const double x, double * jl_x_array);\n\n\n/* Irregular spherical Bessel function y_0(x)\n *\n * exceptions: none\n */\nint gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_y0(const double x);\n\n\n/* Irregular spherical Bessel function y_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_y1(const double x);\n\n\n/* Irregular spherical Bessel function y_2(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_y2(const double x);\n\n\n/* Irregular spherical Bessel function y_l(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_yl(const int l, const double x);\n\n\n/* Irregular spherical Bessel function y_l(x) for l=0,1,...,lmax\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_yl_array(const int lmax, const double x, double * result_array);\n\n\n/* Regular scaled modified spherical Bessel function\n *\n * Exp[-|x|] i_0(x)\n *\n * exceptions: none\n */\nint gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_i0_scaled(const double x);\n\n\n/* Regular scaled modified spherical Bessel function\n *\n * Exp[-|x|] i_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_i1_scaled(const double x);\n\n\n/* Regular scaled modified spherical Bessel function\n *\n * Exp[-|x|] i_2(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_i2_scaled(const double x);\n\n\n/* Regular scaled modified spherical Bessel functions\n *\n * Exp[-|x|] i_l(x)\n *\n * i_l(x) = Sqrt[Pi/(2x)] BesselI[l+1/2,x]\n *\n * l >= 0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_il_scaled(const int l, const double x);\n\n\n/* Regular scaled modified spherical Bessel functions\n *\n * Exp[-|x|] i_l(x)\n * for l=0,1,...,lmax\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array);\n\n\n/* Irregular scaled modified spherical Bessel function\n * Exp[x] k_0(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_k0_scaled(const double x);\n\n\n/* Irregular modified spherical Bessel function\n * Exp[x] k_1(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW\n */\nint gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_k1_scaled(const double x);\n\n\n/* Irregular modified spherical Bessel function\n * Exp[x] k_2(x)\n *\n * x > 0.0\n * exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW\n */\nint gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_k2_scaled(const double x);\n\n\n/* Irregular modified spherical Bessel function\n * Exp[x] k_l[x]\n *\n * k_l(x) = Sqrt[Pi/(2x)] BesselK[l+1/2,x]\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_kl_scaled(const int l, const double x);\n\n\n/* Irregular scaled modified spherical Bessel function\n * Exp[x] k_l(x)\n *\n * for l=0,1,...,lmax\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_kl_scaled_array(const int lmax, const double x, double * result_array);\n\n\n/* Regular cylindrical Bessel function J_nu(x)\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Jnu(const double nu, const double x);\n\n\n/* Irregular cylindrical Bessel function Y_nu(x)\n *\n * exceptions: \n */\nint gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Ynu(const double nu, const double x);\n\n\n/* Regular cylindrical Bessel function J_nu(x)\n * evaluated at a series of x values. The array\n * contains the x values. They are assumed to be\n * strictly ordered and positive. The array is\n * over-written with the values of J_nu(x_i).\n *\n * exceptions: GSL_EDOM, GSL_EINVAL\n */\nint gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v);\n\n\n/* Scaled modified cylindrical Bessel functions\n *\n * Exp[-|x|] BesselI[nu, x]\n * x >= 0, nu >= 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Inu_scaled(double nu, double x);\n\n\n/* Modified cylindrical Bessel functions\n *\n * BesselI[nu, x]\n * x >= 0, nu >= 0\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Inu(double nu, double x);\n\n\n/* Scaled modified cylindrical Bessel functions\n *\n * Exp[+|x|] BesselK[nu, x]\n * x > 0, nu >= 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Knu_scaled(const double nu, const double x);\n\n\n/* Modified cylindrical Bessel functions\n *\n * BesselK[nu, x]\n * x > 0, nu >= 0\n *\n * exceptions: GSL_EDOM, GSL_EUNDRFLW\n */\nint gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_Knu(const double nu, const double x);\n\n\n/* Logarithm of modified cylindrical Bessel functions.\n *\n * Log[BesselK[nu, x]]\n * x > 0, nu >= 0\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result);\ndouble gsl_sf_bessel_lnKnu(const double nu, const double x);\n\n\n/* s'th positive zero of the Bessel function J_0(x).\n *\n * exceptions: \n */\nint gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result);\ndouble gsl_sf_bessel_zero_J0(unsigned int s);\n\n\n/* s'th positive zero of the Bessel function J_1(x).\n *\n * exceptions: \n */\nint gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result);\ndouble gsl_sf_bessel_zero_J1(unsigned int s);\n\n\n/* s'th positive zero of the Bessel function J_nu(x).\n *\n * exceptions: \n */\nint gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result);\ndouble gsl_sf_bessel_zero_Jnu(double nu, unsigned int s);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_BESSEL_H__ */\n", "meta": {"hexsha": "cf45d55d0fe660423556018dc4dc648716cf2334", "size": 14068, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gsl/gsl_sf_bessel.h", "max_stars_repo_name": "iti-luebeck/HANSE2011", "max_stars_repo_head_hexsha": "0bd5b3f1e0bc5a02516e7514b2241897337334c2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/gsl_sf_bessel.h", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "gsl/include/gsl/gsl_sf_bessel.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "avg_line_length": 25.6247723133, "max_line_length": 105, "alphanum_fraction": 0.7345038385, "num_tokens": 4194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.673684584295572}} {"text": "/* AUTORIGHTS\nCopyright (C) 2007 Princeton University\n \nThis file is part of Ferret Toolkit.\n\nFerret Toolkit is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2, or (at your option)\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software Foundation,\nInc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*/\n#include \n#ifdef _OPENMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \"LSH.h\"\n#include \"local.h\"\n\n#define ERR\t1e-4\n\nstruct local_params\n{\n\tdouble a;\n\tdouble b;\n\tdouble W;\n\tint M;\n\tint L;\n\tint K;\n};\n\n\nstatic inline double p_col_helper (double x)\n{\n\tdouble result;\n\tresult = 2.0*gsl_cdf_ugaussian_P(x) - 1.0;\n\tresult += sqrt(2.0/M_PI) * (exp(-x*x/2.0)-1.0)/x;\n\treturn result; \n}\n\nstatic inline double p_col (double x, double W, int M, int L)\n{\n\treturn 1.0 - pow(1.0 - pow(p_col_helper(W/x), M), L);\n}\n\nstatic int fun (const gsl_vector *x, void *params, gsl_vector *f)\n{\n\tdouble W = ((struct local_params *)params)->W;\n\tint M = ((struct local_params *)params)->M;\n\tint L = ((struct local_params *)params)->L;\n\tint K = ((struct local_params *)params)->K;\n\tdouble fa = ((struct local_params *)params)->a;\n\tdouble fb = ((struct local_params *)params)->b;\n\tdouble sxx, sxy, sx, sy, k, d;\n\tdouble a, b;\n\tint n;\n\n\tdouble alpha = gsl_vector_get(x, 0);\n\tdouble beta = gsl_vector_get(x, 1);\n\n\tsxx = sxy = sx = sy = 0;\n\n\tn = 0;\n\tk = 0;\n\twhile ((k < K) && (n < 1000))\n\t{\n\t\tdouble lk, ld;\n\t\tn++;\n\t\td = alpha * pow(n, beta);\n\t\tk += p_col(sqrt(d), W, M, L);\n\t\tlk = log(k);\n\t\tld = log(d);\n\t\tsx += lk;\n\t\tsy += ld;\n\t\tsxx += lk * lk;\n\t\tsxy += lk * ld;\n\t}\n\t\n\tleast_squares(&a, &b, n, sxx, sxy, sx, sy);\n\n\ta = exp(a);\n\n\tgsl_vector_set(f, 0, a - fa);\n\tgsl_vector_set(f, 1, b - fb);\n\treturn GSL_SUCCESS;\n}\n\nint print_state (size_t iter, gsl_multiroot_fsolver *s)\n{\n\tfprintf(stderr, \"iter = %3zu x = %.3f %.3f \"\n\t\t\"f(x) = %.3e %.3e\\n\",\n\t\titer, \n\t\tgsl_vector_get(s->x, 0),\n\t\tgsl_vector_get(s->x, 1),\n\t\tgsl_vector_get(s->f, 0),\n\t\tgsl_vector_get(s->f, 1));\n\treturn 0;\n}\n\nint localdim (double a, double b, double *alpha, double *beta, double W, int M, int L, int K)\n{\n\tconst gsl_multiroot_fsolver_type *T = NULL;\n\tgsl_multiroot_fsolver *s = NULL;\n\n\tint status;\n\tsize_t iter = 0;\n\n\tstruct local_params params = {.a = a, .b = b, .W = W, .M = M, .L = L, .K = K};\n\tgsl_multiroot_function f = {&fun, 2, ¶ms};\n\n\tgsl_vector *x = gsl_vector_alloc(2);\n\tgsl_vector_set(x, 0, a);\n\tgsl_vector_set(x, 1, b);\n\n\tif (s == NULL)\n\t{\n\t\tT = gsl_multiroot_fsolver_hybrids;\n\t\ts = gsl_multiroot_fsolver_alloc(T, 2);\n\t}\n\n\tgsl_multiroot_fsolver_set(s, &f, x);\n\n\tdo\n\t{\n\t\tstatus = gsl_multiroot_fsolver_iterate(s);\n\n//\t\tprint_state(iter, s);\n\n\t\tif (status) break;\n\n\t\tstatus = gsl_multiroot_test_residual(s->f, ERR);\n\t\titer++;\n\t} while ((status == GSL_CONTINUE) && (iter < 1000));\n\n//\tfprintf(stderr, \"status = %s\\n\", gsl_strerror(status));\n\t*alpha = gsl_vector_get(s->x, 0);\n\t*beta = gsl_vector_get(s->x, 1);\n\n\tgsl_multiroot_fsolver_free(s);\n\tgsl_vector_free(x);\n\treturn 0;\n}\n\nint LSH_est_init (LSH_est_t *est, int a_step, double a_min, double a_max,\n\t\t\t\tint b_step, double b_min, double b_max, double W, int M, int L, int K)\n{\n\tdouble a_delta, b_delta;\n\tint i, j;\n\test->a_step = a_step;\n\test->b_step = b_step;\n\test->a_min = a_min;\n\test->b_min = b_min;\n\test->a_max = a_max;\n\test->b_max = b_max;\n\ta_delta = est->a_delta = (a_max - a_min) / a_step;\n\tb_delta = est->b_delta = (b_max - b_min) / b_step;\n\test->a_table = type_matrix_alloc(double , a_step, b_step);\n\test->b_table = type_matrix_alloc(double , a_step, b_step);\n\n\tfor (i = 0; i < a_step; i++)\n\t{\n\t\tfor (j = 0; j < b_step; j++)\n\t\t{\n\t\t\tlocaldim(a_min + i * a_delta,\n\t\t\t\tb_min + j * b_delta,\n\t\t\t\t&est->a_table[i][j],\n\t\t\t\t&est->b_table[i][j],\n\t\t\t\tW, M, L, K);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "5a46af74ba18f906182acc4530b5a9996cb9af6f", "size": 4251, "ext": "c", "lang": "C", "max_stars_repo_path": "bench/ferret/src/src/lsh/local.c", "max_stars_repo_name": "wustl-pctg/PORRidge", "max_stars_repo_head_hexsha": "68add84d77c61c26bbf180ba55c85decf7e142eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T06:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-10T06:22:32.000Z", "max_issues_repo_path": "bench/ferret/src/src/lsh/local.c", "max_issues_repo_name": "wustl-pctg/PORRidge", "max_issues_repo_head_hexsha": "68add84d77c61c26bbf180ba55c85decf7e142eb", "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": "bench/ferret/src/src/lsh/local.c", "max_forks_repo_name": "wustl-pctg/PORRidge", "max_forks_repo_head_hexsha": "68add84d77c61c26bbf180ba55c85decf7e142eb", "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.8548387097, "max_line_length": 93, "alphanum_fraction": 0.6523171019, "num_tokens": 1407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6729787936337337}} {"text": "/* specfunc/bessel_sequence.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\n#define DYDX_p(p,u,x) (-(p)/(x) + (((nu)*(nu))/((x)*(x))-1.0)*(u))\n#define DYDX_u(p,u,x) (p)\n\nstatic int\nrk_step(double nu, double x, double dx, double * Jp, double * J)\n{\n double p_0 = *Jp;\n double u_0 = *J;\n\n double p_1 = dx * DYDX_p(p_0, u_0, x);\n double u_1 = dx * DYDX_u(p_0, u_0, x);\n\n double p_2 = dx * DYDX_p(p_0 + 0.5*p_1, u_0 + 0.5*u_1, x + 0.5*dx);\n double u_2 = dx * DYDX_u(p_0 + 0.5*p_1, u_0 + 0.5*u_1, x + 0.5*dx);\n\n double p_3 = dx * DYDX_p(p_0 + 0.5*p_2, u_0 + 0.5*u_2, x + 0.5*dx);\n double u_3 = dx * DYDX_u(p_0 + 0.5*p_2, u_0 + 0.5*u_2, x + 0.5*dx);\n\n double p_4 = dx * DYDX_p(p_0 + p_3, u_0 + u_3, x + dx);\n double u_4 = dx * DYDX_u(p_0 + p_3, u_0 + u_3, x + dx);\n\n *Jp = p_0 + p_1/6.0 + p_2/3.0 + p_3/3.0 + p_4/6.0;\n *J = u_0 + u_1/6.0 + u_2/3.0 + u_3/3.0 + u_4/6.0;\n\n return GSL_SUCCESS;\n}\n\n\nint\ngsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v)\n{\n /* CHECK_POINTER(v) */\n\n if(nu < 0.0) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(size == 0) {\n GSL_ERROR (\"error\", GSL_EINVAL);\n }\n else {\n const gsl_prec_t goal = GSL_MODE_PREC(mode);\n const double dx_array[] = { 0.001, 0.03, 0.1 }; /* double, single, approx */\n const double dx_nominal = dx_array[goal];\n\n const int cnu = (int) ceil(nu);\n const double nu13 = pow(nu,1.0/3.0);\n const double smalls[] = { 0.01, 0.02, 0.4, 0.7, 1.3, 2.0, 2.5, 3.2, 3.5, 4.5, 6.0 };\n const double x_small = ( nu >= 10.0 ? nu - nu13 : smalls[cnu] );\n\n gsl_sf_result J0, J1;\n double Jp, J;\n double x;\n size_t i = 0;\n\n /* Calculate the first point. */\n x = v[0];\n gsl_sf_bessel_Jnu_e(nu, x, &J0);\n v[0] = J0.val;\n ++i;\n\n /* Step over the idiot case where the\n * first point was actually zero.\n */\n if(x == 0.0) {\n if(v[1] <= x) {\n /* Strict ordering failure. */\n GSL_ERROR (\"error\", GSL_EFAILED);\n }\n x = v[1];\n gsl_sf_bessel_Jnu_e(nu, x, &J0);\n v[1] = J0.val;\n ++i;\n }\n\n /* Calculate directly as long as the argument\n * is small. This is necessary because the\n * integration is not very good there.\n */\n while(v[i] < x_small && i < size) {\n if(v[i] <= x) {\n /* Strict ordering failure. */\n GSL_ERROR (\"error\", GSL_EFAILED);\n }\n x = v[i];\n gsl_sf_bessel_Jnu_e(nu, x, &J0);\n v[i] = J0.val;\n ++i;\n }\n\n /* At this point we are ready to integrate.\n * The value of x is the last calculated\n * point, which has the value J0; v[i] is\n * the next point we need to calculate. We\n * calculate nu+1 at x as well to get\n * the derivative, then we go forward.\n */\n gsl_sf_bessel_Jnu_e(nu+1.0, x, &J1);\n J = J0.val;\n Jp = -J1.val + nu/x * J0.val;\n\n while(i < size) {\n const double dv = v[i] - x;\n const int Nd = (int) ceil(dv/dx_nominal);\n const double dx = dv / Nd;\n double xj;\n int j;\n\n if(v[i] <= x) {\n /* Strict ordering failure. */\n GSL_ERROR (\"error\", GSL_EFAILED);\n }\n\n /* Integrate over interval up to next sample point.\n */\n for(j=0, xj=x; j\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"qdm.h\"\n\nvoid\nqdm_ispline_vector(\n gsl_vector *result,\n const double tau,\n const size_t spline_df,\n const gsl_vector *knots\n)\n{\n size_t bin = qdm_vector_search(knots, tau);\n\n gsl_vector_set(result, 0, 1);\n\n for (size_t m = 0; m < result->size - 1; m++) {\n double v;\n\n if (bin < m) {\n v = 0;\n } else if (bin - spline_df + 1 > m) {\n v = 1;\n } else if (bin == m) {\n double n = gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 3);\n double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double d3 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m);\n\n v = n / (d1 * d2 * d3);\n } else if (bin == m + 1) {\n double i1n = 3 * tau;\n double i1d = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i1 = i1n / i1d;\n\n double i2n = -gsl_sf_pow_int(tau - gsl_vector_get(knots, m), 3);\n double i2d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i2d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double i2d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i2 = i2n / (i2d1 * i2d2 * i2d3);\n\n double i3n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 3);\n double i3d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);\n double i3d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i3d3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i3 = i3n / (i3d1 * i3d2 * i3d3);\n\n double i4an = -3 * gsl_vector_get(knots, m + 1);\n double i4ad = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i4a = i4an / i4ad;\n double i4bn = gsl_sf_pow_int(gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m), 3);\n double i4bd1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i4bd2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double i4bd3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i4b = i4bn / (i4bd1 * i4bd2 * i4bd3);\n double i4cn = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1), 3);\n double i4cd1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);\n double i4cd2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i4cd3 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m + 1);\n double i4c = i4cn / (i4cd1 * i4cd2 * i4cd3);\n double i4 = i4a + i4b - i4c;\n\n double i5 = 0;\n if (m != 1) {\n double i5n = gsl_sf_pow_int(gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m), 3);\n double i5d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double i5d2 = gsl_vector_get(knots, m + 2) - gsl_vector_get(knots, m);\n double i5d3 = gsl_vector_get(knots, m + 1) - gsl_vector_get(knots, m);\n i5 = i5n / (i5d1 * i5d2 * i5d3);\n }\n\n v = i1 + i2 + i3 + i4 + i5;\n } else {\n double n = gsl_sf_pow_int(gsl_vector_get(knots, m + 3) - tau, 3);\n double d1 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m);\n double d2 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 1);\n double d3 = gsl_vector_get(knots, m + 3) - gsl_vector_get(knots, m + 2);\n double d = d1 * d2 * d3;\n\n v = 1 - n / d;\n }\n\n gsl_vector_set(result, m + 1, v);\n }\n}\n\nvoid\nqdm_ispline_matrix(\n gsl_matrix *result,\n const gsl_vector *taus,\n const size_t spline_df,\n const gsl_vector *knots\n)\n{\n for (size_t i = 0; i < result->size1; i++) {\n gsl_vector_view row = gsl_matrix_row(result, i);\n qdm_ispline_vector(&row.vector, gsl_vector_get(taus, i), spline_df, knots);\n }\n}\n", "meta": {"hexsha": "795763e981977d894566799168dd0709f537e81f", "size": 3978, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ispline.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/ispline.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/ispline.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": 36.8333333333, "max_line_length": 99, "alphanum_fraction": 0.6126194067, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6726097547939075}} {"text": "/*******************************************/\n/* libScalar: -lm */\n/* -lIO */\n/* */\n/* Scalar Arithmetic Operations and Macros */\n/* */\n/* Nov 11 1999 Ju Li */\n/*******************************************/\n\n#ifndef _Scalar_h\n#define _Scalar_h\n\n#include \n#include \n#include \n#include \n#include \n\n/** Mathematical Constants **/\n\n#define HALF (0.5)\n#define THIRD (1./3.)\n#define FOURTH (0.25)\n#define FIFTH (0.2)\n#define SIXTH (1./6.)\n#define SEVENTH (1./7.)\n#define EIGHTH (0.125)\n#define NINTH (1./9.)\n#define TENTH (1./10.)\n#define ELEVENTH (1./11.)\n#define TWELFTH (1./12.)\n\n/* extended precision to 60 digits: see Notes/mathconst.mws */\n#define SQRT2 (1.41421356237309504880168872420969807856967187537694807317668)\n#define SQRT3 (1.73205080756887729352744634150587236694280525381038062805581)\n#define SQRT5 (2.23606797749978969640917366873127623544061835961152572427090)\n#define SQRT6 (2.44948974278317809819728407470589139196594748065667012843269)\n#define SQRT7 (2.64575131106459059050161575363926042571025918308245018036833)\n#define SQRT8 (2.82842712474619009760337744841939615713934375075389614635336)\n#define CBRT2 (1.25992104989487316476721060727822835057025146470150798008198)\n#define CBRT3 (1.44224957030740838232163831078010958839186925349935057754642)\n#define CBRT4 (1.58740105196819947475170563927230826039149332789985300980829)\n#define CBRT5 (1.70997594667669698935310887254386010986805511054305492438286)\n#define CBRT6 (1.81712059283213965889121175632726050242821046314121967148133)\n#define CBRT7 (1.91293118277238910119911683954876028286243905034587576621065)\n#define CBRT9 (2.08008382305190411453005682435788538633780534037326210969759)\n/* (-1+sqrt(5.))/2 */\n#define GOLDEN_RATIO \\\n (.618033988749894848204586834365638117720309179805762862135450)\n#define GOLDEN_RATIO_RECIPROCAL (GOLDEN_RATIO + 1)\n\n#ifndef PI\n#define PI (3.14159265358979323846264338327950288419716939937510582097494)\n#endif\n#define RADIAN_TO_DEGREE(r) ((r)/PI*180.)\n#define DEGREE_TO_RADIAN(d) ((d)/180.*PI)\n\n#define SIN(x) sin(DEGREE_TO_RADIAN(x))\n#define COS(x) cos(DEGREE_TO_RADIAN(x))\n#define TAN(x) tan(DEGREE_TO_RADIAN(x))\n#define ASIN(x) RADIAN_TO_DEGREE(asin(x))\n#define ACOS(x) RADIAN_TO_DEGREE(acos(x))\n#define ATAN(x) RADIAN_TO_DEGREE(atan(x))\n\n#ifndef EPS\n/* IEEE 754 floating-point arithmetic relative error bound */\n#define EPS (2.220446e-16)\n#endif\n\n/* Deemed reasonably large number of floating point operations */\n#ifndef REASONABLE_FLOPS\n#define REASONABLE_FLOPS (1000)\n#endif\n/* on variables to estimate their likely numerical relative error */\n\n/* When the condition number gets bad, for instance if subtracting */\n/* two close numbers, we should override the above to larger value */\n\n#ifndef TINY /* as compared to unity */\n#define TINY (REASONABLE_FLOPS*EPS)\n#endif\n\n#ifndef HUGE /* as compared to unity */\n#define HUGE (1./TINY)\n#endif\n\n#ifndef HUGE_INT\n#define HUGE_INT (INT_MAX/2)\n#endif\n\n/* Close to the floating-point overflow */\n/* IEEE 754 32-bit floating-point standard: 1.175494e-38 to 3.402823e38 */\n#define SINGLE_PRECISION_INFINITY (1e37)\n/* IEEE 754 64-bit floating-point standard: 2.225074e-308 to 1.797693e308 */\n#define DOUBLE_PRECISION_INFINITY (1e307)\n\n#ifndef SMALL /* as compared to unity */\n#define SMALL (sqrt(EPS))\n#endif\n\n#ifndef LARGE /* as compared to unity */\n #define LARGE (1./SMALL)\n#endif\n\n/* a wise choice for estimating quadratic curvature */\n#ifndef DELTA /* as compared to unity */\n#define DELTA (sqrt(sqrt(EPS)))\n#endif\n\n/* very large exponent for later purposes of defining inf-norm, etc. */\n#ifndef EXPONENT_INFINITY\n#define EXPONENT_INFINITY (16.)\n#endif\n\n#define EQ(x,y) ( (x) == (y) )\n#define GE(x,y) ( (x) >= (y) )\n#define GT(x,y) ( (x) > (y) )\n#define LE(x,y) ( (x) <= (y) )\n#define LT(x,y) ( (x) < (y) )\n/* x = [lower_bound, upper_bound] */\n#define XIN(x,lower_bound,upper_bound) (GE(x,lower_bound) && LE(x,upper_bound))\n#define XINW(x,width) XIN(x,0.,width)\n/* more likely to overflow than underflow, I think */\n#define XOU(x,lower_bound,upper_bound) (GT(x,upper_bound) || LT(x,lower_bound))\n#define XOUW(x,width) XOU(x,0.,width)\n/* with no assumption about which is bigger, bound1 or bound2 */\n#define INSIDE(x,bound1,bound2) (XIN(x,bound1,bound2) || XIN(x,bound2,bound1))\n#define OUSIDE(x,bound1,bound2) (XOU(x,bound1,bound2) && XOU(x,bound2,bound1))\n/* i = [lower_bound, upper_bound) */\n#define IN(i,lower_bound,upper_bound) (GE(i,lower_bound) && LT(i,upper_bound))\n#define INW(i,n) IN(i,0,n) /* i = 0..n-1, C convention */\n#define OU(i,lower_bound,upper_bound) (GE(i,upper_bound) || LT(i,lower_bound))\n#define OUW(i,n) OU(i,0,n)\n\n#define ABS(x) ((x)>0?(x):-(x))\n#define ABS_LE(x,positive_bound) XIN(x,-(positive_bound),(positive_bound))\n#define ABS_GT(x,positive_bound) XOU(x,-(positive_bound),(positive_bound))\n#define ABS_LT(x,positive_bound) \\\n (GT(x,-(positive_bound)) && LT(x,(positive_bound)))\n#define ABS_GE(x,positive_bound) \\\n (GE(x,(positive_bound)) || LE(x,-(positive_bound)))\n\n#ifndef MIN \n#define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n#ifndef MAX\n#define MAX(x,y) ((x)>(y)?(x):(y))\n#endif\n#define SWAP(x,y,tmp) ((tmp)=(x), (x)=(y), (y)=(tmp))\n#define SWITCH(p,q,state0,state1) CAN ( if ((p) == (state0)) \\\n { (p)=(state1); (q)=(state0); } else { (p)=(state0); (q)=(state1); } )\n#define SWITCHSTATE(p,q,state) SWITCH(p,q,state,(state)+1)\n#define ENSURE(min,max,tmp) { if (min>max) SWAP(min,max,tmp); }\n#define FIND3(x0,x1,x2,op,xm) CAN( xm = x0; \\\n if (xm op x1) xm = x1; if (xm op x2) xm = x2 )\n#define FIND4(x0,x1,x2,x3,op,xm) CAN( xm = x0; \\\n if (xm op x1) xm = x1; if (xm op x2) xm = x2; if (xm op x3) xm = x3 )\n#define BEPOSITIVE(x) CAN( if ((x) < 0) x = -(x) )\n#define SQUARE(i) ((i)*(i))\n#define CUBE(i) ((i)*(i)*(i))\n#define QUAD(i) ((i)*(i)*(i)*(i))\n#define CEIL(i,j) (((i)<=0)?0:((i)-1)/(j)+1)\n#define SEIL(i,j) ((size_t)CEIL(i,j))\n#define ROUNDUP_TO(i,j) (CEIL(i,j)*(j))\n#define SEPARATION(x,y) (fabs((x)-(y)))\n#define SMALLSEPARATION(x,y,z) (fabs((x)-(y))= 0.) && ((x) < 1.) )\n#define NEED_TRIM(x) ( ((x) < 0.) || ((x) >= 1.) )\n#define Trim(x) { if ((x)<0) do (x)++; while((x)<0); else \\\n if ((x)>=1) do (x)--; while ((x)>=1); }\n/* faster than TRIM(x) when x is around 1 */\n#define TRIM(x) ((x)-floor((double)(x))) /* x's image on [0,1) */\n/* faster than Trim(x) when x is very large */\n\n#define NONEED_IMAGE(x) ( ((x) >= -0.5) && ((x) < 0.5) )\n#define NEED_IMAGE(x) ( ((x) < -0.5) || ((x) >= 0.5) )\n#define Image(x) { if ((x)<-0.5) do (x)++; while((x)<-0.5); else \\\n if ((x)>=0.5) do (x)--; while ((x)>=0.5); }\n/* faster than IMAGE(x) when x is around 1 */\n#define IMAGE(x) (TRIM(x+0.5)-0.5) /* x's image on [-0.5,0.5) */\n/* faster than Image(x) when x is very large */\n\n#define DISTANCE2(x,y,z) (SQUARE(x)+SQUARE(y)+SQUARE(z))\n#define DISTANCE(x,y,z) sqrt(DISTANCE2(x,y,z))\n#define DISTANCED2(x,y) (SQUARE(x)+SQUARE(y))\n#define DISTANCE2D(x,y) sqrt(DISTANCED2(x,y))\n\n/* b^2 = c^2 - a^2: the answer b will be nonnegative */\n#define SafePythagorasComplement(c,a) \\\n ( (c)>fabs(a) ? sqrt(SQUARE(c)-SQUARE(a)) : 0 )\n\n/* x is floating-point */\n#define Floor(x) (((x)==(int)(x))?(int)(x):(((x)>0)?((int)(x)):((int)(x)-1)))\n#define FLOOR(x,i) { (i)=(int)(x); if ((i)>(x)) (i)--; }\n\n#if defined(_alpha)\n/* Compaq C warns about negative shifts which cannot actually happen */\n#define SAFE_RSHIFT(a,n) ( ((n)>=0) ? ((a)>>ABS(n)) : ((a)<=0) ? ((a)<>ABS(n)) )\n#else\n#define SAFE_RSHIFT(a,n) ( ((n)>=0) ? ((a)>>(n)) : ((a)<<(-(n))) )\n#define SAFE_LSHIFT(a,n) ( ((n)>=0) ? ((a)<<(n)) : ((a)>>(-(n))) )\n#endif\n\n/* x, target can now be of any numeric type */\n#define ERR(x,target) Ferr((double)(x), (double)(target))\n\n#define ISTINY(a) (fabs(a)=TINY)\n#define ISSMALL(a) (fabs(a)=SMALL)\n#define ISDELTA(a) (fabs(a)=DELTA)\n#define NEAR(x,y) ISTINY((x)-(y))\n#define NOTNEAR(x,y) NOTTINY((x)-(y))\n\n/* whether x and y are equal to floating point accuracy */\n#define EQUAL(x,y) ((fabs((double)(x-y)) 0.5)\n\n/* randomly pick an integer in min..max (set {min,min+1... max}) */\n#define Fran(min,max) (INT(min)+(int)floor((INT(max)-INT(min)+1)*Frandom()))\n/* randomly pick an integer in min..max-1 (set {min,min+1... max-1}) */\n#define fran(min,max) (INT(min)+(int)floor((INT(max)-INT(min))*Frandom()))\n\n/* return normally distributed random number with =E, <(x-E)^2>=sigma2 */\n#define Frandnorm(E,sigma2) \\\n(sqrt(-2.*log(Frandom()))*sin(2*acos(-1.)*Frandom())*sqrt((double)sigma2)+E)\n/* The above is not most efficient. For array assignment, use Vfrandnorm() */\n\n/* return normally distributed random number with =0, =1 */\n#define FRANDNORM() (sqrt(-2.*log(Frandom()))*sin(2*acos(-1.)*Frandom()))\n\n/* return exponentially distributed random number with =tau */\n#define Frandexp(tau) (-log(Frandom())*(tau))\n\n/* return exponentially distributed random number with =1 */\n#define FRANDEXP() (-log(Frandom()))\n\n/* if a is an integer factor of b */\n#define isfactor(a,b) (((int)(b))%((int)(a))==0)\n#define isnotfactor(a,b) (((int)(b))%((int)(a))!=0)\n\n/* f(x) := x * Heaviside(x) */\n#define ZERO_RAMP(x) (((x)>0)?(x):0)\n\n/** Scalar.c: **/\n\n/* greatest common divisor of a and b */\nlong gcd (long a, long b);\n#define GCD(a,b) gcd((long)(a),(long)(b))\n/* least common multiple */\n#define LCM(a,b) (long)(a)*(b)/gcd((long)(a),(long)(b))\n/* check if a is a factor of b */\n#define ISFACTOR(a,b) (((long)(b))%((long)(a))==0)\n#define ISEVEN(a) (((unsigned int)(a)&1)==0)\n#define ISODD(a) (((unsigned int)(a)&1))\n\n/* find k,l such that k * x + l * y = gcd(x,y) */\nvoid diophantine2 (int x, int y, int *k, int *l);\n\n/* set Bitmap \"b\", starting from the bit \"offset\", every \"period\" */\n/* bits to the lowest \"period\" bits of \"value\", for \"n\" periods. */\nBmap *Bperiod (Bmap *b, int offset, int n, int period, int value);\n\n/* relative error of x compared to target */\n#define rerr(x,target) ((x)/(target)-1)\ndouble Ferr(double x, double target);\n\n/* calculates |_ a/b _| with mathematically correct floor */\nint floorDiv (int a, int b);\n\n/* calculates |^ a/b ^| with mathamatically correct ceiling */\nint ceilDiv (int a,int b);\n\n/* return (n!) = GAMMA(n+1) in double precision */\ndouble factorial (int n);\n\n/* Take average on structures whose first element is the counter */\n#define avg_what(type,s) (sizeof(type)/sizeof(double)),((double *)(s))\n#define Avg_what(type,s) (sizeof(type)/sizeof(double)),((double *)(&(s)))\nvoid avg_clear (int n, double *s);\nint avg_add (int n, double *s, ...);\nint avg_done (int n, double *s);\nint avg_recover (int n, double *s);\n/* to avoid alignment trouble please define the counter as double */\n\n/* Generate a string of n-1 random base64 characters ended by EOS. */\nchar *RandomBase64String (int n, char *a);\n\n/* (-1)%3=-1, but positive_remainder(-1,3)=2 */\nint positive_remainder(int a, int b);\n\n/* quadrature.c: */\n\n/* Integration of one-dimensional function: */\n\n/* Gaussian quadrature with W(x)=1, N=10, NR pp.148 */\ndouble qgaus (double (*func)(double), double a, double b);\n\n/* Romberg quadrature: */\n#define QROMB_JMAX 20\n#define QROMB_K 5\n#define QROMB_DEFAULT_TOLERANCE 1e-14\nextern double qromb_tolerance;\ndouble qromb (double (*func)(double), double a, double b);\n\n\n/* newtonian.c: */\n\n/************************************************************/\n/* K-evaluation Integration of Newtonian Dynamics: */\n/* */\n/* Given x(0),dotx(0) and routine ddotx(x) which is derived */\n/* from a potential, we want to get x(h),dotx(h) where h is */\n/* called a full step, during which K calls to ddotx(x) are */\n/* made. Let g = h / K. For a scheme to be competitive, it */\n/* should give better results at t_f = Lh >> h compared to */\n/* other schemes with equal g, for some g/accuracy choices. */\n/* */\n/* Algorithms with so-called FSAL property can combine two */\n/* consecutive h-steps to save one evaluation. We provide */\n/* _start, _fsal, _stop routines where _start and _fsal */\n/* need K evaluations and _stop may need one. For complete- */\n/* ness, we also give _nofsal which needs K+1 evaluations. */\n/************************************************************/\n\n/* k=0..K-1 (some _nofsal/_stop call k=K), n, x[n], acc[n]=workspace */\ntypedef void (*Newtonian_ddotx) (int, int, double *, double *);\n\n\n/***************************/\n/* Symplectic Algorithm 1: */\n/***************************/\n/* First x, then dotx evolution. No great need to use FSAL savings. */\n\n/* This algorithm is not the best for heat current computation or */\n/* total energy checksum because when ddotx() is called at k=0, x */\n/* is already shifted. Ruth83, Schlier98_6a, Tsitouras99. */\n\n/****************************************************/\n/* Computer \"Experiments\" on Classical Fluids. I. */\n/* Thermodynamical Properties of Lennard-Jones */\n/* Molecules, L. Verlet, Phys. Rev. 159, 98 (1967). */\n/* A Canonical Integration Technique, R.D. Ruth, */\n/* IEEE Trans. Nucl. Sci. NS-30, 2669 (1983). */\n/****************************************************/\n/* evaluations per h-step: 1 */\n/* global truncation error: h^2 */\n\n/* First x, then dotx evolution. No great need to use FSAL savings. */\nvoid symplectic_Ruth83_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Ruth83_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Ruth83_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Ruth83_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/**************************************************************/\n/* Ch. Schlier and A. Seiter, J. Phys. Chem. 102 (1998) 9399. */\n/**************************************************************/\n/* evaluations per h-step: 9 */\n/* global truncation error: h^6 */\n\n/* First x, then dotx evolution. No great need to use FSAL savings. */\nvoid symplectic_Schlier98_6a_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Schlier98_6a_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier98_6a_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier98_6a_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/************************************************************/\n/* Haruo Yoshida, Phys. Lett. A 150, 262 (1990). */\n/* Celestial Mechanics and Dynamical Astronomy 74 (1999) */\n/* 223-230, Ch. Tsitouras, */\n/* www.math.ntua.gr/people/tsitoura/publications.html */\n/************************************************************/\n/* evaluations per h-step: 33 */\n/* global truncation error: h^10 */\n\n/* First x, then dotx evolution. No great need to use FSAL savings. */\nvoid symplectic_Tsitouras99_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Tsitouras99_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Tsitouras99_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Tsitouras99_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/***************************/\n/* Symplectic Algorithm 2: */\n/***************************/\n/* First dotx, then x evolution. You do need FSAL savings. */\n\n/* This algorithm is more appropriate for heat current computation */\n/* or total energy checksum when ddotx() of _start is called at k */\n/* = 0, if _stop was called at the last step, because exact p(nh), */\n/* q(nh) would then be passed to ddotx(). Calvo93, Schlier00_6b, */\n/* Schlier00_8b, Schlier00_8c. */\n\n\n/************************************************************/\n/* The Development of Variable-Step Symplectic Integrators, */\n/* With Application to the Two-Body Problem, M.P. Calvo, */\n/* J.M. Sanz-Serna, SIAM J. Sci. Comput. 14, 936-952 (1993) */\n/* Numerical Hamiltonian Problems, J.M. Sanz-Serna, */\n/* M.P. Calvo, Chapman & Hall, London (1994). */\n/************************************************************/\n/* evaluations per h-step: 4 */\n/* global truncation error: h^4 */\n\n/* First dotx, then x evolution. No FSAL savings yet. */\nvoid symplectic_Calvo93_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Calvo93_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Calvo93_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Calvo93_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/*******************************************************/\n/* High-Order Symplectic Integration: An Assessment, */\n/* Ch. Schlier, A. Seiter, Comp. Phys. Comm. (2000) */\n/* phya8.physik.uni-freiburg.de/abt/papers/papers.html */\n/*******************************************************/\n/* evaluations per h-step: 8 */\n/* global truncation error: h^6 */\n\n/* First dotx, then x evolution. No FSAL savings yet. */\nvoid symplectic_Schlier00_6b_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Schlier00_6b_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_6b_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_6b_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/*******************************************************/\n/* Ch. Schlier and A. Seiter, Comp. Phys. Comm. (2000) */\n/*******************************************************/\n/* evaluations per h-step: 17 */\n/* global truncation error: h^8 */\n\n/* First dotx, then x evolution. No FSAL savings yet. */\nvoid symplectic_Schlier00_8b_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Schlier00_8b_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_8b_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_8b_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/*******************************************************/\n/* Ch. Schlier and A. Seiter, Comp. Phys. Comm. (2000) */\n/*******************************************************/\n/* evaluations per h-step: 17 */\n/* global truncation error: h^8 */\n\n/* First dotx, then x evolution. No FSAL savings yet. */\nvoid symplectic_Schlier00_8c_nofsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n/* FSAL sequence: _start, _fsal, _stop */\nvoid symplectic_Schlier00_8c_start\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_8c_fsal\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\nvoid symplectic_Schlier00_8c_stop\n(double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n\n\n/**********************************************************************/\n/* Routers to various routines by K, the number of evaluations per h. */\n/* To make fair comparison, one should use equal g for different K's. */\n/* It gives \"exact\" x(wh) and dotx(wh), w=1..L, after each full step. */\n/**********************************************************************/\nvoid symplectic_nofsal ( int K, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n\n/**********************************************************************/\n/* Routers to various routines by K, the number of evaluations per h. */\n/* To make fair comparison, one should use equal g for different K's. */\n/* To integrate t from 0 to Lh, one should call 1 x symplectic_start, */\n/* (L-1) x symplectic_fsal, and 1 x symplectic_stop. One cannot have */\n/* \"exact\" x(wh) and dotx(wh) except when w=0,L, but capturing k=0 */\n/* calls to ddotx(k,n,x,acc) at w=1..L-1 gives approximate answers. */\n/**********************************************************************/\nvoid symplectic_start ( int K, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\nvoid symplectic_fsal ( int K, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\nvoid symplectic_stop ( int K, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n\n/*******************************************************/\n/* Well known non-symplectic integrators & Benchmarks: */\n/*******************************************************/\n\n/************************************************************/\n/* classic 4th-order Runge-Kutta method: Numerical Recipes */\n/* in C: The Art of Scientific Computing, William H. Press, */\n/* Saul A. Teukolsky, William T. Vetterling, Brian P. */\n/* Flannery, Cambridge University Press, Cambridge (1992). */\n/* http://mathworld.wolfram.com/Runge-KuttaMethod.html */\n/************************************************************/\n/* evaluations per h-step: 4 */\n/* global truncation error: h^4 */\n\n/* suited for heat current computation & total energy checksum at k=0 */\n\n/* allocate 8*n internal workspace. No integration is performed yet. */\nvoid rk4_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* \"acc\" would not be used, so it can be passed as NULL. */\nvoid rk4 (double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx);\n/* free 8*n internal workspace */\nvoid rk4_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n\n/**********************************************************/\n/* Gear predictor-corrector algorithm: Numerical Initial */\n/* Value Problems in Ordinary Differential Equation, */\n/* C.W. Gear, Englewood Cliffs N.J., Prentice-Hall, 1971. */\n/* itp.nat.uni-magdeburg.de/~schinner/dip/node22.html */\n/**********************************************************/\n/* k-value: keep k n-arrays: x^0,x^1,..,x^{k-1}: */\n/* initialized by \"exact\" time derivatives. */\n/* Before corrector, x0 has local truncation error h^k; */\n/* after corrector, x0 has local truncation error h^(k+1) */\n/* therefore the global truncation error of x0 is h^k. */\n/* The global truncation error of dotx is h^{k-1}, etc. */\n/**********************************************************/\n\n#define GEAR_TEST_H 50\n\n/* 4-value Gear predictor-corrector algorithm */\n/* evaluations per h-step: 1 */\n/* local truncation error: h^5 */\n/* global truncation error: h^4 */\n\n/* Initialize 4-value Gear integrator and allocate 2*n */\n/* internal workspace. No integration is performed yet. */\nvoid gear4_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\nvoid gear4 ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* free 2*n internal workspace */\nvoid gear4_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n/******************************************************/\n/* 5-value Gear predictor-corrector algorithm: */\n/* Computer Simulation of Liquids, M.P. Allen and */\n/* D.J. Tildesley, Clarendon Press, (Oxford 1987). */\n/* ftp://ftp.dl.ac.uk/ccp5/ALLEN_TILDESLEY/F.02 */\n/* itp.nat.uni-magdeburg.de/~schinner/dip/node22.html */\n/******************************************************/\n/* evaluations per h-step: 1 */\n/* local truncation error: h^6 */\n/* global truncation error: h^5 */\n\n/* Initialize 5-value Gear integrator and allocate 3*n */\n/* internal workspace. No integration is performed yet. */\nvoid gear5_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\nvoid gear5 ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* free 3*n internal workspace */\nvoid gear5_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n\n/* 6-value Gear predictor-corrector algorithm */\n/* evaluations per h-step: 1 */\n/* local truncation error: h^7 */\n/* global truncation error: h^6 */\n\n/* Initialize 6-value Gear integrator and allocate 4*n */\n/* internal workspace. No integration is performed yet. */\nvoid gear6_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\nvoid gear6 ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* free 4*n internal workspace */\nvoid gear6_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n/* 7-value Gear predictor-corrector algorithm */\n/* evaluations per h-step: 1 */\n/* local truncation error: h^8 */\n/* global truncation error: h^7 */\n\n/* Initialize 7-value Gear integrator and allocate 5*n */\n/* internal workspace. No integration is performed yet. */\nvoid gear7_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\nvoid gear7 ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* free 5*n internal workspace */\nvoid gear7_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n/* 8-value Gear predictor-corrector algorithm */\n/* evaluations per h-step: 1 */\n/* local truncation error: h^9 */\n/* global truncation error: h^8 */\n\n/* Initialize 8-value Gear integrator and allocate 6*n */\n/* internal workspace. No integration is performed yet. */\nvoid gear8_prep ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\nvoid gear8 ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n/* free 6*n internal workspace */\nvoid gear8_free ( double h, int n, double *x, double *dotx, double *acc,\n Newtonian_ddotx ddotx );\n\n/* symplectic algorithm 1 */\n#define NEWTONIAN_RUTH83 0\n#define NEWTONIAN_SCHLIER98_6A (NEWTONIAN_RUTH83 + 1)\n#define NEWTONIAN_TSITOURAS99 (NEWTONIAN_SCHLIER98_6A + 1)\n#define NEWTONIAN_SYMPLECTIC_ALGORITHM_1_MAX (NEWTONIAN_TSITOURAS99 + 1)\n/* symplectic algorithm 2 */\n#define NEWTONIAN_CALVO93 NEWTONIAN_SYMPLECTIC_ALGORITHM_1_MAX\n#define NEWTONIAN_SCHLIER00_6B (NEWTONIAN_CALVO93 + 1)\n#define NEWTONIAN_SCHLIER00_8B (NEWTONIAN_SCHLIER00_6B + 1)\n#define NEWTONIAN_SCHLIER00_8C (NEWTONIAN_SCHLIER00_8B + 1)\n#define NEWTONIAN_SYMPLECTIC_ALGORITHM_2_MAX (NEWTONIAN_SCHLIER00_8C + 1)\n/* non-symplectic algorithms */\n#define NEWTONIAN_RK4 NEWTONIAN_SYMPLECTIC_ALGORITHM_2_MAX\n#define NEWTONIAN_GEAR4 (NEWTONIAN_RK4 + 1)\n#define NEWTONIAN_GEAR5 (NEWTONIAN_GEAR4 + 1)\n#define NEWTONIAN_GEAR6 (NEWTONIAN_GEAR5 + 1)\n#define NEWTONIAN_GEAR7 (NEWTONIAN_GEAR6 + 1)\n#define NEWTONIAN_GEAR8 (NEWTONIAN_GEAR7 + 1)\n#define NEWTONIAN_MAX (NEWTONIAN_GEAR8 + 1)\n\ntypedef void (*Integrator) ( double, int, double *, double *, double *,\n Newtonian_ddotx );\ntypedef struct\n{\n char *name;\n bool is_symplectic;\n int K;\n int order;\n Integrator a,b,c;\n} Newtonian;\n\nextern Newtonian newtonian [NEWTONIAN_MAX];\n\n/***************************************************************/\n/* prep + [ firststep, L-1 nextstep, halt ] repeat + free */\n/* | */\n/* k=0 property calculation for algorithm 2 and non-symplectic */\n/***************************************************************/\n\n/* Allocate and initialize states if necessary, but do NOT integrate. */\nvoid newtonian_integrator_prep\n( int id, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n/* Get the integrator to run its first full step of a session. */\nvoid newtonian_integrator_firststep\n( int id, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n/* Run other full steps of a session. */\nvoid newtonian_integrator_nextstep\n( int id, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n/* Halt the session and do necessary mop-ups. To */\n/* start a new session, call _firststep again. */\nvoid newtonian_integrator_halt\n( int id, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n/* Free workspace if any. No more sessions. To restart, call _prep. */\nvoid newtonian_integrator_free\n( int id, double g, int n, double *x, double *dotx,\n double *acc, Newtonian_ddotx ddotx );\n\n\n/** spline.c: **/\n\n#define SPLINE_CUBIC_NATURAL 0\n#define SPLINE_CUBIC_PERIODIC 1\n#define SPLINE_AKIMA_NATURAL 2\n#define SPLINE_AKIMA_PERIODIC 3\n\ntypedef struct\n{\n gsl_spline *spline;\n gsl_interp_accel *acc;\n double xmin, xmax, ymax, ymin;\n} Spline;\n\n/* Allocate and initialize Spline structure based on */\n/* lookup table x[0..N-1],y[0..N-1] and spline type. */\nSpline *spline_initialize (int N, double *x, double *y, int spline_type);\n\n/* Evaluate spline value. */\ndouble spline_value (Spline *sp, double x);\n\n/* Evaluate first-order derivative. */\ndouble spline_deriv (Spline *sp, double x);\n\n/* Evaluate second-order derivative. */\ndouble spline_deriv2 (Spline *sp, double x);\n\n/* Free all data structure. */\nvoid spline_finalize (Spline *sp);\n\n\n/** histogram.c: **/\n\ntypedef struct\n{\n double xmin, xmax; /* domain of interest: {xmin,xmax} */\n int bins; /* # of collection bins in the domain of interest */\n double xbin; /* width of one bin */\n int totalcount; /* counts of total submission */\n double domaincount; /* counts that fall into the domain of interest */\n double *bincount; /* count in each bin */\n double *x_sample; /* center x of each bin */\n double *density_profile; /* density profile which integrates to 1 */\n} Histogram;\n\n/* Given finite xmin < xmax and bins >= 1, reallocate */\n/* data structure in h and reset all counters. */\nvoid histogram_reinitialize\n(double xmin, double xmax, int bins, Histogram *h);\n\n/* Update histogram by data array x[0..n-1]; return domaincount */\ndouble histogram_intercept (int n, double *x, Histogram *h);\n\n/* Return the interception rate = domaincount / totalcount */\ndouble histogram_interception_rate (Histogram *h);\n\n/* Update the density profile; return the interception rate */\ndouble histogram_update_density_profile (Histogram *h);\n\n/* Save histogram in matlab script \"fname\" as */\n/* symbol \"token\" and notify I/O stream \"info\" */\ndouble histogram_save_as_matlab\n(Histogram *h, FILE *info, char *token, char *fname);\n#define histogram_save_as_MATLAB(h,info,token) histogram_save_as_matlab\\\n (h,info,token,str2(token,\"_h.m\"))\n\n/* Clear all counters as if it is just the beginning */\nvoid histogram_reset_all_counters (Histogram *h);\n\n/* Free the histogram data structure and reset all counters */\nvoid histogram_free (Histogram *h);\n\n#endif /* _Scalar_h */\n", "meta": {"hexsha": "dce28215ac90fdf17a29678cafd4bd99ac6fdeda", "size": 33304, "ext": "h", "lang": "C", "max_stars_repo_path": "Scalar/Scalar.h", "max_stars_repo_name": "jameskermode/AtomEye", "max_stars_repo_head_hexsha": "c418eb2553f6793460d4a956236fc698c39fbe74", "max_stars_repo_licenses": ["NetCDF"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T05:54:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:59:24.000Z", "max_issues_repo_path": "Scalar/Scalar.h", "max_issues_repo_name": "jameskermode/AtomEye", "max_issues_repo_head_hexsha": "c418eb2553f6793460d4a956236fc698c39fbe74", "max_issues_repo_licenses": ["NetCDF"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-04-09T13:00:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-16T18:02:16.000Z", "max_forks_repo_path": "Scalar/Scalar.h", "max_forks_repo_name": "jameskermode/AtomEye", "max_forks_repo_head_hexsha": "c418eb2553f6793460d4a956236fc698c39fbe74", "max_forks_repo_licenses": ["NetCDF"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-09T12:44:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T01:41:46.000Z", "avg_line_length": 39.6476190476, "max_line_length": 79, "alphanum_fraction": 0.6249399472, "num_tokens": 9669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6724450473568729}} {"text": "/* sys/ldfrexp.c\n * \n * Copyright (C) 2002, Gert Van den Eynde\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\ndouble\ngsl_ldexp (const double x, const int e)\n{\n double p2 = pow (2.0, (double)e);\n return x * p2;\n}\n\ndouble\ngsl_frexp (const double x, int *e)\n{\n if (x == 0.0)\n {\n *e = 0;\n return 0.0;\n }\n else\n {\n double ex = ceil (log (fabs (x)) / M_LN2);\n int ei = (int) ex;\n double f = gsl_ldexp (x, -ei);\n\n while (fabs (f) >= 1.0)\n {\n ei++;\n f /= 2.0;\n }\n \n while (fabs (f) < 0.5)\n {\n ei--;\n f *= 2.0;\n }\n\n *e = ei;\n return f;\n }\n}\n", "meta": {"hexsha": "c5ba3a6a734193e06fa88580b807ca3c961545b8", "size": 1409, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/sys/ldfrexp.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/sys/ldfrexp.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/sys/ldfrexp.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.0983606557, "max_line_length": 81, "alphanum_fraction": 0.5968772179, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.6721281630504646}} {"text": "#include \n#include \n#include \n\n#include \"timer.h\"\n\nvoid integral_recur (int nmin, int nmax, double vals[]);\nvoid integral_gen (int nmin, int nmax, double vals[]);\ndouble ff (double x, void *params);\nint adjust_rep_count (int count, double time, double tmin, double tmax);\n\ndouble ff (double x, void *params)\n{\n double n = *(double *) params;\n double f = exp (-x) * pow (x, n);\n\n return f;\n}\n\nvoid integral_recur (int nmin, int nmax, double vals[])\n{\n int i;\n\n vals[nmax] = 0.;\n for (i = nmax - 1; i >= nmin; i--)\n {\n vals[i] = vals[i + 1] / (i + 1) + 1. / ((i + 1) * M_E);\n }\n}\n\nvoid integral_gen (int nmin, int nmax, double vals[])\n{\n int i;\n double result, error;\n double a = 0., b = 1.;\n double abserr = 1.e-9, relerr = 1.e-9;\n double n;\n size_t np = 1000;\n gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);\n\n gsl_function F;\n\n F.function = &ff;\n\n for (i = nmax; i >= nmin; i--)\n {\n n = (double) i;\n F.params = &n;\n\n gsl_integration_qag (&F, a, b, abserr, relerr, np, GSL_INTEG_GAUSS15,\n w, &result, &error);\n\n vals[i] = result;\n }\n\n\n gsl_integration_workspace_free (w);\n\n}\n\n#define N 100\n\nint main (void)\n{\n int i;\n double integral1[N + 1], integral2[N + 1];\n int nmax = N;\n int nmin = 10;\n\n integral_recur (nmin, nmax, integral1);\n integral_gen (nmin, nmax, integral2);\n\n for (i = nmin; i <= nmax; i++)\n {\n printf (\"%5d % 14.6f % 14.6f %g\\n\", i, integral1[i],\n integral2[i], fabs (integral1[i] - integral2[i]));\n }\n\n double time, time1, time2, tmin = 1., tmax = 2.;\n int count = 1000;\n\n do\n {\n\n timer_start ();\n for (i = 0; i < count; i++)\n {\n integral_recur (nmin, nmax, integral1);\n }\n time = timer_stop ();\n\n time1 = time / count;\n printf (\"Recur: %10.2f usec %10.6f sec %10d\\n\", time1 * 1.e6, time,\n count);\n /*\n * adjust count such that cpu time is between\n * tmin and tmax\n */\n count = adjust_rep_count (count, time, tmin, tmax);\n }\n while ((time > tmax) || (time < tmin));\n\n count = 1000;\n\n do\n {\n\n timer_start ();\n for (i = 0; i < count; i++)\n {\n integral_gen (nmin, nmax, integral2);\n }\n time = timer_stop ();\n\n time2 = time / count;\n printf (\"Integ: %10.2f usec %10.6f sec %10d\\n\", time1 * 1.e6, time,\n count);\n /*\n * adjust count such that cpu time is between\n * tmin and tmax\n */\n count = adjust_rep_count (count, time, tmin, tmax);\n }\n while ((time > tmax) || (time < tmin));\n\n printf (\"Speedup: %.2f\\n\", time2 / time1);\n\n return 0;\n}\n", "meta": {"hexsha": "5452be17b35a0a77f91c5ca536862b2a0b8eadae", "size": 2830, "ext": "c", "lang": "C", "max_stars_repo_path": "recur.c", "max_stars_repo_name": "matthewignal/hw07", "max_stars_repo_head_hexsha": "ea1028946c812057d792cbb83ee7a29a14f9d57c", "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": "recur.c", "max_issues_repo_name": "matthewignal/hw07", "max_issues_repo_head_hexsha": "ea1028946c812057d792cbb83ee7a29a14f9d57c", "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": "recur.c", "max_forks_repo_name": "matthewignal/hw07", "max_forks_repo_head_hexsha": "ea1028946c812057d792cbb83ee7a29a14f9d57c", "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.7692307692, "max_line_length": 77, "alphanum_fraction": 0.522614841, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6719936822477673}} {"text": "#include \n#include \n\n#include \t\t//Relevant GSL functions for VEGAS numerical integration\n#include \n\n#include \"timer.c\"\t\t\t//Timing Functions\n#include \"plotfun.h\"\t\t\t//Automatic Plotting Function\n\nvoid timer_start (void);\ndouble timer_stop (void);\n\nvoid pfun(double x[], double y[], double u[], double v[], int points);\n\nextern double g (double *t, size_t dim, void *params);\nstruct my_params {double r;};\n\ndouble f (double x1, double x2, double y1, double y2, double z1, double z2, double r);\n\ndouble dipole_approx (double r);\n\nint main (void)\n{\n\tint np = 20;\n\tdouble distance[20];\n\tdouble vegas_energy[20];\n\tdouble res, err;\n double error1[20];\n\tdouble error2[20];\n\t\n\n\tsize_t dim = 6;\n\tdouble xl[] = {0., 0., 0., 0., 0., 0.};\n\tdouble xu[] = {1., 1., 1., 1., 1., 1.};\n\t\n\tgsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);\n\tunsigned long seed = 1UL;\n\t\n\tgsl_rng_set (r, seed);\n\t\n\tsize_t calls = 1000000;\n\n\tdouble dd = (4.-1.001)/np;\n\t\n\n\ttimer_start();\n\n\tfor(int q = 0; q < np; q++)\n\t{\n\t\tdistance[q] = 1.001 + q*dd;\n\t}\n\t\n\t//VEGAS Integration\n\t\n\tfor(int j = 0; j < np; j++)\n\t{\n\t\tstruct my_params params = {distance[j]};\n\t\tgsl_monte_function G = { &g, dim , ¶ms};\n\n\t\tgsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim);\n\t\n\t\tgsl_monte_vegas_init (sv);\n\n\t\tgsl_monte_vegas_integrate (&G, xl, xu, dim, calls / 10, r, sv, &res, &err);\n\n\t\tdo\n\t\t{\n\t\t\tgsl_monte_vegas_integrate (&G, xl, xu, dim, calls, r, sv, &res, &err);\n\t\t\tfflush (stdout);\n\t\t}\n\t\twhile (fabs (gsl_monte_vegas_chisq (sv) - 1.0) > 0.2);\n\t\tvegas_energy[j] = fabs(res);\n\t\terror1[j] = fabs(err);\n\n\t\tgsl_monte_vegas_free (sv);\n\t}\n\n\tdouble t1 = timer_stop();\n\n\tgsl_rng_free (r);\n\n\tint iterations = 1000000;\n\tint tot = 20;\n\tdouble x1, x2, y1, y2, z1, z2;\n\tdouble handmade_energy[20];\n\n\tgsl_rng *zed = gsl_rng_alloc (gsl_rng_taus2);\n\n\tgsl_rng_set (zed, seed);\n\n\ttimer_start();\n\n\t//Handmade Monte Carlo Integrator\n\n\tfor(int j = 0; j < 20.; j++)\n\t{\n\t double d = 1.001 + j * dd;\n\t double ival = 0;\n\t double i2val = 0; \n\t for(int z = 0; z < 16; z++)\n\t {\n\t double value = 0;\n \t\tfor (int q = 0; q < iterations; q++)\n \t{\n \t\tx1 = gsl_rng_uniform(zed);\n \t\tx2 = gsl_rng_uniform(zed);\n \t\ty1 = gsl_rng_uniform(zed);\n \t\ty2 = gsl_rng_uniform(zed);\n \t\tz1 = gsl_rng_uniform(zed);\n \t\tz2 = gsl_rng_uniform(zed);\n \t\tvalue += f(x1, x2, y1, y2, z1, z2, d);\n \t\t}\n\t\tival += value;\n\t\ti2val += value*value;\n\t }\n\n\t double result = ival/iterations/16;\n\t double result2 = i2val/iterations/iterations/16;\n\n\t error2[j] = sqrt(fabs((result*result)-result2));\n\t \n\t handmade_energy[j] = fabs(result);\n\t}\n\n\tdouble t2 = timer_stop();\n\n\t//Dipole Approximation\n\n\tdouble dipole_energy[20];\n\tfor(int u = 0; u < tot; u++)\n\t{\n\t\tdipole_energy[u] = dipole_approx(distance[u]);\n\t}\n\n\tprintf(\"Distance VEGAS Error Handmade Error Dipole\\n\");\n\t\t\n\tfor(int w = 0; w < tot; w++)\n\t{\n\t printf(\"%.6f %.6f %.6f %.6f %.6f %.6f\\n\", distance[w], vegas_energy[w], error1[w], handmade_energy[w], error2[w], dipole_energy[w]);\n\t}\n\n\tprintf(\"Time for VEGAS: %.6f\\nTime for HANDMADE: %.6f\\n\", t1, t2);\t\n\n\t//Plots the 3 methods vs. distance automatically (function in plotfun.h)\n\n\tpfun(distance, vegas_energy, handmade_energy, dipole_energy, 20);\n\t\n\treturn 0;\n}\n\ndouble g (double *t, size_t dim, void *params)\n{\n \tdouble dist2, delta;\n \tdouble rho1, rho2;\n \tint sdim = ((int) dim)/2;\n \tdouble r = *((double *) params);\n\n \tdist2 = 0.;\n \tfor (int i = 0; i < sdim; i++)\n \t{\n \tdelta = t[i] - t[i + sdim]; \n \tif (i == 0)\n \t{\n \t\tdelta += r;\n \t}\n \tdist2 += delta*delta; \n \t}\n\n \tdouble norm = 512./(9.*(M_PI - 2.));\n \trho1 = norm * atan(2*(t[0]-.5))*pow(sin(M_PI*t[1]),4.)*pow(sin(M_PI*t[2]),4.);\n \trho2 = norm * atan(2*(t[3]-.5))*pow(sin(M_PI*t[4]),4.)*pow(sin(M_PI*t[5]),4.);\n\n \treturn rho1*rho2/sqrt(dist2);\n}\n\ndouble f (double x1, double x2, double y1, double y2, double z1, double z2, double r)\n{\n\tdouble dist2;\n \tdouble rho1, rho2;\n \n \tdist2 = (x1 - x2 + r)*(x1 - x2 + r) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2);\n\n \tdouble norm = 512./(9.*(M_PI - 2.));\n \trho1 = norm * atan(2*(x1-.5))*pow(sin(M_PI*y1),4.)*pow(sin(M_PI*z1),4.);\n \trho2 = norm * atan(2*(x2-.5))*pow(sin(M_PI*y2),4.)*pow(sin(M_PI*z2),4.);\n\n \treturn rho1*rho2/sqrt(dist2);\n}\n\ndouble dipole_approx (double r)\n{\n\treturn 2/(r*r*r);\n}\n\n", "meta": {"hexsha": "1799d58dd8df82bce5d4c9ac81843e144a58a193", "size": 4519, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "connor-occhialini/fin2", "max_stars_repo_head_hexsha": "d13fa38b59a96c79e21f9775cf18398a30128578", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.c", "max_issues_repo_name": "connor-occhialini/fin2", "max_issues_repo_head_hexsha": "d13fa38b59a96c79e21f9775cf18398a30128578", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.c", "max_forks_repo_name": "connor-occhialini/fin2", "max_forks_repo_head_hexsha": "d13fa38b59a96c79e21f9775cf18398a30128578", "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.1743589744, "max_line_length": 145, "alphanum_fraction": 0.5764549679, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.671920393783812}} {"text": "#include \n#include \n#include \n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n#endif\n\n/*!\n * @brief Computes the angle between moment tensors. This is from \n * Equation 15 of Tape and Tape 2016 - A confidence parameter for \n * seismic moment tensors\n *\n * @param[in] n Number of moment tensors.\n * @param[in] M1in First moment tensor packed {m11, m22, m33, m12, m13, m23}.\n * This is an array of dimension [6 x n] with leading\n * dimension 6.\n * @param[in] M2in Second moment tensor packed {m11, m22, m33, m12, m13, m23}.\n * This is an array of dimension [6 x n] with leading\n * dimension 6.\n *\n * @param[out] theta Angle between moment tensors M1 and M2 in radians. \n * This is an array of dimension [n].\n *\n * @result 0 indicates success.\n *\n * @author Ben Baker\n *\n * @copyright MIT\n *\n */\nint compearth_angleMT(const int n,\n const double *__restrict__ M1in,\n const double *__restrict__ M2in,\n double *__restrict__ theta)\n{\n double M1[9*CE_CHUNKSIZE] __attribute__((aligned(64)));\n double M2[9*CE_CHUNKSIZE] __attribute__((aligned(64)));\n double M1_mag[CE_CHUNKSIZE] __attribute__((aligned(64)));\n double M2_mag[CE_CHUNKSIZE] __attribute__((aligned(64)));\n double xden[CE_CHUNKSIZE] __attribute__((aligned(64)));\n double arg[CE_CHUNKSIZE] __attribute__((aligned(64)));\n double xnum[CE_CHUNKSIZE] __attribute__((aligned(64)));\n int i, ierr, imt, nmtLoc;\n ierr = 0;\n for (imt=0; imt 1.0)\n {\n fprintf(stdout, \"%s: Warning arg is %f setting to +1\\n\",\n __func__, arg[i]);\n arg[i] = 1.0;\n }\n }\n // Finally compute the angle\n for (i=0; i // Defines the assert function.\n//#define assert(x) {} //to avoid bound checking\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#define BUFF_SIZE 4096\n\nclass Matrix {\n\npublic:\n\n// Default Constructor. Creates a 1 by 1 matrix; sets value to zero. \nMatrix () {\n ma = gsl_matrix_alloc( 1, 1);// Allocate memory\n ve.owner = 0;\n ve.block = ma->block;\n set(0.0); // Set value of data_[0] to 0.0\n \n header = NULL;\n}\n\n// Regular Constructor. Creates an nR by nC matrix; sets values to zero.\n// If number of columns is not specified, it is set to 1.\nMatrix(int nR, int nC = 1, char *head=NULL) {\n assert(nR > 0 && nC > 0); // Check that nC and nR both > 0.\n ma = gsl_matrix_alloc( nR, nC);// Allocate memory\n ve.owner = 0;\n ve.block = ma->block;\n set(0.0); // Set values of data_[] to 0.0\n\n if (head != NULL)\n\theader = strdup(head);\n else\n\theader = NULL;\n}\n\n\n//copy constructor\nMatrix(Matrix &mat) {\nprintf(\"Matrix::Matrix 2 ...\\n\");\n ma = gsl_matrix_alloc( mat.nRow(), mat.nCol());// Allocate memory\n ve.owner = 0;\n ve.block = ma->block;\n copy(mat);\n \n if (mat.Header() != NULL)\n\theader = strdup(mat.Header());\n else\n\theader = NULL;\n \n}\n\n//Identity (preferably square) matrix\nvoid Iden() {\n //assert(nRow() == nCol()); // Check that square matrix.\n set(0.0); // Set values of data_[] to 0.0\n for (int i=0; idata[ (ma->tda)*i + i] = 1.0;\n}\n\n\n\n// Destructor. Called when a Matrix object goes out of scope or deleted.\n~Matrix() {\n\t//printf(\"Matrix::~Matrix\\n\");\n\tif (ma != NULL)\n\t\t gsl_matrix_free(ma); // Release allocated memory\n\tif (header != NULL) {\n\t\tfree(header);\n\t}\n}\n\n\n\n// Assignment operator function.\n// Overloads the equal sign operator to work with\n// Matrix objects.\nMatrix& operator=(const Matrix& mat) {\n if( this == &mat ) return *this; // If two sides equal, do nothing.\n this->copy(mat); // Copy right hand side to l.h.s.\n return *this;\n}\n\n// += operator function.\n// Overloads the += sign operator to work with\n// Matrix objects.\nMatrix& operator+=(const Matrix& mat) {\n gsl_matrix_add( this->ma, mat.ma); \n return *this;\n}\n\n// -= operator function.\n// Overloads the -= sign operator to work with\n// Matrix objects.\nMatrix& operator-=(const Matrix& mat) {\n gsl_matrix_sub( this->ma, mat.ma); \n return *this;\n}\n\n// *= operator function.\n// Overloads the *= sign operator to work with\n// Matrix objects.\nMatrix& operator*=(const double a) {\n gsl_matrix_scale( this->ma, a); \n return *this;\n}\n\n\n\n\n\n// Set function. Sets all elements of a matrix to a given value.\nvoid set(double value) {\n gsl_matrix_set_all( ma, value);\n}\n\n/*// Set function. Sets all elements of a matrix to a given value.\nvoid eval(double value, double (*fct)(double x)) {\n to be done\n}*/\n\n\n//info\n// Simple \"get\" functions. Return number of rows or columns.\nint nRow() const { return ma->size1; }\nint nCol() const { return ma->size2; }\n\n//min and max\ndouble Max() { gsl_matrix_max(ma); }\ndouble Min() { gsl_matrix_min(ma); }\n\n\n// Parenthesis operator function.\n// Allows access to values of Matrix via (i,j) pair.\n// Example: a(1,1) = 2*b(2,3); \n// If column is unspecified, take as 1.\ndouble& operator() (int i, int j = 0) {\n assert(i >= 0 && i < ma->size1); // Bounds checking for rows\n assert(j >= 0 && j < ma->size2); // Bounds checking for columns\n return ma->data[ (ma->tda)*i + j]; // Access appropriate value\n}\n\n// Parenthesis operator function (const version).\nconst double& operator() (int i, int j = 0) const{\n assert(i >= 0 && i < ma->size1); // Bounds checking for rows\n assert(j >= 0 && j < ma->size2); // Bounds checking for columns\n return ma->data[(ma->tda)*i + j]; // Access appropriate value\n}\n\n// Allows access to values of Matrix via ele(i,j) pair.\n// If column is unspecified, take as 1.\ndouble ele(int i, int j = 0) {\n assert(i >= 0 && i < ma->size1); // Bounds checking for rows\n assert(j >= 0 && j < ma->size2); // Bounds checking for columns\n return ma->data[ (ma->tda)*i + j]; // Access appropriate value\n}\n\n\n\n\n//i/o\n//Print function\nvoid print( FILE *F, char *name=NULL, int fw=11, int pres=4, char *sep=\" \", int rownums=0, int colnums=0)\n{\n\tif (name == NULL)\n\t\tif (header == NULL)\n\t\t\tfprintf( F, \"\\n\");\n\t\telse\n\t\t\tfprintf( F, \"%s\\n\", header);\n\telse\n\t\tfprintf( F, \"%s\", name);\n\tfor (int i=0; isize1; i++)\n\t{\n\t\tif ((i == 0) && (colnums)) {\n\t\t\tfprintf( F, \"%*s%s\", fw, \"\", sep);\n\t\t\tfor (int j=0; jsize2; j++)\n\t\t\t\tfprintf( F, \"%*d%s\", fw, j, sep);\n\t\t\tfprintf(F, \"\\n\");\n\t\t}\n\t\tfor (int j=0; jsize2; j++) {\n\t\t\tif ((j == 0) && (rownums))\n\t\t\t\tfprintf( F, \"%3d%s\", i, sep);\n\t\t\tfprintf( F, \"%*.*g%s\", fw, pres, ele(i,j), sep);\n\t\t}\n\t\tfprintf( F, \"\\n\");\n\t}\n}\nvoid print(char *name=NULL) { print( stdout, name, 11, 4, \" \", 0, 0); }\nvoid printnums(char *name=NULL) { print( stdout, name, 11, 4, \" \", 1, 1); }\n\nvoid fileprint(char *fnam) {\n\tFILE *F;\n\t\n\tif ((F = fopen( fnam, \"w+\")) == NULL)\n\t{\n\t\tprintf( \"Could not open file %s for writing\\n\", fnam);\n\n\t\tassert(F == NULL);\n\t}\n\telse\n\t{\n\t\tprint( F, NULL, 11, 4, \" \");\n\t\n\t\tfclose(F);\n\t}\n}\n\nvoid printrow(int i) {\n\tassert(i < nRow());\n\t\n\tfor (int j=0; jsize2; j++) {\n\t\tprintf( \"%*.*g%s\", 11, 4, ele(i,j), \" \");\n\t}\n\tprintf( \"\\n\");\n}\n\nint filescan(char *fnam, int file_header=0) {\n\tFILE *F;\n\t\n\tif ((F = fopen( fnam, \"r\")) == NULL)\n\t{\n\t\tprintf( \"File %s not found\\n\", fnam);\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tif (file_header == 1) {\n\t\t\theader = (char *) malloc((size_t) BUFF_SIZE);\n\n\t\t\theader = fgets( header, (size_t) BUFF_SIZE, F);\n\t\t\theader[strlen(header)-1] = '\\0'; //remove the \\n\n\t\t}\n\t\t\n\t\tgsl_matrix_fscanf( F, ma);\n\t\n\t\tfclose(F);\n\t\treturn 1;\n\t}\n}\n\n/*********************** Views *********************/\n//Get the gsl matrix\ngsl_matrix *Ma() { return ma; }\n\n\n//Column gsl Vector\ngsl_vector *AsColVec(int Col) {\n\tassert(Col >= 0 && Col < ma->size2); // Bounds checking for columns\n\tve.size = ma->size1;\n\tve.stride = ma->tda;\n\tve.data = ma->data + Col;\n\t\n\treturn &ve;\n}\n//First column is the defalut\ngsl_vector *Ve() { \n\tve.size = ma->size1;\n\tve.stride = ma->tda;\n\tve.data = ma->data;\n\t\n\treturn &ve;\n}\n\n\n//Row Vector\ngsl_vector *AsRowVec(int Row, int ChopOff=0) {\n\tassert(Row >= 0 && Row < ma->size1); // Bounds checking for rows\n\tve.size = ma->size2-ChopOff;\n\tve.stride = 1;\n\tve.data = ma->data + (ma->tda)*Row;\n\t\n\treturn &ve;\n}\n\n\n\n// Copy function.\n// Copies values from one Matrix object to another.\nvoid Copy(const Matrix *mat) {\n\n\tassert((nRow() == mat->nRow()) && (nCol() == mat->nCol()));\n gsl_matrix_memcpy( ma, mat->ma);\n}\n\n// Copy function.\n// Copies values from one Matrix object to another.\nvoid copy(const Matrix& mat) {\n gsl_matrix_memcpy( ma, mat.ma);\t\n}\n\n\nconst char *Header() { return header; }\n\n//*********************************************************************\nprotected:\n\n// Matrix data.\ngsl_matrix *ma;\ngsl_vector ve;\n\nchar *header;\n\n\n}; // Class Matrix\n\n\n\n\n\n\n\n\nclass SubMatrix : public Matrix {\n\nprivate:\n\tgsl_matrix_view view;\n\tMatrix *Parent;\n\t\npublic:\n\tSubMatrix(Matrix &mat, size_t k1, size_t k2, size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix ( mat.Ma(), k1, k2, n1, n2);\n\t\tma = &view.matrix;\n\t\tParent = &mat;\n\t\tif (mat.Header() != NULL)\n\t\t\theader = strdup(mat.Header());\n\t\telse\n\t\t\theader = NULL;\n\t}\n\t\n\tSubMatrix( Matrix& mat, size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix ( mat.Ma(), (size_t) 0, (size_t) 0, n1, n2);\n\t\tma = &view.matrix;\n\t\tParent = &mat;\n\t\tif (mat.Header() != NULL)\n\t\t\theader = strdup(mat.Header());\n\t\telse\n\t\t\theader = NULL;\n\t}\n\n\tSubMatrix() {\n\t//delay the opening of this submatrix\n\t\tma = NULL;\n\t\tParent = NULL;\n\t\theader = NULL;\n\t}\n\t\n\t~SubMatrix() { \n\t\tma = NULL; //we avoid the base class call to free with this\n\t\tif (header != NULL) {\n\t\t\tfree(header);\n\t\t\theader=NULL;\n\t\t}\n\n\t}\n\t\n\tvoid Set(Matrix *mat, size_t k1, size_t k2, size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix ( mat->Ma(), k1, k2, n1, n2);\n\t\tma = &view.matrix;\n\t\tParent = mat;\n\t\tif (mat->Header() == NULL)\n\t\t\theader = NULL;\n\t\telse\n\t\t\theader = strdup(mat->Header());\n\t}\n\t\n\tconst char *SetHeader(char *head) {\n\t\tif (header != NULL)\n\t\t\tfree(header);\n\t\theader == NULL;\n\t\tif (head != NULL)\n\t\t\theader = strdup(head);\n\t\treturn header;\n\t}\n\t\n\n// Assignment operator function.\n// Overloads the equal sign operator to work with\n// Matrix objects.\nSubMatrix& operator=(const SubMatrix& mat) {\n if( this == &mat ) return *this; // If two sides equal, do nothing.\n this->copy(mat); // Copy right hand side to l.h.s.\n return *this;\n}\n\n// += operator function.\n// Overloads the += sign operator to work with\n// Matrix objects.\nSubMatrix& operator+=(const SubMatrix& mat) {\n gsl_matrix_add( this->ma, mat.ma); \n return *this;\n}\n\n// -= operator function.\n// Overloads the -= sign operator to work with\n// Matrix objects.\nSubMatrix& operator-=(const SubMatrix& mat) {\n gsl_matrix_sub( this->ma, mat.ma); \n return *this;\n}\n\n// *= operator function.\n// Overloads the *= sign operator to work with\n// Matrix objects.\nSubMatrix& operator*=(const double a) {\n gsl_matrix_scale( this->ma, a); \n return *this;\n}\n\n\n\n\tvoid Set( Matrix *mat, size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix ( mat->Ma(), (size_t) 0, (size_t) 0, n1, n2);\n\t\tma = &view.matrix;\n\t\tParent = mat;\n\t}\n\n\t\n\tvoid ReSize(size_t k1, size_t k2, size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix( Parent->Ma(), k1, k2, n1, n2);\n\t\tma = &view.matrix;\n\t}\n\t\n\tvoid ReSize(size_t n1, size_t n2) {\n\t\tview = gsl_matrix_submatrix ( Parent->Ma(), (size_t) 0, (size_t) 0, n1, n2);\n\t\tma = &view.matrix;\n\t}\n\t\n};\n\n\n\n/*Auxiliary functions*/\n//C = A^trA B^trB \nint MatMul(Matrix &C, int trA, Matrix &A, int trB, Matrix &B);\nint MatMul(Matrix &C, Matrix &A, Matrix &B);\ndouble CuadForm(Matrix &A, Matrix &b);\nint MatMulSym(Matrix &C, Matrix &A, Matrix &B);\n//inverse of real (symetric) positive defined matrix\n//as a by product we may obtain the square root of the determinat of A\nint InvRPD(Matrix &R, Matrix &A, double *LogDetSqrt=NULL, Matrix *ExternChol=NULL);\n//I have seen problems with this when dest and src are rows or cls of the same matrix\nint VecCopy(gsl_vector * dest, const gsl_vector * src);\n\n\n\n#endif\n\n", "meta": {"hexsha": "5b9ec14354316c3555dace23d84c7a00d16f43b6", "size": 10484, "ext": "h", "lang": "C", "max_stars_repo_path": "UW_ACES2016/cpp/Matrix.h", "max_stars_repo_name": "SFlantua/Workshops", "max_stars_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T16:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T22:49:11.000Z", "max_issues_repo_path": "UW_ACES2016/cpp/Matrix.h", "max_issues_repo_name": "SFlantua/Workshops", "max_issues_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-07-25T19:44:00.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-14T18:14:40.000Z", "max_forks_repo_path": "UW_ACES2016/cpp/Matrix.h", "max_forks_repo_name": "SFlantua/Workshops", "max_forks_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-07T03:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T13:27:02.000Z", "avg_line_length": 22.8409586057, "max_line_length": 105, "alphanum_fraction": 0.6054940862, "num_tokens": 3254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6716194594997201}} {"text": "#ifndef __GSLEXTRA_H__\n#define __GSLEXTRA_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#include \n#include \n#include \n#include \n#include \n\n#endif\n\nvoid gsl_vector_complex_convert(gsl_vector * source, gsl_vector_complex * target, int length);\nvoid gsl_matrix_complex_convert(gsl_matrix * source, gsl_matrix_complex * target, int rows, int columns);\nvoid gsl_vector_complex_extract(gsl_vector_complex * source, gsl_vector * real, gsl_vector * imag, int length);\nvoid gsl_matrix_complex_extract(gsl_vector_complex * source, gsl_matrix * real,gsl_matrix * imag, int rows, int columns);\nvoid gsl_vector_complex_combine(gsl_vector * real, gsl_vector * imag, gsl_vector_complex * target);\nvoid gsl_matrix_complex_combine(gsl_matrix * real,gsl_matrix * imag, gsl_matrix_complex * target);\nvoid gsl_matrix_diag(gsl_matrix * target, gsl_vector * diag, int length);\nvoid gsl_matrix_complex_diag(gsl_matrix_complex * target, gsl_vector_complex * diag, int length);\nvoid gsl_matrix_mul(gsl_matrix * A, gsl_matrix *B, gsl_matrix * Result,int Acolumn,int Arow,int Bcolumn);\nvoid gsl_matrix_complex_mul(gsl_matrix_complex * A, gsl_matrix_complex *B, gsl_matrix_complex * Result,int Acolumn,int Arow,int Bcolumn);\ndouble gsl_vector_inner_product(gsl_vector * A, gsl_vector * B,int length);\ngsl_complex gsl_vector_complex_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);\ngsl_complex gsl_vector_complex_inner_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);\nvoid gsl_vector_transform(gsl_vector * vec,gsl_matrix * trf,int length);\nvoid gsl_vector_complex_transform(gsl_vector_complex * vec, gsl_matrix_complex * trf,int length);\nvoid gsl_matrix_unitmatrix(gsl_matrix * m,int length);\nvoid gsl_matrix_complex_unitmatrix(gsl_matrix_complex * m,int length);\nvoid gsl_vector_complex_conjugate(gsl_vector_complex * v, int length);\nvoid gsl_matrix_complex_conjugate(gsl_matrix_complex * m, int rows, int columns);", "meta": {"hexsha": "61c376dfb52ebeaaa69744fae1c69ac7dad8475d", "size": 2289, "ext": "h", "lang": "C", "max_stars_repo_path": "gslextra.h", "max_stars_repo_name": "Walter-Feng/HomebrewLib", "max_stars_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T12:45:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T12:45:50.000Z", "max_issues_repo_path": "gslextra.h", "max_issues_repo_name": "Walter-Feng/HomebrewLib", "max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43", "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": "gslextra.h", "max_forks_repo_name": "Walter-Feng/HomebrewLib", "max_forks_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43", "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": 54.5, "max_line_length": 137, "alphanum_fraction": 0.8090869375, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567085, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6714628579463383}} {"text": "#include \r\n#include \r\n#include \r\n\r\n//#include \"WignerD_fftw.h\"\r\n\r\n#include \r\n\r\n#define max(a,b) \\\r\n ({ __typeof__ (a) _a = (a); \\\r\n __typeof__ (b) _b = (b); \\\r\n _a > _b ? _a : _b; })\r\n\t \r\n#define min(x,y) (((x) < (y)) ? (x) : (y))\r\n\r\n#define MAXFILENAME 100\r\n\r\nlapack_complex_double *Iy_Matrix(lapack_int Ndim) \r\n{\r\ndouble J = (Ndim-1)/2.;\r\nlapack_complex_double *AB = calloc(Ndim*2,sizeof(lapack_complex_double));\r\n\r\nlapack_complex_double zero = lapack_make_complex_double(0.0,0.0);\r\nlapack_complex_double myimag = lapack_make_complex_double(0.0,1.0);\r\n//prepare the upper triangle of Iy\r\n//the array is computed in FORTRAN style (transposed)\r\n double m;\r\n for (int i=0; i\n#include \n#include \n#include \n#include \n\n/* The lognormal distribution has the form \n\n p(x) dx = 1/(x * sqrt(2 pi sigma^2)) exp(-(ln(x) - zeta)^2/2 sigma^2) dx\n\n for x > 0. Lognormal random numbers are the exponentials of\n gaussian random numbers */\n\ndouble\ngsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma)\n{\n double u, v, r2, normal, z;\n\n do\n {\n /* choose x,y in uniform square (-1,-1) to (+1,+1) */\n\n u = -1 + 2 * gsl_rng_uniform (r);\n v = -1 + 2 * gsl_rng_uniform (r);\n\n /* see if it is in the unit circle */\n r2 = u * u + v * v;\n }\n while (r2 > 1.0 || r2 == 0);\n\n normal = u * sqrt (-2.0 * log (r2) / r2);\n\n z = exp (sigma * normal + zeta);\n\n return z;\n}\n\ndouble\ngsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma)\n{\n if (x <= 0)\n {\n return 0 ;\n }\n else\n {\n double u = (log (x) - zeta)/sigma;\n double p = 1 / (x * fabs(sigma) * sqrt (2 * M_PI)) * exp (-(u * u) /2);\n return p;\n }\n}\n", "meta": {"hexsha": "2dc215ae96c729144138383aba6c27510ef56436", "size": 1925, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/lognormal.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/lognormal.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/lognormal.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.1126760563, "max_line_length": 81, "alphanum_fraction": 0.6358441558, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6712801974907743}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"../Scanner/scanner.h\"\n#include \"../Utils/Types.h\"\n\nclass Expression;\n\ntypedef std::shared_ptr expression;\ntypedef std::map Variables;\n\nextern const Variables emptyVars;\n\ntypedef expression(*TransformerFunction)(expression);\n\nclass Expression: public std::enable_shared_from_this {\n\n public:\n const Scanner::Type kind;\n\n Expression(Scanner::Type kind);\n virtual ~Expression();\n\n virtual expression simplify();\n virtual expression derivative(const std::string& var);\n virtual expression integrate(const std::string& var);\n\n virtual bool isComplex() const = 0;\n virtual bool isEvaluable(const Variables& vars = emptyVars) const = 0;\n virtual bool isNumber() const { return false; }\n\n virtual expression eval(const Variables& vars = emptyVars) = 0;\n virtual double value(const Variables& vars = emptyVars) const = 0;\n virtual gsl_complex complex(const Variables& vars = emptyVars) const;\n\n virtual bool equals(expression, double precision=1e-15) const = 0;\n\n std::vector array();\n virtual expression at(const int index);\n virtual double get(const int index);\n virtual size_t shape(const int axis) const;\n virtual size_t size() const;\n\n virtual expression call(expression e);\n inline expression operator()(expression e){ return call(e); }\n\n virtual expression apply(TransformerFunction f);\n inline expression operator()(TransformerFunction f){ return apply(f); }\n\n inline bool is(Scanner::Type kind) const { return this->kind == kind; }\n virtual std::string repr() const;\n virtual int id() const;\n\n expression copy();\n\n virtual std::ostream& print(std::ostream&, const bool pretty=false) const = 0;\n virtual std::ostream& postfix(std::ostream&) const = 0;\n\n private:\n struct gsl_expression_struct {\n Expression* e;\n const std::string var;\n Variables vars;\n\n gsl_expression_struct(Expression*, const std::string var = \"x\");\n };\n static double gsl_expression_function(double x, void* p);\n std::unique_ptr gsl_params;\n\n public:\n virtual gsl_function function(const std::string& var = \"x\");\n\n private:\n struct ExpressionIterator {\n expression e;\n size_t index;\n\n ExpressionIterator(expression e, size_t index);\n\n expression operator*();\n\n bool operator==(const ExpressionIterator& other) const;\n bool operator!=(const ExpressionIterator& other) const;\n bool operator<(const ExpressionIterator& other) const;\n bool operator<=(const ExpressionIterator& other) const;\n bool operator>(const ExpressionIterator& other) const;\n bool operator>=(const ExpressionIterator& other) const;\n\n ExpressionIterator& operator++();\n ExpressionIterator& operator--();\n };\n public:\n ExpressionIterator begin();\n ExpressionIterator end();\n};\n\nstd::ostream& operator<<(std::ostream&, const expression);\n\n#define EXPRESSION_PARTIAL_OVERRIDES \\\n bool isComplex() const override; \\\n bool isEvaluable(const Variables& vars = emptyVars) const override; \\\n bool equals(expression, double precision) const override; \\\n std::ostream& print(std::ostream&, const bool pretty = false) const override; \\\n std::ostream& postfix(std::ostream&) const override;\n\n#define EXPRESSION_OVERRIDES \\\n EXPRESSION_PARTIAL_OVERRIDES \\\n expression eval(const Variables& vars = emptyVars) override; \\\n double value(const Variables& vars = emptyVars) const override;\n", "meta": {"hexsha": "dc8d7c71188f3ffe49006af78efdc0074d70d08e", "size": 4187, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Expressions/Expression.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "MathEngine/Expressions/Expression.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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": "MathEngine/Expressions/Expression.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "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.4830508475, "max_line_length": 86, "alphanum_fraction": 0.6240745164, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6711141778604831}} {"text": "/*\n * Dice Tester - Counter tool to display statistics about the randomness of dice \n */\n\n#include \n#include \n#include \n#include \n#include \n\nint\ngetSides(int argc, char **argv) {\n int sides = 6;\n if (argc >= 2 && atoi(argv[1]) > 0)\n sides = atoi(argv[1]);\n return sides;\n}\n\ndouble\nchiSquared(double *observed, double *expected, int sides) {\n double sum = 0.0;\n for (int i = 0; i < sides; i++)\n sum += pow((observed[i] - expected[i]), 2) / expected[i];\n return sum;\n}\n\nint\nmain(int argc, char **argv)\n{\n char input[8];\n int num, total, sides, memSize;\n double *observed, *expected;\n \n total = 0;\n\n sides = getSides(argc, argv);\n memSize = sizeof(double) * sides;\n observed = malloc(memSize);\n expected = malloc(memSize);\n printf(\"HERE %d\\n\", sides);\n for (int i = 0; i < sides; i++)\n observed[i] = 0.0;\n \n printf(\"HERE %d\\n\", sides);\n printf(\"Obs: %f\\n\", observed[0]);\n /* Load observed data */\n while (scanf(\"%s\", input) != EOF) {\n num = atoi(input);\n\n if (num >= 1 && num <= sides) {\n printf(\"%d\\n\", num);\n observed[num-1] += 1;\n total += 1;\n }\n getchar();\n }\n\n /* Random = flat distribution */\n for (int i = 0; i < sides; i++)\n expected[i] = (double) total / sides;\n\n double chi2 = chiSquared(observed, expected, sides);\n double pval = 1-gsl_cdf_chisq_P(chi2, sides-1);\n\n fputs(\"\\n########## RESULTS ##########\\n\", stderr);\n fputs(\"Num:\\tExp:\\tObs:\\tPer:\\t\\n\", stderr);\n for (int i = 0; i < sides; i++)\n fprintf(stderr, \"%d:\\t %2.0f\\t %2.0f\\t %3.0f%%\\n\", i+1, expected[i], observed[i], (observed[i] / total)*100);\n if (pval >= 0.1)\n fputs(\"\\nDie is fair :)\\n\", stderr);\n else if (pval > 0.05)\n fputs(\"\\nDie is probably fair\\n\", stderr);\n else\n fputs(\"\\nDie not fair :(\\n\", stderr);\n\n free(observed);\n free(expected);\n \n return 0;\n}\n", "meta": {"hexsha": "58beb881a92a59a58dc580f4405b8dae0c6e9fcb", "size": 1874, "ext": "c", "lang": "C", "max_stars_repo_path": "dt.c", "max_stars_repo_name": "Seth0110/dicetester", "max_stars_repo_head_hexsha": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7", "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": "dt.c", "max_issues_repo_name": "Seth0110/dicetester", "max_issues_repo_head_hexsha": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7", "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": "dt.c", "max_forks_repo_name": "Seth0110/dicetester", "max_forks_repo_head_hexsha": "43c4c656bfe92d7815eb9850e39eea84ff81dfe7", "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.1358024691, "max_line_length": 113, "alphanum_fraction": 0.5752401281, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6705316119982723}} {"text": "#include \n#include \n#include \n#include \n#include \n\nint\nmain (void)\n{\n int N = 4;\n double x[4] = {0.00, 0.10, 0.27, 0.30};\n double y[4] = {0.15, 0.70, -0.10, 0.15}; \n /* Note: y[0] == y[3] for periodic data */\n\n gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n const gsl_interp_type *t = gsl_interp_cspline_periodic; \n gsl_spline *spline = gsl_spline_alloc (t, N);\n\n int i; double xi, yi;\n\n printf (\"#m=0,S=5\\n\");\n for (i = 0; i < N; i++)\n {\n printf (\"%g %g\\n\", x[i], y[i]);\n }\n\n printf (\"#m=1,S=0\\n\");\n gsl_spline_init (spline, x, y, N);\n\n for (i = 0; i <= 100; i++)\n {\n xi = (1 - i / 100.0) * x[0] + (i / 100.0) * x[N-1];\n yi = gsl_spline_eval (spline, xi, acc);\n printf (\"%g %g\\n\", xi, yi);\n }\n \n gsl_spline_free (spline);\n gsl_interp_accel_free (acc);\n return 0;\n}\n", "meta": {"hexsha": "02488a1c878f96a751ab6c010d04f63536e05752", "size": 896, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/interpp.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/doc/examples/interpp.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/interpp.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": 21.8536585366, "max_line_length": 58, "alphanum_fraction": 0.5401785714, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6703122776547225}} {"text": "/* Foundation and miscellenea for the statistics modules.\n * \n * Contents:\n * 1. Summary statistics (means, variances)\n * 2. Special functions\n * 3. Standard statistical tests\n * 4. Data fitting.\n * 5. Unit tests.\n * 6. Test driver.\n * 7. Examples.\n * - driver for linear regression\n * - driver for G-test\n */\n#include \"esl_config.h\"\n\n#include \n\n#include \"easel.h\"\n#include \"esl_stats.h\"\n\n\n/*****************************************************************\n * 1. Summary statistics calculations (means, variances)\n *****************************************************************/\n\n/* Function: esl_stats_DMean()\n * Synopsis: Calculates mean and $\\sigma^2$ for samples $x_i$.\n *\n * Purpose: Calculates the sample mean and $s^2$, the unbiased\n * estimator of the population variance, for a\n * sample of numbers , and optionally\n * returns either or both through and\n * .\n * \n * and do the same,\n * for float and integer vectors.\n *\n * Args: x - samples x[0]..x[n-1]\n * n - number of samples\n * opt_mean - optRETURN: mean\n * opt_var - optRETURN: estimate of population variance \n *\n * Returns: on success.\n */\nint\nesl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\nint\nesl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\nint\nesl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var)\n{\n double sum = 0.;\n double sqsum = 0.;\n int i;\n\n for (i = 0; i < n; i++) \n { \n sum += x[i];\n sqsum += x[i]*x[i];\n }\n if (opt_mean != NULL) *opt_mean = sum / (double) n;\n if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);\n return eslOK;\n}\n/*--------------- end, summary statistics -----------------------*/\n\n\n\n/*****************************************************************\n * 2. Special functions.\n *****************************************************************/\n\n/* Function: esl_stats_LogGamma()\n * Synopsis: Calculates $\\log \\Gamma(x)$.\n *\n * Purpose: Returns natural log of $\\Gamma(x)$, for $x > 0$.\n * \n * Credit: Adapted from a public domain implementation in the\n * NCBI core math library. Thanks to John Spouge and\n * the NCBI. (According to NCBI, that's Dr. John\n * \"Gammas Galore\" Spouge to you, pal.)\n *\n * Args: x : argument, x > 0.0\n * ret_answer : RETURN: the answer\n *\n * Returns: Put the answer in ; returns .\n * \n * Throws: if $x <= 0$.\n */\nint\nesl_stats_LogGamma(double x, double *ret_answer)\n{\n int i;\n double xx, tx;\n double tmp, value;\n static double cof[11] = {\n 4.694580336184385e+04,\n -1.560605207784446e+05,\n 2.065049568014106e+05,\n -1.388934775095388e+05,\n 5.031796415085709e+04,\n -9.601592329182778e+03,\n 8.785855930895250e+02,\n -3.155153906098611e+01,\n 2.908143421162229e-01,\n -2.319827630494973e-04,\n 1.251639670050933e-10\n };\n \n /* Protect against invalid x<=0 */\n if (x <= 0.0) ESL_EXCEPTION(eslERANGE, \"invalid x <= 0 in esl_stats_LogGamma()\");\n\n xx = x - 1.0;\n tx = tmp = xx + 11.0;\n value = 1.0;\n for (i = 10; i >= 0; i--)\t/* sum least significant terms first */\n {\n value += cof[i] / tmp;\n tmp -= 1.0;\n }\n value = log(value);\n tx += 0.5;\n value += 0.918938533 + (xx+0.5)*log(tx) - tx;\n *ret_answer = value;\n return eslOK;\n}\n\n\n/* Function: esl_stats_Psi()\n * Synopsis: Calculates $\\Psi(x)$ (the digamma function).\n *\n * Purpose: Computes $\\Psi(x)$ (the \"digamma\" function), which is\n * the derivative of log of the Gamma function:\n * $d/dx \\log \\Gamma(x) = \\frac{\\Gamma'(x)}{\\Gamma(x)} = \\Psi(x)$.\n * Argument $x$ is $> 0$. \n * \n * This is J.M. Bernardo's \"Algorithm AS103\",\n * Appl. Stat. 25:315-317 (1976). \n */\nint\nesl_stats_Psi(double x, double *ret_answer)\n{\n double answer = 0.;\n double x2;\n\n if (x <= 0.0) ESL_EXCEPTION(eslERANGE, \"invalid x <= 0 in esl_stats_Psi()\");\n \n /* For small x, Psi(x) ~= -0.5772 - 1/x + O(x), we're done.\n */\n if (x <= 1e-5) {\n *ret_answer = -eslCONST_EULER - 1./x;\n return eslOK;\n }\n\n /* For medium x, use Psi(1+x) = \\Psi(x) + 1/x to c.o.v. x,\n * big enough for Stirling approximation to work...\n */\n while (x < 8.5) {\n answer = answer - 1./x;\n x += 1.;\n }\n \n /* For large X, use Stirling approximation\n */\n x2 = 1./x;\n answer += log(x) - 0.5 * x2;\n x2 = x2*x2;\n answer -= (1./12.)*x2;\n answer += (1./120.)*x2*x2;\n answer -= (1./252.)*x2*x2*x2;\n\n *ret_answer = answer;\n return eslOK;\n}\n\n\n\n/* Function: esl_stats_IncompleteGamma()\n * Synopsis: Calculates the incomplete Gamma function.\n * \n * Purpose: Returns $P(a,x)$ and $Q(a,x)$ where:\n *\n * \\begin{eqnarray*}\n * P(a,x) & = & \\frac{1}{\\Gamma(a)} \\int_{0}^{x} t^{a-1} e^{-t} dt \\\\\n * & = & \\frac{\\gamma(a,x)}{\\Gamma(a)} \\\\\n * Q(a,x) & = & \\frac{1}{\\Gamma(a)} \\int_{x}^{\\infty} t^{a-1} e^{-t} dt\\\\\n * & = & 1 - P(a,x) \\\\\n * \\end{eqnarray*}\n *\n * $P(a,x)$ is the CDF of a gamma density with $\\lambda = 1$,\n * and $Q(a,x)$ is the survival function.\n * \n * For $x \\simeq 0$, $P(a,x) \\simeq 0$ and $Q(a,x) \\simeq 1$; and\n * $P(a,x)$ is less prone to roundoff error. \n * \n * The opposite is the case for large $x >> a$, where\n * $P(a,x) \\simeq 1$ and $Q(a,x) \\simeq 0$; there, $Q(a,x)$ is\n * less prone to roundoff error.\n *\n * Method: Based on ideas from Numerical Recipes in C, Press et al.,\n * Cambridge University Press, 1988. \n * \n * Args: a - for instance, degrees of freedom / 2 [a > 0]\n * x - for instance, chi-squared statistic / 2 [x >= 0] \n * ret_pax - RETURN: P(a,x)\n * ret_qax - RETURN: Q(a,x)\n *\n * Return: on success.\n *\n * Throws: if or is out of accepted range.\n * if approximation fails to converge.\n */ \nint\nesl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax)\n{\n int iter;\t\t\t/* iteration counter */\n double pax;\t\t\t/* P(a,x) */\n double qax;\t\t\t/* Q(a,x) */\n int status;\n\n if (a <= 0.) ESL_EXCEPTION(eslERANGE, \"esl_stats_IncompleteGamma(): a must be > 0\");\n if (x < 0.) ESL_EXCEPTION(eslERANGE, \"esl_stats_IncompleteGamma(): x must be >= 0\");\n\n /* For x > a + 1 the following gives rapid convergence;\n * calculate Q(a,x) = \\frac{\\Gamma(a,x)}{\\Gamma(a)},\n * using a continued fraction development for \\Gamma(a,x).\n */\n if (x > a+1) \n {\n double oldp;\t\t/* previous value of p */\n double nu0, nu1;\t\t/* numerators for continued fraction calc */\n double de0, de1;\t\t/* denominators for continued fraction calc */\n\n nu0 = 0.;\t\t\t/* A_0 = 0 */\n de0 = 1.;\t\t\t/* B_0 = 1 */\n nu1 = 1.;\t\t\t/* A_1 = 1 */\n de1 = x;\t\t\t/* B_1 = x */\n\n oldp = nu1;\n for (iter = 1; iter < 100; iter++)\n\t{\n\t /* Continued fraction development:\n\t * set A_j = b_j A_j-1 + a_j A_j-2\n\t * B_j = b_j B_j-1 + a_j B_j-2\n * We start with A_2, B_2.\n\t */\n\t\t\t\t/* j = even: a_j = iter-a, b_j = 1 */\n\t\t\t\t/* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */\n\t nu0 = nu1 + ((double)iter - a) * nu0;\n\t de0 = de1 + ((double)iter - a) * de0;\n\t\t\t\t/* j = odd: a_j = iter, b_j = x */\n\t\t\t\t/* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */\n\t nu1 = x * nu0 + (double) iter * nu1;\n\t de1 = x * de0 + (double) iter * de1;\n\t\t\t\t/* rescale */\n\t if (de1 != 0.) \n\t { \n\t nu0 /= de1; \n\t de0 /= de1;\n\t nu1 /= de1;\n\t de1 = 1.;\n\t }\n\t\t\t\t/* check for convergence */\n\t if (fabs((nu1-oldp)/nu1) < 1.e-7)\n\t {\n\t if ((status = esl_stats_LogGamma(a, &qax)) != eslOK) return status;\t \n\t qax = nu1 * exp(a * log(x) - x - qax);\n\n\t if (ret_pax != NULL) *ret_pax = 1 - qax;\n\t if (ret_qax != NULL) *ret_qax = qax;\n\t return eslOK;\n\t }\n\n\t oldp = nu1;\n\t}\n ESL_EXCEPTION(eslENOHALT,\n\t\t\"esl_stats_IncompleteGamma(): fraction failed to converge\");\n }\n else /* x <= a+1 */\n {\n double p;\t\t\t/* current sum */\n double val;\t\t/* current value used in sum */\n\n /* For x <= a+1 we use a convergent series instead:\n * P(a,x) = \\frac{\\gamma(a,x)}{\\Gamma(a)},\n * where\n * \\gamma(a,x) = e^{-x}x^a \\sum_{n=0}{\\infty} \\frac{\\Gamma{a}}{\\Gamma{a+1+n}} x^n\n * which looks appalling but the sum is in fact rearrangeable to\n * a simple series without the \\Gamma functions:\n * = \\frac{1}{a} + \\frac{x}{a(a+1)} + \\frac{x^2}{a(a+1)(a+2)} ...\n * and it's obvious that this should converge nicely for x <= a+1.\n */\n p = val = 1. / a;\n for (iter = 1; iter < 10000; iter++)\n\t{\n\t val *= x / (a+(double)iter);\n\t p += val;\n\t \n\t if (fabs(val/p) < 1.e-7)\n\t {\n\t if ((status = esl_stats_LogGamma(a, &pax)) != eslOK) return status;\n\t pax = p * exp(a * log(x) - x - pax);\n\n\t if (ret_pax != NULL) *ret_pax = pax;\n\t if (ret_qax != NULL) *ret_qax = 1. - pax;\n\t return eslOK;\n\t }\n\t}\n ESL_EXCEPTION(eslENOHALT,\n\t\t\"esl_stats_IncompleteGamma(): series failed to converge\");\n }\n /*NOTREACHED*/\n return eslOK;\n}\n\n\n/* Function: esl_stats_erfc()\n * Synopsis: Complementary error function.\n *\n * Purpose: Calculate and return the complementary error function, \n * erfc(x).\n * \n * erfc(x) is mandated by the ANSI C99 standard but that\n * doesn't mean it's available on supposedly modern systems\n * (looking at you here, Microsoft).\n * \n * Used for cumulative distribution function calculations\n * for the normal (Gaussian) distribution. See \n * module.\n * \n * erfc(-inf) = 2.0\n * erfc(0) = 1.0\n * erfc(inf) = 0.0\n * erfc(NaN) = NaN\n *\n * Args: x : any real-numbered value -inf..inf\n *\n * Returns: erfc(x)\n *\n * Throws: (no abnormal error conditions)\n *\n * Source:\n * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. \n * Developed at SunPro, a Sun Microsystems, Inc. business.\n * Permission to use, copy, modify, and distribute this software is\n * freely granted, provided that this notice is preserved.\n * [as posted by eggcrook at stackexchange.com, 21 Dec 2012]\n * \n * Removed arcane incantations for runtime detection of endianness,\n * and for treating IEEE754 doubles as two adjacent uint32_t;\n * replaced with ANSI-compliant macros and compile-time detection\n * of endianness. [Apr 2015]\n */\ndouble\nesl_stats_erfc(double x)\n{\n static const double tiny = 1e-300;\n static const double half = 5.00000000000000000000e-01; /* 0x3FE00000, 0x00000000 */\n static const double one = 1.00000000000000000000e+00; /* 0x3FF00000, 0x00000000 */\n static const double two = 2.00000000000000000000e+00; /* 0x40000000, 0x00000000 */\n static const double erx = 8.45062911510467529297e-01; /* 0x3FEB0AC1, 0x60000000 */\n /*\n * Coefficients for approximation to erf on [0,0.84375]\n */\n static const double pp0 = 1.28379167095512558561e-01; /* 0x3FC06EBA, 0x8214DB68 */\n static const double pp1 = -3.25042107247001499370e-01; /* 0xBFD4CD7D, 0x691CB913 */\n static const double pp2 = -2.84817495755985104766e-02; /* 0xBF9D2A51, 0xDBD7194F */\n static const double pp3 = -5.77027029648944159157e-03; /* 0xBF77A291, 0x236668E4 */\n static const double pp4 = -2.37630166566501626084e-05; /* 0xBEF8EAD6, 0x120016AC */\n static const double qq1 = 3.97917223959155352819e-01; /* 0x3FD97779, 0xCDDADC09 */\n static const double qq2 = 6.50222499887672944485e-02; /* 0x3FB0A54C, 0x5536CEBA */\n static const double qq3 = 5.08130628187576562776e-03; /* 0x3F74D022, 0xC4D36B0F */\n static const double qq4 = 1.32494738004321644526e-04; /* 0x3F215DC9, 0x221C1A10 */\n static const double qq5 = -3.96022827877536812320e-06; /* 0xBED09C43, 0x42A26120 */\n /*\n * Coefficients for approximation to erf in [0.84375,1.25]\n */\n static const double pa0 = -2.36211856075265944077e-03; /* 0xBF6359B8, 0xBEF77538 */\n static const double pa1 = 4.14856118683748331666e-01; /* 0x3FDA8D00, 0xAD92B34D */\n static const double pa2 = -3.72207876035701323847e-01; /* 0xBFD7D240, 0xFBB8C3F1 */\n static const double pa3 = 3.18346619901161753674e-01; /* 0x3FD45FCA, 0x805120E4 */\n static const double pa4 = -1.10894694282396677476e-01; /* 0xBFBC6398, 0x3D3E28EC */\n static const double pa5 = 3.54783043256182359371e-02; /* 0x3FA22A36, 0x599795EB */\n static const double pa6 = -2.16637559486879084300e-03; /* 0xBF61BF38, 0x0A96073F */\n static const double qa1 = 1.06420880400844228286e-01; /* 0x3FBB3E66, 0x18EEE323 */\n static const double qa2 = 5.40397917702171048937e-01; /* 0x3FE14AF0, 0x92EB6F33 */\n static const double qa3 = 7.18286544141962662868e-02; /* 0x3FB2635C, 0xD99FE9A7 */\n static const double qa4 = 1.26171219808761642112e-01; /* 0x3FC02660, 0xE763351F */\n static const double qa5 = 1.36370839120290507362e-02; /* 0x3F8BEDC2, 0x6B51DD1C */\n static const double qa6 = 1.19844998467991074170e-02; /* 0x3F888B54, 0x5735151D */\n /*\n * Coefficients for approximation to erfc in [1.25,1/0.35]\n */\n static const double ra0 = -9.86494403484714822705e-03; /* 0xBF843412, 0x600D6435 */\n static const double ra1 = -6.93858572707181764372e-01; /* 0xBFE63416, 0xE4BA7360 */\n static const double ra2 = -1.05586262253232909814e+01; /* 0xC0251E04, 0x41B0E726 */\n static const double ra3 = -6.23753324503260060396e+01; /* 0xC04F300A, 0xE4CBA38D */\n static const double ra4 = -1.62396669462573470355e+02; /* 0xC0644CB1, 0x84282266 */\n static const double ra5 = -1.84605092906711035994e+02; /* 0xC067135C, 0xEBCCABB2 */\n static const double ra6 = -8.12874355063065934246e+01; /* 0xC0545265, 0x57E4D2F2 */\n static const double ra7 = -9.81432934416914548592e+00; /* 0xC023A0EF, 0xC69AC25C */\n static const double sa1 = 1.96512716674392571292e+01; /* 0x4033A6B9, 0xBD707687 */\n static const double sa2 = 1.37657754143519042600e+02; /* 0x4061350C, 0x526AE721 */\n static const double sa3 = 4.34565877475229228821e+02; /* 0x407B290D, 0xD58A1A71 */\n static const double sa4 = 6.45387271733267880336e+02; /* 0x40842B19, 0x21EC2868 */\n static const double sa5 = 4.29008140027567833386e+02; /* 0x407AD021, 0x57700314 */\n static const double sa6 = 1.08635005541779435134e+02; /* 0x405B28A3, 0xEE48AE2C */\n static const double sa7 = 6.57024977031928170135e+00; /* 0x401A47EF, 0x8E484A93 */\n static const double sa8 = -6.04244152148580987438e-02; /* 0xBFAEEFF2, 0xEE749A62 */\n /*\n * Coefficients for approximation to erfc in [1/.35,28]\n */\n static const double rb0 = -9.86494292470009928597e-03; /* 0xBF843412, 0x39E86F4A */\n static const double rb1 = -7.99283237680523006574e-01; /* 0xBFE993BA, 0x70C285DE */\n static const double rb2 = -1.77579549177547519889e+01; /* 0xC031C209, 0x555F995A */\n static const double rb3 = -1.60636384855821916062e+02; /* 0xC064145D, 0x43C5ED98 */\n static const double rb4 = -6.37566443368389627722e+02; /* 0xC083EC88, 0x1375F228 */\n static const double rb5 = -1.02509513161107724954e+03; /* 0xC0900461, 0x6A2E5992 */\n static const double rb6 = -4.83519191608651397019e+02; /* 0xC07E384E, 0x9BDC383F */\n static const double sb1 = 3.03380607434824582924e+01; /* 0x403E568B, 0x261D5190 */\n static const double sb2 = 3.25792512996573918826e+02; /* 0x40745CAE, 0x221B9F0A */\n static const double sb3 = 1.53672958608443695994e+03; /* 0x409802EB, 0x189D5118 */\n static const double sb4 = 3.19985821950859553908e+03; /* 0x40A8FFB7, 0x688C246A */\n static const double sb5 = 2.55305040643316442583e+03; /* 0x40A3F219, 0xCEDF3BE6 */\n static const double sb6 = 4.74528541206955367215e+02; /* 0x407DA874, 0xE79FE763 */\n static const double sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */\n\n int hx,ix;\n double R,S,P,Q,s,y,z,r;\n\n ESL_GET_HIGHWORD(hx, x); // SRE: replaced original Sun incantation here.\n ix = hx & 0x7fffffff;\n if (ix>=0x7ff00000) /* erfc(nan)=nan; erfc(+-inf)=0,2 */\n return (double)(((unsigned)hx>>31)<<1)+one/x;\n\n if (ix < 0x3feb0000) /* |x|<0.84375 */\n {\n if (ix < 0x3c700000) return one-x; /* |x|<2**-56 */\n z = x*x;\n r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4)));\n s = one+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5))));\n y = r/s;\n if (hx < 0x3fd00000) /* x<1/4 */\n\t{ \n\t return one-(x+x*y);\n\t} \n else \n\t{\n\t r = x*y;\n\t r += (x-half);\n\t return half - r ;\n\t}\n }\n\n if (ix < 0x3ff40000) /* 0.84375 <= |x| < 1.25 */\n { \n s = fabs(x)-one;\n P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6)))));\n Q = one+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6)))));\n if (hx>=0) \n\t{\n\t z = one-erx; \n\t return z - P/Q;\n\t}\n else \n\t{\n\t z = erx+P/Q;\n\t return one+z;\n\t}\n }\n\n if (ix < 0x403c0000) /* |x|<28 */\n { \n x = fabs(x);\n s = one/(x*x);\n if (ix< 0x4006DB6D) /* |x| < 1/.35 ~ 2.857143*/ \n\t{ \n\t R = ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*(ra5+s*(ra6+s*ra7))))));\n\t S = one+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*(sa5+s*(sa6+s*(sa7+s*sa8)))))));\n\t}\n else /* |x| >= 1/.35 ~ 2.857143 */\n\t{\n\t if (hx < 0 && ix >= 0x40180000) return two-tiny; /* x < -6 */\n\t R = rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*(rb5+s*rb6)))));\n\t S = one+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*(sb5+s*(sb6+s*sb7))))));\n\t}\n z = x;\n ESL_SET_LOWWORD(z, 0); // SRE: replaced original Sun incantation here.\n r = exp(-z*z-0.5625) * exp((z-x)*(z+x)+R/S);\n\n if (hx>0) return r/x;\n else return two-r/x;\n } \n else \n {\n if (hx>0) return tiny*tiny; \n else return two-tiny;\n }\n}\n/*----------------- end, special functions ----------------------*/\n\n\n/*****************************************************************\n * 3. Standard statistical tests.\n *****************************************************************/\n\n/* Function: esl_stats_GTest()\n * Synopsis: Calculates a G-test on 2 vs. 1 binomials.\n *\n * Purpose: In experiment a, we've drawn successes in total\n * trials; in experiment b, we've drawn successes in\n * total trials. Are the counts different enough to\n * conclude that the two experiments are different? The\n * null hypothesis is that the successes in both experiments\n * were drawn from the same binomial distribution with\n * per-trial probability $p$. The tested hypothesis is that\n * experiments a,b have different binomial probabilities\n * $p_a,p_b$. The G-test is a log-likelihood-ratio statistic,\n * assuming maximum likelihood values for $p,p_a,p_b$. \n * $2G$ is distributed approximately as $X^2(1)$,\n * %\"X\" is \"Chi\"\n * which we use to calculate a P-value for the G statistic.\n * \n * Args: ca - number of positives in experiment a\n * na - total number in experiment a\n * cb - number of positives in experiment b\n * nb - total number in experiment b\n * ret_G - RETURN: G statistic, a log likelihood ratio, in nats \n * ret_P - RETURN: P-value for the G-statistic\n *\n * Returns: on success.\n *\n * Throws: (no abnormal error conditions)\n *\n * Xref: Archive1999/0906-sagescore/sagescore.c\n */\nint\nesl_stats_GTest(int ca, int na, int cb, int nb, double *ret_G, double *ret_P)\n{\n double a,b,c,d,n;\n double G = 0.;\n\n a = (double) ca;\n b = (double) (na - ca);\n c = (double) cb;\n d = (double) (nb - cb);\n n = (double) na+nb;\n\n /* Yes, the calculation here is correct; algebraic \n * rearrangement of the log-likelihood-ratio with \n * p_a = ca/na, p_b = cb/nb, and p = (ca+cb)/(na+nb).\n * Guard against 0 probabilities; assume 0 log 0 => 0. \n */\n if (a > 0.) G = a * log(a);\n if (b > 0.) G += b * log(b);\n if (c > 0.) G += c * log(c);\n if (d > 0.) G += d * log(d);\n if (n > 0.) G += n * log(n);\n if (a+b > 0.) G -= (a+b) * log(a+b);\n if (c+d > 0.) G -= (c+d) * log(c+d);\n if (a+c > 0.) G -= (a+c) * log(a+c);\n if (b+d > 0.) G -= (b+d) * log(b+d);\n\n *ret_G = G;\n return esl_stats_IncompleteGamma( 0.5, G, NULL, ret_P);\n}\n\n\n/* Function: esl_stats_ChiSquaredTest()\n * Synopsis: Calculates a $\\chi^2$ P-value.\n * Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis]\n *\n * Purpose: Calculate the probability that a chi-squared statistic\n * with degrees of freedom would exceed the observed\n * chi-squared value ; return it in . If\n * this probability is less than some small threshold (say,\n * 0.05 or 0.01), then we may reject the hypothesis we're\n * testing.\n *\n * Args: v - degrees of freedom\n * x - observed chi-squared value\n * ret_answer - RETURN: P(\\chi^2 > x)\n *\n * Returns: on success.\n *\n * Throws: if or are out of valid range.\n * if iterative calculation fails.\n */\nint\nesl_stats_ChiSquaredTest(int v, double x, double *ret_answer)\n{\n return esl_stats_IncompleteGamma((double)v/2., x/2., NULL, ret_answer);\n}\n/*----------------- end, statistical tests ---------------------*/\n\n\n\n/*****************************************************************\n * 4. Data fitting.\n *****************************************************************/\n\n/* Function: esl_stats_LinearRegression()\n * Synopsis: Fit data to a straight line.\n * Incept: SRE, Sat May 26 11:33:46 2007 [Janelia]\n *\n * Purpose: Fit points , to a straight line\n * $y = a + bx$ by linear regression. \n * \n * The $x_i$ are taken to be known, and the $y_i$ are taken\n * to be observed quantities associated with a sampling\n * error $\\sigma_i$. If known, the standard deviations\n * $\\sigma_i$ for $y_i$ are provided in the array.\n * If they are unknown, pass , and the\n * routine will proceed with the assumption that $\\sigma_i\n * = 1$ for all $i$.\n * \n * The maximum likelihood estimates for $a$ and $b$ are\n * optionally returned in and .\n * \n * The estimated standard deviations of $a$ and $b$ and\n * their estimated covariance are optionally returned in\n * , , and .\n * \n * The Pearson correlation coefficient is optionally\n * returned in . \n * \n * The $\\chi^2$ P-value for the regression fit is\n * optionally returned in . This P-value may only be\n * obtained when the $\\sigma_i$ are known. If is\n * passed as and is requested, <*opt_Q> is\n * set to 1.0.\n * \n * This routine follows the description and algorithm in\n * \\citep[pp.661-666]{Press93}.\n *\n * must be greater than 2; at least two x[i] must\n * differ; and if is provided, all must\n * be $>0$. If any of these conditions isn't met, the\n * routine throws .\n *\n * Args: x - x[0..n-1]\n * y - y[0..n-1]\n * sigma - sample error in observed y_i\n * n - number of data points\n * opt_a - optRETURN: intercept estimate\t\t\n * opt_b - optRETURN: slope estimate\n * opt_sigma_a - optRETURN: error in estimate of a\n * opt_sigma_b - optRETURN: error in estimate of b\n * opt_cov_ab - optRETURN: covariance of a,b estimates\n * opt_cc - optRETURN: Pearson correlation coefficient for x,y\n * opt_Q - optRETURN: X^2 P-value for linear fit\n *\n * Returns: on success.\n *\n * Throws: on allocation error;\n * if a contract condition isn't met;\n * if the chi-squared test fails.\n * In these cases, all optional return values are set to 0.\n */\nint\nesl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n,\n\t\t\t double *opt_a, double *opt_b,\n\t\t\t double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab,\n\t\t\t double *opt_cc, double *opt_Q)\n{\n int status;\n double *t = NULL;\n double S, Sx, Sy, Stt;\n double Sxy, Sxx, Syy;\n double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q;\n double xdev, ydev;\n double tmp;\n int i;\n\n /* Contract checks. */\n if (n <= 2) ESL_XEXCEPTION(eslEINVAL, \"n must be > 2 for linear regression fitting\");\n if (sigma != NULL) \n for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, \"sigma[%d] <= 0\", i);\n status = eslEINVAL;\n for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; }\n if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, \"all x[i] are 0.\");\n\n /* Allocations */\n ESL_ALLOC(t, sizeof(double) * n);\n\n /* S = \\sum_{i=1}{n} \\frac{1}{\\sigma_i^2}. (S > 0.) */\n if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); }\n else S = (double) n;\n\n /* S_x = \\sum_{i=1}{n} \\frac{x[i]}{ \\sigma_i^2} (Sx real.) */\n for (Sx = 0., i = 0; i < n; i++) { \n if (sigma == NULL) Sx += x[i];\n else Sx += x[i] / (sigma[i] * sigma[i]);\n }\n\n /* S_y = \\sum_{i=1}{n} \\frac{y[i]}{\\sigma_i^2} (Sy real.) */\n for (Sy = 0., i = 0; i < n; i++) { \n if (sigma == NULL) Sy += y[i];\n else Sy += y[i] / (sigma[i] * sigma[i]);\n }\n\n /* t_i = \\frac{1}{\\sigma_i} \\left( x_i - \\frac{S_x}{S} \\right) (t_i real) */\n for (i = 0; i < n; i++) {\n t[i] = x[i] - Sx/S;\n if (sigma != NULL) t[i] /= sigma[i];\n }\n\n /* S_{tt} = \\sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */\n for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; }\n\n /* b = \\frac{1}{S_{tt}} \\sum_{i=1}^{N} \\frac{t_i y_i}{\\sigma_i} */\n for (b = 0., i = 0; i < n; i++) {\n if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; }\n else { b += t[i]*y[i]; }\n }\n b /= Stt;\n\n /* a = \\frac{ S_y - S_x b } {S} */\n a = (Sy - Sx * b) / S;\n \n /* \\sigma_a^2 = \\frac{1}{S} \\left( 1 + \\frac{ S_x^2 }{S S_{tt}} \\right) */\n sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S);\n\n /* \\sigma_b = \\frac{1}{S_{tt}} */\n sigma_b = sqrt (1. / Stt);\n\n /* Cov(a,b) = - \\frac{S_x}{S S_{tt}} */\n cov_ab = -Sx / (S * Stt);\n \n /* Pearson correlation coefficient */\n Sxy = Sxx = Syy = 0.;\n for (i = 0; i < n; i++) {\n if (sigma != NULL) { \n xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n);\n ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n);\n } else {\n xdev = x[i] - (Sx / n);\n ydev = y[i] - (Sy / n);\n }\n Sxy += xdev * ydev;\n Sxx += xdev * xdev;\n Syy += ydev * ydev;\n }\n cc = Sxy / (sqrt(Sxx) * sqrt(Syy));\n\n /* \\chi^2 */\n for (X2 = 0., i = 0; i < n; i++) {\n tmp = y[i] - a - b*x[i];\n if (sigma != NULL) tmp /= sigma[i];\n X2 += tmp*tmp;\n }\n \n /* We can calculate a goodness of fit if we know the \\sigma_i */\n if (sigma != NULL) {\n if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; }\n } else Q = 1.0;\n\n /* If we didn't use \\sigma_i, adjust the sigmas for a,b */\n if (sigma == NULL) {\n tmp = sqrt(X2 / (double)(n-2));\n sigma_a *= tmp;\n sigma_b *= tmp;\n }\n \n /* Done. Set up for normal return.\n */\n free(t);\n if (opt_a != NULL) *opt_a = a;\n if (opt_b != NULL) *opt_b = b;\n if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a;\n if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b;\n if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab;\n if (opt_cc != NULL) *opt_cc = cc;\n if (opt_Q != NULL) *opt_Q = Q;\n return eslOK;\n \n ERROR:\n if (t != NULL) free(t);\n if (opt_a != NULL) *opt_a = 0.;\n if (opt_b != NULL) *opt_b = 0.;\n if (opt_sigma_a != NULL) *opt_sigma_a = 0.;\n if (opt_sigma_b != NULL) *opt_sigma_b = 0.;\n if (opt_cov_ab != NULL) *opt_cov_ab = 0.;\n if (opt_cc != NULL) *opt_cc = 0.;\n if (opt_Q != NULL) *opt_Q = 0.;\n return status;\n}\n/*------------------- end, data fitting -------------------------*/\n\n\n\n/*****************************************************************\n * 5. Unit tests.\n *****************************************************************/\n#ifdef eslSTATS_TESTDRIVE\n#include \"esl_random.h\"\n#include \"esl_stopwatch.h\"\n#ifdef HAVE_LIBGSL \n#include \n#endif\n\n\n/* Macros for treating IEEE754 double as two uint32_t halves, with\n * compile-time handling of endianness; see esl_stats.h.\n */\nstatic void\nutest_doublesplitting(ESL_RANDOMNESS *rng)\n{\n char msg[] = \"esl_stats:: doublesplitting unit test failed\";\n uint32_t ix0, ix1;\n double x;\n double x2;\n int iteration; // iteration 0 uses x = 2; iteration 1 uses random x = [0,1).\n\n for (iteration = 0; iteration < 2; iteration++)\n {\n x = (iteration == 0 ? 2.0 : esl_random(rng));\n ESL_GET_WORDS(ix0, ix1, x);\n ESL_SET_WORDS(x2, ix0, ix1);\n if (x2 != x) esl_fatal(msg);\n\n ESL_GET_HIGHWORD(ix0, x);\n ESL_SET_HIGHWORD(x2, ix0);\n if (x2 != x) esl_fatal(msg);\n\n ESL_GET_LOWWORD(ix0, x);\n ESL_SET_LOWWORD(x2, ix0);\n if (iteration == 0 && ix0 != 0) esl_fatal(msg);\n if (x2 != x) esl_fatal(msg);\n }\n}\n \n/* The LogGamma() function is rate-limiting in hmmbuild, because it is\n * used so heavily in mixture Dirichlet calculations.\n * ./configure --with-gsl; [compile test driver]\n * ./stats_utest -v\n * runs a comparison of time/precision against GSL.\n * SRE, Sat May 23 10:04:41 2009, on home Mac:\n * LogGamma = 1.29u / N=1e8 = 13 nsec/call\n * gsl_sf_lngamma = 1.43u / N=1e8 = 14 nsec/call\n */\nstatic void\nutest_LogGamma(ESL_RANDOMNESS *r, int N, int be_verbose)\n{\n char *msg = \"esl_stats_LogGamma() unit test failed\";\n ESL_STOPWATCH *w = esl_stopwatch_Create();\n double *x = malloc(sizeof(double) * N);\n double *lg = malloc(sizeof(double) * N);\n double *lg2 = malloc(sizeof(double) * N);\n int i;\n\n for (i = 0; i < N; i++) \n x[i] = esl_random(r) * 100.;\n \n esl_stopwatch_Start(w);\n for (i = 0; i < N; i++) \n if (esl_stats_LogGamma(x[i], &(lg[i])) != eslOK) esl_fatal(msg);\n esl_stopwatch_Stop(w);\n\n if (be_verbose) esl_stopwatch_Display(stdout, w, \"esl_stats_LogGamma() timing: \");\n\n#ifdef HAVE_LIBGSL\n esl_stopwatch_Start(w);\n for (i = 0; i < N; i++) lg2[i] = gsl_sf_lngamma(x[i]);\n esl_stopwatch_Stop(w);\n\n if (be_verbose) esl_stopwatch_Display(stdout, w, \"gsl_sf_lngamma() timing: \");\n \n for (i = 0; i < N; i++)\n if (esl_DCompare(lg[i], lg2[i], 1e-2) != eslOK) esl_fatal(msg);\n#endif\n \n free(lg2);\n free(lg);\n free(x);\n esl_stopwatch_Destroy(w);\n}\n\n\n/* The test of esl_stats_LinearRegression() is a statistical test,\n * so we can't be too aggressive about testing results. \n * \n * Args:\n * r - a source of randomness\n * use_sigma - TRUE to pass sigma to the regression fit.\n * be_verbose - TRUE to print results (manual, not automated test mode)\n */\nstatic void\nutest_LinearRegression(ESL_RANDOMNESS *r, int use_sigma, int be_verbose)\n{\n char msg[] = \"linear regression unit test failed\";\n double a = -3.;\n double b = 1.;\n int n = 100;\n double xori = -20.;\n double xstep = 1.0;\n double setsigma = 1.0;\t\t/* sigma on all points */\n int i;\n double *x = NULL;\n double *y = NULL;\n double *sigma = NULL;\n double ae, be, siga, sigb, cov_ab, cc, Q;\n \n if ((x = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n if ((y = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n if ((sigma = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);\n \n /* Simulate some linear data */\n for (i = 0; i < n; i++)\n {\n sigma[i] = setsigma;\n x[i] = xori + i*xstep;\n y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);\n }\n \n if (use_sigma) {\n if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);\n } else {\n if (esl_stats_LinearRegression(x, y, NULL, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);\n }\n\n if (be_verbose) {\n printf(\"Linear regression test:\\n\");\n printf(\"estimated intercept a = %8.4f [true = %8.4f]\\n\", ae, a);\n printf(\"estimated slope b = %8.4f [true = %8.4f]\\n\", be, b);\n printf(\"estimated sigma on a = %8.4f\\n\", siga);\n printf(\"estimated sigma on b = %8.4f\\n\", sigb);\n printf(\"estimated cov(a,b) = %8.4f\\n\", cov_ab);\n printf(\"correlation coeff = %8.4f\\n\", cc);\n printf(\"P-value = %8.4f\\n\", Q);\n }\n\n /* The following tests are statistical.\n */\n if ( fabs(ae-a) > 2*siga ) esl_fatal(msg);\n if ( fabs(be-b) > 2*sigb ) esl_fatal(msg);\n if ( cc < 0.95) esl_fatal(msg);\n if (use_sigma) {\n if (Q < 0.001) esl_fatal(msg);\n } else {\n if (Q != 1.0) esl_fatal(msg);\n }\n\n free(x);\n free(y);\n free(sigma);\n}\n\nstatic void\nutest_erfc(ESL_RANDOMNESS *rng, int be_verbose)\n{\n char msg[] = \"esl_stats:: erfc unit test failed\";\n double x;\n double result;\n int i;\n\n if (be_verbose) {\n printf(\"#--------------------------\\n\");\n printf(\"# erfc unit testing...\\n\");\n }\n\n result = esl_stats_erfc( eslNaN);\n if (! isnan(result)) esl_fatal(msg);\n if (esl_stats_erfc(-eslINFINITY) != 2.0) esl_fatal(msg);\n if (esl_stats_erfc( 0.0) != 1.0) esl_fatal(msg);\n if (esl_stats_erfc( eslINFINITY) != 0.0) esl_fatal(msg);\n\n for (i = 0; i < 42; i++)\n {\n x = esl_random(rng) * 10. - 5.;\n result = esl_stats_erfc(x);\n if (!isfinite(result)) esl_fatal(msg);\n#ifdef HAVE_ERFC\n if (esl_DCompare(result, erfc(x), 1e-6) != eslOK) esl_fatal(msg);\n if (be_verbose)\n\tprintf(\"%15f %15f %15f\\n\", x, result, erfc(x));\n#endif\n }\n \n if (be_verbose)\n printf(\"#--------------------------\\n\");\n return;\n}\n\n#endif /*eslSTATS_TESTDRIVE*/\n/*-------------------- end of unit tests ------------------------*/\n\n\n\n\n/*****************************************************************\n * 6. Test driver.\n *****************************************************************/\n#ifdef eslSTATS_TESTDRIVE\n/* gcc -g -Wall -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lm\n * gcc -DHAVE_LIBGSL -O2 -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lgsl -lm\n */\n#include \n#include \"easel.h\"\n#include \"esl_getopts.h\"\n#include \"esl_random.h\"\n#include \"esl_stats.h\"\n\nstatic ESL_OPTIONS options[] = {\n /* name type default env range togs reqs incomp help docgrp */\n {\"-h\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"show help and usage\", 0},\n {\"-s\", eslARG_INT, \"42\", NULL, NULL, NULL, NULL, NULL, \"set random number seed to \", 0},\n {\"-v\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"verbose: show verbose output\", 0},\n {\"-N\", eslARG_INT,\"10000000\", NULL, NULL, NULL, NULL, NULL, \"number of trials in LogGamma test\", 0},\n { 0,0,0,0,0,0,0,0,0,0},\n};\nstatic char usage[] = \"[-options]\";\nstatic char banner[] = \"test driver for stats special functions\";\n\nint\nmain(int argc, char **argv)\n{\n ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);\n ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, \"-s\"));\n int be_verbose = esl_opt_GetBoolean(go, \"-v\");\n int N = esl_opt_GetInteger(go, \"-N\");\n\n if (be_verbose) printf(\"seed = %\" PRIu32 \"\\n\", esl_randomness_GetSeed(r));\n\n utest_doublesplitting(r);\n utest_erfc(r, be_verbose);\n utest_LogGamma(r, N, be_verbose);\n utest_LinearRegression(r, TRUE, be_verbose);\n utest_LinearRegression(r, FALSE, be_verbose);\n \n esl_getopts_Destroy(go);\n esl_randomness_Destroy(r);\n exit(0);\n}\n#endif /*eslSTATS_TESTDRIVE*/\n/*------------------- end of test driver ------------------------*/\n\n\n\n\n/*****************************************************************\n * 7. Examples.\n *****************************************************************/\n\n/* Compile: gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm \n * or gcc -g -Wall -o example -I. -L. -DeslSTATS_EXAMPLE esl_stats.c -leasel -lm \n */\n#ifdef eslSTATS_EXAMPLE\n/*::cexcerpt::stats_example::begin::*/\n/* gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm */\n#include \n#include \"easel.h\"\n#include \"esl_random.h\"\n#include \"esl_stats.h\"\n\nint main(void)\n{\n ESL_RANDOMNESS *r = esl_randomness_Create(0);\n double a = -3.;\n double b = 1.;\n double xori = -20.;\n double xstep = 1.0;\n double setsigma = 1.0;\t\t/* sigma on all points */\n int n = 100;\n double *x = malloc(sizeof(double) * n);\n double *y = malloc(sizeof(double) * n);\n double *sigma = malloc(sizeof(double) * n);\n int i;\n double ae, be, siga, sigb, cov_ab, cc, Q;\n \n /* Simulate some linear data, with Gaussian noise added to y_i */\n for (i = 0; i < n; i++) {\n sigma[i] = setsigma;\n x[i] = xori + i*xstep;\n y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);\n }\n \n if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK)\n esl_fatal(\"linear regression failed\");\n\n printf(\"estimated intercept a = %8.4f [true = %8.4f]\\n\", ae, a);\n printf(\"estimated slope b = %8.4f [true = %8.4f]\\n\", be, b);\n printf(\"estimated sigma on a = %8.4f\\n\", siga);\n printf(\"estimated sigma on b = %8.4f\\n\", sigb);\n printf(\"estimated cov(a,b) = %8.4f\\n\", cov_ab);\n printf(\"correlation coeff = %8.4f\\n\", cc);\n printf(\"P-value = %8.4f\\n\", Q);\n\n free(x); free(y); free(sigma); \n esl_randomness_Destroy(r);\n exit(0);\n}\n/*::cexcerpt::stats_example::end::*/\n#endif /* eslSTATS_EXAMPLE */\n\n\n#ifdef eslSTATS_EXAMPLE2\n\n#include \n\n#include \"easel.h\"\n#include \"esl_getopts.h\"\n#include \"esl_stats.h\"\n\nstatic ESL_OPTIONS options[] = {\n /* name type default env range toggles reqs incomp help docgroup*/\n { \"-h\", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, \"show brief help on version and usage\", 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },\n};\nstatic char usage[] = \"[-options] \";\nstatic char banner[] = \"example from the stats module: using a G-test\";\n\nint\nmain(int argc, char **argv)\n{\n ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 4, argc, argv, banner, usage);\n int ca = strtol(esl_opt_GetArg(go, 1), NULL, 10);\n int na = strtol(esl_opt_GetArg(go, 2), NULL, 10);\n int cb = strtol(esl_opt_GetArg(go, 3), NULL, 10);\n int nb = strtol(esl_opt_GetArg(go, 4), NULL, 10);\n double G, P;\n int status;\n \n if (ca > na || cb > nb) esl_fatal(\"argument order wrong? expect ca, na, cb, nb for ca/na, cb/nb\");\n \n if ( (status = esl_stats_GTest(ca, na, cb, nb, &G, &P)) != eslOK) esl_fatal(\"G-test failed?\");\n printf(\"%-10.3g %12.2f\\n\", P, G);\n exit(0);\n}\n#endif /* eslSTATS_EXAMPLE2 */\n/*--------------------- end of examples -------------------------*/\n\n", "meta": {"hexsha": "7fc7801b80674a19c7b6126676aa4c30dec601b9", "size": 40611, "ext": "c", "lang": "C", "max_stars_repo_path": "hmmer-3.3/easel/esl_stats.c", "max_stars_repo_name": "WooMichael/Project_Mendel", "max_stars_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "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": "hmmer-3.3/easel/esl_stats.c", "max_issues_repo_name": "WooMichael/Project_Mendel", "max_issues_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "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": "hmmer-3.3/easel/esl_stats.c", "max_forks_repo_name": "WooMichael/Project_Mendel", "max_forks_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8", "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.9793281654, "max_line_length": 124, "alphanum_fraction": 0.5533476152, "num_tokens": 13737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.8221891327004133, "lm_q1q2_score": 0.6702752859877765}} {"text": "/*********************************************************************************/\r\n/* Matrix product program with MPI on a virtual ring of processors */\r\n/* S. Vialle - October 2014 */\r\n/*********************************************************************************/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"main.h\"\r\n#include \"Calcul.h\"\r\n\r\n\r\n/*-------------------------------------------------------------------------------*/\r\n/* Sequential product of local matrixes (optimized seq product). */\r\n/*-------------------------------------------------------------------------------*/\r\nvoid OneLocalProduct(int step)\r\n{\r\n int OffsetStepLigC;\r\n int i, j, k;\r\n\r\n // Set the number of OpenMP threads inside parallel regions\r\n omp_set_num_threads(NbThreads);\r\n\r\n // Compute the current step offset, in the MPI program, to access right C lines\r\n OffsetStepLigC = (Me * LOCAL_SIZE + step * LOCAL_SIZE) % SIZE; \r\n\r\n switch (KernelId) {\r\n\r\n // Kernel 0 : Optimized code implemented by an application developer\r\n case 0 :\r\n for (i = 0; i < LOCAL_SIZE; i++) {\r\n for (j = 0; j < LOCAL_SIZE; j++) {\r\n double accu[8];\r\n accu[0] = accu[1] = accu[2] = accu[3] = accu[4] = accu[5] = accu[6] = accu[7] = 0.0;\r\n for (k = 0; k < (SIZE/8)*8; k += 8) {\r\n accu[0] += A_Slice[i][k+0] * TB_Slice[j][k+0];\r\n accu[1] += A_Slice[i][k+1] * TB_Slice[j][k+1];\r\n accu[2] += A_Slice[i][k+2] * TB_Slice[j][k+2];\r\n accu[3] += A_Slice[i][k+3] * TB_Slice[j][k+3];\r\n accu[4] += A_Slice[i][k+4] * TB_Slice[j][k+4];\r\n accu[5] += A_Slice[i][k+5] * TB_Slice[j][k+5];\r\n accu[6] += A_Slice[i][k+6] * TB_Slice[j][k+6];\r\n accu[7] += A_Slice[i][k+7] * TB_Slice[j][k+7];\r\n }\r\n for (k = (SIZE/8)*8; k < SIZE; k++) {\r\n accu[0] += A_Slice[i][k] * TB_Slice[j][k];\r\n } \r\n C_Slice[i+OffsetStepLigC][j] = accu[0] + accu[1] + accu[2] + accu[3] +\r\n accu[4] + accu[5] + accu[6] + accu[7];\r\n }\r\n }\r\n break;\r\n\r\n // Kernel 1 : Very optimized computing kernel implemented in a HPC library\r\n case 1 :\r\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\r\n LOCAL_SIZE, LOCAL_SIZE, SIZE,\r\n 1.0, &A_Slice[0][0], SIZE, \r\n &B_Slice[0][0], LOCAL_SIZE,\r\n 0.0, &C_Slice[OffsetStepLigC][0], LOCAL_SIZE);\r\n break;\r\n\r\n default :\r\n fprintf(stderr,\"Error: kernel %d not implemented!\\n\",KernelId);\r\n exit(EXIT_FAILURE);\r\n break;\r\n }\r\n}\r\n", "meta": {"hexsha": "5db53b6d78e359cf5694e41b78470772757d6304", "size": 2727, "ext": "c", "lang": "C", "max_stars_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c", "max_stars_repo_name": "pallamidessi/Courses", "max_stars_repo_head_hexsha": "ac5573cefc4c307c1a9f16a2c4e016a201dabece", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c", "max_issues_repo_name": "pallamidessi/Courses", "max_issues_repo_head_hexsha": "ac5573cefc4c307c1a9f16a2c4e016a201dabece", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c", "max_forks_repo_name": "pallamidessi/Courses", "max_forks_repo_head_hexsha": "ac5573cefc4c307c1a9f16a2c4e016a201dabece", "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.3561643836, "max_line_length": 97, "alphanum_fraction": 0.4503116978, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6701881880574306}} {"text": "#include \n#include \"poissonfunctions.h\"\n\nPetscErrorCode Poisson1DFunctionLocal(DMDALocalInfo *info, double *au,\n double *aF, PoissonCtx *user) {\n PetscErrorCode ierr;\n int i;\n double xmax[1], xmin[1], h, x, ue, uw;\n ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);\n h = (xmax[0] - xmin[0]) / (info->mx - 1);\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = xmin[0] + i * h;\n if (i==0 || i==info->mx-1) {\n aF[i] = au[i] - user->g_bdry(x,0.0,0.0,user);\n aF[i] *= user->cx * (2.0 / h);\n } else {\n ue = (i+1 == info->mx-1) ? user->g_bdry(x+h,0.0,0.0,user)\n : au[i+1];\n uw = (i-1 == 0) ? user->g_bdry(x-h,0.0,0.0,user)\n : au[i-1];\n aF[i] = user->cx * (2.0 * au[i] - uw - ue) / h\n - h * user->f_rhs(x,0.0,0.0,user);\n }\n }\n ierr = PetscLogFlops(9.0*info->xm);CHKERRQ(ierr);\n return 0;\n}\n\n//STARTFORM2DFUNCTION\nPetscErrorCode Poisson2DFunctionLocal(DMDALocalInfo *info, double **au,\n double **aF, PoissonCtx *user) {\n PetscErrorCode ierr;\n int i, j;\n double xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, x, y,\n ue, uw, un, us;\n ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info->mx - 1);\n hy = (xymax[1] - xymin[1]) / (info->my - 1);\n darea = hx * hy;\n scx = user->cx * hy / hx;\n scy = user->cy * hx / hy;\n scdiag = 2.0 * (scx + scy); // diagonal scaling\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = xymin[1] + j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = xymin[0] + i * hx;\n if (i==0 || i==info->mx-1 || j==0 || j==info->my-1) {\n aF[j][i] = au[j][i] - user->g_bdry(x,y,0.0,user);\n aF[j][i] *= scdiag;\n } else {\n ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,0.0,user)\n : au[j][i+1];\n uw = (i-1 == 0) ? user->g_bdry(x-hx,y,0.0,user)\n : au[j][i-1];\n un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,0.0,user)\n : au[j+1][i];\n us = (j-1 == 0) ? user->g_bdry(x,y-hy,0.0,user)\n : au[j-1][i];\n aF[j][i] = scdiag * au[j][i]\n - scx * (uw + ue) - scy * (us + un)\n - darea * user->f_rhs(x,y,0.0,user);\n }\n }\n }\n ierr = PetscLogFlops(11.0*info->xm*info->ym);CHKERRQ(ierr);\n return 0;\n}\n//ENDFORM2DFUNCTION\n\nPetscErrorCode Poisson3DFunctionLocal(DMDALocalInfo *info, double ***au,\n double ***aF, PoissonCtx *user) {\n PetscErrorCode ierr;\n int i, j, k;\n double xyzmin[3], xyzmax[3], hx, hy, hz, dvol, scx, scy, scz, scdiag,\n x, y, z, ue, uw, un, us, uu, ud;\n ierr = DMDAGetBoundingBox(info->da,xyzmin,xyzmax); CHKERRQ(ierr);\n hx = (xyzmax[0] - xyzmin[0]) / (info->mx - 1);\n hy = (xyzmax[1] - xyzmin[1]) / (info->my - 1);\n hz = (xyzmax[2] - xyzmin[2]) / (info->mz - 1);\n dvol = hx * hy * hz;\n scx = user->cx * dvol / (hx*hx);\n scy = user->cy * dvol / (hy*hy);\n scz = user->cz * dvol / (hz*hz);\n scdiag = 2.0 * (scx + scy + scz);\n for (k = info->zs; k < info->zs + info->zm; k++) {\n z = xyzmin[2] + k * hz;\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = xyzmin[1] + j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = xyzmin[0] + i * hx;\n if ( i==0 || i==info->mx-1\n || j==0 || j==info->my-1\n || k==0 || k==info->mz-1) {\n aF[k][j][i] = au[k][j][i] - user->g_bdry(x,y,z,user);\n aF[k][j][i] *= scdiag;\n } else {\n ue = (i+1 == info->mx-1) ? user->g_bdry(x+hx,y,z,user)\n : au[k][j][i+1];\n uw = (i-1 == 0) ? user->g_bdry(x-hx,y,z,user)\n : au[k][j][i-1];\n un = (j+1 == info->my-1) ? user->g_bdry(x,y+hy,z,user)\n : au[k][j+1][i];\n us = (j-1 == 0) ? user->g_bdry(x,y-hy,z,user)\n : au[k][j-1][i];\n uu = (k+1 == info->mz-1) ? user->g_bdry(x,y,z+hz,user)\n : au[k+1][j][i];\n ud = (k-1 == 0) ? user->g_bdry(x,y,z-hz,user)\n : au[k-1][j][i];\n aF[k][j][i] = scdiag * au[k][j][i]\n - scx * (uw + ue) - scy * (us + un) - scz * (uu + ud)\n - dvol * user->f_rhs(x,y,z,user);\n }\n }\n }\n }\n ierr = PetscLogFlops(14.0*info->xm*info->ym*info->zm);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode Poisson1DJacobianLocal(DMDALocalInfo *info, PetscScalar *au,\n Mat J, Mat Jpre, PoissonCtx *user) {\n PetscErrorCode ierr;\n int i,ncols;\n double xmin[1], xmax[1], h, v[3];\n MatStencil col[3],row;\n\n ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);\n h = (xmax[0] - xmin[0]) / (info->mx - 1);\n for (i = info->xs; i < info->xs+info->xm; i++) {\n row.i = i;\n col[0].i = i;\n ncols = 1;\n if (i==0 || i==info->mx-1) {\n v[0] = user->cx * 2.0 / h;\n } else {\n v[0] = user->cx * 2.0 / h;\n if (i-1 > 0) {\n col[ncols].i = i-1; v[ncols++] = - user->cx / h;\n }\n if (i+1 < info->mx-1) {\n col[ncols].i = i+1; v[ncols++] = - user->cx / h;\n }\n }\n ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);\n }\n\n ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != Jpre) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\nPetscErrorCode Poisson2DJacobianLocal(DMDALocalInfo *info, PetscScalar **au,\n Mat J, Mat Jpre, PoissonCtx *user) {\n PetscErrorCode ierr;\n double xymin[2], xymax[2], hx, hy, scx, scy, scdiag, v[5];\n int i,j,ncols;\n MatStencil col[5],row;\n\n ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info->mx - 1);\n hy = (xymax[1] - xymin[1]) / (info->my - 1);\n scx = user->cx * hy / hx;\n scy = user->cy * hx / hy;\n scdiag = 2.0 * (scx + scy);\n for (j = info->ys; j < info->ys+info->ym; j++) {\n row.j = j;\n col[0].j = j;\n for (i = info->xs; i < info->xs+info->xm; i++) {\n row.i = i;\n col[0].i = i;\n ncols = 1;\n v[0] = scdiag;\n if (i>0 && imx-1 && j>0 && jmy-1) {\n if (i-1 > 0) {\n col[ncols].j = j; col[ncols].i = i-1; v[ncols++] = - scx; }\n if (i+1 < info->mx-1) {\n col[ncols].j = j; col[ncols].i = i+1; v[ncols++] = - scx; }\n if (j-1 > 0) {\n col[ncols].j = j-1; col[ncols].i = i; v[ncols++] = - scy; }\n if (j+1 < info->my-1) {\n col[ncols].j = j+1; col[ncols].i = i; v[ncols++] = - scy; }\n }\n ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);\n }\n }\n\n ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != Jpre) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\nPetscErrorCode Poisson3DJacobianLocal(DMDALocalInfo *info, PetscScalar ***au,\n Mat J, Mat Jpre, PoissonCtx *user) {\n PetscErrorCode ierr;\n double xyzmin[3], xyzmax[3], hx, hy, hz, dvol, scx, scy, scz, scdiag, v[7];\n int i,j,k,ncols;\n MatStencil col[7],row;\n\n ierr = DMDAGetBoundingBox(info->da,xyzmin,xyzmax); CHKERRQ(ierr);\n hx = (xyzmax[0] - xyzmin[0]) / (info->mx - 1);\n hy = (xyzmax[1] - xyzmin[1]) / (info->my - 1);\n hz = (xyzmax[2] - xyzmin[2]) / (info->mz - 1);\n dvol = hx * hy * hz;\n scx = user->cx * dvol / (hx*hx);\n scy = user->cy * dvol / (hy*hy);\n scz = user->cz * dvol / (hz*hz);\n scdiag = 2.0 * (scx + scy + scz);\n for (k = info->zs; k < info->zs+info->zm; k++) {\n row.k = k;\n col[0].k = k;\n for (j = info->ys; j < info->ys+info->ym; j++) {\n row.j = j;\n col[0].j = j;\n for (i = info->xs; i < info->xs+info->xm; i++) {\n row.i = i;\n col[0].i = i;\n ncols = 1;\n v[0] = scdiag;\n if (i>0 && imx-1 && j>0 && jmy-1 && k>0 && kmz-1) {\n if (i-1 > 0) {\n col[ncols].k = k; col[ncols].j = j; col[ncols].i = i-1;\n v[ncols++] = - scx;\n }\n if (i+1 < info->mx-1) {\n col[ncols].k = k; col[ncols].j = j; col[ncols].i = i+1;\n v[ncols++] = - scx;\n }\n if (j-1 > 0) {\n col[ncols].k = k; col[ncols].j = j-1; col[ncols].i = i;\n v[ncols++] = - scy;\n }\n if (j+1 < info->my-1) {\n col[ncols].k = k; col[ncols].j = j+1; col[ncols].i = i;\n v[ncols++] = - scy;\n }\n if (k-1 > 0) {\n col[ncols].k = k-1; col[ncols].j = j; col[ncols].i = i;\n v[ncols++] = - scz;\n }\n if (k+1 < info->mz-1) {\n col[ncols].k = k+1; col[ncols].j = j; col[ncols].i = i;\n v[ncols++] = - scz;\n }\n }\n ierr = MatSetValuesStencil(Jpre,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);\n }\n }\n }\n ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != Jpre) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n\nPetscErrorCode InitialState(DM da, InitialType it, PetscBool gbdry,\n Vec u, PoissonCtx *user) {\n PetscErrorCode ierr;\n DMDALocalInfo info;\n PetscRandom rctx;\n switch (it) {\n case ZEROS:\n ierr = VecSet(u,0.0); CHKERRQ(ierr);\n break;\n case RANDOM:\n ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx); CHKERRQ(ierr);\n ierr = VecSetRandom(u,rctx); CHKERRQ(ierr);\n ierr = PetscRandomDestroy(&rctx); CHKERRQ(ierr);\n break;\n default:\n SETERRQ(PETSC_COMM_WORLD,4,\"invalid InitialType ... how did I get here?\\n\");\n }\n if (!gbdry) {\n return 0;\n }\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n switch (info.dim) {\n case 1:\n {\n int i;\n double xmax[1], xmin[1], h, x, *au;\n ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);\n ierr = DMDAGetBoundingBox(da,xmin,xmax); CHKERRQ(ierr);\n h = (xmax[0] - xmin[0]) / (info.mx - 1);\n for (i = info.xs; i < info.xs + info.xm; i++) {\n if (i==0 || i==info.mx-1) {\n x = xmin[0] + i * h;\n au[i] = user->g_bdry(x,0.0,0.0,user);\n }\n }\n ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);\n break;\n }\n case 2:\n {\n int i, j;\n double xymin[2], xymax[2], hx, hy, x, y, **au;\n ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);\n ierr = DMDAGetBoundingBox(da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info.mx - 1);\n hy = (xymax[1] - xymin[1]) / (info.my - 1);\n for (j = info.ys; j < info.ys + info.ym; j++) {\n y = xymin[1] + j * hy;\n for (i = info.xs; i < info.xs + info.xm; i++) {\n if (i==0 || i==info.mx-1 || j==0 || j==info.my-1) {\n x = xymin[0] + i * hx;\n au[j][i] = user->g_bdry(x,y,0.0,user);\n }\n }\n }\n ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);\n break;\n }\n case 3:\n {\n int i, j, k;\n double xyzmin[3], xyzmax[3], hx, hy, hz, x, y, z, ***au;\n ierr = DMDAVecGetArray(da, u, &au); CHKERRQ(ierr);\n ierr = DMDAGetBoundingBox(da,xyzmin,xyzmax); CHKERRQ(ierr);\n hx = (xyzmax[0] - xyzmin[0]) / (info.mx - 1);\n hy = (xyzmax[1] - xyzmin[1]) / (info.my - 1);\n hz = (xyzmax[2] - xyzmin[2]) / (info.mz - 1);\n for (k = info.zs; k < info.zs+info.zm; k++) {\n z = xyzmin[2] + k * hz;\n for (j = info.ys; j < info.ys + info.ym; j++) {\n y = xyzmin[1] + j * hy;\n for (i = info.xs; i < info.xs + info.xm; i++) {\n if (i==0 || i==info.mx-1 || j==0 || j==info.my-1\n || k==0 || k==info.mz-1) {\n x = xyzmin[0] + i * hx;\n au[k][j][i] = user->g_bdry(x,y,z,user);\n }\n }\n }\n }\n ierr = DMDAVecRestoreArray(da, u, &au); CHKERRQ(ierr);\n break;\n }\n default:\n SETERRQ(PETSC_COMM_WORLD,5,\"invalid dim from DMDALocalInfo\\n\");\n }\n return 0;\n}\n\n", "meta": {"hexsha": "e5bced073f16e701dffa5a42bbb10e9b938a4a3c", "size": 14629, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch6/poissonfunctions.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch6/poissonfunctions.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch6/poissonfunctions.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2084507042, "max_line_length": 97, "alphanum_fraction": 0.4136988174, "num_tokens": 4775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6698425716227511}} {"text": "\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef RANFUN_H\n#define RANFUN_H\n\n\n#define min(x,y) ((x) < (y) ? (x) : (y))\n#define max(x,y) ((x) > (y) ? (x) : (y))\n\ninline double sqr( double x) { return (x*x);}\n\n//interface for gsl_compare\n// x==y, 0, xy, 1.\nint fcmp (double x, double y, double epsilon = 0.00000000001); \n\n/*Interface with gsl*/\n\n/*Available random number generators from gsl \n gsl_rng_taus\n \n see http://sourceware.cygnus.com/gsl/ref/gsl-ref_5.html*/\n\n#define GENERATOR gsl_rng_taus\n\n/*to use inline functions in gsl (in c++)*/\n/*define DHAVE_INLINE at compile time*/\n#ifdef DHAVE_INLINE\n#define INLINE inline\n#endif\n\n#ifndef DHAVE_INLINE\n#define INLINE /*nothing*/\n#endif\n\n\nvoid Seed(unsigned long int s);\n\nunsigned long int GetSeed();\n\ndouble Un01(); /*Un01() */\n\ndouble Unab(double a, double b); /*U(a,b]*/\n\nunsigned int Un0n(int n); /*Uniform integer in { 0, 1, ..., n-1 }*/\n\nint Sign(); /*random -1 or 1*/\n\ndouble NorSim(double m, double sigma); /*Normal*/\n\ndouble ExpSim(double mu); /*p(x) dx = {1 \\over \\mu} \\exp(-x/\\mu) dx*/\n\ndouble GammaSim(double a, double b); /*Gamma: p(x) dx = K x^{a-1} e^{-x/b} dx*/\ndouble GammaDens(double x, double a, double b); /*density for beta, as above */\n\ndouble BetaSim(double a, double b); /*Beta: p(x) dx = K x^{a-1} (1-x)^{b-1} dx */\ndouble BetaDens(double x, double a, double b); /*density for beta, as above */\n\nunsigned int BiSim( double p, int n); /*Binomial: p^k (1-p)^{n-k} */\n\n/*Log of Special function Gamma*/\n\ndouble LogGamma(double x);\n\n#endif\n\n\n\n\n\n\n\n \n", "meta": {"hexsha": "6061b46baf8095f445b891a79a3aa4cdb0f3f471", "size": 1677, "ext": "h", "lang": "C", "max_stars_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_stars_repo_name": "SFlantua/Workshops", "max_stars_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-10-25T16:00:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T22:49:11.000Z", "max_issues_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_issues_repo_name": "SFlantua/Workshops", "max_issues_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-07-25T19:44:00.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-14T18:14:40.000Z", "max_forks_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_forks_repo_name": "SFlantua/Workshops", "max_forks_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-07T03:10:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T13:27:02.000Z", "avg_line_length": 20.4512195122, "max_line_length": 81, "alphanum_fraction": 0.6428145498, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6692982342386709}} {"text": "// lasp_math_raw.h\n//\n// Author: J.A. de Jong - ASCEE\n//\n// Description: Raw math routines working on raw arrays of floats and\n// complex numbers.\n//////////////////////////////////////////////////////////////////////\n#pragma once\n#ifndef LASP_MATH_RAW_H\n#define LASP_MATH_RAW_H\n#include \"lasp_assert.h\"\n#include \"lasp_tracer.h\"\n#include \"lasp_types.h\"\n#include \n#include \n\n#if LASP_USE_BLAS == 1\n#include \n#elif LASP_USE_BLAS == 0\n#else\n#error \"LASP_USE_BLAS should be set to either 0 or 1\"\n#endif\n\n#ifdef LASP_DOUBLE_PRECISION\n#define c_real creal\n#define c_imag cimag\n#define d_abs fabs\n#define c_abs cabs\n#define c_conj conj\n#define d_atan2 atan2\n#define d_acos acos\n#define d_sqrt sqrt\n#define c_exp cexp\n#define d_sin sin\n#define d_cos cos\n#define d_pow pow\n#define d_log10 log10\n#define d_ln log\n#define d_epsilon (DBL_EPSILON)\n\n#else // LASP_DOUBLE_PRECISION not defined\n#define c_conj conjf\n#define c_real crealf\n#define c_imag cimagf\n#define d_abs fabsf\n#define c_abs cabsf\n#define d_atan2 atan2f\n#define d_acos acosf\n#define d_sqrt sqrtf\n#define c_exp cexpf\n#define d_sin sinf\n#define d_cos cosf\n#define d_pow powf\n#define d_log10 log10f\n#define d_ln logf\n#define d_epsilon (FLT_EPSILON)\n#endif // LASP_DOUBLE_PRECISION\n\n/// Positive infinite\n#define d_inf (INFINITY)\n\n#ifdef M_PI\nstatic const d number_pi = M_PI;\n#else\nstatic const d number_pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679;\n#endif\n\n/** \n * Set all elements in an array equal to val\n *\n * @param to \n * @param val \n * @param size \n */\nstatic inline void d_set(d to[],d val,us size) {\n for(us i=0;ib?a:b;\n}\n\n\n/** \n * Return the dot product of two arrays, one of them complex-valued,\n * the other real-valued\n *\n * @param a the complex-valued array\n * @param b the real-valued array\n * @param size the size of the arrays. *Should be equal-sized!*\n *\n * @return the dot product\n */\nstatic inline c cd_dot(const c a[],const d b[],us size){\n c result = 0;\n us i;\n for(i=0;i max) max=a[i];\n }\n return max;\n}\n/** \n * Compute the minimum of an array\n *\n * @param a array\n * @param size size of the array\n * @return minimum\n */\nstatic inline d d_min(const d a[],us size){\n us i;\n d min = a[0];\n for(i=1;i min) min=a[i];\n }\n return min;\n}\n\n/** \n * Compute the \\f$ L_2 \\f$ norm of an array of doubles\n *\n * @param a Array\n * @param size Size of array\n */\nstatic inline d d_norm(const d a[],us size){\n #if LASP_USE_BLAS == 1\n return cblas_dnrm2(size,a,1);\n #else\t\n d norm = 0;\n us i;\n for(i=0;i\n#include \n#include \n#include \n#include \"scf.h\"\n\n/* Computing Phi_nl(r), which is the radial part of the basis functions\n *\n * The Gegenbauer polynomials for the host halo and subhalos can either be computed\n * using my own hard coded implementation (see gegenbauer.c) or GSL's implementation.\n *\n */\n\ndouble int_power(float x, int n)\n{\n return gsl_pow_int(x, n);\n}\n\n#ifdef USE_GSL_GEGENBAUER_HOST\nfloat Phi_nl(double Cna, int l, float r)\n{\n return -1.0f * int_power(r,l)/int_power(1.0f+r, 2.0*l+1) * (float)Cna * ROOT_FOUR_PI;\n}\n\nfloat dPhi_nl_dr(double Cna, float phinl, int n, int l, float r)\n{\n int two_l = 2*l;\n\tfloat r1 = r+1.f;\n\t\n\tfloat val = phinl * ( l/r - (two_l+1.0f)/r1 );\n\t\n\tif(n>0)\n\t{\n\t\tval -= ROOT_FOUR_PI * int_power(r,l)*4.0f*(two_l+1.5f) * (float)Cna / int_power(r1,two_l+3);\n\t}\n\t\n\treturn val;\n}\n\n#else\nfloat Phi_nl(int n, int l, float r)\n{\n float xi = (r-1.0f)/(r+1.0f);\n \n return -1.0f * int_power(r,l)/int_power(1.0f+r, 2.0*l+1) * Cna(n,2.0f*l+1.5f,xi) * ROOT_FOUR_PI;\n}\n\nfloat dPhi_nl_dr(float phinl, int n, int l, float r)\n{\n int two_l = 2*l;\n\tfloat r1 = r+1.f;\n\t\n\tfloat val = phinl * ( l/r - (two_l+1.0f)/r1 );\n\t\n\tif(n>0)\n\t{\n\t\tfloat xi = (r-1.f)/r1;\n\t\t\n\t\tval -= ROOT_FOUR_PI * int_power(r,l)*4.0f*(two_l+1.5f) * Cna(n-1,two_l+2.5f,xi) / int_power(r1,two_l+3);\n\t}\n\t\n\treturn val;\n}\n#endif\n\n\n#ifdef USE_GSL_GEGENBAUER_SUBHALO\nfloat Phi_n0(double Cna, float r) \n{\n return -1.0f / (1.0f+r) * (float)Cna * ROOT_FOUR_PI;\n}\n\nfloat dPhi_n0_dr(double Cna, float phin0, int n, float r)\n{\n float r1 = r+1.f;\n \n float val = phin0 * -1.f/r1;\n \n if(n>0)\n {\n val -= ROOT_FOUR_PI * 6.f/r1/r1/r1 * (float)Cna;\n }\n \n return val;\n}\n\n#else\nfloat Phi_n0(int n, float r)\n{\n float xi = (r-1.0f)/(r+1.0f);\n \n return -1.0f / (1.0f+r) * Cna(n,1.5f,xi) * ROOT_FOUR_PI;\n}\n\nfloat dPhi_n0_dr(float phin0, int n, float r)\n{\n float r1 = r+1.f;\n \n float val = phin0 * -1.f/r1;\n \n if(n>0)\n {\n\t\tfloat xi = (r-1.f)/r1;\n val -= ROOT_FOUR_PI * 6.f/r1/r1/r1 * Cna(n-1,2.5f,xi);\n }\n \n return val;\n}\n\n#endif\n\n\n", "meta": {"hexsha": "a87260f29715f593ce1bfdad14aec4a05eab988d", "size": 2145, "ext": "c", "lang": "C", "max_stars_repo_path": "Phi_nl.c", "max_stars_repo_name": "wayne927/vl2-scf", "max_stars_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-07T19:05:02.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-08T23:45:46.000Z", "max_issues_repo_path": "Phi_nl.c", "max_issues_repo_name": "wayne927/vl2-scf", "max_issues_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba", "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": "Phi_nl.c", "max_forks_repo_name": "wayne927/vl2-scf", "max_forks_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba", "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.982300885, "max_line_length": 106, "alphanum_fraction": 0.5962703963, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6685764581026971}} {"text": "static char help[] =\n\"Solves time-dependent heat equation in 2D using TS. Option prefix -ht_.\\n\"\n\"Equation is u_t = D_0 laplacian u + f. Domain is (0,1) x (0,1).\\n\"\n\"Boundary conditions are non-homogeneous Neumann in x and periodic in y.\\n\"\n\"Energy is conserved (for these particular conditions/source) and an extra\\n\"\n\"'monitor' is demonstrated. Discretization is by centered finite differences.\\n\"\n\"Converts the PDE into a system X_t = G(t,X) (PETSc type 'nonlinear') by\\n\"\n\"method of lines. Uses backward Euler time-stepping by default.\\n\";\n\n#include \n\ntypedef struct {\n double D0; // conductivity\n} HeatCtx;\n\nstatic double f_source(double x, double y) {\n return 3.0 * exp(-25.0 * (x-0.6) * (x-0.6)) * sin(2.0*PETSC_PI*y);\n}\n\nstatic double gamma_neumann(double y) {\n return sin(6.0 * PETSC_PI * y);\n}\n\nextern PetscErrorCode Spacings(DMDALocalInfo*, double*, double*);\nextern PetscErrorCode EnergyMonitor(TS, int, double, Vec, void*);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double, double**,\n double**, HeatCtx*);\nextern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, double, double**,\n Mat, Mat, HeatCtx*);\n\nint main(int argc,char **argv)\n{\n PetscErrorCode ierr;\n HeatCtx user;\n TS ts;\n Vec u;\n DM da;\n DMDALocalInfo info;\n double t0, tf;\n PetscBool monitorenergy = PETSC_FALSE;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n user.D0 = 1.0;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"ht_\", \"options for heat\", \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-D0\",\"constant thermal diffusivity\",\n \"heat.c\",user.D0,&user.D0,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-monitor\",\"also display total heat energy at each step\",\n \"heat.c\",monitorenergy,&monitorenergy,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n//STARTDMDASETUP\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_STAR,\n 5,4,PETSC_DECIDE,PETSC_DECIDE, // default to hx=hx=0.25 grid\n 1,1, // degrees of freedom, stencil width\n NULL,NULL,&da); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMCreateGlobalVector(da,&u); CHKERRQ(ierr);\n//ENDDMDASETUP\n\n//STARTTSSETUP\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 = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);\n ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,\n (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);\n ierr = DMDATSSetRHSJacobianLocal(da,\n (DMDATSRHSJacobianLocal)FormRHSJacobianLocal,&user); CHKERRQ(ierr);\n if (monitorenergy) {\n ierr = TSMonitorSet(ts,EnergyMonitor,&user,NULL); CHKERRQ(ierr);\n }\n ierr = TSSetType(ts,TSBDF); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,0.1); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,0.001); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n//ENDTSSETUP\n\n // report on set up\n ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);\n ierr = TSGetMaxTime(ts,&tf); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"solving on %d x %d grid for t0=%g to tf=%g ...\\n\",\n info.mx,info.my,t0,tf); CHKERRQ(ierr);\n\n // solve\n ierr = VecSet(u,0.0); CHKERRQ(ierr); // initial condition\n ierr = TSSolve(ts,u); CHKERRQ(ierr);\n\n VecDestroy(&u); TSDestroy(&ts); DMDestroy(&da);\n return PetscFinalize();\n}\n\nPetscErrorCode Spacings(DMDALocalInfo *info, double *hx, double *hy) {\n if (hx) *hx = 1.0 / (double)(info->mx-1);\n if (hy) *hy = 1.0 / (double)(info->my); // periodic direction\n return 0;\n}\n\n//STARTMONITOR\nPetscErrorCode EnergyMonitor(TS ts, int step, double time, Vec u,\n void *ctx) {\n PetscErrorCode ierr;\n HeatCtx *user = (HeatCtx*)ctx;\n double lenergy = 0.0, energy, dt, hx, hy, **au;\n int i,j;\n MPI_Comm com;\n DM da;\n DMDALocalInfo info;\n\n ierr = TSGetDM(ts,&da); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = DMDAVecGetArrayRead(da,u,&au); CHKERRQ(ierr);\n for (j = info.ys; j < info.ys + info.ym; j++) {\n for (i = info.xs; i < info.xs + info.xm; i++) {\n if ((i == 0) || (i == info.mx-1))\n lenergy += 0.5 * au[j][i];\n else\n lenergy += au[j][i];\n }\n }\n ierr = DMDAVecRestoreArrayRead(da,u,&au); CHKERRQ(ierr);\n ierr = Spacings(&info,&hx,&hy); CHKERRQ(ierr);\n lenergy *= hx * hy;\n ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lenergy,&energy,1,MPI_DOUBLE,MPI_SUM,com); CHKERRQ(ierr);\n ierr = TSGetTimeStep(ts,&dt); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" energy = %9.2e nu = %8.4f\\n\",\n energy,user->D0*dt/(hx*hy)); CHKERRQ(ierr);\n return 0;\n}\n//ENDMONITOR\n\n//STARTRHSFUNCTION\nPetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,\n double t, double **au,\n double **aG, HeatCtx *user) {\n PetscErrorCode ierr;\n int i, j, mx = info->mx;\n double hx, hy, x, y, ul, ur, uxx, uyy;\n\n ierr = Spacings(info,&hx,&hy); CHKERRQ(ierr);\n for (j = info->ys; j < info->ys + info->ym; j++) {\n y = hy * j;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = hx * i;\n // apply Neumann b.c.s\n ul = (i == 0) ? au[j][i+1] + 2.0 * hx * gamma_neumann(y)\n : au[j][i-1];\n ur = (i == mx-1) ? au[j][i-1] : au[j][i+1];\n uxx = (ul - 2.0 * au[j][i]+ ur) / (hx*hx);\n // DMDA is periodic in y\n uyy = (au[j-1][i] - 2.0 * au[j][i]+ au[j+1][i]) / (hy*hy);\n aG[j][i] = user->D0 * (uxx + uyy) + f_source(x,y);\n }\n }\n return 0;\n}\n//ENDRHSFUNCTION\n\n//STARTRHSJACOBIAN\nPetscErrorCode FormRHSJacobianLocal(DMDALocalInfo *info,\n double t, double **au,\n Mat J, Mat P, HeatCtx *user) {\n PetscErrorCode ierr;\n int i, j, ncols;\n const double D = user->D0;\n double hx, hy, hx2, hy2, v[5];\n MatStencil col[5],row;\n\n ierr = Spacings(info,&hx,&hy); CHKERRQ(ierr);\n hx2 = hx * hx; hy2 = hy * hy;\n for (j = info->ys; j < info->ys+info->ym; j++) {\n row.j = j; col[0].j = j;\n for (i = info->xs; i < info->xs+info->xm; i++) {\n // set up a standard 5-point stencil for the row\n row.i = i;\n col[0].i = i;\n v[0] = - 2.0 * D * (1.0 / hx2 + 1.0 / hy2);\n col[1].j = j-1; col[1].i = i; v[1] = D / hy2;\n col[2].j = j+1; col[2].i = i; v[2] = D / hy2;\n col[3].j = j; col[3].i = i-1; v[3] = D / hx2;\n col[4].j = j; col[4].i = i+1; v[4] = D / hx2;\n ncols = 5;\n // if at the boundary, edit the row back to 4 nonzeros\n if (i == 0) {\n ncols = 4;\n col[3].j = j; col[3].i = i+1; v[3] = 2.0 * D / hx2;\n } else if (i == info->mx-1) {\n ncols = 4;\n col[3].j = j; col[3].i = i-1; v[3] = 2.0 * D / hx2;\n }\n ierr = MatSetValuesStencil(P,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);\n }\n }\n\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n//ENDRHSJACOBIAN\n\n", "meta": {"hexsha": "1095be74593f73bbc3226a87568986df0d85f8b6", "size": 8058, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/heat.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch5/heat.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch5/heat.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0094339623, "max_line_length": 91, "alphanum_fraction": 0.5701166543, "num_tokens": 2586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6683254735252847}} {"text": "#pragma once\n\n#include \n#include \n\n#include \"General.h\"\n#include \"HyperionUtils/Concepts.h\"\n#include \"Random.h\"\n\nnamespace hyperion::math {\n\tusing gsl::narrow_cast;\n\tusing utils::concepts::SignedNumeric, utils::concepts::Integral,\n\t\tutils::concepts::SignedIntegral, utils::concepts::FloatingPoint;\n\n\tenum class Vec3Idx : size_t\n\t{\n\t\tX = 0ULL,\n\t\tY,\n\t\tZ\n\t};\n\n\ttemplate\n\tclass Vec3 {\n\t public:\n\t\t/// @brief Creates a default `Vec3`\n\t\tconstexpr Vec3() noexcept = default;\n\n\t\t/// @brief Creates a new `Vec3` with the given x, y, and z components\n\t\t///\n\t\t/// @param x - The x component\n\t\t/// @param y - The y component\n\t\t/// @param z - The z component\n\t\tconstexpr Vec3(T x, T y, T z) noexcept : elements{x, y, z} {\n\t\t}\n\t\tconstexpr Vec3(const Vec3& vec) noexcept = default;\n\t\tconstexpr Vec3(Vec3&& vec) noexcept = default;\n\t\tconstexpr ~Vec3() noexcept = default;\n\n\t\t/// @brief Returns the x component\n\t\t///\n\t\t/// @return a const ref to the x component\n\t\t[[nodiscard]] inline constexpr auto x() const noexcept -> const T& {\n\t\t\treturn elements[X];\n\t\t}\n\n\t\t/// @brief Returns the x component\n\t\t///\n\t\t/// @return a mutable (ie: non-const) ref to the x component\n\t\t[[nodiscard]] inline constexpr auto x() noexcept -> T& {\n\t\t\treturn elements[X];\n\t\t}\n\n\t\t/// @brief Returns the y component\n\t\t///\n\t\t/// @return a const ref to the y component\n\t\t[[nodiscard]] inline constexpr auto y() const noexcept -> const T& {\n\t\t\treturn elements[Y];\n\t\t}\n\n\t\t/// @brief Returns the y component\n\t\t///\n\t\t/// @return a mutable (ie: non-const) ref to the y component\n\t\t[[nodiscard]] inline constexpr auto y() noexcept -> T& {\n\t\t\treturn elements[Y];\n\t\t}\n\n\t\t/// @brief Returns the z component\n\t\t///\n\t\t/// @return a const ref to the z component\n\t\t[[nodiscard]] inline constexpr auto z() const noexcept -> const T& {\n\t\t\treturn elements[Z];\n\t\t}\n\n\t\t/// @brief Returns the z component\n\t\t///\n\t\t/// @return a mutable (ie: non-const) ref to the z component\n\t\t[[nodiscard]] inline constexpr auto z() noexcept -> T& {\n\t\t\treturn elements[Z];\n\t\t}\n\n\t\t/// @brief Returns the magnitude (length) of the vector\n\t\t///\n\t\t/// @return The magnitude\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto magnitude() const noexcept -> TT {\n\t\t\treturn General::sqrt(narrow_cast(magnitude_squared()));\n\t\t}\n\n\t\t/// @brief Returns the dot product of this and `vec`\n\t\t///\n\t\t/// @param vec - The vector to perform the dot product with\n\t\t///\n\t\t/// @return The dot product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto dot_prod(const Vec3& vec) const noexcept -> TT {\n\t\t\treturn narrow_cast(x()) * vec.x() + narrow_cast(y()) * vec.y()\n\t\t\t\t + narrow_cast(z()) * vec.z();\n\t\t}\n\n\t\t/// @brief Returns the dot product of this and `vec`\n\t\t///\n\t\t/// @param vec - The vector to perform the dot product with\n\t\t///\n\t\t/// @return The dot product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto dot_prod(const Vec3& vec) const noexcept -> T {\n\t\t\treturn x() * narrow_cast(vec.x()) + y() * narrow_cast(vec.y())\n\t\t\t\t + z() * narrow_cast(vec.z());\n\t\t}\n\n\t\t/// @brief Performs the cross product\n\t\t///\n\t\t/// @param vec The vector to perform the cross product with\n\t\t///\n\t\t/// @return The cross product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto\n\t\tcross_prod(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\tconst auto _x = narrow_cast(y()) * vec.z() - narrow_cast(z()) * vec.y();\n\t\t\tconst auto _y = narrow_cast(z()) * vec.x() - narrow_cast(x()) * vec.z();\n\t\t\tconst auto _z = narrow_cast(x()) * vec.y() - narrow_cast(y()) * vec.x();\n\t\t\treturn {_x, _y, _z};\n\t\t}\n\n\t\t/// @brief Performs the cross product\n\t\t///\n\t\t/// @param vec The vector to perform the cross product with\n\t\t///\n\t\t/// @return The cross product\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto cross_prod(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\tconst auto _x = y() * narrow_cast(vec.z()) - z() * narrow_cast(vec.y());\n\t\t\tconst auto _y = z() * narrow_cast(vec.x()) - x() * narrow_cast(vec.z());\n\t\t\tconst auto _z = x() * narrow_cast(vec.y()) - y() * narrow_cast(vec.x());\n\t\t\treturn {_x, _y, _z};\n\t\t}\n\n\t\t/// @brief Returns **a** vector normal to this one\n\t\t/// @note this is not necessarily the **only** vector normal to this one\n\t\t///\n\t\t/// @return a vector normal to this\n\t\t[[nodiscard]] inline constexpr auto normal() const noexcept -> Vec3 {\n\t\t\treturn cross_prod(\n\t\t\t\tVec3(narrow_cast(1.0), narrow_cast(0.0), narrow_cast(0.0)));\n\t\t}\n\n\t\t/// @brief Returns this vector with normalized magnitude\n\t\t///\n\t\t/// @return this vector, normalized\n\t\ttemplate\n\t\t[[nodiscard]] inline constexpr auto normalized() const noexcept -> Vec3 {\n\t\t\treturn std::move(*this / magnitude());\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random() noexcept -> Vec3 {\n\t\t\treturn {random_value(), random_value(), random_value()};\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random(TT min, TT max) noexcept -> Vec3 {\n\t\t\treturn {random_value(min, max),\n\t\t\t\t\trandom_value(min, max),\n\t\t\t\t\trandom_value(min, max)};\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random_in_unit_sphere() noexcept -> Vec3 {\n\t\t\tdo {\n\t\t\t\tauto val = random(narrow_cast(-1), narrow_cast(1));\n\t\t\t\tif(narrow_cast(val.magnitude_squared()) < narrow_cast(1)) {\n\t\t\t\t\treturn val;\n\t\t\t\t}\n\t\t\t} while(true);\n\t\t}\n\n\t\ttemplate\n\t\t[[nodiscard]] inline static constexpr auto random_in_unit_disk() noexcept -> Vec3 {\n\t\t\tdo {\n\t\t\t\tauto val = random(narrow_cast(-1), narrow_cast(1));\n\t\t\t\tval.z() = narrow_cast(0);\n\t\t\t\tif(narrow_cast(val.magnitude_squared()) < narrow_cast(1)) {\n\t\t\t\t\treturn val;\n\t\t\t\t}\n\t\t\t} while(true);\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto is_approx_zero() noexcept -> bool {\n\t\t\tconstexpr auto zero_tolerance = narrow_cast(0.0001);\n\t\t\treturn (General::abs(x()) < zero_tolerance) && (General::abs(y()) < zero_tolerance)\n\t\t\t\t && (General::abs(z()) < zero_tolerance);\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto\n\t\treflected(const Vec3& surface_normal) const noexcept -> Vec3 {\n\t\t\treturn std::move(\n\t\t\t\t*this - narrow_cast(2) * (this->dot_prod(surface_normal) * surface_normal));\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto\n\t\trefracted(const Vec3& surface_normal, T eta_external_over_eta_internal) noexcept -> Vec3 {\n\t\t\tconst auto uv = *this;\n\t\t\tconst auto cos_theta = General::min((-uv).dot_prod(surface_normal), narrow_cast(1));\n\n\t\t\tauto out_perpendicular\n\t\t\t\t= eta_external_over_eta_internal * (uv + cos_theta * surface_normal);\n\t\t\tauto out_parallel = -General::sqrt(General::abs(\n\t\t\t\t\t\t\t\t\tnarrow_cast(1) - out_perpendicular.magnitude_squared()))\n\t\t\t\t\t\t\t\t* surface_normal;\n\t\t\treturn out_perpendicular + out_parallel;\n\t\t}\n\n\t\tconstexpr auto operator=(const Vec3& vec) noexcept -> Vec3& = default;\n\t\tconstexpr auto operator=(Vec3&& vec) noexcept -> Vec3& = default;\n\n\t\ttemplate\n\t\tinline constexpr auto operator==(const Vec3& vec) const noexcept -> bool {\n\t\t\tconst auto xEqual\n\t\t\t\t= General::abs(narrow_cast(x()) - vec.x()) < narrow_cast(0.01);\n\t\t\tconst auto yEqual\n\t\t\t\t= General::abs(narrow_cast(y()) - vec.y()) < narrow_cast(0.01);\n\t\t\tconst auto zEqual\n\t\t\t\t= General::abs(narrow_cast(z()) - vec.z()) < narrow_cast(0.01);\n\t\t\treturn xEqual && yEqual && zEqual;\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator==(const Vec3& vec) const noexcept -> bool {\n\t\t\tif constexpr(FloatingPoint) {\n\t\t\t\tconst auto xEqual\n\t\t\t\t\t= General::abs(x() - narrow_cast(vec.x())) < narrow_cast(0.01);\n\t\t\t\tconst auto yEqual\n\t\t\t\t\t= General::abs(y() - narrow_cast(vec.y())) < narrow_cast(0.01);\n\t\t\t\tconst auto zEqual\n\t\t\t\t\t= General::abs(z() - narrow_cast(vec.z())) < narrow_cast(0.01);\n\t\t\t\treturn xEqual && yEqual && zEqual;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn x() == narrow_cast(vec.x()) && y() == narrow_cast(vec.y())\n\t\t\t\t\t && z() == narrow_cast(vec.z());\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator!=(const Vec3& vec) const noexcept -> bool {\n\t\t\treturn !(*this == vec);\n\t\t}\n\n\t\tinline constexpr auto operator-() const noexcept -> Vec3 {\n\t\t\treturn {-x(), -y(), -z()};\n\t\t}\n\n\t\tinline constexpr auto operator[](Vec3Idx i) const noexcept -> T {\n\t\t\tconst auto index = static_cast(i);\n\t\t\treturn elements[index]; // NOLINT\n\t\t}\n\t\tinline constexpr auto operator[](Vec3Idx i) noexcept -> T& {\n\t\t\tconst auto index = static_cast(i);\n\t\t\treturn elements[index]; // NOLINT\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\treturn {narrow_cast(x()) + vec.x(),\n\t\t\t\t\tnarrow_cast(y()) + vec.y(),\n\t\t\t\t\tnarrow_cast(z()) + vec.z()};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\treturn {x() + narrow_cast(vec.x()),\n\t\t\t\t\ty() + narrow_cast(vec.y()),\n\t\t\t\t\tz() + narrow_cast(vec.z())};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator+=(const Vec3& vec) noexcept -> Vec3 {\n\t\t\tx() += narrow_cast(vec.x());\n\t\t\ty() += narrow_cast(vec.y());\n\t\t\tz() += narrow_cast(vec.z());\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\treturn {narrow_cast(x()) - vec.x(),\n\t\t\t\t\tnarrow_cast(y()) - vec.y(),\n\t\t\t\t\tnarrow_cast(z()) - vec.z()};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-(const Vec3& vec) const noexcept -> Vec3 {\n\t\t\treturn {x() - narrow_cast(vec.x()),\n\t\t\t\t\ty() - narrow_cast(vec.y()),\n\t\t\t\t\tz() - narrow_cast(vec.z())};\n\t\t}\n\n\t\ttemplate\n\t\tinline constexpr auto operator-=(const Vec3& vec) noexcept -> Vec3& {\n\t\t\tx() -= narrow_cast(vec.x());\n\t\t\ty() -= narrow_cast(vec.y());\n\t\t\tz() -= narrow_cast(vec.z());\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator*(FloatingPoint auto s) const noexcept -> Vec3 {\n\t\t\tusing TT = decltype(s);\n\t\t\treturn {narrow_cast(x()) * s, narrow_cast(y()) * s, narrow_cast(z()) * s};\n\t\t}\n\n\t\tinline constexpr auto operator*(SignedIntegral auto s) const noexcept -> Vec3 {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\treturn {x() * scalar, y() * scalar, z() * scalar};\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator*(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3 {\n\t\t\treturn rhs * lhs;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator*(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 {\n\t\t\treturn rhs * lhs;\n\t\t}\n\n\t\tinline constexpr auto operator*=(FloatingPoint auto s) noexcept -> Vec3& {\n\t\t\tusing TT = decltype(s);\n\t\t\tx() = narrow_cast(narrow_cast(x()) * s);\n\t\t\ty() = narrow_cast(narrow_cast(y()) * s);\n\t\t\tz() = narrow_cast(narrow_cast(z()) * s);\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator*=(SignedIntegral auto s) noexcept -> Vec3& {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\tx() *= scalar;\n\t\t\ty() *= scalar;\n\t\t\tz() *= scalar;\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator/(FloatingPoint auto s) const noexcept -> Vec3 {\n\t\t\tusing TT = decltype(s);\n\t\t\treturn {narrow_cast(x()) / s, narrow_cast(y()) / s, narrow_cast(z()) / s};\n\t\t}\n\n\t\tinline constexpr auto operator/(SignedIntegral auto s) const noexcept -> Vec3 {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\treturn {x() / scalar, y() / scalar, z() / scalar};\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator/(FloatingPoint auto lhs, const Vec3& rhs) noexcept -> Vec3 {\n\t\t\treturn rhs / lhs;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator/(SignedIntegral auto lhs, const Vec3& rhs) noexcept -> Vec3 {\n\t\t\treturn rhs / lhs;\n\t\t}\n\n\t\tinline constexpr auto operator/=(FloatingPoint auto s) noexcept -> Vec3& {\n\t\t\tusing TT = decltype(s);\n\t\t\tx() = narrow_cast(narrow_cast(x()) / s);\n\t\t\ty() = narrow_cast(narrow_cast(y()) / s);\n\t\t\tz() = narrow_cast(narrow_cast(z()) / s);\n\t\t\treturn *this;\n\t\t}\n\n\t\tinline constexpr auto operator/=(SignedIntegral auto s) noexcept -> Vec3& {\n\t\t\tauto scalar = narrow_cast(s);\n\t\t\tx() /= scalar;\n\t\t\ty() /= scalar;\n\t\t\tz() /= scalar;\n\t\t\treturn *this;\n\t\t}\n\n\t\tfriend inline constexpr auto\n\t\toperator<<(std::ostream& out, const Vec3& vec) noexcept -> std::ostream& {\n\t\t\treturn out << vec.x() << ' ' << vec.y() << ' ' << vec.z();\n\t\t}\n\n\t private:\n\t\tstatic constexpr size_t NUM_ELEMENTS = static_cast(Vec3Idx::Z) + 1;\n\t\tT elements[NUM_ELEMENTS] // NOLINT\n\t\t\t= {narrow_cast(0), narrow_cast(0), narrow_cast(0)};\n\n\t\t/// @brief Calculates the magnitude squared of this vector\n\t\t///\n\t\t/// @return The magnitude squared\n\t\t[[nodiscard]] inline constexpr auto magnitude_squared() const noexcept -> T {\n\t\t\treturn x() * x() + y() * y() + z() * z();\n\t\t}\n\n\t\t/// Index for x component\n\t\tstatic constexpr size_t X = static_cast(Vec3Idx::X);\n\t\t/// Index for y component\n\t\tstatic constexpr size_t Y = static_cast(Vec3Idx::Y);\n\t\t/// Index for z component\n\t\tstatic constexpr size_t Z = static_cast(Vec3Idx::Z);\n\t};\n\n\t// Deduction Guides\n\n\ttemplate\n\texplicit Vec3(T, T, T) -> Vec3;\n\n\ttemplate\n\texplicit Vec3(T, T, T) -> Vec3;\n\n} // namespace hyperion::math\n", "meta": {"hexsha": "1ea115dfc03f339817f0a5a9a58fddca7d7632ab", "size": 13547, "ext": "h", "lang": "C", "max_stars_repo_path": "include/HyperionMath/Vec3.h", "max_stars_repo_name": "braxtons12/Hyperion-Math", "max_stars_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "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/HyperionMath/Vec3.h", "max_issues_repo_name": "braxtons12/Hyperion-Math", "max_issues_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "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/HyperionMath/Vec3.h", "max_forks_repo_name": "braxtons12/Hyperion-Math", "max_forks_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "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.8810679612, "max_line_length": 94, "alphanum_fraction": 0.6378533993, "num_tokens": 3910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6682165150827574}} {"text": "/*\n # Copyright (C) 2009-2013 Thierry Sousbie\n # University of Tokyo / CNRS, 2009\n #\n # This file is part of porject DisPerSE\n # \n # Author : Thierry Sousbie\n # Contact : tsousbie@gmail.com\t\n #\n # Licenses : This file is 'dual-licensed', you have to choose one\n # of the two licenses below to apply.\n #\n # CeCILL-C\n # The CeCILL-C license is close to the GNU LGPL.\n # ( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html )\n #\n # or CeCILL v2.0\n # The CeCILL license is compatible with the GNU GPL.\n # ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )\n #\n # This software is governed either by the CeCILL or the CeCILL-C license\n # under French law and abiding by the rules of distribution of free software.\n # You can use, modify and or redistribute the software under the terms of\n # the CeCILL or CeCILL-C licenses as circulated by CEA, CNRS and INRIA\n # at the following URL : \"http://www.cecill.info\".\n #\n # As a counterpart to the access to the source code and rights to copy,\n # modify and redistribute granted by the license, users are provided only\n # with a limited warranty and the software's author, the holder of the\n # economic rights, and the successive licensors have only limited\n # liability.\n #\n # In this respect, the user's attention is drawn to the risks associated\n # with loading, using, modifying and/or developing or reproducing the\n # software by the user in light of its specific status of free software,\n # that may mean that it is complicated to manipulate, and that also\n # therefore means that it is reserved for developers and experienced\n # professionals having in-depth computer knowledge. Users are therefore\n # encouraged to load and test the software's suitability as regards their\n # requirements in conditions enabling the security of their systems and/or\n # data to be ensured and, more generally, to use and operate it in the\n # same conditions as regards security.\n #\n # The fact that you are presently reading this means that you have had\n # knowledge of the CeCILL and CeCILL-C licenses and that you accept its terms.\n*/\n#include \n#include \n#include \n#include \"simplex.h\"\n\n#ifdef HAVE_GSL\n\n#include \n#include \n\ndouble SimplexVolumed(double **coord,int nvert, int ndims)\n{\n int i,j,k;\n double det;\n int s;\n double m_data[(nvert-1)*(nvert-1)];\n double w_data[(nvert-1)*(nvert-1)];\n/*\n double w_data[3*3] = {1.,0.,0.,\n\t\t\t 1.,1.,0.,\n\t\t\t 1.,1.,1.};*/\n //double wt_data[(nvert-1)*ndims];\n gsl_permutation * perm;\n \n gsl_matrix_view m = gsl_matrix_view_array (m_data, nvert-1, nvert-1); \n gsl_matrix_view w = gsl_matrix_view_array (w_data, nvert-1, ndims);\n //gsl_matrix_view wt = gsl_matrix_view_array (wt_data, nvert-1,ndims);\n\n if (nvert==2)\n {\n\tfor (i=0,det=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 2000\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 5000.0\t/* initial temperature */\n#define MU_T 1.002\t\t/* damping factor for temperature */\n#define T_MIN 5.0e-1\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\nstruct s_tsp_city {\n const char * name;\n double lat, longitude;\t/* coordinates */\n};\ntypedef struct s_tsp_city Stsp_city;\n\nvoid prepare_distance_matrix(void);\nvoid exhaustive_search(void);\nvoid print_distance_matrix(void);\ndouble city_distance(Stsp_city c1, Stsp_city c2);\ndouble Etsp(void *xp);\ndouble Mtsp(void *xp, void *yp);\nvoid Stsp(const gsl_rng * r, void *xp, double step_size);\nvoid Ptsp(void *xp);\n\n/* in this table, latitude and longitude are obtained from the US\n Census Bureau, at http://www.census.gov/cgi-bin/gazetteer */\n\nStsp_city cities[] = {{\"Santa Fe\", 35.68, 105.95},\n\t\t {\"Phoenix\", 33.54, 112.07},\n\t\t {\"Albuquerque\", 35.12, 106.62},\n\t\t {\"Clovis\", 34.41, 103.20},\n\t\t {\"Durango\", 37.29, 107.87},\n\t\t {\"Dallas\", 32.79, 96.77},\n\t\t {\"Tesuque\", 35.77, 105.92},\n\t\t {\"Grants\", 35.15, 107.84},\n\t\t {\"Los Alamos\", 35.89, 106.28},\n\t\t {\"Las Cruces\", 32.34, 106.76},\n\t\t {\"Cortez\", 37.35, 108.58},\n\t\t {\"Gallup\", 35.52, 108.74}};\n\n#define N_CITIES (sizeof(cities)/sizeof(Stsp_city))\n\ndouble distance_matrix[N_CITIES][N_CITIES];\n\n/* distance between two cities */\ndouble city_distance(Stsp_city c1, Stsp_city c2)\n{\n const double earth_radius = 6375.000;\t/* 6000KM approximately */\n /* sin and cos of lat and long; must convert to radians */\n double sla1 = sin(c1.lat*M_PI/180), cla1 = cos(c1.lat*M_PI/180),\n slo1 = sin(c1.longitude*M_PI/180), clo1 = cos(c1.longitude*M_PI/180);\n double sla2 = sin(c2.lat*M_PI/180), cla2 = cos(c2.lat*M_PI/180),\n slo2 = sin(c2.longitude*M_PI/180), clo2 = cos(c2.longitude*M_PI/180);\n\n double x1 = cla1*clo1;\n double x2 = cla2*clo2;\n\n double y1 = cla1*slo1;\n double y2 = cla2*slo2;\n\n double z1 = sla1;\n double z2 = sla2;\n\n double dot_product = x1*x2 + y1*y2 + z1*z2;\n\n double angle = acos(dot_product);\n\n /* distance is the angle (in radians) times the earth radius */\n return angle*earth_radius;\n}\n\n/* energy for the travelling salesman problem */\ndouble Etsp(void *xp)\n{\n /* an array of N_CITIES integers describing the order */\n int *route = (int *) xp;\n double E = 0;\n unsigned int i;\n\n for (i = 0; i < N_CITIES; ++i) {\n /* use the distance_matrix to optimize this calculation; it had\n better be allocated!! */\n E += distance_matrix[route[i]][route[(i + 1) % N_CITIES]];\n }\n\n return E;\n}\n\ndouble Mtsp(void *xp, void *yp)\n{\n int *route1 = (int *) xp, *route2 = (int *) yp;\n double distance = 0;\n unsigned int i;\n\n for (i = 0; i < N_CITIES; ++i) {\n distance += ((route1[i] == route2[i]) ? 0 : 1);\n }\n\n return distance;\n}\n\n/* take a step through the TSP space */\nvoid Stsp(const gsl_rng * r, void *xp, double step_size)\n{\n int x1, x2, dummy;\n int *route = (int *) xp;\n\n step_size = 0 ; /* prevent warnings about unused parameter */\n\n /* pick the two cities to swap in the matrix; we leave the first\n city fixed */\n x1 = (gsl_rng_get (r) % (N_CITIES-1)) + 1;\n do {\n x2 = (gsl_rng_get (r) % (N_CITIES-1)) + 1;\n } while (x2 == x1);\n\n dummy = route[x1];\n route[x1] = route[x2];\n route[x2] = dummy;\n}\n\nvoid Ptsp(void *xp)\n{\n unsigned int i;\n int *route = (int *) xp;\n printf(\" [\");\n for (i = 0; i < N_CITIES; ++i) {\n printf(\" %d \", route[i]);\n }\n printf(\"] \");\n}\n\nint main(void)\n{\n int x_initial[N_CITIES];\n unsigned int i;\n\n const gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ;\n\n gsl_ieee_env_setup ();\n\n prepare_distance_matrix();\n\n /* set up a trivial initial route */\n printf(\"# initial order of cities:\\n\");\n for (i = 0; i < N_CITIES; ++i) {\n printf(\"# \\\"%s\\\"\\n\", cities[i].name);\n x_initial[i] = i;\n }\n\n printf(\"# distance matrix is:\\n\");\n print_distance_matrix();\n\n printf(\"# initial coordinates of cities (longitude and latitude)\\n\");\n /* this can be plotted with */\n /* ./siman_tsp > hhh ; grep city_coord hhh | awk '{print $2 \" \" $3}' | xyplot -ps -d \"xy\" > c.eps */\n for (i = 0; i < N_CITIES+1; ++i) {\n printf(\"###initial_city_coord: %g %g \\\"%s\\\"\\n\",\n\t -cities[x_initial[i % N_CITIES]].longitude,\n\t cities[x_initial[i % N_CITIES]].lat,\n\t cities[x_initial[i % N_CITIES]].name);\n }\n\n/* exhaustive_search(); */\n\n gsl_siman_solve(r, x_initial, Etsp, Stsp, Mtsp, Ptsp, NULL, NULL, NULL,\n\t\t N_CITIES*sizeof(int), params);\n\n printf(\"# final order of cities:\\n\");\n for (i = 0; i < N_CITIES; ++i) {\n printf(\"# \\\"%s\\\"\\n\", cities[x_initial[i]].name);\n }\n\n printf(\"# final coordinates of cities (longitude and latitude)\\n\");\n /* this can be plotted with */\n /* ./siman_tsp > hhh ; grep city_coord hhh | awk '{print $2 \" \" $3}' | xyplot -ps -d \"xy\" > c.eps */\n for (i = 0; i < N_CITIES+1; ++i) {\n printf(\"###final_city_coord: %g %g %s\\n\",\n\t -cities[x_initial[i % N_CITIES]].longitude,\n\t cities[x_initial[i % N_CITIES]].lat,\n\t cities[x_initial[i % N_CITIES]].name);\n }\n\n printf(\"# \");\n fflush(stdout);\n#if 0\n system(\"date\");\n#endif /* 0 */\n fflush(stdout);\n\n return 0;\n}\n\nvoid prepare_distance_matrix()\n{\n unsigned int i, j;\n double dist;\n\n for (i = 0; i < N_CITIES; ++i) {\n for (j = 0; j < N_CITIES; ++j) {\n if (i == j) {\n\tdist = 0;\n } else {\n\tdist = city_distance(cities[i], cities[j]);\n }\n distance_matrix[i][j] = dist;\n }\n }\n}\n\nvoid print_distance_matrix()\n{\n unsigned int i, j;\n\n for (i = 0; i < N_CITIES; ++i) {\n printf(\"# \");\n for (j = 0; j < N_CITIES; ++j) {\n printf(\"%15.8f \", distance_matrix[i][j]);\n }\n printf(\"\\n\");\n }\n}\n\n/* [only works for 12] search the entire space for solutions */\nstatic double best_E = 1.0e100, second_E = 1.0e100, third_E = 1.0e100;\nstatic int best_route[N_CITIES];\nstatic int second_route[N_CITIES];\nstatic int third_route[N_CITIES];\nstatic void do_all_perms(int *route, int n);\n\nvoid exhaustive_search()\n{\n static int initial_route[N_CITIES] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};\n printf(\"\\n# \");\n fflush(stdout);\n#if 0\n system(\"date\");\n#endif\n fflush(stdout);\n do_all_perms(initial_route, 1);\n printf(\"\\n# \");\n fflush(stdout);\n#if 0\n system(\"date\");\n#endif /* 0 */\n fflush(stdout);\n\n printf(\"# exhaustive best route: \");\n Ptsp(best_route);\n printf(\"\\n# its energy is: %g\\n\", best_E);\n\n printf(\"# exhaustive second_best route: \");\n Ptsp(second_route);\n printf(\"\\n# its energy is: %g\\n\", second_E);\n\n printf(\"# exhaustive third_best route: \");\n Ptsp(third_route);\n printf(\"\\n# its energy is: %g\\n\", third_E);\n}\n\n/* James Theiler's recursive algorithm for generating all routes */\nstatic void do_all_perms(int *route, int n)\n{\n if (n == (N_CITIES-1)) {\n /* do it! calculate the energy/cost for that route */\n double E;\n E = Etsp(route);\t\t/* TSP energy function */\n /* now save the best 3 energies and routes */\n if (E < best_E) {\n third_E = second_E;\n memcpy(third_route, second_route, N_CITIES*sizeof(*route));\n second_E = best_E;\n memcpy(second_route, best_route, N_CITIES*sizeof(*route));\n best_E = E;\n memcpy(best_route, route, N_CITIES*sizeof(*route));\n } else if (E < second_E) {\n third_E = second_E;\n memcpy(third_route, second_route, N_CITIES*sizeof(*route));\n second_E = E;\n memcpy(second_route, route, N_CITIES*sizeof(*route));\n } else if (E < third_E) {\n third_E = E;\n memcpy(route, third_route, N_CITIES*sizeof(*route));\n }\n } else {\n int new_route[N_CITIES];\n unsigned int j;\n int swap_tmp;\n memcpy(new_route, route, N_CITIES*sizeof(*route));\n for (j = n; j < N_CITIES; ++j) {\n swap_tmp = new_route[j];\n new_route[j] = new_route[n];\n new_route[n] = swap_tmp;\n do_all_perms(new_route, n+1);\n }\n }\n}\n", "meta": {"hexsha": "5a44a8ed106d82ca7a39e509b7117d6447d8ea26", "size": 9148, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/siman/siman_tsp.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_tsp.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_tsp.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": 27.7212121212, "max_line_length": 104, "alphanum_fraction": 0.6251639703, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6674896709754043}} {"text": "#include \n#include \n#include \n\ndouble f (double x,void *params);\ndouble f (double x,void *params)\n{\n double n=* (double *) params;\n double f=exp (-x) * pow (x,n);\n return f;\n}\n\nvoid integral_gen (int nmin, int nmax, double vals[]);\nvoid integral_gen (int nmin, int nmax, double vals[])\n{\n\tdouble a=0.,b=1;\n double abserr=1.e-9,relerr=1.e-9;\n double result;\n double error;\n double n=10;\n size_t np=1000;\n\t gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);\n gsl_function F;\n F.function = &f;\n\n\tfor (int i=nmin;i<=nmax;i++)\n\t{\n \tF.params =&n;\n \tgsl_integration_qag (&F, a, b, abserr, relerr,np,GSL_INTEG_GAUSS15, w, &result, &error);\n\t\tvals[i]=result;\n\t}\n\tgsl_integration_workspace_free (w);\n}\n", "meta": {"hexsha": "a8d8c1c7455e45db9b4a5c6d64725d7689dab90f", "size": 852, "ext": "c", "lang": "C", "max_stars_repo_path": "int_gsl.c", "max_stars_repo_name": "jlichtman13/hw07", "max_stars_repo_head_hexsha": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1", "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": "int_gsl.c", "max_issues_repo_name": "jlichtman13/hw07", "max_issues_repo_head_hexsha": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1", "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": "int_gsl.c", "max_forks_repo_name": "jlichtman13/hw07", "max_forks_repo_head_hexsha": "2bb5b0948f221f9ebba7ef9c17978930ddf71ac1", "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.0588235294, "max_line_length": 97, "alphanum_fraction": 0.6021126761, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6670442843096144}} {"text": "#include \n#include \n#include \"compressibleFlow.h\"\n#include \"mesh.h\"\n#include \"petscdmplex.h\"\n#include \"petscts.h\"\n\ntypedef struct {\n PetscInt dim;\n PetscReal k;\n PetscReal gamma;\n PetscReal Rgas;\n PetscReal L;\n} Constants;\n\ntypedef struct {\n Constants constants;\n FlowData flowData;\n} ProblemSetup;\n\nstatic PetscReal ComputeTExact( PetscReal time, const PetscReal xyz[], Constants *constants, PetscReal rho){\n\n PetscReal cv = constants->gamma*constants->Rgas/(constants->gamma - 1) - constants->Rgas;\n\n PetscReal alpha = constants->k/(rho*cv);\n PetscReal Tinitial = 100.0;\n PetscReal T = 300.0;\n for(PetscReal n =1; n < 2000; n ++){\n PetscReal Bn = -Tinitial*2.0*(-1.0 + PetscPowReal(-1.0, n))/(n*PETSC_PI);\n T += Bn*PetscSinReal(n * PETSC_PI*xyz[0]/constants->L)*PetscExpReal(-n*n*PETSC_PI*PETSC_PI*alpha*time/(PetscSqr(constants->L)));\n }\n\n return T;\n}\n\nstatic PetscErrorCode InitialConditions(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *node, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n\n PetscReal T = ComputeTExact(time, xyz, constants, 1.0);\n\n PetscReal u = 0.0;\n PetscReal v = xyz[0];\n PetscReal rho = 1.0;\n PetscReal p= rho*constants->Rgas*T;\n PetscReal e = p/((constants->gamma - 1.0)*rho);\n PetscReal eT = e + 0.5*(u*u + v*v);\n\n node[RHO] = rho;\n node[RHOE] = rho*eT;\n node[RHOU + 0] = rho*u;\n node[RHOU + 1] = rho*v;\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscReal computeTemperature(PetscInt dim, const PetscScalar* conservedValues, PetscReal gamma, PetscReal Rgas){\n PetscReal density = conservedValues[RHO];\n PetscReal totalEnergy = conservedValues[RHOE]/density;\n\n // Get the velocity in this direction\n PetscReal speedSquare = 0.0;\n for (PetscInt d =0; d < dim; d++){\n speedSquare += PetscSqr(conservedValues[RHOU + d]/density);\n }\n\n // assumed eos\n PetscReal internalEnergy = (totalEnergy) - 0.5 * speedSquare;\n PetscReal p = (gamma - 1.0)*density*internalEnergy;\n\n PetscReal T = p/(Rgas*density);\n\n return T;\n}\n\nstatic PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n\n FlowData flowData = (FlowData)ctx;\n\n // Get the DM\n DM dm;\n ierr = TSGetDM(ts, &dm);\n CHKERRQ(ierr);\n\n ierr = FlowViewFromOptions(flowData, \"-sol_view\");\n CHKERRQ(ierr);\n\n ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), \"TS at %f\\n\", time);\n CHKERRQ(ierr);\n\n // Compute the error\n void *exactCtxs[1];\n PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n PetscDS ds;\n ierr = DMGetDS(dm, &ds);\n CHKERRQ(ierr);\n\n // Get the exact solution\n ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]);\n CHKERRQ(ierr);\n\n // Create an vector to hold the exact solution\n Vec exactVec;\n ierr = VecDuplicate(u, &exactVec);\n CHKERRQ(ierr);\n ierr = DMProjectFunction(dm, time, exactFuncs, exactCtxs, INSERT_ALL_VALUES, exactVec);\n CHKERRQ(ierr);\n\n ierr = PetscObjectSetName((PetscObject)exactVec, \"exact\");\n CHKERRQ(ierr);\n ierr = VecViewFromOptions(exactVec, NULL, \"-sol_view\");\n CHKERRQ(ierr);\n\n // For each component, compute the l2 norms\n ierr = VecAXPY(exactVec, -1.0, u);\n CHKERRQ(ierr);\n\n PetscReal ferrors[4];\n ierr = VecSetBlockSize(exactVec, 4);\n CHKERRQ(ierr);\n\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"Timestep: %04d time = %-8.4g \\t\\n\", (int)step, (double)time);\n CHKERRQ(ierr);\n ierr = VecStrideNormAll(exactVec, NORM_2, ferrors);\n CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double)(ferrors[0]), (double)(ferrors[1]), (double)(ferrors[2]), (double)(ferrors[3]));\n CHKERRQ(ierr);\n\n // And the infinity error\n ierr = VecStrideNormAll(exactVec, NORM_INFINITY, ferrors);\n CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double)ferrors[0], (double)ferrors[1], (double)ferrors[2], (double)ferrors[3]);\n CHKERRQ(ierr);\n\n ierr = PetscObjectSetName((PetscObject)exactVec, \"error\");\n CHKERRQ(ierr);\n ierr = VecViewFromOptions(exactVec, NULL, \"-sol_view\");\n CHKERRQ(ierr);\n\n ierr = VecDestroy(&exactVec);\n CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n//\n//static PetscErrorCode FillBoundary(PetscInt dim, PetscInt dof, const PetscFVFaceGeom *faceGeom, const PetscFVCellGeom *cellGeom, const PetscFVCellGeom *cellGeomG, const PetscScalar *a_xI, const PetscScalar *a_xGradI, const PetscScalar *a_xG, PetscScalar *a_xGradG, void *ctx){\n//\n// for(PetscInt pd = 0; pd < dof; ++pd) {\n// PetscReal dPhidS = a_xG[pd] - a_xI[pd];\n//\n// // over each direction\n// for (PetscInt dir = 0; dir < dim; dir++) {\n// PetscReal dx = (cellGeomG->centroid[dir] - faceGeom->centroid[dir]);\n//\n// // If there is a contribution in this direction\n// if (PetscAbs(dx) > 1E-8) {\n// a_xGradG[pd*dim + dir] = dPhidS / (dx);\n// } else {\n// a_xGradG[pd*dim + dir] = 0.0;\n// }\n// }\n// }\n// return 0;\n//}\n//\n///**\n// * this function updates the boundaries with the gradient computed from the boundary cell value\n// * @param dm\n// * @param auxFvm\n// * @param gradLocalVec\n// * @return\n// */\n//static PetscErrorCode DMPlexFillGradientInBoundaryFVM(DM dm, PetscFV auxFvm, Vec localXVec, Vec gradLocalVec){\n// PetscFunctionBeginUser;\n// PetscErrorCode ierr;\n//\n// // Get the dmGrad\n// DM dmGrad;\n// ierr = VecGetDM(gradLocalVec, &dmGrad);CHKERRQ(ierr);\n//\n// // get the problem\n// PetscDS prob;\n// PetscInt nFields;\n// ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);\n// ierr = PetscDSGetNumFields(prob, &nFields);CHKERRQ(ierr);\n// if (nFields > 1){\n// SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONG, \"Cannot fill DMPlexFillGradientInBoundaryFVM with more than a single field.\" );\n// }\n// PetscInt field;\n// ierr = PetscDSGetFieldIndex(prob, (PetscObject) auxFvm, &field);CHKERRQ(ierr);\n// PetscInt dof;\n// ierr = PetscDSGetFieldSize(prob, field, &dof);CHKERRQ(ierr);\n//\n// // Obtaining local cell ownership\n// PetscInt cellStart, cellEnd, cEndInterior;\n// ierr = DMPlexGetHeightStratum(dm, 0, &cellStart, &cellEnd);CHKERRQ(ierr);\n// ierr = DMPlexGetGhostCellStratum(dm, &cEndInterior, NULL);CHKERRQ(ierr);\n// cEndInterior = cEndInterior < 0 ? cellEnd: cEndInterior;\n//\n// // Get the fvm face and cell geometry\n// Vec cellGeomVec = NULL;/* vector of structs related to cell geometry*/\n// Vec faceGeomVec = NULL;/* vector of structs related to face geometry*/\n// ierr = DMPlexGetGeometryFVM(dm, &faceGeomVec, &cellGeomVec, NULL);CHKERRQ(ierr);\n//\n// // get the dm for each geom type\n// DM dmFaceGeom, dmCellGeom;\n// ierr = VecGetDM(faceGeomVec, &dmFaceGeom);CHKERRQ(ierr);\n// ierr = VecGetDM(cellGeomVec, &dmCellGeom);CHKERRQ(ierr);\n//\n// // extract the gradLocalVec\n// PetscScalar * gradLocalArray;\n// ierr = VecGetArray(gradLocalVec, &gradLocalArray);CHKERRQ(ierr);\n//\n// const PetscScalar* localArray;\n// ierr = VecGetArrayRead(localXVec, &localArray);CHKERRQ(ierr);\n//\n// // get the dim\n// PetscInt dim;\n// ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);\n//\n// // extract the arrays for the face and cell geom, along with their dm\n// const PetscScalar *cellGeomArray;\n// ierr = VecGetArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr);\n//\n// const PetscScalar *faceGeomArray;\n// ierr = VecGetArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr);\n//\n// // March over each face\n// for (PetscInt cell = cellStart; cell < cEndInterior; ++cell) {\n// // Get the face information\n// PetscInt numFaces;\n// const PetscInt *faces;\n// ierr = DMPlexGetConeSize(dm, cell, &numFaces);CHKERRQ(ierr);\n// ierr = DMPlexGetCone(dm, cell, &faces);CHKERRQ(ierr);\n//\n// //March over each face\n// for(PetscInt f =0 ; f < numFaces; f++){\n// PetscBool boundary;\n// ierr = DMIsBoundaryPoint(dm, faces[f], &boundary);CHKERRQ(ierr);\n//\n// // if this is on the boundary\n// if(boundary){\n// // get the boundary cell index\n// const PetscInt *fcells;\n// ierr = DMPlexGetSupport(dm, faces[f], &fcells);CHKERRQ(ierr);\n// PetscInt side = (cell != fcells[0]); /* c is on left=0 or right=1 of face */\n// PetscInt ncell = fcells[!side]; /* the neighbor */\n//\n// // get the face geom\n// const PetscFVFaceGeom *faceGeom;\n// ierr = DMPlexPointLocalRead(dmFaceGeom, faces[f], faceGeomArray, &faceGeom);CHKERRQ(ierr);\n//\n// // get the cell centroid information\n// const PetscFVCellGeom *cellGeom;\n// const PetscFVCellGeom *cellGeomGhost;\n// ierr = DMPlexPointLocalRead(dmCellGeom, cell, cellGeomArray, &cellGeom);CHKERRQ(ierr);\n// ierr = DMPlexPointLocalRead(dmCellGeom, ncell, cellGeomArray, &cellGeomGhost);CHKERRQ(ierr);\n//\n// // Read the local point\n// PetscScalar* boundaryGradCellValues;\n// ierr = DMPlexPointLocalRef(dmGrad, ncell, gradLocalArray, &boundaryGradCellValues);CHKERRQ(ierr);\n//\n// const PetscScalar* cellGradValues;\n// ierr = DMPlexPointLocalRead(dmGrad, cell, gradLocalArray, &cellGradValues);CHKERRQ(ierr);\n//\n// const PetscScalar* boundaryCellValues;\n// ierr = DMPlexPointLocalRead(dm, ncell, localArray, &boundaryCellValues);CHKERRQ(ierr);\n// const PetscScalar* cellValues;\n// ierr = DMPlexPointLocalRead(dm, cell, localArray, &cellValues);CHKERRQ(ierr);\n//\n// // compute the gradient for the boundary node and pass in\n// //const PetscReal *cellGeom, const PetscReal *cellGeomG, const PetscScalar *a_xI, const PetscScalar *a_xGradI, PetscScalar *a_xG, PetscScalar *a_xGradG, void *ctx\n// ierr = FillBoundary(dim, dof, faceGeom, cellGeom, cellGeomGhost, cellValues, cellGradValues, boundaryCellValues, boundaryGradCellValues, NULL);CHKERRQ(ierr);\n// }\n// }\n// }\n//\n// ierr = VecRestoreArrayRead(localXVec, &localArray);CHKERRQ(ierr);\n// ierr = VecRestoreArray(gradLocalVec, &gradLocalArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr);\n//\n// PetscFunctionReturn(0);\n//}\n//\n//static PetscErrorCode DiffusionSource(DM dm, PetscReal time, Vec locXVec, Vec globFVec, void *ctx){\n// // Call the flux calculation\n// PetscErrorCode ierr;\n//\n// ProblemSetup *setup = (ProblemSetup *)ctx;\n//\n// // call the base rhs function eval\n// ierr = DMPlexTSComputeRHSFunctionFVM(dm, time, locXVec, globFVec, setup->flowData);CHKERRQ(ierr);\n//\n// // update the aux fields\n// ierr = UpdateAuxFields(NULL, locXVec, setup->flowData);CHKERRQ(ierr);\n//\n// Constants constants = setup->constants;\n//\n// // get the fvm field assuming that it is the first\n// PetscFV auxFvm;\n// ierr = DMGetField(setup->flowData->auxDm,0, NULL, (PetscObject*)&auxFvm);CHKERRQ(ierr);\n//\n// PetscInt dim;\n// ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);\n//\n// // Get the locXArray\n// const PetscScalar *locXArray;\n// ierr = VecGetArrayRead(locXVec, &locXArray);CHKERRQ(ierr);\n//\n// // Get the fvm face and cell geometry\n// Vec cellGeomVec = NULL;/* vector of structs related to cell geometry*/\n// Vec faceGeomVec = NULL;/* vector of structs related to face geometry*/\n//\n// // extract the fvm data\n// ierr = DMPlexGetGeometryFVM(setup->flowData->dm, &faceGeomVec, &cellGeomVec, NULL);CHKERRQ(ierr);\n//\n// // Get the needed auxDm\n// DM auxFieldGradDM = NULL; /* dm holding the grad information */\n// ierr = DMPlexGetDataFVM(setup->flowData->auxDm, auxFvm, NULL, NULL, &auxFieldGradDM);CHKERRQ(ierr);\n// if(!auxFieldGradDM){\n// SETERRQ(PetscObjectComm((PetscObject)setup->flowData->auxDm), PETSC_ERR_ARG_WRONGSTATE, \"The FVM method for aux variables must support computing gradients.\");\n// }\n//\n// // get the dm for each geom type\n// DM dmFaceGeom, dmCellGeom;\n// ierr = VecGetDM(faceGeomVec, &dmFaceGeom);CHKERRQ(ierr);\n// ierr = VecGetDM(cellGeomVec, &dmCellGeom);CHKERRQ(ierr);\n//\n// // extract the arrays for the face and cell geom, along with their dm\n// const PetscScalar *faceGeomArray, *cellGeomArray;\n// ierr = VecGetArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr);\n// ierr = VecGetArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr);\n//\n// // Obtaining local cell and face ownership\n// PetscInt faceStart, faceEnd;\n// PetscInt cellStart, cellEnd;\n// ierr = DMPlexGetHeightStratum(dm, 1, &faceStart, &faceEnd);CHKERRQ(ierr);\n// ierr = DMPlexGetHeightStratum(dm, 0, &cellStart, &cellEnd);CHKERRQ(ierr);\n//\n// // get the ghost label\n// DMLabel ghostLabel;\n// ierr = DMGetLabel(dm, \"ghost\", &ghostLabel);CHKERRQ(ierr);\n//\n// // extract the localFArray from the locFVec\n// PetscScalar *fa;\n// Vec locFVec;\n// ierr = DMGetLocalVector(dm, &locFVec);CHKERRQ(ierr);\n// ierr = VecZeroEntries(locFVec);CHKERRQ(ierr);\n// ierr = VecGetArray(locFVec, &fa);CHKERRQ(ierr);\n//\n// // create a global and local grad vector for the auxField\n// Vec gradGlobalVec, gradLocalVec;\n// ierr = DMCreateGlobalVector(auxFieldGradDM, &gradGlobalVec);CHKERRQ(ierr);\n// ierr = VecSet(gradGlobalVec, NAN);CHKERRQ(ierr);\n//\n// // compute the global grad values\n// ierr = DMPlexReconstructGradientsFVM(setup->flowData->auxDm, setup->flowData->auxField, gradGlobalVec);CHKERRQ(ierr);\n//\n// // Map to a local grad vector\n// ierr = DMCreateLocalVector(auxFieldGradDM, &gradLocalVec);CHKERRQ(ierr);\n// ierr = DMGlobalToLocalBegin(auxFieldGradDM, gradGlobalVec, INSERT_VALUES, gradLocalVec);CHKERRQ(ierr);\n// ierr = DMGlobalToLocalEnd(auxFieldGradDM, gradGlobalVec, INSERT_VALUES, gradLocalVec);CHKERRQ(ierr);\n//\n// // fill the boundary conditions\n// ierr = DMPlexFillGradientInBoundaryFVM(setup->flowData->auxDm, auxFvm, setup->flowData->auxField, gradLocalVec);CHKERRQ(ierr);\n//\n// // access the local vector\n// const PetscScalar *localGradArray;\n// ierr = VecGetArrayRead(gradLocalVec,&localGradArray);CHKERRQ(ierr);\n//\n// // march over each face\n// for (PetscInt face = faceStart; face < faceEnd; ++face) {\n// PetscFVFaceGeom *fg;\n// PetscFVCellGeom *cgL, *cgR;\n// const PetscScalar *gradL;\n// const PetscScalar *gradR;\n//\n// // make sure that this is a valid face to check\n// PetscInt ghost, nsupp, nchild;\n// ierr = DMLabelGetValue(ghostLabel, face, &ghost);CHKERRQ(ierr);\n// ierr = DMPlexGetSupportSize(dm, face, &nsupp);CHKERRQ(ierr);\n// ierr = DMPlexGetTreeChildren(dm, face, &nchild, NULL);CHKERRQ(ierr);\n// if (ghost >= 0 || nsupp > 2 || nchild > 0){\n// continue;// skip this face\n// }\n//\n// // get the face geometry\n// ierr = DMPlexPointLocalRead(dmFaceGeom, face, faceGeomArray, &fg);CHKERRQ(ierr);\n//\n// // Get the left and right cells for this face\n// const PetscInt *faceCells;\n// ierr = DMPlexGetSupport(dm, face, &faceCells);CHKERRQ(ierr);\n//\n// // get the cell geom for the left and right faces\n// ierr = DMPlexPointLocalRead(dmCellGeom, faceCells[0], cellGeomArray, &cgL);CHKERRQ(ierr);\n// ierr = DMPlexPointLocalRead(dmCellGeom, faceCells[1], cellGeomArray, &cgR);CHKERRQ(ierr);\n//\n// // extract the cell grad\n// ierr = DMPlexPointLocalRead(auxFieldGradDM, faceCells[0], localGradArray, &gradL);CHKERRQ(ierr);\n// ierr = DMPlexPointLocalRead(auxFieldGradDM, faceCells[1], localGradArray, &gradR);CHKERRQ(ierr);\n//\n// PetscInt f = 0;\n//\n// // extract the field values\n// PetscScalar *xL, *xR,\n// ierr = DMPlexPointLocalFieldRead(dm, faceCells[0], f, locXArray, &xL);CHKERRQ(ierr);\n// ierr = DMPlexPointLocalFieldRead(dm, faceCells[1], f, locXArray, &xR);CHKERRQ(ierr);\n//\n// // Compute the normal grad\n// PetscReal normalGrad = 0.0;\n// PetscInt dof = 0;\n// for (PetscInt d = 0; d < dim; ++d){\n// normalGrad += fg->normal[d]*0.5*(gradL[dof*dim + d] + gradR[dof*dim + d]);\n// }\n//\n// // compute the normal heatFlux\n// PetscReal normalHeatFlux = -constants.k *normalGrad;\n//\n// // Add to the source terms of f\n// PetscScalar *fL = NULL, *fR = NULL;\n// ierr = DMLabelGetValue(ghostLabel,faceCells[0],&ghost);CHKERRQ(ierr);\n// if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, faceCells[0], f, fa, &fL);CHKERRQ(ierr);}\n// ierr = DMLabelGetValue(ghostLabel,faceCells[1],&ghost);CHKERRQ(ierr);\n// if (ghost <= 0) {ierr = DMPlexPointLocalFieldRef(dm, faceCells[1], f, fa, &fR);CHKERRQ(ierr);}\n//\n// if(fL){\n// fL[RHOE] -= normalHeatFlux/cgL->volume;\n// }\n// if(fR){\n// fR[RHOE] += normalHeatFlux/cgR->volume;\n// }\n// }\n//\n// // Add the new locFVec to the globFVec\n// ierr = VecRestoreArray(locFVec, &fa);CHKERRQ(ierr);\n// ierr = DMLocalToGlobalBegin(dm, locFVec, INSERT_VALUES, globFVec);CHKERRQ(ierr);\n// ierr = DMLocalToGlobalEnd(dm, locFVec, INSERT_VALUES, globFVec);CHKERRQ(ierr);\n// ierr = DMRestoreLocalVector(dm, &locFVec);CHKERRQ(ierr);\n//\n// // restore the arrays\n// ierr = VecRestoreArrayRead(gradLocalVec, &localGradArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(cellGeomVec, &cellGeomArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(faceGeomVec, &faceGeomArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(locXVec, &locXArray);CHKERRQ(ierr);\n//\n// // destroy grad vectors\n// ierr = VecDestroy(&gradGlobalVec);CHKERRQ(ierr);\n// ierr = VecDestroy(&gradLocalVec);CHKERRQ(ierr);\n//\n//// VecView(globFVec, PETSC_VIEWER_STDOUT_WORLD);\n//\n// PetscFunctionReturn(0);\n//}\n\nstatic PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) {\n PetscFunctionBeginUser;\n Constants *constants = (Constants *)ctx;\n\n // compute the centroid location of the real cell\n // Offset the calc assuming the cells are square\n PetscReal x[3];\n for(PetscInt i =0; i < constants->dim; i++){\n// x[i] = c[i] - n[i]*0.5;//TODO:zero boundary\n x[i] = c[i] + n[i]*0.5;//TODO:uniform grad\n }\n\n // compute the temperature\n PetscReal Tinside = ComputeTExact(time, x, constants, 1.0);\n PetscReal boundaryValue = 300.0;\n\n PetscReal T = boundaryValue;//boundaryValue - (Tinside - boundaryValue);//TODO: fix uniform grad\n\n// PetscReal T = c[0] < constants->L/2.0 ? 300 : 400;\n\n PetscReal u = 0.0;\n PetscReal v = 0.0;\n PetscReal rho = 1.0;\n PetscReal p= rho*constants->Rgas*T;\n PetscReal e = p/((constants->gamma - 1.0)*rho);\n PetscReal eT = e + 0.5*(u*u + v*v);\n\n a_xG[RHO] = rho;\n a_xG[RHOE] = rho*eT;\n a_xG[RHOU + 0] = rho*u;\n a_xG[RHOU + 1] = rho*v;\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PhysicsBoundary_Mirror(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) {\n PetscFunctionBeginUser;\n Constants *constants = (Constants *)ctx;\n\n // Offset the calc assuming the cells are square\n for(PetscInt f =0; f < RHOU + constants->dim; f++){\n a_xG[f] = a_xI[f];\n }\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv)\n{\n // Setup the problem\n Constants constants;\n\n // sub sonic\n constants.dim = 2;\n constants.L = 0.1;\n constants.gamma = 1.4;\n constants.k = 0.3;\n constants.Rgas = 1.0;\n\n PetscErrorCode ierr;\n // create the mesh\n // setup the ts\n DM dm; /* problem definition */\n TS ts; /* timestepper */\n\n // initialize petsc and mpi\n PetscInitialize(&argc, &argv, NULL, \"HELP\");\n\n // Create a ts\n ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);\n ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);\n ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr);\n\n // Create a mesh\n // hard code the problem setup\n PetscReal start[] = {0.0, 0.0};\n PetscReal end[] = {constants.L, constants.L};\n PetscReal nxHeight = 3;\n PetscInt nx[] = {nxHeight, nxHeight};\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr);\n\n // Setup the flow data\n FlowData flowData; /* store some of the flow data*/\n ierr = FlowCreate(&flowData);CHKERRQ(ierr);\n\n // Combine the flow data\n ProblemSetup problemSetup;\n problemSetup.flowData = flowData;\n problemSetup.constants = constants;\n\n //Setup\n CompressibleFlow_SetupDiscretization(flowData, &dm);\n\n // Add in the flow parameters\n PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS];\n params[CFL] = 0.5;\n params[GAMMA] = constants.gamma;\n params[RGAS] = constants.Rgas;\n params[K] = constants.k;\n\n // set up the finite volume fluxes\n CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params);\n\n // Add in any boundary conditions\n PetscDS prob;\n ierr = DMGetDS(flowData->dm, &prob);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n const PetscInt idsLeft[]= {2, 4};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"wall left\", \"Face Sets\", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 2, idsLeft, &constants);CHKERRQ(ierr);\n\n const PetscInt idsTop[]= {1, 3};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"top/bottom\", \"Face Sets\", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Mirror, NULL, 2, idsTop, &constants);CHKERRQ(ierr);\n\n// ierr = FlowRegisterAuxField(flowData, \"Temperature\", \"T\", 1, FV);CHKERRQ(ierr);\n\n // Complete the problem setup\n ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Override the flow calc for now\n// ierr = DMTSSetRHSFunctionLocal(flowData->dm, DiffusionSource, &problemSetup);CHKERRQ(ierr);\n\n // Name the flow field\n ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the TS\n ierr = TSSetFromOptions(ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSMonitorSet(ts, MonitorError, problemSetup.flowData, NULL);CHKERRQ(ierr);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // set the initial conditions\n PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {InitialConditions};\n void* ctxs[1] ={&constants};\n ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr);\n\n // for the mms, add the exact solution\n ierr = PetscDSSetExactSolution(prob, 0, InitialConditions, &constants);CHKERRQ(ierr);\n\n // Output the mesh\n ierr = DMViewFromOptions(flowData->dm, NULL, \"-dm_view\");CHKERRQ(ierr);\n\n // Compute the end time so it goes around once\n // compute dt\n PetscReal cv = constants.gamma*constants.Rgas/(constants.gamma - 1) - constants.Rgas;\n PetscReal dxMin = constants.L/(10 * PetscPowRealInt(2, 2));\n\n PetscReal alpha = PetscAbs(constants.k/ (cv * 1.0));\n double dt_conduc = 0.00000625;//.3*PetscSqr(dxMin) / alpha;\n\n PetscPrintf(PETSC_COMM_WORLD, \"dt_conduc: %f\\n\", dt_conduc);\n TSSetTimeStep(ts, dt_conduc);\n// TSSetMaxTime(ts, 0.001);\n TSSetMaxSteps(ts, 600);\n\n PetscDSView(prob, PETSC_VIEWER_STDOUT_WORLD);\n\n\n DMView(flowData->auxDm, PETSC_VIEWER_STDOUT_WORLD);\n\n ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr);\n\n FlowDestroy(&flowData);\n TSDestroy(&ts);\n\n return PetscFinalize();\n\n}", "meta": {"hexsha": "622891421214a8051c784f3d9435948dd66e152e", "size": 24500, "ext": "c", "lang": "C", "max_stars_repo_path": "eulerWithDiffusion.c", "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eulerWithDiffusion.c", "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eulerWithDiffusion.c", "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1373801917, "max_line_length": 279, "alphanum_fraction": 0.6495510204, "num_tokens": 7076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.666743040605425}} {"text": "/****************************************************************\n wigner_gsl.h / wigner_gsl_twice.h\n\n Defines Wigner coupling and recoupling symbols as wrappers for GSL\n angular momentum functions:\n\n - wigner_gsl.h -- takes HalfInt angular momentum arguments (RECOMMENDED)\n - wigner_gsl_twice.h -- takes integer \"twice value\" angular momentum arguments\n\n Naming convention: \n - Function names *not* ending in '2' accept HalfInt arguments J.\n - Function names ending in '2' accept integer arguments 2*J.\n\n See, e.g., appendix to de Shalit and Talmi for underlying formulas.\n\n DOCUMENTATION: See wigner_gsl.h (rather than wigner_gsl_twice.h) for\n more complete function comments.\n\n Language: C++\n\n Mark A. Caprio\n University of Notre Dame\n\n 2/16/10 (mac): Created.\n 11/13/15 (mac): Add unitary 6J for (12)3-(13)2 recoupling \n and Racah reduction factor.\n 2/27/16 (mac): Update includes for restructured header files.\n 3/8/16 (mac): Enclose in namespace.\n 6/8/16 (mac): Update #define guard directive.\n 6/21/16 (mac): Remove Racah reduction factor. Update comments.\n 10/18/16 (mac): Update Unitary6J comment. Rename wigner2_gsl.h to\n wigner_gsl_twice.h.\n 4/28/18 (mac): Restore missing Hat2 and ParitySign2 to\n wigner_gsl_twice.h.\n \n****************************************************************/\n\n#ifndef WIGNER_GSL_H_\n#define WIGNER_GSL_H_\n\n#include \n\n#include \"am.h\"\n\nnamespace am {\n\n // Wigner3J(ja,jb,jc,ma,mb,mc)\n // returns Wigner 3-J symbol\n // wrapper for gsl_sf_coupling_3j\n\n inline \n double Wigner3J(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& ma, const HalfInt& mb, const HalfInt& mc\n )\n {\n return gsl_sf_coupling_3j(\n TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), \n TwiceValue(ma), TwiceValue(mb), TwiceValue(mc)\n );\n }\n\n // ClebschGordan(ja,ma,jb,mb,jc,mc)\n // returns Clebsch-Gordan coefficient\n // wrapper for gsl_sf_coupling_3j\n\n inline \n double ClebschGordan(\n const HalfInt& ja, const HalfInt& ma, \n const HalfInt& jb, const HalfInt& mb, \n const HalfInt& jc, const HalfInt& mc\n )\n {\n return Hat(jc)*ParitySign(ja-jb+mc)\n *gsl_sf_coupling_3j(\n TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), \n TwiceValue(ma), TwiceValue(mb), -TwiceValue(mc)\n );\n }\n\n // Wigner6J(ja,jb,jc,jd,je,jf)\n // returns Wigner 6-J symbol\n // wrapper for gsl_sf_coupling_6j\n\n inline \n double Wigner6J(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& jd, const HalfInt& je, const HalfInt& jf\n )\n {\n return gsl_sf_coupling_6j(\n TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), \n TwiceValue(jd), TwiceValue(je), TwiceValue(jf)\n );\n }\n\n // Unitary6J(ja,jb,jc,jd,je,jf)\n // wrapper for gsl_sf_coupling_6j\n // returns unitary recoupling symbol for (12)3-1(23) recoupling\n //\n // Arguments follow row order in 6J symbol:\n // Unitary6J(J1,J2,J12,J3,J,J23)\n // This is equivalent to U(J1,J2,J,J3,J12,J23), though neither is a\n // particularly memorable ordering. Why not (J1,J2,J3,J12,J23,J)?!\n\n inline \n double Unitary6J(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& jd, const HalfInt& je, const HalfInt& jf\n )\n {\n return ParitySign(ja+jb+jd+je)*Hat(jc)*Hat(jf)\n *Wigner6J(ja,jb,jc,jd,je,jf);\n }\n\n // Unitary6JZ(ja,jb,jc,jd,je,jf)\n // wrapper for gsl_sf_coupling_6j\n // returns unitary recoupling symbol for (12)3-(13)2 recoupling\n // the name \"Z\" follows Millener for this purpose\n //\n // Arguments follow row order in 6J symbol:\n // Unitary6JZ(J1,J2,J12,J,J3,J13)\n // This is equivalent to Z(J2,J1,J,J3,J12,J13), though neither is a\n // particularly memorable ordering. Why not (J1,J2,J3,J12,J13,J)?!\n\n inline \n double Unitary6JZ(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& jd, const HalfInt& je, const HalfInt& jf\n )\n {\n return ParitySign(jb+je+jc+jf)*Hat(jc)*Hat(jf)\n *Wigner6J(ja,jb,jc,jd,je,jf);\n }\n\n // Wigner9J(ja,jb,jc,jd,je,jf,jg,jh,ji)\n // returns Wigner 9-J symbol\n // wrapper for gsl_sf_coupling_9j\n\n inline \n double Wigner9J(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& jd, const HalfInt& je, const HalfInt& jf,\n const HalfInt& jg, const HalfInt& jh, const HalfInt& ji\n )\n {\n return gsl_sf_coupling_9j(\n TwiceValue(ja), TwiceValue(jb), TwiceValue(jc), \n TwiceValue(jd), TwiceValue(je), TwiceValue(jf),\n TwiceValue(jg), TwiceValue(jh), TwiceValue(ji)\n );\n }\n\n // Unitary9J(ja,jb,jc,jd,je,jf,jg,jh,ji)\n // returns unitary 9-J symbol\n // wrapper for gsl_sf_coupling_9j\n\n inline \n double Unitary9J(\n const HalfInt& ja, const HalfInt& jb, const HalfInt& jc, \n const HalfInt& jd, const HalfInt& je, const HalfInt& jf,\n const HalfInt& jg, const HalfInt& jh, const HalfInt& ji\n )\n {\n return Hat(jc)*Hat(jf)*Hat(jg)*Hat(jh)\n *Wigner9J(\n ja, jb, jc, \n jd, je, jf,\n jg, jh, ji\n );\n }\n\n} // namespace\n\n#endif\n", "meta": {"hexsha": "4c2f4590186271ce57185b69c22658040bad55f4", "size": 5253, "ext": "h", "lang": "C", "max_stars_repo_path": "wigner_gsl.h", "max_stars_repo_name": "e-eight/am", "max_stars_repo_head_hexsha": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "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": "wigner_gsl.h", "max_issues_repo_name": "e-eight/am", "max_issues_repo_head_hexsha": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "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": "wigner_gsl.h", "max_forks_repo_name": "e-eight/am", "max_forks_repo_head_hexsha": "d9866d999d2ffb63935364b3efc6c395f2fff58f", "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.8465909091, "max_line_length": 82, "alphanum_fraction": 0.6299257567, "num_tokens": 1712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6665490559850492}} {"text": "#include \n#include \n#include \n\n#include \n#include \n\nint\nmain(void)\n{\n size_t i;\n const size_t N = 9;\n\n /* this dataset is taken from\n * J. M. Hyman, Accurate Monotonicity preserving cubic interpolation,\n * SIAM J. Sci. Stat. Comput. 4, 4, 1983. */\n const double x[] = { 7.99, 8.09, 8.19, 8.7, 9.2,\n 10.0, 12.0, 15.0, 20.0 };\n const double y[] = { 0.0, 2.76429e-5, 4.37498e-2,\n 0.169183, 0.469428, 0.943740,\n 0.998636, 0.999919, 0.999994 };\n\n gsl_interp_accel *acc = gsl_interp_accel_alloc();\n gsl_spline *spline_cubic = gsl_spline_alloc(gsl_interp_cspline, N);\n gsl_spline *spline_akima = gsl_spline_alloc(gsl_interp_akima, N);\n gsl_spline *spline_steffen = gsl_spline_alloc(gsl_interp_steffen, N);\n\n gsl_spline_init(spline_cubic, x, y, N);\n gsl_spline_init(spline_akima, x, y, N);\n gsl_spline_init(spline_steffen, x, y, N);\n\n for (i = 0; i < N; ++i)\n printf(\"%g %g\\n\", x[i], y[i]);\n\n printf(\"\\n\\n\");\n\n for (i = 0; i <= 100; ++i)\n {\n double xi = (1 - i / 100.0) * x[0] + (i / 100.0) * x[N-1];\n double yi_cubic = gsl_spline_eval(spline_cubic, xi, acc);\n double yi_akima = gsl_spline_eval(spline_akima, xi, acc);\n double yi_steffen = gsl_spline_eval(spline_steffen, xi, acc);\n\n printf(\"%g %g %g %g\\n\", xi, yi_cubic, yi_akima, yi_steffen);\n }\n\n gsl_spline_free(spline_cubic);\n gsl_spline_free(spline_akima);\n gsl_spline_free(spline_steffen);\n gsl_interp_accel_free(acc);\n\n return 0;\n}\n", "meta": {"hexsha": "2049df48ed454064e0e24d1db6f62e81c59098f6", "size": 1567, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/interp_compare.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/interp_compare.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/interp_compare.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 29.0185185185, "max_line_length": 71, "alphanum_fraction": 0.6266751755, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6665329748514357}} {"text": "//\n// her.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 12/23/11.\n// Copyright (c) 2011 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _her_h\n#define _her_h\n\n/// @file her.h Performs complex vector outer product.\n\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs a vector outer product of a complex vector with itself.\n /// \n /// For a complex Hermitian matrix A, complex vector x and real scalar alpha,\n ///\n /// A := alpha * x * x' + A\n ///\n /// is computed. The result is Hermitian and is stored as either upper or lower triangular in A.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param uplo Specifies whether A is stored as upper or lower triangular.\n ///\n /// if uplo = 'U' or 'u' then A is upper triangular\n /// if uplo = 'L' or 'l' then A is lower triangular\n ///\n /// @param n Specifies the order of the matrix A. n>=0\n /// @param alpha Real scalar.\n /// @param x Pointer to complex vector x.\n /// @param incx Increment of the vector x. x!=0\n /// @param A Pointer to complex Hermitian n-by-n matrix A. If uplo = 'U' or 'u' then only the upper\n /// triangular part of A is referenced and the lower part is not referenced. If uplo = 'L' or 'l' then\n /// only the lower triangular part of A is referenced and the upper part is not referenced.\n /// @param ldA Column length of matrix A. ldA>=n.\n /// @ingroup BLAS\n\n template \n int HER(char uplo, int_t n, real_t alpha, complex *x, int_t incx, complex *A, int_t ldA)\n {\n using std::conj;\n using std::real;\n using std::toupper;\n const real_t zero(0.0);\n complex t;\n int_t i,j,kx,jx,ix;\n\n uplo=toupper(uplo);\n\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(ldA0)?0:(1-n)*incx;\n if(uplo=='U')\n {\n jx=kx;\n for(j=0;j\n\n template <> int HER(char uplo, int_t n, float alpha, complex *x, int_t incx, complex *A, int_t ldA)\n {\n uplo=std::toupper(uplo);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(ldA int HER(char uplo, int_t n, double alpha, complex *x, int_t incx, complex *A, int_t ldA)\n {\n uplo=std::toupper(uplo);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if(n<0)\n return -2;\n else if(incx==0)\n return -5;\n else if(ldA\n#include \n#include \n#include \n#include \n\nstruct quadratic_params\n{\n double a, b, c;\n};\n\ndouble\nquadratic (double x, void *params)\n{\n struct quadratic_params *p\n = (struct quadratic_params *) params;\n\n double a = p->a;\n double b = p->b;\n double c = p->c;\n\n return (a * x + b) * x + c;\n}\n\ndouble\nquadratic_deriv (double x, void *params)\n{\n struct quadratic_params *p\n = (struct quadratic_params *) params;\n\n double a = p->a;\n double b = p->b;\n\n return 2.0 * a * x + b;\n}\n\nvoid\nquadratic_fdf (double x, void *params,\n double *y, double *dy)\n{\n struct quadratic_params *p\n = (struct quadratic_params *) params;\n\n double a = p->a;\n double b = p->b;\n double c = p->c;\n\n *y = (a * x + b) * x + c;\n *dy = 2.0 * a * x + b;\n}\n\nint\nmain (int argc, char *argv[])\n{\n int status;\n int iter = 0, max_iter = 100;\n const gsl_root_fdfsolver_type *T;\n gsl_root_fdfsolver *s;\n double x0, x = 5.0, r_expected = sqrt (5.0);\n gsl_function_fdf FDF;\n struct quadratic_params params = {1.0, -2.0, 1.0};\n\n FDF.f = &quadratic;\n FDF.df = &quadratic_deriv;\n FDF.fdf = &quadratic_fdf;\n FDF.params = ¶ms;\n\n if (argc < 2) {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n char *method = argv[1];\n if (0 == strcmp(\"newton\", method)) {\n T = gsl_root_fdfsolver_newton;\n } else if (0 == strcmp(\"secant\", method)) {\n T = gsl_root_fdfsolver_secant;\n } else if (0 == strcmp(\"steffenson\", method)) {\n T = gsl_root_fdfsolver_steffenson;\n } else {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n s = gsl_root_fdfsolver_alloc (T);\n gsl_root_fdfsolver_set (s, &FDF, x);\n\n printf (\"using %s method\\n\",\n gsl_root_fdfsolver_name (s));\n\n printf (\"%-5s %10s %10s %10s\\n\",\n \"iter\", \"root\", \"err\", \"err(est)\");\n do\n {\n iter++;\n status = gsl_root_fdfsolver_iterate (s);\n x0 = x;\n x = gsl_root_fdfsolver_root (s);\n status = gsl_root_test_delta (x, x0, 0, 1e-3);\n\n if (status == GSL_SUCCESS)\n printf (\"Converged:\\n\");\n\n printf (\"%5d %10.7f %+10.7f %10.7f\\n\",\n iter, x, x - r_expected, x - x0);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n gsl_root_fdfsolver_free (s);\n return status;\n}\n", "meta": {"hexsha": "6fea89f7cc914e33bf8156c9c4f99c3c29bfe9bc", "size": 2470, "ext": "c", "lang": "C", "max_stars_repo_path": "lab5/zad3.c", "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab5/zad3.c", "max_issues_repo_name": "mistyfiky/agh-mownit", "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab5/zad3.c", "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0535714286, "max_line_length": 54, "alphanum_fraction": 0.5489878543, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6662206572436746}} {"text": "#include \n#include \n#include \n\n#define NUM 5\n\nint main() {\n int i;\n double data[NUM];\n double mean, variance, largest, smallest;\n\n gsl_rng* r = gsl_rng_alloc(gsl_rng_default);\n for (i = 0; i < NUM; ++i) data[i] = gsl_rng_uniform(r);\n\n mean = gsl_stats_mean(data, 1, NUM);\n variance = gsl_stats_variance(data, 1, NUM);\n largest = gsl_stats_max(data, 1, NUM);\n smallest = gsl_stats_min(data, 1, NUM);\n\n printf(\"The data set is\");\n for (i = 0; i < NUM; ++i) printf(\" %6.3f\", data[i]);\n printf(\"\\n\");\n\n printf(\"Mean: %6.3f\\n\", mean);\n printf(\"Variance: %6.3f\\n\", variance);\n printf(\"Max value:%6.3f\\n\", largest);\n printf(\"Min value:%6.3f\\n\", smallest);\n\n return 0;\n}\n", "meta": {"hexsha": "6883e512eb2578235df87ad8e0a5a6c588287383", "size": 730, "ext": "c", "lang": "C", "max_stars_repo_path": "src_book0/ex10/list1032/list1032C.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/list1032/list1032C.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/list1032/list1032C.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": 23.5483870968, "max_line_length": 57, "alphanum_fraction": 0.6273972603, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6660756044604251}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble funcExp(double x, void *p)\n{\n (void)(p); //avoid unused parameter warning\n return exp(pow(x, 2));\n}\n\ndouble funcAbs(double x, void *p)\n{\n (void)(p); //avoid unused parameter warning\n return fabs(x + pow(x, 3));\n}\n\ndouble funcSign(double x, void *p)\n{\n (void)(p); //avoid unused parameter warning\n if (x == 0) return 0.0;\n else if (x < 0) return -1.0;\n\n return 1.0;\n}\n\nvoid calculateExp()\n{\n const int stepsCount = 1000;\n FILE* outputR1 = fopen(\"cheb_exp_r1.txt\", \"w\");\n FILE* outputR2 = fopen(\"cheb_exp_r2.txt\", \"w\");\n FILE* outputR4 = fopen(\"cheb_exp_r4.txt\", \"w\");\n FILE* outputR8 = fopen(\"cheb_exp_r8.txt\", \"w\");\n FILE* outputR16 = fopen(\"cheb_exp_r16.txt\", \"w\");\n FILE* outputR25 = fopen(\"cheb_exp_r25.txt\", \"w\");\n FILE* outputR40 = fopen(\"cheb_exp_r40.txt\", \"w\");\n\n gsl_cheb_series* cs = gsl_cheb_alloc(40);\n\n gsl_function function;\n\n function.function = funcExp;\n function.params = 0;\n\n gsl_cheb_init(cs, &function, -1.0, 1.0);\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double r1 = GSL_FN_EVAL(&function, x);\n double r2 = gsl_cheb_eval_n(cs, 2, x);\n double r4 = gsl_cheb_eval_n(cs, 4, x);\n double r8 = gsl_cheb_eval_n(cs, 8, x);\n double r16 = gsl_cheb_eval_n(cs, 16, x);\n double r25 = gsl_cheb_eval_n(cs, 25, x);\n double r40 = gsl_cheb_eval_n(cs, 40, x);\n\n fprintf (outputR1,\"%g %g\\n\", x, r1);\n fprintf (outputR2,\"%g %g\\n\", x, r2);\n fprintf (outputR4,\"%g %g\\n\", x, r4);\n fprintf (outputR8,\"%g %g\\n\", x, r8);\n fprintf (outputR16,\"%g %g\\n\", x, r16);\n fprintf (outputR25,\"%g %g\\n\", x, r25);\n fprintf (outputR40,\"%g %g\\n\", x, r40);\n }\n\n gsl_cheb_free(cs);\n}\n\n\nvoid calculateAbs()\n{\n const int stepsCount = 1000;\n FILE* outputR1 = fopen(\"cheb_abs_r1.txt\", \"w\");\n FILE* outputR2 = fopen(\"cheb_abs_r2.txt\", \"w\");\n FILE* outputR4 = fopen(\"cheb_abs_r4.txt\", \"w\");\n FILE* outputR8 = fopen(\"cheb_abs_r8.txt\", \"w\");\n FILE* outputR16 = fopen(\"cheb_abs_r16.txt\", \"w\");\n FILE* outputR25 = fopen(\"cheb_abs_r25.txt\", \"w\");\n FILE* outputR40 = fopen(\"cheb_abs_r40.txt\", \"w\");\n\n gsl_cheb_series* cs = gsl_cheb_alloc(40);\n\n gsl_function function;\n\n function.function = funcAbs;\n function.params = 0;\n\n gsl_cheb_init(cs, &function, -1.0, 1.0);\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double r1 = GSL_FN_EVAL(&function, x);\n double r2 = gsl_cheb_eval_n(cs, 2, x);\n double r4 = gsl_cheb_eval_n(cs, 4, x);\n double r8 = gsl_cheb_eval_n(cs, 8, x);\n double r16 = gsl_cheb_eval_n(cs, 16, x);\n double r25 = gsl_cheb_eval_n(cs, 25, x);\n double r40 = gsl_cheb_eval_n(cs, 40, x);\n\n fprintf (outputR1,\"%g %g\\n\", x, r1);\n fprintf (outputR2,\"%g %g\\n\", x, r2);\n fprintf (outputR4,\"%g %g\\n\", x, r4);\n fprintf (outputR8,\"%g %g\\n\", x, r8);\n fprintf (outputR16,\"%g %g\\n\", x, r16);\n fprintf (outputR25,\"%g %g\\n\", x, r25);\n fprintf (outputR40,\"%g %g\\n\", x, r40);\n }\n\n gsl_cheb_free(cs);\n}\n\nvoid calculateSign()\n{\n const int stepsCount = 1000;\n FILE* outputR1 = fopen(\"cheb_sign_r1.txt\", \"w\");\n FILE* outputR2 = fopen(\"cheb_sign_r2.txt\", \"w\");\n FILE* outputR4 = fopen(\"cheb_sign_r4.txt\", \"w\");\n FILE* outputR8 = fopen(\"cheb_sign_r8.txt\", \"w\");\n FILE* outputR16 = fopen(\"cheb_sign_r16.txt\", \"w\");\n FILE* outputR25 = fopen(\"cheb_sign_r25.txt\", \"w\");\n FILE* outputR40 = fopen(\"cheb_sign_r40.txt\", \"w\");\n\n gsl_cheb_series* cs = gsl_cheb_alloc(40);\n\n gsl_function function;\n\n function.function = funcSign;\n function.params = 0;\n\n gsl_cheb_init(cs, &function, -1.0, 1.0);\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double r1 = GSL_FN_EVAL(&function, x);\n double r2 = gsl_cheb_eval_n(cs, 2, x);\n double r4 = gsl_cheb_eval_n(cs, 4, x);\n double r8 = gsl_cheb_eval_n(cs, 8, x);\n double r16 = gsl_cheb_eval_n(cs, 16, x);\n double r25 = gsl_cheb_eval_n(cs, 25, x);\n double r40 = gsl_cheb_eval_n(cs, 40, x);\n\n fprintf (outputR1,\"%g %g\\n\", x, r1);\n fprintf (outputR2,\"%g %g\\n\", x, r2);\n fprintf (outputR4,\"%g %g\\n\", x, r4);\n fprintf (outputR8,\"%g %g\\n\", x, r8);\n fprintf (outputR16,\"%g %g\\n\", x, r16);\n fprintf (outputR25,\"%g %g\\n\", x, r25);\n fprintf (outputR40,\"%g %g\\n\", x, r40);\n }\n\n gsl_cheb_free(cs);\n}\n\nvoid fitLinear()\n{\n const int stepsCount = 1000;\n double xArray[stepsCount * 2];\n double yArray[stepsCount * 2];\n\n FILE* outputOriginal = fopen(\"linear_original.txt\", \"w\");\n FILE* outputFit = fopen(\"linear_fit.txt\", \"w\");\n FILE* outputCheb = fopen(\"linear_cheb.txt\", \"w\");\n\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double y = pow(0.5, pow(x, 2) + 2 * x);\n\n xArray[i + stepsCount] = x;\n yArray[i + stepsCount] = y;\n\n fprintf (outputOriginal,\"%g %g\\n\", x, y);\n }\n\n double c0 = 0;\n double c1 = 0;\n double cov00 = 0;\n double cov01 = 0;\n double cov11 = 0;\n double sumsq = 0;\n gsl_fit_linear(xArray, 1, yArray, 1, stepsCount * 2, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);\n\n//------\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double y = c0 + c1 * x;\n\n xArray[i + stepsCount] = x;\n yArray[i + stepsCount] = y;\n\n fprintf (outputFit,\"%g %g\\n\", x, y);\n }\n\n printf(\"c0: %f --- c1: %f\\n\", c0, c1);\n}\n\ndouble funcCheb(double x, void *p)\n{\n (void)(p); //avoid unused parameter warning\n return pow(0.5, pow(x, 2) + 2 * x);\n}\n\nvoid fitCheb()\n{\n const int stepsCount = 1000;\n FILE* outputR4 = fopen(\"cheb_fit_r4.txt\", \"w\");\n FILE* outputR40 = fopen(\"cheb_fit_r40.txt\", \"w\");\n\n gsl_cheb_series* cs = gsl_cheb_alloc(40);\n gsl_function function;\n function.function = funcCheb;\n function.params = 0;\n\n gsl_cheb_init(cs, &function, -1.0, 1.0);\n for (int i = -stepsCount; i <= stepsCount; i++)\n {\n double x = (double)i / (double)stepsCount;\n double r4 = gsl_cheb_eval_n(cs, 4, x);\n double r40 = gsl_cheb_eval_n(cs, 40, x);\n fprintf (outputR4,\"%g %g\\n\", x, r4);\n fprintf (outputR40,\"%g %g\\n\", x, r40);\n }\n gsl_cheb_free(cs);\n}\n\nint main (int argc, char* argv[])\n{\n calculateExp();\n calculateSign();\n calculateAbs();\n fitLinear();\n fitCheb();\n return 0;\n}\n\n/* \n\nplot \"cheb_exp_r1.txt\" with lines, \\\n \"cheb_exp_r2.txt\" with lines, \\\n \"cheb_exp_r4.txt\" with lines, \\\n \"cheb_exp_r8.txt\" with lines, \\\n \"cheb_exp_r16.txt\" with lines, \\\n \"cheb_exp_r25.txt\" with lines, \\\n \"cheb_exp_r40.txt\" with lines\n\nplot \"cheb_abs_r1.txt\" with lines, \\\n \"cheb_abs_r2.txt\" with lines, \\\n \"cheb_abs_r4.txt\" with lines, \\\n \"cheb_abs_r8.txt\" with lines, \\\n \"cheb_abs_r16.txt\" with lines, \\\n \"cheb_abs_r25.txt\" with lines, \\\n \"cheb_abs_r40.txt\" with lines\n\nplot \"cheb_sign_r1.txt\" with lines, \\\n \"cheb_sign_r2.txt\" with lines, \\\n \"cheb_sign_r4.txt\" with lines, \\\n \"cheb_sign_r8.txt\" with lines, \\\n \"cheb_sign_r16.txt\" with lines, \\\n \"cheb_sign_r25.txt\" with lines, \\\n \"cheb_sign_r40.txt\" with lines\n\n================\n\nplot \"linear_original.txt\" with lines title 'Original', \\\n \"linear_fit.txt\" with lines title 'Linear least sqr fit', \\\n \"cheb_fit_r4.txt\" with lines title 'Chebyshev approx R4'\n\n*/", "meta": {"hexsha": "5b7a811a2223040c2969c867ca47e79959901ed5", "size": 8137, "ext": "c", "lang": "C", "max_stars_repo_path": "zad3/aproksymacja.c", "max_stars_repo_name": "komilll/mownit_linux", "max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zad3/aproksymacja.c", "max_issues_repo_name": "komilll/mownit_linux", "max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zad3/aproksymacja.c", "max_forks_repo_name": "komilll/mownit_linux", "max_forks_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8546099291, "max_line_length": 99, "alphanum_fraction": 0.5929703822, "num_tokens": 2733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6657578527268655}} {"text": "#include \n#include \n#include \n// #include \"covar.h\"\n\nvoid print_mat(gsl_matrix* C)\n{\n int i, j;\n for (i = 0; i < C->size1; i++)\n {\n printf(\"\\n\");\n for (j = 0; j < C->size2; j++)\n {\n printf(\"%f\", C->data[C->size2*i+j]);\n if(j < C->size2 - 1) printf(\", \");\n }\n }\n printf(\"\\n\");\n}\n\n\nint main()\n{\n int i, j;\n\n/* \n Okay, here's what we want to do\n 1) Collect *all* the data - 10 seconds at standstill should be sufficient, with\n x, y, z, yaw, pitch, roll; for both pose and twist\n 2) twist gives us euler angles (yaw pitch roll), but pose gives us quaternions,\n so we'll need to convert\n 2) This leads to a 6 by N matrix of values\n 3) We propose a cov_gen() function\n input: 6 by N matrix of observation values\n output: 6 by 6 matrix of covariance values\n 4) We can put a ROS wrapper around this function as a service routine,\n i.e. the output of cov_gen() will serve as our estimate of\n the covariance matrix for loam_velodyne's odometry topic\n */\n\n // const int rsize = 5;\n // const int csize = 3;\n #define rsize 8\n #define csize 6\n\n double dataA[rsize][csize] = \n {{9, 6, 9, 3, 2, 1},\n {9, 9, 3, 4, 3, 5},\n {6, 6, 6, 6, 7, 3},\n {6, 6, 9, 4, 5, 1},\n {9, 9, 3, 4, 3, 5},\n {6, 6, 6, 6, 7, 3},\n {6, 6, 9, 4, 5, 1},\n {3, 3, 3, 6, 4, 1}};\n\n // double dataA[rsize][csize] = \n // {{90, 60, 90},\n // {90, 90, 30},\n // {60, 60, 60},\n // {60, 60, 90},\n // {30, 30, 30}};\n\n // double dataA[5][3] = {{ 24, 0, 30},\n // { 24, 30, -30},\n // { -6, 0, 0},\n // { -6, 0, 30},\n // {-36, -30, -30}};\n\n // double dataA[6][6] = {{1,1,1,1,1,1},\n // {2,2,2,2,2,2},\n // {3,3,3,3,3,3},\n // {4,4,4,4,4,4},\n // {5,5,5,5,5,5},\n // {6,6,6,6,6,6}};\n \n gsl_vector_view a, b;\n\n gsl_matrix *A, *C;\n A = gsl_matrix_alloc(rsize, csize);\n C = gsl_matrix_alloc(csize, csize);\n\n for ( i = 0; i < rsize; i++)\n for ( j = 0; j < csize; j++) \n gsl_matrix_set (A, i, j, dataA[i][j]);\n\n print_mat(A);\n\n for (i = 0; i < A->size2; i++) {\n for (j = 0; j < A->size2; j++) {\n a = gsl_matrix_column (A, i);\n b = gsl_matrix_column (A, j);\n double cov = gsl_stats_covariance(a.vector.data, \n a.vector.stride,\n b.vector.data, \n b.vector.stride, \n rsize);\n gsl_matrix_set (C, i, j, cov);\n }\n }\n\n print_mat(C);\n\n return 0;\n}\n\n\n", "meta": {"hexsha": "b23607fe109b9559f1e14a4a768517168f0d0530", "size": 3035, "ext": "c", "lang": "C", "max_stars_repo_path": "src/utility/covar/src/file.c", "max_stars_repo_name": "joeyzhu00/FusionAD", "max_stars_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2018-06-03T19:45:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T09:18:11.000Z", "max_issues_repo_path": "src/utility/covar/src/file.c", "max_issues_repo_name": "joeyzhu00/FusionAD", "max_issues_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T03:48:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-30T21:57:01.000Z", "max_forks_repo_path": "src/utility/covar/src/file.c", "max_forks_repo_name": "joeyzhu00/FusionAD", "max_forks_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T04:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T10:10:49.000Z", "avg_line_length": 28.3644859813, "max_line_length": 84, "alphanum_fraction": 0.4144975288, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6654887034602656}} {"text": "/*----------------------------------------------------------------------------*/\n/* */\n/* quad_golden.c */\n/* */\n/* Copyright (C) 2007 James Howse */\n/* Copyright (C) 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, */\n/* Boston, MA 02110-1301, USA. */\n/* */\n/* :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */\n/* */\n/* This algorithm performs univariate minimization (i.e., line search). */\n/* It requires only objective function values g(x) to compute the minimum. */\n/* The algorithm maintains an interval of uncertainty [a,b] and a point x */\n/* in the interval [a,b] such that a < x < b, and g(a) > g(x) and */\n/* g(x) < g(b). The algorithm also maintains the three points with the */\n/* smallest objective values x, v and w such that g(x) < g(v) < g(w). The */\n/* algorithm terminates when max( x - a, b - x ) < 2(r |x| + t) where r */\n/* and t are small positive reals. At a given iteration, the algorithm */\n/* first fits a quadratic through the three points (x, g(x)), (v, g(v)) */\n/* and (w, g(w)) and computes the location of the minimum u of the */\n/* resulting quadratic. If u is in the interval [a,b] then g(u) is */\n/* computed. If u is not in the interval [a,b], and either v < x and */\n/* w < x, or v > x and w > x (i.e., the quadratic is extrapolating), then */\n/* a point u' is computed using a safeguarding procedure and g(u') is */\n/* computed. If u is not in the interval [a,b], and the quadratic is not */\n/* extrapolating, then a point u'' is computed using approximate golden */\n/* section and g(u'') is computed. After evaluating g() at the */\n/* appropriate new point, a, b, x, v, and w are updated and the next */\n/* iteration is performed. The algorithm is based on work presented in */\n/* the following references. */\n/* */\n/* Algorithms for Minimization without derivatives */\n/* Richard Brent */\n/* Prentice-Hall Inc., Englewood Cliffs, NJ, 1973 */\n/* */\n/* Safeguarded Steplength Algorithms for Optimization using Descent Methods */\n/* Philip E. Gill and Walter Murray */\n/* Division of Numerical Analysis and Computing */\n/* National Physical Laboratory, Teddington, United Kingdom */\n/* NPL Report NAC 37, August 1974 */\n/* */\n/*----------------------------------------------------------------------------*/\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"min.h\"\n\n#define REL_ERR_VAL 1.0e-06\n#define ABS_ERR_VAL 1.0e-10\n#define GOLDEN_MEAN 0.3819660112501052\t/* (3 - sqrt(5))/2 */\n#define GOLDEN_RATIO 1.6180339887498950\t/* (1 + sqrt(5))/2 */\n\n#define DEBUG_PRINTF(x) /* do nothing */\n\ntypedef struct\n{\n double step_size, stored_step, prev_stored_step;\n double x_prev_small, f_prev_small, x_small, f_small;\n unsigned int num_iter;\n}\nquad_golden_state_t;\n\nstatic int\nquad_golden_init (void *vstate, gsl_function * f, double x_minimum,\n\t\t double f_minimum, double x_lower, double f_lower,\n\t\t double x_upper, double f_upper)\n{\n quad_golden_state_t *state = (quad_golden_state_t *) vstate;\n\n /* For the original behavior, the first value for x_minimum_minimum\n passed in by the user should be a golden section step but we\n don't enforce this here. */\n\n state->x_prev_small = x_minimum;\n state->x_small = x_minimum;\n\n state->f_prev_small = f_minimum;\n state->f_small = f_minimum;\n\n state->step_size = 0.0;\n state->stored_step = 0.0;\n state->prev_stored_step = 0.0;\n state->num_iter = 0;\n\n x_lower = 0 ; /* avoid warnings about unused variables */\n x_upper = 0 ;\n f_lower = 0 ;\n f_upper = 0 ;\n f = 0;\n\n return GSL_SUCCESS;\n}\n\nstatic int\nquad_golden_iterate (void *vstate, gsl_function * f, double *x_minimum,\n\t\t double *f_minimum, double *x_lower, double *f_lower,\n\t\t double *x_upper, double *f_upper)\n{\n quad_golden_state_t *state = (quad_golden_state_t *) vstate;\n\n const double x_m = *x_minimum;\n const double f_m = *f_minimum;\n\n const double x_l = *x_lower;\n const double x_u = *x_upper;\n\n const double x_small = state->x_small;\n const double f_small = state->f_small;\n\n const double x_prev_small = state->x_prev_small;\n const double f_prev_small = state->f_prev_small;\n \n double stored_step = state->stored_step; /* update on exit */\n double prev_stored_step = state->prev_stored_step; /* update on exit */\n double step_size = state->step_size; /* update on exit */\n\n double quad_step_size = prev_stored_step;\n \n double x_trial;\n double x_eval, f_eval;\n\n double x_midpoint = 0.5 * (x_l + x_u);\n double tol = REL_ERR_VAL * fabs (x_m) + ABS_ERR_VAL; /* total error tolerance */\n\n if (fabs (stored_step) - tol > -2.0 * GSL_DBL_EPSILON)\n {\n /* Fit quadratic */\n double c3 = (x_m - x_small) * (f_m - f_prev_small);\n double c2 = (x_m - x_prev_small) * (f_m - f_small);\n double c1 = (x_m - x_prev_small) * c2 - (x_m - x_small) * c3;\n\n c2 = 2.0 * (c2 - c3);\n\n if (fabs (c2) > GSL_DBL_EPSILON)\t/* if( c2 != 0 ) */\n\t{\n\t if (c2 > 0.0)\n\t c1 = -c1;\n\n\t c2 = fabs (c2);\n\n\t quad_step_size = c1 / c2;\n\t}\n else\n\t{\n\t /* Handle case where c2 ~=~ 0 */\n\t /* Insure that the line search will NOT take a quadratic\n\t interpolation step in this iteration */\n\t quad_step_size = stored_step;\n\t}\n\n prev_stored_step = stored_step;\n stored_step = step_size;\n }\n\n x_trial = x_m + quad_step_size;\n\n if (fabs (quad_step_size) < fabs (0.5 * prev_stored_step) && x_trial > x_l && x_trial < x_u)\n {\n /* Take quadratic interpolation step */\n step_size = quad_step_size;\n\n /* Do not evaluate function too close to x_l or x_u */\n if ((x_trial - x_l) < 2.0 * tol || (x_u - x_trial) < 2.0 * tol)\n {\n step_size = (x_midpoint >= x_m ? +1.0 : -1.0) * fabs(tol);\n }\n\n DEBUG_PRINTF((\"quadratic step: %g\\n\", step_size));\n }\n else if ((x_small != x_prev_small && x_small < x_m && x_prev_small < x_m) ||\n (x_small != x_prev_small && x_small > x_m && x_prev_small > x_m))\n {\n /* Take safeguarded function comparison step */\n double outside_interval, inside_interval;\n\n if (x_small < x_m)\n\t{\n\t outside_interval = x_l - x_m;\n\t inside_interval = x_u - x_m;\n\t}\n else\n\t{\n\t outside_interval = x_u - x_m;\n\t inside_interval = x_l - x_m;\n\t}\n\n if (fabs (inside_interval) <= tol)\n\t{\n /* Swap inside and outside intervals */\n double tmp = outside_interval;\n\t outside_interval = inside_interval;\n\t inside_interval = tmp;\n\t}\n\n {\n double step = inside_interval;\n double scale_factor;\n\n if (fabs (outside_interval) < fabs (inside_interval))\n {\n scale_factor = 0.5 * sqrt (-outside_interval / inside_interval);\n }\n else\n {\n scale_factor = (5.0 / 11.0) * (0.1 - inside_interval / outside_interval);\n }\n\n state->stored_step = step;\n step_size = scale_factor * step;\n }\n\n DEBUG_PRINTF((\"safeguard step: %g\\n\", step_size));\n }\n else\n {\n /* Take golden section step */\n double step;\n\n if (x_m < x_midpoint)\n {\n step = x_u - x_m;\n }\n else\n {\n step = x_l - x_m;\n }\n\n state->stored_step = step;\n step_size = GOLDEN_MEAN * step;\n\n DEBUG_PRINTF((\"golden step: %g\\n\", step_size));\n }\n\n /* Do not evaluate function too close to x_minimum */\n if (fabs (step_size) > tol)\n {\n x_eval = x_m + step_size;\n }\n else\n {\n x_eval = x_m + (step_size >= 0 ? +1.0 : -1.0) * fabs(tol);\n }\n\n /* Evaluate function at the new point x_eval */\n SAFE_FUNC_CALL(f, x_eval, &f_eval);\n\n /* Update {x,f}_lower, {x,f}_upper, {x,f}_prev_small, {x,f}_small, and {x,f}_minimum */\n if (f_eval <= f_m)\n {\n if (x_eval < x_m)\n\t{\n *x_upper = x_m;\n *f_upper = f_m;\n }\n else\n \t{\n *x_lower = x_m;\n *f_upper = f_m;\n }\n\n state->x_prev_small = x_small;\n state->f_prev_small = f_small;\n\n state->x_small = x_m;\n state->f_small = f_m;\n\n *x_minimum = x_eval;\n *f_minimum = f_eval;\n }\n else\n {\n if (x_eval < x_m)\n {\n *x_lower = x_eval;\n *f_lower = f_eval;\n }\n else\n { \n *x_upper = x_eval;\n *f_upper = f_eval;\n }\n\n if (f_eval <= f_small || fabs (x_small - x_m) < 2.0 * GSL_DBL_EPSILON)\n\t{\n\t state->x_prev_small = x_small;\n\t state->f_prev_small = f_small;\n\n\t state->x_small = x_eval;\n\t state->f_small = f_eval;\n\t}\n else if (f_eval <= f_prev_small ||\n\t fabs (x_prev_small - x_m) < 2.0 * GSL_DBL_EPSILON ||\n\t fabs (x_prev_small - x_small) < 2.0 * GSL_DBL_EPSILON)\n\t{\n\t state->x_prev_small = x_eval;\n\t state->f_prev_small = f_eval;\n\t}\n }\n\n /* Update stored values for next iteration */\n\n state->stored_step = stored_step;\n state->prev_stored_step = prev_stored_step;\n state->step_size = step_size;\n state->num_iter++;\n\n DEBUG_PRINTF((\"[%d] Final State: %g %g %g\\n\", state->num_iter, x_l, x_m, x_u));\n\n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_min_fminimizer_type quad_golden_type = { \"quad-golden\",\t/* name */\n sizeof (quad_golden_state_t),\n &quad_golden_init,\n &quad_golden_iterate\n};\n\nconst gsl_min_fminimizer_type *gsl_min_fminimizer_quad_golden =\n &quad_golden_type;\n", "meta": {"hexsha": "c078bd66e48110c4c5e9d1ad304c18ce7b58f7f6", "size": 11639, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/min/quad_golden.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/min/quad_golden.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/min/quad_golden.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 33.8343023256, "max_line_length": 94, "alphanum_fraction": 0.530114271, "num_tokens": 2915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6652405430698288}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nint\nmain(void)\n{\n const size_t N = 500; /* length of time series */\n const size_t K = 11; /* window size */\n gsl_movstat_workspace * w = gsl_movstat_alloc(K);\n gsl_vector *x = gsl_vector_alloc(N);\n gsl_vector *xmean = gsl_vector_alloc(N);\n gsl_vector *xmin = gsl_vector_alloc(N);\n gsl_vector *xmax = gsl_vector_alloc(N);\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n size_t i;\n\n for (i = 0; i < N; ++i)\n {\n double xi = cos(4.0 * M_PI * i / (double) N);\n double ei = gsl_ran_gaussian(r, 0.1);\n\n gsl_vector_set(x, i, xi + ei);\n }\n\n /* compute moving statistics */\n gsl_movstat_mean(GSL_MOVSTAT_END_PADVALUE, x, xmean, w);\n gsl_movstat_minmax(GSL_MOVSTAT_END_PADVALUE, x, xmin, xmax, w);\n\n /* print results */\n for (i = 0; i < N; ++i)\n {\n printf(\"%zu %f %f %f %f\\n\",\n i,\n gsl_vector_get(x, i),\n gsl_vector_get(xmean, i),\n gsl_vector_get(xmin, i),\n gsl_vector_get(xmax, i));\n }\n\n gsl_vector_free(x);\n gsl_vector_free(xmean);\n gsl_rng_free(r);\n gsl_movstat_free(w);\n\n return 0;\n}\n", "meta": {"hexsha": "2d119c2a18a9ca017db386071c8c6fae8d4e2489", "size": 1309, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/movstat1.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/doc/examples/movstat1.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/movstat1.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.6981132075, "max_line_length": 72, "alphanum_fraction": 0.5996944232, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6646868645273684}} {"text": "/* integration/qk15.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n\n/* Gauss quadrature weights and kronrod quadrature abscissae and\n weights as evaluated with 80 decimal digit arithmetic by\n L. W. Fullerton, Bell Labs, Nov. 1981. */\n\nstatic const double xgk[8] = /* abscissae of the 15-point kronrod rule */\n{\n 0.991455371120812639206854697526329,\n 0.949107912342758524526189684047851,\n 0.864864423359769072789712788640926,\n 0.741531185599394439863864773280788,\n 0.586087235467691130294144838258730,\n 0.405845151377397166906606412076961,\n 0.207784955007898467600689403773245,\n 0.000000000000000000000000000000000\n};\n\n/* xgk[1], xgk[3], ... abscissae of the 7-point gauss rule. \n xgk[0], xgk[2], ... abscissae to optimally extend the 7-point gauss rule */\n\nstatic const double wg[4] = /* weights of the 7-point gauss rule */\n{\n 0.129484966168869693270611432679082,\n 0.279705391489276667901467771423780,\n 0.381830050505118944950369775488975,\n 0.417959183673469387755102040816327\n};\n\nstatic const double wgk[8] = /* weights of the 15-point kronrod rule */\n{\n 0.022935322010529224963732008058970,\n 0.063092092629978553290700663189204,\n 0.104790010322250183839876322541518,\n 0.140653259715525918745189590510238,\n 0.169004726639267902826583426598550,\n 0.190350578064785409913256402421014,\n 0.204432940075298892414161999234649,\n 0.209482141084727828012999174891714\n};\n\nvoid\ngsl_integration_qk15 (const gsl_function * f, double a, double b,\n double *result, double *abserr,\n double *resabs, double *resasc)\n{\n double fv1[8], fv2[8];\n gsl_integration_qk (8, xgk, wg, wgk, fv1, fv2, f, a, b, result, abserr, resabs, resasc);\n}\n\n", "meta": {"hexsha": "bfba5176224528f656c7cff696542d24f38cec13", "size": 2472, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/qk15.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qk15.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/qk15.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": 34.8169014085, "max_line_length": 90, "alphanum_fraction": 0.7560679612, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6644040015957917}} {"text": "static char help[] =\n \"Newton's method for a two-variable system. Implements analytical Jacobian.\\n\"\n \"Adds struct to hold parameter.\\n\";\n\n#include \n\ntypedef struct {\n double b;\n} AppCtx;\n\nextern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);\nextern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void*);\n\n//STARTMAIN\nint main(int argc,char **argv) {\n SNES snes; // nonlinear solver context\n Vec x,r; // solution, residual vectors\n Mat J;\n AppCtx user;\n PetscErrorCode ierr;\n\n PetscInitialize(&argc,&argv,NULL,help);\n user.b = 2.0;\n\n ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);\n ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(x); CHKERRQ(ierr);\n ierr = VecDuplicate(x,&r); CHKERRQ(ierr);\n\n ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr);\n ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr);\n ierr = MatSetFromOptions(J); CHKERRQ(ierr);\n ierr = MatSetUp(J); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetFunction(snes,r,FormFunction,&user);CHKERRQ(ierr);\n ierr = SNESSetJacobian(snes,J,J,FormJacobian,&user);CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);\n\n ierr = VecSet(x,1.0);CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,x);CHKERRQ(ierr);\n ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes); MatDestroy(&J);\n return PetscFinalize();\n}\n//ENDMAIN\n\n//STARTFORM\nPetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {\n PetscErrorCode ierr;\n AppCtx *user = (AppCtx*)ctx;\n const double b = user->b, *ax;\n double *aF;\n\n ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecGetArray(F,&aF);CHKERRQ(ierr);\n aF[0] = (1.0 / b) * PetscExpReal(b * ax[0]) - ax[1];\n aF[1] = ax[0] * ax[0] + ax[1] * ax[1] - 1.0;\n ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr);\n ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FormJacobian(SNES snes, Vec x, Mat J, Mat P, void *ctx) {\n PetscErrorCode ierr;\n AppCtx *user = (AppCtx*)ctx;\n const double b = user->b, *ax;\n double v[4];\n int row[2] = {0,1}, col[2] = {0,1};\n\n ierr = VecGetArrayRead(x,&ax); CHKERRQ(ierr);\n v[0] = PetscExpReal(b * ax[0]); v[1] = -1.0;\n v[2] = 2.0 * ax[0]; v[3] = 2.0 * ax[1];\n ierr = VecRestoreArrayRead(x,&ax); CHKERRQ(ierr);\n ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n//ENDFORM\n\n", "meta": {"hexsha": "42854af8d91952e54e5e2c2a9e8836915d7062bb", "size": 2871, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch4/ecjac.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch4/ecjac.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch4/ecjac.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 82, "alphanum_fraction": 0.6475095785, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6644039897885613}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"linear_algebra.h\"\n\nMatrix *new_matrix(int row_num, int col_num)\n{\n Matrix *matrix = malloc(sizeof(Matrix));\n if (matrix == NULL) return NULL;\n matrix->data = malloc((unsigned long) (row_num * col_num) * sizeof(double));\n\n if (matrix->data == NULL)\n {\n perror(\"Error allocating memory for a matrix\");\n exit(EXIT_FAILURE);\n }\n\n matrix->row_num = row_num;\n matrix->col_num = col_num;\n\n return matrix;\n}\n\nMatrix *new_matrix_from_array(double *array, int row_num, int col_num)\n{\n Matrix *matrix = new_matrix(row_num, col_num);\n memcpy(matrix->data, array, (unsigned long)(row_num * col_num) * sizeof(double));\n return matrix;\n}\n\nvoid free_matrix(Matrix *matrix)\n{\n free(matrix->data);\n free(matrix);\n}\n\nMatrix *add_matrices(Matrix *matrix1, Matrix *matrix2)\n{\n if (matrix1->row_num != matrix2->row_num ||\n matrix1->col_num != matrix2->col_num)\n {\n perror(\"Dimensions of the two matrices do not match\");\n exit(EXIT_FAILURE);\n }\n\n Matrix *result_matrix = new_matrix(matrix1->row_num, matrix1->col_num);\n\n int i;\n int elements = matrix1->row_num * matrix1->col_num;\n\n for (i = 0; i < elements; i++)\n {\n result_matrix->data[i] = matrix1->data[i] + matrix2->data[i];\n }\n\n return result_matrix;\n}\n\n\nMatrix *multiply_matrices(Matrix *matrix1, Matrix *matrix2)\n{\n if (matrix1->col_num != matrix2->row_num)\n {\n perror(\"Incompatible matrix dimensions\");\n exit(EXIT_FAILURE);\n }\n\n Matrix *product = new_matrix(matrix1->row_num, matrix2->col_num);\n\n int m = matrix1->row_num;\n int n = matrix2->col_num;\n int k = matrix1->col_num;\n\n // Use high-performace matrix multiplication from BLAS\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1,\n matrix1->data, k, matrix2->data, n, 0, product->data, n);\n\n return product;\n}\n\nvoid multiply_vector_by_vector_transpose(Matrix *vector1, Matrix *vector2, double scalar, Matrix *matrix)\n{\n if (vector1->col_num != 1 || vector2->col_num != 1)\n {\n perror(\"Not a vector.\");\n exit(EXIT_FAILURE);\n }\n\n int m = vector1->row_num;\n int n = vector2->row_num;\n\n cblas_dger(CblasRowMajor, m, n, scalar, vector1->data, 1, vector2->data, 1, matrix->data, n);\n}\n\n\nMatrix *multiply_matrix_with_vector(Matrix *matrix, Matrix *vector, double scalar)\n{\n if (matrix->col_num != vector->row_num)\n {\n perror(\"Incompatible matrix dimensions\");\n exit(EXIT_FAILURE);\n }\n\n if (vector->col_num != 1)\n {\n perror(\"Not a vector.\");\n exit(EXIT_FAILURE);\n }\n\n Matrix *product = new_matrix(matrix->row_num, 1);\n\n int m = matrix->row_num;\n int n = matrix->col_num;\n\n cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, scalar, matrix->data, n,\n vector->data, 1, 0, product->data, 1);\n\n return product;\n}\n\n\nMatrix *multiply_upper_symmetric_matrix_with_vector(Matrix *matrix, Matrix *vector)\n{\n if (matrix->col_num != matrix->row_num)\n {\n perror(\"Matrix is not square\");\n exit(EXIT_FAILURE);\n }\n\n if (matrix->col_num != vector->row_num)\n {\n perror(\"Incompatible matrix dimensions\");\n exit(EXIT_FAILURE);\n }\n\n if (vector->col_num != 1)\n {\n perror(\"Not a vector.\");\n exit(EXIT_FAILURE);\n }\n\n Matrix *product = new_matrix(matrix->row_num, 1);\n\n int n = matrix->col_num;\n\n cblas_dsymv(CblasRowMajor, CblasUpper, n, 1, matrix->data,\n n, vector->data, 1, 0, product->data, 1);\n\n return product;\n}\n\n\nvoid multiply_matrix_with_a_number(Matrix *matrix, double number)\n{\n int i;\n int n = matrix->col_num;\n int row_num = matrix->row_num;\n\n for (i = 0; i < row_num; i++)\n {\n cblas_dscal(n, number, matrix->data + i * n, 1);\n }\n}\n\n\nMatrix *transpose_matrix(Matrix *matrix)\n{\n Matrix *product = new_matrix(matrix->col_num, matrix->row_num);\n\n int i, j;\n\n for (i = 0; i < matrix->col_num; i++)\n {\n for (j = 0; j < matrix->row_num; j++)\n {\n product->data[i * matrix->row_num + j] = matrix->data[j * matrix->col_num + i];\n }\n }\n\n return product;\n}\n\n\ndouble dot_product(Matrix *matrix1, Matrix *matrix2)\n{\n if (matrix1->row_num != matrix2->row_num ||\n matrix1->col_num != 1 || matrix2->col_num != 1)\n {\n perror(\"Matrices are not n by 1.\");\n exit(EXIT_FAILURE);\n }\n\n int i;\n double result = 0;\n\n for (i = 0; i < matrix1->row_num; i++)\n {\n result += matrix1->data[i] * matrix2->data[i];\n }\n\n return result;\n}\n\n\ndouble norm(Matrix *matrix)\n{\n return sqrt(dot_product(matrix, matrix));\n}\n\n\nMatrix *gramian(Matrix *matrix)\n{\n Matrix *product = new_matrix(matrix->col_num, matrix->col_num);\n\n int n = matrix->col_num;\n int k = matrix->row_num;\n\n cblas_dsyrk(CblasRowMajor, CblasUpper, CblasTrans,\n\t\t n, k, 1, matrix->data, n, 0, product->data, n);\n\n return product;\n}\n", "meta": {"hexsha": "df83902ae3bcf9350118f8af912bca78ecbd012c", "size": 5062, "ext": "c", "lang": "C", "max_stars_repo_path": "src/linear_algebra.c", "max_stars_repo_name": "evgenyneu/image_compressor_c", "max_stars_repo_head_hexsha": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-20T07:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-20T07:33:22.000Z", "max_issues_repo_path": "src/linear_algebra.c", "max_issues_repo_name": "evgenyneu/image_compressor_c", "max_issues_repo_head_hexsha": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "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/linear_algebra.c", "max_forks_repo_name": "evgenyneu/image_compressor_c", "max_forks_repo_head_hexsha": "6e270eca0921eaa7e505c15a2f84da31df750fdd", "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": 22.4977777778, "max_line_length": 105, "alphanum_fraction": 0.6141841169, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6642529118675492}} {"text": "/***************************************************************************************\n * Multivariate Normal density function and random number generator\n * Multivariate Student t density function and random number generator\n * Wishart random number generator\n * Using GSL -> www.gnu.org/software/gsl\n *\n * Copyright (C) 2006 Ralph dos Santos Silva\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * AUTHOR \n * Ralph dos Santos Silva, [EMAIL PROTECTED]\n * March, 2006 \n***************************************************************************************/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../hmm/adkGSL.h\"\n#include \"mvnorm_gsl.h\"\n/*****************************************************************************************************************/\n/*****************************************************************************************************************/\nint rmvnorm(const gsl_rng *r, const int n, const gsl_vector *mean, const gsl_matrix *var, gsl_vector *result){\n/* multivariate normal distribution random number generator */\n/*\n*\tn\tdimension of the random vetor\n*\tmean\tvector of means of size n\n*\tvar\tvariance matrix of dimension n x n\n*\tresult\toutput variable with a sigle random vector normal distribution generation\n*/\nint k;\ngsl_matrix *work = gsl_matrix_alloc(n,n);\n\ngsl_matrix_memcpy(work,var);\ngsl_linalg_cholesky_decomp(work);\n\nfor(k=0; ksize1; k++){\n\tgsl_matrix_set( work, k, k, sqrt( gsl_ran_chisq( r, (dof-k) ) ) );\n\tfor(l=0; lsize1;\t\n\tdenom = 1.0;\n\tdenom *= pow(2,(d*dof/2.0)) * mv_gamma_func(dof/2.0, d);\n\t\n\t//multiply x by inverse of sigma and take trace\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans,1.0, sigma, winv,0.0, work);\n\ttrace = gsl_matrix_trace(work);\n\tnum = pow(detSig, dof / 2.0) * pow(detX , (-dof-d-1)/ 2.0) * exp(-0.5 * trace);\n\treturn(num/denom);\n}\n\n/*****************************************************************************************************************/\n//rwishartGelman-- uses alg described in Gelman et al appendix\nvoid rwishartGelman(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, \n\tgsl_matrix *work,gsl_matrix *work2, gsl_vector *mean,gsl_vector *xm, gsl_matrix *output){\n/* Wishart distribution random number generator */\n/*\n*\tn\t gives the dimension of the random matrix\n*\tdof\t degrees of freedom\n*\tscale\t scale matrix of dimension n x n\n*\tresult\t output variable with a single random matrix Wishart distribution generation\n*/\n\tint i;\n\n\tgsl_vector_set_all(mean,0.0);\n\tgsl_matrix_set_all(output,0.0);\n\tfor(i = 0; i < dof; i++){\n\t\tgsl_vector_set_all(xm,0);\n\t\trmvnorm_prealloc(r, n, mean, scale, work, xm);\n\t\tgsl_vector_outer_product(xm,xm,work2);\n\t\tgsl_matrix_add(output,work2);\n\t}\n}\n\n//rwishartOdellFeiveson-- uses alg of Odell and Feiveson\nvoid rwishartOdellFeiveson(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, \n\tgsl_matrix *work,gsl_matrix *work2, gsl_vector *mean,gsl_vector *xm, gsl_matrix *output){\n/* Wishart distribution random number generator */\n/*\n*\tn\t gives the dimension of the random matrix\n*\tdof\t degrees of freedom\n*\tscale\t scale matrix of dimension n x n\n*\tresult\t output variable with a single random matrix Wishart distribution generation\n*/\n\tint i,j, k;\n\tdouble sum, tmp;\n\n\tgsl_vector_set_all(mean,0.0);\n\tgsl_matrix_set_all(output,0.0);\n\n\tfor(j=0;j\n#include \n#include \n\n\n// author: Andrew Liew \n// copyright: Copyright 2018, BLOCK Research Group - ETH Zurich\n// license: MIT License\n// email: liew@arch.ethz.ch\n\n\nint i;\nint j;\n\n\n// ==========================================================================================================\n// One vector\n// ==========================================================================================================\n\n\ndouble length_vector(gsl_vector *u)\n{\n double L = gsl_blas_dnrm2(u);\n\n return L;\n}\n\n\ndouble length_vector_squared(gsl_vector *u)\n{\n double a = 0.;\n\n for (i = 0; i < 3; i++)\n {\n a += gsl_pow_2(gsl_vector_get(u, i));\n }\n\n return a;\n}\n\n\nvoid normalize_vector(gsl_vector *u)\n{\n gsl_vector_scale(u, 1./length_vector(u));\n}\n\n\nvoid scale_vector(gsl_vector *u, double a)\n{\n gsl_vector_scale(u, a);\n}\n\n\nvoid vector_from_pointer(double *ptr, gsl_vector *w)\n{\n gsl_vector_set(w, 0, *(ptr + 0));\n gsl_vector_set(w, 1, *(ptr + 1));\n gsl_vector_set(w, 2, *(ptr + 2));\n}\n\n\n// ==========================================================================================================\n// Two vectors\n// ==========================================================================================================\n\nvoid add_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w)\n{\n gsl_vector_memcpy(w, u);\n gsl_vector_add(w, v);\n}\n\n\nvoid cross_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w)\n{\n double w1 = gsl_vector_get(u, 1) * gsl_vector_get(v, 2) - gsl_vector_get(u, 2) * gsl_vector_get(v, 1);\n double w2 = gsl_vector_get(u, 2) * gsl_vector_get(v, 0) - gsl_vector_get(u, 0) * gsl_vector_get(v, 2);\n double w3 = gsl_vector_get(u, 0) * gsl_vector_get(v, 1) - gsl_vector_get(u, 1) * gsl_vector_get(v, 0);\n\n gsl_vector_set(w, 0, w1);\n gsl_vector_set(w, 1, w2);\n gsl_vector_set(w, 2, w3);\n}\n\n\ndouble dot_vectors(const gsl_vector *u, const gsl_vector *v)\n{\n double a = 0.;\n\n for (i = 0; i < 3; i++)\n {\n a += gsl_vector_get(u, i) * gsl_vector_get(v, i);\n }\n\n return a;\n}\n\n\nvoid subtract_vectors(const gsl_vector *u, const gsl_vector *v, gsl_vector *w)\n{\n gsl_vector_memcpy(w, u);\n gsl_vector_sub(w, v);\n}\n", "meta": {"hexsha": "cd7fd34e0f9d86458b3bca6f8432afb9c4aaf032", "size": 2309, "ext": "h", "lang": "C", "max_stars_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_stars_repo_name": "philianeles/compas", "max_stars_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_issues_repo_name": "philianeles/compas", "max_issues_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compas_hpc/geometry/basic_c.h", "max_forks_repo_name": "philianeles/compas", "max_forks_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2019230769, "max_line_length": 109, "alphanum_fraction": 0.515807709, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.664017413269996}} {"text": "#include \n#include \n#include \"compressibleFlow.h\"\n#include \"mesh.h\"\n#include \"petscdmplex.h\"\n#include \"petscts.h\"\n\n//MMS from Verification of a Compressible CFD Code using the Method of Manufactured Solutions, Christopher J. Roy,† Thomas M. Smith,‡ and Curtis C. Ober§\n\n// Define\n#define Pi PETSC_PI\n#define Sin PetscSinReal\n#define Cos PetscCosReal\n#define Power PetscPowReal\n\ntypedef struct {\n PetscReal phiO;\n PetscReal phiX;\n PetscReal phiY;\n PetscReal phiZ;\n PetscReal aPhiX;\n PetscReal aPhiY;\n PetscReal aPhiZ;\n} PhiConstants;\n\ntypedef struct {\n PetscInt dim;\n PhiConstants rho;\n PhiConstants u;\n PhiConstants v;\n PhiConstants w;\n PhiConstants p;\n PetscReal L;\n PetscReal gamma;\n PetscReal R;\n PetscReal mu;\n} Constants;\n\ntypedef struct {\n Constants constants;\n FlowData flowData;\n} ProblemSetup;\n\nstatic PetscErrorCode EulerExact(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n PetscReal L = constants->L;\n PetscReal gamma = constants->gamma;\n\n PetscReal rhoO = constants->rho.phiO;\n PetscReal rhoX = constants->rho.phiX;\n PetscReal rhoY = constants->rho.phiY;\n PetscReal rhoZ = constants->rho.phiZ;\n PetscReal aRhoX = constants->rho.aPhiX;\n PetscReal aRhoY = constants->rho.aPhiY;\n PetscReal aRhoZ = constants->rho.aPhiZ;\n\n PetscReal uO = constants->u.phiO;\n PetscReal uX = constants->u.phiX;\n PetscReal uY = constants->u.phiY;\n PetscReal uZ = constants->u.phiZ;\n PetscReal aUX = constants->u.aPhiX;\n PetscReal aUY = constants->u.aPhiY;\n PetscReal aUZ = constants->u.aPhiZ;\n\n PetscReal vO = constants->v.phiO;\n PetscReal vX = constants->v.phiX;\n PetscReal vY = constants->v.phiY;\n PetscReal vZ = constants->v.phiZ;\n PetscReal aVX = constants->v.aPhiX;\n PetscReal aVY = constants->v.aPhiY;\n PetscReal aVZ = constants->v.aPhiZ;\n\n PetscReal wO = constants->w.phiO;\n PetscReal wX = constants->w.phiX;\n PetscReal wY = constants->w.phiY;\n PetscReal wZ = constants->w.phiZ;\n PetscReal aWX = constants->w.aPhiX;\n PetscReal aWY = constants->w.aPhiY;\n PetscReal aWZ = constants->w.aPhiZ;\n\n PetscReal pO = constants->p.phiO;\n PetscReal pX = constants->p.phiX;\n PetscReal pY = constants->p.phiY;\n PetscReal pZ = constants->p.phiZ;\n PetscReal aPX = constants->p.aPhiX;\n PetscReal aPY = constants->p.aPhiY;\n PetscReal aPZ = constants->p.aPhiZ;\n\n PetscReal x = xyz[0];\n PetscReal y = xyz[1];\n PetscReal z = dim > 2? xyz[2] : 0.0;\n\n u[RHO] = rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L);\n u[RHOE] = (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.);\n\n u[RHOU + 0] = (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L));\n u[RHOU + 1] = (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n (vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L));\n\n if(dim > 2){\n u[RHOU + 2] = (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L));\n }\n\n PetscFunctionReturn(0);\n}\n\n\nstatic PetscErrorCode EulerExactTimeDerivative(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {\n PetscFunctionBeginUser;\n u[RHO] = 0.0;\n u[RHOE] = 0.0;\n u[RHOU + 0] = 0.0;\n u[RHOU + 1] = 0.0;\n if(dim > 2) {\n u[RHOU + 2] = 0.0;\n }\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n\n // Get the DM\n DM dm;\n ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);\n\n ierr = VecViewFromOptions(u, NULL, \"-sol_view\");CHKERRQ(ierr);\n ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), \"TS at %f\\n\", time);CHKERRQ(ierr);\n\n // Compute the error\n void *exactCtxs[1];\n PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n PetscDS ds;\n ierr = DMGetDS(dm, &ds);CHKERRQ(ierr);\n\n // Get the exact solution\n ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]);CHKERRQ(ierr);\n\n // Create an vector to hold the exact solution\n Vec exactVec;\n ierr = VecDuplicate(u, &exactVec);CHKERRQ(ierr);\n ierr = DMProjectFunction(dm,time,exactFuncs,exactCtxs,INSERT_ALL_VALUES,exactVec);CHKERRQ(ierr);\n\n // For each component, compute the l2 norms\n ierr = VecAXPY(exactVec, -1.0, u);CHKERRQ(ierr);\n\n PetscReal ferrors[4];\n ierr = VecSetBlockSize(exactVec, 4);CHKERRQ(ierr);\n\n // Compute the L2 Difference\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"Timestep: %04d time = %-8.4g \\t\\n\", (int) step, (double) time);CHKERRQ(ierr);\n ierr = VecStrideNormAll(exactVec, NORM_2,ferrors);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double) ferrors[0], (double) ferrors[1], (double) ferrors[2], (double) ferrors[3]);CHKERRQ(ierr);\n ierr = VecStrideNormAll(exactVec, NORM_INFINITY,ferrors);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double) ferrors[0], (double) ferrors[1], (double) ferrors[2], (double) ferrors[3]);CHKERRQ(ierr);\n\n ierr = VecDestroy(&exactVec);CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode SourceRho(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n PetscReal L = constants->L;\n PetscReal gamma = constants->gamma;\n\n PetscReal rhoO = constants->rho.phiO;\n PetscReal rhoX = constants->rho.phiX;\n PetscReal rhoY = constants->rho.phiY;\n PetscReal rhoZ = constants->rho.phiZ;\n PetscReal aRhoX = constants->rho.aPhiX;\n PetscReal aRhoY = constants->rho.aPhiY;\n PetscReal aRhoZ = constants->rho.aPhiZ;\n\n PetscReal uO = constants->u.phiO;\n PetscReal uX = constants->u.phiX;\n PetscReal uY = constants->u.phiY;\n PetscReal uZ = constants->u.phiZ;\n PetscReal aUX = constants->u.aPhiX;\n PetscReal aUY = constants->u.aPhiY;\n PetscReal aUZ = constants->u.aPhiZ;\n\n PetscReal vO = constants->v.phiO;\n PetscReal vX = constants->v.phiX;\n PetscReal vY = constants->v.phiY;\n PetscReal vZ = constants->v.phiZ;\n PetscReal aVX = constants->v.aPhiX;\n PetscReal aVY = constants->v.aPhiY;\n PetscReal aVZ = constants->v.aPhiZ;\n\n PetscReal wO = constants->w.phiO;\n PetscReal wX = constants->w.phiX;\n PetscReal wY = constants->w.phiY;\n PetscReal wZ = constants->w.phiZ;\n PetscReal aWX = constants->w.aPhiX;\n PetscReal aWY = constants->w.aPhiY;\n PetscReal aWZ = constants->w.aPhiZ;\n\n PetscReal pO = constants->p.phiO;\n PetscReal pX = constants->p.phiX;\n PetscReal pY = constants->p.phiY;\n PetscReal pZ = constants->p.phiZ;\n PetscReal aPX = constants->p.aPhiX;\n PetscReal aPY = constants->p.aPhiY;\n PetscReal aPZ = constants->p.aPhiZ;\n\n PetscReal x = xyz[0];\n PetscReal y = xyz[1];\n PetscReal z = dim > 2? xyz[2] : 0.0;\n\n u[0] = (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +\n uX*Sin((aUX*Pi*x)/L)))/L + (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*\n (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L +\n (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -\n (aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +\n vZ*Sin((aVZ*Pi*z)/L)))/L - (aWZ*Pi*wZ*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n Sin((aWZ*Pi*z)/L))/L;\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode SourceRhoU(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n PetscReal L = constants->L;\n PetscReal gamma = constants->gamma;\n\n PetscReal rhoO = constants->rho.phiO;\n PetscReal rhoX = constants->rho.phiX;\n PetscReal rhoY = constants->rho.phiY;\n PetscReal rhoZ = constants->rho.phiZ;\n PetscReal aRhoX = constants->rho.aPhiX;\n PetscReal aRhoY = constants->rho.aPhiY;\n PetscReal aRhoZ = constants->rho.aPhiZ;\n\n PetscReal uO = constants->u.phiO;\n PetscReal uX = constants->u.phiX;\n PetscReal uY = constants->u.phiY;\n PetscReal uZ = constants->u.phiZ;\n PetscReal aUX = constants->u.aPhiX;\n PetscReal aUY = constants->u.aPhiY;\n PetscReal aUZ = constants->u.aPhiZ;\n\n PetscReal vO = constants->v.phiO;\n PetscReal vX = constants->v.phiX;\n PetscReal vY = constants->v.phiY;\n PetscReal vZ = constants->v.phiZ;\n PetscReal aVX = constants->v.aPhiX;\n PetscReal aVY = constants->v.aPhiY;\n PetscReal aVZ = constants->v.aPhiZ;\n\n PetscReal wO = constants->w.phiO;\n PetscReal wX = constants->w.phiX;\n PetscReal wY = constants->w.phiY;\n PetscReal wZ = constants->w.phiZ;\n PetscReal aWX = constants->w.aPhiX;\n PetscReal aWY = constants->w.aPhiY;\n PetscReal aWZ = constants->w.aPhiZ;\n\n PetscReal pO = constants->p.phiO;\n PetscReal pX = constants->p.phiX;\n PetscReal pY = constants->p.phiY;\n PetscReal pZ = constants->p.phiZ;\n PetscReal aPX = constants->p.aPhiX;\n PetscReal aPY = constants->p.aPhiY;\n PetscReal aPZ = constants->p.aPhiZ;\n\n PetscReal x = xyz[0];\n PetscReal y = xyz[1];\n PetscReal z = dim > 2? xyz[2] : 0.0;\n\n\n u[0] = -((aPX*Pi*pX*Sin((aPX*Pi*x)/L))/L) + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*\n Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2))/L +\n (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +\n uX*Sin((aUX*Pi*x)/L))*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/\n L + (2*aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +\n uX*Sin((aUX*Pi*x)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -\n (aUZ*Pi*uZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n Sin((aUZ*Pi*z)/L))/L - (aRhoY*Pi*rhoY*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aRhoY*Pi*y)/L)*\n (vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -\n (aUY*Pi*uY*Sin((aUY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +\n vZ*Sin((aVZ*Pi*z)/L)))/L - (aWZ*Pi*wZ*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n Sin((aWZ*Pi*z)/L))/L;\n\n u[1] = (aPY*Pi*pY*Cos((aPY*Pi*y)/L))/L - (aVX*Pi*vX*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aVX*Pi*x)/L)*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L +\n (aVZ*Pi*vZ*Cos((aVZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +\n wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n (vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L +\n (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +\n wY*Sin((aWY*Pi*y)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/\n L + (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +\n vZ*Sin((aVZ*Pi*z)/L)))/L + (2*aVY*Pi*vY*Cos((aVY*Pi*y)/L)*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n (vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -\n (aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +\n vZ*Sin((aVZ*Pi*z)/L),2))/L - (aWZ*Pi*wZ*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n (vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*Sin((aWZ*Pi*z)/L))/L;\n\n if(dim >2){\n u[2] = (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) +\n uX*Sin((aUX*Pi*x)/L))*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/\n L + (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*\n Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2))/L -\n (aPZ*Pi*pZ*Sin((aPZ*Pi*z)/L))/L + (aWX*Pi*wX*Cos((aWX*Pi*x)/L)*\n (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L +\n (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +\n wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L)))/L + (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*\n (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L)))/L -\n (aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) +\n wY*Sin((aWY*Pi*y)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/\n L + (aWY*Pi*wY*Cos((aWY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) +\n rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) +\n vZ*Sin((aVZ*Pi*z)/L)))/L - (2*aWZ*Pi*wZ*\n (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*\n (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n Sin((aWZ*Pi*z)/L))/L;\n }\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode SourceRhoE(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *u, void *ctx) {\n PetscFunctionBeginUser;\n\n Constants *constants = (Constants *)ctx;\n PetscReal L = constants->L;\n PetscReal gamma = constants->gamma;\n\n PetscReal rhoO = constants->rho.phiO;\n PetscReal rhoX = constants->rho.phiX;\n PetscReal rhoY = constants->rho.phiY;\n PetscReal rhoZ = constants->rho.phiZ;\n PetscReal aRhoX = constants->rho.aPhiX;\n PetscReal aRhoY = constants->rho.aPhiY;\n PetscReal aRhoZ = constants->rho.aPhiZ;\n\n PetscReal uO = constants->u.phiO;\n PetscReal uX = constants->u.phiX;\n PetscReal uY = constants->u.phiY;\n PetscReal uZ = constants->u.phiZ;\n PetscReal aUX = constants->u.aPhiX;\n PetscReal aUY = constants->u.aPhiY;\n PetscReal aUZ = constants->u.aPhiZ;\n\n PetscReal vO = constants->v.phiO;\n PetscReal vX = constants->v.phiX;\n PetscReal vY = constants->v.phiY;\n PetscReal vZ = constants->v.phiZ;\n PetscReal aVX = constants->v.aPhiX;\n PetscReal aVY = constants->v.aPhiY;\n PetscReal aVZ = constants->v.aPhiZ;\n\n PetscReal wO = constants->w.phiO;\n PetscReal wX = constants->w.phiX;\n PetscReal wY = constants->w.phiY;\n PetscReal wZ = constants->w.phiZ;\n PetscReal aWX = constants->w.aPhiX;\n PetscReal aWY = constants->w.aPhiY;\n PetscReal aWZ = constants->w.aPhiZ;\n\n PetscReal pO = constants->p.phiO;\n PetscReal pX = constants->p.phiX;\n PetscReal pY = constants->p.phiY;\n PetscReal pZ = constants->p.phiZ;\n PetscReal aPX = constants->p.aPhiX;\n PetscReal aPY = constants->p.aPhiY;\n PetscReal aPZ = constants->p.aPhiZ;\n\n PetscReal x = xyz[0];\n PetscReal y = xyz[1];\n PetscReal z = dim > 2? xyz[2] : 0.0;\n\n u[0] = -((aPX*Pi*pX*Sin((aPX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L)))/L) + (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/L +\n (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/L - (aPZ*Pi*pZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*Sin((aPZ*Pi*z)/L))/L +\n (aPY*Pi*pY*Cos((aPY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L + (rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*\n ((aRhoY*Pi*rhoY*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))*Sin((aRhoY*Pi*y)/L))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2)) +\n (aPY*Pi*pY*Cos((aPY*Pi*y)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n ((-2*aUY*Pi*uY*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aUY*Pi*y)/L))/L + (2*aWY*Pi*wY*Cos((aWY*Pi*y)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L +\n (2*aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L)/2.) + (uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n (-((aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2))) -\n (aPX*Pi*pX*Sin((aPX*Pi*x)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n ((2*aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L)))/L + (2*aWX*Pi*wX*Cos((aWX*Pi*x)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L)))/L -\n (2*aVX*Pi*vX*Sin((aVX*Pi*x)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L)/2.) + (aRhoX*Pi*rhoX*Cos((aRhoX*Pi*x)/L)*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*\n ((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +\n (aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +\n (aUX*Pi*uX*Cos((aUX*Pi*x)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L +\n (aVY*Pi*vY*Cos((aVY*Pi*y)/L)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L -\n (aRhoY*Pi*rhoY*Sin((aRhoY*Pi*y)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L))*((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.))/L -\n (aWZ*Pi*wZ*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))*Sin((aWZ*Pi*z)/L))/L - (aWZ*Pi*wZ*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n ((pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L))/((-1. + gamma)*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n (Power(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L),2) + Power(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L),2) + Power(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L),2))/2.)*Sin((aWZ*Pi*z)/L))/L +\n (wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))*\n (-((aRhoZ*Pi*rhoZ*Cos((aRhoZ*Pi*z)/L)*(pO + pX*Cos((aPX*Pi*x)/L) + pZ*Cos((aPZ*Pi*z)/L) + pY*Sin((aPY*Pi*y)/L)))/((-1. + gamma)*L*Power(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L),2))) -\n (aPZ*Pi*pZ*Sin((aPZ*Pi*z)/L))/((-1. + gamma)*L*(rhoO + rhoY*Cos((aRhoY*Pi*y)/L) + rhoX*Sin((aRhoX*Pi*x)/L) + rhoZ*Sin((aRhoZ*Pi*z)/L))) +\n ((-2*aUZ*Pi*uZ*(uO + uY*Cos((aUY*Pi*y)/L) + uZ*Cos((aUZ*Pi*z)/L) + uX*Sin((aUX*Pi*x)/L))*Sin((aUZ*Pi*z)/L))/L + (2*aVZ*Pi*vZ*Cos((aVZ*Pi*z)/L)*(vO + vX*Cos((aVX*Pi*x)/L) + vY*Sin((aVY*Pi*y)/L) + vZ*Sin((aVZ*Pi*z)/L)))/L -\n (2*aWZ*Pi*wZ*(wO + wZ*Cos((aWZ*Pi*z)/L) + wX*Sin((aWX*Pi*x)/L) + wY*Sin((aWY*Pi*y)/L))*Sin((aWZ*Pi*z)/L))/L)/2.);\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) {\n PetscFunctionBeginUser;\n Constants *constants = (Constants *)ctx;\n\n // Offset the calc assuming the cells are square\n PetscReal x[3];\n\n for(PetscInt i =0; i < constants->dim; i++){\n x[i] = c[i] + n[i]*0.5;\n }\n\n EulerExact(constants->dim, time, x, 0, a_xG, ctx);\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode ComputeRHSWithSourceTerms(DM dm, PetscReal time, Vec locXVec, Vec globFVec, void *ctx){\n PetscFunctionBeginUser;\n PetscErrorCode ierr;\n ProblemSetup *setup = (ProblemSetup *)ctx;\n\n // Call the flux calculation\n ierr = DMPlexTSComputeRHSFunctionFVM(dm, time, locXVec, globFVec, setup->flowData);CHKERRQ(ierr);\n\n // Convert the dm to a plex\n DM plex;\n DMConvert(dm, DMPLEX, &plex);\n\n // Extract the cell geometry, and the dm that holds the information\n Vec cellgeom;\n DM dmCell;\n const PetscScalar *cgeom;\n ierr = DMPlexGetGeometryFVM(plex, NULL, &cellgeom, NULL);CHKERRQ(ierr);\n ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);\n ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n\n // Get the cell start and end for the fv cells\n PetscInt cStart, cEnd;\n ierr = DMPlexGetSimplexOrBoxCells(dmCell, 0, &cStart, &cEnd);CHKERRQ(ierr);\n\n // create a local f vector\n Vec locFVec;\n PetscScalar *locFArray;\n ierr = DMGetLocalVector(dm, &locFVec);CHKERRQ(ierr);\n ierr = VecZeroEntries(locFVec);CHKERRQ(ierr);\n ierr = VecGetArray(locFVec, &locFArray);CHKERRQ(ierr);\n\n // get the current values\n const PetscScalar *locXArray;\n ierr = VecGetArrayRead(locXVec, &locXArray);CHKERRQ(ierr);\n\n PetscInt rank;\n MPI_Comm_rank(PETSC_COMM_WORLD, &rank);\n\n // March over each cell volume\n for (PetscInt c = cStart; c < cEnd; ++c) {\n PetscFVCellGeom *cg;\n const PetscReal *xc;\n PetscReal *fc;\n\n ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);\n ierr = DMPlexPointLocalFieldRead(plex, c, 0, locXArray, &xc);CHKERRQ(ierr);\n ierr = DMPlexPointGlobalFieldRef(plex, c, 0, locFArray, &fc);CHKERRQ(ierr);\n\n if(fc) { // must be real cell and not ghost\n SourceRho(setup->constants.dim, time, cg->centroid, 0, fc + RHO, &setup->constants);\n SourceRhoE(setup->constants.dim, time, cg->centroid, 0, fc + RHOE, &setup->constants);\n SourceRhoU(setup->constants.dim, time, cg->centroid, 0, fc + RHOU, &setup->constants);\n }\n }\n\n // restore the cell geometry\n ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(locXVec, &locXArray);CHKERRQ(ierr);\n ierr = VecRestoreArray(locFVec, &locFArray);CHKERRQ(ierr);\n\n ierr = DMLocalToGlobalBegin(dm, locFVec, ADD_VALUES, globFVec);CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(dm, locFVec, ADD_VALUES, globFVec);CHKERRQ(ierr);\n ierr = DMRestoreLocalVector(dm, &locFVec);CHKERRQ(ierr);\n\n// {// check rhs,\n// // temp read current residual\n// const PetscScalar *currentFArray;\n// ierr = VecGetArrayRead(globFVec, ¤tFArray);CHKERRQ(ierr);\n// ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n//\n// // March over each cell volume\n// for (PetscInt c = cStart; c < cEnd; ++c) {\n// PetscFVCellGeom *cg;\n// const PetscReal *fcCurrent;\n//\n// ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);\n// ierr = DMPlexPointGlobalFieldRead(plex, c, 0, currentFArray, &fcCurrent);CHKERRQ(ierr);\n//\n// if(fcCurrent) { // must be real cell and not ghost\n// if(PetscAbsReal(cg->centroid[0] - .5 ) < 1E-8 && PetscAbsReal(cg->centroid[1] - .5 ) < 1E-8){\n// printf(\"Residual(%f, %f): %f %f %f %f\\n\", cg->centroid[0], cg->centroid[1], fcCurrent[0], fcCurrent[1], fcCurrent[2], fcCurrent[3]);\n// }\n// }\n// }\n//\n// // temp return current residual\n// ierr = VecRestoreArrayRead(globFVec, ¤tFArray);CHKERRQ(ierr);\n// ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n// }\n\n PetscFunctionReturn(0);\n}\n\nPetscErrorCode ComputeRHS(TS ts, DM dm, PetscReal t, Vec u, PetscInt blockSize, PetscReal residualNorm2[], PetscReal residualNormInf[], PetscReal start[], PetscReal end[])\n{\n MPI_Comm comm;\n Vec r;\n PetscErrorCode ierr;\n\n PetscFunctionBeginUser;\n Vec sol;\n ierr = VecDuplicate(u, &sol);CHKERRQ(ierr);\n ierr = VecCopy(u, sol);CHKERRQ(ierr);\n\n ierr = PetscObjectGetComm((PetscObject) ts, &comm);CHKERRQ(ierr);\n ierr = DMComputeExactSolution(dm, t, sol, NULL);CHKERRQ(ierr);\n ierr = VecDuplicate(u, &r);CHKERRQ(ierr);\n ierr = TSComputeRHSFunction(ts, t, sol, r);CHKERRQ(ierr);\n\n // zero out the norms\n for(PetscInt b =0; b < blockSize; b++){\n residualNorm2[b] = 0.0;\n residualNormInf[b] = 0.0;\n }\n\n {//March over each cell\n // Extract the cell geometry, and the dm that holds the information\n Vec cellgeom;\n DM dmCell;\n PetscInt dim;\n const PetscScalar *cgeom;\n ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr);\n ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);\n ierr = DMGetDimension(dm, &dim);CHKERRQ(ierr);\n\n // Get the cell start and end for the fv cells\n PetscInt cStart, cEnd;\n ierr = DMPlexGetSimplexOrBoxCells(dmCell, 0, &cStart, &cEnd);CHKERRQ(ierr);\n\n // temp read current residual\n const PetscScalar *currentRHS;\n ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n ierr = VecGetArrayRead(r, ¤tRHS);CHKERRQ(ierr);\n\n // Count up the cells\n PetscInt count = 0;\n\n // March over each cell volume\n for (PetscInt c = cStart; c < cEnd; ++c) {\n PetscFVCellGeom *cg;\n const PetscReal *rhsCurrent;\n\n ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);\n ierr = DMPlexPointGlobalFieldRead(dm, c, 0, currentRHS, &rhsCurrent);CHKERRQ(ierr);\n\n PetscBool countCell = PETSC_TRUE;\n for(PetscInt d =0; d < dim; d++){\n countCell = cg->centroid[d] < start[d] || cg->centroid[d] > end[d] ? PETSC_FALSE : countCell;\n }\n\n if(rhsCurrent && countCell ) { // must be real cell and not ghost\n for(PetscInt b =0; b < blockSize; b++){\n residualNorm2[b] += PetscSqr(rhsCurrent[b]);\n residualNormInf[b] = PetscMax(residualNormInf[b], PetscAbs(rhsCurrent[b]));\n }\n count++;\n }\n }\n\n // normalize the norm2\n for(PetscInt b =0; b < blockSize; b++){\n residualNorm2[b] = PetscSqrtReal(residualNorm2[b]/count);\n }\n\n // temp return current residual\n ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);\n ierr = VecRestoreArrayRead(r, ¤tRHS);CHKERRQ(ierr);\n }\n\n ierr = VecDestroy(&sol);CHKERRQ(ierr);\n ierr = VecDestroy(&r);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\nint main(int argc, char **argv)\n{\n\n // Setup the problem\n Constants constants;\n\n // sub sonic\n constants.dim = 2;\n constants.L = 1.0;\n constants.gamma = 1.4;\n constants.R = 287.0;\n constants.mu = 10;\n\n constants.rho.phiO = 1.0;\n constants.rho.phiX = 0.15;\n constants.rho.phiY = -0.1;\n constants.rho.phiZ = 0.0;\n constants.rho.aPhiX = 1.0;\n constants.rho.aPhiY = 0.5;\n constants.rho.aPhiZ = 0.0;\n\n constants.u.phiO = 70;\n constants.u.phiX = 5;\n constants.u.phiY = -7;\n constants.u.phiZ = 0.0;\n constants.u.aPhiX = 1.5;\n constants.u.aPhiY = 0.6;\n constants.u.aPhiZ = 0.0;\n\n constants.v.phiO = 90;\n constants.v.phiX = -15;\n constants.v.phiY = -8.5;\n constants.v.phiZ = 0.0;\n constants.v.aPhiX = 0.5;\n constants.v.aPhiY = 2.0/3.0;\n constants.v.aPhiZ = 0.0;\n\n constants.w.phiO = 0.0;\n constants.w.phiX = 0.0;\n constants.w.phiY = 0.0;\n constants.w.phiZ = 0.0;\n constants.w.aPhiX = 0.0;\n constants.w.aPhiY = 0.0;\n constants.w.aPhiZ = 0.0;\n\n constants.p.phiO = 1E5;\n constants.p.phiX = 0.2E5;\n constants.p.phiY = 0.5E5;\n constants.p.phiZ = 0.0;\n constants.p.aPhiX = 2.0;\n constants.p.aPhiY = 1.0;\n constants.p.aPhiZ = 0.0;\n\n\n PetscErrorCode ierr;\n // create the mesh\n // setup the ts\n DM dm; /* problem definition */\n TS ts; /* timestepper */\n\n // initialize petsc and mpi\n PetscInitialize(&argc, &argv, NULL, \"HELP\");\n\n // Create a ts\n ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr);\n ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr);\n ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr);\n\n // Create a mesh\n // hard code the problem setup\n PetscReal start[] = {0.0, 0.0};\n PetscReal end[] = {constants.L, constants.L};\n PetscInt nx[] = {4, 4};\n DMBoundaryType bcType[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};\n ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, bcType, PETSC_TRUE, &dm);CHKERRQ(ierr);\n\n // Setup the flow data\n FlowData flowData; /* store some of the flow data*/\n ierr = FlowCreate(&flowData);CHKERRQ(ierr);\n\n // Combine the flow data\n ProblemSetup problemSetup;\n problemSetup.flowData = flowData;\n problemSetup.constants = constants;\n\n //Setup\n CompressibleFlow_SetupDiscretization(flowData, &dm);\n\n // Add in the flow parameters\n PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS];\n params[CFL] = 0.5;\n params[GAMMA] = constants.gamma;\n\n // set up the finite volume fluxes\n CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params);\n DMView(flowData->dm, PETSC_VIEWER_STDERR_SELF);\n // Add in any boundary conditions\n PetscDS prob;\n ierr = DMGetDS(flowData->dm, &prob);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n const PetscInt idsLeft[]= {1, 2, 3, 4};\n ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, \"wall left\", \"Face Sets\", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 4, idsLeft, &constants);CHKERRQ(ierr);\n\n // Complete the problem setup\n ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Override the flow calc for now\n ierr = DMTSSetRHSFunctionLocal(flowData->dm, ComputeRHSWithSourceTerms, &problemSetup);CHKERRQ(ierr);\n\n // Name the flow field\n ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the TS\n ierr = TSSetFromOptions(ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSMonitorSet(ts, MonitorError, &constants, NULL);CHKERRQ(ierr);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSSetMaxTime(ts, 0.01);CHKERRQ(ierr);\n\n // set the initial conditions\n PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {EulerExact};\n void* ctxs[1] ={&constants};\n ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr);\n\n // for the mms, add the exact solution\n ierr = PetscDSSetExactSolution(prob, 0, EulerExact, &constants);CHKERRQ(ierr);\n ierr = PetscDSSetExactSolutionTimeDerivative(prob, 0, EulerExactTimeDerivative, &constants);CHKERRQ(ierr);\n\n // Output the mesh\n ierr = DMViewFromOptions(dm, NULL, \"-dm_view\");CHKERRQ(ierr);\n\n TSSetMaxSteps(ts, 1);\n ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr);\n\n // Check the current residual\n PetscReal l2Residual[4];\n PetscReal infResidual[4];\n\n // Only take the residual over the central 1/3\n PetscReal resStart[2] = {1.0/3.0, 1.0/3.0};\n PetscReal resEnd[2] = {2.0/3.0, 2.0/3.0};\n\n ierr = ComputeRHS(ts, flowData->dm, 0.0, flowData->flowField, 4, l2Residual, infResidual, resStart, resEnd);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_2 Residual: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double) l2Residual[0], (double) l2Residual[1], (double) l2Residual[2], (double) l2Residual[3]);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"\\tL_Inf Residual: [%2.3g, %2.3g, %2.3g, %2.3g]\\n\", (double) infResidual[0], (double) infResidual[1], (double) infResidual[2], (double) infResidual[3]);CHKERRQ(ierr);\n\n\n PetscReal time = 0.0;\n\n\n\n// {\n// Vec sol;\n// VecDuplicate(flowData->flowField, &sol);\n// VecCopy(flowData->flowField, sol);\n//\n// SNES snes;\n// ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);\n// ierr = DMSNESCheckDiscretization(snes, flowData->dm, time, sol, -1.0, NULL);CHKERRQ(ierr);\n//\n// Vec u_t;\n// ierr = DMGetGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);\n// ierr = DMTSCheckResidual(ts, flowData->dm, time, sol, u_t, -1.0, NULL);CHKERRQ(ierr);\n// ierr = DMRestoreGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);\n//\n// VecDestroy(&sol);\n// }\n\n\n// {\n// Vec sol;\n// VecDuplicate(flowData->flowField, &sol);\n// VecCopy(flowData->flowField, sol);\n//\n// SNES snes;\n// ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);\n// ierr = DMSNESCheckDiscretization(snes, flowData->dm, time, sol, -1.0, NULL);CHKERRQ(ierr);\n//\n// Vec u_t;\n// ierr = DMGetGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);\n// ierr = DMTSCheckResidual(ts, flowData->dm, time, sol, u_t, -1.0, NULL);CHKERRQ(ierr);\n// ierr = DMRestoreGlobalVector(flowData->dm, &u_t);CHKERRQ(ierr);\n//\n// VecDestroy(&sol);\n// }\n\n return PetscFinalize();\n\n}", "meta": {"hexsha": "70551590619ff2c38b05f12f08d7f3c08f7e073d", "size": 44048, "ext": "c", "lang": "C", "max_stars_repo_path": "euler2DMMS.c", "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "euler2DMMS.c", "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "euler2DMMS.c", "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.113022113, "max_line_length": 612, "alphanum_fraction": 0.5167544497, "num_tokens": 15399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6638789787048719}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n/* --------- ROUTINE: h_over_h0 ---------\nINPUT: scale factor, cosmology\nTASK: Compute E(a)=H(a)/H0\n*/\nstatic double h_over_h0(double a, ccl_cosmology * cosmo, int *status)\n{\n // Check if massive neutrinos are present - if not, we don't need to\n // compute their contribution\n double Om_mass_nu;\n if ((cosmo->params.N_nu_mass)>1e-12) {\n Om_mass_nu = ccl_Omeganuh2(\n a, cosmo->params.N_nu_mass, cosmo->params.m_nu, cosmo->params.T_CMB,\n status) / (cosmo->params.h) / (cosmo->params.h);\n }\n else {\n Om_mass_nu = 0;\n }\n\n /* Calculate h^2 using the formula (eqn 2 in the CCL paper):\n E(a)^2 = Omega_m a^-3 +\n Omega_l a^(-3*(1+w0+wa)) exp(3*wa*(a-1)) +\n Omega_k a^-2 +\n (Omega_g + Omega_nu_rel) a^-4 +\n Om_mass_nu\n */\n return sqrt(\n (cosmo->params.Omega_c + cosmo->params.Omega_b +\n cosmo->params.Omega_l *\n pow(a,-3*(cosmo->params.w0+cosmo->params.wa)) *\n exp(3*cosmo->params.wa*(a-1)) +\n cosmo->params.Omega_k * a +\n (cosmo->params.Omega_g + cosmo->params.Omega_nu_rel) / a +\n Om_mass_nu * a*a*a) / (a*a*a));\n}\n\n/* --------- ROUTINE: ccl_omega_x ---------\nINPUT: cosmology object, scale factor, species label\nTASK: Compute the density relative to critical, Omega(a) for a given species.\nPossible values for \"label\":\nccl_species_crit_label <- critical (physical)\nccl_species_m_label <- matter\nccl_species_l_label <- DE\nccl_species_g_label <- radiation\nccl_species_k_label <- curvature\nccl_species_ur_label <- massless neutrinos\nccl_species_nu_label <- massive neutrinos\n*/\ndouble ccl_omega_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int *status)\n{\n // If massive neutrinos are present, compute the phase-space integral and\n // get OmegaNuh2. If not, set OmegaNuh2 to zero.\n double OmNuh2;\n if ((cosmo->params.N_nu_mass) > 0.0001) {\n // Call the massive neutrino density function just once at this redshift.\n OmNuh2 = ccl_Omeganuh2(a, cosmo->params.N_nu_mass, cosmo->params.m_nu,\n cosmo->params.T_CMB, status);\n }\n else {\n OmNuh2 = 0.;\n }\n\n double hnorm = h_over_h0(a, cosmo, status);\n\n switch(label) {\n case ccl_species_crit_label :\n return 1.;\n case ccl_species_m_label :\n return (cosmo->params.Omega_c + cosmo->params.Omega_b) / (a*a*a) / hnorm / hnorm +\n OmNuh2 / (cosmo->params.h) / (cosmo->params.h) / hnorm / hnorm;\n case ccl_species_l_label :\n return\n cosmo->params.Omega_l *\n pow(a,-3 * (1 + cosmo->params.w0 + cosmo->params.wa)) *\n exp(3 * cosmo->params.wa * (a-1)) / hnorm / hnorm;\n case ccl_species_g_label :\n return cosmo->params.Omega_g / (a*a*a*a) / hnorm / hnorm;\n case ccl_species_k_label :\n return cosmo->params.Omega_k / (a*a) / hnorm / hnorm;\n case ccl_species_ur_label :\n return cosmo->params.Omega_nu_rel / (a*a*a*a) / hnorm / hnorm;\n case ccl_species_nu_label :\n return OmNuh2 / (cosmo->params.h) / (cosmo->params.h) / hnorm / hnorm;\n default:\n *status = CCL_ERROR_PARAMETERS;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_omega_x(): Species %d not supported\\n\", label);\n return NAN;\n }\n}\n\n/* --------- ROUTINE: ccl_rho_x ---------\nINPUT: cosmology object, scale factor, species label\nTASK: Compute rho_x(a), with x defined by species label.\nPossible values for \"label\":\nccl_species_crit_label <- critical (physical)\nccl_species_m_label <- matter (physical)\nccl_species_l_label <- DE (physical)\nccl_species_g_label <- radiation (physical)\nccl_species_k_label <- curvature (physical)\nccl_species_ur_label <- massless neutrinos (physical)\nccl_species_nu_label <- massive neutrinos (physical)\n*/\ndouble ccl_rho_x(ccl_cosmology * cosmo, double a, ccl_species_x_label label, int is_comoving, int *status)\n{\n double comfac;\n if (is_comoving) {\n comfac = a*a*a;\n } else {\n comfac = 1.0;\n }\n double hnorm = h_over_h0(a, cosmo, status);\n double rhocrit =\n ccl_constants.RHO_CRITICAL *\n (cosmo->params.h) *\n (cosmo->params.h) * hnorm * hnorm * comfac;\n\n return rhocrit * ccl_omega_x(cosmo, a, label, status);\n}\n\n/* --------- ROUTINE: ccl_mu_MG ---------\nINPUT: cosmology object, scale factor\nTASK: Compute mu(a) where mu is one of the the parameterizating functions\nof modifications to GR in the quasistatic approximation.\n*/\n\ndouble ccl_mu_MG(ccl_cosmology * cosmo, double a, int *status)\n{\n // This function can be extended to include other\n // z-dependences for mu in the future.\n return cosmo->params.mu_0 * ccl_omega_x(cosmo, a, ccl_species_l_label, status) / cosmo->params.Omega_l;\n}\n\n/* --------- ROUTINE: ccl_Sig_MG ---------\nINPUT: cosmology object, scale factor\nTASK: Compute Sigma(a) where Sigma is one of the the parameterizating functions\nof modifications to GR in the quasistatic approximation.\n*/\n\ndouble ccl_Sig_MG(ccl_cosmology * cosmo, double a, int *status)\n{\n // This function can be extended to include other\n // z-dependences for Sigma in the future.\n return cosmo->params.sigma_0 * ccl_omega_x(cosmo, a, ccl_species_l_label, status) / cosmo->params.Omega_l;\n}\n\n// Structure to hold parameters of chi_integrand\ntypedef struct {\n ccl_cosmology *cosmo;\n int * status;\n} chipar;\n\n/* --------- ROUTINE: chi_integrand ---------\nINPUT: scale factor\nTASK: compute the integrand of the comoving distance\n*/\nstatic double chi_integrand(double a, void * params_void)\n{\n ccl_cosmology * cosmo = ((chipar *)params_void)->cosmo;\n int *status = ((chipar *)params_void)->status;\n\n return ccl_constants.CLIGHT_HMPC/(a*a*h_over_h0(a, cosmo, status));\n}\n\n/* --------- ROUTINE: growth_ode_system ---------\nINPUT: scale factor\nTASK: Define the ODE system to be solved in order to compute the growth (of the density)\n*/\nstatic int growth_ode_system(double a,const double y[],double dydt[],void *params)\n{\n int status = 0;\n ccl_cosmology * cosmo = params;\n\n double hnorm=h_over_h0(a,cosmo, &status);\n double om=ccl_omega_x(cosmo, a, ccl_species_m_label, &status);\n\n dydt[1]=1.5*hnorm*a*om*y[0];\n dydt[0]=y[1]/(a*a*a*hnorm);\n\n return status;\n}\n\n/* --------- ROUTINE: growth_ode_system_muSig ---------\nINPUT: scale factor\nTASK: Define the ODE system to be solved in order to compute the growth (of the density)\n* in the case in which we use the mu / Sigma quasistatic parameterisation of modified gravity\n*/\nstatic int growth_ode_system_muSig(double a,const double y[],double dydt[],void *params)\n{\n int status = 0;\n ccl_cosmology * cosmo = params;\n\n double hnorm=h_over_h0(a,cosmo, &status);\n double om=ccl_omega_x(cosmo, a, ccl_species_m_label, &status);\n\n double mu = ccl_mu_MG(cosmo, a, &status);\n dydt[1]=1.5*hnorm*a*om*y[0]*(1. + mu);\n\n dydt[0]=y[1]/(a*a*a*hnorm);\n\n return status;\n}\n\n/* --------- ROUTINE: df_integrand ---------\nINPUT: scale factor, spline object\nTASK: Compute integrand from modified growth function\n*/\nstatic double df_integrand(double a,void * spline_void)\n{\n if(a<=0)\n return 0;\n else {\n gsl_spline *df_a_spline=(gsl_spline *)spline_void;\n\n return gsl_spline_eval(df_a_spline,a,NULL)/a;\n }\n}\n\n/* --------- ROUTINE: growth_factor_and_growth_rate ---------\nINPUT: scale factor, cosmology\nTASK: compute the growth (D(z)) and the growth rate, logarithmic derivative (f?)\n*/\n\nstatic int growth_factor_and_growth_rate(double a, double *gf, double *fg, ccl_cosmology *cosmo, int *stat)\n{\n if(a < cosmo->gsl_params.EPS_SCALEFAC_GROWTH) {\n *gf = a;\n *fg = 1;\n return 0;\n }\n else {\n int gslstatus;\n double y[2];\n double ainit = cosmo->gsl_params.EPS_SCALEFAC_GROWTH;\n\n // if mu0 == 0, call normal growth_ode_system, otherwise call growth_ode_system_muSig\n if (cosmo->params.mu_0 > 1e-12 || cosmo->params.mu_0 < -1e-12) {\n gsl_odeiv2_system sys = {growth_ode_system_muSig, NULL, 2, cosmo};\n\n gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(\n &sys, gsl_odeiv2_step_rkck,\n 0.1*cosmo->gsl_params.EPS_SCALEFAC_GROWTH, 0, cosmo->gsl_params.ODE_GROWTH_EPSREL);\n\n if (d == NULL) {\n return CCL_ERROR_MEMORY;\n }\n\n y[0] = cosmo->gsl_params.EPS_SCALEFAC_GROWTH;\n y[1] = (\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH *\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH *\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH *\n h_over_h0(cosmo->gsl_params.EPS_SCALEFAC_GROWTH, cosmo, stat));\n\n gslstatus = gsl_odeiv2_driver_apply(d, &ainit, a, y);\n gsl_odeiv2_driver_free(d);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: growth_factor_and_growth_rate():\");\n return 0;\n }\n\n *gf = y[0];\n *fg = y[1]/(a*a*h_over_h0(a, cosmo, stat)*y[0]);\n return 0;\n }\n else {\n gsl_odeiv2_system sys = {growth_ode_system, NULL, 2, cosmo};\n\n gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(\n &sys, gsl_odeiv2_step_rkck,\n 0.1*cosmo->gsl_params.EPS_SCALEFAC_GROWTH, 0, cosmo->gsl_params.ODE_GROWTH_EPSREL);\n\n if (d == NULL) {\n return CCL_ERROR_MEMORY;\n }\n\n y[0] = cosmo->gsl_params.EPS_SCALEFAC_GROWTH;\n y[1] = (\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH *\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH *\n cosmo->gsl_params.EPS_SCALEFAC_GROWTH*\n h_over_h0(cosmo->gsl_params.EPS_SCALEFAC_GROWTH, cosmo, stat));\n\n gslstatus = gsl_odeiv2_driver_apply(d, &ainit, a, y);\n gsl_odeiv2_driver_free(d);\n\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: growth_factor_and_growth_rate():\");\n return 0;\n }\n\n *gf = y[0];\n *fg = y[1]/(a*a*h_over_h0(a, cosmo, stat)*y[0]);\n\n return 0;\n }\n }\n}\n\n\n/* --------- ROUTINE: compute_chi ---------\nINPUT: scale factor, cosmology\nOUTPUT: chi -> radial comoving distance\nTASK: compute radial comoving distance at a\n*/\nvoid compute_chi(double a, ccl_cosmology *cosmo, double * chi, int * stat)\n{\n int gslstatus;\n double result;\n chipar p;\n\n p.cosmo=cosmo;\n p.status=stat;\n\n gsl_integration_cquad_workspace * workspace = NULL;\n\n gsl_function F;\n F.function = &chi_integrand;\n F.params = &p;\n\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\n if (workspace == NULL) {\n *stat = CCL_ERROR_MEMORY;\n } else {\n //TODO: CQUAD is great, but slower than other methods. This could be sped up if it becomes an issue.\n gslstatus=gsl_integration_cquad(\n &F, a, 1.0, 0.0, cosmo->gsl_params.INTEGRATION_DISTANCE_EPSREL, workspace, &result, NULL, NULL);\n *chi=result/cosmo->params.h;\n\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: compute_chi():\");\n *stat = CCL_ERROR_COMPUTECHI;\n }\n }\n\n gsl_integration_cquad_workspace_free(workspace);\n}\n\n\n//Root finding for a(chi)\ntypedef struct {\n double chi;\n ccl_cosmology *cosmo;\n int * status;\n} Fpar;\n\nstatic double fzero(double a,void *params)\n{\n double chi,chia,a_use=a;\n\n chi=((Fpar *)params)->chi;\n compute_chi(a_use,((Fpar *)params)->cosmo,&chia, ((Fpar *)params)->status);\n\n return chi-chia;\n}\n\nstatic double dfzero(double a,void *params)\n{\n ccl_cosmology *cosmo=((Fpar *)params)->cosmo;\n int *stat = ((Fpar *)params)->status;\n\n chipar p;\n p.cosmo=cosmo;\n p.status=stat;\n\n return chi_integrand(a,&p)/cosmo->params.h;\n}\n\nstatic void fdfzero(double a,void *params,double *f,double *df)\n{\n *f=fzero(a,params);\n *df=dfzero(a,params);\n}\n\n/* --------- ROUTINE: a_of_chi ---------\nINPUT: comoving distance chi, cosmology, stat, a_old, gsl_root_fdfsolver\nOUTPUT: scale factor\nTASK: compute the scale factor that corresponds to a given comoving distance chi\nNote: This routine uses a root solver to find an a such that compute_chi(a) = chi.\nThe root solver uses the derivative of compute_chi (which is chi_integrand) and\nthe value itself.\n*/\nstatic void a_of_chi(double chi, ccl_cosmology *cosmo, int* stat, double *a_old, gsl_root_fdfsolver *s)\n{\n if(chi==0) {\n *a_old=1;\n }\n else {\n Fpar p;\n gsl_function_fdf FDF;\n double a_previous,a_current=*a_old;\n\n p.cosmo=cosmo;\n p.chi=chi;\n p.status=stat;\n FDF.f=&fzero;\n FDF.df=&dfzero;\n FDF.fdf=&fdfzero;\n FDF.params=&p;\n gsl_root_fdfsolver_set(s,&FDF,a_current);\n\n int iter=0, gslstatus;\n do {\n iter++;\n gslstatus=gsl_root_fdfsolver_iterate(s);\n if(gslstatus!=GSL_SUCCESS) ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: a_of_chi():\");\n a_previous=a_current;\n a_current=gsl_root_fdfsolver_root(s);\n gslstatus=gsl_root_test_delta(a_current, a_previous, 0, cosmo->gsl_params.ROOT_EPSREL);\n } while(gslstatus==GSL_CONTINUE && iter <= cosmo->gsl_params.ROOT_N_ITERATION);\n\n *a_old=a_current;\n\n // Allows us to pass a status to h_over_h0 for the neutrino integral calculation.\n if(gslstatus==GSL_SUCCESS) {\n *stat = *(p.status);\n }\n else {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: a_of_chi():\");\n *stat = CCL_ERROR_COMPUTECHI;\n }\n }\n}\n\n/* ----- ROUTINE: ccl_cosmology_compute_distances ------\nINPUT: cosmology\nTASK: if not already there, make a table of comoving distances and of E(a)\n*/\n\nvoid ccl_cosmology_compute_distances(ccl_cosmology * cosmo, int *status)\n{\n //Do nothing if everything is computed already\n if(cosmo->computed_distances)\n return;\n\n // Create logarithmically and then linearly-spaced values of the scale factor\n int na = cosmo->spline_params.A_SPLINE_NA+cosmo->spline_params.A_SPLINE_NLOG-1;\n double * a = ccl_linlog_spacing(\n cosmo->spline_params.A_SPLINE_MINLOG, cosmo->spline_params.A_SPLINE_MIN,\n cosmo->spline_params.A_SPLINE_MAX, cosmo->spline_params.A_SPLINE_NLOG,\n cosmo->spline_params.A_SPLINE_NA);\n // Allocate arrays for all three of E(a), chi(a), and a(chi)\n double *E_a = malloc(sizeof(double)*na);\n double *chi_a = malloc(sizeof(double)*na);\n // Allocate E(a) and chi(a) splines\n gsl_spline * E = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n gsl_spline * chi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n // a(chi) spline allocated below\n\n //Check for too little memory\n if (a == NULL || E_a == NULL || chi_a == NULL || E == NULL || chi == NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\\n\");\n }\n\n //Check for messed up scale factor conditions\n if (!*status){\n if ((fabs(a[0]-cosmo->spline_params.A_SPLINE_MINLOG)>1e-5) ||\n (fabs(a[na-1]-cosmo->spline_params.A_SPLINE_MAX)>1e-5) ||\n (a[na-1]>1.0)) {\n *status = CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_cosmology_compute_distances(): Error \"\n \"creating first logarithmic and then linear spacing in a\\n\");\n }\n }\n\n // Fill in E(a) - note, this step cannot change the status variable\n if (!*status)\n for (int i=0; ispline_params.A_SPLINE_TYPE, na);\n\n //Check for too little memory\n if (!*status){\n if (a == NULL || chi_a == NULL || s == NULL || achi == NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\\n\");\n }\n else if (fabs(chi_a[0]-chi0) > 1e-5 || fabs(chi_a[na-1]-chif) > 1e-5) { //Check for messed up chi conditions\n *status = CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): Error creating linear spacing in chi\\n\");\n }\n }\n\n // Calculate a(chi)\n if (!*status){\n a[0]=a0; a[na-1]=af;\n for(int i=1;idata.E = E;\n cosmo->data.chi = chi;\n cosmo->data.achi = achi;\n cosmo->computed_distances = true;\n }\n}\n\n/* ----- ROUTINE: ccl_cosmology_distances_from_input ------\nINPUT: cosmology, scale factor array, comoving distance chi computed at the scale factor array values\nTASK: if not already there, make a table of comoving distances from an input array\n*/\nvoid ccl_cosmology_distances_from_input(ccl_cosmology * cosmo, int na, double a[], double chi_a[], double E_a[],\n int *status)\n{\n double *chi_a_reversed = NULL;\n double *a_reversed = NULL;\n\n //Do nothing if everything is computed already\n if(cosmo->computed_distances)\n return;\n\n // Allocate E(a), chi(a) and a(chi) splines\n gsl_spline * E = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n gsl_spline * chi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n gsl_spline * achi = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n\n //Check for too little memory\n if (a == NULL || E_a == NULL || chi_a == NULL || E == NULL || chi == NULL || achi == NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_distances_from_input(): ran out of memory\\n\");\n }\n\n // Update the minimum scale factor value used by the user, which is necessary because it is used in ccl_tracers.c\n cosmo->spline_params.A_SPLINE_MIN = a[0];\n\n // Initialize a E(a) spline\n if (!*status){\n if (gsl_spline_init(E, a, E_a, na)){\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_distances_from_input(): Error creating E(a) spline\\n\");\n }\n }\n\n // Initialize chi(a) spline\n if (!*status){\n if (gsl_spline_init(chi, a, chi_a, na)){//in Mpc\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_distances_from_input(): Error creating chi(a) spline\\n\");\n }\n }\n\n // Reverse the order of chi(a) so that we can initialize the a(chi) spline, which needs monotonically decreasing x-array.\n if (!*status) {\n chi_a_reversed = malloc(na*sizeof(double));\n a_reversed = malloc(na*sizeof(double));\n if (chi_a_reversed == NULL || a_reversed == NULL) {\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_distances_from_input(): ran out of memory\\n\");\n }\n else {\n for (int i=0; idata.E = E;\n cosmo->data.chi = chi;\n cosmo->data.achi = achi;\n cosmo->computed_distances = true;\n }\n\n return;\n}\n\n/* ----- ROUTINE: ccl_cosmology_growth_from_input ------\nINPUT: cosmology, scale factor array, growth array, growth rate array\nTASK: if not already there, create growth splines with the input arrays and store them.\n*/\nvoid ccl_cosmology_growth_from_input(ccl_cosmology* cosmo, int na, double a[],\n double growth_arr[], double fgrowth_arr[], int* status)\n{\n int chistatus;\n if (cosmo->computed_growth)\n return;\n\n double *growth_normed = NULL;\n gsl_spline * growth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n gsl_spline * fgrowth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n //The last element corresponds to a=1 (which is checked for in python).\n double growth0 = growth_arr[na-1];\n\n if (growth == NULL || fgrowth == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_growth_from_input(): ran out of memory\\n\");\n }\n\n // Need to normalize the growth factor\n if (*status == 0) {\n growth_normed = malloc(na*sizeof(double));\n if (growth_normed == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_growth_from_input(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n for(int ia=0; iadata.growth = growth;\n cosmo->data.fgrowth = fgrowth;\n cosmo->data.growth0 = growth0;\n cosmo->computed_growth = true;\n }\n\n free(growth_normed);\n}\n\n/* ----- ROUTINE: ccl_cosmology_compute_growth ------\nINPUT: cosmology\nTASK: if not already there, make a table of growth function and growth rate\n normalize growth to input parameter growth0\n*/\nvoid ccl_cosmology_compute_growth(ccl_cosmology* cosmo, int* status)\n{\n if (cosmo->computed_growth)\n return;\n\n // Create logarithmically and then linearly-spaced values of the scale factor\n int chistatus = 0, na = cosmo->spline_params.A_SPLINE_NA+cosmo->spline_params.A_SPLINE_NLOG-1;\n double *a = NULL;\n gsl_integration_cquad_workspace * workspace = NULL;\n gsl_function F;\n gsl_spline *df_a_spline = NULL;\n double *df_arr = NULL;\n gsl_spline *df_z_spline = NULL;\n int status_mg = 0, gslstatus;\n double growth0, fgrowth0;\n double *y = NULL;\n double *y2 = NULL;\n double df, integ;\n\n if (*status == 0) {\n a = ccl_linlog_spacing(\n cosmo->spline_params.A_SPLINE_MINLOG, cosmo->spline_params.A_SPLINE_MIN,\n cosmo->spline_params.A_SPLINE_MAX, cosmo->spline_params.A_SPLINE_NLOG,\n cosmo->spline_params.A_SPLINE_NA);\n\n if (a == NULL ||\n (fabs(a[0]-cosmo->spline_params.A_SPLINE_MINLOG) > 1e-5) ||\n (fabs(a[na-1]-cosmo->spline_params.A_SPLINE_MAX) > 1e-5) ||\n (a[na-1] > 1.0)) {\n *status = CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_cosmology_compute_growth(): \"\n \"Error creating logarithmically and then linear spacing in a\\n\");\n }\n }\n\n if(cosmo->params.has_mgrowth) {\n if (*status == 0) {\n df_arr = malloc(na*sizeof(double));\n\n if(df_arr == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n // Generate spline for Delta f(z) that we will then interpolate into an array of a\n if (*status == 0) {\n df_z_spline = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, cosmo->params.nz_mgrowth);\n if (df_z_spline == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n chistatus = gsl_spline_init(df_z_spline,cosmo->params.z_mgrowth,\n cosmo->params.df_mgrowth,\n cosmo->params.nz_mgrowth);\n\n if(chistatus) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(z) spline\\n\");\n }\n }\n\n if (*status == 0) {\n for (int i=0; i0) {\n double z=1./a[i]-1.;\n\n if(z<=cosmo->params.z_mgrowth[0])\n df_arr[i]=cosmo->params.df_mgrowth[0];\n else if(z>cosmo->params.z_mgrowth[cosmo->params.nz_mgrowth-1])\n df_arr[i]=cosmo->params.df_mgrowth[cosmo->params.nz_mgrowth-1];\n else\n chistatus |= gsl_spline_eval_e(df_z_spline,z,NULL,&df_arr[i]);\n } else {\n df_arr[i]=0;\n }\n }\n if(chistatus) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error evaluating Delta f(z) spline\\n\");\n }\n }\n\n // Generate Delta(f) spline\n if (*status == 0) {\n df_a_spline = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE,na);\n\n if (df_a_spline == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n chistatus = gsl_spline_init(df_a_spline, a, df_arr, na);\n\n if (chistatus) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(a) spline\\n\");\n }\n }\n\n if (*status == 0) {\n workspace = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n F.function = &df_integrand;\n F.params = df_a_spline;\n }\n }\n\n // allocate space for y, which will be all three\n // of E(a), chi(a), D(a) and f(a) in turn.\n if (*status == 0) {\n y = malloc(sizeof(double)*na);\n if (y == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n y2 = malloc(sizeof(double)*na);\n if (y2 == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n // Get the growth factor and growth rate at z=0\n chistatus |= growth_factor_and_growth_rate(1., &growth0, &fgrowth0, cosmo, status);\n\n // Get the growth factor and growth rate at other redshifts\n for(int i=0; iparams.has_mgrowth) {\n if(a[i]>0) {\n // Add modification to f\n gslstatus = gsl_spline_eval_e(df_a_spline, a[i], NULL, &df);\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_cosmology_compute_growth():\");\n status_mg |= gslstatus;\n }\n y2[i] += df;\n\n // Multiply D by exp(-int(df))\n gslstatus = gsl_integration_cquad(\n &F, a[i], 1.0, 0.0, cosmo->gsl_params.INTEGRATION_DISTANCE_EPSREL,\n workspace, &integ, NULL, NULL);\n if (gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_cosmology_compute_growth():\");\n status_mg |= gslstatus;\n }\n y[i] *= exp(-integ);\n }\n }\n // Normalizing to the growth factor to the growth today\n y[i] /= growth0;\n }\n\n if (chistatus || status_mg || *status) {\n if (chistatus) {\n *status = CCL_ERROR_INTEG;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): integral for linear growth factor didn't converge\\n\");\n }\n if(status_mg) {\n *status = CCL_ERROR_INTEG;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): integral for MG growth factor didn't converge\\n\");\n }\n }\n }\n\n gsl_spline *growth = NULL;\n gsl_spline *fgrowth = NULL;\n\n if (*status == 0) {\n growth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n fgrowth = gsl_spline_alloc(cosmo->spline_params.A_SPLINE_TYPE, na);\n\n if (growth == NULL || fgrowth == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): ran out of memory\\n\");\n }\n }\n\n if (*status == 0) {\n chistatus = gsl_spline_init(growth, a, y, na);\n\n if (chistatus) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating D(a) spline\\n\");\n }\n }\n\n if (*status == 0) {\n chistatus = gsl_spline_init(fgrowth, a, y2, na);\n if (chistatus) {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating f(a) spline\\n\");\n }\n }\n\n if (*status == 0) {\n // assign all the splines we've just made to the structure.\n cosmo->data.growth = growth;\n cosmo->data.fgrowth = fgrowth;\n cosmo->data.growth0 = growth0;\n cosmo->computed_growth = true;\n }\n else {\n gsl_spline_free(growth);\n gsl_spline_free(fgrowth);\n }\n\n free(a);\n free(y);\n free(y2);\n free(df_arr);\n gsl_spline_free(df_z_spline);\n gsl_spline_free(df_a_spline);\n gsl_integration_cquad_workspace_free(workspace);\n}\n\n//Expansion rate normalized to 1 today\n\ndouble ccl_h_over_h0(ccl_cosmology * cosmo, double a, int* status)\n{\n\n if(!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_h_over_h0(): distance splines have not been precomputed!\");\n return NAN;\n }\n\n double h_over_h0;\n int gslstatus = gsl_spline_eval_e(cosmo->data.E, a, NULL, &h_over_h0);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_h_over_h0():\");\n *status = gslstatus;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_h_over_h0(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n\n return h_over_h0;\n}\n\n\nvoid ccl_h_over_h0s(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i (1.0 - 1.e-8)) && (a<=1.0)) {\n return 0.;\n }\n else if(a>1.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\\n\");\n return NAN;\n }\n else {\n if(!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_comoving_radial_distance(): distance splines have not been precomputed!\");\n return NAN;\n }\n\n double crd;\n int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, NULL, &crd);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_comoving_radial_distance():\");\n *status = gslstatus;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_comoving_radial_distance(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n return crd;\n }\n}\n\nvoid ccl_comoving_radial_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int* status)\n{\n int _status;\n\n for (int i=0; iparams.k_sign) {\n case -1:\n return sinh(cosmo->params.sqrtk * chi) / cosmo->params.sqrtk;\n case 1:\n return sin(cosmo->params.sqrtk*chi) / cosmo->params.sqrtk;\n case 0:\n return chi;\n default:\n *status = CCL_ERROR_PARAMETERS;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_sinn: ill-defined cosmo->params.k_sign = %d\",\n cosmo->params.k_sign);\n return NAN;\n }\n}\n\ndouble ccl_comoving_angular_distance(ccl_cosmology * cosmo, double a, int* status)\n{\n if((a > (1.0 - 1.e-8)) && (a<=1.0)) {\n return 0.;\n }\n else if(a>1.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\\n\");\n return NAN;\n }\n else {\n if (!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_comoving_angular_distance(): distance splines have not been precomputed!\");\n return NAN;\n }\n\n double chi;\n int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, NULL, &chi);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_comoving_angular_distance():\");\n *status |= gslstatus;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_comoving_angular_distance(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n return ccl_sinn(cosmo,chi,status);\n }\n}\n\nvoid ccl_comoving_angular_distances(ccl_cosmology * cosmo, int na, double a[],\n double output[], int* status)\n{\n int _status;\n\n for (int i=0; i < na; i++) {\n _status = 0;\n output[i] = ccl_comoving_angular_distance(cosmo, a[i], &_status);\n *status |= _status;\n }\n}\n\n\ndouble ccl_angular_diameter_distance(ccl_cosmology * cosmo, double a1, double a2, int* status)\n{\n if(a1>1. || a2>1. || a1computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(cosmo,\"ccl_background.c: ccl_angular_diameter_distance(): distance splines have not been precomputed!\");\n return NAN;\n }\n double chi1,chi2;\n int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a1, NULL, &chi1);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_angular_diameter_distance():\");\n *status |= gslstatus;\n ccl_cosmology_set_status_message(cosmo,\"ccl_background.c: ccl_angular_diameter_distance(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n gslstatus = gsl_spline_eval_e(cosmo->data.chi, a2, NULL, &chi2);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_angular_diameter_distance():\");\n *status |= gslstatus;\n ccl_cosmology_set_status_message(cosmo,\"ccl_background.c: ccl_angular_diameter_distance(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n return a2*ccl_sinn(cosmo,chi2-chi1,status);\n }\n}\n\n\nvoid ccl_angular_diameter_distances(ccl_cosmology * cosmo, int na, double a1[], double a2[],\n double output[], int* status)\n{\n int _status;\n\n for (int i=0; i < na; i++) {\n _status = 0;\n output[i] = ccl_angular_diameter_distance(cosmo, a1[i], a2[i], &_status);\n *status |= _status;\n }\n}\n\n\ndouble ccl_luminosity_distance(ccl_cosmology * cosmo, double a, int* status)\n{\n return ccl_comoving_angular_distance(cosmo, a, status) / a;\n}\n\nvoid ccl_luminosity_distances(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i (1.0 - 1.e-8)) && (a<=1.0)) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: distance_modulus undefined for a=1.\\n\");\n return NAN;\n } else if(a>1.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\\n\");\n return NAN;\n } else {\n if (!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_distance_modulus(): distance splines have not been precomputed!\");\n return NAN;\n }\n /* distance modulus = 5 * log10(d) - 5\n Since d in CCL is in Mpc, you get\n 5*log10(10^6) - 5 = 30 - 5 = 25\n for the constant.\n */\n return 5 * log10(ccl_luminosity_distance(cosmo, a, status)) + 25;\n }\n}\n\n\nvoid ccl_distance_moduli(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i=0.)) {\n return 1.;\n }\n else if(chi<0.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: distance cannot be smaller than 0.\\n\");\n return NAN;\n }\n else {\n if (!cosmo->computed_distances) {\n *status = CCL_ERROR_DISTANCES_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_scale_factor_of_chi(): distance splines have not been precomputed!\");\n return NAN;\n }\n double a;\n int gslstatus = gsl_spline_eval_e(cosmo->data.achi, chi, NULL, &a);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_scale_factor_of_chi():\");\n *status |= gslstatus;\n }\n return a;\n }\n}\n\nvoid ccl_scale_factor_of_chis(ccl_cosmology * cosmo, int nchi, double chi[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i1.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\");\n return NAN;\n }\n else {\n if (!cosmo->computed_growth){\n *status = CCL_ERROR_GROWTH_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_growth_factor(): growth factor splines have not been precomputed!\");\n return NAN;\n }\n if (*status != CCL_ERROR_NOT_IMPLEMENTED) {\n double D;\n int gslstatus = gsl_spline_eval_e(cosmo->data.growth, a, NULL, &D);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_growth_factor():\");\n *status |= gslstatus;\n ccl_cosmology_set_status_message(\n cosmo, \"ccl_background.c: ccl_growth_factor(): Scale factor outside interpolation range.\");\n return NAN;\n }\n return D;\n }\n else {\n return NAN;\n }\n }\n}\n\nvoid ccl_growth_factors(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; icomputed_growth) {\n *status = CCL_ERROR_GROWTH_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_growth_factor_unnorm(): growth factor splines have not been precomputed!\");\n }\n\n if (*status != CCL_ERROR_NOT_IMPLEMENTED) {\n return cosmo->data.growth0 * ccl_growth_factor(cosmo, a, status);\n } else {\n return NAN;\n }\n}\n\nvoid ccl_growth_factors_unnorm(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i1.) {\n *status = CCL_ERROR_COMPUTECHI;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\\n\");\n return NAN;\n } else {\n if (!cosmo->computed_growth) {\n *status = CCL_ERROR_GROWTH_INIT;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_background.c: ccl_growth_rate(): growth rate splines have not been precomputed!\");\n }\n if(*status != CCL_ERROR_NOT_IMPLEMENTED) {\n double g;\n int gslstatus = gsl_spline_eval_e(cosmo->data.fgrowth, a, NULL ,&g);\n if(gslstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(gslstatus, \"ccl_background.c: ccl_growth_rate():\");\n *status |= gslstatus;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_growth_rate(): Scale factor outside interpolation range.\\n\");\n return NAN;\n }\n return g;\n } else {\n return NAN;\n }\n }\n}\n\nvoid ccl_growth_rates(ccl_cosmology * cosmo, int na, double a[], double output[], int * status)\n{\n int _status;\n\n for (int i=0; i\n#include \n#include \n#include \n#include \n\n/* The F distribution has the form\n\n p(x) dx = (nu1^(nu1/2) nu2^(nu2/2) Gamma((nu1 + nu2)/2) /\n Gamma(nu1/2) Gamma(nu2/2)) *\n x^(nu1/2 - 1) (nu2 + nu1 * x)^(-nu1/2 -nu2/2) dx\n\n The method used here is the one described in Knuth */\n\ndouble\ngsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2)\n{\n\n double Y1 = gsl_ran_gamma (r, nu1 / 2, 2.0);\n double Y2 = gsl_ran_gamma (r, nu2 / 2, 2.0);\n\n double f = (Y1 * nu2) / (Y2 * nu1);\n\n return f;\n}\n\ndouble\ngsl_ran_fdist_pdf (const double x, const double nu1, const double nu2)\n{\n if (x < 0)\n {\n return 0 ;\n }\n else\n {\n double p;\n double lglg = (nu1 / 2) * log (nu1) + (nu2 / 2) * log (nu2) ;\n\n double lg12 = gsl_sf_lngamma ((nu1 + nu2) / 2);\n double lg1 = gsl_sf_lngamma (nu1 / 2);\n double lg2 = gsl_sf_lngamma (nu2 / 2);\n \n p = exp (lglg + lg12 - lg1 - lg2)\n\t* pow (x, nu1 / 2 - 1) * pow (nu2 + nu1 * x, -nu1 / 2 - nu2 / 2);\n \n return p;\n }\n}\n", "meta": {"hexsha": "ef532fffc747278982f2f7054d07472f36cbf5c1", "size": 1907, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/fdist.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/randist/fdist.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/randist/fdist.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.0441176471, "max_line_length": 72, "alphanum_fraction": 0.6345044573, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7905303112671294, "lm_q1q2_score": 0.663835151674841}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble interpolate_integral(interp_info *interp, double x_lo, double x_hi) {\n double x_lo_interp;\n double x_hi_interp;\n double x_lo_tmp;\n double x_hi_tmp;\n double x_min;\n double x_max;\n double y_x_min;\n double y_x_max;\n double r_val;\n double alpha;\n int flag_error = GBP_FALSE;\n\n x_min = ((interp_info *)interp)->x[0];\n x_max = ((interp_info *)interp)->x[((interp_info *)interp)->n - 1];\n y_x_min = ((interp_info *)interp)->y[0];\n y_x_max = ((interp_info *)interp)->y[((interp_info *)interp)->n - 1];\n\n r_val = 0.;\n x_lo_interp = x_lo;\n x_hi_interp = x_hi;\n\n if(x_hi > x_lo) {\n // Extrapolate integral to low-x assuming dI prop. to x^alpha\n if(x_lo < x_min) {\n x_lo_tmp = x_lo;\n x_hi_tmp = GBP_MIN(x_hi, x_min);\n alpha = interpolate_derivative(interp, ((interp_info *)interp)->x[0]);\n if(alpha < -1. && x_lo_tmp * x_hi_tmp == 0.) {\n fprintf(stderr, \"ERROR: integration extrapolation to low-x is divergent! (alpha=%lf)\\n\", alpha);\n flag_error = GBP_TRUE;\n } else\n r_val += (y_x_min / (alpha + 1.)) * (pow(x_hi_tmp / x_min, alpha + 1.) - pow(x_lo_tmp / x_min, alpha + 1.));\n x_lo_interp = x_min;\n }\n\n // Extrapolate integral to high-x assuming dI prop. to x^alpha\n if(x_hi > x_max) {\n x_lo_tmp = GBP_MAX(x_max, x_lo);\n x_hi_tmp = x_hi;\n alpha = interpolate_derivative(interp, ((interp_info *)interp)->x[((interp_info *)interp)->n - 1]);\n if(alpha < 0. && x_lo_tmp * x_hi_tmp == 0.) {\n fprintf(stderr, \"ERROR: integration extrapolation to high-x is divergent! (alpha=%lf)\\n\", alpha);\n flag_error = GBP_TRUE;\n } else\n r_val += (y_x_min / (alpha + 1.)) * (pow(x_hi_tmp / x_min, alpha + 1.) - pow(x_lo_tmp / x_min, alpha + 1.));\n x_hi_interp = x_max;\n }\n\n r_val += gsl_interp_eval_integ(((interp_info *)interp)->interp,\n ((interp_info *)interp)->x,\n ((interp_info *)interp)->y,\n x_lo_interp,\n x_hi_interp,\n ((interp_info *)interp)->accel);\n }\n return (r_val);\n}\n", "meta": {"hexsha": "7da7dc8de0daae9ce48b63f5c8c655fda9d72a48", "size": 2593, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpInterpolate/interpolate_integral.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/gbpInterpolate/interpolate_integral.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/gbpInterpolate/interpolate_integral.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": 38.1323529412, "max_line_length": 124, "alphanum_fraction": 0.5345160046, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6638328896949623}} {"text": "/* randist/gauss.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006 James Theiler, Brian Gough\n * Copyright (C) 2006 Charles Karney\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* Of the two methods provided below, I think the Polar method is more\n * efficient, but only when you are actually producing two random\n * deviates. We don't produce two, because then we'd have to save one\n * in a static variable for the next call, and that would screws up\n * re-entrant or threaded code, so we only produce one. This makes\n * the Ratio method suddenly more appealing.\n *\n * [Added by Charles Karney] We use Leva's implementation of the Ratio\n * method which avoids calling log() nearly all the time and makes the\n * Ratio method faster than the Polar method (when it produces just one\n * result per call). Timing per call (gcc -O2 on 866MHz Pentium,\n * average over 10^8 calls)\n *\n * Polar method: 660 ns\n * Ratio method: 368 ns\n *\n */\n\n/* Polar (Box-Mueller) method; See Knuth v2, 3rd ed, p122 */\n\ndouble\ngsl_ran_gaussian (const gsl_rng * r, const double sigma)\n{\n double x, y, r2;\n\n do\n {\n /* choose x,y in uniform square (-1,-1) to (+1,+1) */\n x = -1 + 2 * gsl_rng_uniform_pos (r);\n y = -1 + 2 * gsl_rng_uniform_pos (r);\n\n /* see if it is in the unit circle */\n r2 = x * x + y * y;\n }\n while (r2 > 1.0 || r2 == 0);\n\n /* Box-Muller transform */\n return sigma * y * sqrt (-2.0 * log (r2) / r2);\n}\n\n/* Ratio method (Kinderman-Monahan); see Knuth v2, 3rd ed, p130.\n * K+M, ACM Trans Math Software 3 (1977) 257-260.\n *\n * [Added by Charles Karney] This is an implementation of Leva's\n * modifications to the original K+M method; see:\n * J. L. Leva, ACM Trans Math Software 18 (1992) 449-453 and 454-455. */\n\ndouble\ngsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma)\n{\n double u, v, x, y, Q;\n const double s = 0.449871; /* Constants from Leva */\n const double t = -0.386595;\n const double a = 0.19600;\n const double b = 0.25472;\n const double r1 = 0.27597;\n const double r2 = 0.27846;\n\n do /* This loop is executed 1.369 times on average */\n {\n /* Generate a point P = (u, v) uniform in a rectangle enclosing\n the K+M region v^2 <= - 4 u^2 log(u). */\n\n /* u in (0, 1] to avoid singularity at u = 0 */\n u = 1 - gsl_rng_uniform (r);\n\n /* v is in the asymmetric interval [-0.5, 0.5). However v = -0.5\n is rejected in the last part of the while clause. The\n resulting normal deviate is strictly symmetric about 0\n (provided that v is symmetric once v = -0.5 is excluded). */\n v = gsl_rng_uniform (r) - 0.5;\n\n /* Constant 1.7156 > sqrt(8/e) (for accuracy); but not by too\n much (for efficiency). */\n v *= 1.7156;\n\n /* Compute Leva's quadratic form Q */\n x = u - s;\n y = fabs (v) - t;\n Q = x * x + y * (a * y - b * x);\n\n /* Accept P if Q < r1 (Leva) */\n /* Reject P if Q > r2 (Leva) */\n /* Accept if v^2 <= -4 u^2 log(u) (K+M) */\n /* This final test is executed 0.012 times on average. */\n }\n while (Q >= r1 && (Q > r2 || v * v > -4 * u * u * log (u)));\n\n return sigma * (v / u); /* Return slope */\n}\n\ndouble\ngsl_ran_gaussian_pdf (const double x, const double sigma)\n{\n double u = x / fabs (sigma);\n double p = (1 / (sqrt (2 * M_PI) * fabs (sigma))) * exp (-u * u / 2);\n return p;\n}\n\ndouble\ngsl_ran_ugaussian (const gsl_rng * r)\n{\n return gsl_ran_gaussian (r, 1.0);\n}\n\ndouble\ngsl_ran_ugaussian_ratio_method (const gsl_rng * r)\n{\n return gsl_ran_gaussian_ratio_method (r, 1.0);\n}\n\ndouble\ngsl_ran_ugaussian_pdf (const double x)\n{\n return gsl_ran_gaussian_pdf (x, 1.0);\n}\n\n", "meta": {"hexsha": "2ceb80487501a49b406d6c75046fc963d0573484", "size": 4505, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/gauss.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/gauss.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/gauss.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.2847222222, "max_line_length": 83, "alphanum_fraction": 0.6357380688, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6636725452608103}} {"text": "//This is a simple example meant to test your capabilities with basic library linking functionality. All you have to do is return the output to modelica.\n\n\n\n#include \n#include \n\ndouble sf_bessel(double x)\n{\n\tdouble y = gsl_sf_bessel_J0 (x);\n\treturn y;\t\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.\n/*\nint main(void)\n{\n\tdouble x = 5;\n\tdouble a = sf_bessel(x);\n\n\tprintf(\"a = %f \\n\",a);\n\treturn 0;\n}\n*/\n", "meta": {"hexsha": "69788a540169bba9b4255e8f57e7d4839eb268f7", "size": 535, "ext": "c", "lang": "C", "max_stars_repo_path": "Resources/Include/p1.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/p1.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/p1.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": 20.5769230769, "max_line_length": 153, "alphanum_fraction": 0.7158878505, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6630156997616862}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Your function must have the following signature: */\n\nvoid sgemm( int m, int n, float *A, float *C );\n\n/* The benchmarking program */\n\nint main( int argc, char **argv )\n{\n\tsrand(time(NULL));\n\t\n\tif(argc != 3)\n\t{\n\t\tprintf(\"Incorrect number of arguments!\\n\");\n\t\tprintf(\"Usage: ./bench-test M N\\n\");\n\t\texit(0);\n\t}\t\n\n\tint m = atoi(argv[1]);\n\tint n = atoi(argv[2]);\n\t\n\t// Change these values to modify range checking\n\tif(m < 1000 || m > 10000 || n < 32 || n > 10000)\n\t{\n\t\tprintf(\"Dimensions provided are out of the range of matrices we will be testing! Change tester.c to modify range checking.\\n\");\n\t\texit(0);\n\t}\n\n\t/* Allocate and fill 2 random matrices A, C */\n\tfloat *A = (float*) malloc( m * n * sizeof(float) );\n\tfloat *C = (float*) malloc( m * m * sizeof(float) );\n\t\n\tfor( int i = 0; i < m*n; i++ ) A[i] = 2 * drand48() - 1;\n\tfor( int i = 0; i < m*m; i++ ) C[i] = 2 * drand48() - 1;\n\t\n\t/* measure Gflop/s rate; time a sufficiently long sequence of calls to eliminate noise */\n\tdouble Gflop_s, seconds = -1.0;\n\tfor( int n_iterations = 1; seconds < 0.1; n_iterations *= 2 ) \n\t{\n\t\t/* warm-up */\n\t\tsgemm( m, n, A, C );\n\t\t \n\t\t/* measure time */\n\t\tstruct timeval start, end;\n\t\tgettimeofday( &start, NULL );\n\t\tfor( int i = 0; i < n_iterations; i++ )\n\t\t\tsgemm( m,n, A, C );\n\t\tgettimeofday( &end, NULL );\n\t\tseconds = (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);\n\t\t \n\t\t/* compute Gflop/s rate */\n\t\tGflop_s = 2e-9 * n_iterations * m * m * n / seconds;\n\t}\n\t\n\tprintf( \"%d by %d matrix \\t %g Gflop/s\\n\", m, n, Gflop_s );\n\t\n\t/* Ensure that error does not exceed the theoretical error bound */\n\t\t\n\t/* Set initial C to 0 and do matrix multiply of A*B */\n\tmemset( C, 0, sizeof( float ) * m * m );\n\tsgemm( m,n, A, C );\n\t\n\t/* Subtract A*B from C using standard sgemm (note that this should be 0 to within machine roundoff) */\n\tcblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -1, A,m, A,m, 1, C,m );\n\t\n\t/* Subtract the maximum allowed roundoff from each element of C */\n\tfor( int i = 0; i < m*n; i++ ) A[i] = fabs( A[i] );\n\tfor( int i = 0; i < m*m; i++ ) C[i] = fabs( C[i] );\n\tcblas_sgemm( CblasColMajor,CblasNoTrans,CblasTrans, m,m,n, -3.0*FLT_EPSILON*n, A,m, A,m, 1, C,m );\n\t\n\t/* After this test if any element in C is still positive something went wrong in square_sgemm */\n\tfor( int i = 0; i < m * m; i++ )\n\t \tif( C[i] > 0 ) {\n\t\t\tprintf( \"FAILURE: error in matrix multiply exceeds an acceptable margin\\n\" );\n\t\treturn -1;\n\t}\n\t\n\t/* release memory */\n\tfree( C );\n\tfree( A );\n\treturn 0;\n}\n", "meta": {"hexsha": "992ca03b508636d3ca3da57b0eaaf5d5dddde6bb", "size": 2667, "ext": "c", "lang": "C", "max_stars_repo_path": "MatrixMultiply/tester.c", "max_stars_repo_name": "jasonaibrahim/AcademicWorks", "max_stars_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MatrixMultiply/tester.c", "max_issues_repo_name": "jasonaibrahim/AcademicWorks", "max_issues_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MatrixMultiply/tester.c", "max_forks_repo_name": "jasonaibrahim/AcademicWorks", "max_forks_repo_head_hexsha": "4c3e75f48bdafa02fabb551beb6ebf2fea871238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3076923077, "max_line_length": 130, "alphanum_fraction": 0.6070491189, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6624203823368889}} {"text": "static char help[] =\n\"ODE system solver example using TS, but with Jacobian. Sets TS type to\\n\"\n\"implicit Crank-Nicolson. Compare ode.c.\\n\\n\";\n\n#include \n\nextern PetscErrorCode ExactSolution(PetscReal, Vec);\nextern PetscErrorCode FormRHSFunction(TS, PetscReal, Vec, Vec, void*);\nextern PetscErrorCode FormRHSJacobian(TS, PetscReal, Vec, Mat, Mat, void*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n PetscInt steps;\n PetscReal t0 = 0.0, tf = 20.0, dt = 0.1, err;\n Vec y, yexact;\n Mat J;\n TS ts;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\n\n ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr);\n ierr = VecSetSizes(y,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(y); CHKERRQ(ierr);\n ierr = VecDuplicate(y,&yexact); CHKERRQ(ierr);\n\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr);\n\n//STARTMATJ\n ierr = MatCreate(PETSC_COMM_WORLD,&J); CHKERRQ(ierr);\n ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr);\n ierr = MatSetFromOptions(J); CHKERRQ(ierr);\n ierr = MatSetUp(J); CHKERRQ(ierr);\n ierr = TSSetRHSJacobian(ts,J,J,FormRHSJacobian,NULL); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSCN); CHKERRQ(ierr);\n//ENDMATJ\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 ierr = TSSetFromOptions(ts); CHKERRQ(ierr);\n\n // set initial values and solve\n ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);\n ierr = ExactSolution(t0,y); CHKERRQ(ierr);\n ierr = TSSolve(ts,y); CHKERRQ(ierr);\n\n // compute error and report\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);\n ierr = ExactSolution(tf,yexact); CHKERRQ(ierr);\n ierr = VecAXPY(y,-1.0,yexact); CHKERRQ(ierr); // y <- y - yexact\n ierr = VecNorm(y,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"error at tf = %.3f with %d steps: |y-y_exact|_inf = %g\\n\",\n tf,steps,err); CHKERRQ(ierr);\n\n MatDestroy(&J);\n VecDestroy(&y); VecDestroy(&yexact); TSDestroy(&ts);\n return PetscFinalize();\n}\n\nPetscErrorCode ExactSolution(PetscReal t, Vec y) {\n PetscReal *ay;\n VecGetArray(y,&ay);\n ay[0] = t - PetscSinReal(t);\n ay[1] = 1.0 - PetscCosReal(t);\n VecRestoreArray(y,&ay);\n return 0;\n}\n\nPetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec y, Vec g,\n void *ptr) {\n const PetscReal *ay;\n PetscReal *ag;\n VecGetArrayRead(y,&ay);\n VecGetArray(g,&ag);\n ag[0] = ay[1]; // = g_1(t,y)\n ag[1] = - ay[0] + t; // = g_2(t,y)\n VecRestoreArrayRead(y,&ay);\n VecRestoreArray(g,&ag);\n return 0;\n}\n\n//STARTJACOBIAN\nPetscErrorCode FormRHSJacobian(TS ts, PetscReal t, Vec y, Mat J, Mat P,\n void *ptr) {\n PetscErrorCode ierr;\n PetscInt row[2] = {0, 1}, col[2] = {0, 1};\n PetscReal v[4] = { 0.0, 1.0,\n -1.0, 0.0};\n ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n if (J != P) {\n ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n }\n return 0;\n}\n//ENDJACOBIAN\n\n", "meta": {"hexsha": "319c5ccf9d7f5711ba64adb7131adb4c1f86d23f", "size": 3619, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/odejac.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/ch5/odejac.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/ch5/odejac.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 34.141509434, "max_line_length": 76, "alphanum_fraction": 0.6465874551, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6614088458460151}} {"text": "#include \n#include \n#include \n#include \n#include \n\n/*\nAdapted from C code from Darren Wilkinson's blog\nhttps://darrenjw.wordpress.com/2011/07/16/gibbs-sampler-in-various-languages-revisited/\nTo build:\ngcc -O3 gibbs_gsl.c -I/usr/local/include -L/usr/local/lib -lgsl -lgslcblas -lm -o gibbs_gsl\nTo run:\ntime ./gibbs_gsl\n*/\n\n/* Arrays xa and ya are passed by reference */\nvoid gibbs(int N, int thin, double **xa, double **ya)\n{\n int i,j;\n gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);\n double x=0;\n double y=0;\n for (i=0;i //printf\n#include //memset\n#include //time\n#include //cblas_scopy, cblas_sscal, cblas_sgemm\n#include //times\n#include //sysconf\n#include //fabsf\n#include //_mm_malloc\n#define ALIGN 16\n\nfloat* gen_matrix(int order, float range){\n float* m = _mm_malloc(order * order * sizeof(float), ALIGN);\n srand(time(NULL));\n for(int i = 0; i < order * order; ++i)\n m[i] = ((float)rand() / (float)(RAND_MAX)) * range;\n return m;\n}\n\nvoid transpose_matrix(float* m, int order){\n for(int i = 0; i < order; ++i)\n for(int j = i; j < order; ++j){\n float tmp = m[i * order + j];\n m[i * order + j] = m[j * order + i];\n m[j * order + i] = tmp;\n }\n}\n\nvoid print_matrix(float* m, int order, FILE* out){\n fprintf(out, \"Order: %d\\n\", order);\n for(int i = 0; i < order; ++i){\n for(int j = 0; j < order; ++j)\n fprintf(out, \"%.4f \", m[i * order + j]);\n fprintf(out, \"\\n\");\n }\n fprintf(out, \"\\n\");\n}\n\nvoid get_matrix_norms(float* m, int order, float* l1_norm, float* max_norm){\n *l1_norm = 0;\n *max_norm = 0;\n for(int i = 0; i < order; ++i){\n float row_sum = 0;\n float col_sum = 0;\n for(int j = 0; j < order; ++j){\n row_sum += fabs(m[i * order + j]);\n col_sum += fabs(m[j * order + i]);\n }\n if(*l1_norm < col_sum)\n *l1_norm = col_sum;\n if(*max_norm < row_sum)\n *max_norm = row_sum;\n }\n}\n\nfloat* get_identity_matrix(int order){\n float* m = _mm_malloc(order * order * sizeof(float), ALIGN);\n memset(m, 0, order * order * sizeof(float));\n for(int i = 0; i < order; ++i)\n m[i * order + i] = 1;\n return m;\n}\n\nfloat* invert_matrix(float* A, int order, int iter_number){\n float* B = _mm_malloc(order * order * sizeof(float), ALIGN);\n cblas_scopy(order * order, A, 1, B, 1);\n transpose_matrix(B, order);\n float l1_norm, max_norm;\n get_matrix_norms(A, order, &l1_norm, &max_norm);\n cblas_sscal(order * order, 1.0 / (l1_norm * max_norm), B, 1);\n float* R = get_identity_matrix(order);\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, -1, B, order, A, order, 1, R, order);\n float* R_1_deg = _mm_malloc(order * order * sizeof(float), ALIGN);\n cblas_scopy(order * order, R, 1, R_1_deg, 1);\n float* tmp = NULL;\n float* inv_A = get_identity_matrix(order);\n for(int i = 0; i < iter_number; ++i){\n tmp = _mm_malloc(order * order * sizeof(float), ALIGN);\n cblas_saxpy(order * order, 1, R, 1, inv_A, 1);\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, 1, R, order, R_1_deg, order, 0, tmp,\n order);\n _mm_free(R);\n R = tmp;\n }\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, order, order, order, 1, inv_A, order, B, order, 0.0, tmp,\n order);\n _mm_free(inv_A);\n inv_A = tmp;\n _mm_free(B);\n _mm_free(R_1_deg);\n return inv_A;\n}\n\nint main(){\n FILE* input = fopen(\"input.txt\", \"r\");\n FILE* output = fopen(\"output.txt\", \"w\");\n int N = 0, M = 0;\n fscanf(input, \"%d%d\", &N, &M);\n float* A = gen_matrix(N, 5.0);\n time_t start_real = time(NULL);\n float* inv_A = invert_matrix(A, N, M);\n time_t finish_real = time(NULL);\n float* rez = _mm_malloc(N * N * sizeof(float), ALIGN);\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, N, N, 1, inv_A, N, A, N, 0, rez, N);\n print_matrix(rez, N, output);\n printf(\"Total real time: %ld sec.\\n\", finish_real - start_real);\n _mm_free(A);\n _mm_free(inv_A);\n _mm_free(rez);\n fclose(input);\n fclose(output);\n return 0;\n}", "meta": {"hexsha": "75fe4a97069673b58d7e329731cf66d1375bd197", "size": 3796, "ext": "c", "lang": "C", "max_stars_repo_path": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_stars_repo_name": "xp10rd/NSU-FIT", "max_stars_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "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": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_issues_repo_name": "xp10rd/NSU-FIT", "max_issues_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "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": "The 2nd course/Computers and devices/laboratory work #7/with_cblas/cblas.c", "max_forks_repo_name": "xp10rd/NSU-FIT", "max_forks_repo_head_hexsha": "2175f07ff325e754a0b5d19d760224af55a0e700", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-29T08:17:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-29T08:17:38.000Z", "avg_line_length": 33.8928571429, "max_line_length": 120, "alphanum_fraction": 0.5692834563, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.660679015472614}} {"text": "/* specfunc/gsl_sf_coupling.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_COUPLING_H__\n#define __GSL_SF_COUPLING_H__\n\n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* 3j Symbols: / ja jb jc \\\n * \\ ma mb mc /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,\n int two_ma, int two_mb, int two_mc,\n\t\t\t gsl_sf_result * result\n\t\t\t );\ndouble gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,\n int two_ma, int two_mb, int two_mc\n );\n\n\n/* 6j Symbols: / ja jb jc \\\n * \\ jd je jf /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n\t\t\t gsl_sf_result * result\n\t\t\t );\ndouble gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf\n );\n\n\n/* 9j Symbols: / ja jb jc \\\n * | jd je jf |\n * \\ jg jh ji /\n *\n * exceptions: GSL_EDOM, GSL_EOVRFLW\n */\nint gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n\t\t\t int two_jg, int two_jh, int two_ji,\n\t\t\t gsl_sf_result * result\n\t\t\t );\ndouble gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,\n int two_jd, int two_je, int two_jf,\n int two_jg, int two_jh, int two_ji\n );\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_COUPLING_H__ */\n", "meta": {"hexsha": "50dd1b881e498ce951d6583e4919be6e0709ade9", "size": 2584, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coupling.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": 29.3636363636, "max_line_length": 72, "alphanum_fraction": 0.625, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6605845342274467}} {"text": "/* roots/newton.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* newton.c -- newton root finding algorithm \n\n This is the classical Newton-Raphson iteration.\n\n x[i+1] = x[i] - f(x[i])/f'(x[i])\n\n*/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"roots.h\"\n\ntypedef struct\n {\n double f, df;\n }\nnewton_state_t;\n\nstatic int newton_init (void * vstate, gsl_function_fdf * fdf, double * root);\nstatic int newton_iterate (void * vstate, gsl_function_fdf * fdf, double * root);\n\nstatic int\nnewton_init (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n newton_state_t * state = (newton_state_t *) vstate;\n\n const double x = *root ;\n\n state->f = GSL_FN_FDF_EVAL_F (fdf, x);\n state->df = GSL_FN_FDF_EVAL_DF (fdf, x) ;\n\n return GSL_SUCCESS;\n\n}\n\nstatic int\nnewton_iterate (void * vstate, gsl_function_fdf * fdf, double * root)\n{\n newton_state_t * state = (newton_state_t *) vstate;\n \n double root_new, f_new, df_new;\n\n if (state->df == 0.0)\n {\n GSL_ERROR(\"derivative is zero\", GSL_EZERODIV);\n }\n\n root_new = *root - (state->f / state->df);\n\n *root = root_new ;\n \n GSL_FN_FDF_EVAL_F_DF(fdf, root_new, &f_new, &df_new);\n\n state->f = f_new ;\n state->df = df_new ;\n\n if (!finite(f_new))\n {\n GSL_ERROR (\"function not continuous\", GSL_EBADFUNC);\n }\n\n if (!finite (df_new))\n {\n GSL_ERROR (\"function not differentiable\", GSL_EBADFUNC);\n }\n \n return GSL_SUCCESS;\n}\n\n\nstatic const gsl_root_fdfsolver_type newton_type =\n{\"newton\",\t\t\t\t/* name */\n sizeof (newton_state_t),\n &newton_init,\n &newton_iterate};\n\nconst gsl_root_fdfsolver_type * gsl_root_fdfsolver_newton = &newton_type;\n", "meta": {"hexsha": "e2df7a700f0bf57fc5bea8e871aa8bfbccb2ee53", "size": 2535, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/roots/newton.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/roots/newton.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/roots/newton.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.691588785, "max_line_length": 81, "alphanum_fraction": 0.6887573964, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6601400527472774}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ccl.h\"\n\n//maths helper function for NFW profile\nstatic double helper_fx(double x){\n double f;\n f = log(1.+x)-x/(1.+x);\n return f;\n}\n\n//cosmo: ccl cosmology object containing cosmological parameters\n//c: halo concentration, needs to be consistent with halo size definition\n//halomass: halo mass\n//massdef_delta: mass definition, overdensity relative to mean matter density\n//a: scale factor\n//r: radii at which to calculate output\n//nr: number of radii for calculation\n//rho_r: stores densities at r\n//returns void\nvoid ccl_halo_profile_nfw(ccl_cosmology *cosmo, double c, double halomass,\n double massdef_delta_m, double a, double *r, int nr,\n double *rho_r, int *status) {\n\n //haloradius: halo radius for mass definition\n //rs: scale radius\n double haloradius, rs;\n\n haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status);\n rs = haloradius/c;\n\n //rhos: NFW density parameter\n double rhos;\n\n rhos = halomass/(4.*M_PI*(rs*rs*rs)*helper_fx(c));\n\n int i;\n double x;\n for(i=0; i < nr; i++) {\n x = r[i]/rs;\n rho_r[i] = rhos/(x*(1.+x)*(1.+x));\n }\n return;\n}\n\n//cosmo: ccl cosmology object containing cosmological parameters\n//c: halo concentration, needs to be consistent with halo size definition\n//halomass: halo mass\n//massdef_delta: mass definition, overdensity relative to mean matter density\n//a: scale factor\n//rp: radius at which to calculate output\n//nr: number of radii for calculation\n//sigma_r: stores surface mass density (integrated along line of sight) at given projected rp\n//returns void\nvoid ccl_projected_halo_profile_nfw(ccl_cosmology *cosmo, double c,\n double halomass, double massdef_delta_m,\n double a, double *rp, int nr, double *sigma_r,\n int *status) {\n\n //haloradius: halo radius for mass definition\n //rs: scale radius\n double haloradius, rs;\n\n haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status);\n rs = haloradius/c;\n\n //rhos: NFW density parameter\n double rhos;\n\n rhos = halomass/(4.*M_PI*(rs*rs*rs)*helper_fx(c));\n\n double x;\n\n int i;\n for(i=0; i < nr; i++){\n\n x = rp[i]/rs;\n if (x==1.){\n sigma_r[i] = 2.*rs*rhos/3.;\n }\n else if (x<1.){\n sigma_r[i] = 2.*rs*rhos*(1.-2.*atanh(sqrt(fabs((1.-x)/(1.+x))))/sqrt(fabs(1.-x*x)))/(x*x-1.);\n }\n else {\n sigma_r[i] = 2.*rs*rhos*(1.-2.*atan(sqrt(fabs((1.-x)/(1.+x))))/sqrt(fabs(1.-x*x)))/(x*x-1.);\n }\n }\n return;\n\n}\n\n//maths helper function assuming NFW approximation\nstatic double helper_solve_cvir(double c, void *rhs_pointer){\n double rhs = *(double*)rhs_pointer;\n return (log(1.+c)-c/(1.+c))/(c*c*c) - rhs;\n}\n\n//solve for cvir from different mass definition iteratively, assuming NFW profile.\nstatic double solve_cvir(ccl_cosmology *cosmo, double rhs, double initial_guess, int *status){\n\n int rootstatus;\n int iter = 0, max_iter = 100;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver *s;\n double cvir;\n double c_lo = 0.1, c_hi = initial_guess*100.;\n gsl_function F;\n\n F.function = &helper_solve_cvir;\n F.params = &rhs;\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc (T);\n if (s != NULL) {\n gsl_root_fsolver_set (s, &F, c_lo, c_hi);\n\n do\n {\n iter++;\n gsl_root_fsolver_iterate (s);\n cvir = gsl_root_fsolver_root (s);\n c_lo = gsl_root_fsolver_x_lower (s);\n c_hi = gsl_root_fsolver_x_upper (s);\n rootstatus = gsl_root_test_interval (c_lo, c_hi, 0, 0.0001);\n }\n while (rootstatus == GSL_CONTINUE && iter < max_iter);\n\n gsl_root_fsolver_free(s);\n\n // Check for errors\n if (rootstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(rootstatus, \"ccl_haloprofile.c: solve_cvir():\");\n *status = CCL_ERROR_PROFILE_ROOT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_haloprofile.c: solve_cvir(): Root finding failure\\n\");\n return NAN;\n } else {\n return cvir;\n }\n }\n else {\n *status = CCL_ERROR_MEMORY;\n return NAN;\n }\n}\n\n// Structure to hold parameters of integrand_einasto\ntypedef struct{\n ccl_cosmology *cosmo;\n double alpha, rs;\n} Int_Einasto_Par;\n\nstatic double integrand_einasto(double r, void *params){\n\n Int_Einasto_Par *p = (Int_Einasto_Par *)params;\n double alpha = p->alpha;\n double rs = p->rs;\n\n return 4.*M_PI*r*r*exp(-2.*(pow(r/rs,alpha)-1)/alpha);\n}\n\n//integrate einasto profile to get normalization of rhos\nstatic double integrate_einasto(ccl_cosmology *cosmo, double R, double alpha, double rs, int *status){\n int qagstatus;\n double result = 0, eresult;\n Int_Einasto_Par ipar;\n gsl_function F;\n gsl_integration_workspace *w = NULL;\n\n w = gsl_integration_workspace_alloc(1000);\n\n if (w == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n // Structure required for the gsl integration\n ipar.cosmo = cosmo;\n ipar.alpha = alpha;\n ipar.rs = rs;\n F.function = &integrand_einasto;\n F.params = &ipar;\n\n // Actually does the integration\n qagstatus = gsl_integration_qag(\n &F, 0, R, 0, 0.0001, 1000, 3, w,\n &result, &eresult);\n\n // Check for errors\n if (qagstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(qagstatus, \"ccl_haloprofile.c: integrate_einasto():\");\n *status = CCL_ERROR_PROFILE_INT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_haloprofile.c: integrate_einasto(): Integration failure\\n\");\n result = NAN;\n }\n }\n\n // Clean up\n gsl_integration_workspace_free(w);\n\n return result;\n}\n\n\n//cosmo: ccl cosmology object containing cosmological parameters\n//c: halo concentration, needs to be consistent with halo size definition\n//halomass: halo mass\n//massdef_delta: mass definition, overdensity relative to mean matter density\n//a: scale factor\n//r: radii at which to calculate output\n//nr: number of radii for calculation\n//rho_r: stores densities at r\n//returns void\nvoid ccl_halo_profile_einasto(ccl_cosmology *cosmo, double c, double halomass,\n double massdef_delta_m, double a, double *r, int nr,\n double *rho_r, int *status) {\n\n //haloradius: halo radius for mass definition\n //rs: scale radius\n double haloradius, rs;\n\n haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status);\n rs = haloradius/c;\n\n\n //nu: peak height, https://arxiv.org/pdf/1401.1216.pdf eqn1\n //alpha: Einasto parameter, https://arxiv.org/pdf/1401.1216.pdf eqn5\n double nu;\n double alpha; //calibrated relation with nu, with virial mass\n double Mvir;\n double Delta_v;\n\n Delta_v = Dv_BryanNorman(cosmo, a, status); //virial definition, if odelta is this, the definition is virial.\n\n if (massdef_delta_mDelta_v-1){ //allow rounding of virial definition\n Mvir = halomass;\n }\n else{\n double rhs; //NFW equation for cvir: f(Rvir/Rs)/f(c)=(Rvir^3*Delta_v)/(R^3*massdef) -> f(cvir)/cvir^3 = rhs\n rhs = (helper_fx(c)*(rs*rs*rs)*Delta_v)/((haloradius*haloradius*haloradius)*massdef_delta_m);\n Mvir = halomass*helper_fx(solve_cvir(cosmo, rhs, c, status))/helper_fx(c);\n }\n\n nu = 1.686/ccl_sigmaM(cosmo, log10(Mvir), a, status); //delta_c_Tinker\n alpha = 0.155 + 0.0095*nu*nu;\n\n //rhos: scale density\n double rhos;\n\n rhos = halomass/integrate_einasto(cosmo, haloradius, alpha, rs, status); //normalize\n\n int i;\n for(i=0; i < nr; i++) {\n rho_r[i] = rhos*exp(-2.*(pow(r[i]/rs,alpha)-1.)/alpha);\n }\n\n return;\n\n}\n\n// Structure to hold parameters of integrand_hernquist\ntypedef struct{\n ccl_cosmology *cosmo;\n double rs;\n} Int_Hernquist_Par;\n\nstatic double integrand_hernquist(double r, void *params){\n\n Int_Hernquist_Par *p = (Int_Hernquist_Par *)params;\n double rs = p->rs;\n\n return 4.*M_PI*r*r/((r/rs)*(1.+r/rs)*(1.+r/rs)*(1.+r/rs));\n}\n\n//integrate hernquist profile to get normalization of rhos\nstatic double integrate_hernquist(ccl_cosmology *cosmo, double R, double rs, int *status){\n int qagstatus;\n double result = 0, eresult;\n Int_Hernquist_Par ipar;\n gsl_function F;\n gsl_integration_workspace *w = NULL;\n\n w = gsl_integration_workspace_alloc(1000);\n\n if (w == NULL) {\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0) {\n // Structure required for the gsl integration\n ipar.cosmo = cosmo;\n ipar.rs = rs;\n F.function = &integrand_hernquist;\n F.params = &ipar;\n\n // Actually does the integration\n qagstatus = gsl_integration_qag(\n &F, 0, R, 0, 0.0001, 1000, 3, w,\n &result, &eresult);\n\n // Check for errors\n if (qagstatus != GSL_SUCCESS) {\n ccl_raise_gsl_warning(qagstatus, \"ccl_haloprofile.c: integrate_hernquist():\");\n *status = CCL_ERROR_PROFILE_INT;\n ccl_cosmology_set_status_message(cosmo, \"ccl_haloprofile.c: integrate_hernquist(): Integration failure\\n\");\n result = NAN;\n }\n }\n\n // Clean up\n gsl_integration_workspace_free(w);\n\n return result;\n}\n\n\n//cosmo: ccl cosmology object containing cosmological parameters\n//c: halo concentration, needs to be consistent with halo size definition\n//halomass: halo mass\n//massdef_delta: mass definition, overdensity relative to mean matter density\n//a: scale factor\n//r: radii at which to calculate output\n//nr: number of radii for calculation\n//rho_r: stores densities at r\n//returns void\nvoid ccl_halo_profile_hernquist(ccl_cosmology *cosmo, double c, double halomass,\n double massdef_delta_m, double a, double *r, int nr,\n double *rho_r, int *status) {\n\n //haloradius: halo radius for mass definition\n //rs: scale radius\n double haloradius, rs;\n\n haloradius = r_delta(cosmo, halomass, a, massdef_delta_m, status);\n rs = haloradius/c;\n\n //rhos: scale density\n double rhos;\n\n rhos = halomass/integrate_hernquist(cosmo, haloradius, rs, status); //normalize\n\n int i;\n double x;\n for(i=0; i < nr; i++) {\n x = r[i]/rs;\n rho_r[i] = rhos/(x*pow((1.+x),3));\n }\n\n return;\n\n}\n", "meta": {"hexsha": "83a59b2b4c39d696043fd33b8d247548d6d0b334", "size": 10557, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_haloprofile.c", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_haloprofile.c", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_haloprofile.c", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 29.654494382, "max_line_length": 115, "alphanum_fraction": 0.6414701146, "num_tokens": 3047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6597433347540027}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ellipsoid/ellipsoid.h\"\n\nint testCoordinateTransform()\n{\n //Verify that the ellipsoidal to Cartesian transformation is a bijection\n //the tolerance is 10 significant figures\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, 3.0, 2.0, 1.0, 32);\n \n double relErrorX, relErrorY, relErrorZ;\n\n //loop over octants\n for(int sx=-1; sx<=1; sx+=2) { //sx = [-1,1]\n for(int sy=-1; sy<=1; sy+=2) { //sy = [-1,1]\n for(int sz=-1; sz<=1; sz+=2) { //sz = [-1,1]\n\t//loop over brick in cartesian space\n\tfor(double x=4; x<5+tol; x+=1.5) {\n\t for(double y=4; y<5+tol; y+=1.5) {\n\t for(double z=4; z<5+tol; z+=1.5) {\n\t Point temp = { .x1 = sx*x, .x2 = sy*y, .x3 = sz*z };\n\t cartesianToEllipsoidal(&e, &temp);\n\t ellipsoidToCartesian(&e, &temp);\n\t relErrorX = fabs(sx*x - temp.x1)/x;\n\t relErrorY = fabs(sy*y - temp.x2)/y;\n\t relErrorZ = fabs(sz*z - temp.x3)/z;\n\t //check error\n\t if( relErrorX > tol ||\n\t\t relErrorY > tol ||\n\t\t relErrorZ > tol) {\n\t\tprintf(\"testCoordinateTransform failed\\n\");\n\t\tprintf(\"relative error(x): %16.16f\\n\", relErrorX);\n\t\tprintf(\"relative error(y): %16.16f\\n\", relErrorY);\n\t\tprintf(\"relative error(z): %16.16f\\n\", relErrorZ);\n\t\treturn 0;\n\t }\n\t }\n\t }\n\t}\n }\n }\n }\n return 1;\n}\n\nint testLameType()\n{\n\n static char formula1[18] = \"K^0_1 L^0_1 M^0_1\";\n static char formula2[30] = \"K^0_2 K^1_2 L^0_2 M^0_2 N^0_2\";\n static char formula3[66] = \"K^0_5 K^1_5 K^2_5 L^0_5 L^1_5 L^2_5 M^0_5 M^1_5 M^2_5 N^0_5 N^1_5\";\n\n char **checks = (char**) malloc(sizeof(char*)*3);\n checks[0] = (char*) malloc(sizeof(char)*17);\n checks[1] = (char*) malloc(sizeof(char)*29);\n checks[2] = (char*) malloc(sizeof(char)*65);\n\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, 3.0, 2.0, 1.0, 32);\n int index[3] = { 1, 2, 5 };\n int k;\n int n;\n for(int i=0; i<3; ++i) {\n n = index[i];\n for(int p=0; p < 2*n + 1; ++p) {\n k = p*6;\n checks[i][k] = getLameTypeT(n, p);\n checks[i][k+1] = '^';\n checks[i][k+2] = getLameTypeTp(n, p) + '0';\n checks[i][k+3] = '_';\n checks[i][k+4] = n + '0';\n if( p != 2*n )\n\tchecks[i][k+5] = ' ';\n }\n }\n //check first string\n for(int i=0; i < 17; ++i) {\n if(checks[0][i] != formula1[i]) {\n return 0;\n }\n }\n //check second string\n for(int i=0; i < 29; ++i) {\n if(checks[1][i] != formula2[i]) {\n return 0;\n }\n }\n //check first string\n for(int i=0; i < 65; ++i) {\n if(checks[2][i] != formula3[i]) {\n return 0;\n }\n }\n free(checks[0]);\n free(checks[1]);\n free(checks[2]);\n free(checks);\n return 1;\n}\n\nint testI()\n{\n //Using results from Dassios, test the computation of I^p_n for n = 0, 1, 2\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, 3.0, 2.0, 1.0, 32);\n double a = e.a;\n double b = e.b;\n double c = e.c;\n double h = e.h;\n double k = e.k;\n double l = a;\n double rootSum = sqrt((a*a*a*a - b*b*c*c) + (b*b*b*b - a*a*c*c) + (c*c*c*c - a*a*b*b));\n double DassiosLambda = (1/3.)*(a*a + b*b + c*c) + (1/3.)*rootSum;\n double DassiosLambdaPrime = (1/3.)*(a*a + b*b + c*c) - (1/3.)*rootSum;\n\n double errors[18];\n int derror[18] = { 1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7, 8, 9, 10, 11, 12, 13 };\n int ecount = 0;\n //Dassios D1 error\n double lhs = 3 * (DassiosLambda + DassiosLambdaPrime);\n double rhs = 2 * (a*a + b*b + c*c);\n errors[ecount] = fabs(lhs - rhs); ecount++;\n //Dassios D2 error\n lhs = 3 * DassiosLambda * DassiosLambdaPrime;\n rhs = a*a*b*b + a*a*c*c + b*b*c*c;\n errors[ecount] = fabs(lhs - rhs); ecount ++;\n //Dassios D3 error\n lhs = ((-1)*(b*b - c*c)*(DassiosLambda - a*a)) + (k*k*(DassiosLambda - b*b)) + (-h*h*(DassiosLambda - c*c));\n rhs = ((-1)*(b*b - c*c)*(DassiosLambdaPrime - a*a)) + (k*k*(DassiosLambdaPrime - b*b)) + (-h*h*(DassiosLambdaPrime - c*c));\n errors[ecount] = fabs(lhs-0); ecount++;\n errors[ecount ] = fabs(rhs-0); ecount++;\n //Dassios D4 error\n lhs = (-a*a*(b*b - c*c)*(DassiosLambda - a*a)) + (b*b*k*k*(DassiosLambda - b*b)) + (-c*c*h*h*(DassiosLambda - c*c));\n rhs = (-a*a*(b*b - c*c)*(DassiosLambdaPrime - a*a)) + (b*b*k*k*(DassiosLambdaPrime - b*b)) + (-c*c*h*h*(DassiosLambdaPrime - c*c));\n double analytical = h*h*k*k*(b*b - c*c);\n errors[ecount] = fabs(lhs - analytical); ecount++;\n errors[ecount] = fabs(rhs - analytical); ecount++;\n //Dassios D5 error\n double alpha[3] = { a, b, c };\n lhs = 0;\n rhs = 0;\n for(int i=0; i<3; ++i) {\n lhs += alpha[i]*alpha[i]/(alpha[i]*alpha[i] - DassiosLambda);\n rhs += alpha[i]*alpha[i]/(alpha[i]*alpha[i] - DassiosLambdaPrime);\n }\n errors[ecount] = fabs(lhs - 3); ecount++;\n errors[ecount] = fabs(rhs - 3); ecount++;\n //Dassios D6 error\n double anal1 = h*h*k*k*(b*b - c*c);\n double num1 = 3*(b*b - c*c)*(DassiosLambda - a*a)*(DassiosLambdaPrime - a*a);\n double anal2 = -h*h*k*k*(b*b - c*c);\n double num2 = 3*k*k*(DassiosLambda - b*b)*(DassiosLambdaPrime - b*b);\n double anal3 = h*h*k*k*(b*b - c*c);\n double num3 = 3*h*h*(DassiosLambda - c*c)*(DassiosLambdaPrime - c*c);\n errors[ecount] = fabs(num1 - anal1); ecount++;\n errors[ecount] = fabs(num2 - anal2); ecount++;\n errors[ecount] = fabs(num3 - anal3); ecount++;\n \n //Calculate I^p_n\n int nmax = 2;\n int Isize = 0;\n for(int n=0; n < nmax+1; ++n) {\n for(int p=0; p < 2*n+1; ++p) {\n Isize++;\n }\n }\n double *Ival = (double*) malloc(sizeof(double)*Isize);\n int i=0;\n for(int n=0; n < nmax+1; ++n) {\n for(int p=0; p < 2*n+1; ++p) {\n calcI(&e, n, p, l, 1, 1, Ival+i); //Ival[i] = calcI(&e, n, p, l, 1, 1);\n i++;\n }\n }\n \n //Dassios D7: their h_3 = our h and their h_2 = our k\n double analyticalSumTest1 = 1.0/(l*sqrt(l*l - h*h)*sqrt(l*l - k*k));\n double numericalSumTest1 = 0;\n for(int k=1; k<4; ++k) {\n numericalSumTest1 += Ival[k];\n }\n errors[ecount] = fabs(analyticalSumTest1 - numericalSumTest1); ecount++;\n \n //Dassios D8: their alpha1 = our a, their alpha2 = our b, their alpha3 = our c\n double analyticalSumTest2 = Ival[0] - (l*l - a*a)/(l*sqrt(l*l - h*h)*sqrt(l*l - k*k));\n double numericalSumTest2 = a*a*Ival[1] + b*b*Ival[2] + c*c*Ival[3];\n errors[ecount] = fabs(analyticalSumTest2 - numericalSumTest2); ecount++;\n //Dassios D9: their Lambda = our DassiosLambda, their LambdaPrime = our DassiosLambdaPrime\n double analyticalSumTest3 = 1.0/(2.0*(DassiosLambda - a*a + l*l)*l*sqrt(l*l - h*h)*sqrt(l*l - k*k)) - (1.0/2.0)*(Ival[1]/(DassiosLambda - a*a) + Ival[2]/(DassiosLambda - b*b) + Ival[3]/(DassiosLambda - c*c));\n double numericalSumTest3 = Ival[4];\n errors[ecount] = fabs(analyticalSumTest3 - numericalSumTest3); ecount++;\n //Dassios D10: their Lambda = our DassiosLambda, their LambdaPrime = our DassiosLambdaPrime\n double analyticalSumTest4 = 1.0/(2.0*(DassiosLambdaPrime - a*a + l*l)*l*sqrt(l*l - h*h)*sqrt(l*l - k*k)) - (1.0/2.0)*(Ival[1]/(DassiosLambdaPrime - a*a) + Ival[2]/(DassiosLambdaPrime - b*b) + Ival[3]/(DassiosLambdaPrime - c*c));\n double numericalSumTest4 = Ival[5];\n errors[ecount] = fabs(analyticalSumTest4 - numericalSumTest4); ecount++;\n //Dassios D11: their h1*h1 = our (b*b - c*c)\n double analyticalSumTest5 = (1.0/(h*h)) * (Ival[2] - Ival[1]);\n double numericalSumTest5 = Ival[6];\n errors[ecount] = fabs(analyticalSumTest5 - numericalSumTest5); ecount++;\n //Dassios D12: their h1*h1 = our (b*b - c*c)\n double analyticalSumTest6 = (1.0/(k*k)) * (Ival[3] - Ival[1]);\n double numericalSumTest6 = Ival[7];\n errors[ecount] = fabs(analyticalSumTest6 - numericalSumTest6); ecount++;\n //Dassios D13: their h1*h1 = our (b*b - c*c)\n double analyticalSumTest7 = (1.0/(b*b - c*c)) * (Ival[3] - Ival[2]);\n double numericalSumTest7 = Ival[8];\n errors[ecount] = fabs(analyticalSumTest7 - numericalSumTest7); ecount++;\n \n //checking errors\n for(int i=0; i < 18; ++i) {\n if(errors[i] > tol) {\n printf(\"Dassios D%d failed with error %8.8e\\n\", derror[i], errors[i]);\n free(Ival);\n return 0;\n }\n }\n \n free(Ival);\n return 1;\n}\n\nint testNormalization()\n{\n //Check calculated \\gamma^p_n against analytic results for n = 0, 1, 2\n double a = 3.0;\n double b = 2.0;\n double c = 1.0;\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, a, b, c, 32);\n //Dassios (B14)\n double firstTerm = (a*a + b*b + c*c)/3.0;\n double secondTerm = sqrt((a*a*a*a - b*b*c*c) + (b*b*b*b - a*a*c*c) + (c*c*c*c - a*a*b*b))/3.0;\n double LambdaD = firstTerm + secondTerm;\n double LambdaDprime = firstTerm - secondTerm;\n //Dassios (B16)-(B20)\n double hx = sqrt(b*b - c*c);\n double hy = e.k;\n double hz = e.h;\n double analytic[9] = { 4*PETSC_PI,\n\t\t\t 4*PETSC_PI/3 * hy*hy*hz*hz,\n\t\t\t 4*PETSC_PI/3 * hx*hx*hz*hz,\n\t\t\t 4*PETSC_PI/3 * hx*hx*hy*hy,\n\t\t\t -8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaD - a*a)*(LambdaD - b*b)*(LambdaD - c*c),\n\t\t\t 8*PETSC_PI/5 * (LambdaD - LambdaDprime)*(LambdaDprime - a*a)*(LambdaDprime - b*b)*(LambdaDprime - c*c),\n\t\t\t 4*PETSC_PI/15 * hx*hx*hy*hy*hz*hz*hz*hz,\n\t\t\t 4*PETSC_PI/15 * hx*hx*hy*hy*hy*hy*hz*hz,\n\t\t\t 4*PETSC_PI/15 * hx*hx*hx*hx*hy*hy*hz*hz };\n printf(\"analytic[0] = %4.4e\\n\", analytic[0]);\n printf(\"analytic[1] = %4.4e\\n\", analytic[1]);\n double value, estimate, error;\n int counter = 0;\n for(int n=0; n<3; ++n) {\n for(int p=0; p<2*n+1; ++p) {\n value = analytic[counter];\n calcNormalization(&e, n, p, &estimate);\n error = estimate - value;\n if(fabs(error) > tol) {\n\tprintf(\"testnormalization failed iteration %d at (n,p) = (%d,%d) with error %8.8e\\n\", counter, n, p, fabs(error));\n\treturn 0;\n }\n counter++;\n }\n }\n return 1;\n\n}\n\nvoid testfunc(mpfr_t *x, mpfr_t *val, FuncInfo4 *ctx)\n{\n double a2 = (*ctx).a2;\n double b2 = (*ctx).b2;\n double c2 = (*ctx).c2;\n double botVar = (*ctx).botVar;\n \n mpfr_t temp, s;\n mpfr_init2(temp, mpfr_get_prec(*x));\n mpfr_init2(s , mpfr_get_prec(*x));\n //change of variables\n //s = (1-x)/x\n mpfr_d_sub(s, 1.0, *x, MPFR_RNDZ);\n mpfr_div(s, s, *x, MPFR_RNDN);\n\n mpfr_add_d(temp, s, a2, MPFR_RNDN);\n mpfr_add_d(*val, s, b2, MPFR_RNDN);\n mpfr_mul(*val, *val, temp, MPFR_RNDN);\n mpfr_add_d(temp, s, c2, MPFR_RNDN);\n mpfr_mul(*val, *val, temp, MPFR_RNDN);\n mpfr_sqrt(*val, *val, MPFR_RNDN);\n \n mpfr_add_d(temp, s, botVar, MPFR_RNDN);\n mpfr_mul(*val, *val, temp, MPFR_RNDN);\n \n mpfr_d_div(*val, 1.0, *val, MPFR_RNDN);\n\n //multiply by dt = ds * (1+t)^2\n mpfr_add_d(temp, s, 1.0, MPFR_RNDN);\n mpfr_mul(temp, temp, temp, MPFR_RNDN);\n mpfr_mul(*val, *val, temp, MPFR_RNDN);\n //mpfr_clears(temp, s, NULL);\n}\n\nint testSurfaceOperatorEigenvalues()\n{\n EllipsoidalSystem e;\n double a = 3.0;\n double b = 2.0;\n double c = 1.0;\n initEllipsoidalSystem(&e, a, b, c, 32);\n double l = a;\n int n = 1;\n double analytic[3];\n mpfr_t integral;\n\n\n mpfr_t mpfrzero, mpfrone;\n mpfr_inits(mpfrzero, mpfrone, integral, NULL);\n mpfr_set_d(mpfrzero, 0.0, MPFR_RNDN);\n mpfr_set_d(mpfrone, 1.0, MPFR_RNDN);\n\n //Integrals are from Ritter, need to transform integrals to finite interval\n FuncInfo4 ctx = { &e, a*a, b*b, c*c, a*a };\n integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) testfunc, &e, mpfrzero, mpfrone, 14, &integral, &ctx);\n analytic[0] = (a*b*c * mpfr_get_d(integral, MPFR_RNDN) - 1.0)/2.0;\n ctx.botVar = b*b;\n integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) testfunc, &e, mpfrzero, mpfrone, 14, &integral, &ctx);\n analytic[1] = (a*b*c * mpfr_get_d(integral, MPFR_RNDN) - 1.0)/2.0;\n ctx.botVar = c*c;\n integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) testfunc, &e, mpfrzero, mpfrone, 14, &integral, &ctx);\n analytic[2] = (a*b*c * mpfr_get_d(integral, MPFR_RNDN) - 1.0)/2.0;\n\n\n double *ev = (double*) malloc(sizeof(double)*(3));\n for(int p=0; p < 3; ++p)\n calcSurfaceOperatorEigenvalues(&e, n, p, l, 1, 1, ev+p); //ev[p] = calcSurfaceOperatorEigenvalues(&e, n, p, l, 1, 1);\n for(int p=0; p < 3; ++p) {\n if(fabs(ev[p] - analytic[p]) > tol) {\n printf(\"analytic (%8.8e) doesn't match numerical (%8.8e), error = (%8.8e) for integral %d\\n\", analytic[p], ev[p], fabs(ev[p] - analytic[p]), p+1);\n return 0;\n }\n }\n mpfr_clears(mpfrzero, mpfrone, integral, NULL);\n free(ev);\n return 1;\n\n}\n\nint compareIntegration()\n{\n\n //int n, p given in calcNormalization\n int n = 1;\n int p = 1;\n\n int digits = 32;\n\n //set up ellipsoidal system\n EllipsoidalSystem e;\n double xA = 3.0;\n double yB = 2.0;\n double zC = 1.0;\n initEllipsoidalSystem(&e, xA, yB, zC, digits);\n \n \n mpfr_t bound_a, bound_b; \n mpfr_inits2(4*digits, bound_a, bound_b, NULL);\n \n FuncInfo2 ctx1 = { .e = &e, .n = n, .p = p, .numeratorType = 0, .denomSign = 1 };\n\n mpfr_t a, b, c;\n mpfr_inits(a, b, c, NULL);\n double integralMPFR, integralMidpoint;\n\n integrateMPFR((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, &e, e.hp_h, e.hp_k, 14, &integralMPFR, &ctx1);\n integrateMidpoint((PetscErrorCode (*)(mpfr_t*, mpfr_t*, void*)) normFunction1, e.hp_h, e.hp_k, 10, &integralMidpoint, &ctx1);\n\n\n printf(\"MPFR integral is: %15.15f\\n\", integralMPFR);\n printf(\"Midpoint integral is: %15.15f\\n\", integralMidpoint);\n printf(\"oh wow\\n\");\n\n mpfr_clears(a, b, c, NULL);\n \n return 0;\n}\n\nint main(int argc, char **argv)\n{\n mpfr_set_default_prec(4*64);\n /*\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, 3.0, 2.0, 1.0);\n printf(\"h: %15.15f\\nh2: %15.15f\\nk: %15.15f\\nk2: %15.15f\\n\", e.h, e.h2, e.k, e.k2);\n int n = 1;\n int p = 1;\n double l = 1.0;\n \n //printf(\"calcLame(1, 1, 1.0) = %15.15f\\n\", calcLame(&e, 1, 1, 1.0));\n \n printf(\"calcNormalization(%d, %d, %15.15f) = %15.15f\\n\", n, p, l, calcNormalization(&e, n, p));\n */\n \n if(testCoordinateTransform())\n printf(\"testCoordinateTransform passed\\n\");\n else\n printf(\"testCoordinateTransform failed\\n\");\n if(testLameType())\n printf(\"testLameType passed\\n\");\n else\n printf(\"testLameType failed\\n\");\n if(testI())\n printf(\"testI passed\\n\");\n else\n printf(\"testI failed\\n\"); \n if(testNormalization())\n printf(\"testNormalization passed\\n\");\n else\n printf(\"testNormalization failed\\n\");\n if(testSurfaceOperatorEigenvalues())\n printf(\"testSurfaceOperatorEigenvalues passed\\n\");\n else\n printf(\"testSurfaceOperatorEigenvalues failed\\n\");\n\n //compareIntegration();\n \n /* \n double h = .1;\n mpfr_t x, val;\n EllipsoidalSystem e;\n initEllipsoidalSystem(&e, 3.0, 2.0, 1.0);\n FuncInfo2 ctx1 = { .e = &e, .n = 1, .p = 2, .numeratorType = 0, .denomSign = -1 };\n mpfr_inits2(4*16, x, val, NULL);\n for(int k=0; k < 10; ++k) {\n mpfr_set_d(x, k*h, MPFR_RNDN);\n normFunction1(&x, &val, &ctx1); \n printf(\"normfunction1(%8.8f) = %15.15f\\n\", k*h, mpfr_get_d(val, MPFR_RNDN));\n }\n */\n return 0;\n}\n", "meta": {"hexsha": "62c66672399d4dcdb06db202399d66e527b3a582", "size": 14768, "ext": "c", "lang": "C", "max_stars_repo_path": "src/testEllipsoid.c", "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_issues_repo_path": "src/testEllipsoid.c", "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/testEllipsoid.c", "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1121076233, "max_line_length": 230, "alphanum_fraction": 0.5947995666, "num_tokens": 5702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6596013504988819}} {"text": "/* poly/gsl_poly.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 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#ifndef __GSL_POLY_H__\n#define __GSL_POLY_H__\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\n/* Evaluate polynomial\n *\n * c[0] + c[1] x + c[2] x^2 + ... + c[len-1] x^(len-1)\n *\n * exceptions: none\n */\n\n/* real polynomial, real x */\nINLINE_DECL double gsl_poly_eval(const double c[], const int len, const double x);\n\n/* real polynomial, complex x */\nINLINE_DECL gsl_complex gsl_poly_complex_eval (const double c [], const int len, const gsl_complex z);\n\n/* complex polynomial, complex x */\nINLINE_DECL gsl_complex gsl_complex_poly_complex_eval (const gsl_complex c [], const int len, const gsl_complex z);\n\nint gsl_poly_eval_derivs(const double c[], const size_t lenc, const double x, double res[], const size_t lenres);\n\n#ifdef HAVE_INLINE\nINLINE_FUN\ndouble \ngsl_poly_eval(const double c[], const int len, const double x)\n{\n int i;\n double ans = c[len-1];\n for(i=len-1; i>0; i--) ans = c[i-1] + x * ans;\n return ans;\n}\n\nINLINE_FUN\ngsl_complex\ngsl_poly_complex_eval(const double c[], const int len, const gsl_complex z)\n{\n int i;\n gsl_complex ans;\n GSL_SET_COMPLEX (&ans, c[len-1], 0.0);\n for(i=len-1; i>0; i--) {\n /* The following three lines are equivalent to\n ans = gsl_complex_add_real (gsl_complex_mul (z, ans), c[i-1]); \n but faster */\n double tmp = c[i-1] + GSL_REAL (z) * GSL_REAL (ans) - GSL_IMAG (z) * GSL_IMAG (ans);\n GSL_SET_IMAG (&ans, GSL_IMAG (z) * GSL_REAL (ans) + GSL_REAL (z) * GSL_IMAG (ans));\n GSL_SET_REAL (&ans, tmp);\n } \n return ans;\n}\n\nINLINE_FUN\ngsl_complex\ngsl_complex_poly_complex_eval(const gsl_complex c[], const int len, const gsl_complex z)\n{\n int i;\n gsl_complex ans = c[len-1];\n for(i=len-1; i>0; i--) {\n /* The following three lines are equivalent to\n ans = gsl_complex_add (c[i-1], gsl_complex_mul (x, ans));\n but faster */\n double tmp = GSL_REAL (c[i-1]) + GSL_REAL (z) * GSL_REAL (ans) - GSL_IMAG (z) * GSL_IMAG (ans);\n GSL_SET_IMAG (&ans, GSL_IMAG (c[i-1]) + GSL_IMAG (z) * GSL_REAL (ans) + GSL_REAL (z) * GSL_IMAG (ans));\n GSL_SET_REAL (&ans, tmp);\n }\n return ans;\n}\n#endif /* HAVE_INLINE */\n\n/* Work with divided-difference polynomials, Abramowitz & Stegun 25.2.26 */\n\nint\ngsl_poly_dd_init (double dd[], const double x[], const double y[],\n size_t size);\n\nINLINE_DECL double\ngsl_poly_dd_eval (const double dd[], const double xa[], const size_t size, const double x);\n\n#ifdef HAVE_INLINE\nINLINE_FUN\ndouble \ngsl_poly_dd_eval(const double dd[], const double xa[], const size_t size, const double x)\n{\n size_t i;\n double y = dd[size - 1];\n for (i = size - 1; i--;) y = dd[i] + (x - xa[i]) * y;\n return y;\n}\n#endif /* HAVE_INLINE */\n\n\nint\ngsl_poly_dd_taylor (double c[], double xp,\n const double dd[], const double x[], size_t size,\n double w[]);\n\n/* Solve for real or complex roots of the standard quadratic equation,\n * returning the number of real roots.\n *\n * Roots are returned ordered.\n */\nint gsl_poly_solve_quadratic (double a, double b, double c, \n double * x0, double * x1);\n\nint \ngsl_poly_complex_solve_quadratic (double a, double b, double c, \n gsl_complex * z0, gsl_complex * z1);\n\n\n/* Solve for real roots of the cubic equation\n * x^3 + a x^2 + b x + c = 0, returning the\n * number of real roots.\n *\n * Roots are returned ordered.\n */\nint gsl_poly_solve_cubic (double a, double b, double c, \n double * x0, double * x1, double * x2);\n\nint \ngsl_poly_complex_solve_cubic (double a, double b, double c, \n gsl_complex * z0, gsl_complex * z1, \n gsl_complex * z2);\n\n\n/* Solve for the complex roots of a general real polynomial */\n\ntypedef struct \n{ \n size_t nc ;\n double * matrix ; \n} \ngsl_poly_complex_workspace ;\n\ngsl_poly_complex_workspace * gsl_poly_complex_workspace_alloc (size_t n);\nvoid gsl_poly_complex_workspace_free (gsl_poly_complex_workspace * w);\n\nint\ngsl_poly_complex_solve (const double * a, size_t n, \n gsl_poly_complex_workspace * w,\n gsl_complex_packed_ptr z);\n\n__END_DECLS\n\n#endif /* __GSL_POLY_H__ */\n", "meta": {"hexsha": "fa40a69469f05bc8c2c635e3988cb12f1a58de2d", "size": 5248, "ext": "h", "lang": "C", "max_stars_repo_path": "gsl-2.6/gsl/gsl_poly.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_poly.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_poly.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": 29.1555555556, "max_line_length": 115, "alphanum_fraction": 0.6661585366, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6586643130033949}} {"text": "/*This program evaluates the differential equations for a photon's geodesic in Minkowski spacetime.\nThe equations are written in the form $\\frac{d(x or p)^{\\alpha}}{d\\lambda}=f(x^{\\alpha},p^{\\alpha})$.\nWhere $p^{\\alpha}={\\dot{x}}^{\\alpha}$*/\n\n#include \n#include \n#include \n#include //GSL error management module\n\n#define C 299792.458 //Speed of light in velocity units\n#define DLAMBDA 0.001 //Geodesics parameter step\n\n\n/*Function for solving the differential equations of Minkowski geodesics.*/\nvoid euler1(double *x0, double *x1, double *x2, double *x3, double *p0, double *p1, double *p2, double *p3, double *lambda)\n{\n /*Increment in the variables of the differential equation we want to solve*/\n double dx0, dx1, dx2, dx3, dp0, dp1, dp2, dp3;\n\n /*Calculation of the increments*/\n dx0 = *p0*DLAMBDA; dx1 = *p1*DLAMBDA; dx2 = *p2*DLAMBDA; dx3 = *p3*DLAMBDA;\n dp0 = 0.0; dp1 = 0.0; dp2 = 0.0; dp3 = 0.0;\n\n /*New values of the variables of the differential equation. Since we are using pointers, when called the routine the value of variable change.*/\n *x0 = *x0 + dx0; *x1 = *x1 + dx1; *x2 = *x2 + dx2; *x3 = *x3 + dx3;\n *p0 = *p0 + dp0; *p1 = *p1 + dp1; *p2 = *p2 + dp2; *p3 = *p3 + dp3;\n \n /*Increment of parameter of geodesics*/\n *lambda = *lambda + DLAMBDA;\n}\n\nint main(void)\n{\n int i; //For array manipulation\n\n /*Initial conditions*/\n double x0 = 0.0, x1 = 0.0, x2 = 0.0, x3 = 0.0, p1 = 0.1*C, p2 = 0.9*C, p3 = 0.0, lambda = 0.0;\n double p0 = sqrt(pow(p1,2) + pow(p2,2) + pow(p3,2))/C;\n\n /*Pointer to file where solution of differential equation will be saved.*/\n FILE *geodesic;\n geodesic = fopen(\"geodesic_solution.dat\",\"w\");\n \n /*Write line of initial values in file*/\n fprintf(geodesic, \"%.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf %.12lf\\n\", lambda, x0, x1, x2, x3, p0, p1, p2, p3);\n\n /*Solution of the differential equation*/\n for(i=0; i<1000; i++)\n {\n euler1(&x0, &x1, &x2, &x3, &p0, &p1, &p2, &p3, &lambda);\n fprintf(geodesic, \"%12lf %12lf %12lf %12lf %12lf %12lf %12lf %12lf %12lf\\n\", lambda, x0, x1, x2, x3, p0, p1, p2, p3);\n }\n\n /** Releasing all used space in memory **/\n fclose(geodesic); //Close file storing the results\n\n /*GNUPLOT*/\n\n FILE *plot;\n plot = popen(\"gnuplot -persist\",\"w\");\n fprintf(plot, \"set terminal x11 0\\n\");\n fprintf(plot, \"set multiplot layout 1,3\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:2 not\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:3 not\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:4 not\\n\");\n fprintf(plot, \"unset multiplot\\n\");\n fprintf(plot, \"reset\\n\");\n fprintf(plot, \"set terminal x11 1\\n\");\n fprintf(plot, \"set multiplot layout 1,3\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:6 not\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:7 not\\n\");\n fprintf(plot, \"plot 'geodesic_solution.dat' using 1:8 not\\n\");\n fprintf(plot, \"unset multiplot\\n\");\n fprintf(plot, \"set terminal x11 2\\n\");\n fprintf(plot, \"splot 'geodesic_solution.dat' using 2:3:1\\n\");\n\n pclose(plot);\n //system(\"rm geodesic_solution.dat\");\n}\n", "meta": {"hexsha": "e628338802c6966aff1826a3bdd06744280cc9bc", "size": 3171, "ext": "c", "lang": "C", "max_stars_repo_path": "secondary_files/minkowski.c", "max_stars_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_stars_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T03:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T03:59:02.000Z", "max_issues_repo_path": "secondary_files/minkowski.c", "max_issues_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_issues_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-05-26T05:36:42.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-19T20:33:09.000Z", "max_forks_repo_path": "secondary_files/minkowski.c", "max_forks_repo_name": "CesarArroyo09/light_geodesics_thesis", "max_forks_repo_head_hexsha": "4a747f79bea7a03a717bb2a65549ff9a0f42bd68", "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.6375, "max_line_length": 146, "alphanum_fraction": 0.6464837591, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6586028247870515}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#ifdef ACCELERATE\n#include \n#else\n#include \n#endif\n\n#include \"neural.h\"\n\nvoid \nneural_feed_forward(struct neural_net_layer *head, float *x, int batch_size) \n{\n\t/* point \"current\" layer to head and set input as feature array x */\n\tstruct neural_net_layer *curr = head;\n\tstruct neural_net_layer *next;\n\tcurr->act = x;\n\n\tint in_nodes;\n\tint out_nodes;\n\n\twhile ((next = curr->next) != NULL) {\n\t\tin_nodes = curr->in_nodes;\n\t\tout_nodes = curr->out_nodes;\n\n\t\t/* act = X * Theta^T + bias */\n\t\tfor (int i = 0; i < batch_size; i++) {\n\t\t\tmemcpy(next->act + i * out_nodes, curr->bias, out_nodes * sizeof(float));\n\t\t}\n\t\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, batch_size, out_nodes, in_nodes,\n\t\t\t1.0, curr->act, in_nodes, curr->theta, in_nodes, 1.0, next->act, out_nodes);\n\n\t\t/* apply sigmoid function */\n\t\tfor (int i = 0; i < out_nodes * batch_size; i++) {\n\t\t\tnext->act[i] = 1.0 / (1 + expf(-next->act[i]));\n\t\t}\n\n\t\t/* transition to next layer */\n\t\tcurr = next;\n\t}\n}\n\nvoid \nneural_sgd_feed_forward(struct neural_net_layer *head, float *x) \n{\n\t/* point \"current\" layer to head and set input as feature array x */\n\tstruct neural_net_layer *curr = head;\n\tstruct neural_net_layer *next;\n\tcurr->act = x;\n\n\tint rows;\n\tint cols;\n\n\twhile ((next = curr->next) != NULL) {\n\t\trows = curr->out_nodes;\n\t\tcols = curr->in_nodes;\n\n\t\t/* act = theta * x + act */\n\t\tmemcpy(next->act, curr->bias, rows * sizeof(float));\n\t\tcblas_sgemv(CblasRowMajor, CblasNoTrans, rows, cols, 1.0, curr->theta, \n\t\t\tcols, curr->act, 1, 1.0, next->act, 1);\n\n\t\t/* apply sigmoid function */\n\t\tfor (int i = 0; i < rows; i++) {\n\t\t\tnext->act[i] = 1.0 / (1 + expf(-next->act[i]));\n\t\t}\n\n\t\t/* transition to next layer */\n\t\tcurr = next;\n\t}\n}\n\nvoid \nneural_back_prop(struct neural_net_layer *tail, float *y, const int batch_size,\n\t\tconst float alpha, const float lambda) \n{\n\t/* get delta from final predictions vs. actual; delta = a - y */\n\tcblas_scopy(tail->in_nodes * batch_size, tail->act, 1, tail->delta, 1);\n\tcblas_saxpy(tail->in_nodes * batch_size, -1.0, y, 1, tail->delta, 1);\n\n\tstruct neural_net_layer *curr;\n\tstruct neural_net_layer *prev;\n\tint in_nodes;\n\tint out_nodes;\n\n\tfor (curr = tail; curr->prev != NULL; curr = prev) {\n\t\tprev = curr->prev;\n\t\tin_nodes = prev->in_nodes;\n\t\tout_nodes = prev->out_nodes;\n\n\t\t/* Delta^(n-1) = Delta^(n) * Theta^(n-1) .* A^(n-1) (1 - A^(n-1)) */\n\t\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, batch_size, in_nodes, out_nodes,\n\t\t\t\t1.0, curr->delta, out_nodes, prev->theta, in_nodes, 0.0, prev->delta, in_nodes);\n\t\tfor (int j = 0; j < in_nodes * batch_size; j++) {\n\t\t\tprev->delta[j] *= (prev->act[j] * (1 - prev->act[j]));\n\t\t}\n\t}\n\n\tfor (curr = tail; curr->prev != NULL; curr = prev) {\n\t\tprev = curr->prev;\n\t\tin_nodes = prev->in_nodes;\n\t\tout_nodes = prev->out_nodes;\n\n\t\t/* bias -= alpha * delta */\n\t\tfor (int i = 0; i < batch_size; i++) {\n\t\t\tcblas_saxpy(out_nodes, -alpha, curr->delta + i * out_nodes, 1, prev->bias, 1);\n\t\t}\n\n\t\t/* Theta -= alpha * (Delta^T * Act + lambda * Theta) */\n\t\tcblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, out_nodes, in_nodes, batch_size,\n\t\t\t\t-alpha, curr->delta, out_nodes, prev->act, in_nodes, 1 - alpha * lambda, \n\t\t\t\tprev->theta, in_nodes);\n\t}\n}\n\nvoid \nneural_sgd_back_prop(struct neural_net_layer *tail, float *y, const float alpha, \n\t\tconst float lambda) \n{\n\t/* get delta from final predictions vs. actual; delta = a - y */\n\tcblas_scopy(tail->in_nodes, tail->act, 1, tail->delta, 1);\n\tcblas_saxpy(tail->in_nodes, -1.0, y, 1, tail->delta, 1);\n\n\tstruct neural_net_layer *curr;\n\tstruct neural_net_layer *prev;\n\tint rows;\n\tint cols;\n\n\tfor (curr = tail; curr->prev != NULL; curr = prev) {\n\t\tprev = curr->prev;\n\t\trows = prev->out_nodes;\n\t\tcols = prev->in_nodes;\n\n\t\t/* delta^(n-1) = theta^(n-1)T * delta^(n) .* a^(n-1) (1 - a^(n-1)) */\n\t\tcblas_sgemv(CblasRowMajor, CblasTrans, rows, cols, 1.0, prev->theta, \n\t\t\t\tcols, curr->delta, 1, 0.0, prev->delta, 1); \n\t\tfor (int j = 0; j < cols; j++) {\n\t\t\tprev->delta[j] *= (prev->act[j] * (1 - prev->act[j]));\n\t\t}\n\t}\n\n\tfor (curr = tail; curr->prev != NULL; curr = prev) {\n\t\tprev = curr->prev;\n\t\trows = prev->out_nodes;\n\t\tcols = prev->in_nodes;\n\n\t\t/* bias -= alpha * delta */\n\t\tcblas_saxpy(rows, -alpha, curr->delta, 1, prev->bias, 1);\n\n\t\t/* theta -= alpha * (delta * actT + lambda * theta) */\n\t\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, rows, cols, 1, -alpha, \n\t\t\t\tcurr->delta, 1, prev->act, cols, 1 - alpha * lambda, prev->theta, cols);\n\t}\n}\n\nvoid\nneural_train_iteration(struct neural_net_layer *head, struct neural_net_layer *tail, \n\t\tfloat *features, float *labels, const int n_samples, const int batch_size, \n\t\tconst float alpha, const float lambda)\n{\n\tint n_features = head->in_nodes;\n\tint n_labels = tail->in_nodes;\n\tint i;\n\n\tif (batch_size == 1) {\n\t\tfor (i = 0; i < n_samples; i++) {\n\t\t\tneural_sgd_feed_forward(head, features + i * n_features);\n\t\t\tneural_sgd_back_prop(tail, labels + i * n_labels, alpha, lambda);\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < n_samples / batch_size; i++) {\n\t\t\tneural_feed_forward(head, features + i * n_features * batch_size, batch_size);\n\t\t\tneural_back_prop(tail, labels + i * n_labels * batch_size, batch_size, alpha, lambda);\n\t\t}\n\n\t\t/* take care of remaining examples */\n\t\tint remainder = n_samples % batch_size;\n\t\tif (remainder > 0) {\n\t\t\tneural_feed_forward(head, features + i * n_features * batch_size, remainder);\n\t\t\tneural_back_prop(tail, labels + i * n_labels * batch_size, remainder, alpha, lambda);\n\t\t}\n\t}\n}\n\nvoid\nneural_predict_prob(struct neural_net_layer *head, struct neural_net_layer *tail,\n\t\tfloat *features, float *preds, const int n_samples, const int batch_size)\n{\n\tint n_features = head->in_nodes;\n\tint n_labels = tail->in_nodes;\n\tint i;\n\n\tif (batch_size == 1) {\n\t\tfor (i = 0; i < n_samples; i++) {\n\t\t\tneural_sgd_feed_forward(head, features + i * n_features);\n\t\t\tmemcpy(preds + i * n_labels, tail->act, n_labels * sizeof(float));\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < n_samples / batch_size; i++) {\n\t\t\tneural_feed_forward(head, features + i * n_features * batch_size, batch_size);\n\t\t\tmemcpy(preds + i * n_labels * batch_size, tail->act, \n\t\t\t\t\tn_labels * batch_size * sizeof(float));\n\t\t}\n\n\t\t/* take care of remaining examples */\n\t\tint remainder = n_samples % batch_size;\n\t\tif (remainder > 0) {\n\t\t\tneural_feed_forward(head, features + i * n_features * batch_size, remainder);\n\t\t\tmemcpy(preds + i * n_labels * batch_size, tail->act,\n\t\t\t\t\tn_labels * remainder * sizeof(float));\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "85c7dc5a3c395e7eb8084102677e7ca8dd980504", "size": 6539, "ext": "c", "lang": "C", "max_stars_repo_path": "src/neural.c", "max_stars_repo_name": "jwilk-forks/pyneural", "max_stars_repo_head_hexsha": "5de244c702915bff404a31c2b10820cdec67130a", "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/neural.c", "max_issues_repo_name": "jwilk-forks/pyneural", "max_issues_repo_head_hexsha": "5de244c702915bff404a31c2b10820cdec67130a", "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/neural.c", "max_forks_repo_name": "jwilk-forks/pyneural", "max_forks_repo_head_hexsha": "5de244c702915bff404a31c2b10820cdec67130a", "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.995412844, "max_line_length": 89, "alphanum_fraction": 0.6511699037, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107966642556, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6584187606090222}} {"text": "#include \"matrix_support.h\"\n#include \n\nint main(int argc, char *argv[])\n{\n /* enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102}; */\n /* enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113}; */\n /* enum CBLAS_UPLO {CblasUpper=121, CblasLower=122}; */\n /* enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132}; */\n /* enum CBLAS_SIDE {CblasLeft=141, CblasRight=142}; */\n\n CBLAS_ORDER order = CblasRowMajor;\n CBLAS_TRANSPOSE transA = CblasNoTrans;\n CBLAS_TRANSPOSE transB = CblasNoTrans;\n int m = 2;\n int k = 3;\n int n = 4;\n double alpha = 1;\n double beta = 1;\n double *A = create_matrix(m, k);\n double *B = create_matrix(k, n);\n double *C = create_matrix(m, n);\n double *D = create_matrix(n, k);\n double *x = create_vector(k);\n double *d = create_vector(m);\n printf(\"A\\n\");\n init_matrix_vector(A, m * k, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0);\n print_matrix(A, m, k);\n printf(\"\\nB\\n\");\n init_matrix_vector(B, k * n, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,\n 10.0, 11.0);\n print_matrix(B, k, n);\n printf(\"\\nD\\n\");\n init_matrix_vector(D, n * k, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,\n 10.0, 11.0);\n print_matrix(D, n, k);\n printf(\"\\nx\\n\");\n init_matrix_vector(x, k * 1, -2.0, 2.0, 10.0);\n print_vector(x, k);\n\n /* void 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 cblas_dgemm(order,\n transA,\n transB, \n m,\n n,\n k,\n alpha,\n A,\n k,\n B,\n n,\n beta,\n C,\n n);\n printf(\"\\nC = A.dot(B)\\n\");\n print_matrix(C, m, n);\n\n\n printf(\"\\nd = A.dot(x)\\n\");\n\n /*\n * dasum takes the sum of the absolute values\n */\n\n /**\n * ddot dot product between two vectors\n */\n\n /*\n * dnrm2 Eucledian norm of a vector\n */\n\n /*\n * dscal scales a vector by a constant\n */\n\n /*\n * daxpy constant times a vector plus a vector. uses unrolled loops for\n * increments equal to one.\n */\n\n /* void cblas_dgemv(const enum CBLAS_ORDER order, */\n /* const enum CBLAS_TRANSPOSE TransA, const int M, const int N, */\n /* const double alpha, const double *A, const int lda, */\n /* const double *X, const int incX, const double beta, */\n /* double *Y, const int incY); */\n cblas_dgemv(order,\n transA, // not transposed\n m, // rows of a\n k, // cols of a\n alpha, // scalar to multiply A with \n A, //matrix A\n k, // lda: leading dimension of A\n x, // vector x\n 1, // incx\n beta, // beta: scalar to multiply y with (0 having y as output)\n d, // vector d (Y in formula)\n 1); // incy\n\n print_vector(d, m);\n return 0;\n}\n", "meta": {"hexsha": "5d00e4ba6843ad99e30784cf1fd9fb57a1bdd057", "size": 3288, "ext": "c", "lang": "C", "max_stars_repo_path": "c/main.c", "max_stars_repo_name": "chibby0ne/using_blas", "max_stars_repo_head_hexsha": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "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/main.c", "max_issues_repo_name": "chibby0ne/using_blas", "max_issues_repo_head_hexsha": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "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/main.c", "max_forks_repo_name": "chibby0ne/using_blas", "max_forks_repo_head_hexsha": "66d270783ed40a99a11ae3a3aaefd61df3a3619b", "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.8909090909, "max_line_length": 91, "alphanum_fraction": 0.5182481752, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.6581729905298243}} {"text": "static char help[] =\n\"ODE system solver example using TS. Solves N-dimensional system\\n\"\n\" dy/dt = G(t,y)\\n\"\n\"with y(t0) = y0 to compute y(tf). Serial only.\\n\"\n\"Sets TS type to Runge-Kutta. The implemented example has\\n\"\n\"G_0 = y_1, G_1 = - y_0 + t, y_0(0) = 0, y_1(0) = 0. The exact solution is\\n\"\n\"y_0(t) = t - sin(t), y_1(t) = 1 - cos(t).\\n\\n\";\n\n#include \n\nextern PetscErrorCode ExactSolution(double, Vec);\nextern PetscErrorCode FormRHSFunction(TS, double, Vec, Vec, void*);\n\n//STARTMAIN\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n int steps;\n double t0 = 0.0, tf = 20.0, dt = 0.1, err;\n Vec y, yexact;\n TS ts;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr);\n ierr = VecSetSizes(y,PETSC_DECIDE,2); CHKERRQ(ierr);\n ierr = VecSetFromOptions(y); CHKERRQ(ierr);\n ierr = VecDuplicate(y,&yexact); CHKERRQ(ierr);\n\n ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);\n ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);\n ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSRK); 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 ierr = TSSetFromOptions(ts); CHKERRQ(ierr);\n\n // set initial values and solve\n ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);\n ierr = ExactSolution(t0,y); CHKERRQ(ierr);\n ierr = TSSolve(ts,y); CHKERRQ(ierr);\n\n // compute error and report\n ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);\n ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);\n ierr = ExactSolution(tf,yexact); CHKERRQ(ierr);\n ierr = VecAXPY(y,-1.0,yexact); CHKERRQ(ierr); // y <- y - yexact\n ierr = VecNorm(y,NORM_INFINITY,&err); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"error at tf = %.3f with %d steps: |y-y_exact|_inf = %g\\n\",\n tf,steps,err); CHKERRQ(ierr);\n\n VecDestroy(&y); VecDestroy(&yexact); TSDestroy(&ts);\n return PetscFinalize();\n}\n//ENDMAIN\n\n//STARTCALLBACKS\nPetscErrorCode ExactSolution(double t, Vec y) {\n double *ay;\n VecGetArray(y,&ay);\n ay[0] = t - sin(t);\n ay[1] = 1.0 - cos(t);\n VecRestoreArray(y,&ay);\n return 0;\n}\n\nPetscErrorCode FormRHSFunction(TS ts, double t, Vec y, Vec g, void *ptr) {\n const double *ay;\n double *ag;\n VecGetArrayRead(y,&ay);\n VecGetArray(g,&ag);\n ag[0] = ay[1]; // = G_1(t,y)\n ag[1] = - ay[0] + t; // = G_2(t,y)\n VecRestoreArrayRead(y,&ay);\n VecRestoreArray(g,&ag);\n return 0;\n}\n//ENDCALLBACKS\n\n", "meta": {"hexsha": "f81e299f1ac3ced2fd966c16e230dc29d8f1d181", "size": 2700, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/ode.c", "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/ch5/ode.c", "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/ch5/ode.c", "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1428571429, "max_line_length": 78, "alphanum_fraction": 0.6418518519, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.658074598746193}} {"text": "/*\n** t-tests\n**\n** G.Lohmann, Jan 2017\n*/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\n\n#define TINY 1.0e-10\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n#define SQR(x) ((x)*(x))\n\n\n/* \n** convert t to z values \n*/\ndouble t2z(double t,double df)\n{\n double p=0,z=0;\n double a,b,x;\n extern double gsl_sf_beta_inc(double,double,double);\n\n\n /* t to p */\n x = df/(df+(t*t));\n if (x <= 0 || x > 1) return 0;\n\n a = 0.5*df;\n b = 0.5;\n p = 0.5 * gsl_sf_beta_inc(a,b,x);\n\n\n /* p to z */\n z = gsl_cdf_ugaussian_Qinv(p);\n return z;\n}\n\n\nvoid avevar(double *data,int n,double *a,double *v)\n{\n int j;\n double ave,var,nx,s,u;\n\n nx = (double)n;\n ave = 0;\n for (j=0; j\n\n#include \n#include \n#include \n\n#include \n\n\nBIO_NS_START\n\n/** Calculates the log of n choose the observed counts. */\ntemplate < typename ObsIt >\ndouble\ncalc_ln_n_choose(\n\tObsIt obs_begin,\n\tObsIt obs_end)\n{\n\tdouble result = 0.0;\n\n\tunsigned n = 0;\n\twhile (obs_end != obs_begin)\n\t{\n\t\tresult -= gsl_sf_lnfact(*obs_begin);\n\t\tn += *obs_begin;\n\n\t\t++obs_begin;\n\t}\n\n\tresult += gsl_sf_lnfact(n);\n\n\treturn result;\n}\n\n\n/** Calculates a factor involved in the likelihood of a multinomial distribution with a dirichlet prior. */\ntemplate < typename ObsIt, typename AlphaIt >\ndouble\ncalc_ln_gamma_factor(\n\tObsIt obs_begin,\n\tObsIt obs_end,\n\tAlphaIt alpha_begin)\n{\n\tdouble ln_pi_gamma_alpha_obs = 0.0; //work in logarithms\n\tdouble ln_pi_gamma_alpha = 0.0; //work in logarithms\n\tdouble sum_alpha = 0.0;\n\tdouble sum_obs = 0.0;\n\twhile (obs_end != obs_begin)\n\t{\n\t\tsum_alpha += *alpha_begin;\n\t\tsum_obs += *obs_begin;\n\t\tln_pi_gamma_alpha += gsl_sf_lngamma(*alpha_begin);\n\t\tln_pi_gamma_alpha_obs += gsl_sf_lngamma(*alpha_begin + *obs_begin);\n\n\t\t++obs_begin;\n\t\t++alpha_begin;\n\t}\n\n\tdouble ln_result =\n\t\tgsl_sf_lngamma(sum_alpha)\n\t\t- ln_pi_gamma_alpha\n\t\t+ ln_pi_gamma_alpha_obs\n\t\t- gsl_sf_lngamma(sum_alpha + sum_obs);\n\n\treturn ln_result;\n}\n\n/** Calculates the log of the likelihood of seeing the observed counts under a dirichlet prior. */\ntemplate < typename ObsIt, typename AlphaIt >\ndouble\ncalc_multinomial_ln_likelihood_dirichlet_prior(\n\tObsIt obs_begin,\n\tObsIt obs_end,\n\tAlphaIt alpha_begin)\n{\n\treturn calc_ln_gamma_factor(obs_begin, obs_end, alpha_begin) + calc_ln_n_choose(obs_begin, obs_end);\n}\n\n\n/** Calculates the log of the likelihood of seeing the observed counts under a uniform multinomial distribution. */\ntemplate < typename ObsIt >\ndouble\ncalc_multinomial_ln_likelihood_uniform_dist(\n\tObsIt obs_begin,\n\tObsIt obs_end)\n{\n\tconst unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));\n\tif (0 == n)\n\t{\n\t\treturn 0.0;\n\t}\n\n\tconst double ln_n_choose = calc_ln_n_choose(obs_begin, obs_end);\n\treturn ln_n_choose - n * gsl_sf_log(double(obs_end - obs_begin));\n}\n\n\n/** Calculates the log of the likelihood of seeing the observed counts under a multinomial distribution with given p's. */\ntemplate < typename ObsIt, typename PIt >\ndouble\ncalc_multinomial_ln_likelihood(\n\tObsIt obs_begin,\n\tObsIt obs_end,\n\tPIt p_begin)\n{\n\tconst unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));\n\tif (0 == n)\n\t{\n\t\treturn 0.0;\n\t}\n\n\tdouble result = calc_ln_n_choose(obs_begin, obs_end);\n\twhile (obs_end != obs_begin)\n\t{\n\t\tresult += *obs_begin * gsl_sf_log(*p_begin);\n\n\t\t++obs_begin;\n\t\t++p_begin;\n\t}\n\n\treturn result;\n}\n\n\n/** Calculates the ratio of evidence in favour of a uniform distribution over one with a dirichlet prior\ndefined by the alphas. */\ntemplate < typename ObsIt, typename AlphaIt >\ndouble\ncalc_ln_multinomial_uniform_evidence(\n\tObsIt obs_begin,\n\tObsIt obs_end,\n\tAlphaIt alpha_begin)\n{\n\tconst double ln_likelihood_uniform_dist = calc_multinomial_ln_likelihood_uniform_dist(obs_begin, obs_end);\n\tconst double ln_likelihood_dirichlet_prior = calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);\n\treturn ln_likelihood_uniform_dist - ln_likelihood_dirichlet_prior;\n}\n\n/** Calculates the ratio of evidence in favour of a particular multinomial distribution (defined by the p's)\nover one with a dirichlet prior defined by the alpha's. */\ntemplate < typename ObsIt, typename AlphaIt, typename PIt >\ndouble\ncalc_ln_multinomial_evidence(\n\tObsIt obs_begin,\n\tObsIt obs_end,\n\tAlphaIt alpha_begin,\n\tPIt p_begin)\n{\n\treturn\n\t\tcalc_multinomial_ln_likelihood(obs_begin, obs_end, p_begin)\n\t\t- calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);\n}\n\n\nBIO_NS_END\n\n\n#endif //BIO_MATH_H_\n\n", "meta": {"hexsha": "6d90c7f62044139e91d5ca7ba6e23b0f016e2afb", "size": 3902, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/bio/math.h", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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++/include/bio/math.h", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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++/include/bio/math.h", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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.2261904762, "max_line_length": 126, "alphanum_fraction": 0.7621732445, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6573170735967955}} {"text": "/* randist/weibull.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n/* The Weibull distribution has the form,\n\n p(x) dx = (b/a) (x/a)^(b-1) exp(-(x/a)^b) dx\n\n */\n\ndouble\ngsl_ran_weibull (const gsl_rng * r, const double a, const double b)\n{\n double x = gsl_rng_uniform_pos (r);\n\n double z = pow (-log (x), 1 / b);\n\n return a * z;\n}\n\ndouble\ngsl_ran_weibull_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 (b == 1)\n return 1/a ;\n else\n return 0 ;\n }\n else if (b == 1)\n {\n return exp(-x/a)/a ;\n }\n else\n {\n double p = (b/a) * exp (-pow (x/a, b) + (b - 1) * log (x/a));\n return p;\n }\n}\n", "meta": {"hexsha": "b1494ef3656faf7e01189e66e14df6e8f20d9751", "size": 1578, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/weibull.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/randist/weibull.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/weibull.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 24.2769230769, "max_line_length": 81, "alphanum_fraction": 0.6324461343, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6573022415177016}} {"text": "#include \n#include \n\nint main() {\n double a = 1.0, b = -3.0, c = 2.0;\n double x0 = 0.0, x1 = 0.0;\n gsl_poly_solve_quadratic(a, b, c, &x0, &x1);\n printf(\"%4.1fx^2 + %4.1fx + %4.1f = 0 -> x = %4.1f, %4.1f\\n\",\n a, b, c, x0, x1);\n return 0;\n}\n", "meta": {"hexsha": "5d4d2554e4bed843b1023fa19238675f8031db74", "size": 274, "ext": "c", "lang": "C", "max_stars_repo_path": "src_book0/ex10/list1032/list1032A.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/list1032/list1032A.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/list1032/list1032A.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": 22.8333333333, "max_line_length": 63, "alphanum_fraction": 0.5109489051, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6569897170913874}} {"text": "/* randist/multinomial.c\n * \n * Copyright (C) 2002 Gavin E. Crooks \n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The multinomial distribution has the form\n\n N! n_1 n_2 n_K\n prob(n_1, n_2, ... n_K) = -------------------- p_1 p_2 ... p_K\n (n_1! n_2! ... n_K!) \n\n where n_1, n_2, ... n_K are nonnegative integers, sum_{k=1,K} n_k = N,\n and p = (p_1, p_2, ..., p_K) is a probability distribution. \n\n Random variates are generated using the conditional binomial method.\n This scales well with N and does not require a setup step.\n\n Ref: \n C.S. David, The computer generation of multinomial random variates,\n Comp. Stat. Data Anal. 16 (1993) 205-217\n*/\n\nvoid\ngsl_ran_multinomial (const gsl_rng * r, const size_t K,\n const unsigned int N, const double p[], unsigned int n[])\n{\n size_t k;\n double norm = 0.0;\n double sum_p = 0.0;\n\n unsigned int sum_n = 0;\n\n /* p[k] may contain non-negative weights that do not sum to 1.0.\n * Even a probability distribution will not exactly sum to 1.0\n * due to rounding errors. \n */\n\n for (k = 0; k < K; k++)\n {\n norm += p[k];\n }\n\n for (k = 0; k < K; k++)\n {\n if (p[k] > 0.0)\n {\n n[k] = gsl_ran_binomial (r, p[k] / (norm - sum_p), N - sum_n);\n }\n else\n {\n n[k] = 0;\n }\n\n sum_p += p[k];\n sum_n += n[k];\n }\n\n}\n\n\ndouble\ngsl_ran_multinomial_pdf (const size_t K,\n const double p[], const unsigned int n[])\n{\n return exp (gsl_ran_multinomial_lnpdf (K, p, n));\n}\n\n\ndouble\ngsl_ran_multinomial_lnpdf (const size_t K,\n const double p[], const unsigned int n[])\n{\n size_t k;\n unsigned int N = 0;\n double log_pdf = 0.0;\n double norm = 0.0;\n\n for (k = 0; k < K; k++)\n {\n N += n[k];\n }\n\n for (k = 0; k < K; k++)\n {\n norm += p[k];\n }\n\n log_pdf = gsl_sf_lnfact (N);\n\n for (k = 0; k < K; k++)\n {\n log_pdf -= gsl_sf_lnfact (n[k]);\n }\n\n for (k = 0; k < K; k++)\n {\n log_pdf += log (p[k] / norm) * n[k];\n }\n\n return log_pdf;\n}\n", "meta": {"hexsha": "321e1727079370ce7c6ce39b534ed79af246e335", "size": 2989, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/multinomial.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/multinomial.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/multinomial.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.5, "max_line_length": 81, "alphanum_fraction": 0.5787888926, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6566024471161136}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\ngsl_spline *cosmocalc_aexpn2age_spline = NULL;\ngsl_interp_accel *cosmocalc_aexpn2age_acc = NULL; \ndouble AGE = 0;\n\n/* function for integration using gsl integration */\nstatic double age_integ_funct(double a, void *p)\n{\n return 1.0/a/hubble_noscale(a);\n}\n\n/* init function - some help from Gadget-2 applied here */\nvoid init_cosmocalc_age_table(void)\n{\n#define WORKSPACE_NUM 100000\n#define ABSERR 0.0\n#define RELERR 1e-8\n\n static int initFlag = 1;\n static int currCosmoNum;\n \n gsl_integration_workspace *workspace;\n gsl_function F;\n long i;\n double result,abserr,afact;\n double age_table[COSMOCALC_AGE_TABLE_LENGTH];\n double aexpn_table[COSMOCALC_AGE_TABLE_LENGTH];\n \n if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)\n {\n initFlag = 0;\n currCosmoNum = cosmoData.cosmoNum;\n \n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n\n aexpn_table[0] = 0.0;\n age_table[0] = 0.0; \n for(i=1;i\n#include \n\ndouble real_trigamma_cmplxarg(double x, double y, int m, int l){\n //compute the real part of the trigamma function at z = x + iy using\n //my accelerated series formula\n //argument should have positive real part (x > 0)\n //m gives the number of zeta function terms to use\n //l gives the number of terms to use in the residual series\n double result = 0;\n\n //if x is small, the result will be large and thus, inaccurate. Use the\n //polygamma shift formula to give a larger value of x for the computation\n if(x < 1000){\n return ((x*x - y*y)/(x*x + y*y)/(x*x + y*y)) + real_trigamma_cmplxarg(x + 1, y, m, l);\n }\n else{\n double phase, ypow = 1.0, xpow, denom;\n //compute finite sum of Hurwitz zeta functions\n for (int i = 1; i < m; ++i){\n phase = 2*(i/2) == i ? -1.0 : 1.0;\n result += phase*(2*i - 1)*ypow*gsl_sf_hzeta(2*i, x);\n ypow = ypow*y*y;\n }\n //compute the infinite sum of residuals\n phase = 2*(m/2) == m ? 1.0 : -1.0;\n for (int n = 0; n < l; ++n){\n xpow = pow(x + n, 2*m);\n denom = ((x + n)*(x + n) + y*y)*((x + n)*(x + n) + y*y);\n result += phase*ypow*((2*m - 1)*y*y + (2*m + 1)*(x + n)*(x + n)) / xpow / denom;\n }\n return result;\n }\n}", "meta": {"hexsha": "b676ff5973f69a2e2ef80da02a3b644b0127086b", "size": 1372, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/cmplx_math.h", "max_stars_repo_name": "butchertx/spin_boson_mc", "max_stars_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/cmplx_math.h", "max_issues_repo_name": "butchertx/spin_boson_mc", "max_issues_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/cmplx_math.h", "max_forks_repo_name": "butchertx/spin_boson_mc", "max_forks_repo_head_hexsha": "0d47b188b4953734725efe98ea57d4da3d2ffc76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1111111111, "max_line_length": 94, "alphanum_fraction": 0.5357142857, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342024724487, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6562027159698601}} {"text": "/*\n * bspline.c: Routines for calculating values of B-splines and their\n * derivatives, as well as efficient computation of the values of\n * N-dimensional B-spline surfaces.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"photospline/bspline.h\"\n\n/*\n * Compute the value of the ith nth-order basis spline of a set\n * defined by knots at the point x.\n *\n * This is implemented using the De Boor algorithm, as outlined on\n * Wikipedia.\n */\n\ndouble\nbspline(const double *knots, double x, int i, int n)\n{\n\tdouble result;\n\n\tif (n == 0) {\n\t\t/*\n\t\t * Special case the 0th order case, where B-Splines\n\t\t * are constant functions from one knot to the next.\n\t\t */\n\n\t\tif (x >= knots[i] && x < knots[i+1])\n\t\t\treturn 1.0;\n\t\telse\n\t\t\treturn 0.0;\n\t}\n\n\tresult = (x - knots[i])*bspline(knots, x, i, n-1) /\n\t (knots[i+n] - knots[i]);\n\tresult += (knots[i+n+1] - x)*bspline(knots, x, i+1, n-1) /\n\t (knots[i+n+1] - knots[i+1]);\n\n\treturn result;\n}\n\n/*\n * A brain-dead reimplementation of de Boor's BSPLVB, which generates\n * the values of the non-zero B-splines at x from the bottom up without\n * unnecessarily recalculating terms. \n * \n * NB: for bsplvb_simple(), bspline_nonzero(), and bspline_deriv_nonzero(),\n * `left' must be the index of the nearest fully-supported knot\n * span for splines of order n, i.e. n <= left <= nknots-n-2. For bsplvb(),\n * `left' must be the index of the nonzero 0-th order spline, i.e.\n * knots[left] <= x < knots[left+1].\n *\n * See Chapter X in: \n * \n * Carl de Boor. A Practical Guide to Splines, volume 27 of Applied\n * Mathematical Sciences. Springer-Verlag, 1978.\n */\n\nvoid\nbsplvb_simple(const double *knots, const unsigned nknots,\n double x, int left, int degree, float *restrict biatx)\n{\n\tassert(degree>0);\n\tint i, j;\n\tdouble saved, term;\n\tdouble delta_l[degree], delta_r[degree];\n\t\n\tbiatx[0] = 1.0;\n\t\n\t/*\n\t * Handle the (rare) cases where x is outside the full\n\t * support of the spline surface.\n\t */\n\tif (left == degree-1)\n\t\twhile (left >= 0 && x < knots[left])\n\t\t\tleft--;\n\telse if (left == nknots-degree-1)\n\t\twhile (left < nknots-1 && x > knots[left+1])\n\t\t\tleft++;\t\n\t\n\t/* \n\t * NB: if left < degree-1 or left > nknots-degree-1,\n\t * the following loop will dereference addresses ouside\n\t * of knots[0:nknots]. While terms involving invalid knot\n\t * indices will be discarded, it is important that `knots'\n\t * have (maxdegree-1)*sizeof(double) bytes of padding\n\t * before and after its valid range to prevent segfaults\n\t * (see parsefitstable()).\n\t */\n\tfor (j = 0; j < degree-1; j++) {\n\t\tdelta_r[j] = knots[left+j+1] - x;\n\t\tdelta_l[j] = x - knots[left-j];\n\t\t\n\t\tsaved = 0.0;\n\t\t\n\t\tfor (i = 0; i < j+1; i++) {\n\t\t\tterm = biatx[i] / (delta_r[i] + delta_l[j-i]);\n\t\t\tbiatx[i] = saved + delta_r[i]*term;\n\t\t\tsaved = delta_l[j-i]*term;\n\t\t}\n\t\t\n\t\tbiatx[j+1] = saved;\n\t}\n\t\n\t/* \n\t * If left < (spline order), only the first (left+1)\n\t * splines are valid; the remainder are utter nonsense.\n\t */\n\tif ((i = degree-1-left) > 0) {\n\t\tfor (j = 0; j < left+1; j++)\n\t\t\tbiatx[j] = biatx[j+i]; /* Move valid splines over. */\n\t\tfor ( ; j < degree; j++)\n\t\t\tbiatx[j] = 0.0; /* The rest are zero by construction. */\n\t} else if ((i = left+degree+1-nknots) > 0) {\n\t\tfor (j = degree-1; j > i-1; j--)\n\t\t\tbiatx[j] = biatx[j-i];\n\t\tfor ( ; j >= 0; j--)\n\t\t\tbiatx[j] = 0.0;\n\t}\n}\n\nvoid\nbsplvb(const double *knots, const double x, const int left, const int jlow,\n const int jhigh, float *restrict biatx,\n double *restrict delta_l, double *restrict delta_r)\n{\n\tint i, j;\n\tdouble saved, term;\n\n\tif (jlow == 0)\n\t\tbiatx[0] = 1.0;\n\t\n\tfor (j = jlow; j < jhigh-1; j++) {\n\t\tdelta_r[j] = knots[left+j+1] - x;\n\t\tdelta_l[j] = x - knots[left-j];\n\t\t\n\t\tsaved = 0.0;\n\t\t\n\t\tfor (i = 0; i < j+1; i++) {\n\t\t\tterm = biatx[i] / (delta_r[i] + delta_l[j-i]);\n\t\t\tbiatx[i] = saved + delta_r[i]*term;\n\t\t\tsaved = delta_l[j-i]*term;\n\t\t}\n\t\t\n\t\tbiatx[j+1] = saved;\n\t}\n}\n\n\nvoid\nbspline_deriv_nonzero(const double *knots, const unsigned nknots,\n const double x, int left, const int n, float *restrict biatx)\n{\n\t/* NB: it might be tempting to use unsigned integers *left* and *n* here,\n\t but indices into the knot vector may be negative (up to -order) before\n\t the first fully-supported knot. */\n\tassert(n>0);\n\tint i, j;\n\tdouble temp, a;\n\tdouble delta_l[n], delta_r[n];\n\t\n\t/* Special case for constant splines */\n\tif (n == 0)\n\t\treturn;\n\t\n\t/*\n\t * Handle the (rare) cases where x is outside the full\n\t * support of the spline surface.\n\t */\n\tif (left == n)\n\t\twhile (left >= 0 && x < knots[left])\n\t\t\tleft--;\n\telse if (left == nknots-n-2)\n\t\twhile (left < nknots-1 && x > knots[left+1])\n\t\t\tleft++;\n\t\n\t/* Get the non-zero n-1th order B-splines at x */\n\tbsplvb(knots, x, left, 0 /* jlow */, n /* jhigh */,\n\t biatx, delta_l, delta_r);\n\t\n\t/* \n\t * Now, form the derivatives of the nth order B-splines from\n\t * linear combinations of the lower-order splines.\n\t */\n\t\n\t/* \n\t * On the last supported segment of the ith nth order spline,\n\t * only the i+1th n-1th order spline is nonzero.\n\t */\n\ttemp = biatx[0];\n\tbiatx[0] = - n*temp / ((knots[left+1] - knots[left+1-n]));\n\t\n\t/* On the middle segments, both the ith and i+1th splines contribute. */\n\tfor (i = 1; i < n; i++) {\n\t\ta = n*temp/((knots[left+i] - knots[left+i-n]));\n\t\ttemp = biatx[i];\n\t\tbiatx[i] = a - n*temp/(knots[left+i+1] - knots[left+i+1-n]);\n\t}\n\t/*\n\t * On the first supported segment of the i+nth nth order spline,\n\t * only the ith n-1th order spline is nonzero.\n\t */\n\tbiatx[n] = n*temp/((knots[left+n] - knots[left]));\n\n\t/* Rearrange for partially-supported points. */\n\tif ((i = n-left) > 0) {\n\t\tfor (j = 0; j < left+1; j++)\n\t\t\tbiatx[j] = biatx[j+i]; /* Move valid splines over. */\n\t\tfor ( ; j < n+1; j++)\n\t\t\tbiatx[j] = 0.0; /* The rest are zero by construction. */\n\t} else if ((i = left+n+2-nknots) > 0) {\n\t\tfor (j = n; j > i-1; j--)\n\t\t\tbiatx[j] = biatx[j-i];\n\t\tfor ( ; j >= 0; j--)\n\t\t\tbiatx[j] = 0.0;\n\t}\n\n}\n\ndouble\nbspline_deriv(const double *knots, double x, int i, int n, unsigned order)\n{\n\tdouble result;\n\n\tif (n == 0) {\n\t\t/*\n\t\t * Special case the 0th order case, where B-Splines\n\t\t * are constant functions from one knot to the next.\n\t\t */\n\n\t\treturn 0.0;\n\t}\n\t\n\tif (order <= 1) {\n\t\tresult = n * bspline(knots, x, i, n-1) / (knots[i+n] - knots[i]);\n\t\tresult -= n * bspline(knots, x, i+1, n-1) / (knots[i+n+1] - knots[i+1]);\n\t} else {\n\t\tresult = n * bspline_deriv(knots, x, i, n-1, order-1) / (knots[i+n] - knots[i]);\n\t\tresult -= n * bspline_deriv(knots, x, i+1, n-1, order-1) / (knots[i+n+1] - knots[i+1]);\n\t}\n\treturn result;\n}\n\ndouble\nbspline_deriv_2(const double *knots, double x, int i, int n)\n{\n\tdouble result;\n\n\tif (n <= 1) {\n\t\t/*\n\t\t * Special case the 1st order case, where B-Splines\n\t\t * are linear functions from one knot to the next.\n\t\t */\n\n\t\treturn 0.0;\n\t}\n\t\n\tresult = bspline(knots, x, i, n-2) /\n\t ((knots[i+n] - knots[i])*(knots[i+n-1] - knots[i]));\n\tresult -= bspline(knots, x, i+1, n-2) *\n\t (1./(knots[i+n] - knots[i]) + 1./(knots[i+n+1] - knots[i+1])) / \n\t (knots[i+n] - knots[i+1]);\n\tresult += bspline(knots, x, i+2, n-2) / \n\t ((knots[i+n+1] - knots[i+1])*(knots[i+n+1] - knots[i+2]));\n\t\n\tresult *= n*(n-1);\n\t\n\treturn result;\n}\n\n\n/*\n * Evaluates the results of a full spline basis given a set of knots,\n * a position, an order, and a central spline for the position (or -1).\n * The central spline should be the index of the 0th order basis spline\n * that is non-zero at the position x.\n */\n\ndouble\nsplineeval(const double *knots, const double *weights, int nknots, double x, int order,\n int center)\n{\n\tdouble work = 0.0;\n\tint i;\n\n\tif (center < 0) {\n\t\t/* XXX: should be a binary search */\n\t\tfor (center = 0; center+1 < nknots; center++) {\n\t\t\tif (x > knots[center] && x < knots[center+1])\n\t\t\t\tbreak;\n\t\t}\n\t\n\t\tif (center+1 >= nknots)\n\t\t\treturn 0.0;\n\t}\n\n\ti = center - order;\n\tif (i < 0)\n\t\ti = 0;\n\n\twhile (i < nknots-order-1 && i <= center) {\n\t\twork += weights[i]*bspline(knots, x, i, order);\n\t\ti++;\n\t}\n\n\treturn work;\n}\n\nint\ntablesearchcenters(const struct splinetable *table, const double *x, int *centers)\n{\n\tint i, min, max;\n\n\tfor (i = 0; i < table->ndim; i++) {\n\t\t\n\t\t/* Ensure we are actually inside the table. */\n\t\tif (x[i] <= table->knots[i][0] ||\n\t\t x[i] > table->knots[i][table->nknots[i]-1])\n\t\t\treturn (-1);\n\t\t\n\t\t/*\n\t\t * If we're only a few knots in, take the center to be\n\t\t * the nearest fully-supported knot.\n\t\t */\n\t\tif (x[i] < table->knots[i][table->order[i]]) {\n\t\t\tcenters[i] = table->order[i];\n\t\t\tcontinue;\n\t\t} else if (x[i] >= table->knots[i][table->naxes[i]]) {\n\t\t\tcenters[i] = table->naxes[i]-1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tmin = table->order[i];\n\t\tmax = table->nknots[i]-2;\n\t\tdo {\n\t\t\tcenters[i] = (max+min)/2;\n\n\t\t\tif (x[i] < table->knots[i][centers[i]])\n\t\t\t\tmax = centers[i]-1;\n\t\t\telse\n\t\t\t\tmin = centers[i]+1;\n\t\t} while (x[i] < table->knots[i][centers[i]] ||\n\t\t x[i] >= table->knots[i][centers[i]+1]);\n\n\t\t/*\n\t\t * B-splines are defined on a half-open interval. For the\n\t\t * last point of the interval, move center one point to the\n\t\t * left to get the limit of the sum without evaluating\n\t\t * absent basis functions.\n\t\t */\n\t\tif (centers[i] == table->naxes[i])\n\t\t\tcenters[i]--;\n\t}\n\n\n\treturn (0);\n}\n\nstatic int\nmaxorder(int *order, int ndim)\n{\n\tint i, max = 0;\n\t\n\tfor (i = 0; i < ndim; i++)\n\t\tif (order[i] > max)\n\t\t\tmax = order[i];\n\t\n\treturn (max);\n}\n \n/*\n * The N-Dimensional tensor product basis version of splineeval.\n * Evaluates the results of a full spline basis given a set of knots,\n * a position, an order, and a central spline for the position (or -1).\n * The central spline should be the index of the 0th order basis spline\n * that is non-zero at the position x.\n *\n * x is the vector at which we will evaluate the space\n */\n\nstatic double\nndsplineeval_core(const struct splinetable *table, const int *centers, int maxdegree,\n float localbasis[table->ndim][maxdegree])\n{\n\tassert(table->ndim>0);\n\tint i, j, n, tablepos;\n\tfloat result;\n\tfloat basis_tree[table->ndim+1];\n\tint nchunks;\n\tint decomposedposition[table->ndim];\n\n\ttablepos = 0;\n\tfor (n = 0; n < table->ndim; n++) {\n\t\tdecomposedposition[n] = 0;\n\t\ttablepos += (centers[n] - table->order[n])*table->strides[n];\n\t}\n\n\tbasis_tree[0] = 1;\n\tfor (n = 0; n < table->ndim; n++)\n\t\tbasis_tree[n+1] = basis_tree[n]*localbasis[n][0];\n\tnchunks = 1;\n\tfor (n = 0; n < table->ndim - 1; n++)\n\t\tnchunks *= (table->order[n] + 1);\n\n\tresult = 0;\n\tn = 0;\n\twhile (1) {\n\t\tfor (i = 0; __builtin_expect(i < table->order[table->ndim-1] +\n\t\t 1, 1); i++) {\n\n\t\t\tresult += basis_tree[table->ndim-1]*\n\t\t\t localbasis[table->ndim-1][i]*\n\t\t\t table->coefficients[tablepos + i];\n\t\t}\n\n\t\tif (__builtin_expect(++n == nchunks, 0))\n\t\t\tbreak;\n\n\t\ttablepos += table->strides[table->ndim-2];\n\t\tdecomposedposition[table->ndim-2]++;\n\n\t\t/* Carry to higher dimensions */\n\t\tfor (i = table->ndim-2;\n\t\t decomposedposition[i] > table->order[i]; i--) {\n\t\t\tdecomposedposition[i-1]++;\n\t\t\ttablepos += (table->strides[i-1]\n\t\t\t - decomposedposition[i]*table->strides[i]);\n\t\t\tdecomposedposition[i] = 0;\n\t\t}\n\t\tfor (j = i; __builtin_expect(j < table->ndim-1, 1); j++)\n\t\t\tbasis_tree[j+1] = basis_tree[j]*\n\t\t\t localbasis[j][decomposedposition[j]];\n\t}\n\n\treturn result;\n}\n\n/* This function returns bspline coefficients along a given dimension, fixing the values+coefficients for the\nother dimensions. Used to obtain a 1-d spline representation that can be easily further convolved. */\n\nvoid\nndsplineeval_slice_coeffs(const struct splinetable *table, const double *x, const int *centers, double *results,int slice_dimension, int derivative, int area_norm )\n{\n\tassert(table->ndim>0);\n\tint n;\n\tint maxdegree = maxorder(table->order, table->ndim) + 1; \n\tfloat localbasis[table->ndim][maxdegree];\n\n\tif(slice_dimension==table->ndim-1)\n\t{\n\t\tprintf(\"ERROR!!! slice dimension cannot be ndim-1 in this implementation!\");\n\t}\n\t\n\t\n\tfor (n = 0; n < table->ndim; n++) {\n\t\t\n\t\t\t\n\t\t\tbsplvb_simple(table->knots[n], table->nknots[n],\n\t\t\t x[n], centers[n], table->order[n] + 1,\n\t\t\t localbasis[n]);\n\t}\n\n\t\n\n\n\tint i, j, tablepos, slice_dimension_stride, num_coeffs;\n\t//double result;\n\tnum_coeffs=table->nknots[slice_dimension]-table->order[slice_dimension]-1;\n\n\tmemset(results, 0, sizeof(double)*num_coeffs);\n\t// temp_result is stored to teomporarily store coefficients for derivative calculation\n\tdouble temp_result[num_coeffs];\n\n\tfloat basis_tree[table->ndim+1]; // the last basis_tree dimension is unused .. \n\tint nchunks;\n\tint decomposedposition[table->ndim];\n\n\t//int derivative_correction[table->ndim];\n\n\n\t\n\n\tnchunks = 1;\n\tfor (n = 0; n < table->ndim - 1; n++)\n\t{\t\n\t\t//derivative_correction[n]=0;\n\t\t\n\t\tif(n==slice_dimension)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tnchunks *= (table->order[n] + 1);\n\t\t\n\t}\n\n\n\n\t// initialize overall table position\n\ttablepos = 0;\n\tfor (n = 0; n < table->ndim; n++) {\n\t\tdecomposedposition[n]=0;\n\t\tif(n!=slice_dimension)\n\t\t{\n\t\t\t\n\t\t\ttablepos += (centers[n] - table->order[n])*table->strides[n];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tslice_dimension_stride=table->strides[n];\n\t\t}\n\t}\n\t\n\t\n\t\t\n\t// initialize local basis\n\tbasis_tree[0] = 1;\n\tfor (n = 0; n < table->ndim; n++)\n\t{\t\n\t\tif(n==slice_dimension)\n\t\t{\n\t\t\tbasis_tree[n+1] = basis_tree[n];\n\t\t\tcontinue;\n\n\t\t}\n\t\tbasis_tree[n+1] = basis_tree[n]*localbasis[n][0];\n\t}\n\n\t\t\n\tdouble temp_base_eval=0.0;\n\tn=0;\n\twhile (1) {\n\t\t\n\t\tfor (i = 0; __builtin_expect(i < table->order[table->ndim-1] +\n\t\t 1, 1); i++) {\n\n\t\t\t// in contrast to ndsplineeval_core, save a value for each coefficient, separated by the slice dimension stride\n\t\t\ttemp_base_eval=basis_tree[table->ndim-1]*localbasis[table->ndim-1][i];\n\t\t\tfor(int nc=0; __builtin_expect(nccoefficients[tablepos + i + nc*slice_dimension_stride];\n\t\t\t}\n\n\t\t}\n\n\t\tif (__builtin_expect(++n == nchunks, 0))\n\t\t\tbreak;\n\n\t\t// special case when the slicing dimension is ndim-2 .. skip over this dimension immediately by pushing tablepos forward by (order+1)*strides\n\t\tif(slice_dimension==table->ndim-2)\n\t\t{\n\t\t\ttablepos += table->strides[table->ndim-2]*(table->order[table->ndim-2]+1);\n\t\t\tdecomposedposition[table->ndim-2]+=(table->order[table->ndim-2]+1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// otherwise just add one stride\n\t\t\ttablepos += table->strides[table->ndim-2];\n\t\t\tdecomposedposition[table->ndim-2]++;\n\t\t}\n\t\t\n\t\t// Carry to higher dimensions\n\t\tfor (i = table->ndim-2;\n\t\t decomposedposition[i] > table->order[i]; i--) {\n\t\t\n\t\t\t\n\t\t\tif(i==slice_dimension+1)\n\t\t\t{\n\t\t\t\t//printf(\"i=slicedimsino +1 .. \\n\");\n\t\t\t\tdecomposedposition[i-2]++;\n\t\t\t\ttablepos += (table->strides[i-2]\n\t\t\t - decomposedposition[i]*table->strides[i]);\n\t\t\t\tdecomposedposition[i] = 0;\n\t\t\t\t// add one extra -1, since we want to skip the slicing dimension\n\t\t\t\ti=i-1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdecomposedposition[i-1]++;\n\t\t\t\ttablepos += (table->strides[i-1]\n\t\t\t - decomposedposition[i]*table->strides[i]);\n\t\t\t\tdecomposedposition[i] = 0;\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t// stacks the tree basis up .. never include the dimension of interest, ie.e the slice dimension\n\t\tfor (j = i; __builtin_expect(j < table->ndim-1, 1); j++)\n\t\t {\n\t\t\t//printf(\"last loop index .. %d\\n\", j);\n\t\t\tif(j==slice_dimension)\n\t\t\t{\n\t\t\t\tbasis_tree[j+1] = basis_tree[j];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbasis_tree[j+1] = basis_tree[j]*\n\t\t\t localbasis[j][decomposedposition[j]];\n\t\t\t}\n\t\t}\n\n\t}\n\n\t\t\n\n\tfor(int nc=0; __builtin_expect(nc0)\n\t\t{\t\n\t\t\tdouble y_diff;\n\t\t\tdouble x_diff;\n\t\t\tint deriv_order=table->order[slice_dimension];\n\n\t\t\tif(nc==0)\n\t\t\t{\n\t\t\t\t// first one is special\n\t\t\t\ty_diff=deriv_order*results[0];\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\n\t\t\t\t// first form derivatives\n\t\t\t\t// requires two coefficient results usually ... so only start once we know >=2 coefficients\n\t\t\t\t// since table->order is really the degree, the new derivative order is just the degree of the original spline\n\t\t\t\t\n\t\t\t\ty_diff=deriv_order*(results[nc]-results[nc-1]);\n\n\t\t\t}\n\t\t\tx_diff=table->knots[slice_dimension][deriv_order+nc]-table->knots[slice_dimension][nc];\n\n\t\t\ttemp_result[nc]=y_diff/((double)x_diff);\n\n\t\t\t\n\t\t\tif(area_norm)\n\t\t\t{\t\n\t\t\t\tdouble norm_factor= ((double)deriv_order)/( table->knots[slice_dimension][deriv_order+nc] - table->knots[slice_dimension][nc]);\n\t\t\t\ttemp_result[nc]/=norm_factor;\n\t\t\t}\n\n\t\t\t// check again for area normalization\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(area_norm)\n\t\t\t{\t\n\t\t\t\tint real_order=table->order[slice_dimension]+1;\n\t\t\t\tdouble norm_factor= ((double)(real_order))/ ( table->knots[slice_dimension][real_order+nc] - table->knots[slice_dimension][nc]);\n\t\t\t\tresults[nc]/=norm_factor;\n\t\t\t}\n\n\t\t\t//printf(\"SLICE: abs res: %d %.10f\\n\", nc, results[nc]);\n\t\t}\n\n\t}\n\n\t// calculated the derivate .. copy temp_result into result\n\tif(derivative>0)\n\t{\n\t\tmemcpy(results, temp_result, sizeof(temp_result));\n\t}\n\t\n\n}\n\n\ndouble\nndsplineeval(const struct splinetable *table, const double *x, const int *centers,\n int derivatives)\n{\n\tassert(table->ndim>0);\n\tint n;\n\tint maxdegree = maxorder(table->order, table->ndim) + 1; \n\tfloat localbasis[table->ndim][maxdegree];\n\t\n\tfor (n = 0; n < table->ndim; n++) {\n\t\tif (derivatives & (1 << n)) {\n\t\t\tbspline_deriv_nonzero(table->knots[n], \n\t\t\t table->nknots[n], x[n], centers[n],\n\t\t\t table->order[n], localbasis[n]);\n\t\t} else {\n\t\t\tbsplvb_simple(table->knots[n], table->nknots[n],\n\t\t\t x[n], centers[n], table->order[n] + 1,\n\t\t\t localbasis[n]);\n\t\t}\n\t}\n\n\treturn ndsplineeval_core(table, centers, maxdegree, localbasis);\n}\n\ndouble\nndsplineeval_deriv(const struct splinetable *table, const double *x,\n const int *centers, const unsigned *derivatives)\n{\n\n\tassert(table->ndim>0);\n\tint i, n;\n\tint maxdegree = maxorder(table->order, table->ndim) + 1; \n\tfloat localbasis[table->ndim][maxdegree];\n\t\n\tfor (n = 0; n < table->ndim; n++) {\n\t\tif (derivatives == NULL || derivatives[n] == 0) {\n\t\t\tbsplvb_simple(table->knots[n], table->nknots[n],\n\t\t\t x[n], centers[n], table->order[n] + 1,\n\t\t\t localbasis[n]);\n\t\t} else if (derivatives[n] == 1) {\n\t\t\tbspline_deriv_nonzero(table->knots[n], \n\t\t\t table->nknots[n], x[n], centers[n],\n\t\t\t table->order[n], localbasis[n]);\n\t\t} else {\n\t\t\tfor (i = 0; i <= table->order[n]; i++)\n\t\t\t\tlocalbasis[n][i] = bspline_deriv(\n\t\t\t\t table->knots[n], x[n],\n\t\t\t\t centers[n] - table->order[n] + i,\n\t\t\t\t table->order[n], derivatives[n]);\n\t\t}\n\t}\n\n\treturn ndsplineeval_core(table, centers, maxdegree, localbasis);\n}\n\ndouble\nndsplineeval_linalg(const struct splinetable *table, const double *x,\n const int *centers, int derivatives)\n{\n\tassert(table->ndim>0);\n\tint totalcoeff, n;\n\tint coeffstrides[table->ndim];\n\tgsl_matrix_float *basis1, *basis2, *basis_elem;\n\n\tassert(table->ndim > 0);\n\tcoeffstrides[table->ndim - 1] = totalcoeff = 1;\n for (n = table->ndim-1; n >= 0; n--) {\n totalcoeff *= (table->order[n] + 1);\n if (n > 0)\n coeffstrides[n-1] = totalcoeff;\n }\n\n\tfloat basis1_data[totalcoeff], basis2_data[totalcoeff],\n\t elem_data[maxorder(table->order, table->ndim) + 1];\n\tgsl_matrix_float b1, b2, be;\n\tbasis1 = &b1; basis2 = &b2; basis_elem = &be;\n\tbasis1->data = basis1_data;\n\tbasis2->data = basis2_data;\n\tbasis_elem->data = elem_data;\n\n\t/*\n\t * Form outer product basis1 = basis2 x basis_elem, filling basis_elem\n\t * every time with the non-zero basis functions on each axis and\n\t * swapping basis1 and basis2 via tmp_basis.\n\t */\n\tbasis2->size1 = 1;\n\tbasis2->size2 = 1;\n\tbasis2->data[0] = 1.0;\n\n\tfor (n = table->ndim-1; n >= 0; n--) {\n\t\tgsl_matrix_float *tmp_basis;\n\t\tif (derivatives & (1 << n)) {\n\t\t\tbspline_deriv_nonzero(table->knots[n], \n\t\t\t table->nknots[n], x[n], centers[n],\n\t\t\t table->order[n], basis_elem->data);\n\t\t} else {\n\t\t\tbsplvb_simple(table->knots[n], table->nknots[n],\n\t\t\t x[n], centers[n], table->order[n] + 1,\n\t\t\t basis_elem->data);\n\t\t}\n\n\t\tbasis_elem->size1 = table->order[n] + 1;\n\t\tbasis_elem->size2 = 1;\n\n\t\tbasis1->size2 = basis2->size2;\n\t\tbasis1->size1 = basis_elem->size1;\n\t\tcblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t basis1->size1, basis1->size2, basis_elem->size2, 1.0,\n\t\t basis_elem->data, 1, basis2->data, basis2->size2, 0,\n\t\t basis1->data, basis1->size2);\n\t\tbasis1->size2 = basis1->size1 * basis1->size2;\n\t\tbasis1->size1 = 1;\n\n\t\ttmp_basis = basis1;\n\t\tbasis1 = basis2;\n\t\tbasis2 = tmp_basis;\n\t}\n\n\t/* Now basis1 is free, so fill it with the spline coefficients */\n\tint i, tablepos;\n\tint decomposedposition[table->ndim];\n\ttablepos = 0;\n\tfor (n = 0; n < table->ndim; n++) {\n\t\tdecomposedposition[n] = 0;\n\t\ttablepos += (centers[n] - table->order[n])*table->strides[n];\n\t}\n\n\tfor (i = 0; i < table->order[table->ndim-1] + 1; i++)\n\t\tbasis1->data[i] = table->coefficients[tablepos + i];\n\tfor (n = 1; n < coeffstrides[0] /* number of chunks */; n++) {\n\t\ttablepos += table->strides[table->ndim-2];\n\t\tdecomposedposition[table->ndim-2]++;\n\t\t/* Carry to higher dimensions */\n\t\tfor (i = table->ndim-2; __builtin_expect(i > 0 && \n\t\t decomposedposition[i] > table->order[i], 0); i--) {\n\t\t\tdecomposedposition[i-1]++;\n\t\t\ttablepos += (table->strides[i-1]\n\t\t\t - decomposedposition[i]*table->strides[i]);\n\t\t\tdecomposedposition[i] = 0;\n\t\t}\n\n\t\tfor (i = 0; i < table->order[table->ndim-1] + 1; i++)\n\t\t\tbasis1->data[n*(table->order[table->ndim-1] + 1) + i] =\n\t\t\t table->coefficients[tablepos + i];\n\t}\n\n\t/* Take the dot product */\n\t__builtin_prefetch(basis1->data);\n\t__builtin_prefetch(basis2->data);\n\treturn cblas_sdot(totalcoeff, basis1->data, 1, basis2->data, 1);\n}\n\n", "meta": {"hexsha": "97272fd19515174a250d489cf223703c9d836d5f", "size": 21306, "ext": "c", "lang": "C", "max_stars_repo_path": "photospline/private/lib/bspline.c", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "photospline/private/lib/bspline.c", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "photospline/private/lib/bspline.c", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 25.794188862, "max_line_length": 164, "alphanum_fraction": 0.62282925, "num_tokens": 7025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6561123950757903}} {"text": "#include \n#include \n#include \n\n// #include \n// #include \n\n\n\ndouble circle_overlap(double *rA, double radiiA, double *rB, double radiiB)\n{\n\n double rAB[2];\n rAB[0] = rB[0] - rA[0];\n rAB[1] = rB[1] - rA[1];\n\n double F;\n F = (pow(rAB[0], 2) + pow(rAB[1], 2)) / pow(radiiA + radiiB, 2);\n\n return F;\n\n}\n\n\n\n\n\n\n\nsize_t gen_pts_rsa_2d(double *x, double *y,\n size_t npoints, double radius, int step_limit,\n unsigned long randSeed)\n{\n\n // Setup GSL random number generator\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n // Set the seed\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n // Set the initial position\n double xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;\n double yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;\n x[0] = xn;\n y[0] = yn;\n\n double diameter = 2 * radius;\n\n size_t valid_pts;\n double F;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n\n double rA[2];\n double rB[2];\n\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;\n yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;\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 rB[0] = xn;\n rB[1] = yn;\n\n F = circle_overlap(&rA[0], radius, &rB[0], radius);\n\n if (F < 1.0)\n {\n\n flag = 0;\n break;\n\n }\n }\n if (flag == 1)\n {\n\n x[valid_pts] = xn;\n y[valid_pts] = yn;\n valid_pts += 1;\n\n }\n\n step += 1;\n \n }\n \n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}\n\n\n\n\n\n\nunsigned int metro_md_2d(double *x, double *y,\n double radius, size_t npoints, unsigned int step_limit,\n unsigned long randSeed)\n{\n\n /* Setup GSL random number generator */\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n /* Set the seed */\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n double diameter = 2 * radius;\n\n double F, dx, dy, xn, yn;\n unsigned int step, i, k, flag, success_steps;\n\n double rA[2];\n double rB[2];\n\n step = 0;\n success_steps = 0;\n while (step < step_limit)\n {\n\n i = step % npoints;\n\n /* Generate new position */\n while (1)\n {\n\n dx = diameter * (gsl_rng_uniform (r) - 0.5);\n xn = x[i] + dx;\n\n dy = diameter * (gsl_rng_uniform (r) - 0.5);\n yn = y[i] + dy;\n\n\n if (((xn > radius) & (xn < 1 - radius)) & ((yn > radius) & (yn < 1 - radius)) )\n {\n break;\n }\n\n }\n\n /* Determine if new position overlaps with other positions */\n flag = 1;\n for (k = 0; k < npoints; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n rB[0] = xn;\n rB[1] = yn;\n\n F = circle_overlap(&rA[0], radius, &rB[0], radius);\n\n if ((F < 1.0) & (i != k))\n {\n flag = 0;\n break;\n }\n\n\n }\n\n if (flag == 1)\n {\n\n x[i] = xn;\n y[i] = yn;\n success_steps = success_steps + 1;\n\n }\n\n step = step + 1;\n\n\n }\n\n gsl_rng_free (r);\n\n return success_steps;\n\n}\n\n\n\n\nunsigned int metro_pd_2d(double *x, double *y,\n double *radius, size_t npoints, int step_limit,\n unsigned long randSeed)\n{\n\n /* Setup GSL random number generator */\n const gsl_rng_type * T;\n gsl_rng * r;\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n /* Set the seed */\n // srand ( time(NULL) );\n // unsigned long randSeed = rand();\n gsl_rng_set(r, randSeed);\n\n\n double F, dx, dy, xn, yn, diameter;\n unsigned int step, i, k, flag, success_steps;\n\n double rA[2];\n double rB[2];\n\n step = 0;\n success_steps = 0;\n while (step < step_limit)\n {\n\n i = step % npoints;\n\n /* Generate new position */\n while (1)\n {\n\n diameter = 2 * radius[i];\n\n dx = diameter * (gsl_rng_uniform (r) - 0.5);\n xn = x[i] + dx;\n\n dy = diameter * (gsl_rng_uniform (r) - 0.5);\n yn = y[i] + dy;\n\n\n if (((xn > radius[i]) & (xn < 1 - radius[i])) & ((yn > radius[i]) & (yn < 1 - radius[i])) )\n {\n break;\n }\n\n }\n\n /* Determine if new position overlaps with other positions */\n flag = 1;\n for (k = 0; k < npoints; k++)\n {\n\n rA[0] = x[k];\n rA[1] = y[k];\n rB[0] = xn;\n rB[1] = yn;\n\n F = circle_overlap(&rA[0], radius[i], &rB[0], radius[k]);\n\n if ((F < 1.0) & (i != k))\n {\n flag = 0;\n break;\n }\n\n\n }\n\n if (flag == 1)\n {\n\n x[i] = xn;\n y[i] = yn;\n success_steps += 1;\n\n }\n\n step = step + 1;\n\n\n }\n\n gsl_rng_free (r);\n\n return success_steps;\n\n}", "meta": {"hexsha": "107b6d56ade1dc50a2e792e51bd87abf8f1d93d1", "size": 5308, "ext": "c", "lang": "C", "max_stars_repo_path": "particle_packing/cython/c/circle.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/circle.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/circle.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": 17.9324324324, "max_line_length": 103, "alphanum_fraction": 0.4498869631, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6560161797562305}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define READ_MATCHES_GOODNESS_A 1.4421650782960167E+01\n#define READ_MATCHES_GOODNESS_B 2.7010890377990435E+01\n#define READ_MATCHES_GOODNESS_C ONE_THIRD\n#define READ_MATCHES_GOODNESS_D -2.4490239433470165E+00\n\n#define MAXIMUM_SCORE_COEFF 2.61 // Only if MATCH_SCORE_RANK_INDEX=-1.5. This comes from Wolfram Alpha. Query \"sum k^(-1.5) from k = 1 to N\"\n#define EULER_MASCHERONI_CONST 0.5772 // Used if MATCH_SCORE_RANK_INDEX=-1\n\nfloat maximum_match_score(double n_particles) {\n if(n_particles < 1)\n return (0);\n if(MATCH_SCORE_RANK_INDEX == (-1.5))\n return (MAXIMUM_SCORE_COEFF - gsl_sf_hzeta(-MATCH_SCORE_RANK_INDEX, n_particles));\n else if(MATCH_SCORE_RANK_INDEX == (-1.))\n return (EULER_MASCHERONI_CONST + take_ln(n_particles));\n else if(MATCH_SCORE_RANK_INDEX == (-TWO_THIRDS))\n return ((float)pow(READ_MATCHES_GOODNESS_A + READ_MATCHES_GOODNESS_B * n_particles, READ_MATCHES_GOODNESS_C) + READ_MATCHES_GOODNESS_D);\n else\n SID_exit_error(\n \"Invalid MATCH_SCORE_RANK_INDEX passed to maximum_match_score(). Please update the code to accomodate MATCH_SCORE_RANK_INDEX=%lf.\",\n SID_ERROR_LOGIC, MATCH_SCORE_RANK_INDEX);\n}\n", "meta": {"hexsha": "eac93a09b83a676b395777d76218b87425da2e39", "size": 1376, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpHalos/maximum_match_score.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/gbpHalos/maximum_match_score.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/gbpHalos/maximum_match_score.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": 43.0, "max_line_length": 148, "alphanum_fraction": 0.7441860465, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.6560057484182359}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nint\nmain(void)\n{\n const size_t N = 500; /* length of time series */\n const size_t K = 51; /* window size */\n const double alpha[3] = { 0.5, 3.0, 10.0 }; /* alpha values */\n gsl_vector *x = gsl_vector_alloc(N); /* input vector */\n gsl_vector *y1 = gsl_vector_alloc(N); /* filtered output vector for alpha1 */\n gsl_vector *y2 = gsl_vector_alloc(N); /* filtered output vector for alpha2 */\n gsl_vector *y3 = gsl_vector_alloc(N); /* filtered output vector for alpha3 */\n gsl_vector *k1 = gsl_vector_alloc(K); /* Gaussian kernel for alpha1 */\n gsl_vector *k2 = gsl_vector_alloc(K); /* Gaussian kernel for alpha2 */\n gsl_vector *k3 = gsl_vector_alloc(K); /* Gaussian kernel for alpha3 */\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n gsl_filter_gaussian_workspace *gauss_p = gsl_filter_gaussian_alloc(K);\n size_t i;\n double sum = 0.0;\n\n /* generate input signal */\n for (i = 0; i < N; ++i)\n {\n double ui = gsl_ran_gaussian(r, 1.0);\n sum += ui;\n gsl_vector_set(x, i, sum);\n }\n\n /* compute kernels without normalization */\n gsl_filter_gaussian_kernel(alpha[0], 0, 0, k1);\n gsl_filter_gaussian_kernel(alpha[1], 0, 0, k2);\n gsl_filter_gaussian_kernel(alpha[2], 0, 0, k3);\n\n /* apply filters */\n gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha[0], 0, x, y1, gauss_p);\n gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha[1], 0, x, y2, gauss_p);\n gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha[2], 0, x, y3, gauss_p);\n\n /* print kernels */\n for (i = 0; i < K; ++i)\n {\n double k1i = gsl_vector_get(k1, i);\n double k2i = gsl_vector_get(k2, i);\n double k3i = gsl_vector_get(k3, i);\n\n printf(\"%e %e %e\\n\", k1i, k2i, k3i);\n }\n\n printf(\"\\n\\n\");\n\n /* print filter results */\n for (i = 0; i < N; ++i)\n {\n double xi = gsl_vector_get(x, i);\n double y1i = gsl_vector_get(y1, i);\n double y2i = gsl_vector_get(y2, i);\n double y3i = gsl_vector_get(y3, i);\n\n printf(\"%.12e %.12e %.12e %.12e\\n\", xi, y1i, y2i, y3i);\n }\n\n gsl_vector_free(x);\n gsl_vector_free(y1);\n gsl_vector_free(y2);\n gsl_vector_free(y3);\n gsl_vector_free(k1);\n gsl_vector_free(k2);\n gsl_vector_free(k3);\n gsl_rng_free(r);\n gsl_filter_gaussian_free(gauss_p);\n\n return 0;\n}\n", "meta": {"hexsha": "a4a1a28c257a93a313f574a91b544fdfcd26b1ac", "size": 2512, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/gaussfilt.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/doc/examples/gaussfilt.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/gaussfilt.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": 31.012345679, "max_line_length": 86, "alphanum_fraction": 0.6277866242, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7577943822145997, "lm_q1q2_score": 0.655661938599444}} {"text": "#ifndef UTILITIES_H\n#define UTILITIES_H\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 \"Structures.h\"\n#include \n\nusing namespace std;\nusing namespace boost::math;\nusing namespace Eigen;\nusing namespace cv;\n\nnamespace Eigen {\n namespace internal {\n template\n struct scalar_normal_dist_op\n {\n static boost::mt19937 rng; // The uniform pseudo-random algorithm\n mutable boost::normal_distribution norm; // The gaussian combinator\n EIGEN_EMPTY_STRUCT_CTOR(scalar_normal_dist_op)\n template\n inline const Scalar operator() (Index, Index = 0) const { return norm(rng); }\n };\n template boost::mt19937 scalar_normal_dist_op::rng;\n template\n struct functor_traits >{\n enum{\n Cost = 50 * NumTraits::MulCost, PacketAccess = false, IsRepeatable = false\n };\n };\n }\n}\nclass Utilities{\n public:\n Utilities();\n virtual ~Utilities();\n //Read a file that has a specific number of dimensions for each attribute\n virtual vector < vector < vector > > readFile(string CloudSeperator, string filepath);\n double multivariateNormalPDF(Vector3d instance, Vector3d mu, Matrix3d covar, int dimensionality);\n Eigen::MatrixXd sampleMultivariateNormal( Eigen::VectorXd mean, Eigen::MatrixXd covar, int numOfSamples, int dimensionality);\n Eigen::MatrixXd sampleMultinomial(vector probabilities, int samples);\n int randcat( vector * vec);\n Eigen::Matrix3d iwishrnd( Matrix3d tau, double nu, int dimensionality, int df);\n Eigen::VectorXd exprnd(double rate, int samples);\n double exppdf(double x , double lambda);\n double gammarnd(double alpha , double beta);\n RowVectorXd dirrnd(RowVectorXd q0);\n double catpdf(int index , vector probabilities);\n // Exponential distribution distances\n double Expsquaredhellinger(double lambda1, double lambda2);\n double ExpKLDivergence(double lambda1, double lambda2);\n // Gaussian distribution distances\n double GaussKLDivergence(std::vector mean1, Matrix3d covar1, std::vector mean2, Matrix3d covar2 );\n double Wasserstein(std::vector mean1, Matrix3d covar1, std::vector mean2, Matrix3d covar2 );\n\n vector categoricalhistogramCompare( float histA[], float histB[] , int N);\n float categoricalKLDivergence( cv::Mat * mat1, cv::Mat * mat2);\n protected:\n private:\n};\n#endif // UTILITIES_H\n", "meta": {"hexsha": "cb5de0085e1f71ce85579dc4314468b7137b9b05", "size": 3037, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Utilities.h", "max_stars_repo_name": "hadjichristslave/SMC", "max_stars_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "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/Utilities.h", "max_issues_repo_name": "hadjichristslave/SMC", "max_issues_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T12:34:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-13T13:12:04.000Z", "max_forks_repo_path": "include/Utilities.h", "max_forks_repo_name": "hadjichristslave/SMC", "max_forks_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "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.602739726, "max_line_length": 133, "alphanum_fraction": 0.694435298, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6553296168015399}} {"text": "/* fft/bitreverse.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\n#include \"complex_internal.h\"\n#include \"bitreverse.h\"\n\nstatic int \nFUNCTION(fft_complex,bitreverse_order) (BASE data[], \n const size_t stride,\n const size_t n,\n size_t logn)\n{\n /* This is the Goldrader bit-reversal algorithm */\n\n size_t i;\n size_t j = 0;\n\n logn = 0 ; /* not needed for this algorithm */\n\n for (i = 0; i < n - 1; i++)\n {\n size_t k = n / 2 ;\n\n if (i < j)\n {\n const BASE tmp_real = REAL(data,stride,i);\n const BASE tmp_imag = IMAG(data,stride,i);\n REAL(data,stride,i) = REAL(data,stride,j);\n IMAG(data,stride,i) = IMAG(data,stride,j);\n REAL(data,stride,j) = tmp_real;\n IMAG(data,stride,j) = tmp_imag;\n }\n\n while (k <= j) \n {\n j = j - k ;\n k = k / 2 ;\n }\n\n j += k ;\n }\n\n return 0;\n}\n\n\nstatic int \nFUNCTION(fft_real,bitreverse_order) (BASE data[], \n const size_t stride, \n const size_t n,\n size_t logn)\n{\n /* This is the Goldrader bit-reversal algorithm */\n\n size_t i;\n size_t j = 0;\n\n logn = 0 ; /* not needed for this algorithm */\n\n for (i = 0; i < n - 1; i++)\n {\n size_t k = n / 2 ;\n\n if (i < j)\n {\n const BASE tmp = VECTOR(data,stride,i);\n VECTOR(data,stride,i) = VECTOR(data,stride,j);\n VECTOR(data,stride,j) = tmp;\n }\n\n while (k <= j) \n {\n j = j - k ;\n k = k / 2 ;\n }\n\n j += k ;\n }\n\n return 0;\n}\n\n", "meta": {"hexsha": "15e0e8a2510e862a741cabdd8a25b5910a3f19e9", "size": 2519, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/fft/bitreverse.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/fft/bitreverse.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/fft/bitreverse.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.6960784314, "max_line_length": 81, "alphanum_fraction": 0.5387058356, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6546253409764012}} {"text": "/* cdf/poisson.c\n *\n * Copyright (C) 2004 Jason H. Stover.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n/*\n * Computes the cumulative distribution function for a Poisson\n * random variable. For a Poisson random variable X with parameter\n * mu,\n *\n * Pr( X <= k ) = Pr( Y >= p )\n *\n * where Y is a gamma random variable with parameters k+1 and 1.\n *\n * Reference: \n * \n * W. Feller, \"An Introduction to Probability and Its\n * Applications,\" volume 1. Wiley, 1968. Exercise 46, page 173,\n * chapter 6.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n/*\n * Pr (X <= k) for a Poisson random variable X.\n */\n\ndouble\ngsl_cdf_poisson_P (const unsigned int k, const double mu)\n{\n double P;\n double a;\n\n if (mu <= 0.0)\n {\n CDF_ERROR (\"mu <= 0\", GSL_EDOM);\n }\n\n a = (double) k + 1.0;\n P = gsl_cdf_gamma_Q (mu, a, 1.0);\n\n return P;\n}\n\n/*\n * Pr ( X > k ) for a Possion random variable X.\n */\n\ndouble\ngsl_cdf_poisson_Q (const unsigned int k, const double mu)\n{\n double Q;\n double a;\n\n if (mu <= 0.0)\n {\n CDF_ERROR (\"mu <= 0\", GSL_EDOM);\n }\n\n a = (double) k + 1.0;\n Q = gsl_cdf_gamma_P (mu, a, 1.0);\n\n return Q;\n}\n", "meta": {"hexsha": "cab04505ee2f0802ad40cd362807c81855577454", "size": 1914, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/cdf/poisson.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/cdf/poisson.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/cdf/poisson.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.5176470588, "max_line_length": 77, "alphanum_fraction": 0.657262278, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6545382848505933}} {"text": "/////////////////////////////////////////////////////////////////////////////////\n// \n// Levenberg - Marquardt non-linear minimization algorithm\n// Modified and simplified by Ted Laurence to use for MLE of Poisson-distributed data; Used only for \n//\t\tdouble precision, without constraints\n// Copyright (C) 2004 Manolis Lourakis (lourakis at ics forth gr)\n// Institute of Computer Science, Foundation for Research & Technology - Hellas\n// Heraklion, Crete, Greece.\n//\n// Modifications Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. Written by Ted Laurence (laurence2@llnl.gov)\n// LLNL-CODE-424602 All rights reserved.\n// This file is part of dlevmar_mle_der\n//\n// Please also read Our Notice and GNU General Public License.\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation; either version 2 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n/////////////////////////////////////////////////////////////////////////////////\n#include \n#include \n#include \n\n#include \"levmar_mle.h\"\n#include \"lm_mle_compiler.h\"\n\n#define EPSILON 1E-12\n#define ONE_THIRD 0.3333333334 /* 1.0/3.0 */\n#define LM_REAL_MAX FLT_MAX\n#define LM_REAL_MIN -FLT_MAX\n\n\n\n\ndouble compute_chisq_measure(double *e, double *x, double *hx, int n, int fitType)\n{\n\tint i;\n\tdouble chisq=0.0;\n\n\tswitch (fitType)\n\t{\n\tcase LM_CHISQ_MLE:\n\t\tfor (i=0; i 0)\n\t\t\t{\n\t\t\t\tif (x[i]==0)\n\t\t\t\t\tchisq += 2 * hx[i];\n\t\t\t\telse\n\t\t\t\t\tchisq += 2 * (hx[i]-x[i]-x[i]*log(hx[i]/x[i]));\n\t\t\t\te[i]=x[i]/hx[i]-1.0;\n\t\t\t}\n\t\t\telse\n\t\t\t\te[i]=0.0;\n\t\t}\n\t\tbreak;\n\tcase LM_CHISQ_NEYMAN: \n\t\tfor (i=0; i R^n with n>=m,\n * it finds p s.t. func(p) ~= x, i.e. the squared second order (i.e. L2) norm of\n * e=x-func(p) is minimized.\n *\n * This function requires an analytic Jacobian. \n *\n * Returns the number of iterations (>=0) if successful, LM_ERROR if failed\n *\n * For more details, see K. Madsen, H.B. Nielsen and O. Tingleff's lecture notes on \n * non-linear least squares at http://www.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf\n */\n\nint dlevmar_mle_der(\n void (*func)(double *p, double *hx, int m, int n, void *adata), /* functional relation describing measurements. A p \\in R^m yields a \\hat{x} \\in R^n */\n void (*jacf)(double *p, double *j, int m, int n, void *adata), /* function to evaluate the Jacobian \\part x / \\part p */ \n double *p, /* I/O: initial parameter estimates. On output has the estimated solution */\n double *x, /* I: measurement vector. NULL implies a zero vector */\n int m, /* I: parameter vector dimension (i.e. #unknowns) */\n int n, /* I: measurement vector dimension */\n int itmax, /* I: maximum number of iterations */\n double opts[5], /* I: minim. options [\\mu, \\epsilon1, \\epsilon2, \\epsilon3,\\epsilon4]. Respectively the scale factor for initial \\mu,\n * stopping thresholds for ||J^T e||_inf, ||Dp||_2, chisq, and delta_chisq. Set to NULL for defaults to be used\n */\n double info[LM_INFO_SZ],\n\t\t\t\t\t /* O: information regarding the minimization. Set to NULL if don't care\n * info[0]= ||e||_2 at initial p.\n * info[1-4]=[ ||e||_2, ||J^T e||_inf, ||Dp||_2, mu/max[J^T J]_ii ], all computed at estimated p.\n * info[5]= # iterations,\n * info[6]=reason for terminating: 1 - stopped by small gradient J^T e\n * 2 - stopped by small Dp\n * 3 - stopped by itmax\n * 4 - singular matrix. Restart from current p with increased mu \n * 5 - no further error reduction is possible. Restart with increased mu\n * 6 - stopped by small ||e||_2\n * 7 - stopped by invalid (i.e. NaN or Inf) \"func\" values. This is a user error\n\t\t\t\t\t *\t\t\t\t\t\t\t\t\t8 - stopped by small change in chisq on successful iteration (dF0; )\n\t\tjacTjac[i]=0.0;\n\t for(i=m; i-->0; )\n\t\tjacTe[i]=0.0;\n\n\t for(l=n; l-->0; ){\n\t\tjaclm=jac+l*m;\n\t\tswitch (fitType)\n\t\t{\n\t\tcase LM_CHISQ_MLE:\n\t\t\tif (hx[l]>0)\n\t\t\t\twt=x[l]/(hx[l]*hx[l]);\n\t\t\telse\n\t\t\t\twt=0.0;\n\t\t\tbreak;\n\t\tcase LM_CHISQ_NEYMAN: \n\t\t\tif (x[l]==0)\n\t\t\t\twt=1.0;\n\t\t\telse\n\t\t\t\twt=1.0/x[l];\n\t\t\tbreak;\n\t\tcase LM_CHISQ_EQUAL_WT:\n\t\t\twt=1.0;\n\t\t\tbreak;\n\t\t}\n\t\tfor(i=m; i-->0; ){\n\t\t im=i*m;\n\t\t alpha=jaclm[i]; //jac[l*m+i];\n\t\t for(j=i+1; j-->0; ) /* j<=i computes lower triangular part only */\n\t\t\tjacTjac[im+j]+=jaclm[j]*alpha*wt; //jac[l*m+j]\n\n\t\t /* J^T e */\n\t\t jacTe[i]+=alpha*e[l];\n\t\t}\n\t }\n\n\t for(i=m; i-->0; ) /* copy to upper part */\n\t\tfor(j=i+1; jtmp) tmp=diag_jacTjac[i]; /* find max diagonal element */\n mu=tau*tmp;\n }\n\n /* determine increment using adaptive damping */\n while(1){\n /* augment normal equations */\n for(i=0; i=(p_L2+eps2)/EPSILON*EPSILON){ /* almost singular */\n// stop=4;\n// break;\n// }\n\n (*func)(pDp, hx, m, n, adata); ++nfev; /* evaluate function at p + Dp */\n /* compute ||e(pDp)||_2 */\n /* ### hx=x-hx, pDp_chisq=||hx|| */\n pDp_chisq= compute_chisq_measure(e_test, x, hx, n, fitType);\n\n\t\tif(!LM_FINITE(pDp_chisq)){ /* chisq is not finite, most probably due to a user error.\n * This check makes sure that the inner loop does not run indefinitely.\n * Thanks to Steve Danauskas for reporting such cases\n */\n stop=7;\n break;\n }\n\n for(i=0, dL=0.0; i0.0 && dF>0.0){ /* reduction in error, increment is accepted */\n tmp=(2.0*dF/dL-1.0);\n tmp=1.0-tmp*tmp*tmp;\n mu=mu*( (tmp>=ONE_THIRD)? tmp : ONE_THIRD );\n nu=2;\n\n for(i=0 ; i=itmax) stop=3;\n\n for(i=0; i\n#include \n\n#include \n#include \n// you need to add the following libraries to your project : gsl, gslcblas\n\nclass Vec3 {\nprivate:\n float mVals[3];\npublic:\n Vec3() {}\n Vec3( float x , float y , float z ) {\n mVals[0] = x; mVals[1] = y; mVals[2] = z;\n }\n float & operator [] (unsigned int c) { return mVals[c]; }\n float operator [] (unsigned int c) const { return mVals[c]; }\n void operator = (Vec3 const & other) {\n mVals[0] = other[0] ; mVals[1] = other[1]; mVals[2] = other[2];\n }\n float squareLength() const {\n return mVals[0]*mVals[0] + mVals[1]*mVals[1] + mVals[2]*mVals[2];\n }\n float length() const { return sqrt( squareLength() ); }\n void normalize() { float L = length(); mVals[0] /= L; mVals[1] /= L; mVals[2] /= L; }\n static float dot( Vec3 const & a , Vec3 const & b ) {\n return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];\n }\n static Vec3 cross( Vec3 const & a , Vec3 const & b ) {\n return Vec3( a[1]*b[2] - a[2]*b[1] ,\n a[2]*b[0] - a[0]*b[2] ,\n a[0]*b[1] - a[1]*b[0] );\n }\n void operator += (Vec3 const & other) {\n mVals[0] += other[0];\n mVals[1] += other[1];\n mVals[2] += other[2];\n }\n void operator -= (Vec3 const & other) {\n mVals[0] -= other[0];\n mVals[1] -= other[1];\n mVals[2] -= other[2];\n }\n void operator *= (float s) {\n mVals[0] *= s;\n mVals[1] *= s;\n mVals[2] *= s;\n }\n void operator /= (float s) {\n mVals[0] /= s;\n mVals[1] /= s;\n mVals[2] /= s;\n }\n\n static Vec3 Rand(float magnitude = 1.f) {\n return Vec3( magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) , magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) , magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) );\n }\n\n Vec3 getOrthogonal() const {\n // CAREFUL ! THE NORM IS NOT PRESERVED !!!!\n if( mVals[0] == 0 ) {\n return Vec3( 0 , mVals[2] , -mVals[1] );\n }\n else if( mVals[1] == 0 ) {\n return Vec3( mVals[2] , 0 , -mVals[0] );\n }\n return Vec3( mVals[1] , -mVals[0] , 0 );\n }\n};\n\nstatic inline Vec3 operator + (Vec3 const & a , Vec3 const & b) {\n return Vec3(a[0]+b[0] , a[1]+b[1] , a[2]+b[2]);\n}\nstatic inline Vec3 operator - (Vec3 const & a , Vec3 const & b) {\n return Vec3(a[0]-b[0] , a[1]-b[1] , a[2]-b[2]);\n}\nstatic inline Vec3 operator * (float a , Vec3 const & b) {\n return Vec3(a*b[0] , a*b[1] , a*b[2]);\n}\nstatic inline Vec3 operator / (Vec3 const & a , float b) {\n return Vec3(a[0]/b , a[1]/b , a[2]/b);\n}\nstatic inline std::ostream & operator << (std::ostream & s , Vec3 const & p) {\n s << p[0] << \" \" << p[1] << \" \" << p[2];\n return s;\n}\nstatic inline std::istream & operator >> (std::istream & s , Vec3 & p) {\n s >> p[0] >> p[1] >> p[2];\n return s;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Mat3\n{\npublic:\n //////////// CONSTRUCTORS //////////////\n Mat3()\n {\n vals[0] = 0;\n vals[1] = 0;\n vals[2] = 0;\n vals[3] = 0;\n vals[4] = 0;\n vals[5] = 0;\n vals[6] = 0;\n vals[7] = 0;\n vals[8] = 0;\n }\n Mat3( float v1 , float v2 , float v3 , float v4 , float v5 , float v6 , float v7 , float v8 , float v9)\n {\n vals[0] = v1;\n vals[1] = v2;\n vals[2] = v3;\n vals[3] = v4;\n vals[4] = v5;\n vals[5] = v6;\n vals[6] = v7;\n vals[7] = v8;\n vals[8] = v9;\n }\n Mat3( const Mat3 & m )\n {\n for(int i = 0 ; i < 3 ; ++i )\n for(int j = 0 ; j < 3 ; ++j )\n (*this)(i,j) = m(i,j);\n }\n\n\n bool isnan() const {\n return std::isnan(vals[0]) || std::isnan(vals[1]) || std::isnan(vals[2])\n || std::isnan(vals[3]) || std::isnan(vals[4]) || std::isnan(vals[5])\n || std::isnan(vals[6]) || std::isnan(vals[7]) || std::isnan(vals[8]);\n }\n\n\n void operator = (const Mat3 & m)\n {\n for(int i = 0 ; i < 3 ; ++i )\n for(int j = 0 ; j < 3 ; ++j )\n (*this)(i,j) = m(i,j);\n }\n\n\n\n\n void operator += (const Mat3 & m)\n {\n for(int i = 0 ; i < 3 ; ++i )\n for(int j = 0 ; j < 3 ; ++j )\n (*this)(i,j) += m(i,j);\n }\n void operator -= (const Mat3 & m)\n {\n for(int i = 0 ; i < 3 ; ++i )\n for(int j = 0 ; j < 3 ; ++j )\n (*this)(i,j) -= m(i,j);\n }\n void operator /= (double s)\n {\n for( unsigned int c = 0 ; c < 9 ; ++c )\n vals[c] /= s;\n }\n\n\n\n Mat3 operator - (const Mat3 & m2)\n {\n return Mat3( (*this)(0,0)-m2(0,0) , (*this)(0,1)-m2(0,1) , (*this)(0,2)-m2(0,2) , (*this)(1,0)-m2(1,0) , (*this)(1,1)-m2(1,1) , (*this)(1,2)-m2(1,2) , (*this)(2,0)-m2(2,0) , (*this)(2,1)-m2(2,1) , (*this)(2,2)-m2(2,2) );\n }\n Mat3 operator + (const Mat3 & m2)\n {\n return Mat3( (*this)(0,0)+m2(0,0) , (*this)(0,1)+m2(0,1) , (*this)(0,2)+m2(0,2) , (*this)(1,0)+m2(1,0) , (*this)(1,1)+m2(1,1) , (*this)(1,2)+m2(1,2) , (*this)(2,0)+m2(2,0) , (*this)(2,1)+m2(2,1) , (*this)(2,2)+m2(2,2) );\n }\n\n\n\n\n Mat3 operator / (float s)\n {\n return Mat3( (*this)(0,0)/s , (*this)(0,1)/s , (*this)(0,2)/s , (*this)(1,0)/s , (*this)(1,1)/s , (*this)(1,2)/s , (*this)(2,0)/s , (*this)(2,1)/s , (*this)(2,2)/s );\n }\n Mat3 operator * (float s)\n {\n return Mat3( (*this)(0,0)*s , (*this)(0,1)*s , (*this)(0,2)*s , (*this)(1,0)*s , (*this)(1,1)*s , (*this)(1,2)*s , (*this)(2,0)*s , (*this)(2,1)*s , (*this)(2,2)*s );\n }\n\n\n Vec3 operator * (const Vec3 & p) // computes m.p\n {\n return Vec3(\n (*this)(0,0)*p[0] + (*this)(0,1)*p[1] + (*this)(0,2)*p[2],\n (*this)(1,0)*p[0] + (*this)(1,1)*p[1] + (*this)(1,2)*p[2],\n (*this)(2,0)*p[0] + (*this)(2,1)*p[1] + (*this)(2,2)*p[2]);\n }\n\n Mat3 operator * (const Mat3 & m2)\n {\n return Mat3(\n (*this)(0,0)*m2(0,0) + (*this)(0,1)*m2(1,0) + (*this)(0,2)*m2(2,0) ,\n (*this)(0,0)*m2(0,1) + (*this)(0,1)*m2(1,1) + (*this)(0,2)*m2(2,1) ,\n (*this)(0,0)*m2(0,2) + (*this)(0,1)*m2(1,2) + (*this)(0,2)*m2(2,2) ,\n (*this)(1,0)*m2(0,0) + (*this)(1,1)*m2(1,0) + (*this)(1,2)*m2(2,0) ,\n (*this)(1,0)*m2(0,1) + (*this)(1,1)*m2(1,1) + (*this)(1,2)*m2(2,1) ,\n (*this)(1,0)*m2(0,2) + (*this)(1,1)*m2(1,2) + (*this)(1,2)*m2(2,2) ,\n (*this)(2,0)*m2(0,0) + (*this)(2,1)*m2(1,0) + (*this)(2,2)*m2(2,0) ,\n (*this)(2,0)*m2(0,1) + (*this)(2,1)*m2(1,1) + (*this)(2,2)*m2(2,1) ,\n (*this)(2,0)*m2(0,2) + (*this)(2,1)*m2(1,2) + (*this)(2,2)*m2(2,2)\n );\n }\n\n\n\n\n\n //////// ACCESS TO COORDINATES /////////\n float operator () (unsigned int i , unsigned int j) const\n { return vals[3*i + j]; }\n float & operator () (unsigned int i , unsigned int j)\n { return vals[3*i + j]; }\n\n\n\n\n\n\n\n\n\n //////// BASICS /////////\n inline float sqrnorm()\n {\n return vals[0]*vals[0] + vals[1]*vals[1] + vals[2]*vals[2]\n + vals[3]*vals[3] + vals[4]*vals[4] + vals[5]*vals[5]\n + vals[6]*vals[6] + vals[7]*vals[7] + vals[8]*vals[8];\n }\n\n inline float norm()\n { return sqrt( sqrnorm() ); }\n\n inline float determinant() const\n {\n return vals[0] * ( vals[4] * vals[8] - vals[7] * vals[5] )\n - vals[1] * ( vals[3] * vals[8] - vals[6] * vals[5] )\n + vals[2] * ( vals[3] * vals[7] - vals[6] * vals[4] );\n }\n\n\n static\n Mat3 pseudoInverse( Mat3 const & m , bool & isRealInverse , double defaultValueForInverseSingularValue = 0.0 )\n {\n float det = m.determinant();\n if( fabs(det) != 0.0 )\n {\n isRealInverse = true;\n return Mat3( m(1,1)*m(2,2) - m(2,1)*m(1,2) , m(0,2)*m(2,1) - m(0,1)*m(2,2) , m(0,1)*m(1,2) - m(0,2)*m(1,1) ,\n m(1,2)*m(2,0) - m(1,0)*m(2,2) , m(0,0)*m(2,2) - m(0,2)*m(2,0) , m(0,2)*m(1,0) - m(0,0)*m(1,2) ,\n m(1,0)*m(2,1) - m(1,1)*m(2,0) , m(0,1)*m(2,0) - m(0,0)*m(2,1) , m(0,0)*m(1,1) - m(0,1)*m(1,0) ) / det ;\n }\n\n // otherwise:\n isRealInverse = false;\n Mat3 U ; float sx ; float sy ; float sz ; Mat3 Vt;\n m.SVD(U,sx,sy,sz,Vt);\n float sxInv = sx == 0.0 ? 1.0 / sx : defaultValueForInverseSingularValue;\n float syInv = sy == 0.0 ? 1.0 / sy : defaultValueForInverseSingularValue;\n float szInv = sz == 0.0 ? 1.0 / sz : defaultValueForInverseSingularValue;\n return Vt.getTranspose() * Mat3::diag(sxInv , syInv , szInv) * U.getTranspose();\n }\n\n\n inline float trace() const\n { return vals[0] + vals[4] + vals[8]; }\n\n\n\n\n //////// TRANSPOSE /////////\n inline\n void transpose()\n {\n float xy = vals[1] , xz = vals[2] , yz = vals[5];\n vals[1] = vals[3];\n vals[3] = xy;\n vals[2] = vals[6];\n vals[6] = xz;\n vals[5] = vals[7];\n vals[7] = yz;\n }\n Mat3 getTranspose() const\n {\n return Mat3(vals[0],vals[3],vals[6],vals[1],vals[4],vals[7],vals[2],vals[5],vals[8]);\n }\n\n\n\n\n\n\n\n // ---------- ROTATION <-> AXIS/ANGLE ---------- //\n template< class point_t >\n void getAxisAndAngleFromRotationMatrix( point_t & axis , float & angle )\n {\n angle = acos( (trace() - 1.f) / 2.f );\n axis[0] = vals[7] - vals[5];\n axis[1] = vals[2] - vals[6];\n axis[2] = vals[3] - vals[1];\n axis.normalize();\n }\n\n template< class point_t >\n inline static\n Mat3 getRotationMatrixFromAxisAndAngle( const point_t & axis , float angle )\n {\n Mat3 w = vectorial(axis);\n return Identity() + w * std::sin(angle) + w * w * ((1.0) - std::cos(angle));\n }\n\n\n\n // ---------- STATIC STANDARD MATRICES ---------- //\n inline static Mat3 Identity()\n { return Mat3(1,0,0 , 0,1,0 , 0,0,1); }\n\n inline static Mat3 Zero()\n { return Mat3(0,0,0 , 0,0,0 , 0,0,0); }\n\n template< typename T2 >\n inline static Mat3 diag( T2 x , T2 y ,T2 z )\n { return Mat3(x,0,0 , 0,y,0 , 0,0,z); }\n\n\n template< class point_t >\n inline static Mat3 getFromCols(const point_t & c1 , const point_t & c2 , const point_t & c3)\n {\n // 0 1 2\n // 3 4 5\n // 6 7 8\n return Mat3( c1[0] , c2[0] , c3[0] ,\n c1[1] , c2[1] , c3[1] ,\n c1[2] , c2[2] , c3[2] );\n }\n template< class point_t >\n inline static Mat3 getFromRows(const point_t & r1 , const point_t & r2 , const point_t & r3)\n {\n // 0 1 2\n // 3 4 5\n // 6 7 8\n return Mat3( r1[0] , r1[1] , r1[2] ,\n r2[0] , r2[1] , r2[2] ,\n r3[0] , r3[1] , r3[2] );\n }\n\n\n inline static Mat3 RandRotation()\n {\n Vec3 axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,\n -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,\n -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) );\n axis.normalize();\n float angle = 2.0 * M_PI * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 );\n\n return Mat3::getRotationMatrixFromAxisAndAngle( axis , angle );\n }\n\n inline static Mat3 RandRotation( float maxAngle )\n {\n Vec3 axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,\n -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,\n -1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) );\n axis.normalize();\n float angle = maxAngle * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 );\n\n return Mat3::getRotationMatrixFromAxisAndAngle( axis , angle );\n }\n\n\n inline static Mat3 RandRotation( Vec3 twistAxis , double maxTwist , double maxRotation )\n {\n twistAxis.normalize();\n Vec3 u = twistAxis.getOrthogonal();\n u.normalize();\n const Vec3 & v = Vec3::cross(u,twistAxis);\n\n double uv_axis_angle = 2.0*M_PI * (double)(rand()) / (double)(RAND_MAX);\n const Vec3 & uv = cos(uv_axis_angle)*u + sin(uv_axis_angle)*v;\n\n double rotation_angle = maxRotation * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 );\n double twist_angle = maxTwist * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 );\n\n return Mat3::getRotationMatrixFromAxisAndAngle(uv , rotation_angle) * Mat3::getRotationMatrixFromAxisAndAngle(twistAxis , twist_angle);\n }\n\n\n void SVD( Mat3 & U , float & sx , float & sy , float & sz , Mat3 & Vt ) const\n {\n gsl_matrix * u = gsl_matrix_alloc(3,3);\n for(unsigned int i = 0 ; i < 3; ++i)\n for(unsigned int j = 0 ; j < 3; ++j)\n gsl_matrix_set( u , i , j , (*this)(i,j) );\n\n gsl_matrix * v = gsl_matrix_alloc(3,3);\n gsl_vector * s = gsl_vector_alloc(3);\n gsl_vector * work = gsl_vector_alloc(3);\n\n gsl_linalg_SV_decomp (u,\n v,\n s,\n work);\n\n sx = s->data[0];\n sy = s->data[1];\n sz = s->data[2];\n for(unsigned int i = 0 ; i < 3; ++i)\n {\n for(unsigned int j = 0 ; j < 3; ++j)\n {\n U(i,j) = gsl_matrix_get( u , i , j );\n Vt(i,j) = gsl_matrix_get( v , j , i );\n }\n }\n\n gsl_matrix_free(u);\n gsl_matrix_free(v);\n gsl_vector_free(s);\n gsl_vector_free(work);\n\n // a transformation float is given as R.B.S.Bt, R = rotation , B = local basis (rotation matrix), S = scales in the basis B\n // it can be obtained from the svd decomposition of float = U Sigma Vt :\n // B = V\n // S = Sigma\n // R = U.Vt\n }\n\n\n\n\n\n\n\n // ---------- Projections onto Rotations ----------- //\n\n\n void setRotation()\n {\n Mat3 U,Vt;\n float sx,sy,sz;\n SVD(U,sx,sy,sz,Vt);\n const Mat3 & res = U*Vt;\n if( res.determinant() < 0 )\n {\n U(0,2) = -U(0,2);\n U(1,2) = -U(1,2);\n U(2,2) = -U(2,2);\n *this = (U*Vt);\n return;\n }\n // else\n *this = (res);\n }\n\n\n\n\n\n\n template< class point_t >\n inline static\n Mat3 tensor( const point_t & p1 , const point_t & p2 )\n {\n return Mat3(\n p1[0]*p2[0] , p1[0]*p2[1] , p1[0]*p2[2],\n p1[1]*p2[0] , p1[1]*p2[1] , p1[1]*p2[2],\n p1[2]*p2[0] , p1[2]*p2[1] , p1[2]*p2[2]);\n }\n\n template< class point_t >\n inline static\n Mat3 vectorial( const point_t & p )\n {\n return Mat3(\n 0 , -p[2] , p[1] ,\n p[2] , 0 , - p[0] ,\n - p[1] , p[0] , 0\n );\n }\n\n\n\n Mat3 operator - () const\n {\n return Mat3( - vals[0],- vals[1],- vals[2],- vals[3],- vals[4],- vals[5],- vals[6],- vals[7],- vals[8] );\n }\n\n\nprivate:\n float vals[9];\n // will be noted as :\n // 0 1 2\n // 3 4 5\n // 6 7 8\n};\n\n\n\ninline static\nMat3 operator * (float s , const Mat3 & m)\n{\n return Mat3( m(0,0)*s , m(0,1)*s , m(0,2)*s , m(1,0)*s , m(1,1)*s , m(1,2)*s , m(2,0)*s , m(2,1)*s , m(2,2)*s );\n}\n\n\ninline static std::ostream & operator << (std::ostream & s , Mat3 const & m)\n{\n s << m(0,0) << \" \\t\" << m(0,1) << \" \\t\" << m(0,2) << std::endl << m(1,0) << \" \\t\" << m(1,1) << \" \\t\" << m(1,2) << std::endl << m(2,0) << \" \\t\" << m(2,1) << \" \\t\" << m(2,2) << std::endl;\n return s;\n}\n\n\n#endif\n", "meta": {"hexsha": "085a5dd0b20b8460af4309a00b6447f05090970c", "size": 15799, "ext": "h", "lang": "C", "max_stars_repo_path": "HMIN323/TP4_MLS/src/Vec3.h", "max_stars_repo_name": "Eikins/M2-Imagina", "max_stars_repo_head_hexsha": "6e37ef755bd5312fc808ec599b3bd76084d35568", "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": "HMIN323/TP4_MLS/src/Vec3.h", "max_issues_repo_name": "Eikins/M2-Imagina", "max_issues_repo_head_hexsha": "6e37ef755bd5312fc808ec599b3bd76084d35568", "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": "HMIN323/TP4_MLS/src/Vec3.h", "max_forks_repo_name": "Eikins/M2-Imagina", "max_forks_repo_head_hexsha": "6e37ef755bd5312fc808ec599b3bd76084d35568", "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.5308411215, "max_line_length": 228, "alphanum_fraction": 0.4449648712, "num_tokens": 5807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6541435236969702}} {"text": "/*****************************************************************************\n* This program allows the reverberation time of a venue to be determined\n* blindly, using a sample of music or speech that is recorded in the venue\n* C implementation of Paul Kendrick's Matlab algorithm:\n*\n* Kendrick, Paul, et al. \"Blind estimation of reverberation parameters for\n* non-diffuse rooms.\" Acta Acustica united with Acustica 93.5 (2007): 760-770.\n*\n* C implementation by Kim Jones \n*****************************************************************************/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"butter_params.h\"\n#include \n\n#define\tMAX_PATH_SZ\t150\n#define SPLIT\t\t20\t\t/* Process wav in SPLIT segment(s) */\n#define MAX_CHUNK_SIZE\t1024 * 1024 * 1024\n#define WINDOW_WIDTH\t0.5\n#define OVERLAP\t\t0.98\n#define USE_HARD_BUTTER\t1\t\t/* Use butter_params.h if set */\n#define OCT_FILT_ORDER\t5\n#define ENV_FILT_ORDER\t4\n#define N_OCT \t\tOCT_FILT_ORDER * 2\n#define R_OCT \t\tN_OCT % 2\n#define L_OCT \t\t(N_OCT - R_OCT) / 2\n\n#define N_ENV \t\tENV_FILT_ORDER\n#define R_ENV \t\tN_ENV % 2\n#define L_ENV \t\t(N_ENV - R_ENV) / 2\n#define LOW_PASS_CUTOFF\t80.0\n#define DAMP_SEG_SIZE\t0.5\n#define DAMP_STEP_SIZE\t0.002\n#define MAX_RT\t\t100.0\t\n#define MIN_RT\t\t0.005\t\n#define\tBEST_S_NUM\t20000\t\t/* Set to 100000 in Matlab */\n#define PAR_UP_BOUND\t0.99999\n#define PAR_LOW_BOUND\t0.99\n#define SQP_STEP\t5\n//#define COARSE_DR_EST\t1\n#define SEG_LEN\t\t3 * 60\t\t/* 3 minutes */\n#define RT_DECAY\t25\t\t/* 25 = T20 decay; 35 = T30 decay */\n#define DISCARD_THRESH\t0\t\t/* Discard decay segs if <= this */\n\n/* Functions */\nvoid usage_func(void);\nint get_wav_data(char *filename);\nint compute_rt(int samp, int array_size, int *store_start, int *store_end, \n\tdouble *dr, double *a, double *b, double *alpha, double *mean_rt,\n\tdouble *rt_sd, int band, FILE *fh);\nint optimum_model(double a, double b, double alpha, double dr, int samp, int n,\n\tdouble *chan_2);\nint optimum_model_2(double **chan, int n, int chan_sz, int samp, double *lin);\nvoid hanning(int len, double *hann);\nint process_wav_data(int band, float *wav_data, SF_INFO input_info, \n\tSNDFILE *input, unsigned long long frames, double *p_alpha,\n\tdouble *p_a, double *p_b, double *p_dr, int *p_start, int *p_end, int\n\t*filt_frames);\nfloat * resamp_wav_data(SwrContext *resamp, int in_rate, uint64_t num_frames, \n\tint samp_freq, const uint8_t **wav_data, int *resamp_frms);\nfloat * oct_filt_data(float *output_data, int band_num, float samp_freq,\n\tint resamp_frames);\nfloat * get_envelope(float samp_freq, float *resampled_wav, \n\tint resamp_frames);\nint ** apply_polyfit(float samp_freq, int resamp_frames, float *env, \n\tint *s_e_size);\nint ** choose_segments(float *var, int step_size, int len, int not_dumped,\n\tint *seg_num_els);\nint perform_ml(int **start_end, float *env, int s_e_size, \n\tfloat *filtered_wav, int resamp_frames, int samp_freq,\n\tdouble **p_alpha, double **p_a_par, double **p_b_par, double **p_dr,\n\tint **p_start, int **p_end);\nint ml_fit(float *data_seg, int len, float samp_freq, double *a_par, \n\tdouble *b_par, double *alph_par);\ndouble get_decay_region(int c_len, double a, double b, double alpha,\n\t\tint len_store);\ndouble alpha_opt(int n, const double *a, double *grad, void *nldv);\ndouble par_3_opt(int n, const double *a, double *grad, void *nldv);\n\n/* Structs */\nstruct nl_extra_data {\n\tfloat *data_seg;\n\tint len;\n\tdouble a_val;\n\tdouble b_val;\n};\n\n\n/* Globals */\nint seg_len_val = SEG_LEN;\nint num_bands = 8;\nint octave_bands[] = {63, 125, 250, 500, 1000, 2000, 4000, 8000};\nint samp_freq_per_band[] = {3000, 3000, 3000, 3000, 3000, 6000, 12000, 24000};\nconst char fname[] = \"./blind_rts.log\";\n\n#if OCT_FILT_ORDER >= ENV_FILT_ORDER\n\tfloat butt_b[3 * (L_OCT + R_OCT)] = {0};\n\tfloat butt_a[3 * (L_OCT + R_OCT)] = {0};\n#else\n\tfloat butt_b[3 * (L_ENV + R_ENV)] = {0};\n\tfloat butt_a[3 * (L_ENV + R_ENV)] = {0};\n#endif\n\nint main(int argc, char *argv[])\n{\n\tdouble ret;\n\tchar filename[MAX_PATH_SZ];\n\n\tif (argc < 2 || argc > 3) {\n\t\tusage_func();\n\t\treturn 0;\n\t}\n\n\t/* Read optional seg_len_val amendment */\n\tif (argc == 3) {\n\t\tif (atoi(argv[2]) > 0 && atoi(argv[2]) < 10) {\n\t\t\tseg_len_val = atoi(argv[2]);\t\t\t\n\t\t\tprintf(\"Changing segment length to %d minutes\\n\",\n\t\t\t\tseg_len_val);\n\t\t}\n\t\t\t\n\t} \n\n\tif (snprintf(filename, MAX_PATH_SZ, \"%s\", argv[1]) >= MAX_PATH_SZ) {\n\t\tprintf(\"File path too long, please shorten the path / filename\\n\"\n\t\t\t\"Filename was truncated: %s\\n\", filename);\n\t\treturn 0;\n\t}\n\n\tret = get_wav_data(filename);\n\n\tif (ret < 0) {\n\t\tprintf(\"Error returned during calculations...\\n\");\n\t\treturn -1;\n\t} else {\n\t\tprintf(\"Results exported to log file: %s\\n\", fname);\n\t\tprintf(\"Exiting gracefully...\\n\");\n }\n\treturn 0;\n}\n\n\nvoid usage_func(void) {\n\tprintf(\"Usage:\\n\"\n\t\t\"./blind_rt_est [segment length]\\n\\n\"\n\t\t\"Wav file must be 16 bit signed and in mono channel format.\\n\\n\"\n\t\t\"Segment length is an optional command line parameter to\\n\"\n\t\t\"change the segment length from the default value (3 mins).\\n\"\n\t\t\"The audio is divided into segments for obtaining the RT;\\n\"\n\t\t\"there should be 36 decays of at least -25 dB in each \"\n\t\t\"segment.\\nIf you are unsure, just ignore this parameter and \"\n\t\t\"use the default value.\\n\");\n}\n\nint get_wav_data(char *filename) {\n\tSF_INFO input_info;\n\tfloat *wav_data;\n\tunsigned long long long_ret = 0;\t\n\tint *store_start, *store_end;\n\tint i, j, k, band, array_size, current_sz = 0, ret = 0;\n\tint filt_frm_tot, filt_frames;\n\tdouble *a, *b, *alpha, *dr, mean_rt, rt_sd;\n\ttime_t ct = time(NULL);\n\tFILE *fh = fopen(fname, \"a+\");\n\n\tif (fh == NULL) {\n\t\tprintf(\"Error opening log file!\\n\");\n\t\treturn 0;\n\t}\n\n\t/* Open file */\n\tinput_info.format = 0;\n\tSNDFILE *input = sf_open(filename, SFM_READ, &input_info);\n\n\tif (input == NULL) {\n\t\tprintf(\"Error opening Wav file!\\n\");\n\t\tusage_func();\n\t\treturn 0;\n\t} else\n\t\tprintf(\"Reading %s\\n\", filename);\n\n\t/* Print header data */\n\tprintf(\"Frames: %llu\\nSample Rate: %d\\nChannels: %d\\nFormat: 0x%X\\n\"\n\t\t\"Sections: %d\\nSeekable: %d\\n\",(unsigned long long) \n\t\tinput_info.frames, input_info.samplerate, input_info.channels, \n\t\tinput_info.format, input_info.sections, input_info.seekable);\n\n\t/* Check to make sure that the wav file is in the expected format:\n\t\tmono channel and 16 bit signed wav */\n\tif ((input_info.format & 0xFF000F) != 0x10002 &&\n\t\t\t(input_info.format & 0xFF000F) != 0x130002) {\n\t\tprintf(\"Program requires 16-bit signed wav.\\nMake sure format \"\n\t\t\t\"is 0x10002 or 0x130002.\\nExiting...\\n\");\n\t\tsf_close(input);\n\t\treturn 0;\n\t}\n\tif (input_info.channels != 1) {\n\t\tprintf(\"Input must be a single channel wav file. Exiting...\\n\");\n\t\tsf_close(input);\n\t\treturn 0;\n\t}\n\n\tfprintf(fh, \"=====================================================\\n\");\n\tfprintf(fh, \"Reverberation Time calculations: %s\\n\", filename);\n\tfprintf(fh, \"Time and Date: %s\\n\", ctime(&ct));\n\n\t/* Create arrays large enough to store values */\n\ta = calloc(BEST_S_NUM, sizeof(double));\n\tb = calloc(BEST_S_NUM, sizeof(double));\n\talpha = calloc(BEST_S_NUM, sizeof(double));\n\tdr = calloc(BEST_S_NUM, sizeof(double));\n\tstore_start = calloc(BEST_S_NUM, sizeof(int));\n\tstore_end = calloc(BEST_S_NUM, sizeof(int));\n\n\t/* Store data in array */\n\twav_data = (float *) calloc(input_info.frames / SPLIT, sizeof(float));\n\n\tif (wav_data == NULL) {\n\t\tprintf(\"Memory allocation error\\nExiting...\\n\");\n\t\tsf_close(input);\n\t\treturn -1;\n\t}\n\n\t/* Octave band filtering */\n\tfor (band = 0; band < 8; band++) {\n\t\tprintf(\"\\n\\nCalculations of Reverberation Time for %d Hz \"\n\t\t\t\"octave band.\\n\", octave_bands[band]);\n\t\tfprintf(fh, \"\\nCalculations of Reverberation Time for %d Hz \"\n\t\t\t\"octave band.\\n\", octave_bands[band]);\n\n\t\tarray_size = 0;\n\t\tcurrent_sz = 0;\n\t\tfilt_frm_tot = 0;\n\t\tfilt_frames = 0;\n\n\t\t/* Single channel, so can call this way */\n\t\tfor (i = 0; i < SPLIT; i++) {\n\t\t\tprintf(\"\\nPart %d of %d\\n\", i + 1, SPLIT);\n\n\t\t\tlong_ret = sf_read_float(input, wav_data, \n\t\t\t\t\tfloor(input_info.frames / SPLIT));\n\n\t\t\t/* Process the wav data */\n\t\t\tret = process_wav_data(band, wav_data, input_info,\n\t\t\t\tinput, long_ret, alpha, a, b,\n\t\t\t\tdr, store_start, store_end, &filt_frames);\n\n\t\t\t/* If ret < 0, error */\n\t\t\t/* If >= 0, ret is the size of the returned arrays */\n\t\t\tif (ret < 0) {\n\t\t\t\tfree(wav_data);\n\t\t\t\tsf_close(input);\n\t\t\t\treturn -1;\n\t\t\t} else {\n\t\t\t\tarray_size += ret;\n\t\t\t\tcurrent_sz = ret;\n\t\t\t\tfilt_frm_tot += filt_frames;\n\t\t\t}\n\n\t\t\tfor (k = 0; k < current_sz; k++) {\n\t\t\t\tstore_start[k] += (filt_frm_tot - filt_frames);\n\t\t\t\tstore_end[k] += (filt_frm_tot - filt_frames);\n\t\t\t}\n\n\t\t\ta += current_sz;\n\t\t\tb += current_sz;\n\t\t\talpha += current_sz;\n\t\t\tdr += current_sz;\n\t\t\tstore_start += current_sz;\n\t\t\tstore_end += current_sz;\n\n\n\t\t\t/* Reset bytes to zero */\n\t\t\tmemset(wav_data, 0, sizeof(float) *\n\t\t\t\t(input_info.frames / SPLIT));\n\t\t}\n\n\t\t/* Return the pointers to zero position */\n\t\tif (sf_seek(input, 0, SEEK_SET) < 0) {\n\t\t\tprintf(\"Error returning to start of wav!\\n\"\n\t\t\t\t\"Exiting...\\n\");\n\t\t\tfree(wav_data);\n\t\t\tsf_close(input);\n\t\t\treturn ret;\n\t\t}\n\n\t\ta -= array_size;\n\t\tb -= array_size;\n\t\talpha -= array_size;\n\t\tdr -= array_size;\n\t\tstore_start -= array_size;\n\t\tstore_end -= array_size;\n\n\t\t/* Compute the reverberation time (RT) */\n\t\tret = compute_rt(samp_freq_per_band[band],\n\t\t\tarray_size, store_start, store_end, dr, a, b,\n\t\t\talpha, &mean_rt, &rt_sd, octave_bands[band], fh);\n\n\t\tfprintf(fh, \"=============================================\\n\");\n\n\t\t/* Reset bytes to zero */\n\t\tmemset(a, 0, sizeof(double) * BEST_S_NUM);\n\t\tmemset(b, 0, sizeof(double) * BEST_S_NUM);\n\t\tmemset(alpha, 0, sizeof(double) * BEST_S_NUM);\n\t\tmemset(dr, 0, sizeof(double) * BEST_S_NUM);\n\t\tmemset(store_start, 0, sizeof(int) * BEST_S_NUM);\n\t\tmemset(store_end, 0, sizeof(int) * BEST_S_NUM);\n\t}\n\n\n\t/* Clean up */\n\tsf_close(input);\n\tfree(wav_data);\n\tfree(a);\n\tfree(b);\n\tfree(alpha);\n\tfree(dr);\n\tfree(store_start);\n\tfree(store_end);\n\tfclose(fh);\n\n\treturn ret;\n}\n\n\n/* \n * Compute RT for room \n */\nint compute_rt(int samp, int array_size, int *store_start, int *store_end, \n\t\tdouble *dr, double *a, double *b, double *alpha, \n\t\tdouble *mean_rt, double *rt_sd, int band, FILE *fh) {\n\tint n_seg, file_len, pos_to, pos_from, seg_len_n, i, j, k, l_reg, ret_sz;\n\tint min_5dB_index, min_rtdB_index, nan_count = 0;\n\tint n_chan = 4 * samp, l = 0, discard = 0;\n\tdouble **chan, *chan_opt, *chan_opt_log, sd_tmp;\n\tdouble *sd_rev_time, max, min_5dB, min_rtdB, **mat_a, mat_a_mul[2];\n\n\t/* SVDLIBC stuff */\n\tSVDRec svd_mat = svdNewSVDRec();\n\tDMat dmat_a_mat;\n\tSVDVerbosity = 0;\t/* 1: normal verbosity; 3: very verbose */\n\n\t/* Initialise */\n\t*mean_rt = 0.0;\n\t*rt_sd = 0.0;\n\n\tprintf(\"Computing the Reverberation Time...\\n\");\n\n\tchan = calloc(array_size, sizeof(double *));\n\tchan_opt = calloc(n_chan, sizeof(double));\n\tchan_opt_log = calloc(n_chan, sizeof(double));\n\n\tfor (i = 0; i < array_size; i++)\n\t\tchan[i] = calloc(n_chan, sizeof(double));\n\n\t/* Find the end position of the last decay phase by finding max\n\t *\tof store_end[] */\n\tfile_len = store_end[0];\n\tfor (i = 1; i < array_size; i++) {\n\t\tif (store_end[i] > file_len)\n\t\t\tfile_len = store_end[i];\n\t}\n\n\t/* seg_len_n is the number of samples in the length of time\n\t *\tchosen, seg_len. n_seg is the number of chunks, For\n\t *\texample, if seg_len_val = 180 secs and file_len = 6200\n\t *\tsamples, then n_seg = 3 chunks (2 chunks of 180 secs and\n\t *\t1 shorter chunk). */\n\tseg_len_n = seg_len_val * samp;\n\tn_seg = ceil((double)file_len / seg_len_n);\n\n\t/* Create array to store standard deviation values */\n\tsd_rev_time = calloc(n_seg, sizeof(double));\n\n\tfor (i = 0; i < n_seg; i++) {\n\t\t/* Get start and end positions of each chunk */\n\t\tpos_from = i * seg_len_n;\n\t\tpos_to = (i+1) * seg_len_n - 1;\n\n\t\t/* In case of partial chunk */\n\t\tif (i == n_seg - 1)\n\t\t\tpos_to = file_len;\n\n\t\tk = 0;\n\t\tfor (j = 0; j < array_size; j++) {\n\t\t\t/* Find decay rates < -25 dB */\n\t\t\tif (dr[j] < -25.0) {\n\t\t\t\t/* Does decay rate occur in this chunk? */\n\t\t\t\tif (store_start[j] >= pos_from && \n\t\t\t\t\t\tstore_end[j] < pos_to) {\n\t\t\t\t\t//printf(\"DR: %lf\\n\", dr[j]);\n\t\t\t\t\toptimum_model(a[j], b[j], alpha[j], dr[j],\n\t\t\t\t\t\t\tsamp, n_chan, \n\t\t\t\t\t\t\t&chan[k][0]);\n\n\t\t\t\t\tk++;\n\t\t\t\t\tl++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprintf(\"Segment: %d; Num Valid Decays: %d\\n\", i, k);\n\t\tfprintf(fh, \"Segment: %d; Num Valid Decays: %d\\n\", i, k);\n\n\t\tif (k <= DISCARD_THRESH) {\n\t\t\tdiscard++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tret_sz = optimum_model_2(chan, n_chan, k, samp, chan_opt);\n\n\t\t/* Get cumulative sum */\n\t\tchan_opt_log[ret_sz - 1] = pow(chan_opt[ret_sz - 1], 2);\n\t\tfor (j = ret_sz - 2; j >= 0; j--) {\n\t\t\tchan_opt_log[j] = pow(chan_opt[j], 2) +\n\t\t\t\tchan_opt_log[j + 1];\n\t\t}\n\n\t\t// DEBUG note: chan_opt_log[0] close to matlab\n\n\t\t/* Get max before getting log */\n\t\tmax = fabs(chan_opt_log[0]);\n\t\tfor (j = 1; j < ret_sz; j++) {\n\t\t\tif (fabs(chan_opt_log[j]) > max)\n\t\t\t\tmax = fabs(chan_opt_log[j]);\n\t\t}\n\n\t\tfor (j = 0; j < ret_sz; j++) {\n\t\t\t/* Convert to decibels */\n\t\t\tchan_opt_log[j] = 10 * log10(chan_opt_log[j] / max);\n\n\t\t\t/* Find -5 dB and -RT_DECAY dB decay points */\n\t\t\tif (j == 0) {\n\t\t\t\tmin_5dB = fabs(chan_opt_log[0] - (-5));\n\t\t\t\tmin_rtdB = fabs(chan_opt_log[0] - (-RT_DECAY));\n\t\t\t\tmin_5dB_index = 0;\n\t\t\t\tmin_rtdB_index = 0;\n\t\t\t} else {\n\t\t\t\tif (fabs(chan_opt_log[j] - (-5)) < min_5dB) {\n\t\t\t\t\tmin_5dB = fabs(chan_opt_log[j] - (-5));\n\t\t\t\t\tmin_5dB_index = j;\n\t\t\t\t}\n\n\t\t\t\tif (fabs(chan_opt_log[j]-(-RT_DECAY)) < min_rtdB) {\n\t\t\t\t\tmin_rtdB = fabs(chan_opt_log[j] -\n\t\t\t\t\t\t(-RT_DECAY));\n\t\t\t\t\tmin_rtdB_index = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tl_reg = min_rtdB_index - min_5dB_index + 1;\n\n\t\t/* Allocate space for mat_a */\n\t\tmat_a = calloc(l_reg, sizeof(double *));\n\t\tfor (k = 0; k < l_reg; k++)\n\t\t\tmat_a[k] = calloc(2, sizeof(double));\n\n\t\t/* Get the RT */\n\t\t/* Note: due to (possible bug?) in SVDLIBC, I need to normalise\n\t\t\tthe 2nd column of the matrix. I will multiply the RT\n\t\t\tat the end to compensate for the normalisation */\n\t\tfor (j = 0; j < l_reg; j++) {\n\t\t\tmat_a[j][0] = 1.0;\n\t\t\tmat_a[j][1] = ((double) (min_5dB_index + j)) /\n\t\t\t\tmin_rtdB_index;\n\t\t}\n\n\t\t/* Get the SVD of mat_a */\n\t\tdmat_a_mat = svdNewDMat(l_reg, 2);\n\t\tdmat_a_mat->value = mat_a;\t\t\t\t\n\n\t\tsvd_mat = svdLAS2A(svdConvertDtoS(dmat_a_mat), 0);\n\n\t\t/* Get reciprocal of S */\n\t\tfor (k = 0; k < 2; k++)\n\t\t\tsvd_mat->S[k] = 1.0 / svd_mat->S[k];\n\n\t\t/* Multiply modified S val by V */\n\t\tfor (k = 0; k < 2; k++)\n\t\t\tfor (j = 0; j < 2; j++)\n\t\t\t\tsvd_mat->Vt->value[k][j] *= svd_mat->S[k];\n\n\t\t/* Matrix multiplcation of modified V with U */\n\t\tfor (j = 0; j < l_reg; j++) {\n\t\t\tmat_a[j][0] = svd_mat->Ut->value[0][j] *\n\t\t\t\tsvd_mat->Vt->value[0][0];\n\n\t\t\tmat_a[j][1] = svd_mat->Ut->value[1][j] *\n\t\t\t\tsvd_mat->Vt->value[1][1];\n\n\t\t\tmat_a[j][0] += svd_mat->Ut->value[1][j] *\n\t\t\t\t\tsvd_mat->Vt->value[1][0];\n\n\t\t\tmat_a[j][1] += svd_mat->Ut->value[0][j] *\n\t\t\t\t\tsvd_mat->Vt->value[0][1];\n\n\t\t\t// DEBUG: MATLAB matches output when same values are\n\t\t\t//\tpassed to Matlab\n \t}\n\n\t\t/* Multiply pseudoinverse by sig */\n\t\tmat_a_mul[0] = 0.0;\n\t\tmat_a_mul[1] = 0.0;\n\t\tfor (j = 0; j < l_reg; j++) {\n\t\t\tmat_a_mul[0] += mat_a[j][0] *\n\t\t\t\tchan_opt_log[j + min_5dB_index];\n\t\t\tmat_a_mul[1] += mat_a[j][1] *\n\t\t\t\tchan_opt_log[j + min_5dB_index];\n\t\t}\n\n\t\t/* \n\t\t * If RT for segment != nan, add to rev_time\n\t\t */\n\t\tif(!isnan(-60.0 / (samp * mat_a_mul[1]))) {\n\t\t\tsd_rev_time[i - nan_count - discard] =\n\t\t\t\t((double) (-60.0 * min_rtdB_index)) /\n\t\t\t\t(samp * mat_a_mul[1]);\n\n\t\t\t*mean_rt += sd_rev_time[i - nan_count - discard];\n\t\t} else\n\t\t\tnan_count++;\n\n\t\t/* Free array */\n\t\tfor (k = 0; k < l_reg; k++)\n\t\t\tfree(mat_a[k]);\n\n\t\tfree(mat_a);\n\t}\n\n\tprintf(\"n_seg: %d; nan_count: %d; discarded seg: %d\\n\",\n\t\tn_seg, nan_count, discard);\n\tprintf(\"There are %d decays of at least -25 dB.\\n\", l);\n\tfprintf(fh, \"n_seg: %d; nan_count: %d; discarded seg: %d\\n\",\n\t\tn_seg, nan_count, discard);\n\tfprintf(fh, \"There are %d decays of at least -25 dB.\\n\", l);\n\n\t/* Get mean RT and standard dev of RT if num of valid RTs > 1 */\n\tif (n_seg - nan_count - discard > 1) {\n\t\t*mean_rt /= (n_seg - nan_count - discard);\n\n\t\tfor (sd_tmp = 0.0, i = 0; i < n_seg - nan_count - discard; i++)\n\t\t\tsd_tmp += pow(fabs(sd_rev_time[i] - *mean_rt), 2);\n\n\t\t*rt_sd = sqrt(sd_tmp / (n_seg - nan_count - discard - 1));\n\n\t\t/* Get standard error from std dist (97.5 percentile) */\n\t\t*rt_sd = (*rt_sd / sqrt(n_seg - nan_count - discard)) * 1.96;\n\t}\n\n\t\n\tprintf(\"Mean RT for %d band: %lf\\n\", band, *mean_rt);\n\tprintf(\"RT Standard Dev for %d band: %lf\\n\", band, *rt_sd);\n\tfprintf(fh, \"Mean RT for %d band: %lf\\n\", band, *mean_rt);\n\tfprintf(fh, \"RT Standard Dev for %d band: %lf\\n\\n\", band, *rt_sd);\n\n\t/* Free stuff */\n\tfor (i = 0; i < array_size; i++)\n\t\tfree(chan[i]);\n\n\tfree(chan);\n\tfree(chan_opt);\n\tfree(chan_opt_log);\n\tfree(sd_rev_time);\n\tsvdFreeSVDRec(svd_mat);\n\n\treturn 0;\n}\n\n\nint optimum_model(double a, double b, double alpha, double dr, int samp, int n,\n\t\tdouble *chan_2) {\n\tint i;\n\tdouble a_pow, b_pow, max;\n\n\tfor (i = 0; i < n; i++) {\n\t\ta_pow = pow(a, i);\n\t\tb_pow = pow(b, i);\n\t\tchan_2[i] = alpha * a_pow + (1 - alpha) * b_pow;\n\n\t\tif (i == 0)\n\t\t\tmax = fabs(chan_2[i]);\n\t\telse {\n\t\t\tif (fabs(chan_2[i]) > max)\n\t\t\t\tmax = fabs(chan_2[i]);\n\t\t}\n\t}\n\n\tfor (i = 0; i < n; i++)\n\t\tchan_2[i] /= max;\n\n\treturn 0;\n}\n\n\nint optimum_model_2(double **chan, int n, int chan_sz, int samp, double *lin) {\n\tdouble winn = 0.1;\n\tdouble over = 0.5;\n\tint nn = winn * samp;\n\tint i, j, k, n1, min_index, l_reg; \n\tint n0 = floor((1.0 - over) * nn);\n\tint n_sect = floor(((double)n - nn) / n0);\n\tdouble n2, min, chan_sum[chan_sz], *last; \n\tdouble win[nn * n_sect];\n\n\tlast = calloc(n, sizeof(double));\n\n\tfor (i = 0, n1 = 0; i < n_sect; i++) {\n\t\tn2 = n1 + nn;\n\t\tl_reg = n2 - n1;\n\n\t\tfor (j = 0; j < chan_sz; j++) {\n\t\t\tchan_sum[j] = 0;\n\t\t\tfor (k = n1; k < n2; k++) \n\t\t\t\tchan_sum[j] += pow(chan[j][k], 2);\n\n\t\t\t/* Get the minimum */\n\t\t\tif (j == 0) {\n\t\t\t\tmin = chan_sum[0];\n\t\t\t\tmin_index = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (chan_sum[j] < min) {\n\t\t\t\t\tmin = chan_sum[j];\n\t\t\t\t\tmin_index = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// DEBUG note: min and min_index match matlab 250 Hz\n\n\t\tif (i == 0) {\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tif (k >= n1 && k < n2)\n\t\t\t\t\tlin[k] = chan[min_index][k];\n\n\t\t\t\tlast[k] = chan[min_index][k];\n\t\t\t}\n\t\t} else {\n\t\t\thanning(l_reg, win);\n\n\t\t\tfor (k = l_reg / 2 - 1; k < l_reg; k++)\n\t\t\t\twin[k] = 1.0;\n\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tif (k >= n1 && k < n2) {\n\t\t\t\t\tlin[k] = last[k] * fabs(win[k] - 1.0) +\n\t\t\t\t\t\tchan[min_index][k] * win[k];\n\t\t\t\t}\n\n\t\t\t\tlast[k] = chan[min_index][k];\n\t\t\t}\n\t\t}\t\n\t\tn1 += n0;\n\t}\n\t//DEBUG note: lin[0-9] matches MATLAB\n\n\tfree(last);\n\treturn (int) n2;\n}\n\nvoid hanning(int len, double *hann) {\n\tint n;\n\n\tfor (n = 0; n < len; n++)\n\t\thann[n] = 0.5 * (1.0 - cos(2.0 * M_PI * n / (len - 1.0)));\n\n\treturn;\n}\n\nint process_wav_data(int band, float *wav_data, SF_INFO input_info, \n\t\tSNDFILE *input, unsigned long long frames, double *p_alpha,\n\t\tdouble *p_a, double *p_b, double *p_dr,\n\t\tint *p_start, int *p_end, int *filt_frames) {\n\tint i, ret, s_e_size, resamp_frames = 0, **start_end;\n\tfloat *resampled_wav, *filtered_wav, *env;\n\tdouble *alpha, *a, *b, *dr;\n\tint *store_start, *store_end;\n\n\t/* Specifications that apply to all subbands */\n\tSwrContext *resamp = swr_alloc();\n\n\tav_opt_set_int(resamp, \"in_channel_layout\", AV_CH_LAYOUT_MONO, 0);\n\tav_opt_set_int(resamp, \"out_channel_layout\", AV_CH_LAYOUT_MONO, 0);\n\tav_opt_set_int(resamp, \"in_sample_rate\", input_info.samplerate, 0);\n\tav_opt_set_sample_fmt(resamp, \"in_sample_fmt\", AV_SAMPLE_FMT_FLT, 0);\n\tav_opt_set_sample_fmt(resamp, \"out_sample_fmt\", AV_SAMPLE_FMT_FLT, 0);\n\n\n\tav_opt_set_int(resamp, \"out_sample_rate\", \n\t\tsamp_freq_per_band[band], 0); \n\n\tret = swr_init(resamp);\n\n\tif (ret < 0) {\n\t\tprintf(\"Resample initialisation error\\nExiting...\\n\");\n\t\treturn -1;\n\t}\n\n\t/* Resample the wav file */\n\tresampled_wav = resamp_wav_data(resamp, input_info.samplerate, \n\t\t(uint64_t) frames, samp_freq_per_band[band],\n\t\t(const uint8_t **) &wav_data, &resamp_frames);\n\n\tswr_free(&resamp);\n\tif (resamp_frames <= 0 || resampled_wav == NULL) {\n\t\tprintf(\"Resample error\\nExiting...\\n\");\n\t\treturn -1;\n\t}\n\n\t*filt_frames = resamp_frames;\n\n\t/* Octave band filtering */\n\tfiltered_wav = oct_filt_data(resampled_wav, \n\t\tband, (float) samp_freq_per_band[band],\n\t\tresamp_frames);\n\n\t/* Free memory no longer needed */\n\tav_free((uint8_t **) &resampled_wav[0]);\n\tresampled_wav = NULL;\n\n\t/* Obtain signal envelope */\n\tenv = get_envelope((float) samp_freq_per_band[band], filtered_wav, \n\t\tresamp_frames);\n\n\t/* Polyfit algorithm & get decay segments */\n\tstart_end = apply_polyfit((float) samp_freq_per_band[band], \n\t\tresamp_frames, env, &s_e_size);\n\n\t/* Perform Maximum Likelihood Estimation */\n\tret = perform_ml(start_end, env, s_e_size, filtered_wav, \n\t\tresamp_frames, samp_freq_per_band[band], &alpha, &a, &b, &dr,\n\t\t&store_start, &store_end);\n\n\tif (ret >= 0) {\n\t\tprintf(\"Maximum Likelihood calculations have completed!\\n%d \"\n\t\t\t\"potential segments analysed, %d may be valid\\n\",\n\t\t\ts_e_size, ret);\n\n\t\t/* Return pointers to caller */\n\t\tfor (i = 0; i < ret; i++) {\n\t\t\t*(p_alpha + i) = alpha[i];\n\t\t\t*(p_a + i) = a[i];\n\t\t\t*(p_b + i) = b[i];\n\t\t\t*(p_dr + i) = dr[i];\n\t\t\t*(p_start + i) = store_start[i];\n\t\t\t*(p_end + i) = store_end[i];\n\t\t}\n\t}\n\n\t/* Free memory no longer needed */\n\tfree(filtered_wav);\n\tfiltered_wav = NULL;\n\n\tfree(env);\n\tenv = NULL;\n\n\tfor (i = 0; i < 2; i++)\n\t\tfree(start_end[i]);\n\tfree(start_end);\n\tstart_end = NULL;\n\n\tfree(alpha);\n\talpha = NULL;\n\tfree(a);\n\ta = NULL;\n\tfree(b);\n\tb = NULL;\n\tfree(dr);\n\tdr = NULL;\n\tfree(store_start);\n\tstore_start = NULL;\n\tfree(store_end);\n\tstore_end = NULL;\n\n\t/* Return */\n\tif (ret < 0)\n\t\treturn -1;\n\telse\n\t\treturn ret;\n}\n\nfloat * resamp_wav_data(SwrContext *resamp, int in_rate, uint64_t num_frames, int samp_freq, const uint8_t **wav_data, int *resamp_frms) {\n\tuint8_t *output_data;\n\tint ret, resamp_frames;\n\n\tprintf(\"Resampling wav...\\n\");\n\tresamp_frames = av_rescale_rnd(swr_get_delay(resamp, in_rate) + \n\t\tnum_frames, samp_freq, in_rate, AV_ROUND_UP);\n\n\tret = av_samples_alloc(&output_data, NULL, 1, resamp_frames, \n\t\tAV_SAMPLE_FMT_FLT, 0);\n\n\tif (ret < 0) {\n\t\tprintf(\"Output buffer alloc failure\\nExiting...\\n\");\n\t\treturn NULL;\n\t}\n\n\tresamp_frames = swr_convert(resamp, &output_data, resamp_frames,\n\t\twav_data, num_frames);\n\n\tif (resamp_frames < 0) {\n\t\tprintf(\"Resampling failure\\nExiting...\\n\");\n\t\tav_free(&output_data[0]);\n\t\treturn NULL;\n\t}\n\n\t/* Store # frames in pointer */\n\t*resamp_frms = resamp_frames;\n\n\t/* Return pointer to beginning of data */\n\treturn (float *) output_data;\n}\n\nfloat * oct_filt_data(float *resamp_data, int band_num, float samp_freq, int resamp_frames) {\n\tint i, flag = 0;\n\tfloat *filtered = calloc(resamp_frames, sizeof(float)); \n\tfloat band = octave_bands[band_num];\n\n\tmemset(butt_b, 0, sizeof(butt_b));\n\tmemset(butt_a, 0, sizeof(butt_a));\n\n\tprintf(\"Applying octave band filter...\\n\");\n\n#ifdef USE_HARD_BUTTER\n\t/* Only accurate when numbers are not tiny */\n\tif (fabs(butter_b[band_num][0]) > 1e-5)\n\t\tflag = 1;\n#endif\n\n\tif (flag == 1) {\n\t\tiirfilt_rrrf f_obj_oct1 = iirfilt_rrrf_create(\n\t\t\tbutter_b[band_num], 2 * OCT_FILT_ORDER + 1,\n\t\t\tbutter_a[band_num], 2 * OCT_FILT_ORDER + 1);\n\n\t\t/* Filter data */\n\t\tfor (i = 0; i < resamp_frames; i++)\n\t\t\tiirfilt_rrrf_execute(f_obj_oct1, resamp_data[i],\n\t\t\t\t&filtered[i]);\n\n\t\t/* Free filter and reset coefficient arrays */\n\t\tiirfilt_rrrf_destroy(f_obj_oct1);\n\t} else {\n\t\t/* Create bandpass filter - 7th and 8th parameter are ignored */\n\t\tliquid_iirdes(LIQUID_IIRDES_BUTTER, LIQUID_IIRDES_BANDPASS,\n\t\t\tLIQUID_IIRDES_SOS, OCT_FILT_ORDER,\n\t\t\tband / (sqrt(2.0) * samp_freq),\n\t\t\tband / samp_freq, 1.0, 1.0, butt_b, butt_a);\n\t\t//printf(\"res: %d\\n\\n\", iirdes_isstable(butt_b, butt_a,\n\t\t//\t3 * (L_OCT + R_OCT)));\n\t\tiirfilt_rrrf f_obj_oct2 = iirfilt_rrrf_create_sos(\n\t\t\tbutt_b, butt_a, L_OCT + R_OCT);\n\n\t\t/* Filter data */\n\t\tfor (i = 0; i < resamp_frames; i++)\n\t\t\tiirfilt_rrrf_execute(f_obj_oct2, resamp_data[i],\n\t\t\t\t&filtered[i]);\n\n\t\t/* Free filter and reset coefficient arrays */\n\t\tiirfilt_rrrf_destroy(f_obj_oct2);\n\t}\n\n\t/* fiiltered data: return to previous function */\n\treturn filtered;\n}\n\n\nfloat * get_envelope(float samp_freq, float *filtered_wav, \n\t\tint resamp_frames) {\n\tfloat complex *filt_complex = calloc(resamp_frames, sizeof(float complex));\n\tfloat complex *tmp = calloc(resamp_frames, sizeof(float complex));\n\tfloat complex *tmp2 = calloc(resamp_frames, sizeof(float complex));\n\tfloat complex *hilb = calloc(resamp_frames, sizeof(float complex));\n\tfloat *env = calloc(resamp_frames, sizeof(float));\n\tint i, j;\n\n\t//FIXME add calloc NULL check\t\n\n\tmemset(butt_b, 0, sizeof(butt_b));\n\tmemset(butt_a, 0, sizeof(butt_a));\n\n\t/* Create Low Pass Filter - 6th, 7th and 8th param are ignored */\n\tprintf(\"Obtaining signal envelope...\\n\");\n\tliquid_iirdes(LIQUID_IIRDES_BUTTER, LIQUID_IIRDES_LOWPASS, \n\t\tLIQUID_IIRDES_TF, ENV_FILT_ORDER,\n\t\tLOW_PASS_CUTOFF / samp_freq, 0.1, \n\t\t1.0, 1.0, butt_b, butt_a);\n\n\tiirfilt_crcf f_obj_env = iirfilt_crcf_create(butt_b,\n\t\tENV_FILT_ORDER+1, butt_a, ENV_FILT_ORDER+1);\n\n\tfftplan fft_pln = fft_create_plan(resamp_frames, (float complex *) \n\t\tfilt_complex, (float complex *) tmp, LIQUID_FFT_FORWARD, 0);\n\tfftplan ifft_pln = fft_create_plan(resamp_frames, (float complex *) tmp,\n \t\t(float complex *) hilb, LIQUID_FFT_BACKWARD, 0);\n\n\t/* Get the Hilbert transform - really it's the analytic signal as the\n\t\tHilbert transform is stored in the imaginary part of the soln */\n\tfor (i = 0; i < resamp_frames; i++)\n\t\tfilt_complex[i] = (float complex) filtered_wav[i];\n\n\tfft_execute(fft_pln);\t\n\n\tfor (i = 0; i < resamp_frames; i+= 1) {\n\t\tj = i + 1;\n\n\t\tif (resamp_frames % 2 == 0) {\n\t\t\t/* Even number of samples */\n\t\t\t/* Set if value should be non-zero (array contains zeros)*/\n\t\t\tif (j == 1 || j == ((resamp_frames / 2) + 1))\n\t\t\t\ttmp2[i] = 1.0;\n\t\t\telse if (j >= 2 && j <= (resamp_frames / 2))\n\t\t\t\ttmp2[i] = 2.0;\n\t\t} else {\n\t\t\t/* Odd number of samples */\n\t\t\t/* Set if value should be non-zero (array contains zeros)*/\n\t\t\tif (j == 1)\n\t\t\t\ttmp2[i] = 1.0;\n\t\t\telse if (j >= 2 && j <= (resamp_frames + 1) / 2)\n\t\t\t\ttmp2[i] = 2.0;\n\t\t}\n\n\t\ttmp[i] *= tmp2[i];\n\t}\n\n\n\tfft_execute(ifft_pln);\n\n\tfor (i = 0; i < resamp_frames; i++) {\n\t\t/* Normalisation correction */\n\t\thilb[i] *= (1.0 / resamp_frames);\n\n\t\t/* Get envelope */\n\t\thilb[i] = csqrtf(filt_complex[i] * filt_complex[i] + \n\t\t\thilb[i] * hilb[i]);\n\n\t\t/* Apply low pass filter to envelope */\n\t\tiirfilt_crcf_execute(f_obj_env, hilb[i], &tmp[i]);\n\n\t\tenv[i] = cabsf(tmp[i]);\n\t}\n\n\tfree(tmp2);\n\tfree(tmp);\n\tfree(hilb);\n\tfree(filt_complex);\n\tiirfilt_crcf_destroy(f_obj_env);\n\tfft_destroy_plan(ifft_pln);\n\tfft_destroy_plan(fft_pln);\n\n\t/* envelope pointer: return to previous function */\n\treturn env;\n}\n\n\nint ** apply_polyfit(float samp_freq, int resamp_frames, float *env, int *s_e_size) {\n\tint i, j, seg_size, step_size, num_segs, poly_coeff = 2, dump = 0;\n\tint **seg_index, invalid_coeff = 0, actual_seg_num_els = 0, max = 0;\n\tint **start_end; \n\tfloat *poly_param, **poly_res, *poly_seg, max_poly_res, min_poly_res;\n\tfloat *var;\n\tfloat *log_env = calloc(resamp_frames, sizeof(float));\n\t//FIXME: add calloc NULL check\n\n\tprintf(\"Applying polyfit algorithm...\\n\");\n\n\tfor (i = 0; i < resamp_frames; i++)\n\t\tlog_env[i] = log10f(env[i]);\n\n\tseg_size = (int) floorf(samp_freq * DAMP_SEG_SIZE);\n\n\tstep_size = (int) floorf(samp_freq * DAMP_STEP_SIZE);\n\n\tnum_segs = (int) floorf((resamp_frames - seg_size) / step_size + 1);\n\n\t//FIXME: add calloc NULL check\n\tpoly_param = calloc(seg_size, sizeof(float));\n\tpoly_res = calloc(num_segs, sizeof(float *));\n\tpoly_seg = calloc(seg_size, sizeof(float));\n\tvar = calloc(num_segs, sizeof(float));\n\n\tfor (i = 0; i < num_segs; i++) \n\t\tpoly_res[i] = calloc(poly_coeff, sizeof(float));\n\n\t/* Fill in Polyfit function parameter */\n\tfor (i = 0; i < seg_size; i++)\n\t\tpoly_param[i] = i + 1;\n\n\tmax_poly_res = -log10f(exp(6.91 / MAX_RT / samp_freq));\n\tmin_poly_res = -log10f(exp(6.91 / MIN_RT / samp_freq));\n\n\tfor (i = 0; i < num_segs; i++) {\n\t\tfor (j = i * step_size; j < i * step_size + seg_size; j++)\n\t\t\tpoly_seg[j - i * step_size] = log_env[j];\n\t\n\t\tpolyf_fit(poly_param, poly_seg, seg_size, &poly_res[i][0], \n\t\t\tpoly_coeff);\n\n\t\t//TODO: CHECK MATLAB POLYFIT COEFFS\n\t\t//TODO: CHECK MATLAB VALUES UP TO HERE\n\t\t//DONE ABOVE - SEEMED FINE BUT POLY COEFFS REVERESED...\n//\t\tfor (j = 0; j < poly_coeff; j++) {\n//\t\t\tprintf(\"%lf\", poly_res[i][j]);\n//\t\t\tif (j == 0)\n//\t\t\t\tprintf(\",\");\n//\t\t\telse\n//\t\t\t\tprintf(\"\\n\");\n//\t\t}\n\n\t\tfor (j = 0; j < poly_coeff; j++) {\n\t\t\t//FIXME eeeh floating point comparisons are DODGEY in C\n\t\t\tif (poly_res[i][j] < min_poly_res || \n\t\t\t\tpoly_res[i][j] > max_poly_res) {\n\t\t\t\tinvalid_coeff++;\n\t\t\t}\n\t\t}\n\t\tif (invalid_coeff == poly_coeff) {\n\t\t\tvar[i] = -1.0;\n\t\t\tdump++;\n\t\t}\n\t\tinvalid_coeff = 0;\t\t\n\t}\n\n\t/* Choose segments */\n\tseg_index = choose_segments(var, step_size, num_segs, num_segs - dump,\n\t\t&actual_seg_num_els);\n\n\t/* Number of decay segments should not be greater than BEST_S_NUM */\n\tif (actual_seg_num_els > BEST_S_NUM)\n\t\tactual_seg_num_els = BEST_S_NUM;\n\n\tstart_end = calloc(2, sizeof(int *));\n\tfor (i = 0; i < 2; i++)\n\t\tstart_end[i] = calloc(actual_seg_num_els, sizeof(int));\n\n\tfor (i = 0; i < actual_seg_num_els; i++) {\n\t\tmax = 0;\n\t\tfor (j = 0; j < actual_seg_num_els; j++) {\n\t\t\tif (seg_index[j][1] > seg_index[max][1])\n\t\t\t\tmax = j;\n\t\t}\n\n\t\tstart_end[0][i] = seg_index[max][0] * step_size;\n\t\tstart_end[1][i] = seg_index[max][0] * step_size + \n\t\t\tseg_size + seg_index[max][1] * step_size - 1;\n\n\t\t/* Remove longest segment - it has been chosen */\n\t\tseg_index[max][1] = 0;\n\t\t\n\t}\n\n\t/* Free arrays */\n\tfor (i = 0; i < num_segs; i++) \n\t\tfree(poly_res[i]);\n\tfree(poly_res);\n\n\tfor (i = 0; i < num_segs - dump; i++)\n\t\tfree(seg_index[i]);\n\tfree(seg_index);\n\tseg_index = NULL;\n\n\tfree(poly_seg);\n\tfree(var);\n\tfree(poly_param);\n\tfree(log_env);\n\n\t*s_e_size = actual_seg_num_els;\n\n\treturn start_end;\n}\n\nint ** choose_segments(float *var, int step_size, int len, int not_dumped, \n\t\tint *seg_num_els) {\n\tint i, k, j = 0;\n\tint **seg_index;\n\n\t/* Max possible size of seg_index */\n\tseg_index = calloc(not_dumped, sizeof(int *));\n\n\tfor (i = 0; i < not_dumped; i++) \n\t\tseg_index[i] = calloc(2, sizeof(int));\n\n\t/* Set decay segments and number of continuous segments in array */\n\tfor (i = 0; i < len - 1; i += k) {\n\t\tk = 1;\n\n\t\t/* Floating point method of checking if var[i] == 0 */\n\t\tif (fabs(var[i]) < 0.0001) {\n\t\t\tseg_index[j][0] = i;\n\t\t\tseg_index[j][1] = 0;\n\n\t\t\twhile (((i + k) < len) && fabs(var[i + k]) < 0.0001) {\n\t\t\t\tseg_index[j][1]++;\n\t\t\t\tk++;\n\t\t\t}\n\t\t\tj++;\n\t\t\tk += step_size;\n\t\t}\n\t}\n\n\t*seg_num_els = j;\n\t/* FIXME: don't free seg_index... what am I supposed to do about it? */\n\treturn seg_index;\n}\n\nint perform_ml(int **start_end, float *env, int s_e_size, float *filtered_wav, \n\t\tint resamp_frames, int samp_freq, double **p_alpha, \n\t\tdouble **p_a_par, double **p_b_par, double **p_dr,\n\t\tint **p_start, int **p_end) {\n\tint sz, i, all_ret = 0;\n\tfloat *abs_filtered = calloc(resamp_frames, sizeof(float));\n\tint *store_start = calloc(s_e_size, sizeof(int)); \n\tint *store_end = calloc(s_e_size, sizeof(int));\n\tint *len_store = calloc(s_e_size, sizeof(int));\n\tdouble *a_par = calloc(s_e_size, sizeof(double));\n\tdouble *b_par = calloc(s_e_size, sizeof(double));\n\tdouble *alpha = calloc(s_e_size, sizeof(double));\n\tdouble *dr = calloc(s_e_size, sizeof(double));\n\n\tprintf(\"Performing Maximum Likelihood calculations\\n\"\n\t\t\"This will take a while...\\n\");\n\n\t/* Get absolute vaule of filtered wav */\n\tfor (i = 0; i < resamp_frames; i++)\n\t\tabs_filtered[i] = fabs(filtered_wav[i]);\t\n\n\t/* Largest possible size of arrays - first pair of elements */\n\tsz = start_end[1][0] - start_end[0][0];\n\n\t#pragma omp parallel for schedule(static)\n\tfor (i = 0; i < s_e_size; i++) {\n\t\tfloat *segment = calloc(sz, sizeof(float));\n\t\tfloat *env_seg = calloc(sz, sizeof(float));\n\t\tfloat *abs_filt_seg = calloc(sz, sizeof(float));\n\t\tfloat *seg_seg2 = calloc(sz + sz - roundf((DAMP_SEG_SIZE / 2) *\n\t\t\tsamp_freq), sizeof(float));\n\t\tfloat max_seg2;\n\t\tint k, j, len = abs(start_end[1][i] - start_end[0][i]);\n\t\tint min_abs_filt_seg, max_abs_filt_seg, ret = 0;\n\n\t\t/* Store decay segment in new array */\n\t\tfor (k = 0, j = start_end[0][i]; j < start_end[1][i]; j++, k++)\n\t\t{\n\t\t\tsegment[k] = filtered_wav[j];\n\t\t\tenv_seg[k] = env[j];\n\t\t\tabs_filt_seg[k] = abs_filtered[j];\n\t\t}\n\t\t// DEBUG: above values match matlab!\n\n\t\t/* Get location of minimum */\n\t\tmin_abs_filt_seg = len - round((DAMP_SEG_SIZE / 2) * \n\t\t\tsamp_freq) - 1;\n\t\t\n\t\tfor (j = min_abs_filt_seg; j < len; j++) {\n\t\t\tif (abs_filt_seg[j] < abs_filt_seg[min_abs_filt_seg])\n\t\t\t\tmin_abs_filt_seg = j;\n\t\t}\n\t\t\n\t\t/* Get location of maximum */\n\t\tmax_abs_filt_seg = 0;\n\t\tfor (j = 0; j < round((DAMP_SEG_SIZE / 2) * samp_freq); j++) {\n\t\t\tif (abs_filt_seg[j] > abs_filt_seg[max_abs_filt_seg])\n\t\t\t\tmax_abs_filt_seg = j;\n\t\t}\n\n\t\t/* Store new fine-tuned decay segment */\n\t\tfor (k = 0, j = max_abs_filt_seg; j <= min_abs_filt_seg; k++, \n\t\t\tj++)\n\t\t\tseg_seg2[k] = segment[j];\n\n\t\t/* NB: len_store[] contains INDEX to last element, not # of\n\t\t\telements in array */\n\t\tlen_store[i] = k - 1;\n\t\t\n\t\tk = 0;\n\t\tfor (j = 0; j <= len_store[i]; j++) {\n\t\t\tif (fabs(seg_seg2[j]) > fabs(seg_seg2[k]))\n\t\t\t\tk = j; \n\t\t}\n\t\t\n\t\tmax_seg2 = fabs(seg_seg2[k]);\t\n\t\tfor (j = 0; j <= len_store[i]; j++)\n\t\t\tseg_seg2[j] /= max_seg2;\n\n\t\t/* Save fine-tuned start and end locations */\n\t\t// FIXME: are the -1's OK here? Compare to MATLAB\n\t\tstore_start[i] = start_end[0][i] + max_abs_filt_seg;\n\t\tstore_end[i] = start_end[0][i] + max_abs_filt_seg +\n\t\t\t\tlen_store[i] - 1;\n\n\t\t/* ML fitting of decay model to the data */\n\t\tret = ml_fit(seg_seg2, len_store[i], (float) samp_freq, \n\t\t\t&a_par[i], &b_par[i], &alpha[i]);\n\n\t\tfree(segment);\n\t\tfree(seg_seg2);\n\t\tfree(env_seg);\n\t\tfree(abs_filt_seg);\n\n\t\tif (ret == -1) {\n\t\t\t/* DR being discarded */\n\t\t\tdr[i] = 0;\n\t\t\tcontinue;\n\t\t} else if (ret < -1) {\n\t\t\t/* Error */\n\t\t\tall_ret = -1;\n\t\t}\n\n\t\t/* If code gets to here, DR was possibly valid */\n\t\t/* Compute decay curves using ML-calculated params */\n\t\tdr[i] = get_decay_region(6 * samp_freq, a_par[i], b_par[i],\n\t\t\talpha[i], len_store[i]);\n\t}\n\n\t/* Pointers used by caller cannot be freed. They are alpha[], a[],\n\t\tb[], store_start[], store_end[] and dr[] */\n\t*p_alpha = alpha;\n\t*p_a_par = a_par;\n\t*p_b_par = b_par;\n\t*p_dr = dr;\n\t*p_start = store_start;\n *p_end = store_end;\n\n\t/* Free pointers that are no longer needed */\n\tfree(abs_filtered);\n\tfree(len_store);\n\n\tif (all_ret != 0) {\n\t\tprintf(\"Error during ML calculations!\\n\");\n\t\treturn -1;\n\t} else\n\t\treturn s_e_size;\n}\n\ndouble get_decay_region(int c_len, double a, double b, double alpha,\n\t\tint len_store) {\n\tdouble *chan = calloc(c_len, sizeof(double));\n\tdouble *y = calloc(c_len, sizeof(double));\n\tdouble dr;\n\tint j, max_y;\n\n\t/* Compute decay curves using ML-calculated params */\n\tfor (j = 0; j < c_len; j++)\n\t\tchan[j] = alpha * pow(a, j) + (1.0 - alpha) * pow(b, j);\n\n\t/* Get the reverse cumsum of chan[] and assign to y in reverse */\n\ty[c_len - 1] = pow(chan[c_len - 1], 2);\n\tfor (j = c_len - 2; j >= 0; j--)\n\t\ty[j] = pow(chan[j], 2) + y[j + 1];\n\n\t/* Get max of fabs(y) */\n\tmax_y = fabs(y[0]);\n\tfor (j = 1; j < c_len; j++) {\n\t\tif (fabs(y[j]) > max_y)\n\t\t\tmax_y = fabs(y[j]);\n\t}\n\n\t/* Normalise y first value will be max; stores whole cumsum */\n\tfor (j = 0; j < c_len; j++) \n\t\ty[j] = 10.0 * log10(y[j] / max_y);\n\n\tdr = y[len_store];\n\n\tfree(chan);\n\tfree(y);\n\n\treturn dr;\n}\n\nint ml_fit(float *data_seg, int len, float samp_freq, double *a_par, \n\t\tdouble *b_par, double *alph_par) {\n\tdouble min, max, interval, j, gmax_val, x_fine[3], fine_val, dr;\n\tdouble *coarse_grid, lb[3], ub[3];\n\tdouble like[SQP_STEP][SQP_STEP] = {0}, alpha[SQP_STEP][SQP_STEP] = {0};\n\tint gmax_pos[2], i, k, el_cg, ret = 0;\n\tstruct nl_extra_data nld;\n\n\tlb[0] = 0.0;\n\tub[0] = 1.0;\n\n\tnld.data_seg = data_seg;\n\tnld.len = len;\n\n\tnlopt_opt nl_obj1 = nlopt_create(NLOPT_LN_COBYLA, 1);\n\tnlopt_set_lower_bounds1(nl_obj1, lb[0]);\n\tnlopt_set_upper_bounds1(nl_obj1, ub[0]);\n\tnlopt_set_maxeval(nl_obj1, 100);\n\tnlopt_set_min_objective(nl_obj1, (nlopt_func) alpha_opt, (void *) &nld);\n\n\n\tmin = (-6.91 / log(PAR_LOW_BOUND)) / 3000.0;\n\tmin = exp(-6.91 / (samp_freq * min));\n\n\tmax = (-6.91 / log(PAR_UP_BOUND)) / 3000.0;\t\n\tmax = exp(-6.91 / (samp_freq * max));\n\t\n\tinterval = (max - min) / ((double) SQP_STEP - 1.0);\n\tel_cg = round((max - min) / interval) + 1;\n\tcoarse_grid = calloc(el_cg, sizeof(double));\n\n\t/* Fill in coarse grid */\n\tfor (i = 0, j = min; i < el_cg; i++, j += interval)\n\t\tcoarse_grid[i] = j;\n\n\t// There is another max(abs(x)) division here in MATLAB\n\t// \tMakes no diff - dividing by 1.0 - leaving out\n\t\n\t/* Coarse grid minimisation search */\n\tfor (i = 0; i < SQP_STEP; i++) {\n\t\tnld.b_val = coarse_grid[i];\n \n\t\tfor (k = 0; k < SQP_STEP; k++) {\n\t\t\talpha[k][i] = 0.5;\n\t\t\tnld.a_val = coarse_grid[k];\n\n\t\t\tret = nlopt_optimize(nl_obj1, &alpha[k][i], \n\t\t\t\t&like[k][i]);\n\n\t\t\t/* -4 is an acceptable nlopt return code */\n\t\t\tif (ret < 0 && ret != -4) {\n\t\t\t\tnlopt_destroy(nl_obj1);\n\t\t\t\tfree(coarse_grid);\n\t\t\t\treturn -2;\n\t\t\t}\n\n\t\t\tlike[k][i] *= -1;\n\t\t}\n\t}\n\n\tfor (i = 0; i < SQP_STEP; i++) {\n\t\tfor (k = 0; k < SQP_STEP; k++) {\n\t\t\t/* Store value and position ([][]) of global max */\n\t\t\tif (i == 0 && k == 0) {\n\t\t\t\tgmax_val = like[k][i];\n\t\t\t\tgmax_pos[0] = k;\n\t\t\t\tgmax_pos[1] = i;\t\n\t\t\t} else {\n\t\t\t\tif (like[k][i] > gmax_val) {\n\t\t\t\t\tgmax_val = like[k][i];\n\t\t\t\t\tgmax_pos[0] = k;\n\t\t\t\t\tgmax_pos[1] = i;\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//printf(\"k: %d, i: %d, ret: %d, a: %lf like: %le coarse: %lf\\n\", k+1, i+1, ret, alpha[k][i], like[k][i], coarse_grid[k]);\n\t\t}\n\t}\n\n\t/* No longer need nl_obj1; coarse search is done */\n\tnlopt_destroy(nl_obj1);\n\n#ifdef COARSE_DR_EST\n\tdr = get_decay_region(6 * samp_freq, coarse_grid[gmax_pos[0]],\n\t\tcoarse_grid[gmax_pos[1]], alpha[gmax_pos[0]][gmax_pos[1]], len);\n\n\tif (dr > -1.0) {\n\t\tfree(coarse_grid);\n\t\treturn -1;\n\t}\n#endif\n\n\t/* Create new nlopt object for fine search */\n\tnlopt_opt nl_obj3 = nlopt_create(NLOPT_LN_COBYLA, 3);\n\n\tlb[0] = lb[1] = coarse_grid[0];\n\tub[0] = ub[1] = coarse_grid[el_cg - 1];\n\tlb[2] = 0.0;\n\tub[2] = 1.0;\n\n\tnlopt_set_lower_bounds(nl_obj3, lb);\n\tnlopt_set_upper_bounds(nl_obj3, ub);\n\tnlopt_set_maxeval(nl_obj3, 300);\n\tnlopt_set_min_objective(nl_obj3, (nlopt_func) par_3_opt, (void *) &nld);\n\n\t/* Initial values for fine search */\n\tx_fine[0] = coarse_grid[gmax_pos[0]];\n\tx_fine[1] = coarse_grid[gmax_pos[1]];\n\tx_fine[2] = alpha[gmax_pos[0]][gmax_pos[1]];\t\n\t//printf(\"B4 XVAL: %lf %lf %lf %le\\n\", x_fine[0], x_fine[1], x_fine[2], gmax_val); \n\n\tret = nlopt_optimize(nl_obj3, x_fine, &fine_val);\n\t//printf(\"DEBUG FINE RESULTS - ret: %d XVAL: %lf %lf %lf FINE_VAL: %le\\n\", \n\t\t//ret, x_fine[0], x_fine[1], x_fine[2], fine_val);\n\t\n\t/* Return a, b, alpha in pointers */\n\t*a_par = x_fine[0];\n\t*b_par = x_fine[1];\n\t*alph_par = x_fine[2];\n\t\n\tfree(coarse_grid);\n\tnlopt_destroy(nl_obj3);\n\n\tif (ret < 0 && ret != -4)\n\t\treturn -2;\n\telse\n\t\treturn 0;\n}\n\n\n/* Optimise with respect to alpha */\ndouble alpha_opt(int n, const double *a, double *grad, void *nldv)\n{\n\t/* FIXME ADD THE STUFF IN HERE TO DO WITH READING nld */\n\tint i;\n\tdouble alpha = *a;\n\tstruct nl_extra_data *nld = (struct nl_extra_data *) nldv;\t\n\tdouble sigma_tot = 0, *sigma = calloc(nld->len, sizeof(double));\n\tdouble like_a_tot = 0;\n\tdouble like_b_tot = 0, *like_b = calloc(nld->len, sizeof(double));\n\n\tfor (i = 0; i < nld->len; i++) {\n\t\t/* Get sigma */\n\t\tsigma[i] = alpha * pow(nld->a_val, i) + \n\t\t\t(1.0 - alpha) * pow(nld->b_val, i);\n\n\t\tsigma[i] = -1.0 / pow(sigma[i], 2);\n\n\t\tsigma[i] *= pow(nld->data_seg[i], 2);\n\n\t\tsigma_tot += sigma[i];\n\t}\n\n\tsigma_tot = sqrt(-sigma_tot / ( (double) nld->len ));\n\n\tfor (i = 0; i < nld->len; i++) {\n\t\t/* Get likelihood*/\n\t\tlike_a_tot += log( alpha * pow(nld->a_val, i) + \n\t\t\t(1.0 - alpha) * pow(nld->b_val, i) );\n\n\t\tlike_b[i] = alpha * pow(nld->a_val, i) + \n\t\t\t(1.0 - alpha) * pow(nld->b_val, i);\n\n\t\tlike_b[i] = pow(like_b[i], -2);\n\n\t\tlike_b[i] *= pow(nld->data_seg[i], 2) / \n\t\t\t(2.0 * pow(sigma_tot, 2));\n\n\t\tlike_b_tot += like_b[i];\t\n\t}\n\n\tlike_b_tot = -like_a_tot - like_b_tot - \n\t\t(double) nld->len * log(2 * M_PI * pow(sigma_tot, 2)) / 2.0;\n\n\tfree(like_b);\n\tfree(sigma);\n\n\treturn -like_b_tot;\n}\n\n/* Optimise all three parameters */\ndouble par_3_opt(int n, const double *a, double *grad, void *nldv)\n{\n\tint i;\n struct nl_extra_data *nld = (struct nl_extra_data *) nldv;\n\tdouble a_val = a[0], b_val = a[1], alpha = a[2], sigma_tot = 0;\n\tdouble *env = calloc(nld->len, sizeof(double));\n\tdouble like = 0, x = 0;\n\n\tfor (i = 0; i < nld->len; i++) {\n\t\tenv[i] = alpha * pow(a_val, i) + (1.0 - alpha) * pow(b_val, i);\n\n\t\tsigma_tot -= (-1.0 / pow(env[i], 2)) * pow(nld->data_seg[i], 2);\n\t}\n\n\tsigma_tot = sqrt(sigma_tot / (double) nld->len);\n\n\tfor (i = 0; i < nld->len; i++) {\n\t\tlike -= log(env[i]);\n\n\t\tx += pow(env[i], -2) * pow(nld->data_seg[i], 2) / \n\t\t\t(2.0 * pow(sigma_tot, 2));\n\t}\n\n\tlike -= (x + (double) nld->len * log(2.0 * M_PI * \n\t\t\tpow(sigma_tot, 2)) / 2.0);\n\n\tfree(env);\n\treturn -like;\n}\n", "meta": {"hexsha": "efb78af57b10865bb18f0629de521db3170efccc", "size": 40685, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main.c", "max_stars_repo_name": "kimmariejon3s/rt-blind-estimator", "max_stars_repo_head_hexsha": "128647a6ffea21f01fc7135fe736a38716c0a03c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-10-09T10:13:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T09:14:32.000Z", "max_issues_repo_path": "src/main.c", "max_issues_repo_name": "kimmariejon3s/rt-blind-estimator", "max_issues_repo_head_hexsha": "128647a6ffea21f01fc7135fe736a38716c0a03c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.c", "max_forks_repo_name": "kimmariejon3s/rt-blind-estimator", "max_forks_repo_head_hexsha": "128647a6ffea21f01fc7135fe736a38716c0a03c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-11-11T12:14:41.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-22T16:50:40.000Z", "avg_line_length": 27.268766756, "max_line_length": 138, "alphanum_fraction": 0.6303060096, "num_tokens": 13720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6540101001326162}} {"text": "#include \n#include \n\nint\nmain(void)\n{\n double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6};\n double mean, variance, largest, smallest, sd,\n rms, sd_mean, median, skew, kurtosis;\n gsl_rstat_workspace *rstat_p = gsl_rstat_alloc();\n size_t i, n;\n\n /* add data to rstat accumulator */\n for (i = 0; i < 5; ++i)\n gsl_rstat_add(data[i], rstat_p);\n\n mean = gsl_rstat_mean(rstat_p);\n variance = gsl_rstat_variance(rstat_p);\n largest = gsl_rstat_max(rstat_p);\n smallest = gsl_rstat_min(rstat_p);\n median = gsl_rstat_median(rstat_p);\n sd = gsl_rstat_sd(rstat_p);\n sd_mean = gsl_rstat_sd_mean(rstat_p);\n skew = gsl_rstat_skew(rstat_p);\n rms = gsl_rstat_rms(rstat_p);\n kurtosis = gsl_rstat_kurtosis(rstat_p);\n n = gsl_rstat_n(rstat_p);\n\n printf (\"The dataset is %g, %g, %g, %g, %g\\n\",\n data[0], data[1], data[2], data[3], data[4]);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n printf (\"The largest value is %g\\n\", largest);\n printf (\"The smallest value is %g\\n\", smallest);\n printf( \"The median is %g\\n\", median);\n printf( \"The standard deviation is %g\\n\", sd);\n printf( \"The root mean square is %g\\n\", rms);\n printf( \"The standard devation of the mean is %g\\n\", sd_mean);\n printf( \"The skew is %g\\n\", skew);\n printf( \"The kurtosis %g\\n\", kurtosis);\n printf( \"There are %zu items in the accumulator\\n\", n);\n\n gsl_rstat_reset(rstat_p);\n n = gsl_rstat_n(rstat_p);\n printf( \"There are %zu items in the accumulator\\n\", n);\n\n gsl_rstat_free(rstat_p);\n\n return 0;\n}\n", "meta": {"hexsha": "645507de8ec8f17319372db6f140ea73561f732a", "size": 1606, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/rstat.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rstat.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/rstat.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": 30.8846153846, "max_line_length": 64, "alphanum_fraction": 0.6481942715, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.6538856603339754}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n/*\n * note that for a matrix A(mxn) in the row-major order, the first dimension is n. \n */\n\n/* C(nxn) = A(nxn)*B(nxn) */\nvoid multiply_mat(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n/* C(nxn) = A^T(nxn)*B(nxn) */\nvoid multiply_mat_transposeA(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n/* C(nxn) = A(nxn)*B^T(nxn) */\nvoid multiply_mat_transposeB(double * a, double *b, double *c, int n)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0f\n , a, n, b, n, 0.0f, c, n);\n}\n/* C(m*n) = A(m*k) * B(k*n) */\nvoid multiply_mat_MN(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f\n , a, k, b, n, 0.0f, c, n);\n}\n/* C(m*n) = A^T(m*k) * B(k*n) */\nvoid multiply_mat_MN_transposeA(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0f\n , a, m, b, n, 0.0f, c, n);\n}\n/* C(m*n) = A(m*k) * B^T(k*n) */\nvoid multiply_mat_MN_transposeB(double * a, double *b, double *c, int m, int n, int k)\n{\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0f\n , a, k, b, k, 0.0f, c, n);\n}\n/* y(n) = A(nxn)* x(n) */\nvoid multiply_matvec(double *a, double *x, int n, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n/* y(n) = A^T(nxn)* x(n) */\nvoid multiply_matvec_transposeA(double *a, double *x, int n, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n/* y(m) = A(m, n) * x(n) */\nvoid multiply_matvec_MN(double * a, int m, int n, double *x, double *y)\n{\n cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, 1.0f, a, n, x, 1, 0.0f, y, 1);\n}\n/* A(mxm)^-1 * B(mxn), store the output in B\n * note that A will be changed on exit. */\nint multiply_mat_MN_inverseA(double * a, double *b, int m, int n)\n{\n int * ipiv, info;\n ipiv=malloc(m*sizeof(int));\n\n info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, m, a, m, ipiv);\n if(info!=0)\n {\n strcpy(str_error_exit, \"multiply_mat_MN_inverseA 1.\\n this usually caused by improper nc.\\n increase the low limit of nc\");\n error_exit(9);\n }\n info = LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', m, n, a, m, ipiv, b, n);\n if(info!=0)\n {\n strcpy(str_error_exit, \"multiply_mat_MN_inverseA 2\\n this usually caused by improper nc.\\n increase the low limit of nc\");\n error_exit(9);\n }\n\n free(ipiv);\n return info;\n}\n/* A^-1 */\nvoid inverse_mat(double * a, int n, int *info)\n{\n int * ipiv;\n ipiv=malloc(n*sizeof(int));\n\n// dgetrf_(&n, &n, a, &n, ipiv, info);\n// dgetri_(&n, a, &n, ipiv, work, &lwork, info);\n\n *info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);\n if(*info!=0)\n {\n strcpy(str_error_exit, \"inverse_mat\");\n error_exit(9);\n }\n *info = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, a, n, ipiv);\n if(*info!=0)\n {\n strcpy(str_error_exit, \"inverse_mat\");\n error_exit(9);\n }\n free(ipiv);\n return;\n}\n/* eigen vector and eigen values */\nvoid eigen_sym_mat(double *a, int n, double *val, int *info)\n{\n char jobz='V', uplo='U';\n\n/* store the eigenvectors in a by rows.\n * store the eigenvalues in val in ascending order.\n */\n// dsyev_(&jobz, &uplo, &n, a, &n, val, work, &lwork, info);\n\n/* store the eigenvectors in a by columns.\n * store the eigenvalues in val in ascending order.\n */\n LAPACKE_dsyev(LAPACK_ROW_MAJOR, jobz, uplo, n, a, n, val);\n return;\n}\n/* A(nxn) = x^T(n) * x(n) */\nvoid multiply_vec2mat(double * x, double * a, int n)\n{\n// cblas_dsyr(CblasRowMajor, CblasUpper, n, 1.0f, x, 1, a, n);\n int i, j;\n for(i=0; i=0?1:-1);\n sign_all[i] = (a[i*n+i]>=0?1:-1);\n\n if(ipiv[i]!=i+1)\n {\n //printf(\"%e %d\\n\", a[i*n+i], n);\n //ipiv[ipiv[i]] = ipiv[i];\n //*sign *= -1;\n sign_all[i] *= -1;\n }\n }\n\n for(i=0; i=0?1:-1);\n\n if(ipiv[i]!=i+1)\n {\n //printf(\"%e %d\\n\", a[i*n+i], n);\n //ipiv[ipiv[i]] = ipiv[i];\n *sign *= -1;\n }\n }\n\n return lndet;\n}\n/* Cholesky decomposition of A, i.e., A = M^T* M \n * store M in A */\nvoid Chol_decomp_U(double *a, int n, int *info)\n{\n int i,j;\n char uplo = 'L';\n// dpotrf_(&uplo, &n, a, &n, info);\n *info=LAPACKE_dpotrf(LAPACK_ROW_MAJOR, uplo, n, a, n);\n if(*info<0)\n {\n strcpy(str_error_exit, \"Chol_decomp_U\");\n fprintf(stderr, \"The %d-th argument had an illegal value!\\n\", *info);\n error_exit(9);\n }\n else if (*info>0)\n {\n strcpy(str_error_exit, \"Chol_decomp_U\");\n fprintf(stderr, \"The leading minor of order %d is not positive definite, and the factorization could not be completed.\\n\", *info);\n error_exit(9);\n }\n for(i=0;i\n#include \n\n#include \n#include \n#include \n#include \n#include \n\ngsl_vector *\nqdm_knots_vector(size_t spline_df, gsl_vector *interior_knots)\n{\n size_t size = spline_df * 2 + interior_knots->size;\n gsl_vector *knots = gsl_vector_alloc(size);\n\n // Fill front with zeros.\n for (size_t i = 0; i < spline_df; i++) {\n gsl_vector_set(knots, i, 0);\n }\n\n // Fill middle with interior knots.\n gsl_vector_view view = gsl_vector_subvector(knots, spline_df, interior_knots->size);\n gsl_blas_dcopy(interior_knots, &view.vector);\n\n // Fill end with ones.\n for (size_t i = spline_df + interior_knots->size; i < knots->size; i++) {\n gsl_vector_set(knots, i, 1);\n }\n\n return knots;\n}\n\nint\nqdm_knots_rss(\n double *rss,\n\n gsl_vector *sorted_data,\n gsl_vector *middle,\n gsl_vector *interior_knots,\n\n size_t spline_df\n)\n{\n int status = 0;\n\n gsl_vector *m_knots = qdm_knots_vector(spline_df, interior_knots);\n\n size_t m = spline_df + interior_knots->size;\n gsl_matrix *ix = gsl_matrix_alloc(middle->size, m + 1);\n\n gsl_vector *emperical_quantiles = qdm_vector_quantile(sorted_data, middle);\n gsl_vector *theta = gsl_vector_alloc(ix->size2);\n gsl_vector *spline_quantiles = gsl_vector_alloc(emperical_quantiles->size);\n\n /* Build the true quantile function. */\n qdm_ispline_matrix(ix, middle, spline_df, m_knots);\n\n /* Check if the matrix is full rank. */\n double det = 0;\n status = qdm_matrix_det_tmm(ix, &det);\n if (status != 0) {\n goto cleanup;\n }\n\n if (det <= 0) {\n goto cleanup;\n }\n\n status = qdm_theta_optimize(theta, emperical_quantiles, ix);\n if (status != 0) {\n goto cleanup;\n }\n\n status = gsl_blas_dgemv(CblasNoTrans , 1.0, ix, theta, 0.0, spline_quantiles);\n if (status != 0) {\n goto cleanup;\n }\n\n *rss = qdm_vector_rss(emperical_quantiles, spline_quantiles);\n\ncleanup:\n gsl_vector_free(spline_quantiles);\n gsl_vector_free(theta);\n gsl_vector_free(emperical_quantiles);\n gsl_matrix_free(ix);\n gsl_vector_free(m_knots);\n\n return status;\n}\n\nint\nqdm_knots_optimize(\n gsl_vector *result,\n\n gsl_rng *rng,\n\n gsl_vector *sorted_data,\n gsl_vector *middle,\n gsl_vector *possible_knots,\n\n size_t iterate_n,\n size_t spline_df\n)\n{\n int status = 0;\n double rss = INFINITY;\n double rss_found = 0;\n\n gsl_vector *interior_knots = gsl_vector_alloc(result->size);\n\n for (size_t i = 0; i < iterate_n; i++) {\n status = gsl_ran_choose(\n rng,\n interior_knots->data,\n interior_knots->size,\n possible_knots->data,\n possible_knots->size,\n sizeof(double)\n );\n if (status != 0) {\n goto cleanup;\n }\n\n status = qdm_knots_rss(\n &rss_found,\n\n sorted_data,\n middle,\n interior_knots,\n\n spline_df\n );\n if (status != 0) {\n goto cleanup;\n }\n\n if (rss_found < rss) {\n rss = rss_found;\n\n status = gsl_vector_memcpy(result, interior_knots);\n if (status != 0) {\n goto cleanup;\n }\n }\n }\n\ncleanup:\n gsl_vector_free(interior_knots);\n\n return status;\n}\n", "meta": {"hexsha": "7e76f28b02cafe5b81e57458b07870247ad64597", "size": 3120, "ext": "c", "lang": "C", "max_stars_repo_path": "src/knots.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/knots.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/knots.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.5263157895, "max_line_length": 86, "alphanum_fraction": 0.666025641, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6535823709037764}} {"text": "#include \n#include \n#include \n//#include \n#include \n#include \n#include \n\nvoid least_square_solver(double *matA, int n_row, int n_col, double *y, double *sol_x) {\n \n int i, j, k, tmp;\n double sum;\n gsl_matrix * A = gsl_matrix_alloc (n_row,n_col);\n gsl_matrix * V = gsl_matrix_alloc (n_col,n_col);\n gsl_vector * S = gsl_vector_alloc (n_col);\n gsl_vector * work = gsl_vector_alloc (n_col);\n// gsl_matrix * U = gsl_matrix_alloc (n_row-1,n_col_ids);\n gsl_vector * b = gsl_vector_alloc (n_row);\n gsl_vector * x = gsl_vector_alloc (n_col);\n \n/* //printf A and b\n FILE *fpA, *fpU, *fpb;\n fpA = fopen(\"A.dat\",\"w\");\n fpU = fopen(\"U.dat\",\"w\");\n fpb = fopen(\"b.dat\",\"w\");*/\n \n // need to copy matA to A, y to b!\n for (i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n/* Factorise a general N x N complex matrix A into,\n *\n * P A = L U\n *\n * where P is a permutation matrix, L is unit lower triangular and U\n * is upper triangular.\n *\n * L is stored in the strict lower triangular part of the input\n * matrix. The diagonal elements of L are unity and are not stored.\n *\n * U is stored in the diagonal and upper triangular part of the\n * input matrix. \n * \n * P is stored in the permutation p. Column j of P is column k of the\n * identity matrix, where k = permutation->data[j]\n *\n * signum gives the sign of the permutation, (-1)^n, where n is the\n * number of interchanges in the permutation. \n *\n * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss\n * Elimination with Partial Pivoting).\n */\n\nint\ngsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"LU decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else if (p->size != A->size1)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = A->size1;\n size_t i, j, k;\n\n *signum = 1;\n gsl_permutation_init (p);\n\n for (j = 0; j < N - 1; j++)\n {\n /* Find maximum in the j-th column */\n\n gsl_complex ajj = gsl_matrix_complex_get (A, j, j);\n double max = gsl_complex_abs (ajj);\n size_t i_pivot = j;\n\n for (i = j + 1; i < N; i++)\n {\n gsl_complex aij = gsl_matrix_complex_get (A, i, j);\n double ai = gsl_complex_abs (aij);\n\n if (ai > max)\n {\n max = ai;\n i_pivot = i;\n }\n }\n\n if (i_pivot != j)\n {\n gsl_matrix_complex_swap_rows (A, j, i_pivot);\n gsl_permutation_swap (p, j, i_pivot);\n *signum = -(*signum);\n }\n\n ajj = gsl_matrix_complex_get (A, j, j);\n\n if (!(GSL_REAL(ajj) == 0.0 && GSL_IMAG(ajj) == 0.0))\n {\n for (i = j + 1; i < N; i++)\n {\n gsl_complex aij_orig = gsl_matrix_complex_get (A, i, j);\n gsl_complex aij = gsl_complex_div (aij_orig, ajj);\n gsl_matrix_complex_set (A, i, j, aij);\n\n for (k = j + 1; k < N; k++)\n {\n gsl_complex aik = gsl_matrix_complex_get (A, i, k);\n gsl_complex ajk = gsl_matrix_complex_get (A, j, k);\n \n /* aik = aik - aij * ajk */\n\n gsl_complex aijajk = gsl_complex_mul (aij, ajk);\n gsl_complex aik_new = gsl_complex_sub (aik, aijajk);\n\n gsl_matrix_complex_set (A, i, k, aik_new);\n }\n }\n }\n }\n \n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x)\n{\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LU->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Copy x <- b */\n\n gsl_vector_complex_memcpy (x, b);\n\n /* Solve for x */\n\n gsl_linalg_complex_LU_svx (LU, p, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_vector_complex * x)\n{\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution/rhs size\", GSL_EBADLEN);\n }\n else\n {\n /* Apply permutation to RHS */\n\n gsl_permute_vector_complex (p, x);\n\n /* Solve for c using forward-substitution, L c = P b */\n\n gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x);\n\n /* Perform back-substitution, U x = c */\n\n gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x);\n\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_complex_LU_refine (const gsl_matrix_complex * A, const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * residual)\n{\n if (A->size1 != A->size2)\n {\n GSL_ERROR (\"matrix a must be square\", GSL_ENOTSQR);\n }\n if (LU->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n }\n else if (A->size1 != LU->size2)\n {\n GSL_ERROR (\"LU matrix must be decomposition of a\", GSL_ENOTSQR);\n }\n else if (LU->size1 != p->size)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else if (LU->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LU->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Compute residual, residual = (A * x - b) */\n\n gsl_vector_complex_memcpy (residual, b);\n\n {\n gsl_complex one = GSL_COMPLEX_ONE;\n gsl_complex negone = GSL_COMPLEX_NEGONE;\n gsl_blas_zgemv (CblasNoTrans, one, A, x, negone, residual);\n }\n\n /* Find correction, delta = - (A^-1) * residual, and apply it */\n\n gsl_linalg_complex_LU_svx (LU, p, residual);\n\n {\n gsl_complex negone= GSL_COMPLEX_NEGONE;\n gsl_blas_zaxpy (negone, residual, x);\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_matrix_complex * inverse)\n{\n size_t i, n = LU->size1;\n\n int status = GSL_SUCCESS;\n\n gsl_matrix_complex_set_identity (inverse);\n\n for (i = 0; i < n; i++)\n {\n gsl_vector_complex_view c = gsl_matrix_complex_column (inverse, i);\n int status_i = gsl_linalg_complex_LU_svx (LU, p, &(c.vector));\n\n if (status_i)\n status = status_i;\n }\n\n return status;\n}\n\ngsl_complex\ngsl_linalg_complex_LU_det (gsl_matrix_complex * LU, int signum)\n{\n size_t i, n = LU->size1;\n\n gsl_complex det = gsl_complex_rect((double) signum, 0.0);\n\n for (i = 0; i < n; i++)\n {\n gsl_complex zi = gsl_matrix_complex_get (LU, i, i);\n det = gsl_complex_mul (det, zi);\n }\n\n return det;\n}\n\n\ndouble\ngsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU)\n{\n size_t i, n = LU->size1;\n\n double lndet = 0.0;\n\n for (i = 0; i < n; i++)\n {\n gsl_complex z = gsl_matrix_complex_get (LU, i, i);\n lndet += log (gsl_complex_abs (z));\n }\n\n return lndet;\n}\n\n\ngsl_complex\ngsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU, int signum)\n{\n size_t i, n = LU->size1;\n\n gsl_complex phase = gsl_complex_rect((double) signum, 0.0);\n\n for (i = 0; i < n; i++)\n {\n gsl_complex z = gsl_matrix_complex_get (LU, i, i);\n \n double r = gsl_complex_abs(z);\n\n if (r == 0)\n {\n phase = gsl_complex_rect(0.0, 0.0);\n break;\n }\n else\n {\n z = gsl_complex_div_real(z, r);\n phase = gsl_complex_mul(phase, z);\n }\n }\n\n return phase;\n}\n", "meta": {"hexsha": "53606797dabfc9a30e023cf358dbe2e616a198b8", "size": 8719, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/linalg/luc.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.0268656716, "max_line_length": 202, "alphanum_fraction": 0.5947929808, "num_tokens": 2438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6529351786621035}} {"text": "/* randist/sphere.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 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\nvoid\ngsl_ran_dir_2d (const gsl_rng * r, double *x, double *y)\n{\n /* This method avoids trig, but it does take an average of 8/pi =\n * 2.55 calls to the RNG, instead of one for the direct\n * trigonometric method. */\n\n double u, v, s;\n do\n {\n u = -1 + 2 * gsl_rng_uniform (r);\n v = -1 + 2 * gsl_rng_uniform (r);\n s = u * u + v * v;\n }\n while (s > 1.0 || s == 0.0);\n\n /* This is the Von Neumann trick. See Knuth, v2, 3rd ed, p140\n * (exercise 23). Note, no sin, cos, or sqrt ! */\n\n *x = (u * u - v * v) / s;\n *y = 2 * u * v / s;\n\n /* Here is the more straightforward approach, \n * s = sqrt (s); *x = u / s; *y = v / s;\n * It has fewer total operations, but one of them is a sqrt */\n}\n\nvoid\ngsl_ran_dir_2d_trig_method (const gsl_rng * r, double *x, double *y)\n{\n /* This is the obvious solution... */\n /* It ain't clever, but since sin/cos are often hardware accelerated,\n * it can be faster -- it is on my home Pentium -- than von Neumann's\n * solution, or slower -- as it is on my Sun Sparc 20 at work\n */\n double t = 6.2831853071795864 * gsl_rng_uniform (r); /* 2*PI */\n *x = cos (t);\n *y = sin (t);\n}\n\nvoid\ngsl_ran_dir_3d (const gsl_rng * r, double *x, double *y, double *z)\n{\n double s, a;\n\n /* This is a variant of the algorithm for computing a random point\n * on the unit sphere; the algorithm is suggested in Knuth, v2,\n * 3rd ed, p136; and attributed to Robert E Knop, CACM, 13 (1970),\n * 326.\n */\n\n /* Begin with the polar method for getting x,y inside a unit circle\n */\n do\n {\n *x = -1 + 2 * gsl_rng_uniform (r);\n *y = -1 + 2 * gsl_rng_uniform (r);\n s = (*x) * (*x) + (*y) * (*y);\n }\n while (s > 1.0);\n\n *z = -1 + 2 * s; /* z uniformly distributed from -1 to 1 */\n a = 2 * sqrt (1 - s); /* factor to adjust x,y so that x^2+y^2\n * is equal to 1-z^2 */\n *x *= a;\n *y *= a;\n}\n\nvoid\ngsl_ran_dir_nd (const gsl_rng * r, size_t n, double *x)\n{\n double d;\n size_t i;\n /* See Knuth, v2, 3rd ed, p135-136. The method is attributed to\n * G. W. Brown, in Modern Mathematics for the Engineer (1956).\n * The idea is that gaussians G(x) have the property that\n * G(x)G(y)G(z)G(...) is radially symmetric, a function only\n * r = sqrt(x^2+y^2+...)\n */\n d = 0;\n do\n {\n for (i = 0; i < n; ++i)\n {\n x[i] = gsl_ran_gaussian (r, 1.0);\n d += x[i] * x[i];\n }\n }\n while (d == 0);\n d = sqrt (d);\n for (i = 0; i < n; ++i)\n {\n x[i] /= d;\n }\n}\n", "meta": {"hexsha": "a93615e62b5b9ba663cbcd0b66480fc89ee01422", "size": 3487, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/sphere.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/sphere.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/sphere.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 29.0583333333, "max_line_length": 84, "alphanum_fraction": 0.5864640092, "num_tokens": 1154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.803173801068221, "lm_q1q2_score": 0.6528737334317335}} {"text": "-----------natrix mul---\n/*\n * standard includes\n */\n\t#include \n\t#include \n/*\n * includes for GSL components\n * \t- use double precision\n */\n\t#include \n\t#include \n\t#include \n\t#include \n\n/*\n * FUNCTIONS\n */\n\n/*\n * simple Fibonacci sequence generator function, using recursion\n */\nsize_t fib(size_t k)\n{\n\tif (k==0)\n\t{\n\t\treturn 0;\n\t}\n\telse if (k==1)\n\t{\n\t\treturn 1;\n\t}\n\telse /* k >= 2 */\n\t{\n\t\treturn fib(k-1) + fib(k-2);\n\t}\n}\ngsl_matrix *embt_mm(const gsl_matrix *U,const gsl_matrix *V, size_t N)\n{\n\tgsl_matrix *W=gsl_matrix_calloc(N,N);\n\tdouble sum=0;\n\tfor (size_t i=0;i!=N;i++)\n\t{\n\t\tfor(size_t j=0;j!=N;j++)\n\t\t{\n\t\t\tfor (size_t k=0;k!=N;k++)\n\t\t\t{\n\t\t\t\tsum=sum+gsl_matrix_get(U,i,k)*gsl_matrix_get(V,k,j);\n\t\t\t}\n\t\t\tgsl_matrix_set(W,i,j,(double)sum);\n\t\t\tsum=0;\n\t\t}\n\t}\n\treturn W;\n}\n\ngsl_matrix *embt_apb(gsl_vector *u, gsl_vector *v,size_t N)\n{\n\tgsl_vector *w=gsl_vector_calloc(N);\n\tgsl_vector_add(w,u);\n\tgsl_vector_add(w,v);\n\treturn w;\n}\n\ngsl_matrix *embt_m_print(const gsl_matrix *U, size_t N)\n{\n\tfor (size_t i = 0; i != N; ++i)\n\t{\n\t\tfor (size_t j=0;j!=N;j++)\n\t\t{\n\t\t\tprintf(\"%0.2f\\t\",gsl_matrix_get(U, i, j));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\ngsl_matrix *embt_v_print(const gsl_vector *u, size_t N)\n{\n\tfor (int i = 0; i != N; ++i)\n\t{\n\t\tprintf(\"%0.2f\\n\",gsl_vector_get(u, i));\n\t}\n}\nint main()\n{\n\t/*\n\t * INITIALIZE PARAMETERS\n\t */\n\t\t/* vectors parameters */\n\t\tsize_t\t\tN=3; /* index type, vector sizes */\n\t\tgsl_vector *a = gsl_vector_alloc(N); /* allocate vector from heap of size N */\n\t\tgsl_vector *b = gsl_vector_alloc(N); /* allocate vector from heap of size N */\n\t\tgsl_vector *c = gsl_vector_calloc(N); /* allocate vector of size N but initialize entries to zero */\n\n\t\t/* random number generator parameters */\n\t\tconst gsl_rng_type *T;\n\t\tgsl_rng *r; /* handle for our random number generator */\n\n\t\t/* matrix parameters */\n\t\tgsl_matrix *A = gsl_matrix_alloc(N,N);\n\t\tgsl_matrix *B = gsl_matrix_alloc(N,N);\n\t\tgsl_matrix *C = gsl_matrix_calloc(N,N);\n\n\t/*\n\t * SET UP RANDOM NUMBER GENERATION\n\t */\n\t\tgsl_rng_env_setup();\n\t\tT = gsl_rng_default;\n\t\tr = gsl_rng_alloc(T);\n\n\t/*\n\t * VECTOR OPERATIONS\n\t */\n\t\t/* set the vector elements */\n\t\tfor (size_t i = 0; i != N; ++i)\n\t\t{\n\t\t\tgsl_vector_set(a, i, fib(i)); /* set element i of vector a to Fibonacci number i */\n\t\t\tgsl_vector_set(b, i, gsl_ran_flat(r,-1.0,+1.0)); /* set element of vector b to random number */\n\t\t}\n\n\t\t/* c = a + b */\n\t\tc=embt_apb(a,b,N); /* c += a */\n\t\t//gsl_vector_add(c, b); /* c += b */\n\n\t\t/* print results */\n\n\t\tint sum=0;\n\t/*\tMATRIX OPERATIONS */\n\t\tfor (size_t i=0;i!=N;i++)\n\t\t\tfor (size_t j=0;j!=N;j++)\n\t\t\t{\n\t\t\t\t//size_t x=j+(i*N);\n\t\t\t\tgsl_matrix_set(A,i,j,(double)fib(j+i*N));\n\t\t\t\tgsl_matrix_set(B,i,j,gsl_ran_flat(r,-100,+100));\n\t\t\t}\n\t\t//gsl_matrix_mul_elements(C, A); /* c += a */\n\t\t//gsl_matrix_mul_elements(C, B); /* c += b */\n\t\tC=embt_mm(A,B,N);\n\n\t\tprintf(\"a= \\n\");embt_v_print(a,N);\n\t\tprintf(\"b= \\n\");embt_v_print(b,N);\n\t\tprintf(\"c= \\n\");embt_v_print(c,N);\n\t\tprintf(\"A= \\n\");embt_m_print(A,N);\n\t\tprintf(\"B= \\n\");embt_m_print(B,N);\n\t\tprintf(\"C= \\n\");embt_m_print(C,N);\n\n\t/* de-allocate memory */\n\tgsl_vector_free(a);\n\tgsl_vector_free(b);\n\tgsl_vector_free(c);\n\tgsl_matrix_free(A);\n\tgsl_matrix_free(B);\n\tgsl_matrix_free(C);\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "741a56ec446d6cd9e08a27c5db67143ae09a5204", "size": 3305, "ext": "c", "lang": "C", "max_stars_repo_path": "C program/matric_mul_gsl.c", "max_stars_repo_name": "gov466/Embedded-C", "max_stars_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T15:42:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T15:42:58.000Z", "max_issues_repo_path": "C program/matric_mul_gsl.c", "max_issues_repo_name": "gov466/Embedded-C", "max_issues_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "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 program/matric_mul_gsl.c", "max_forks_repo_name": "gov466/Embedded-C", "max_forks_repo_head_hexsha": "febf81fbda55d38a587335057dd561fc486f5103", "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.3225806452, "max_line_length": 102, "alphanum_fraction": 0.6175491679, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6527251176299957}} {"text": "/**\n * Copyright 2017 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 \"JacobiSolver.h\"\n\nint JacobiSolver(unsigned long *II, unsigned long *J, double *A, unsigned long M, unsigned long N, unsigned long long nz, double *b, unsigned long M_Vector, unsigned long N_Vector, unsigned long long nz_vector,double *x2, int iterationNumber) {\n\t\n\t//Jacobi Method as shown in the example from https://en.wikipedia.org/wiki/Jacobi_method\n\t\n\tunsigned long \tk \t= 0;\n\tint \t\tstop \t= 0;\n\t\n\tunsigned int\ti\t= 0;\n\t\n\tdouble\t\tresult\t= 0.0;\n\t\n\t//Initial solution\n\tdouble *x1=(double *) calloc(nz_vector,sizeof(double));\n\t//double *x2=(double *) calloc(nz_vector,sizeof(double));\n\t\n\tdouble *res=(double *) calloc(nz_vector,sizeof(double));\n\t\n\tdouble *LU=(double *) calloc(nz,sizeof(double));\n\tdouble *Dinv=(double *) calloc(nz,sizeof(double));\n\t\n\tdouble *T=(double *) calloc(nz,sizeof(double));\n\tdouble *C=(double *) calloc(nz_vector,sizeof(double));\n\t\n\t\n\tif(!isDiagonallyDominant(A,M,N,nz)){\n\t\tfprintf(stderr, \"[%s] The matrix is not diagonally dominant\\n\",__func__);\n\t\t//return 0;\n\t}\n\t\n\tgetLUValues(LU, A,M,N,nz);\n\n\tgetDInvValues(Dinv, A,M,N,nz);\n\t\n\tfor(i = 0; i< N; i++){\n\t\tx1[i] = 1.0;\n\t}\n\t\n\t//T=-D^{-1}(L+U)\n\t/*\n\tvoid cblas_dgemm (const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE transa, const CBLAS_TRANSPOSE transb, const MKL_INT m, const MKL_INT n, const MKL_INT k, const double alpha, const double *a, const MKL_INT lda, const double *b, const MKL_INT ldb, const double beta, double *c, const MKL_INT ldc);\n\t*/\n\tcblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, M, N, N, -1.0, Dinv, N, LU, N, 0.0, T, N);\n\t//writeDenseCoordinateMatrixRowLine(\"stdout\", T,M,N,nz);\n\t\n\t//C=-D^{-1}b\n\tcblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, Dinv, N, b, 1, 0.0, C, 1);\n\t\n\t//writeDenseVector(\"stdout\", C,nz_vector,1, nz_vector);\n\tunsigned long maxIterations = M*2;\n\t\n\tif(iterationNumber != 0 ){\n\t\tmaxIterations = iterationNumber;\n\t}\n\t\n\twhile(!stop) {\n\t\n\t\t// x^{(1)}= Tx^{(0)}+C\n\t\t//x2 = T*x1\n\t\tcblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, T, N, x1, 1, 0.0, x2, 1);\n\t\t\n\t\t//x2 = x2+C\n\t\tcblas_daxpy(nz_vector,1.0,C, 1, x2, 1);\n\t\t\n\t\t//res = A*x - b\n\t\tmemcpy(res, b, nz_vector*sizeof(double));\n\t\tcblas_dgemv(CblasRowMajor, CblasNoTrans, M,N , 1.0, A, N, x2, 1, -1.0, res, 1);\n\t\n\t\t\n\t\tresult = vectorSumElements(res,N);\n\t\tif((fabs(result)<=EPSILON)||(k == maxIterations)){\n\t\t\t//fprintf(stderr,\"Sum vector res is %lg\\n\",result);\n\t\t\tstop = 1;\n\t\t}\n\t\n\t\tmemcpy(x1, x2, nz_vector*sizeof(double));\n\t\t//writeDenseVector(\"stdout\", x1,nz_vector,1, nz_vector);\n\t\tk++;\n\t}\n\t\n\t//memcpy(b, x2, N*sizeof(double));\n\n\tfree(x1);\n\t//free(x2);\n\tfree(res);\n\n\tfprintf(stderr, \"[%s] Number of iterations %lu\\n\",__func__,k);\n\t\n\treturn 1;\n\t\n}\n", "meta": {"hexsha": "970ee07fd9b6b9295b51ba9e5b6d6e719966b067", "size": 3466, "ext": "c", "lang": "C", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/solvers/JacobiSolver.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/solvers/JacobiSolver.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/solvers/JacobiSolver.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": 30.6725663717, "max_line_length": 298, "alphanum_fraction": 0.6748413156, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6527037889192143}} {"text": "/* tz_3dgeom_utils.c\n *\n * 17-Jan-2008 Initial write: Ting Zhao\n */\n#include \n#include \n#include \"tz_geo3d_utils.h\"\n#ifdef HAVE_LIBGSL\n# if defined(HAVE_INLINE)\n# undef HAVE_INLINE\n# define INLINE_SUPPRESSED\n# endif\n#include \n#include \n#include \n# if defined(INLINE_SUPPRESSED)\n# define HAVE_INLINE\n# endif\n#endif\n#include \"tz_error.h\"\n#include \"tz_utilities.h\"\n#include \"tz_constant.h\"\n#include \"tz_geoangle_utils.h\"\n#include \"tz_geometry.h\"\n#include \"tz_3dgeom.h\"\n#include \"tz_darray.h\"\n#include \"tz_math.h\"\n\n#define TZ_DIST_3D_EPS 0.0000000000001 /* rounding torelance */\n\n/* Geo3d_Translate_Coordinate(): 3D coordinate translation.\n * \n * Args: x - x coordinate to translate. It stores the result after return;\n * y - y coordinate to translate. It stores the result after return;\n * z - z coordinate to translate. It stores the result after return;\n * dx - x axis translation;\n * dy - y axis translation;\n * dz - z axis translation.\n *\n * Return: void.\n */\nvoid Geo3d_Translate_Coordinate(double *x, double *y, double *z, \n\t\t\t\tdouble dx, double dy, double dz)\n{\n *x += dx;\n *y += dy;\n *z += dz;\n}\n\n/* Geo3d_Coordinate_Offset(): 3D coordinates offset.\n * \n * Args: x1, y1, z1 - start coordinate;\n * x2, y2, z2 - end coordinate;\n * dx, dy, dz - store the result.\n *\n * Return: void.\n */\nvoid Geo3d_Coordinate_Offset(double x1, double y1, double z1,\n\t\t\t double x2, double y2, double z2,\n\t\t\t double *dx, double *dy, double *dz)\n{\n *dx = x2 - x1;\n *dy = y2 - y1;\n *dz = z2 - z1;\n}\n\n/*\n * Geo3d_Rotate_Coordinate(): 3D rotation.\n * \n * Args: x, y, z - the point to be rotated;\n * theta - angle around the X axis;\n * psi - angle around the Z axis;\n * reverse - reverse the rotation or not.\n *\n * Return: void.\n */\nvoid Geo3d_Rotate_Coordinate(double *x, double *y, double *z,\n\t\t\t double theta, double psi, BOOL reverse)\n{\n double p[3] = {*x, *y, *z};\n Rotate_XZ(p, p, 1, theta, psi, reverse);\n *x = p[0];\n *y = p[1];\n *z = p[2];\n}\n\n/* Geo3d_Orientation_Normal(): calculate the normal vector at a certain \n * direction.\n *\n * Args: theta - radian around X axis;\n * psi - radian around Z axis;\n * x - resulted x coordinate;\n * y - resulted y coordinate;\n * z - resulted z coordinate.\n *\n * Return: void.\n */\nvoid Geo3d_Orientation_Normal(double theta, double psi, \n\t\t\t double *x, double *y, double *z)\n{\n /* rotaion of the vector (0, 0, 1) */\n double sin_theta = sin(theta);\n *x = sin_theta * sin(psi);\n *y = -sin_theta * cos(psi);\n //*z = cos(theta);\n *z = sqrt(1.0 - sin_theta * sin_theta);\n}\n\nvoid Geo3d_Normal_Orientation(double x, double y, double z, \n\t\t\t double *theta, double *psi)\n{\n /*\n *theta = acos(z);\n *psi = Vector_Angle(x, y) + TZ_PI_2; \n */\n //*psi = Vector_Angle(x, y) + TZ_PI_2 * 3.0; \n \n /* The range of theta will be [-pi, pi] and \n * the range of psi will be [-pi/2, pi/2]. */\n *theta = acos(z);\n\n if (*theta < GEOANGLE_COMPARE_EPS) {\n *psi = 0.0;\n } else {\n if (y >= 0.0) {\n *theta = -*theta;\n *psi = Vector_Angle(x, y) - TZ_PI_2; \n } else {\n *psi = Vector_Angle(x, y) - TZ_PI_2 * 3.0; \n }\n }\n}\n\nvoid Geo3d_Coord_Orientation(double x, double y, double z, \n\t\t\t double *theta, double *psi)\n{\n double r = Geo3d_Orgdist(x, y, z);\n if (r > TZ_DIST_3D_EPS) {\n x /= r;\n y /= r;\n z /= r;\n Geo3d_Normal_Orientation(x, y, z, theta, psi);\n } else {\n *theta = 0.0;\n *psi = 0.0;\n }\n}\n\nvoid Geo3d_Rotate_Orientation(double rtheta, double rpsi, \n\t\t\t double *theta, double *psi)\n{\n double coord[3];\n Geo3d_Orientation_Normal(*theta, *psi, coord, coord + 1, coord + 2);\n Rotate_XZ(coord, coord, 1, rtheta, rpsi, 0);\n Geo3d_Normal_Orientation(coord[0], coord[1], coord[2], theta, psi);\n}\n\ndouble Geo3d_Dot_Product(double x1, double y1, double z1,\n\t\t\t double x2, double y2, double z2)\n{\n return x1 * x2 + y1 * y2 + z1 * z2;\n}\n\nvoid Geo3d_Cross_Product(double x1, double y1, double z1,\n\t\t\t double x2, double y2, double z2,\n\t\t\t double *x, double *y, double *z)\n{\n *x = y1 * z2 - y2 * z1;\n *y = x2 * z1 - x1 * z2;\n *z = x1 * y2 - x2 * y1;\n}\n\ndouble Geo3d_Orgdist_Sqr(double x, double y, double z)\n{\n return x * x + y * y + z * z;\n}\n\ndouble Geo3d_Orgdist(double x, double y, double z)\n{\n return sqrt(x * x + y * y + z * z);\n}\n\ndouble Geo3d_Dist_Sqr(double x1, double y1, double z1,\n\t\t double x2, double y2, double z2)\n{\n double dx = x1 - x2;\n double dy = y1 - y2;\n double dz = z1 - z2;\n\n return dx * dx + dy * dy + dz * dz;\n}\n\ndouble Geo3d_Dist(double x1, double y1, double z1,\n\t\t double x2, double y2, double z2)\n{\n double dx = x1 - x2;\n double dy = y1 - y2;\n double dz = z1 - z2;\n\n return sqrt(dx * dx + dy * dy + dz * dz); \n}\n\ndouble Geo3d_Angle2(double x1, double y1, double z1,\n\t\t double x2, double y2, double z2)\n{\n double d1 = Geo3d_Orgdist_Sqr(x1, y1, z1);\n if (d1 == 0.0) {\n return 0.0;\n }\n\n double d2 = Geo3d_Orgdist_Sqr(x2, y2, z2);\n if (d2 == 0.0) {\n return 0.0;\n }\n\n double d12 = Geo3d_Dot_Product(x1, y1, z1, x2, y2, z2) / sqrt(d1 * d2);\n \n /* to avoid invalid value caused by rounding error */\n d12 = (fabs(d12) > 1.0) ? round(d12) : d12;\n \n return acos(d12); \n} \n\nvoid Geo3d_Lineseg_Break(const double *line_start, const double *line_end,\n\t\t\t double lambda, double *point)\n{\n int i;\n for (i = 0; i < 3; i++) {\n point[i] = (1 - lambda) * line_start[i] + lambda * line_end[i];\n }\n}\n\n#define GEO3D_LINESEG_DIST2_EPS TZ_DIST_3D_EPS\n\n/*\n * reference: http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline3d/\n */\nstatic int geo3d_line_line_dist(const double *line1_start, \n\t\t\t\tconst double *line1_end,\n\t\t\t\tconst double *line2_start, \n\t\t\t\tconst double *line2_end,\n\t\t\t\tdouble *dc1, double *dc2,\n\t\t\t\tdouble *intersect1, double *intersect2,\n\t\t\t\tdouble eps)\n{\n double ds[3]; /*13*/\n double de[3]; /*24*/\n\n int i;\n for (i = 0; i < 3; i++) {\n dc1[i] = line1_end[i] - line1_start[i]; /*21*/\n dc2[i] = line2_end[i] - line2_start[i]; /*43*/\n ds[i] = line1_start[i] - line2_start[i];\n de[i] = line1_end[i] - line2_end[i];\n }\n\n double d2121 = dc1[0] * dc1[0] + dc1[1] * dc1[1] + dc1[2] * dc1[2];\n double d4343 = dc2[0] * dc2[0] + dc2[1] * dc2[1] + dc2[2] * dc2[2];\n\n if (d2121 < eps) {\n if (d4343 < eps) {\n return -3;\n }\n\n return -1;\n }\n\n if (d4343 < eps) {\n return -2;\n }\n \n double d4321 = dc2[0] * dc1[0] + dc2[1] * dc1[1] + dc2[2] * dc1[2];\n\n double denom = d2121 * d4343 - d4321 * d4321;\n\n double d1343 = ds[0] * dc2[0] + ds[1] * dc2[1] + ds[2] * dc2[2];\n double d1321 = ds[0] * dc1[0] + ds[1] * dc1[1] + ds[2] * dc1[2];\n\n double numer = d1343 * d4321 - d1321 * d4343;\n\n /* parallel */\n if (denom <= eps) {\n return 0;\n }\n\n *intersect1 = numer / denom;\n *intersect2 = (d1343 + d4321 * (*intersect1)) / d4343;\n\n return 1;\n}\n\n\nstatic int geo3d_point_line_dist(const double *point, \n\t\t\t\t const double *line_start,\n\t\t\t\t const double *line_end, \t\t\t\n\t\t\t\t double *lamda, double eps)\n{\n double line_vec[3];\n double point_vec[3];\n int i;\n for (i = 0; i < 3; i++) {\n line_vec[i] = line_end[i] - line_start[i];\n point_vec[i] = point[i] - line_start[i];\n }\n\n double length_sqr = Geo3d_Orgdist_Sqr(line_vec[0], line_vec[1], line_vec[2]);\n\n if (length_sqr < eps) {\n return 0;\n }\n\n /* projection from point to line */\n double dot = point_vec[0] * line_vec[0] + point_vec[1] * line_vec[1] +\n point_vec[2] * line_vec[2];\n\n *lamda = dot / length_sqr;\n\n return 1;\n} \n\n\ndouble Geo3d_Line_Line_Dist(double line1_start[], double line1_end[],\n\t\t\t double line2_start[], double line2_end[])\n{\n double intersect1, intersect2;\n double dc1[3], dc2[3];\n \n double lamda;\n\n switch (geo3d_line_line_dist(line1_start, line1_end, line2_start, line2_end,\n\t\t\t dc1, dc2, &intersect1, &intersect2, \n\t\t\t TZ_DIST_3D_EPS)) {\n case -3: /* point to point */\n return Geo3d_Dist(line1_start[0], line1_start[1], line1_start[2],\n\t\t line2_start[0], line2_start[1], line2_start[2]);\n case -1: /* point to line2 */\n geo3d_point_line_dist(line1_start, line2_start, line2_end, &lamda, \n\t\t\t TZ_DIST_3D_EPS);\n return Geo3d_Dist(line1_start[0], line1_start[1], line1_start[2],\n\t\t line2_start[0] + lamda * dc2[0],\n\t\t line2_start[1] + lamda * dc2[1],\n\t\t line2_start[2] + lamda * dc2[2]);\n case -2: /* point to line 1 */\n geo3d_point_line_dist(line2_start, line1_start, line1_end, &lamda, \n\t\t\t TZ_DIST_3D_EPS);\n return Geo3d_Dist(line2_start[0], line2_start[1], line2_start[2],\n\t\t line1_start[0] + lamda * dc1[0],\n\t\t line1_start[1] + lamda * dc1[1],\n\t\t line1_start[2] + lamda * dc1[2]);\n case 0: /* parallel */\n geo3d_point_line_dist(line1_start, line2_start, line2_end, &lamda, \n\t\t\t TZ_DIST_3D_EPS);\n return Geo3d_Dist(line1_start[0], line1_start[1], line1_start[2],\n\t\t line2_start[0] + lamda * dc2[0],\n\t\t line2_start[1] + lamda * dc2[1],\n\t\t line2_start[2] + lamda * dc2[2]);\n default: /* line to line */\n return sqrt(Geo3d_Dist_Sqr(line1_start[0] + intersect1 * dc1[0],\n\t\t\t line1_start[1] + intersect1 * dc1[1],\n\t\t\t line1_start[2] + intersect1 * dc1[2],\n\t\t\t line2_start[0] + intersect2 * dc2[0],\n\t\t\t line2_start[1] + intersect2 * dc2[1],\n\t\t\t line2_start[2] + intersect2 * dc2[2]));\n }\n}\n\ndouble Geo3d_Lineseg_Lineseg_Dist(double line1_start[], double line1_end[],\n\t\t\t\t double line2_start[], double line2_end[],\n\t\t\t\t double *intersect1, double *intersect2,\n\t\t\t\t int *cond)\n{\n double dc1[3]; /*21*/\n double dc2[3]; /*43*/\n \n double d1, d2;\n\n switch (geo3d_line_line_dist(line1_start, line1_end, line2_start, line2_end,\n\t\t\t dc1, dc2, intersect1, intersect2, \n\t\t\t TZ_DIST_3D_EPS)) {\n case 0: /* parallel */\n *cond = 9;\n d1 = Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end, \n\t\t\t\t intersect1);\n d2 = Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2);\n if (d1 <= d2) {\n *intersect2 = *intersect1;\n *intersect1 = 1.0;\n return d1;\n } else {\n *intersect1 = 0.0;\n return d2;\n }\n case -1:\n *intersect1 = 0.0;\n *cond = 10;\n return Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end, \n\t\t\t\t intersect2);\n case -2:\n *intersect2= 0.0;\n *cond = 10;\n return Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end, \n\t\t\t\t intersect1);\n case -3:\n *cond = 10;\n *intersect1 = 0.0;\n *intersect2 = 0.0;\n return Geo3d_Dist(line1_start[0], line1_start[1], line1_start[2],\n\t\t line2_start[0], line2_start[1], line2_start[2]);\n default:\n#if defined BREAK_IS_IN_RANGE\n# undef BREAK_IS_IN_RANGE\n#endif\n#define BREAK_IS_IN_RANGE(mu) ((mu >= 0.0) && (mu <= 1.0))\n\n if (BREAK_IS_IN_RANGE(*intersect1) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 0;\n return sqrt(Geo3d_Dist_Sqr(line1_start[0] + *intersect1 * dc1[0],\n\t\t\t\t line1_start[1] + *intersect1 * dc1[1],\n\t\t\t\t line1_start[2] + *intersect1 * dc1[2],\n\t\t\t\t line2_start[0] + *intersect2 * dc2[0],\n\t\t\t\t line2_start[1] + *intersect2 * dc2[1],\n\t\t\t\t line2_start[2] + *intersect2 * dc2[2]));\n } else if ((*intersect1 < 0.0) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 1;\n *intersect1 = 0.0;\n return Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2);\n } else if ((*intersect1 > 0.0) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 2;\n *intersect1 = 1.0;\n return Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2);\n } else if ((*intersect2 < 0.0) && BREAK_IS_IN_RANGE(*intersect1)) {\n *cond = 3;\n *intersect2 = 0.0;\n return Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1);\n } else if ((*intersect2 > 1.0) && BREAK_IS_IN_RANGE(*intersect1)) {\n *cond = 4;\n *intersect2 = 1.0;\n return Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1);\n } else if ((*intersect1 < 0.0) && (*intersect2 < 0.0)) {\n *cond = 5;\n d1 = Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end, \n\t\t\t\t intersect2);\n d2 = Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1);\n if (d1 <= d2) {\n\t*intersect1 = 0.0;\n\treturn d1;\n } else {\n\t*intersect2 = 0.0;\n\treturn d2;\n }\n } else if ((*intersect1 > 1.0) && (*intersect2 < 0.0)) {\n *cond = 6;\n d1 = Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2);\n d2 = Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1);\n if (d1 <= d2) {\n\t*intersect1 = 1.0;\n\treturn d1;\n } else {\n\t*intersect2 = 0.0;\n\treturn d2;\n }\n } else if ((*intersect1 < 0.0) && (*intersect2 > 1.0)) {\n *cond = 7;\n d1 = Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2);\n d2 = Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1);\n if (d1 <= d2) {\n\t*intersect1 = 0.0;\n\treturn d1;\n } else {\n\t*intersect2 = 1.0;\n\treturn d2;\n }\n } else if ((*intersect1 > 1.0) && (*intersect2 > 1.0)) {\n *cond = 8;\n d1 = Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2);\n d2 = Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1);\n if (d1<= d2) {\n\t*intersect1 = 1.0;\n\treturn d1;\n } else {\n\t*intersect2 = 1.0;\n\treturn d2;\n }\n }\n }\n\n return -1.0;\n}\n\n\ndouble Geo3d_Lineseg_Dist2(double line1_start[], double line1_end[],\n\t\t\t double line2_start[], double line2_end[],\n\t\t\t double *intersect1, double *intersect2,\n\t\t\t int *cond)\n{\n double dc1[3]; /*21*/\n double dc2[3]; /*43*/\n double ds[3]; /*13*/\n double de[3]; /*24*/\n\n int i;\n for (i = 0; i < 3; i++) {\n dc1[i] = line1_end[i] - line1_start[i];\n dc2[i] = line2_end[i] - line2_start[i];\n ds[i] = line1_start[i] - line2_start[i];\n de[i] = line1_end[i] - line2_end[i];\n }\n\n double d2121 = dc1[0] * dc1[0] + dc1[1] * dc1[1] + dc1[2] * dc1[2];\n double d4343 = dc2[0] * dc2[0] + dc2[1] * dc2[1] + dc2[2] * dc2[2];\n\n ASSERT(d2121 > GEO3D_LINESEG_DIST2_EPS, \"invalid length\");\n ASSERT(d4343 > GEO3D_LINESEG_DIST2_EPS, \"invalid length\");\n \n double d4321 = dc2[0] * dc1[0] + dc2[1] * dc1[1] + dc2[2] * dc1[2];\n\n double denom = d2121 * d4343 - d4321 * d4321;\n\n double d1343 = ds[0] * dc2[0] + ds[1] * dc2[1] + ds[2] * dc2[2];\n double d1321 = ds[0] * dc1[0] + ds[1] * dc1[1] + ds[2] * dc1[2];\n\n double numer = d1343 * d4321 - d1321 * d4343;\n\n if (denom <= GEO3D_LINESEG_DIST2_EPS) {\n *cond = 9;\n return \n dmin2(Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end, \n\t\t\t\t intersect1),\n\t Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2)\n\t );\n }\n\n *intersect1 = numer / denom;\n *intersect2 = (d1343 + d4321 * (*intersect1)) / d4343;\n\n#if defined BREAK_IS_IN_RANGE\n# undef BREAK_IS_IN_RANGE\n#endif\n#define BREAK_IS_IN_RANGE(mu) ((mu >= 0.0) && (mu <= 1.0))\n\n\n if (BREAK_IS_IN_RANGE(*intersect1) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 0;\n return sqrt(Geo3d_Dist_Sqr(line1_start[0] + *intersect1 * dc1[0],\n\t\t\t line1_start[1] + *intersect1 * dc1[1],\n\t\t\t line1_start[2] + *intersect1 * dc1[2],\n\t\t\t line2_start[0] + *intersect2 * dc2[0],\n\t\t\t line2_start[1] + *intersect2 * dc2[1],\n\t\t\t line2_start[2] + *intersect2 * dc2[2]));\n } else if ((*intersect1 < 0.0) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 1;\n return Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2);\n } else if ((*intersect1 > 0.0) && BREAK_IS_IN_RANGE(*intersect2)) {\n *cond = 2;\n return Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2);\n } else if ((*intersect2 < 0.0) && BREAK_IS_IN_RANGE(*intersect1)) {\n *cond = 3;\n return Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1);\n } else if ((*intersect2 > 1.0) && BREAK_IS_IN_RANGE(*intersect1)) {\n *cond = 4;\n return Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1);\n } else if ((*intersect1 < 0.0) && (*intersect2 < 0.0)) {\n *cond = 5;\n return \n dmin2(Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end, \n\t\t\t\t intersect2),\n\t Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1)\n\t );\n } else if ((*intersect1 > 1.0) && (*intersect2 < 0.0)) {\n *cond = 6;\n return \n dmin2(Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2),\n\t Geo3d_Point_Lineseg_Dist(line2_start, line1_start, line1_end,\n\t\t\t\t intersect1)\n\t );\n } else if ((*intersect1 < 0.0) && (*intersect2 > 1.0)) {\n *cond = 7;\n return\n dmin2(Geo3d_Point_Lineseg_Dist(line1_start, line2_start, line2_end,\n\t\t\t\t intersect2),\n\t Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1)\n\t );\n } else if ((*intersect1 > 1.0) && (*intersect2 > 1.0)) {\n *cond = 8;\n return\n dmin2(Geo3d_Point_Lineseg_Dist(line1_end, line2_start, line2_end,\n\t\t\t\t intersect2),\n\t Geo3d_Point_Lineseg_Dist(line2_end, line1_start, line1_end,\n\t\t\t\t intersect1)\n\t );\n }\n\n return -1.0;\n}\n\n#define GEO3D_POINT_LINESEG_EPS 0.0000000000001\ndouble Geo3d_Point_Lineseg_Dist(const double *point, const double *line_start, \n\t\t\t\tconst double *line_end, double *lamda)\n{\n double tmp_lamda;\n int status = geo3d_point_line_dist(point, line_start, line_end, &tmp_lamda, \n\t\t\t\t GEO3D_POINT_LINESEG_EPS);\n \n double dist;\n if (status == 0) {\n dist = Geo3d_Dist(line_start[0], line_start[1], line_start[2],\n\t\t point[0], point[1], point[2]);\n } else {\n if ((tmp_lamda >= 0.0) && (tmp_lamda <= 1.0)) {\n dist = \n\tGeo3d_Dist(point[0], point[1], point[2],\n\t\t (1.0 - tmp_lamda) * line_start[0] + tmp_lamda * line_end[0],\n\t\t (1.0 - tmp_lamda) * line_start[1] + tmp_lamda * line_end[1],\n\t\t (1.0 - tmp_lamda) * line_start[2] + tmp_lamda * line_end[2]);\n } else if (tmp_lamda < 0.0) {\n tmp_lamda = 0.0;\n dist = sqrt(Geo3d_Dist_Sqr(line_start[0], line_start[1], line_start[2],\n\t\t\t\t point[0], point[1], point[2]));\n } else {\n tmp_lamda = 1.0;\n dist = sqrt(Geo3d_Dist_Sqr(line_end[0], line_end[1], line_end[2],\n\t\t\t\t point[0], point[1], point[2]));\n }\n }\n\n /*\n double line_vec[3];\n double point_vec[3];\n int i;\n for (i = 0; i < 3; i++) {\n line_vec[i] = line_end[i] - line_start[i];\n point_vec[i] = point[i] - line_start[i];\n }\n double length_sqr = Geo3d_Orgdist_Sqr(line_vec[0], line_vec[1], line_vec[2]);\n\n double tmp_lamda = 0.0;\n double dist = -1.0;\n\n if (length_sqr <= GEO3D_POINT_LINESEG_EPS) {\n dist = sqrt(Geo3d_Dist_Sqr(line_start[0], line_start[1], line_start[2],\n\t\t\t point[0], point[1], point[2]));\n } else {\n double dot = point_vec[0] * line_vec[0] + point_vec[1] * line_vec[1] +\n point_vec[2] * line_vec[2];\n\n double point_vec_lensqr = Geo3d_Orgdist_Sqr(point_vec[0], point_vec[1], \n\t\t\t\t\t point_vec[2]);\n \n if (point_vec_lensqr <= GEO3D_POINT_LINESEG_EPS) {\n dist = 0.0;\n } else {\n tmp_lamda = dot / length_sqr;\n if ((tmp_lamda >= 0.0) && (tmp_lamda <= 1.0)) {\n\tdist = sqrt(point_vec_lensqr - dot * dot / length_sqr);\n } else if (tmp_lamda < 0.0) {\n\tdist = sqrt(Geo3d_Dist_Sqr(line_start[0], line_start[1], line_start[2],\n\t\t\t\t point[0], point[1], point[2]));\n } else {\n\tdist = sqrt(Geo3d_Dist_Sqr(line_end[0], line_end[1], line_end[2],\n\t\t\t\t point[0], point[1], point[2]));\n }\n }\n }\n */\n if (lamda != NULL) {\n *lamda = tmp_lamda;\n }\n\n return dist;\n}\n\n\nvoid Geo3d_Cov_Orientation(double *cov, double *vec, double *ext)\n{\n#ifdef HAVE_LIBGSL\n gsl_matrix_view gmv = gsl_matrix_view_array(cov, 3, 3);\n \n gsl_vector *eval = gsl_vector_alloc(3);\n gsl_matrix *evec = gsl_matrix_alloc(3,3);\n gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(3);\n\n gsl_eigen_symmv(&(gmv.matrix), eval, evec, w);\n gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_DESC);\n\n if(ext != NULL) {\n darraycpy(ext, gsl_vector_const_ptr(eval, 0), 0, 3);\n }\n\n gsl_vector_view v = gsl_vector_view_array(vec, 3);\n gsl_matrix_get_col(&(v.vector), evec, 0);\n\n gsl_vector_free(eval);\n gsl_matrix_free(evec);\n gsl_eigen_symmv_free(w); \n#else\n double eigv[3];\n Matrix_Eigen_Value_Cs(cov[0], cov[4], cov[8], cov[1], cov[2], cov[5], eigv);\n Matrix_Eigen_Vector_Cs(cov[0], cov[4], cov[8], cov[1], cov[2], cov[5], \n eigv[0], vec);\n if(ext != NULL) {\n darraycpy(ext, eigv, 0, 3);\n }\n#endif\n}\n", "meta": {"hexsha": "3d2c09eaa37580008543228ab3af8d12f9bca58e", "size": 20682, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/tz_geo3d_utils.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/tz_geo3d_utils.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/tz_geo3d_utils.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5268965517, "max_line_length": 79, "alphanum_fraction": 0.6131902137, "num_tokens": 7306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.652461879091966}} {"text": "/*\n # This file is part of the Astrometry.net suite.\n # Licensed under a 3-clause BSD style license - see LICENSE\n */\n\n#include \n\n#include \"compat.h\"\n#include \"gslutils.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint gslutils_solve_leastsquares_v(gsl_matrix* A, int NB, ...) {\n int i, res;\n gsl_vector** B = malloc(NB * sizeof(gsl_vector*));\n // Whoa, three-star programming!\n gsl_vector*** X = malloc(NB * sizeof(gsl_vector**));\n gsl_vector*** R = malloc(NB * sizeof(gsl_vector**));\n\n gsl_vector** Xtmp = malloc(NB * sizeof(gsl_vector*));\n gsl_vector** Rtmp = malloc(NB * sizeof(gsl_vector*));\n\n va_list va;\n va_start(va, NB);\n for (i=0; isize1;\n N = A->size2;\n\n for (i=0; isize == M);\n }\n\n tau = gsl_vector_alloc(MIN(M, N));\n assert(tau);\n\n ret = gsl_linalg_QR_decomp(A, tau);\n assert(ret == 0);\n // A,tau now contains a packed version of Q,R.\n\n for (i=0; i\n#include \n#include \n#include \n#include \n\n#include \n\n/* normalization constants for the spherical harmonics */\nstatic double sph_cnsts[9] = {\n\t0.282094791773878, /* l = 0 */\n\t0.488602511902920, 0.488602511902920, 0.488602511902920, /* l = 1 */\n\t0.182091405098680, 0.364182810197360, 0.630783130505040, 0.364182810197360, 0.182091405098680\n};\n\n/* Computes real spherical harmonics ylm in the direction of vector r:\n\t ylm = c * plm( cos(theta) ) * sin(m*phi) for m < 0\n\t ylm = c * plm( cos(theta) ) * cos(m*phi) for m >= 0\n\t with (theta,phi) the polar angles of r, c a positive normalization\n\t constant and plm associated legendre polynomials. */\n\nvoid FC_FUNC_(oct_ylm, OCT_YLM)\n (const fint * np, const double *x, const double *y, const double *z, const fint *l, const fint *m, double * restrict ylm)\n{\n double r, r2, rr, rx, ry, rz, cosphi, sinphi, cosm, sinm, phase;\n int i, ip;\n\n if(l[0] == 0) {\n for (ip = 0; ip < np[0]; ip++) ylm[ip] = sph_cnsts[0];\n return;\n }\n\n for (ip = 0; ip < np[0]; ip++){\n\n r2 = x[ip]*x[ip] + y[ip]*y[ip] + z[ip]*z[ip];\n\n /* if r=0, direction is undefined => make ylm=0 except for l=0 */\n if(r2 < 1.0e-15){\n ylm[ip] = 0.0;\n continue;\n }\n\n switch(l[0]){\n case 1:\n rr = 1.0/sqrt(r2);\n switch(m[0]){\n case -1: ylm[ip] = -sph_cnsts[1]*rr*y[ip]; continue;\n case 0: ylm[ip] = sph_cnsts[2]*rr*z[ip]; continue;\n case 1: ylm[ip] = -sph_cnsts[3]*rr*x[ip]; continue;\n }\n case 2:\n switch(m[0]){\n case -2: ylm[ip] = sph_cnsts[4]*6.0*x[ip]*y[ip]/r2; \n\tcontinue;\n case -1: ylm[ip] = -sph_cnsts[5]*3.0*y[ip]*z[ip]/r2; \n\tcontinue;\n case 0: ylm[ip] = sph_cnsts[6]*0.5*(3.0*z[ip]*z[ip]/r2 - 1.0); \n\tcontinue;\n case 1: ylm[ip] = -sph_cnsts[7]*3.0*x[ip]*z[ip]/r2; \n\tcontinue;\n case 2: ylm[ip] = sph_cnsts[8]*3.0*(x[ip]*x[ip] - y[ip]*y[ip])/r2; \n\tcontinue;\n }\n }\n\n /* get phase */\n rr = 1.0/sqrt(r2);\n \n rx = x[ip]*rr;\n ry = y[ip]*rr;\n rz = z[ip]*rr;\n\n r = hypot(rx, ry);\n if(r < 1e-20) r = 1e-20; /* one never knows... */\n\n cosphi = rx/r;\n sinphi = ry/r;\n\n /* compute sin(mphi) and cos(mphi) by adding cos/sin */\n cosm = 1.; sinm=0.;\n for(i = 0; i < abs(m[0]); i++){\n double a = cosm, b = sinm;\n cosm = a*cosphi - b*sinphi;\n sinm = a*sinphi + b*cosphi;\n }\n phase = m[0] < 0 ? sinm : cosm;\n phase = m[0] == 0 ? phase : sqrt(2.0)*phase;\n\t\n /* adding small number (~= 10^-308) to avoid floating invalids */\n rz = rz + DBL_MIN;\n\n r = gsl_sf_legendre_sphPlm(l[0], abs(m[0]), rz);\n\n /* I am not sure whether we are including the Condon-Shortley factor (-1)^m */\n ylm[ip] = r*phase;\n }\n}\n\n", "meta": {"hexsha": "45f616548e4e59d5466d7bb2b098f652c5fc3f0f", "size": 3542, "ext": "c", "lang": "C", "max_stars_repo_path": "src/math/ylm.c", "max_stars_repo_name": "neelravi/octopus", "max_stars_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "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/math/ylm.c", "max_issues_repo_name": "neelravi/octopus", "max_issues_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "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/math/ylm.c", "max_forks_repo_name": "neelravi/octopus", "max_forks_repo_head_hexsha": "25cb84cf590276af9ce4617039ba3849e328594c", "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.5166666667, "max_line_length": 126, "alphanum_fraction": 0.6030491248, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6517463532204646}} {"text": "/*\n\tSimbicon 1.5 Controller Editor Framework, \n\tCopyright 2009 Stelian Coros, Philippe Beaudoin and Michiel van de Panne.\n\tAll rights reserved. Web: www.cs.ubc.ca/~van/simbicon_cef\n\n\tThis file is part of the Simbicon 1.5 Controller Editor Framework.\n\n\tSimbicon 1.5 Controller Editor Framework is free software: you can \n\tredistribute it and/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tSimbicon 1.5 Controller Editor Framework is distributed in the hope \n\tthat it will be useful, but WITHOUT ANY WARRANTY; without even the \n\timplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n\tSee the GNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with Simbicon 1.5 Controller Editor Framework. \n\tIf not, see .\n*/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n#include \n\n\n#include \n\n\n#define MATRIX_AT(m, i, j) (*((m->data + ((i) * m->tda + (j)))))\n\nclass Vector3d;\n\n\n/*====================================================================================================================================================================*\n | This class will be used to represent matrices of arbitrary sizes (m rows by n columns) that have elements of type double. The underlying data strucutre used by |\n | this class is gsl's (Gnu Scientific Library) matrix class. This class also makes use of the ATLAS implementation of BLAS for some operations such as matrix-matrix |\n | multiplication. This class is meant to improve performance, not necessarily ease of use. |\n *====================================================================================================================================================================*/\n\nclass Matrix {\nfriend class Vector;\nprotected:\n\n\t//this data structure holds all the matrix data\n\tgsl_matrix *matrix;\n\n\npublic:\n\t/**\n\t\tconstructor - creates an m rows by n columns matrix that is not initialized to any particular values\n\t*/\n\tMatrix(int m, int n);\n\n\t/**\n\t\tdefault constructor\n\t*/\n\tMatrix();\n\n\t/**\n\t\tcopy constructor - performs a deep copy of the matrix passed in as a parameter.\n\t*/\n\tMatrix(const Matrix& other);\n\n\t/**\n\t\tdestructor.\n\t*/\n virtual ~Matrix();\n\n\t/**\n\t\tloads the matrix with all zero values.\n\t*/\n\tvoid loadZero();\n\n\t/**\n\t\tloads the matrix with 1's on the diagonal, 0's everywhere else - note: the matrix doesn't have to be square.\n\t*/\n\tvoid loadIdentity();\n\n\t/**\n\t\tthis method sets the current matrix to a 3x3 matrix that is equal to the outer product of the vectors a and b\n\t*/\n\tvoid setToOuterproduct(const Vector3d& a, const Vector3d& b);\n\n\t/**\n\t\tthis method resizes the current matrix to have m rows and n cols. If not enough space is allocated for it, then a new matrix of\n\t\tcorrect dimensions is allocated. There is no guarantee with regards to the data that is contained in the matrix after a resize operation.\n\t*/\n\tvoid resizeTo(int m, int n);\n\n\t/**\n\t\tcopy operator - performs a deep copy of the matrix passed in as a parameter.\n\t*/\n\tMatrix& operator=(const Matrix &other);\n\n\t/**\n\t\tthis method performs a shallow copy of the matrix that is passed in as a parameter.\n\t*/\n\tvoid shallowCopy(const Matrix& other, int startRow = 0, int startCol = 0, int endRow = -1, int endCol = -1);\n\n\t/**\n\t\tthis method performs a deep copy of the matrix that is passed in as a paramerer.\n\t*/\n\tvoid deepCopy(const Matrix& other);\n\n\t/**\n\t\tReturns the number of columns\n\t*/\n\tint getColumnCount() const;\n\n\t/**\n\t\tReturns the number of rows\n\t*/\n\tint getRowCount()const;\n\n\t/**\n\t\tMultiplies each element in the current matrix by a constant\n\t*/\n\tvoid multiplyBy(const double val);\n\n\t/**\n\t\tThis method sets the current matrix to be equal to one of the products: a * b, a'*b, a*b' or a'*b'.\n\t\tThe values of transA and transB indicate which of the matrices are tranposed and which ones are not.\n\t*/\n\tvoid setToProductOf(const Matrix& a, const Matrix& b, bool transA = false, bool transB = false);\n\n\t/**\n\t\tThis method computes the inverse of the matrix a and writes it over the current matrix. The implementation\n\t\tfor the inverse of a matrix was obtained from Graphite. The parameter t is used as a threshold value for\n\t\tdeterminants, etc so that we still get a result for the inverse of our matrix even if it is very poorly conditioned.\n\t*/\n\tvoid setToInverseOf(const Matrix &a, double t = 0);\n\n /**\n This method prints the contents of the matrix - testing purpose only.\n */\n void printMatrix() const;\n\n /**\n This method prints the contents of the matrix - testing purpose only.\n */\n std::string toString() const;\n\n\t/**\n\t\tThis method sets the current matrix to be a sub-matrix (starting at (i,j) and ending at (i+rows, j+cols)\n\t\tof the one that is passed in as a parameter - shallow copy only.\n\t*/\n\tvoid setToSubmatrix(const Matrix &a, int i, int j, int rows, int cols);\n\n\t/**\n\t\tThis method returns a copy of the value of the matrix at (i,j)\n\t*/\n\tdouble get(int i, int j) const;\n\n\t/**\n\t\tThis method sets the value of the matrix at (i,j) to newVal.\n\t*/\n\tvoid set(int i, int j, double newVal);\n\n\n\t/**\n\t\tThis method is used to set the values in the matrix to the ones that are passed in the array of doubles.\n\t\tIt is assumed that the array contains the right number of elements and that there is no space between consecutive rows (tda == nrCols).\n\t*/\n\tvoid setValues(double* vals);\n\n\t/**\n\t\tthis method returns a pointer to its internal matrix data structure\n\t*/\n\tgsl_matrix* getMatrixPointer() const;\n\n\n\t/**\n\t\tImplement this operator to have a quick way of multiplying 3x3 matrices by vectors - used for dynamics for instance\n\t*/\n\tVector3d operator * (const Vector3d &other);\n\n\t/**\n\t\tImplement a potentially faster function for 3x3 matrix - vector3d multiplication. Result and v need to be different!!\n\t*/\n\tvoid postMultiplyVector(const Vector3d& v, Vector3d& result);\n\n\t/**\n\t\tStill need to do (if need be): get row/col vector. Initialize a matrix from a vector so that we can create a 1xn matrix easily.\n\t\tmake sure dgemv works properly, implement vector class, etc, swap, add, scale matrices, etc\n\t*/\n\n\t/**\n\t\tthis method adds the matrix that is passed in as a parameter to the current matrix. In addition, it scales, both matrices by the two\n\t\tnumbers that are passed in as parameters:\n\t\t*this = a * *this + b * other.\n\t*/\n\tvoid add(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0);\n\n\t/**\n\t\tthis method subtracts the matrix that is passed in as a parameter from the current matrix. In addition, it scales, both matrices by the two\n\t\tnumbers that are passed in as parameters:\n\t\t*this = a * *this - b * other.\n\t*/\n\tvoid sub(const Matrix& other, double scaleA = 1.0, double scaleB = 1.0);\n\n};\n\n\nvoid testMatrixClass();\n\n", "meta": {"hexsha": "be531829907510db638400e83b68b4f02179a559", "size": 7082, "ext": "h", "lang": "C", "max_stars_repo_path": "SPlisHSPlasH/MathLib/Matrix.h", "max_stars_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_stars_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "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": "SPlisHSPlasH/MathLib/Matrix.h", "max_issues_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_issues_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-28T03:31:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-29T12:54:26.000Z", "max_forks_repo_path": "SPlisHSPlasH/MathLib/Matrix.h", "max_forks_repo_name": "scarensac/SPlisHSPlasH_for_cuda", "max_forks_repo_head_hexsha": "02266dab8d3b459d62e7d67c4c7fefd8ae1b69ca", "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.0934579439, "max_line_length": 168, "alphanum_fraction": 0.6715617057, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6513275054641576}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\ndouble wtime(void)\n{\n struct timeval tp;\n gettimeofday(&tp,NULL);\n return ((double) (tp.tv_sec)) + ((double) (tp.tv_usec))/1e6;\n}\n\n#define EPS 3.0e-11\nvoid gauleg(double x1, double x2, double x[], double w[], int n)\n{\n int m,j,i;\n double z1,z,xm,xl,pp,p3,p2,p1;\n\n m=(n+1)/2;\n xm=0.5*(x2+x1);\n xl=0.5*(x2-x1);\n for (i=1;i<=m;i++) {\n z=cos(3.141592654*(i-0.25)/(n+0.5));\n do {\n p1=1.0;\n p2=0.0;\n for (j=1;j<=n;j++) {\n\tp3=p2;\n\tp2=p1;\n\tp1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j;\n }\n pp=n*(z*p1-p2)/(z*z-1.0);\n z1=z;\n z=z1-p1/pp;\n } while (fabs(z-z1) > EPS);\n x[i]=xm-xl*z;\n x[n+1-i]=xm+xl*z;\n w[i]=2.0*xl/((1.0-z*z)*pp*pp);\n w[n+1-i]=w[i];\n }\n}\n#undef EPS\n", "meta": {"hexsha": "9ae41010185a3d6632d2afd4093c21e5aec57e38", "size": 879, "ext": "c", "lang": "C", "max_stars_repo_path": "src/utils.c", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.c", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/utils.c", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 18.3125, "max_line_length": 64, "alphanum_fraction": 0.5221843003, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6513142078455306}} {"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"lib/util/random_matrix.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common/c_math/linalg.h\"\n\nvoid MatArrRandomGaussian(int32_t nr, int32_t nc, const gsl_rng *rng,\n double *d) {\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = 0; j < nc; ++j) {\n d[i*nc + j] = gsl_ran_gaussian(rng, 1.0);\n }\n }\n}\n\nvoid MatArrRandomOrthogonal(int32_t n, const gsl_rng *rng, double *d) {\n MatArrRandomGaussian(n, n, rng, d);\n gsl_matrix *Q = gsl_matrix_alloc((size_t)n, (size_t)n);\n gsl_matrix *R = gsl_matrix_alloc((size_t)n, (size_t)n);\n gsl_vector *tau = gsl_vector_alloc((size_t)n);\n\n gsl_matrix_view A = gsl_matrix_view_array(d, (size_t)n, (size_t)n);\n gsl_linalg_QR_decomp(&A.matrix, tau);\n gsl_linalg_QR_unpack(&A.matrix, tau, Q, R);\n gsl_matrix_memcpy(&A.matrix, Q);\n\n gsl_vector_free(tau);\n gsl_matrix_free(R);\n gsl_matrix_free(Q);\n}\n\nvoid MatArrRandomWithRank(int32_t nr, int32_t nc, int32_t rank,\n const gsl_rng *rng, double *d) {\n assert(rank <= nr && rank <= nc);\n\n MatArrZero(nr, nc, d);\n double *u = (double *)malloc((size_t)nr * sizeof(*d));\n double *v = (double *)malloc((size_t)nc * sizeof(*d));\n for (int32_t k = 0; k < rank; ++k) {\n MatArrRandomGaussian(1, nr, rng, u);\n MatArrRandomGaussian(1, nc, rng, v);\n\n for (int32_t i = 0; i < nr; ++i) {\n for (int32_t j = 0; j < nc; ++j) {\n d[i*nc + j] += u[i] * v[j];\n }\n }\n }\n free(u);\n free(v);\n}\n", "meta": {"hexsha": "bccab2b3bf2704f908ff1e7d8c56e635edfe64f3", "size": 2224, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/util/random_matrix.c", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "lib/util/random_matrix.c", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "lib/util/random_matrix.c", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 30.0540540541, "max_line_length": 75, "alphanum_fraction": 0.6497302158, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6510049619167582}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2017 by Synge Todo \n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include \n#include \n#include \n\nint imin(int x, int y) { return (x < y) ? x : y; }\nint imax(int x, int y) { return (x > y) ? x : y; }\n\nint main(int argc, char** argv) {\n int m = 3;\n int n = 5;\n int r, lwork, i, j, info;\n double norm;\n double *s, *work;\n double **a, **u, **vt, **t;\n\n if (argc > 2) {\n m = atoi(argv[1]);\n n = atoi(argv[2]);\n }\n r = imin(m, n);\n \n /* generate matrix */\n a = alloc_dmatrix(m, n);\n for (j = 0; j < n; ++j) {\n for (i = 0; i < m; ++i) {\n mat_elem(a, i, j) = n - imax(i, j);\n }\n }\n printf(\"Matrix A: \");\n fprint_dmatrix(stdout, m, n, a);\n\n /* singular value decomposition */\n u = alloc_dmatrix(m, r);\n vt = alloc_dmatrix(r, n);\n s = alloc_dvector(r);\n t = alloc_dmatrix(m, n);\n cblas_dcopy(m * n, mat_ptr(a), 1, mat_ptr(t), 1);\n lwork = imax(3 * r + imax(m, n), 5 * r);\n work = alloc_dvector(lwork);\n info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', m, n, mat_ptr(t), m,\n vec_ptr(s), mat_ptr(u), m, mat_ptr(vt), r,\n vec_ptr(work), lwork);\n if (info != 0) {\n fprintf(stderr, \"Error: dgesvd fails\\n\");\n exit(255);\n }\n free_dmatrix(t);\n printf(\"Matrix U: \");\n fprint_dmatrix(stdout, m, r, u);\n printf(\"Singular values: \");\n fprint_dvector(stdout, r, s);\n printf(\"Matrix Vt: \");\n fprint_dmatrix(stdout, r, n, vt);\n\n /* orthogonality check */\n t = alloc_dmatrix(r, r);\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, r, r, m, 1, mat_ptr(u), m,\n mat_ptr(u), m, 0, mat_ptr(t), r);\n for (i = 0; i < r; ++i) mat_elem(t, i, i) -= 1;\n norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(t), r);\n printf(\"|| U^t U - I || = %e\\n\", norm);\n if (norm > 1e-10) {\n fprintf(stderr, \"Error: orthogonality check\\n\");\n exit(255);\n }\n\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, r, r, n, 1, mat_ptr(vt), r,\n mat_ptr(vt), r, 0, mat_ptr(t), r);\n for (i = 0; i < r; ++i) mat_elem(t, i, i) -= 1;\n norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(t), r);\n printf(\"|| V^t V - I || = %e\\n\", norm);\n if (norm > 1e-10) {\n fprintf(stderr, \"Error: orthogonality check\\n\");\n exit(255);\n }\n free_dmatrix(t);\n\n /* solution check */\n t = alloc_dmatrix(m, r);\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, m, r, n, 1, mat_ptr(a), m,\n mat_ptr(vt), r, 0, mat_ptr(t), m);\n free_dmatrix(vt);\n vt = alloc_dmatrix(r, r);\n cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, r, r, m, 1, mat_ptr(u), m,\n mat_ptr(t), m, 0, mat_ptr(vt), r);\n for (i = 0; i < r; ++i) mat_elem(vt, i, i) -= s[i];\n norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(vt), r);\n printf(\"|| U^t A V - diag(S) || = %e\\n\", norm);\n if (norm > 1e-10) {\n fprintf(stderr, \"Error: solution check\\n\");\n exit(255);\n }\n free_dmatrix(t);\n\n free_dmatrix(a);\n free_dmatrix(u);\n free_dmatrix(vt);\n free_dvector(s);\n return 0;\n}\n", "meta": {"hexsha": "03598b9354466773ae9be90783d9134ddb660e56", "size": 3437, "ext": "c", "lang": "C", "max_stars_repo_path": "example/lapack/dgesvd.c", "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_issues_repo_path": "example/lapack/dgesvd.c", "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_forks_repo_path": "example/lapack/dgesvd.c", "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "avg_line_length": 30.6875, "max_line_length": 82, "alphanum_fraction": 0.5466977015, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6509554164997416}} {"text": "/*\n # This file is part of the Astrometry.net suite.\n # Licensed under a 3-clause BSD style license - see LICENSE\n */\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"os-features.h\"\n#include \"sip-utils.h\"\n#include \"gslutils.h\"\n#include \"starutil.h\"\n#include \"mathutil.h\"\n#include \"errors.h\"\n#include \"log.h\"\n\ndouble wcs_pixel_center_for_size(double size) {\n return 0.5 + 0.5 * size;\n}\n\nvoid tan_rotate(const tan_t* tanin, tan_t* tanout, double angle) {\n double s,c;\n double newcd[4];\n memmove(tanout, tanin, sizeof(tan_t));\n s = sin(deg2rad(angle));\n c = cos(deg2rad(angle));\n newcd[0] = c*tanin->cd[0][0] + s*tanin->cd[1][0];\n newcd[1] = c*tanin->cd[0][1] + s*tanin->cd[1][1];\n newcd[2] = -s*tanin->cd[0][0] + c*tanin->cd[1][0];\n newcd[3] = -s*tanin->cd[0][1] + c*tanin->cd[1][1];\n tanout->cd[0][0] = newcd[0];\n tanout->cd[0][1] = newcd[1];\n tanout->cd[1][0] = newcd[2];\n tanout->cd[1][1] = newcd[3];\n}\n\nint sip_ensure_inverse_polynomials(sip_t* sip) {\n if ((sip->a_order == 0 && sip->b_order == 0) ||\n (sip->ap_order > 0 && sip->bp_order > 0)) {\n return 0;\n }\n sip->ap_order = sip->bp_order = MAX(sip->a_order, sip->b_order) + 1;\n return sip_compute_inverse_polynomials(sip, 0, 0, 0, 0, 0, 0);\n}\n\nint sip_compute_inverse_polynomials(sip_t* sip, int NX, int NY,\n double xlo, double xhi,\n double ylo, double yhi) {\n int inv_sip_order;\n int M, N;\n int i, j, p, q, gu, gv;\n double maxu, maxv, minu, minv;\n double u, v, U, V;\n gsl_matrix *mA;\n gsl_vector *b1, *b2, *x1, *x2;\n tan_t* tan;\n\n assert(sip->a_order == sip->b_order);\n assert(sip->ap_order == sip->bp_order);\n tan = &(sip->wcstan);\n\n logverb(\"sip_compute-inverse_polynomials: A %i, AP %i\\n\",\n sip->a_order, sip->ap_order);\n\n /*\n basic idea: lay down a grid in image, for each gridpoint, push\n through the polynomial to get yourself into warped image\n coordinate (but not yet lifted onto the sky). Then, using the\n set of warped gridpoints as inputs, fit back to their original\n grid locations as targets.\n */\n inv_sip_order = sip->ap_order;\n\n // Number of grid points to use:\n if (NX == 0)\n NX = 10 * (inv_sip_order + 1);\n if (NY == 0)\n NY = 10 * (inv_sip_order + 1);\n if (xhi == 0)\n xhi = tan->imagew;\n if (yhi == 0)\n yhi = tan->imageh;\n\n logverb(\"NX,NY %i,%i, x range [%f, %f], y range [%f, %f]\\n\",\n NX,NY, xlo, xhi, ylo, yhi);\n\n // Number of coefficients to solve for:\n // We only compute the upper triangle polynomial terms\n N = (inv_sip_order + 1) * (inv_sip_order + 2) / 2;\n\n // Number of samples to fit.\n M = NX * NY;\n\n mA = gsl_matrix_alloc(M, N);\n b1 = gsl_vector_alloc(M);\n b2 = gsl_vector_alloc(M);\n assert(mA);\n assert(b1);\n assert(b2);\n\n /*\n * Rearranging formula (4), (5), and (6) from the SIP paper gives the\n * following equations:\n * \n * +----------------------- Linear pixel coordinates in PIXELS\n * | before SIP correction\n * | +--- Intermediate world coordinates in DEGREES\n * | |\n * v v\n * -1\n * U = [CD11 CD12] * x\n * V [CD21 CD22] y\n * \n * +---------------- PIXEL distortion delta from telescope to\n * | linear coordinates\n * | +----------- Linear PIXEL coordinates before SIP correction\n * | | +--- Polynomial U,V terms in powers of PIXELS\n * v v v\n * \n * -f(u1,v1) = p11 p12 p13 p14 p15 ... * ap1\n * -f(u2,v2) = p21 p22 p23 p24 p25 ... ap2\n * ...\n * \n * -g(u1,v1) = p11 p12 p13 p14 p15 ... * bp1\n * -g(u2,v2) = p21 p22 p23 p24 p25 ... bp2\n * ...\n * \n * which recovers the A and B's.\n */\n\n minu = xlo - tan->crpix[0];\n maxu = xhi - tan->crpix[0];\n minv = ylo - tan->crpix[1];\n maxv = yhi - tan->crpix[1];\n\t\n // Sample grid locations.\n i = 0;\n for (gu=0; gu inv_sip_order)\n continue;\n assert(j < N);\n gsl_matrix_set(mA, i, j,\n pow(U, (double)p) * pow(V, (double)q));\n j++;\n }\n assert(j == N);\n gsl_vector_set(b1, i, -fuv);\n gsl_vector_set(b2, i, -guv);\n i++;\n }\n }\n assert(i == M);\n\n // Solve the linear equation.\n if (gslutils_solve_leastsquares_v(mA, 2, b1, &x1, NULL, b2, &x2, NULL)) {\n ERROR(\"Failed to solve SIP inverse matrix equation!\");\n return -1;\n }\n\n // Extract the coefficients\n j = 0;\n for (p = 0; p <= inv_sip_order; p++)\n for (q = 0; q <= inv_sip_order; q++) {\n if ((p + q > inv_sip_order))\n continue;\n assert(j < N);\n sip->ap[p][q] = gsl_vector_get(x1, j);\n sip->bp[p][q] = gsl_vector_get(x2, j);\n j++;\n }\n assert(j == N);\n\n // Check that we found values that actually invert the polynomial.\n // The error should be particularly small at the grid points.\n if (log_get_level() > LOG_VERB) {\n // rms error accumulators:\n double sumdu = 0;\n double sumdv = 0;\n int Z;\n for (gu = 0; gu < NX; gu++) {\n for (gv = 0; gv < NY; gv++) {\n double newu, newv;\n // Calculate grid position in original image pixels\n u = (gu * (maxu - minu) / (NX-1)) + minu;\n v = (gv * (maxv - minv) / (NY-1)) + minv;\n sip_calc_distortion(sip, u, v, &U, &V);\n sip_calc_inv_distortion(sip, U, V, &newu, &newv);\n sumdu += square(u - newu);\n sumdv += square(v - newv);\n }\n }\n sumdu /= (NX*NY);\n sumdv /= (NX*NY);\n debug(\"RMS error of inverting a distortion (at the grid points, in pixels):\\n\");\n debug(\" du: %g\\n\", sqrt(sumdu));\n debug(\" dv: %g\\n\", sqrt(sumdu));\n debug(\" dist: %g\\n\", sqrt(sumdu + sumdv));\n\n sumdu = 0;\n sumdv = 0;\n Z = 1000;\n for (i=0; i= 1 && x <= wcs->imagew && y >= 1 && y <= wcs->imageh);\n}\n\nanbool sip_pixel_is_inside_image(const sip_t* wcs, double x, double y) {\n return tan_pixel_is_inside_image(&(wcs->wcstan), x, y);\n}\n\nanbool sip_is_inside_image(const sip_t* wcs, double ra, double dec) {\n double x,y;\n if (!sip_radec2pixelxy(wcs, ra, dec, &x, &y))\n return FALSE;\n return sip_pixel_is_inside_image(wcs, x, y);\n}\n\nanbool tan_is_inside_image(const tan_t* wcs, double ra, double dec) {\n double x,y;\n if (!tan_radec2pixelxy(wcs, ra, dec, &x, &y))\n return FALSE;\n return tan_pixel_is_inside_image(wcs, x, y);\n}\n\nint* sip_filter_stars_in_field(const sip_t* sip, const tan_t* tan,\n const double* xyz, const double* radec,\n int N, double** p_xy, int* inds, int* p_Ngood) {\n int i, Ngood;\n int W, H;\n double* xy = NULL;\n anbool allocd = FALSE;\n\t\n assert(sip || tan);\n assert(xyz || radec);\n assert(p_Ngood);\n\n Ngood = 0;\n if (!inds) {\n inds = malloc(N * sizeof(int));\n allocd = TRUE;\n }\n\n if (p_xy)\n xy = malloc(N * 2 * sizeof(double));\n\n if (sip) {\n W = sip->wcstan.imagew;\n H = sip->wcstan.imageh;\n } else {\n W = tan->imagew;\n H = tan->imageh;\n }\n\n for (i=0; i= W) || (y >= H))\n continue;\n\n inds[Ngood] = i;\n if (xy) {\n xy[Ngood * 2 + 0] = x;\n xy[Ngood * 2 + 1] = y;\n }\n Ngood++;\n }\n\n if (allocd)\n inds = realloc(inds, Ngood * sizeof(int));\n\n if (xy)\n xy = realloc(xy, Ngood * 2 * sizeof(double));\n if (p_xy)\n *p_xy = xy;\n\n *p_Ngood = Ngood;\n\t\n return inds;\n}\n\nvoid sip_get_radec_center(const sip_t* wcs,\n double* p_ra, double* p_dec) {\n double px = wcs_pixel_center_for_size(wcs->wcstan.imagew);\n double py = wcs_pixel_center_for_size(wcs->wcstan.imageh);\n sip_pixelxy2radec(wcs, px, py, p_ra, p_dec);\n}\n\nvoid tan_get_radec_center(const tan_t* wcs,\n double* p_ra, double* p_dec) {\n double px = wcs_pixel_center_for_size(wcs->imagew);\n double py = wcs_pixel_center_for_size(wcs->imageh);\n tan_pixelxy2radec(wcs, px, py, p_ra, p_dec);\n}\n\ndouble sip_get_radius_deg(const sip_t* wcs) {\n return arcsec2deg(sip_pixel_scale(wcs) * hypot(wcs->wcstan.imagew, wcs->wcstan.imageh)/2.0);\n}\n\ndouble tan_get_radius_deg(const tan_t* wcs) {\n return arcsec2deg(tan_pixel_scale(wcs) * hypot(wcs->imagew, wcs->imageh)/2.0);\n}\n\nvoid sip_get_radec_center_hms(const sip_t* wcs,\n int* rah, int* ram, double* ras,\n int* decsign, int* decd, int* decm, double* decs) {\n double ra, dec;\n sip_get_radec_center(wcs, &ra, &dec);\n ra2hms(ra, rah, ram, ras);\n dec2dms(dec, decsign, decd, decm, decs);\n}\n\nvoid sip_get_radec_center_hms_string(const sip_t* wcs,\n char* rastr, char* decstr) {\n double ra, dec;\n sip_get_radec_center(wcs, &ra, &dec);\n ra2hmsstring(ra, rastr);\n dec2dmsstring(dec, decstr);\n}\n\nvoid sip_get_field_size(const sip_t* wcs,\n double* pw, double* ph,\n char** units) {\n double minx = 0.5;\n double maxx = (wcs->wcstan.imagew + 0.5);\n double midx = (minx + maxx) / 2.0;\n double miny = 0.5;\n double maxy = (wcs->wcstan.imageh + 0.5);\n double midy = (miny + maxy) / 2.0;\n double ra1, dec1, ra2, dec2, ra3, dec3;\n double w, h;\n\n // measure width through the middle\n sip_pixelxy2radec(wcs, minx, midy, &ra1, &dec1);\n sip_pixelxy2radec(wcs, midx, midy, &ra2, &dec2);\n sip_pixelxy2radec(wcs, maxx, midy, &ra3, &dec3);\n w = arcsec_between_radecdeg(ra1, dec1, ra2, dec2) +\n arcsec_between_radecdeg(ra2, dec2, ra3, dec3);\n // measure height through the middle\n sip_pixelxy2radec(wcs, midx, miny, &ra1, &dec1);\n sip_pixelxy2radec(wcs, midx, midy, &ra2, &dec2);\n sip_pixelxy2radec(wcs, midx, maxy, &ra3, &dec3);\n h = arcsec_between_radecdeg(ra1, dec1, ra2, dec2) +\n arcsec_between_radecdeg(ra2, dec2, ra3, dec3);\n\n if (MIN(w, h) < 60.0) {\n *units = \"arcseconds\";\n *pw = w;\n *ph = h;\n } else if (MIN(w, h) < 3600.0) {\n *units = \"arcminutes\";\n *pw = w / 60.0;\n *ph = h / 60.0;\n } else {\n *units = \"degrees\";\n *pw = w / 3600.0;\n *ph = h / 3600.0;\n }\n}\n\nvoid sip_walk_image_boundary(const sip_t* wcs, double stepsize,\n void (*callback)(const sip_t* wcs, double x, double y, double ra, double dec, void* token),\n void* token) {\n int i, side;\n // Walk the perimeter of the image in steps of stepsize pixels\n double W = wcs->wcstan.imagew;\n double H = wcs->wcstan.imageh;\n {\n double Xmin = 0.5;\n double Xmax = W + 0.5;\n double Ymin = 0.5;\n double Ymax = H + 0.5;\n double offsetx[] = { Xmin, Xmax, Xmax, Xmin };\n double offsety[] = { Ymin, Ymin, Ymax, Ymax };\n double stepx[] = { +stepsize, 0, -stepsize, 0 };\n double stepy[] = { 0, +stepsize, 0, -stepsize };\n int Nsteps[] = { ceil(W/stepsize), ceil(H/stepsize), ceil(W/stepsize), ceil(H/stepsize) };\n\n for (side=0; side<4; side++) {\n for (i=0; idecmin = MIN(b->decmin, dec);\n b->decmax = MAX(b->decmax, dec);\n if (ra - b->rac > 180)\n // wrap-around: racenter < 180, ra has gone < 0 but been wrapped around to > 180\n ra -= 360;\n if (b->rac - ra > 180)\n // wrap-around: racenter > 180, ra has gone > 360 but wrapped around to > 0.\n ra += 360;\n\n b->ramin = MIN(b->ramin, ra);\n b->ramax = MAX(b->ramax, ra);\n}\n\nvoid sip_get_radec_bounds(const sip_t* wcs, int stepsize,\n double* pramin, double* pramax,\n double* pdecmin, double* pdecmax) {\n struct radecbounds b;\n\n sip_get_radec_center(wcs, &(b.rac), &(b.decc));\n b.ramin = b.ramax = b.rac;\n b.decmin = b.decmax = b.decc;\n sip_walk_image_boundary(wcs, stepsize, radec_bounds_callback, &b);\n\n // Check for poles...\n // north pole\n if (sip_is_inside_image(wcs, 0, 90)) {\n b.ramin = 0;\n b.ramax = 360;\n b.decmax = 90;\n }\n if (sip_is_inside_image(wcs, 0, -90)) {\n b.ramin = 0;\n b.ramax = 360;\n b.decmin = -90;\n }\n\n if (pramin) *pramin = b.ramin;\n if (pramax) *pramax = b.ramax;\n if (pdecmin) *pdecmin = b.decmin;\n if (pdecmax) *pdecmax = b.decmax;\n}\n\nvoid sip_shift(const sip_t* sipin, sip_t* sipout,\n double xlo, double xhi, double ylo, double yhi) {\n memmove(sipout, sipin, sizeof(sip_t));\n tan_transform(&(sipin->wcstan), &(sipout->wcstan),\n xlo, xhi, ylo, yhi, 1.0);\n}\n\nvoid tan_transform(const tan_t* tanin, tan_t* tanout,\n double xlo, double xhi, double ylo, double yhi,\n double scale) {\n memmove(tanout, tanin, sizeof(tan_t));\n tanout->imagew = (xhi - xlo + 1) * scale;\n tanout->imageh = (yhi - ylo + 1) * scale;\n tanout->crpix[0] = (tanout->crpix[0] - (xlo - 1)) * scale;\n tanout->crpix[1] = (tanout->crpix[1] - (ylo - 1)) * scale;\n tanout->cd[0][0] /= scale;\n tanout->cd[0][1] /= scale;\n tanout->cd[1][0] /= scale;\n tanout->cd[1][1] /= scale;\n}\n\nvoid tan_scale(const tan_t* tanin, tan_t* tanout,\n double scale) {\n memmove(tanout, tanin, sizeof(tan_t));\n tanout->imagew *= scale;\n tanout->imageh *= scale;\n\n tanout->crpix[0] = 0.5 + scale * (tanin->crpix[0] - 0.5);\n tanout->crpix[1] = 0.5 + scale * (tanin->crpix[1] - 0.5);\n tanout->cd[0][0] /= scale;\n tanout->cd[0][1] /= scale;\n tanout->cd[1][0] /= scale;\n tanout->cd[1][1] /= scale;\n}\n\nvoid sip_scale(const sip_t* wcsin, sip_t* wcsout,\n double scale) {\n int i, j;\n memmove(wcsout, wcsin, sizeof(sip_t));\n tan_scale(&(wcsin->wcstan), &(wcsout->wcstan), scale);\n for (i=0; i<=wcsin->a_order; i++) {\n for (j=0; j<=wcsin->a_order; j++) {\n if (i + j > wcsin->a_order)\n continue;\n wcsout->a[i][j] *= pow(scale, 1 - (i+j));\n }\n }\n for (i=0; i<=wcsin->b_order; i++) {\n for (j=0; j<=wcsin->b_order; j++) {\n if (i + j > wcsin->b_order)\n continue;\n wcsout->b[i][j] *= pow(scale, 1 - (i+j));\n }\n }\n for (i=0; i<=wcsin->ap_order; i++) {\n for (j=0; j<=wcsin->ap_order; j++) {\n if (i + j > wcsin->ap_order)\n continue;\n wcsout->ap[i][j] *= pow(scale, 1 - (i+j));\n }\n }\n for (i=0; i<=wcsin->bp_order; i++) {\n for (j=0; j<=wcsin->bp_order; j++) {\n if (i + j > wcsin->bp_order)\n continue;\n wcsout->bp[i][j] *= pow(scale, 1 - (i+j));\n }\n }\n}\n\n", "meta": {"hexsha": "88ba8e25b7f6b3602e3436b820a8f73251cf636b", "size": 18086, "ext": "c", "lang": "C", "max_stars_repo_path": "util/sip-utils.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "util/sip-utils.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "util/sip-utils.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 31.7855887522, "max_line_length": 120, "alphanum_fraction": 0.5118323565, "num_tokens": 5795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6507126370476525}} {"text": "//#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic double fun(double x)\n{\n return x + cos(x * x);\n}\n\nint main(void)\n{\n const double a = 1.0;\n const double b = 10.0;\n const int steps = 10;\n double xi, yi, x[100], y[100], dx;\n FILE *input, *output;\n int i;\n\n input = fopen(\"wartosci.txt\", \"w\");\n output = fopen(\"inter-cspline.txt\", \"w\");\n\n dx = (b - a) / (double)steps;\n\n for (i = 0; i <= steps; ++i)\n {\n x[i] = a + (double)i * dx + 0.5 * sin((double)i * dx);\n y[i] = fun(x[i]);\n fprintf(input, \"%g %g\\n\", x[i], y[i]);\n }\n\n {\n gsl_interp_accel *acc = gsl_interp_accel_alloc();\n\n gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, steps + 1);\n\n gsl_spline_init(spline, x, y, steps + 1);\n\n for (xi = a; xi <= b; xi += 0.01)\n {\n yi = gsl_spline_eval(spline, xi, acc);\n fprintf(output, \"%g %g\\n\", xi, yi);\n }\n\n gsl_spline_free(spline);\n gsl_interp_accel_free(acc);\n }\n return 0;\n}\n", "meta": {"hexsha": "fdaccbf9f88cf5bbe029a8de6512ca2e63195a9e", "size": 1148, "ext": "c", "lang": "C", "max_stars_repo_path": "interpolacja.c", "max_stars_repo_name": "kosciolek/uni.mownit2-2022", "max_stars_repo_head_hexsha": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "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": "interpolacja.c", "max_issues_repo_name": "kosciolek/uni.mownit2-2022", "max_issues_repo_head_hexsha": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "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": "interpolacja.c", "max_forks_repo_name": "kosciolek/uni.mownit2-2022", "max_forks_repo_head_hexsha": "5ab20cafc9a89b3fc80832b2658171527bf617a2", "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.6603773585, "max_line_length": 77, "alphanum_fraction": 0.5322299652, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6506593940264856}} {"text": "\n#ifndef BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_\n#define BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_\n\n#include \"bio/defs.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#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nBIO_NS_START\n\n/** @file\nSee http://www.gatsby.ucl.ac.uk/~heller/bhc.pdf for the motivation for these algorithms.\n*/\n\n/** Aggregates a data set with its associated score. */\ntemplate \nstruct Cluster\n{\n typedef std::set data_set_t;\n\n data_set_t data_set;\n Score score;\n};\n\n\n/** A Normal-Wishart prior.\n\nEach datum should be an iterator that points to a sequence of reals.\n\nI am not convinced this is implemented correctly...\n*/\nstruct NormalWishartPrior\n{\n typedef double real_t;\n typedef boost::numeric::ublas::vector vector_t;\n typedef boost::numeric::ublas::matrix matrix_t;\n matrix_t s;\n vector_t m;\n real_t r;\n real_t v;\n unsigned get_num_dims() const { return s.size1(); }\n\n NormalWishartPrior(unsigned num_dimensions = 0)\n : s(num_dimensions, num_dimensions)\n , m(num_dimensions)\n {\n }\n\n template \n real_t\n operator()(\n DataIt data_begin,\n DataIt data_end) const\n {\n using namespace boost::numeric::ublas;\n\n //if we have no data\n if (data_end == data_begin)\n {\n return real_t(1);\n }\n\n //calculate the number of data points\n unsigned n = 0; //std::count_if(data_begin, data_end, true);\n for (DataIt di = data_begin;\n data_end != di;\n ++di)\n {\n ++n;\n }\n\n //put the data set in a matrix\n matrix_t x(get_num_dims(), n);\n unsigned i = 0;\n for (DataIt di = data_begin;\n data_end != di;\n ++di, ++i)\n {\n for (unsigned j = 0;\n get_num_dims() != j;\n ++j)\n {\n x(j,i) = (**di)[j];\n }\n }\n\n //calculate the sum of the data in each dimension\n vector_t x_sum(get_num_dims());\n for (unsigned j = 0;\n get_num_dims() != j;\n ++j)\n {\n x_sum(j) = 0;\n for (unsigned i = 0;\n n != i;\n ++i)\n {\n x_sum(j) += x(j, i);\n }\n }\n\n //calculate s_dash - the first term is s\n matrix_t s_dash(s);\n {\n //add X.XT to s_dash\n s_dash += prod(x, trans(x));\n\n //add m.mT term to s_dash\n s_dash += (r * n / (n + r)) * outer_prod(m, m);\n\n //add x_sum.x_sumT term to s_dash\n s_dash += (1.0 / (n + r)) * outer_prod(x_sum, x_sum);\n\n //subtract m.x_sum term from s_dash\n s_dash -= (r / (n + r)) * (outer_prod(m, x_sum) + outer_prod(x_sum, m));\n }\n\n //std::cout << s << std::endl;\n //std::cout << s_dash << std::endl;\n //std::cout << prod(x, trans(x)) << std::endl;\n\n //calculate the determinants\n const real_t s_det = get_determinant(s);\n const real_t s_dash_det = get_determinant(s_dash);\n\n //v_dash\n const real_t v_dash = v + n;\n\n //the number of dimensions\n const real_t k = get_num_dims();\n\n //the number of data points\n const real_t N = n;\n\n //the natural logarithm of the result\n real_t ln_p_D_given_H1 = 0.0;\n\n ln_p_D_given_H1 -= N * k / 2 * gsl_sf_log(2 * M_PI);\n ln_p_D_given_H1 += k / 2 * gsl_sf_log(r / (N + r));\n ln_p_D_given_H1 += v / 2 * gsl_sf_log(fabs(s_det));\n ln_p_D_given_H1 -= v_dash / 2 * gsl_sf_log(fabs(s_dash_det));\n ln_p_D_given_H1 += v_dash * k / 2 * gsl_sf_log(2);\n ln_p_D_given_H1 -= v * k / 2 * gsl_sf_log(2);\n\n //add/subtract the pi terms\n for (unsigned d = 0; k != d; ++d)\n {\n ln_p_D_given_H1 +=\n gsl_sf_lngamma((v_dash + 1 - d) / 2)\n - gsl_sf_lngamma((v + 1 - d) / 2);\n\n }\n\n return gsl_sf_exp(ln_p_D_given_H1);\n }\n\n template \n static real_t\n get_determinant(const M & m)\n {\n BOOST_ASSERT(m.size1() == m.size2());\n\n matrix_t lu(m);\n //permutation_matrix p(m.size());\n\n lu_factorize(lu);\n\n real_t result = 0;\n for (unsigned j = 0;\n lu.size1() != j;\n ++j)\n {\n result += lu(j,j);\n }\n return result;\n }\n};\n\n\n\n\n/** A Bernoulli - Beta prior.\n\nEach datum should be an iterator that points to a sequence of bools (or convertible types).\n*/\nstruct BernoulliBetaPrior\n{\n typedef double real_t;\n typedef std::vector param_vec_t;\n param_vec_t alpha;\n param_vec_t beta;\n\n BernoulliBetaPrior(unsigned num_dimensions = 0)\n : alpha(num_dimensions)\n , beta(num_dimensions)\n {\n }\n\n template \n real_t\n operator()(\n DataIt data_begin,\n DataIt data_end)\n {\n if (data_end == data_begin)\n {\n return real_t(1);\n }\n\n assert(alpha.size() == beta.size());\n assert((*data_begin)->size() == alpha.size());\n\n //the log of p(D|H1)\n double ln_p_D_H1 = 0.0;\n\n unsigned n = 0;\n for (DataIt i = data_begin; data_end != i; ++i)\n {\n ++n;\n }\n\n //for each dimension\n for (size_t d = 0; alpha.size() != d; ++d)\n {\n //work out m_d\n unsigned m_d = 0;\n for (DataIt i = data_begin; data_end != i; ++i)\n {\n assert((*i)->size() == alpha.size());\n\n if ((**i)[d])\n {\n ++m_d;\n }\n }\n\n ln_p_D_H1 +=\n gsl_sf_lngamma(alpha[d] + beta[d])\n + gsl_sf_lngamma(alpha[d] + m_d)\n + gsl_sf_lngamma(beta[d] + n - m_d)\n - gsl_sf_lngamma(alpha[d])\n - gsl_sf_lngamma(beta[d])\n - gsl_sf_lngamma(alpha[d] + beta[d] + n);\n }\n\n return gsl_sf_exp(ln_p_D_H1);\n }\n};\n\n\n\n\n/** A Multinomial Dirichlet prior.\n\nEach datum should be an iterator that points to a sequence of bools (or convertible types).\n*/\nstruct MultinomialDirichletPrior\n{\n typedef double real_t;\n typedef std::vector param_vec_t;\n param_vec_t alpha;\n\n MultinomialDirichletPrior(unsigned num_dimensions = 0)\n : alpha(num_dimensions)\n {\n }\n\n template \n real_t\n operator()(\n DataIt data_begin,\n DataIt data_end)\n {\n if (data_end == data_begin)\n {\n return real_t(1);\n }\n\n assert((*data_begin)->size() == alpha.size());\n\n //the log of p(D|H1) ie log of the result\n double ln_p_D_H1 = 0.0;\n\n //TODO - not implemented\n\n return gsl_sf_exp(ln_p_D_H1);\n }\n};\n\n\n\n\n\n\n/** The score of a cluster based on a prior model and the score of the two clusters\nit is composed of. */\nstruct BayesianClusterScore\n{\n typedef double real_t;\n\n real_t p_Dk_given_H1k;\n real_t p_Dk_given_Tk;\n\n BayesianClusterScore(real_t p_Dk_given_H1k = 1, real_t p_Dk_given_Tk = 1)\n : p_Dk_given_H1k(p_Dk_given_H1k)\n , p_Dk_given_Tk(p_Dk_given_Tk)\n {\n }\n\n bool operator<(const BayesianClusterScore & rhs) const\n {\n if (real_t(0) == p_Dk_given_Tk)\n {\n return false;\n }\n if (real_t(0) == rhs.p_Dk_given_Tk)\n {\n return false;\n }\n return operator()() < rhs();\n }\n\n real_t operator()() const\n {\n return p_Dk_given_H1k / p_Dk_given_Tk;\n }\n};\n\nBIO_NS_END\n\n\nstd::ostream &\noperator<<(std::ostream & os, const BIO_NS::BayesianClusterScore & score)\n{\n boost::io::ios_all_saver ias(os);\n os.precision(3);\n\n os << score.p_Dk_given_H1k << \"/\" << score.p_Dk_given_Tk << \"=\" << score();\n return os;\n}\n\n\nBIO_NS_START\n\n/** Scores clusters according to http://www.gatsby.ucl.ac.uk/~heller/bhcnew.pdf */\ntemplate \nstruct BayesianClusterScorer\n{\n typedef double real_t;\n typedef Model model_t;\n\n model_t & model;\n BayesianClusterScorer(model_t & model)\n : model(model)\n {\n }\n\n typedef BayesianClusterScore score_t;\n static score_t min_score() { return score_t(-1, 1); }\n\n template \n score_t\n operator()(\n const Cluster & cluster) const\n {\n const real_t marginal_likelihood = model(cluster.data_set.begin(), cluster.data_set.end());\n return score_t(marginal_likelihood, marginal_likelihood);\n }\n\n /** Returns the score of the data set resulting from merging the two data sets. */\n template \n score_t\n operator()(\n const Cluster & cluster_1,\n const Cluster & cluster_2) const\n {\n //merge the two data sets\n typename Cluster::data_set_t merged_data_set;\n set_union(\n cluster_1.data_set.begin(),\n cluster_1.data_set.end(),\n cluster_2.data_set.begin(),\n cluster_2.data_set.end(),\n std::inserter(merged_data_set, merged_data_set.begin()));\n\n score_t result;\n const real_t pi_k = 0.5; //?????\n result.p_Dk_given_H1k =\n pi_k * model(merged_data_set.begin(), merged_data_set.end());\n result.p_Dk_given_Tk =\n result.p_Dk_given_H1k\n + (1 - pi_k) * cluster_1.score.p_Dk_given_Tk * cluster_2.score.p_Dk_given_Tk;\n\n return result;\n }\n};\n\n/** Defines some types for given data types and scorers. */\ntemplate \nstruct ClusterTraits\n{\n typedef DataIt data_it;\n typedef Scorer scorer_t;\n\n typedef typename data_it::value_type data_t;\n typedef std::set data_set_t;\n\n typedef Cluster cluster_t;\n typedef typename cluster_t::data_set_t::iterator cluster_data_it;\n\n typedef std::list cluster_list_t;\n typedef typename cluster_list_t::iterator cluster_it;\n};\n\n/** Clusters the data points according to pairs' scores. */\ntemplate \nvoid\ncluster(\n DataIt data_begin,\n DataIt data_end,\n Scorer & scorer,\n Output & output)\n{\n using namespace boost;\n using namespace std;\n\n typedef ClusterTraits traits_t;\n\n //initialise the list of clusters with one entry for every data point\n typename traits_t::cluster_list_t cluster_list;\n for (DataIt d = data_begin;\n data_end != d;\n ++d)\n {\n typename traits_t::cluster_t cluster;\n cluster.data_set.insert(d);\n cluster.score = scorer(cluster);\n output(cluster_list.insert(cluster_list.begin(), cluster));\n }\n\n //while we have at least 2 clusters to merge\n while (1 < cluster_list.size())\n {\n //look for the best pair of clusters to merge in the hierarchy\n typename std::pair best_clusters =\n make_pair(cluster_list.end(), cluster_list.end());\n typename Scorer::score_t best_score = Scorer::min_score();\n\n //for each pair of clusters, c1 and c2\n for (typename traits_t::cluster_it c1 = cluster_list.begin();\n cluster_list.end() != c1;\n ++c1)\n {\n typename traits_t::cluster_it c2 = c1;\n ++c2;\n for ( ;\n cluster_list.end() != c2;\n ++c2)\n {\n //score the pair of clusters\n const typename Scorer::score_t score = scorer(*c1, *c2);\n\n //is it the best score so far?\n if (best_score < score)\n {\n //update best\n best_score = score;\n best_clusters.first = c1;\n best_clusters.second = c2;\n }\n }\n }\n assert(best_clusters.first != best_clusters.second);\n assert(cluster_list.end() != best_clusters.first);\n assert(cluster_list.end() != best_clusters.second);\n\n //create and add the merged cluster\n typename traits_t::cluster_t merged_cluster;\n merged_cluster.score = best_score;\n set_union(\n best_clusters.first->data_set.begin(),\n best_clusters.first->data_set.end(),\n best_clusters.second->data_set.begin(),\n best_clusters.second->data_set.end(),\n inserter(merged_cluster.data_set, merged_cluster.data_set.begin()));\n\n //let the output know\n output(\n best_clusters.first,\n best_clusters.second,\n cluster_list.insert(cluster_list.begin(), merged_cluster));\n\n //remove the old data sets and add the merged one\n cluster_list.erase(best_clusters.first);\n cluster_list.erase(best_clusters.second);\n }\n}\n\nstruct LoggingClusterer\n{\n std::ostream & os;\n\n LoggingClusterer(std::ostream & os) : os(os)\n {\n }\n\n template \n void\n operator()(\n const ClusterIt & cluster)\n {\n using namespace std;\n\n os << \"Initial cluster: \";\n for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster->data_set.begin();\n cluster->data_set.end() != d;\n ++d)\n {\n os << **d << \",\";\n }\n os << \" score:\" << cluster->score << endl;\n }\n\n template \n void\n operator()(\n ClusterIt cluster_1,\n ClusterIt cluster_2,\n ClusterIt merged_cluster)\n {\n using namespace std;\n\n //print what we are doing\n cout << \"Clustering: \";\n for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster_1->data_set.begin();\n cluster_1->data_set.end() != d;\n ++d)\n {\n os << **d << \",\";\n }\n cout << \" with \";\n for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster_2->data_set.begin();\n cluster_2->data_set.end() != d;\n ++d)\n {\n os << **d << \",\";\n }\n os << \" score:\" << merged_cluster->score << endl;\n }\n};\n\ntemplate \nstruct TreeBuildingClusterer\n{\n typedef DataIt data_it;\n typedef Scorer scorer_t;\n typedef ClusterTraits traits_t;\n\n typedef std::pair vertex_property;\n typedef boost::adjacency_list<\n boost::listS,\n boost::vecS,\n boost::directedS,\n vertex_property,\n typename Scorer::score_t> tree_t;\n typedef typename boost::graph_traits::vertex_iterator tree_vertex_it;\n typedef typename boost::graph_traits::vertex_descriptor tree_vertex;\n tree_t tree;\n\n /** A map from clusters to tree nodes. */\n typedef std::map cluster_vertex_map_t;\n cluster_vertex_map_t cluster_vertex_map;\n\n LoggingClusterer logger;\n bool logging_on;\n\n TreeBuildingClusterer(bool logging_on = false) : logger(std::cout), logging_on(logging_on)\n {\n }\n\n void\n reset()\n {\n cluster_vertex_map.clear();\n tree.clear();\n }\n\n void\n operator()(\n typename traits_t::cluster_it cluster)\n {\n using namespace std;\n using namespace boost;\n\n if (logging_on)\n {\n logger(cluster);\n }\n\n cluster_vertex_map[&*cluster] = add_vertex(make_pair(true, *cluster->data_set.begin()), tree);\n }\n\n void\n operator()(\n typename traits_t::cluster_it cluster_1,\n typename traits_t::cluster_it cluster_2,\n typename traits_t::cluster_it merged_cluster)\n {\n using namespace std;\n using namespace boost;\n\n if (logging_on)\n {\n logger(cluster_1, cluster_2, merged_cluster);\n }\n\n //find the vertex descriptors for cluster_1 and cluster_2\n assert(cluster_vertex_map.end() != cluster_vertex_map.find(&*cluster_1));\n assert(cluster_vertex_map.end() != cluster_vertex_map.find(&*cluster_2));\n\n cluster_vertex_map[&*merged_cluster] = add_vertex(make_pair(false, typename traits_t::data_it()), tree);\n\n add_edge(cluster_vertex_map[&*merged_cluster], cluster_vertex_map[&*cluster_1], tree);\n add_edge(cluster_vertex_map[&*merged_cluster], cluster_vertex_map[&*cluster_2], tree);\n }\n};\n\nBIO_NS_END\n\n\n#endif //BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_\n", "meta": {"hexsha": "c9d0e2136e7cdf52e51d0f7101281cf17ef154c0", "size": 17222, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/bio/bayesian_hierarchical_clustering.h", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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++/include/bio/bayesian_hierarchical_clustering.h", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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++/include/bio/bayesian_hierarchical_clustering.h", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "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.3333333333, "max_line_length": 112, "alphanum_fraction": 0.5822204157, "num_tokens": 4253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017535, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.65065938660426}} {"text": "/* randist/bigauss.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/* The Bivariate Gaussian probability distribution is \n\n p(x,y) dxdy = (1/(2 pi sigma_x sigma_y sqrt(c))) \n exp(-((x/sigma_x)^2 + (y/sigma_y)^2 - 2 r (x/sigma_x)(y/sigma_y))/2c) dxdy \n\n where c = 1-r^2\n*/\n\nvoid\ngsl_ran_bivariate_gaussian (const gsl_rng * r, \n double sigma_x, double sigma_y, double rho,\n double *x, double *y)\n{\n double u, v, r2, scale;\n\n do\n {\n /* choose x,y in uniform square (-1,-1) to (+1,+1) */\n\n u = -1 + 2 * gsl_rng_uniform (r);\n v = -1 + 2 * gsl_rng_uniform (r);\n\n /* see if it is in the unit circle */\n r2 = u * u + v * v;\n }\n while (r2 > 1.0 || r2 == 0);\n\n scale = sqrt (-2.0 * log (r2) / r2);\n\n *x = sigma_x * u * scale;\n *y = sigma_y * (rho * u + sqrt(1 - rho*rho) * v) * scale;\n}\n\ndouble\ngsl_ran_bivariate_gaussian_pdf (const double x, const double y, \n const double sigma_x, const double sigma_y,\n const double rho)\n{\n double u = x / sigma_x ;\n double v = y / sigma_y ;\n double c = 1 - rho*rho ;\n double p = (1 / (2 * M_PI * sigma_x * sigma_y * sqrt(c))) \n * exp (-(u * u - 2 * rho * u * v + v * v) / (2 * c));\n return p;\n}\n", "meta": {"hexsha": "c23f401bf0189d8aab30774f168ea7ed70cd9bd4", "size": 2175, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/bigauss.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/bigauss.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/bigauss.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": 30.6338028169, "max_line_length": 81, "alphanum_fraction": 0.6045977011, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6503880953233281}} {"text": "/*\n hyper.c\n*/\n#include \n#include \n#include \n\nstatic double update_hyper(double param, int *vec, int **mat, int nrow, int ncol){\n double numer = 0.0;\n double denom = 0.0;\n int i, j;\n \n for(i = 0;i < nrow;i++)\n for(j = 0;j < ncol;j++)\n numer += gsl_sf_psi((double)mat[i][j] + param);\n numer -= (double)nrow * (double)ncol * gsl_sf_psi(param);\n \n for(i = 0;i < nrow;i++)\n denom += (double)ncol * gsl_sf_psi((double)vec[i] + param * (double)ncol);\n denom -= (double)nrow * (double)ncol * gsl_sf_psi(param * (double)ncol);\n \n return param * numer / denom;\n}\n\nvoid update_alpha(double *alpha, int *n_m, int **n_mz, int ndocs, int nclass){\n double sum_alpha = 0.0;\n double numer = 0.0;\n double denom = 0.0;\n int d, k;\n for(k = 0;k < nclass;k++)\n sum_alpha += alpha[k];\n for(d = 0;d < ndocs;d++)\n denom += gsl_sf_psi((double)n_m[d] + sum_alpha);\n denom -= (double)ndocs * gsl_sf_psi(sum_alpha);\n \n for(k = 0;k < nclass;k++){\n numer = 0.0;\n for(d = 0;d < ndocs;d++)\n numer += gsl_sf_psi((double)n_mz[d][k] + alpha[k]);\n numer -= (double)ndocs * gsl_sf_psi(alpha[k]);\n alpha[k] = alpha[k] * numer / denom;\n }\n}\n\ndouble update_beta(double beta, int *n_z, int **n_zw, int nclass, int nlex){\n double new_beta = update_hyper(beta, n_z, n_zw, nclass, nlex);\n return new_beta;\n}", "meta": {"hexsha": "d11d6da776d3034c53c99cb8fb9a612d06345fb3", "size": 1450, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hyper.c", "max_stars_repo_name": "khigashi1987/mvsLDA", "max_stars_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "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/hyper.c", "max_issues_repo_name": "khigashi1987/mvsLDA", "max_issues_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "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/hyper.c", "max_forks_repo_name": "khigashi1987/mvsLDA", "max_forks_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "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.2083333333, "max_line_length": 82, "alphanum_fraction": 0.5662068966, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6500768109061824}}