{"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../ellipsoid/ellipsoid.h\"\n#include \"../ellipsoid/ellSolv.h\"\n#include \"../sphere/sphere.h\"\n#include \"../sphere/sphSolv.h\"\n#include \"../constants.h\"\n#include \"testFunctions.h\"\n\n//compares ellipsoidal and spherical\n//has ellipsoidal distribution of charges just inside ellipsoidal boundary\n//computes the solution at two point, one inside smallest enclosing sphere where spherical diverges\n//other solution point is outside of sphere and ellipse to compare convergence\n#undef __FUNCT__\n#define __FUNCT__ \"main\"\nPetscErrorCode main(int argc, char **argv)\n{\n PetscErrorCode ierr;\n //semi-axes of ellipsoid\n PetscReal a = 3.0;\n PetscReal b = 2.5;\n PetscReal c = 1.2;\n //sphere radius\n PetscReal sphRad = 3;\n //dielecric permitivities both set to 1\n const PetscReal eps1 = 1.0;\n const PetscReal eps2 = 1.0;\n //charges placed on ellipsoid with sem-axes smaller by epsilon\n PetscReal epsilon = .5;\n //interior charge XYZ and magnitude\n const PetscInt SQRT_NUM_CHARGES = 3;\n Vec chargeXYZ;\n Vec chargeMag;\n //maximum expansion order for test\n const PetscInt MAX_N = 25;\n //solutions vector\n const PetscInt NUM_SOL_PTS = 2;\n Vec ellSolutions[MAX_N], sphSolutions[MAX_N];\n Vec ellError[MAX_N], sphError[MAX_N];\n Vec exactSolution;\n Vec solXYZ;\n //solution point inside of sphere\n PetscReal sol1X = .1;\n PetscReal sol1Y = .1;\n PetscReal sol1Z = 1.5;\n //solution point outside of sphere\n PetscReal sol2X = 2.1;\n PetscReal sol2Y = 2.6;\n PetscReal sol2Z = 1;\n //pointer for accessing petsc vectors\n PetscScalar *vecPt, *vecPt2;\n PetscFunctionBeginUser;\n\n //initialize petsc\n ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr);\n ierr = PetscLogDefaultBegin();CHKERRQ(ierr);\n\n //create, set charge magnitudes to 1\n ierr = VecCreateSeq(PETSC_COMM_SELF, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeMag);CHKERRQ(ierr);\n ierr = VecSet(chargeMag, 1.0);CHKERRQ(ierr);\n\n //create, set charge XYZ values to be on a-eps,b-eps,c-eps ellipsoid\n ierr = VecCreateSeq(PETSC_COMM_SELF, 3*SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeXYZ);CHKERRQ(ierr);\n ierr = VecGetArray(chargeXYZ, &vecPt);CHKERRQ(ierr);\n PetscReal pu, pv;\n for(PetscInt i=0; i=1.\nFor l1ballproj_Condat only:\nwe can have x==y (projection done in place). If x!=y, the arrays x and y must\nnot overlap, as x is used for temporary calculations before y is accessed.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define datatype double /* type of the elements in y */\n\n\n/* Proposed algorithm */\nstatic void l1ballproj_Condat(datatype* y, datatype* x,\nconst unsigned int length, const double a) {\n\tif (a<=0.0) {\n\t\tif (a==0.0) memset(x,0,length*sizeof(datatype));\n\t\treturn;\n\t}\n\tdatatype*\taux = (x==y ? (datatype*)malloc(length*sizeof(datatype)) : x);\n\tint\t\tauxlength=1;\n\tint\t\tauxlengthold=-1;\n\tdouble\ttau=(*aux=(*y>=0.0 ? *y : -*y))-a;\n\tint \ti=1;\n\tfor (; i0.0) {\n\t\t\tif (y[i]>tau) {\n\t\t\t\tif ((tau+=((aux[auxlength]=y[i])-tau)/(auxlength-auxlengthold))\n\t\t\t\t<=y[i]-a) {\n\t\t\t\t\ttau=y[i]-a;\n\t\t\t\t\tauxlengthold=auxlength-1;\n\t\t\t\t}\n\t\t\t\tauxlength++;\n\t\t\t}\n\t\t} else if (y[i]!=0.0) {\n\t\t\tif (-y[i]>tau) {\n\t\t\t\tif ((tau+=((aux[auxlength]=-y[i])-tau)/(auxlength-auxlengthold))\n\t\t\t\t<=aux[auxlength]-a) {\n\t\t\t\t\ttau=aux[auxlength]-a;\n\t\t\t\t\tauxlengthold=auxlength-1;\n\t\t\t\t}\n\t\t\t\tauxlength++;\n\t\t\t}\n\t\t}\n\tif (tau<=0) {\t/* y is in the l1 ball => x=y */\n\t\tif (x!=y) memcpy(x,y,length*sizeof(datatype));\n\t\telse free(aux);\n\t} else {\n\t\tdatatype* aux0=aux;\n\t\tif (auxlengthold>=0) {\n\t\t\tauxlength-=++auxlengthold;\n\t\t\taux+=auxlengthold;\n\t\t\twhile (--auxlengthold>=0)\n\t\t\t\tif (aux0[auxlengthold]>tau)\n\t\t\t\t\ttau+=((*(--aux)=aux0[auxlengthold])-tau)/(++auxlength);\n\t\t}\n\t\tdo {\n\t\t\tauxlengthold=auxlength-1;\n\t\t\tfor (i=auxlength=0; i<=auxlengthold; i++)\n\t\t\t\tif (aux[i]>tau)\n\t\t\t\t\taux[auxlength++]=aux[i];\n\t\t\t\telse\n\t\t\t\t\ttau+=(tau-aux[i])/(auxlengthold-i+auxlength);\n\t\t} while (auxlength<=auxlengthold);\n\t\tfor (i=0; i0.0 ? y[i]-tau : (y[i]+tau<0.0 ? y[i]+tau : 0.0));\n\t\tif (x==y) free(aux0);\n\t}\n}\n\n\n/* function eplb of the package SLEP, implementing the algorithm IBIS of the paper\nJ. Liu and J. Ye. Efficient Euclidean Projections in Linear Time, ICML 2009.\nVersion without the initial guess lambda0 of lambda (tau in our notations) */\nstatic void l1ballproj_IBIS(datatype* y, datatype* x,\nconst unsigned int length, const double a) {\n #define delta 1e-13\n int i, j, flag=0;\n int rho_1, rho_2, rho, rho_T, rho_S;\n int V_i_b, V_i_e, V_i;\n double lambda_1, lambda_2, lambda_T, lambda_S, lambda;\n double s_1, s_2, s, s_T, s_S, y_max, temp;\n double f_lambda_1, f_lambda_2, f_lambda, f_lambda_T, f_lambda_S;\n int iter_step=0;\n\n /* find the maximal absolute value in y\n * and copy the (absolute) values from y to x\n */\n\n\t/*if (a< 0){\n\t\tprintf(\"\\n a should be nonnegative!\");\n\t\treturn;\n\t}*/\n\n V_i=0;\n if (y[0] !=0){\n rho_1=1;\n s_1=x[V_i]=y_max=fabs(y[0]);\n V_i++;\n }\n else{\n rho_1=0;\n s_1=y_max=0;\n }\n\n for (i=1;i y_max)\n y_max=x[V_i];\n V_i++;\n }\n }\n\n /* If ||y||_1 <= a, then y is the solution */\n if (s_1 <= a){\n flag=1; lambda=0;\n for(i=0;i lambda_1) ){\n i=V_i_b; j=V_i_e; rho=0; s=0;\n while (i <= j){\n while( (i <= V_i_e) && (x[i] <= lambda) ){\n i++;\n }\n while( (j>=V_i_b) && (x[j] > lambda) ){\n s+=x[j];\n j--;\n }\n if (i\tlambda_T)\n lambda_T=lambda_2 + f_lambda_2 /rho_2;\n }\n\n /* compute lambda_S */\n lambda_S=lambda_2 - f_lambda_2 *(lambda_2-lambda_1)/(f_lambda_2-f_lambda_1);\n\n if (fabs(lambda_T-lambda_S) <= delta){\n lambda=lambda_T; flag=1;\n break;\n }\n\n /* set lambda as the middle point of lambda_T and lambda_S */\n lambda=(lambda_T+lambda_S)/2;\n\n s_T=s_S=s=0;\n rho_T=rho_S=rho=0;\n i=V_i_b; j=V_i_e;\n while (i <= j){\n while( (i <= V_i_e) && (x[i] <= lambda) ){\n if (x[i]> lambda_T){\n s_T+=x[i]; rho_T++;\n }\n i++;\n }\n while( (j>=V_i_b) && (x[j] > lambda) ){\n if (x[j] > lambda_S){\n s_S+=x[j]; rho_S++;\n }\n else{\n s+=x[j]; rho++;\n }\n j--;\n }\n if (i lambda_S){\n s_S+=x[i]; rho_S++;\n }\n else{\n s+=x[i]; rho++;\n }\n\n if (x[j]> lambda_T){\n s_T+=x[j]; rho_T++;\n }\n\n temp=x[i]; x[i]=x[j]; x[j]=temp;\n i++; j--;\n }\n\t\t}\n\n s_S+=s_2; rho_S+=rho_2;\n s+=s_S; rho+=rho_S;\n s_T+=s; rho_T+=rho;\n f_lambda_S=s_S-rho_S*lambda_S-a;\n f_lambda=s-rho*lambda-a;\n f_lambda_T=s_T-rho_T*lambda_T-a;\n\n /*printf(\"\\n %d & %d & %5.6f & %5.6f & %5.6f & %5.6f & %5.6f \\\\\\\\ \\n \\\\hline \", iter_step, V_i, lambda_1, lambda_T, lambda, lambda_S, lambda_2);*/\n\n if ( fabs(f_lambda)< delta ){\n /*printf(\"\\n lambda\");*/\n flag=1;\n break;\n }\n if ( fabs(f_lambda_S)< delta ){\n /* printf(\"\\n lambda_S\");*/\n lambda=lambda_S; flag=1;\n break;\n }\n if ( fabs(f_lambda_T)< delta ){\n /* printf(\"\\n lambda_T\");*/\n lambda=lambda_T; flag=1;\n break;\n }\n\n /*\n printf(\"\\n\\n f_lambda_1=%5.6f, f_lambda_2=%5.6f, f_lambda=%5.6f\",f_lambda_1,f_lambda_2, f_lambda);\n printf(\"\\n lambda_1=%5.6f, lambda_2=%5.6f, lambda=%5.6f\",lambda_1, lambda_2, lambda);\n printf(\"\\n rho_1=%d, rho_2=%d, rho=%d \",rho_1, rho_2, rho);\n */\n\n if (f_lambda <0){\n lambda_2=lambda; s_2=s; rho_2=rho;\n f_lambda_2=f_lambda;\n\n lambda_1=lambda_T; s_1=s_T; rho_1=rho_T;\n f_lambda_1=f_lambda_T;\n\n V_i_e=j; i=V_i_b;\n while (i <= j){\n while( (i <= V_i_e) && (x[i] <= lambda_T) ){\n i++;\n }\n while( (j>=V_i_b) && (x[j] > lambda_T) ){\n j--;\n }\n if (i=V_i_b) && (x[j] > lambda_S) ){\n j--;\n }\n if (i lambda)\n x[i]=y[i]-lambda;\n else\n if (y[i]< -lambda)\n x[i]=y[i]+lambda;\n else\n x[i]=0;\n }\n /**root=lambda;\n *steps=iter_step;*/\n}\n\n\n/* Example of code to compare the computation times\nResult on my machine: my algorithm is 2.5x faster than IBIS */\nint main() {\n\tdatatype*\ty;\n\tdatatype*\tx;\n\tdouble\tval=0.0;\n\tdouble \taux;\n\tdouble \tepsi;\n int \ti,j;\n int \tNbrea;\n unsigned int length;\n clock_t\tstart, end;\n const gsl_rng_type *T;\n \tgsl_rng *r;\n \tgsl_rng_env_setup();\n\tgsl_rng_default_seed=32067;\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\tdouble timemean=0.0, timevar=0.0, timedelta;\n\tconst double a = 1.0;\n\tsrand((unsigned int)pow(time(NULL)%100,3));\n double*\t timetable;\n\n length = 1000000;\n\tNbrea = 100;\n\ty=(datatype*)malloc(length*sizeof(datatype));\n\tx=(datatype*)malloc(length*sizeof(datatype));\n\ttimetable=(double*)malloc((Nbrea+1)*sizeof(double));\n\tfor (j=0; j<=Nbrea; j++) {\n\t\tfor (i=0; i\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nvoid pretty_print(const gsl_matrix * M)\n{\n // Get the dimension of the matrix.\n int rows = M->size1;\n int cols = M->size2;\n // Now print out the data in a square format.\n for(int i = 0; i < rows; i++){\n for(int j = 0; j < cols; j++){\n printf(\"%f \", gsl_matrix_get(M, i, j));\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\nvoid pretty_print_vector(const gsl_vector * M)\n{\n int cols = M->size;\n for(int j = 0; j < cols; j++){\n printf(\"%f \", gsl_vector_get(M, j));\n }\n printf(\"\\n\");\n}\n\nint\nmain()\n{\n const size_t M = 4;\n const size_t N = 5;\n double A_data[] = {\n 1.0, 0.0, 0.0, 0.0, 2.0,\n 0.0, 0.0, 3.0, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0, 0.0,\n 0.0, 2.0, 0.0, 0.0, 0.0 };\n gsl_matrix_view A = gsl_matrix_view_array(A_data, 4, 5);\n gsl_matrix * B = gsl_matrix_alloc(N, M);\n gsl_matrix * V = gsl_matrix_alloc(M, M);\n gsl_vector * S = gsl_vector_alloc(M);\n gsl_vector * work = gsl_vector_alloc(M);\n\n gsl_matrix_transpose_memcpy(B, &A.matrix);\n\n gsl_linalg_SV_decomp(B, V, S, work);\n\n printf(\"U:\\n\");\n pretty_print(V);\n\n printf(\"S:\\n\");\n pretty_print_vector(S);\n\n printf(\"V:\\n\");\n pretty_print(B);\n\n gsl_matrix_free(B);\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n\n return 0;\n}", "meta": {"hexsha": "35e7b665e73355d5fefecbab536c95339e08393c", "size": 1516, "ext": "c", "lang": "C", "max_stars_repo_path": "07-lib/gsl/svd1.c", "max_stars_repo_name": "al2698/sp", "max_stars_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "07-lib/gsl/svd1.c", "max_issues_repo_name": "al2698/sp", "max_issues_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "07-lib/gsl/svd1.c", "max_forks_repo_name": "al2698/sp", "max_forks_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6571428571, "max_line_length": 99, "alphanum_fraction": 0.6147757256, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6481432046467678}} {"text": "/* gsl_histogram_stat.c\n * Copyright (C) 2000 Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this library; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram_stat.c: \n * Routines for statisticalcomputations on histograms. \n * Need GSL library and header.\n * Contains the routines:\n * gsl_histogram_mean compute histogram mean\n * gsl_histogram_sigma compute histogram sigma\n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include \n#include \n#include \n#include \n#include \n\n/* FIXME: We skip negative values in the histogram h->bin[i] < 0,\n since those correspond to negative weights (BJG) */\n\ndouble\ngsl_histogram_mean (const gsl_histogram * h)\n{\n const size_t n = h->n;\n size_t i;\n\n /* Compute the bin-weighted arithmetic mean M of a histogram using the\n recurrence relation\n\n M(n) = M(n-1) + (x[n] - M(n-1)) (w(n)/(W(n-1) + w(n))) \n W(n) = W(n-1) + w(n)\n\n */\n\n long double wmean = 0;\n long double W = 0;\n\n for (i = 0; i < n; i++)\n {\n double xi = (h->range[i + 1] + h->range[i]) / 2;\n double wi = h->bin[i];\n\n if (wi > 0)\n {\n W += wi;\n wmean += (xi - wmean) * (wi / W);\n }\n }\n\n return wmean;\n}\n\ndouble\ngsl_histogram_sigma (const gsl_histogram * h)\n{\n const size_t n = h->n;\n size_t i;\n\n long double wvariance = 0 ;\n long double wmean = 0;\n long double W = 0;\n\n /* Use a two-pass algorithm for stability. Could also use a single\n pass formula, as given in N.J.Higham 'Accuracy and Stability of\n Numerical Methods', p.12 */\n\n /* Compute the mean */\n\n for (i = 0; i < n; i++)\n {\n double xi = (h->range[i + 1] + h->range[i]) / 2;\n double wi = h->bin[i];\n\n if (wi > 0)\n {\n W += wi;\n wmean += (xi - wmean) * (wi / W);\n }\n }\n\n /* Compute the variance */\n\n W = 0.0;\n\n for (i = 0; i < n; i++)\n {\n double xi = ((h->range[i + 1]) + (h->range[i])) / 2;\n double wi = h->bin[i];\n\n if (wi > 0) {\n const long double delta = (xi - wmean);\n W += wi ;\n wvariance += (delta * delta - wvariance) * (wi / W);\n }\n }\n\n {\n double sigma = sqrt (wvariance) ;\n return sigma;\n }\n}\n\n\n/*\n sum up all bins of histogram\n */\n\ndouble \ngsl_histogram_sum(const gsl_histogram * h)\n{\n double sum=0;\n size_t i=0;\n size_t n;\n n=h->n;\n\n while(i < n)\n sum += h->bin[i++];\n\n return sum;\n}\n\n", "meta": {"hexsha": "eab0218fb3de0581c149f4283811c4e1acc1ca41", "size": 3211, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/histogram/stat.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/stat.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/stat.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.7730496454, "max_line_length": 74, "alphanum_fraction": 0.5724073497, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6470129608123922}} {"text": "//\n// Created by Harold on 2020/10/7.\n//\n\n#ifndef M_MATH_M_HIST_H\n#define M_MATH_M_HIST_H\n\n#include \n#include \n#include \n#include \n\nnamespace M_MATH {\n template\n class Histogram1D {\n public:\n // [min, max), it: \n template\n Histogram1D(IT begin, IT end, T min, T max, size_t N);\n ~Histogram1D() { gsl_histogram_free(h); gsl_histogram_pdf_free(p); };\n // counts in every bin\n std::vector counts();\n // bins with [lower, upper] boundaries\n std::vector> bins();\n // probability distribution, r in [0, 1]\n double pdf_sample(double r);\n // standard deviation of the histogrammed variable\n double sigma() { return gsl_histogram_sigma(h); }\n // mean of the histogrammed variable\n double mean() { return gsl_histogram_mean(h); }\n // sum of all bin values\n double sum() { return gsl_histogram_sum(h); }\n // find x in which bin\n size_t find(double x) { size_t idx; gsl_histogram_find(h, x, &idx); return idx; }\n\n private:\n gsl_histogram *h;\n gsl_histogram_pdf *p;\n };\n\n template\n class Histogram2D {\n public:\n // [min, max), it: \n template\n Histogram2D(IT begin, IT end, T xmin, T xmax, T ymin, T ymax, size_t xdim, size_t ydim);\n ~Histogram2D() { gsl_histogram2d_free(h); gsl_histogram2d_pdf_free(p); };\n // counts in every bin\n std::vector counts();\n // bins with [lower, upper] boundaries, \n std::pair>, std::vector>> bins();\n // probability distribution , r1, r2 in [0, 1]\n std::pair pdf_sample(double r1, double r2);\n // standard deviation of the histogrammed x and y variables\n std::pair sigma() { return std::make_pair(gsl_histogram2d_xsigma(h), gsl_histogram2d_ysigma(h)); }\n // mean of the histogrammed x and y variables\n std::pair mean() { return std::make_pair(gsl_histogram2d_xmean(h), gsl_histogram2d_ymean(h)); }\n // sum of all bin values\n double sum() { return gsl_histogram2d_sum(h); }\n // covariance of the histogrammed x and y variables\n double cov() { return gsl_histogram2d_cov(h); }\n // find x in which bin, \n std::pair find(double x, double y) { size_t xidx, yidx; gsl_histogram2d_find(h, x, y, &xidx, &yidx); return std::make_pair(xidx, yidx); }\n private:\n gsl_histogram2d *h;\n gsl_histogram2d_pdf *p;\n };\n\n template\n template\n Histogram1D::Histogram1D(IT const begin, IT const end, T min, T max, size_t N) : h(nullptr), p(nullptr) {\n h = gsl_histogram_alloc(N);\n gsl_histogram_set_ranges_uniform(h, min, max);\n for (auto it = begin; it != end; ++it)\n gsl_histogram_increment(h, *it);\n }\n\n template\n std::vector Histogram1D::counts() {\n std::vector res(h->n);\n for (auto i = 0; i < h->n; ++i)\n res[i] = gsl_histogram_get(h, i);\n return res;\n }\n\n template\n std::vector> Histogram1D::bins() {\n std::vector> res(h->n);\n double lower, upper;\n for (auto i = 0; i < h->n; ++i) {\n gsl_histogram_get_range(h, i, &lower, &upper);\n res[i] = std::make_pair(lower, upper);\n }\n return res;\n }\n\n template\n double Histogram1D::pdf_sample(double r) {\n if (p == nullptr) {\n p = gsl_histogram_pdf_alloc(h->n);\n gsl_histogram_pdf_init(p, h);\n }\n return gsl_histogram_pdf_sample(p, r);\n }\n\n template\n template\n Histogram2D::Histogram2D(IT begin, IT end,\n T xmin, T xmax,\n T ymin, T ymax,\n size_t xdim, size_t ydim) : h(nullptr), p(nullptr) {\n h = gsl_histogram2d_alloc(xdim, ydim);\n gsl_histogram2d_set_ranges_uniform(h, xmin, xmax, ymin, ymax);\n for (auto it = begin; it != end; ++it)\n gsl_histogram2d_increment(h, (*it).x, (*it).y);\n }\n\n template\n std::vector Histogram2D::counts() {\n std::vector res((h->nx) * (h->ny));\n for (auto i = 0; i < h->nx; ++i)\n for (auto j = 0; j < h->ny; ++j)\n res[j * (h->nx) + i] = gsl_histogram2d_get(h, i, j);\n return res;\n }\n\n template\n std::pair>, std::vector>> Histogram2D::bins() {\n std::vector> xrange(h->nx), yrange(h->ny);\n double lower, upper;\n for (auto i = 0; i < h->nx; ++i) {\n gsl_histogram2d_get_xrange(h, i, &lower, &upper);\n xrange[i] = std::make_pair(lower, upper);\n }\n for (auto i = 0; i < h->ny; ++i) {\n gsl_histogram2d_get_yrange(h, i, &lower, &upper);\n yrange[i] = std::make_pair(lower, upper);\n }\n return std::make_pair(xrange, yrange);\n }\n\n template\n std::pair Histogram2D::pdf_sample(double r1, double r2) {\n if (p == nullptr) {\n p = gsl_histogram2d_pdf_alloc(h->nx, h->ny);\n gsl_histogram2d_pdf_init(p, h);\n }\n double x, y;\n gsl_histogram2d_pdf_sample(p, r1, r2, &x, &y);\n return std::make_pair(x, y);\n }\n}\n\n#endif //M_MATH_M_HIST_H\n", "meta": {"hexsha": "230cd969a6ac33eaa0861e870a66f7f73909f339", "size": 5746, "ext": "h", "lang": "C", "max_stars_repo_path": "include/m_hist.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_hist.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_hist.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": 37.0709677419, "max_line_length": 161, "alphanum_fraction": 0.5730943265, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6469945816618062}} {"text": "#include \n#include \n\ndouble A[] =\n{\n -1.0, 0.0, 2.0, 1.0,\n 0.0, -1.0, 3.0, 2.0,\n 1.0, 2.0, 3.0, 0.0,\n -3.0, 1.0, 4.0, 2.0\n};\n\ndouble y[] = { 0.0, 1.0, 2.0, 1.0 };\n\nint main() {\n gsl_matrix_view m = gsl_matrix_view_array(A, 4, 4);\n gsl_vector_view b = gsl_vector_view_array(y, 4);\n gsl_vector* x = gsl_vector_alloc(4);\n\n int s;\n gsl_permutation* p = gsl_permutation_alloc(4);\n gsl_linalg_LU_decomp(&m.matrix, p, &s);\n gsl_linalg_LU_solve(&m.matrix, p, &b.vector, x);\n\n printf(\"x = \\n\");\n gsl_vector_fprintf(stdout, x, \"%5.1f\");\n\n gsl_permutation_free(p);\n gsl_vector_free(x);\n return 0;\n}\n", "meta": {"hexsha": "f466e06136b6eb53c937e32ddafe8500c5ad2c5e", "size": 631, "ext": "c", "lang": "C", "max_stars_repo_path": "src_book0/ex10/list1032/list1032B.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/list1032B.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/list1032B.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": 20.3548387097, "max_line_length": 53, "alphanum_fraction": 0.6148969889, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6469347051222029}} {"text": "/**\n* Subroutines for fitting functions to data.\n * Most of the functions are used for the\n * background determination.\n */\n\n#include \n#include \n#include \n#include \n\n#include \"spce_fitting.h\"\n\n\n/**\n * Function: det_vector_polyN\n * A function using GSL fitting functions to fit a set x,y,w of n elements\n * such that an Nth degree polynomial is fitted to the x and y vectors \n * using the weights w. This function avoids NaN values in ys AND elements\n * with an associated weight that is zero.\n *\n * Parameters:\n * @param m - order of the fit \n * @param xs - double vector containing the x values\n * @param ys - double vector containing the y values\n * @param ws - double vector containing the weights associated with ys\n * @param n - number of points in xs,ys, and ws (must be greater than m!)\n * @param c - the vector with the fitted coefficients\n * @param cov - the covariance matrix\n *\n * Returns:\n * @return interp - vector with additional fitting information\n */\ngsl_vector *\ndet_vector_polyN (int m, const double *const xs, double *const ys,\n\t\t double *const ws, const int n, gsl_vector *c,\n\t\t gsl_matrix *cov)\n{\n int i, j, nn, ii;\n double chisq;\n gsl_matrix *X;\n gsl_vector *y, *w;\n \n double *tmp, *xmp;\n double median, xean;\n\n gsl_vector *interp;\n\n // allocate the return vector\n interp = gsl_vector_alloc(5);\n\n // allocate temporary vectors\n tmp = (double *) malloc (n * sizeof (double));\n xmp = (double *) malloc (n * sizeof (double));\n\n\n // fill weights and independent values\n // for the background pixels into the arrays\n nn = 0;\n for (i = 0; i < n; i++)\n {\n if (ws[i] > 0.0)\n\t{\n\t //\t tmp[nn] = ws[i];\n\t tmp[nn] = 1.0/(ws[i]*ws[i]);\n\t xmp[nn] = xs[i];\n\t nn++;\n\t}\n }\n\n // compute the median weight\n // to be used for all pixels\n gsl_sort( tmp, 1, m);\n median = gsl_stats_median_from_sorted_data(tmp, 1, nn);\n\n // determine the anchor point in the\n // independent variable\n xean = gsl_stats_mean (xmp, 1, nn);\n\n // check whether the desired\n // intepolation degree is feasible\n if (nn < m)\n {\n aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n\t\t \"Not enough points (%d) found to perform the %d order fit. Doing %d order instead.\\n\",\n\t\t nn, m, nn);\n m = nn;\n }\n\n // allocate more temporary space\n X = gsl_matrix_alloc (nn, m); \n y = gsl_vector_alloc (nn);\n w = gsl_vector_alloc (nn);\n // c = gsl_vector_alloc (m);\n // cov = gsl_matrix_alloc (m, m);\n \n // transfer independent/dependent and weight\n // values from the background pixels to the\n // temporary arrays\n ii = 0;\n for (i = 0; i < n; i++)\n {\n if (ws[i] > 0.0)\n\t{\n\t // shift the x-values\n\t // and store them in the matrix\n\t for (j = 0; j < m; j++)\n\t {\n\t gsl_matrix_set (X, ii, j, pow (xs[i] - xean, j));\n\t }\n\t gsl_vector_set (y, ii, ys[i]);\n\t gsl_vector_set (w, ii, median);\n\t ii++;\n\t}\n \n }\n\n // allocate space and do the fit; release the space\n gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc (nn, m);\n gsl_multifit_wlinear (X, w, y, c, cov, &chisq, work);\n gsl_multifit_linear_free (work);\n\n\n // release memory\n gsl_matrix_free (X); \n gsl_vector_free (y);\n gsl_vector_free (w);\n\n // free the tmp-arrays\n free(tmp);\n free(xmp);\n\n // fill the mean x-value\n // and the order into the return vector\n gsl_vector_set(interp, 0, xean);\n gsl_vector_set(interp, 1, (double)m);\n \n\n return interp;\n}\n\n/**\n * Function: fill_polyN_interp\n * Evaluates a polynomial of any order and fills the\n * result plus the error, compute using the covariance\n * matrix, in vectors.\n *\n * Parameters:\n * @param xs - double vector containing the x values\n * @param ys - double vector containing the y values\n * @param yi - double vector containing the intermediate y-values\n * @param ws - double vector containing the weights associated with ys\n * @param n - number of points in xs,ys, and ws (must be greater than m!)\n * @param c - the vector with the fitted coefficients\n * @param cov - the covariance matrix\n * @param interp - additional fitting ifnormation\n * @param final - flagg to indicate final fit and\n * therefore a replacement\n */\nvoid\nfill_polyN_interp(const double *const xs, double *const ys,\n\t\t double *const ws, double *yi, const int n,\n\t\t gsl_vector *coeffs, gsl_matrix *cov,\n\t\t gsl_vector *interp, const int final)\n{\n int i, j, m;\n double xf, yf, sq_yf_err, yf_err;\n double xean;\n\n // get the mean x-value and\n // polynomial order from the vector\n xean = gsl_vector_get(interp, 0);\n m = (int)gsl_vector_get(interp, 1);\n\n // put the interpolated values\n // for object pixels back into the\n // inut arrays\n for (i = 0; i < n; i++)\n {\n\n // compute and store interpolated\n // values an corresponding error\n xf = xs[i]-xean;\n yf = 0.0;\n yf_err = 0.0;\n sq_yf_err = 0.0;\n \n // compute the polynimials\n for (j = 0; j < m; j++)\n\t{\n\t // first compute the y-value\n\t yf += gsl_vector_get(coeffs,j)*pow (xf, j);\n\n\t // compute the associated error\n\t sq_yf_err += gsl_matrix_get(cov,j,j) * pow (xf, j) * pow (xf, j);\n\t}\n\n // put the intepolated value in the intermediate vector\n yi[i] = yf;\n\n // if requested, fill the interpolated values\n // into the origina; arrays\n if (final && ws[i] == 0.0)\n\t{\n\t ys[i] = yf;\n\t ws[i] = sqrt(sq_yf_err);\n\t}\n }\n}\n\n\n\n\n/**\n * Function: comp_vector_average\n * The function provides the computation of the average of\n * the y-values and store that average in temporary\n * or the original y-vector.\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param yi - temprary y-values\n * @param n - number of points in xs, ys, ws\n * @param final - flagg to store to temp (0) or final (1) vectors\n */\nvoid\ncomp_vector_average (const double *xs, double *ys,\n\t\t double *ws, double *yi, const int n, const int final)\n{\n double ave, std;\n //int i, m;\n\n det_vector_average (xs, ys, ws, n, &ave, &std);\n fill_const_value(ys, ws, yi, n, ave, std, final);\n}\n\n\n/**\n * Function: comp_vector_median\n * The function provides the computation of the median of\n * the y-values and store that median in temporary\n * or the original y-vector\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param yi - temprary y-values\n * @param n - number of points in xs, ys, ws\n * @param final - flagg to store to temp (0) or final (1) vectors\n */\nvoid\ncomp_vector_median (const double *xs, double *ys,\n\t\t double *ws, double *yi, const int n, const int final)\n{\n double med, std;\n\n det_vector_median (xs, ys, ws, n, &med, &std);\n fill_const_value(ys, ws, yi, n, med, std, final);\n\n}\n\n/**\n * Function: comp_vector_linear\n * The function fits a linear function to the y-values\n * and fills the linear inteprolated values in a temporary\n * vector and, if requested, in the original vector as well.\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param yi - temprary y-values\n * @param n - number of points in xs, ys, ws \n * @param final - flagg to store to temp (0) or final (1) vectors\n */\nvoid\ncomp_vector_linear (const double *xs, double *ys,\n\t\t double *ws, double *yi, const int n, const int final)\n{\n gsl_vector *interp;\n\n // make a weighted linear fit\n interp = det_vector_linear(xs, ys, ws, n, 1);\n\n // make the interpolations,\n // using the linear fit\n fill_linear_interp(xs, ys, ws, yi, n, interp, final);\n\n gsl_vector_free(interp);\n}\n\n/**\n * Function: comp_vector_polyN\n * The function fits a polynomial function to the y-values\n * and fills the evaluated polynomial values in a temporary\n * vector and, if requested, in the original vector as well.\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param yi - temprary y-values\n * @param n - number of points in xs, ys, ws\n * @param final - flagg to store to temp (0) or final (1) vectors\n */\nvoid\ncomp_vector_polyN (const int m, const double *xs, double *ys,\n\t\t double *ws, double *yi, const int n, const int final)\n{\n gsl_vector *interp, *coeffs;\n gsl_matrix *cov;\n\n coeffs = gsl_vector_alloc(m);\n cov = gsl_matrix_alloc(m,m);\n\n interp = det_vector_polyN (m, xs, ys, ws, n, coeffs, cov);\n fill_polyN_interp(xs, ys, ws, yi, n, coeffs, cov, interp, final);\n\n gsl_vector_free(interp);\n gsl_vector_free(coeffs);\n gsl_matrix_free(cov);\n}\n\n/**\n * Function: det_vector_linear\n * Performs a linear fit of the xs, ys, and ws arrays.\n * Ignores NaN values. Fitted values are returned in\n * ys and errors in ws.\n *\n * Parameters:\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - error in ys[]\n * @param n - number of points in xs, ys, ws\n * @param weight - make weighted fit (=1) or not (=0)\n *\n * Returns:\n * @return ret - the covariance values\n */\ngsl_vector *\ndet_vector_linear(const double *xs, double *ys, double *ws,\n\t\t const int n, const int weight)\n{\n int i, m;\n double c0, c1, cov00, cov01, cov11, chisq;\n double *xx, *yy, *ww, *tmp, *xmp;\n double median, xean;\n //double xf, yf, yf_err;\n\n gsl_vector *ret;\n\n ret = gsl_vector_alloc(10);\n\n // allocate space for temporary vectors \n tmp = (double *) malloc (n * sizeof (double));\n xmp = (double *) malloc (n * sizeof (double));\n\n // fill the temporary vectors \n // with background values and weights\n m = 0;\n for (i = 0; i < n; i++)\n {\n if (ws[i] > 0.0)\n\t{\n\t //\t tmp[m] = ws[i];\n\t tmp[m] = 1.0/(ws[i]*ws[i]);\n\t xmp[m] = xs[i];\n\t m++;\n\t}\n }\n\n\n // determine the median weight which\n // is used for all data\n gsl_sort( tmp, 1, m);\n median = gsl_stats_median_from_sorted_data(tmp, 1, m);\n\n // determine the mean in the independent variable\n xean = gsl_stats_mean (xmp, 1, m);\n\n // allocate more temporary vectors\n xx = (double *) malloc (m * sizeof (double));\n yy = (double *) malloc (m * sizeof (double));\n ww = (double *) malloc (m * sizeof (double));\n\n // fill the temporary vectors with\n // background independent/dependent variables\n // plus the weight\n m = 0;\n for (i = 0; i < n; i++)\n {\n if (ws[i] > 0.0)\n\t{\n\t xx[m] = xs[i]-xean;\n\t yy[m] = ys[i];\n\t ww[m] = median;\n\t m++;\n\t}\n }\n\n // check for weighted fit\n if (weight)\n // doe the linear fit\n gsl_fit_wlinear (xx, 1, ww, 1, yy, 1, m, &c0, &c1, &cov00,\n\t\t &cov01, &cov11, &chisq);\n else\n // does the linear fit\n gsl_fit_linear (xx, 1, yy, 1, m, &c0, &c1, &cov00,\n\t\t &cov01, &cov11, &chisq);\n\n\n gsl_vector_set(ret, 0, xean);\n gsl_vector_set(ret, 1, c0);\n gsl_vector_set(ret, 2, c1);\n gsl_vector_set(ret, 3, cov00);\n gsl_vector_set(ret, 4, cov01);\n gsl_vector_set(ret, 5, cov11);\n gsl_vector_set(ret, 6, chisq);\n\n\n // free the arrays\n free(tmp);\n free(xmp);\n free(xx);\n free(yy);\n free(ww);\n\n return ret;\n}\n\n/**\n * Function: fill_linear_interp\n * The function computes and stores linear interpolated values\n * in one or several output vectors.\n *\n * Parameters:\n * @param xs - double vector containing the x values\n * @param ys - double vector containing the y values\n * @param ws - double vector containing the weights associated with ys\n * @param yi - double vector containing the intermediate y-values\n * @param n - number of points in xs,ys, and ws (must be greater than m!)\n * @param interp - vector with the fitted values\n * @param final - flagg to indicate final fit and\n * therefore a replacement\n */\nvoid\nfill_linear_interp(const double *const xs, double *const ys, double *const ws,\n\t\t double *yi, const int n, gsl_vector *interp,\n\t\t const int final)\n{\n double c0, c1, cov00, cov01, cov11, xean;\n double xf, yf, yf_err;\n int i;\n\n xean = gsl_vector_get(interp, 0);\n c0 = gsl_vector_get(interp, 1);\n c1 = gsl_vector_get(interp, 2);\n cov00 = gsl_vector_get(interp, 3);\n cov01 = gsl_vector_get(interp, 4);\n cov11 = gsl_vector_get(interp, 5);\n\n // determine the interpolated values\n // and store them in the input arrays\n for (i = 0; i < n; i++)\n {\n\n xf = xs[i]-xean;\n gsl_fit_linear_est (xf, c0, c1, cov00, cov01, cov11, &yf, &yf_err);\n yi[i] = yf;\n\n // for object pixels,\n // fill in the interpolated values\n if (final && ws[i] == 0.0)\n\t{\n\t ys[i] = yf;\n\t ws[i] = yf_err;\n\t}\n }\n}\n\n\n/**\n * Function: det_vector_average\n * The function computes the average and the standard\n * deviation from the values in a vector\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param n - number of points in xs, ys, ws\n * @param avg - the average\n * @param std - the standard deviation\n */\nvoid\ndet_vector_average (const double *xs, double *ys,\n\t\t double *ws, const int n, double *avg, double *std)\n{\n double *tmp, sum = 0.0;\n int nn = 0;\n int j;\n\n // count the number of\n // interpolation points\n nn = 0;\n for (j = 0; j < n; j++)\n {\n if (ws[j] != 0.0)\n\tnn++;\n }\n\n // allocate a tmp-array\n tmp = malloc (nn * sizeof (double));\n\n // sum up all values in the\n // interpolation points,\n // and transfer the values to the \n // tmp-array\n nn = 0;\n for (j = 0; j < n; j++)\n {\n if (ws[j] != 0.0)\n\t{\n\t sum += ys[j];\n\t tmp[nn] = ys[j];\n\t nn++;\n\t}\n }\n\n // compute the average\n if (nn > 0)\n *avg = sum / (double)nn;\n\n // compute the standard deviation\n *std = gsl_stats_sd (tmp, 1, nn);\n}\n\n/**\n * Function: det_vector_median\n * The function computes the median and the standard\n * deviation from the values in a vector\n *\n * @param xs - absissa\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param n - number of points in xs, ys, ws\n * @param med - the median\n * @param std - the standard deviation\n */\nvoid\ndet_vector_median (const double *xs, double *ys,\n\t\t double *ws, const int n, double *med, double *std)\n{\n double *tmp;\n int nn = 0;\n int j;\n\n // count the number of\n // interpolation points\n for (j = 0; j < n; j++)\n {\n if (ws[j] != 0.0)\n\t nn++;\n }\n\n // allocate a tmp-array\n tmp = malloc (nn * sizeof (double));\n\n // transfer the values of the interpolation\n // points to the tmp-array\n nn = 0;\n for (j = 0; j < n; j++)\n {\n if (ws[j] != 0.0)\n\t{\n\t tmp[nn] = ys[j];\n\t nn++;\n\t}\n }\n\n // sort the tmp array\n gsl_sort (tmp, 1, nn);\n\n // compute the median\n *med = gsl_stats_median_from_sorted_data (tmp, 1, nn);\n\n // compute the standard deviation\n *std = gsl_stats_sd (tmp, 1, nn);\n}\n\n/**\n * Function:fill_const_value\n * The function fills two constant values into\n * up to three vectors.\n *\n * @param ys - value at xs[]\n * @param ws - weight in ys[]\n * @param yi - value at xs[]\n * @param n - number of points in xs, ys, ws\n * @param cval - number of points in xs, ys, ws\n * @param stdev - number of points in xs, ys, ws\n * @param final - flagg which indicates which vectors to fill\n */\nvoid\nfill_const_value(double *ys, double *ws, double *yi, const int n,\n\t\t double cval, double stdev, const int final)\n{\n\n int j;\n int m=0;\n\n // fill the constant value and the stdev\n // in the whole value and error\n // arrays, respectively\n for (j = 0; j < n; j++)\n {\n yi[j] = cval;\n\n if (final && ws[j] == 0.0)\n\t{\n\t ys[j] = cval;\n\t ws[j] = stdev;\n\t m++;\n\t}\n }\n}\n", "meta": {"hexsha": "3bc7c0812ccb66083ccd37836574c0ab4b200880", "size": 15374, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spce_fitting.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spce_fitting.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spce_fitting.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5984, "max_line_length": 92, "alphanum_fraction": 0.6230649148, "num_tokens": 4658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6468391814763169}} {"text": "/* roots/test_funcs.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"test.h\"\n\ngsl_function create_function (double (*f)(double, void *)) \n{\n gsl_function F ;\n F.function = f;\n F.params = 0;\n return F ;\n}\n\ngsl_function_fdf create_fdf (double (*f)(double, void *),\n double (*df)(double, void *),\n void (*fdf)(double, void *, double *, double *))\n{\n gsl_function_fdf FDF ;\n FDF.f = f ;\n FDF.df = df ;\n FDF.fdf = fdf ;\n FDF.params = 0 ;\n return FDF ;\n}\n\n/* f(x) = x^{20} - 1 */\n/* f'(x) = 20x^{19} */\n/* zero at x = 1 or -1 */\n\ndouble\nfunc1 (double x, void *p)\n{\n return pow (x, 20.0) - 1;\n}\n\ndouble\nfunc1_df (double x, void * p)\n{\n return 20.0 * pow (x, 19.0);\n}\n\nvoid\nfunc1_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func1 (x, p);\n *yprime = 20.0 * pow (x, 19.0);\n}\n\n/* f(x) = sqrt(abs(x))*sgn(x) */\n/* f'(x) = 1 / sqrt(abs(x) */\n/* zero at x = 0 */\ndouble\nfunc2 (double x, void * p)\n{\n double delta;\n\n if (x > 0)\n delta = 1.0;\n else if (x < 0)\n delta = -1.0;\n else\n delta = 0.0;\n\n return sqrt (fabs (x)) * delta;\n}\n\ndouble\nfunc2_df (double x, void * p)\n{\n return 1 / sqrt (fabs (x));\n}\n\nvoid\nfunc2_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func2 (x, p);\n *yprime = 1 / sqrt (fabs (x));\n}\n\n\n/* f(x) = x^2 - 1e-8 */\n/* f'(x) = 2x */\n/* zero at x = sqrt(1e-8) or -sqrt(1e-8) */\ndouble\nfunc3 (double x, void * p)\n{\n return pow (x, 2.0) - 1e-8;\n}\n\ndouble\nfunc3_df (double x, void * p)\n{\n return 2 * x;\n}\n\nvoid\nfunc3_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func3 (x, p);\n *yprime = 2 * x;\n}\n\n/* f(x) = x exp(-x) */\n/* f'(x) = exp(-x) - x exp(-x) */\n/* zero at x = 0 */\ndouble\nfunc4 (double x, void * p)\n{\n return x * exp (-x);\n}\n\ndouble\nfunc4_df (double x, void * p)\n{\n return exp (-x) - x * exp (-x);\n}\n\nvoid\nfunc4_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func4 (x, p);\n *yprime = exp (-x) - x * exp (-x);\n}\n\n/* f(x) = 1/(1+exp(x)) */\n/* f'(x) = -exp(x) / (1 + exp(x))^2 */\n/* no roots! */\ndouble\nfunc5 (double x, void * p)\n{\n return 1 / (1 + exp (x));\n}\n\ndouble\nfunc5_df (double x, void * p)\n{\n return -exp (x) / pow (1 + exp (x), 2.0);\n}\n\nvoid\nfunc5_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func5 (x, p);\n *yprime = -exp (x) / pow (1 + exp (x), 2.0);\n}\n\n/* f(x) = (x - 1)^7 */\n/* f'(x) = 7 * (x - 1)^6 */\n/* zero at x = 1 */\ndouble\nfunc6 (double x, void * p)\n{\n return pow (x - 1, 7.0);\n}\n\ndouble\nfunc6_df (double x, void * p)\n{\n return 7.0 * pow (x - 1, 6.0);\n}\n\nvoid\nfunc6_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = func6 (x, p);\n *yprime = 7.0 * pow (x - 1, 6.0);\n}\n\n/* sin(x) packaged up nicely. */\ndouble\nsin_f (double x, void * p)\n{\n return sin (x);\n}\n\ndouble\nsin_df (double x, void * p)\n{\n return cos (x);\n}\n\nvoid\nsin_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = sin (x);\n *yprime = cos (x);\n}\n\n/* cos(x) packaged up nicely. */\ndouble\ncos_f (double x, void * p)\n{\n return cos (x);\n}\n\ndouble\ncos_df (double x, void * p)\n{\n return -sin (x);\n}\n\nvoid\ncos_fdf (double x, void * p, double *y, double *yprime)\n{\n *y = cos (x);\n *yprime = -sin (x);\n}\n", "meta": {"hexsha": "9b8f05e05e3eb9b3a8cfa248f72fe4329b8bd0a7", "size": 4072, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/roots/test_funcs.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/roots/test_funcs.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/roots/test_funcs.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": 17.7043478261, "max_line_length": 81, "alphanum_fraction": 0.5672888016, "num_tokens": 1502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.646671441997854}} {"text": "#include \n#include \n#include \n#include \n\ndouble f1(double x, void* params)\n{\n return x*x;\n}\n\ndouble f2(double x, void* params)\n{\n return 1 / sqrt(x);\n}\n\nvoid calculateIntegralVoid(double (*f)(double x), double a, double b, int maxInterval, double expected)\n{\n FILE* output = fopen(\"integral.txt\", \"w\");\n int n = 1;\n while (n < maxInterval)\n {\n double dx = (b - a) / (double)n;\n double sum = 0;\n\n for (int i = 1; i < n; ++i)\n {\n sum += f(a + i * dx);\n }\n sum *= dx;\n fprintf (output,\"%d %f\\n\", n, expected - sum);\n\n n++;\n }\n}\n\nint calculateIntegral(double (*f)(double x), double a, double b, int n, double expected, double error)\n{\n double dx = (b - a) / (double)n;\n double sum = 0;\n\n for (int i = 1; i < n; ++i)\n {\n sum += f(a + i * dx);\n }\n sum *= dx;\n if (fabs(sum - expected) < error)\n {\n printf(\"Sum with error %.1e error for %d samples: %.18f\\n\", error, n, sum);\n return 1;\n }\n printf(\"DIFFERENCE with error %.1e error for %d samples: %.18f\\n\", error, n, fabs(sum - expected));\n return 1;\n}\n\nvoid tryFindIntergral(double (*f)(double x), double a, double b, double expected, double error, int step)\n{\n int interval = step;\n while (!calculateIntegral(f, a, b, interval, expected, error))\n {\n interval += step;\n }\n}\n\nvoid gslIntegral(double (*f)(double x, void* params), double expected)\n{\n gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n\n double result, error;\n double alpha = 1.0;\n\n gsl_function F;\n F.function = f;\n F.params = α\n\n gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000, w, &result, &error);\n\n printf (\"result = % .18f\\n\", result);\n printf (\"exact result = % .18f\\n\", expected);\n printf (\"estimated error = % .18f\\n\", error);\n printf (\"actual error = % .18f\\n\", result - expected);\n printf (\"intervals = %zu\\n\", w->size);\n\n gsl_integration_workspace_free (w);\n}\n\nint main (int argc, char* argv[])\n{\n // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-3, 1000);\n // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-4, 215000000);\n // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-5, 100000);\n // tryFindIntergral(f2, 0, 1.0, 2.0, 1e-6, 1000000);\n\n // calculateIntegralVoid(f2, 0.0, 1.0, 100000, 2.0);\n\n gslIntegral(f2, 2.0);\n return 0;\n}", "meta": {"hexsha": "35a87ece26506ed2e4809cbaef0837c1bf71b064", "size": 2439, "ext": "c", "lang": "C", "max_stars_repo_path": "zad4/calkowanie.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": "zad4/calkowanie.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": "zad4/calkowanie.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": 25.1443298969, "max_line_length": 105, "alphanum_fraction": 0.565395654, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6464473197565723}} {"text": "//\n// Created by chris on 07.05.21.\n//\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n\nclass test {\npublic:\n int n;\n};\n\n/**\n * Calculates autocorrelation with FFT\n * @param vec\n * @return\n *//*\nstd::vector ac(const std::vector &vec){\n std::vector fftReturn=vec;\n\n gsl_fft_real_wavetable *real;\n gsl_fft_halfcomplex_wavetable *hc;\n gsl_fft_real_workspace *work;\n\n //FFT\n work = gsl_fft_real_workspace_alloc(vec.size());\n real = gsl_fft_real_wavetable_alloc(vec.size());\n\n gsl_fft_real_transform(&fftReturn[0], 1, vec.size(), real, work);\n gsl_fft_real_wavetable_free(real);\n\n hc = gsl_fft_halfcomplex_wavetable_alloc(vec.size());\n\n gsl_fft_halfcomplex_inverse(&fftReturn[0], 1, vec.size(), hc, work);\n\n gsl_fft_halfcomplex_wavetable_free(hc);\n return fftReturn;\n}*/\n\n\n/**\n * @tparam T\n * @param vec\n * @return maximum element of given vector\n */\ntemplate\nT max(const std::vector &vec) {\n T maxVal = vec[0];\n for (int i = 1; i < vec.size(); ++i) {\n maxVal = std::max(maxVal, vec[i]);\n }\n return maxVal;\n}\n\n/**\n * @tparam T\n * @param vec\n * @return minimum element of given vector\n */\ntemplate\nT min(const std::vector &vec) {\n T minVal = vec[0];\n for (int i = 1; i < vec.size(); ++i) {\n minVal = std::min(minVal, vec[i]);\n }\n return minVal;\n}\n\n/**\n * Calculates the arithmetic mean of given vector-elements\n * @tparam T\n * @param vec\n * @return the arithmetic mean\n */\ntemplate\nT mean(const std::vector &vec) {\n return std::accumulate(vec.begin(), vec.end(), 0.0)/vec.size();\n}\n\n/**\n * Calculates the arithmetic mean of given vector-of-vector-of-elements\n * @tparam T\n * @param vec vector of vector of elements (tensor of rank 2)\n * @return the arithmetic mean of all values\n */\ntemplate\nT mean(const std::vector> &vec) {\n std::vector firstMeans;\n firstMeans.reserve(vec.size());\n for(auto &i:vec){\n firstMeans.push_back(mean(i));\n }\n return mean(firstMeans);\n}\n\n/**\n * Calculates the standard deviation of given vector-elements\n * @tparam T\n * @param vec\n * @return standard deviation\n */\ntemplate\nT stdev(const std::vector &vec) {\n T summation=0;\n const T vec_mean=mean(vec);\n for (size_t i = 0; i < vec.size(); ++i) {\n summation+=pow(vec[i]-vec_mean,2);\n }\n return sqrt(summation*1.0/(vec.size()-1));\n}\n\n/**\n * Calculates the autocorrelation-function of given data-sample\n * @tparam T\n * @param vec of data-sample with length n\n * @return autocorrelation-function in vector with length n/2\n */\ntemplate\nstd::vector autoCorr(const std::vector &vec) {\n float mean = std::accumulate(vec.begin(), vec.end(), 0.0f) / vec.size();\n\n std::vector autocorrelation(vec.size() / 2);\n for (size_t t = 0; t < autocorrelation.size(); t++) {\n float n = 0; // Numerator\n float d = 0; // Denominator\n for (size_t i = 0; i < vec.size() - t; i++) {\n float xim = vec[i] - mean;\n n += xim * (vec[(i + t) % vec.size()] - mean);\n d += xim * xim;\n }\n autocorrelation[t] = n / d;\n }\n return autocorrelation;\n}\n\n/**\n * normalizes given vector call by reference\n * @tparam T\n * @param vec vector which should be normalized\n */\ntemplate\nvoid normalize(std::vector &vec) {\n const T vec_max = max(vec);\n for (T &i : vec) {\n i /= 1.0 * vec_max;\n }\n}", "meta": {"hexsha": "45ea1cc93268284a480e0600ebb91b68790ca588", "size": 3592, "ext": "h", "lang": "C", "max_stars_repo_path": "Projects/HelloWorld/test.h", "max_stars_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_stars_repo_head_hexsha": "ededd743fe6d8418894ae230a9783c7db114d7e2", "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": "Projects/HelloWorld/test.h", "max_issues_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_issues_repo_head_hexsha": "ededd743fe6d8418894ae230a9783c7db114d7e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-15T12:57:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-15T12:57:24.000Z", "max_forks_repo_path": "Projects/HelloWorld/test.h", "max_forks_repo_name": "Babalion/NumerischeMethodenStatistischenPhysik", "max_forks_repo_head_hexsha": "ededd743fe6d8418894ae230a9783c7db114d7e2", "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.6315789474, "max_line_length": 76, "alphanum_fraction": 0.6258351893, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6450856465686168}} {"text": "#include \n#include \n#include \"kadbg.h\"\n#include \"matrix.h\"\n#include \"kalas.h\"\n\n#define MAX_BUF_SIZE 128*1024*1024\n#define NUM_OF_STEPS 1024\n\n\nvoid test_sgemm( KalasState *state)\n{\n\tint rowA, colA, rowB, colB, rowC, colC;\n\tMatrix *matA = NULL, *matB = NULL, *matC1 = NULL, *matC2 = NULL;\n\tfloat alpha = 1.0, beta = 0.0, e;\n struct timeval t;\n double ts, te;\n\n\tfor ( rowA = NUM_OF_STEPS; rowA <= MAX_BUF_SIZE / NUM_OF_STEPS\n\t\t\t\t\t/ sizeof(float);\n\t\t\t\trowA += NUM_OF_STEPS) {\n\t\tfor ( colA = NUM_OF_STEPS; rowA * colA <= MAX_BUF_SIZE / sizeof(float);\n\t\t\t\t\tcolA += NUM_OF_STEPS) {\n\n\t\t\trowB = colA;\n\t\t\trowC = rowA;\n\t\t\tfor ( colB = NUM_OF_STEPS; rowB * colB <= MAX_BUF_SIZE / sizeof(float);\n\t\t\t\t\t\tcolB += NUM_OF_STEPS) {\n\t\t\t\tcolC = colB;\n\n\t\t\t\tif ( rowC * colC > MAX_BUF_SIZE / sizeof(float)) break;\n\n\t\t\t\tif ( IS_FAILED( ( matA = matrixNew( rowA, colA, colA,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsizeof(float), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matB = matrixNew( rowB, colB, colB,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsizeof(float), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matC1 = matrixNew( rowC, colC, colC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sizeof(float), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matC2 = matrixNew( rowC, colC, colC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sizeof(float), true)) != NULL))\n\t\t\t\t\tbreak;\n\n\t\t\t\tprintf( \"(%d,%d)(%d,%d)=(%d,%d) \",\n\t\t\t\t\t\t\t\trowA, colA, rowB, colB, rowC, colC);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\n\t\t\t\tcblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t\t\t\t\t\t\t\t\t matC1->row, matC1->col, matA->col,\n\t\t\t\t\t\t\t\t\t\t alpha, matA->elm, matA->col,\n\t\t\t\t\t\t\t\t\t\t matB->elm, matB->col, beta,\n\t\t\t\t\t\t\t\t\t\t matC1->elm, matC1->col);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tte = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\tprintf( \"%f s %f GFlops \", (te - ts),\n\t\t\t\t\t\t\t\t(double)rowA * (double)colA * (double)colB * 2.0\n\t\t\t\t\t\t\t\t/ ( te - ts) / 1000000000.0);\n\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\t\n\t\t\t\tkalasSgemm( state, clblasRowMajor, clblasNoTrans, clblasNoTrans,\n\t\t\t\t\t\t\t\t\t\tmatC2->row, matC2->col, matA->col,\n\t\t\t\t\t\t\t\t\t\talpha, matA->elm, matA->ld,\n\t\t\t\t\t\t\t\t\t\tmatB->elm, matB->ld, beta,\n\t\t\t\t\t\t\t\t\t\tmatC2->elm, matC2->ld);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tte = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\tprintf( \"%f s %f GFlops \", (te - ts),\n\t\t\t\t\t\t\t\t(double)rowA * (double)colA * (double)colB * 2.0\n\t\t\t\t\t\t\t\t/ ( te - ts) / 1000000000.0);\n\n\t\t\t\tprintf( \"%e err\", matrixCalcDiff( matC1, matC2));\n\t\t\t\tputchar( '\\n');\n\t\t\t\tmatrixDelete( matA); matA = NULL;\n\t\t\t\tmatrixDelete( matB); matB = NULL;\n\t\t\t\tmatrixDelete( matC1); matC1 = NULL;\n\t\t\t\tmatrixDelete( matC2); matC2 = NULL;\n\t\t\t}\n\t\t}\n }\n}\n\nvoid test_dgemm( KalasState *state)\n{\n\tint rowA, colA, rowB, colB, rowC, colC;\n\tMatrix *matA = NULL, *matB = NULL, *matC1 = NULL, *matC2 = NULL;\n\tdouble alpha = 1.0, beta = 0.0, e;\n struct timeval t;\n double ts, te;\n\n\tfor ( rowA = NUM_OF_STEPS; rowA <= MAX_BUF_SIZE / NUM_OF_STEPS\n\t\t\t\t\t/ sizeof(double);\n\t\t\t\trowA += NUM_OF_STEPS) {\n\t\tfor ( colA = NUM_OF_STEPS; rowA * colA <= MAX_BUF_SIZE / sizeof(double);\n\t\t\t\t\tcolA += NUM_OF_STEPS) {\n\n\t\t\trowB = colA;\n\t\t\trowC = rowA;\n\t\t\tfor ( colB = NUM_OF_STEPS; rowB * colB <= MAX_BUF_SIZE / sizeof(double);\n\t\t\t\t\t\tcolB += NUM_OF_STEPS) {\n\t\t\t\tcolC = colB;\n\n\t\t\t\tif ( rowC * colC > MAX_BUF_SIZE / sizeof(double)) break;\n\n\t\t\t\tif ( IS_FAILED( ( matA = matrixNew( rowA, colA, colA,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsizeof(double), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matB = matrixNew( rowB, colB, colB,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsizeof(double), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matC1 = matrixNew( rowC, colC, colC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sizeof(double), true)) != NULL))\n\t\t\t\t\tbreak;\n\t\t\t\tif ( IS_FAILED( ( matC2 = matrixNew( rowC, colC, colC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t sizeof(double), true)) != NULL))\n\t\t\t\t\tbreak;\n\n\t\t\t\tprintf( \"(%d,%d)(%d,%d)=(%d,%d) \",\n\t\t\t\t\t\t\t\trowA, colA, rowB, colB, rowC, colC);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\n\t\t\t\tcblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t\t\t\t\t\t\t\t\t matC1->row, matC1->col, matA->col,\n\t\t\t\t\t\t\t\t\t\t alpha, matA->elm, matA->col,\n\t\t\t\t\t\t\t\t\t\t matB->elm, matB->col, beta,\n\t\t\t\t\t\t\t\t\t\t matC1->elm, matC1->col);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tte = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\tprintf( \"%f s %f GFlops \", (te - ts),\n\t\t\t\t\t\t\t\t(double)rowA * (double)colA * (double)colB * 2.0\n\t\t\t\t\t\t\t\t/ ( te - ts) / 1000000000.0);\n\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\t\n\t\t\t\tkalasDgemm( state, clblasRowMajor, clblasNoTrans, clblasNoTrans,\n\t\t\t\t\t\t\t\t\t\tmatC2->row, matC2->col, matA->col,\n\t\t\t\t\t\t\t\t\t\talpha, matA->elm, matA->ld,\n\t\t\t\t\t\t\t\t\t\tmatB->elm, matB->ld, beta,\n\t\t\t\t\t\t\t\t\t\tmatC2->elm, matC2->ld);\n\t\t\t\t\n\t\t\t\tgettimeofday( &t, NULL);\n\t\t\t\tte = t.tv_sec + (double)(t.tv_usec) / 1000000.0;\n\t\t\t\tprintf( \"%f s %f GFlops \", (te - ts),\n\t\t\t\t\t\t\t\t(double)rowA * (double)colA * (double)colB * 2.0\n\t\t\t\t\t\t\t\t/ ( te - ts) / 1000000000.0);\n\n\t\t\t\tprintf( \"%e err\", matrixCalcDiff( matC1, matC2));\n\t\t\t\tputchar( '\\n');\n\t\t\t\tmatrixDelete( matA); matA = NULL;\n\t\t\t\tmatrixDelete( matB); matB = NULL;\n\t\t\t\tmatrixDelete( matC1); matC1 = NULL;\n\t\t\t\tmatrixDelete( matC2); matC2 = NULL;\n\t\t\t}\n\t\t}\n }\n}\n\nint main( void)\n{\n\tKalasState *state;\n\n\tstate = kalasStateNew();\n\t\n\ttest_sgemm( state);\n\ttest_dgemm( state);\n\n\tkalasStateDelete( state);\n\treturn 0;\n}\n", "meta": {"hexsha": "f8a80572598dce504363cf8d5ad40acea8b8ae85", "size": 5426, "ext": "c", "lang": "C", "max_stars_repo_path": "src/test.c", "max_stars_repo_name": "kalab1998e/kalas", "max_stars_repo_head_hexsha": "acb6ec90876383e3763768976ab9380d32ab59d2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test.c", "max_issues_repo_name": "kalab1998e/kalas", "max_issues_repo_head_hexsha": "acb6ec90876383e3763768976ab9380d32ab59d2", "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/test.c", "max_forks_repo_name": "kalab1998e/kalas", "max_forks_repo_head_hexsha": "acb6ec90876383e3763768976ab9380d32ab59d2", "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.9779005525, "max_line_length": 75, "alphanum_fraction": 0.5595281976, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6450788070791807}} {"text": "#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char *argv[]) {\n unsigned long seed = 1234;\n int n = 10;\n if (argc > 1)\n n = atoi(argv[1]);\n gsl_rng_env_setup();\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);\n gsl_rng_set(rng, seed);\n for (int i = 0; i < n; i++) {\n double x = gsl_rng_uniform(rng);\n printf(\"%.12f\\n\", x);\n }\n gsl_rng_free(rng);\n return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "5e8cd47ef7ffca185cc21f68658bd5764f75b6ac", "size": 505, "ext": "c", "lang": "C", "max_stars_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c", "max_forks_repo_name": "Gjacquenot/training-material", "max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 21.9565217391, "max_line_length": 50, "alphanum_fraction": 0.5881188119, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6448625419883657}} {"text": "/*\n* Copyright (c) 2014, Newcastle University, UK.\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* 1. Redistributions of source code must retain the above copyright notice,\n* this list of conditions and the following disclaimer.\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// Linear Regression\n// Dan Jackson, 2014 (but see below)\n\n\n\n\n#include \n//#include \n\n#include \"linearregression.h\"\n\n\n// Linear regression with one independent variable\ndouble *LinearModelFitOneIndependent(int n, double *y, double *x)\n{\n\tstatic double coef[3];\t\t// offset(intersect), scale(gradient), spare(to be compatible with two-variable version)\n\tint i;\n\n\t// sum(Xi * Yi)\n\t// sum(Xi^2)\n\tdouble sumx = 0, sumy = 0;\n\tdouble sumxy = 0, sumxsq = 0;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tsumx += x[i];\n\t\tsumy += y[i];\n\t\tsumxy += x[i] * y[i];\n\t\tsumxsq += x[i] * x[i];\n\t}\n\n\t// Calculate mean of x and y\n\tdouble xmean = n > 0 ? sumx / n : 0;\n\tdouble ymean = n > 0 ? sumy / n : 0;\n\n\t// sum(x*y) - (n * xm * ym)\n\t// Slope (b): b = ------------------------\n\t// sum(x^2) - (n * xm^2)\n\tdouble bNumerator = sumxy - (n * xmean * ymean);\n\tdouble bDenominator = sumxsq - (n * xmean * xmean);\n\tdouble b = bDenominator != 0.0 ? bNumerator / bDenominator : 0.0;\n\n\t// Intercept (a): a = ym - b * xm\n\tdouble a = ymean - (b * xmean);\n\n\t// Line of best fit: y = a + b * X\n\tcoef[0] = a;\n\tcoef[1] = b;\n\tcoef[2] = 0.0;\t\t// just to be compatible with two-variable version\n\n\treturn &coef[0];\n}\n\n\n// Linear regression with two independent variables\ndouble *LinearModelFitTwoIndependent(int n, double *y, double *x1, double *x2)\n{\n\t// Implemented from information from: http://faculty.cas.usf.edu/mbrannick/regression/Reg2IV.html\n\tstatic double coef[3];\t\t// offset (intersect), scale 1 (gradient 1), scale 2 (gradient 2)\n\tint i;\n\n\tdouble sumx1 = 0, sumx2 = 0, sumy = 0;\n\tdouble sumx1y = 0, sumx2y = 0;\n\tdouble sumx1x2 = 0;\n\tdouble sumx1sq = 0, sumx2sq = 0;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tsumx1 += x1[i];\n\t\tsumx2 += x2[i];\n\t\tsumy += y[i];\n\t\tsumx1y += x1[i] * y[i];\n\t\tsumx2y += x2[i] * y[i];\n\t\tsumx1x2 += x1[i] * x2[i];\n\t\tsumx1sq += x1[i] * x1[i];\n\t\tsumx2sq += x2[i] * x2[i];\n\t}\n\n\t// Calculate mean of x1, x2, and y\n\tdouble x1mean = n > 0 ? sumx1 / n : 0;\n\tdouble x2mean = n > 0 ? sumx2 / n : 0;\n\tdouble ymean = n > 0 ? sumy / n : 0;\n\n\t// sum(x2^2).sum(x1*y) - sum(x1*x2).sum(x2*y)\n\t// Slope (b1): b1 = ------------------------------------------\n\t// sum(x1^2).sum(x2^2) - sum(x1*x2)^2\n\tdouble b1Numerator = (sumx2sq * sumx1y) - (sumx1x2 * sumx2y);\n\tdouble b1Denominator = (sumx1sq * sumx2sq) - (sumx1x2 * sumx1x2);\n\tdouble b1 = b1Numerator != 0.0 ? b1Numerator / b1Denominator : 0.0;\n\n\t// sum(x1^2).sum(x2*y) - sum(x1*x2).sum(x1*y)\n\t// Slope (b2): b2 = ------------------------------------------\n\t// sum(x1^2).sum(x2^2) - sum(x1*x2)^2\n\tdouble b2Numerator = (sumx1sq * sumx2y) - (sumx1x2 * sumx1y);\n\tdouble b2Denominator = b1Denominator;\t\t// Same as denominator of b1\n\tdouble b2 = b2Denominator != 0.0 ? b2Numerator / b2Denominator : 0.0;\n\n\t// Intercept (a): a = ym - b1 * x1m - b2 * x2m\n\tdouble a = ymean - (b1 * x1mean) - (b2 * x2mean);\n\n\t// Line of best fit: y = a + b1 * x1 + b2 * x2\n\tcoef[0] = a;\n\tcoef[1] = b1;\n\tcoef[2] = b2;\n\n\treturn &coef[0];\n}\n\n\n#ifdef ENABLE_APPROXIMATE\n// Linear regression with two independent variables, weighted\n// NOTE: This is not really correct...\ndouble *LinearModelFitTwoIndependentWeightedApproximately(int n, double *y, double *x1, double *x2, double *weights)\n{\n\tdouble *weightedY = (double *)malloc(sizeof(double) * n);\n\tdouble *weightedX1 = (double *)malloc(sizeof(double) * n);\n\tdouble *weightedX2 = (double *)malloc(sizeof(double) * n);\n\tint i;\n\n\t// HACK: To reduce influence on intercept\n\tdouble influenceSum = 0;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tdouble sw = sqrt(weights[i]);\n\t\tweightedY[i] = y[i] * sw;\n\t\tweightedX1[i] = x1[i] * sw;\n\t\tweightedX2[i] = x2[i] * sw;\n\t\tinfluenceSum += sw;\n\t}\n\n\tdouble *coef = LinearModelFitTwoIndependent(n, weightedY, weightedX1, weightedX2);\n\tdouble influence = n != 0 ? influenceSum / n : 0;\n\tif (influence != 0.0) { coef[0] /= influence; }\n\n\tfree(weightedY);\n\tfree(weightedX1);\n\tfree(weightedX2);\n\treturn coef;\n}\n#endif\n\n\n\n#ifdef ENABLE_GSL\n\n\n#include \n#include \n//#include \n#include \n#include \n#include \n\n/* General weighted case in gsl/multifit/multilinear.c */\n\n\n\ndouble *LinearModelFitTwoIndependentWeighted(int n, double *y, double *x1, double *x2, double *weights)\n{\n\t#define NPARAMS 2\n\n\t// Allocate\n\tgsl_matrix *matrixX = gsl_matrix_alloc(n, NPARAMS);\n\tgsl_vector *vectorW = gsl_vector_alloc(n);\n\tgsl_vector *vectorY = gsl_vector_alloc(n);\n\tgsl_vector *vectorC = gsl_vector_alloc(1 + NPARAMS);\n\n\t// Copy data\n\tint i;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\t// NPARAMS\n\t\tgsl_matrix_set(matrixX, i, 0, x1[i]);\n\t\tgsl_matrix_set(matrixX, i, 1, x2[i]);\n\t\tgsl_vector_set(vectorW, i, weights[i]);\n\t\tgsl_vector_set(vectorY, i, y[i]);\n\t}\n\n\t\n\t// Compute\n\tgsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(n, NPARAMS);\n\tint ret = gsl_multifit_wlinear(matrixX, vectorW, vectorY, vectorC, /*gsl_matrix * cov*/ NULL, /*double * chisq*/ NULL, work);\n\tgsl_multifit_linear_free(work);\n\n\tstatic double coef[NPARAMS + 1];\n\t// NPARAMS+1\n\tcoef[0] = gsl_vector_get(vectorC, 0);\n\tcoef[1] = gsl_vector_get(vectorC, 1);\n\tcoef[2] = gsl_vector_get(vectorC, 2);\n\n\t// Free\n\tgsl_matrix_free(matrixX);\n\tgsl_vector_free(vectorW);\n\tgsl_vector_free(vectorY);\n\tgsl_vector_free(vectorC);\n\n\treturn coef;\n}\n#endif\n", "meta": {"hexsha": "b0e232c2fbce9e644d0739615a5850a04fdc63b0", "size": 6727, "ext": "c", "lang": "C", "max_stars_repo_path": "Software/AX3/omconvert/linearregression.c", "max_stars_repo_name": "digitalinteraction/openmovement", "max_stars_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": 113.0, "max_stars_repo_stars_event_min_datetime": "2015-01-28T16:27:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:51:24.000Z", "max_issues_repo_path": "Software/AX3/omconvert/linearregression.c", "max_issues_repo_name": "digitalinteraction/openmovement", "max_issues_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T16:26:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T11:52:14.000Z", "max_forks_repo_path": "Software/AX3/omconvert/linearregression.c", "max_forks_repo_name": "digitalinteraction/openmovement", "max_forks_repo_head_hexsha": "ee6c87b0411b5accfad8c488b87445dbd9445500", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-03-17T23:01:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T06:53:26.000Z", "avg_line_length": 30.1659192825, "max_line_length": 126, "alphanum_fraction": 0.6488776572, "num_tokens": 2174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.644631524359066}} {"text": "/*\n** False disovery rate (FDR)\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\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n/* get array of FDR values */\ndouble *GetFdr(gsl_histogram *nullhist,gsl_histogram *realhist)\n{\n size_t i=0;\n size_t nbins = gsl_histogram_bins (nullhist);\n\n /* cumulative distribution functions (CDF) */\n gsl_histogram_pdf *cdfz = gsl_histogram_pdf_alloc(nbins);\n gsl_histogram_pdf *cdf0 = gsl_histogram_pdf_alloc(nbins);\n gsl_histogram_pdf_init (cdfz,realhist);\n gsl_histogram_pdf_init (cdf0,nullhist);\n\n /* fdr array */\n double *fdr = (double *)VCalloc(nbins,sizeof(double));\n for (i=0; isum[i];\n double F0 = cdf0->sum[i];\n double xFdr = 1.0;\n if (Fz < 1.0) xFdr = (1.0-F0)/(1.0-Fz);\n if (xFdr > 1.0) xFdr = 1.0;\n if (xFdr < 0.0) xFdr = 0.0;\n fdr[i] = xFdr;\n }\n\n /* enforce monotonicity */\n fdr[0] = 1.0;\n for (i=1; i fdr[i-1]) fdr[i] = fdr[i-1];\n }\n return fdr;\n}\n\n\n/* thresholding */\nvoid ApplyFdrThreshold(VImage dest,double alpha)\n{\n double u=0,beta=1.0-alpha;\n size_t i,n=0;\n VFloat *pp = VImageData(dest); \n for (i=0; i hmax) u = hmax-tiny;\n\tif (u < hmin) u = hmin+tiny;\n\tif (fabs(u) > 0) {\n\t if (gsl_histogram_find (realhist,(double)u,&j) == GSL_SUCCESS) {\n\t VPixel(dest,b,r,c,VFloat) = 1.0 - Fdr[j];\n\t }\n\t}\n }\n }\n }\n\n /* apply threshold if needed */\n if (alpha < 0.99) ApplyFdrThreshold(dest,alpha);\n return;\n}\n", "meta": {"hexsha": "e833b46491f89ec772a1302af52bf7eac56a5fa6", "size": 2481, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/utils/FDR.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/utils/FDR.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/utils/FDR.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.5545454545, "max_line_length": 93, "alphanum_fraction": 0.6259572753, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6443937627872498}} {"text": "/* randist/flat.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/* This is the uniform distribution in the range [a, b)\n\n p(x) dx = 1/(b-a) dx if a <= x < b\n ..... = 0 otherwise \n\n */\n\ndouble\ngsl_ran_flat (const gsl_rng * r, const double a, const double b)\n{\n double u = gsl_rng_uniform (r);\n\n /* A uniform distribution over [a,b) */\n\n return a * (1 - u) + b * u;\n}\n\ndouble\ngsl_ran_flat_pdf (double x, const double a, const double b)\n{\n if (x < b && x >= a)\n {\n return 1 / (b - a);\n }\n else\n {\n return 0;\n }\n}\n", "meta": {"hexsha": "d81d41492e5ec5cdc8ce26d8ac67b121ba01295a", "size": 1416, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/flat.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/flat.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/flat.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.2222222222, "max_line_length": 81, "alphanum_fraction": 0.6603107345, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6443340357530724}} {"text": "/* ode-initval2/modnewton1.c\n * \n * Copyright (C) 2008, 2009, 2010 Tuomo Keskitalo\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/* A modified Newton iteration method for solving non-linear \n equations in implicit Runge-Kutta methods.\n*/\n\n/* References: \n\n Ascher, U.M., Petzold, L.R., Computer methods for ordinary\n differential and differential-algebraic equations, SIAM, \n Philadelphia, 1998. ISBN 0898714125, 9780898714128\n \n Hairer, E., Wanner, G., Solving Ordinary Differential \n Equations II: Stiff and Differential-Algebraic Problems,\n Springer, 1996. ISBN 3540604529, 9783540604525\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"odeiv_util.h\"\n\ntypedef struct\n{\n /* iteration matrix I - h A (*) J */\n gsl_matrix *IhAJ;\n\n /* permutation for LU-decomposition */\n gsl_permutation *p;\n\n /* difference vector for kth Newton iteration */\n gsl_vector *dYk;\n\n /* scaled dYk with desired error level */\n gsl_vector *dScal;\n\n /* current Runge-Kutta points (absolute values) */\n double *Yk;\n\n /* function values at points Yk */\n double *fYk;\n\n /* right hand side of Newton iteration formula */\n gsl_vector *rhs;\n\n /* stopping criterion value from previous step */\n double eeta_prev;\n}\nmodnewton1_state_t;\n\nstatic void *\nmodnewton1_alloc (size_t dim, size_t stage)\n{\n modnewton1_state_t *state =\n (modnewton1_state_t *) malloc (sizeof (modnewton1_state_t));\n\n if (state == 0)\n {\n GSL_ERROR_NULL (\"failed to allocate space for modnewton1_state_t\",\n GSL_ENOMEM);\n }\n\n state->IhAJ = gsl_matrix_alloc (dim * stage, dim * stage);\n\n if (state->IhAJ == 0)\n {\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for IhAJ\", GSL_ENOMEM);\n }\n\n state->p = gsl_permutation_alloc (dim * stage);\n\n if (state->p == 0)\n {\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for p\", GSL_ENOMEM);\n }\n\n state->dYk = gsl_vector_alloc (dim * stage);\n\n if (state->dYk == 0)\n {\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dYk\", GSL_ENOMEM);\n }\n\n state->dScal = gsl_vector_alloc (dim * stage);\n\n if (state->dScal == 0)\n {\n gsl_vector_free (state->dYk);\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for dScal\", GSL_ENOMEM);\n }\n\n state->Yk = (double *) malloc (dim * stage * sizeof (double));\n\n if (state->Yk == 0)\n {\n gsl_vector_free (state->dScal);\n gsl_vector_free (state->dYk);\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for Yk\", GSL_ENOMEM);\n }\n\n state->fYk = (double *) malloc (dim * stage * sizeof (double));\n\n if (state->fYk == 0)\n {\n free (state->Yk);\n gsl_vector_free (state->dScal);\n gsl_vector_free (state->dYk);\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for Yk\", GSL_ENOMEM);\n }\n\n state->rhs = gsl_vector_alloc (dim * stage);\n\n if (state->rhs == 0)\n {\n free (state->fYk);\n free (state->Yk);\n gsl_vector_free (state->dScal);\n gsl_vector_free (state->dYk);\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n GSL_ERROR_NULL (\"failed to allocate space for rhs\", GSL_ENOMEM);\n }\n\n state->eeta_prev = GSL_DBL_MAX;\n\n return state;\n}\n\nstatic int\nmodnewton1_init (void *vstate, const gsl_matrix * A,\n const double h, const gsl_matrix * dfdy,\n const gsl_odeiv2_system * sys)\n{\n /* Initializes the method by forming the iteration matrix IhAJ\n and generating its LU-decomposition\n */\n\n modnewton1_state_t *state = (modnewton1_state_t *) vstate;\n\n gsl_matrix *const IhAJ = state->IhAJ;\n gsl_permutation *const p = state->p;\n\n const size_t dim = sys->dimension;\n const size_t stage = A->size1;\n\n state->eeta_prev = GSL_DBL_MAX;\n\n /* Generate IhAJ */\n\n {\n size_t i, j, k, m;\n\n for (i = 0; i < dim; i++)\n for (j = 0; j < dim; j++)\n for (k = 0; k < stage; k++)\n for (m = 0; m < stage; m++)\n {\n size_t x = dim * k + i;\n size_t y = dim * m + j;\n\n if (x != y)\n gsl_matrix_set (IhAJ, x, y,\n -h * gsl_matrix_get (A, k, m) *\n gsl_matrix_get (dfdy, i, j));\n else\n gsl_matrix_set (IhAJ, x, y,\n 1.0 - h * gsl_matrix_get (A, k, m) *\n gsl_matrix_get (dfdy, i, j));\n }\n }\n\n /* decompose */\n\n {\n int signum;\n int s = gsl_linalg_LU_decomp (IhAJ, p, &signum);\n\n if (s != GSL_SUCCESS)\n return s;\n }\n\n return GSL_SUCCESS;\n}\n\nstatic int\nmodnewton1_solve (void *vstate, const gsl_matrix * A,\n const double c[], const double t, const double h,\n const double y0[], const gsl_odeiv2_system * sys,\n double YZ[], const double errlev[])\n{\n /* Solves the non-linear equation system resulting from implicit\n Runge-Kutta methods by a modified Newton iteration. The\n modified Newton iteration with this problem is stated in the\n form\n\n IhAJ * dYk = rhs\n\n in which IhAJ is the iteration matrix: IhAJ = (I - hA (*) J) in\n which (*) is the Kronecker matrix product (size of IhAJ =\n dim*stage, dim*stage), dYk is the Runge-Kutta point (Y)\n difference vector for kth Newton iteration: dYk = Y(k+1) - Y(k),\n and rhs = Y(k) - y0 - h * sum j=1..stage (a_j * f(Y(k)))\n\n This function solves dYk by LU-decomposition of IhAJ with partial\n pivoting.\n */\n\n modnewton1_state_t *state = (modnewton1_state_t *) vstate;\n\n gsl_matrix *const IhAJ = state->IhAJ;\n gsl_permutation *const p = state->p;\n gsl_vector *const dYk = state->dYk;\n double *const Yk = state->Yk;\n double *const fYk = state->fYk;\n gsl_vector *const rhs = state->rhs;\n double *const eeta_prev = &(state->eeta_prev);\n gsl_vector *const dScal = state->dScal;\n\n const size_t dim = sys->dimension;\n const size_t stage = A->size1;\n\n int status = GSL_CONTINUE; /* Convergence status for Newton iteration */\n\n /* Set starting values for iteration. Use starting values of Y(k) =\n y0. FIXME: Implement better initial guess described in Hairer and\n Wanner.\n */\n\n {\n size_t j, m;\n\n gsl_vector_set_zero (dYk);\n\n for (j = 0; j < stage; j++)\n for (m = 0; m < dim; m++)\n Yk[j * dim + m] = y0[m];\n }\n\n /* Loop modified Newton iterations */\n\n {\n size_t iter = 0;\n size_t j, m, n;\n\n /* Maximum number of Newton iterations. */\n const size_t max_iter = 7;\n\n double dScal_norm = 0.0; /* Newton iteration step length */\n double dScal_norm_prev = 0.0; /* Previous dScal_norm */\n\n while (status == GSL_CONTINUE && iter < max_iter)\n {\n iter++;\n\n /* Update Y(k) and evaluate function */\n\n for (j = 0; j < stage; j++)\n {\n for (m = 0; m < dim; m++)\n {\n Yk[j * dim + m] += gsl_vector_get (dYk, j * dim + m);\n }\n\n {\n int s = GSL_ODEIV_FN_EVAL (sys, t + c[j] * h, &Yk[j * dim],\n &fYk[j * dim]);\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n }\n\n /* Calculate rhs */\n\n for (j = 0; j < stage; j++)\n for (m = 0; m < dim; m++)\n {\n double sum = 0;\n\n for (n = 0; n < stage; n++)\n sum += gsl_matrix_get (A, j, n) * fYk[n * dim + m];\n\n gsl_vector_set (rhs, j * dim + m,\n -1.0 * Yk[j * dim + m] + y0[m] + h * sum);\n }\n\n /* Solve dYk */\n\n {\n int s = gsl_linalg_LU_solve (IhAJ, p, rhs, dYk);\n\n if (s != GSL_SUCCESS)\n {\n return s;\n }\n }\n\n /* Evaluate convergence according to method by Hairer and\n Wanner, section IV.8. The iteration step is normalized by\n desired error level before calculation of the norm, to take\n the tolerance on each component of y into account.\n */\n\n {\n /* relative change in two Newton iteration steps */\n double theta_k;\n\n /* transformation of theta_k */\n double eeta_k = 0.0;\n\n for (j = 0; j < stage; j++)\n for (m = 0; m < dim; m++)\n {\n gsl_vector_set (dScal, j * dim + m,\n gsl_vector_get (dYk, j * dim + m)\n / errlev[m]);\n }\n\n dScal_norm_prev = dScal_norm;\n dScal_norm = gsl_blas_dnrm2 (dScal);\n\n theta_k = dScal_norm / dScal_norm_prev;\n\n if (iter > 1)\n {\n /* check for increase in step size, which indicates divergence */\n\n if (theta_k >= 1.0)\n {\n return GSL_FAILURE;\n }\n\n eeta_k = theta_k / (1.0 - theta_k);\n }\n\n else\n {\n eeta_k = pow (GSL_MAX_DBL (*eeta_prev, GSL_DBL_EPSILON), 0.8);\n }\n\n *eeta_prev = eeta_k;\n\n if (eeta_k * dScal_norm < 1.0)\n {\n status = GSL_SUCCESS;\n }\n }\n }\n }\n\n /* No convergence reached within allowed iterations */\n\n if (status != GSL_SUCCESS)\n {\n return GSL_FAILURE;\n }\n\n /* Give solution in YZ */\n\n else\n {\n size_t j, m;\n\n for (j = 0; j < stage; j++)\n for (m = 0; m < dim; m++)\n YZ[j * dim + m] =\n Yk[j * dim + m] + gsl_vector_get (dYk, j * dim + m);\n\n return status;\n }\n}\n\nstatic void\nmodnewton1_free (void *vstate)\n{\n modnewton1_state_t *state = (modnewton1_state_t *) vstate;\n\n gsl_vector_free (state->rhs);\n free (state->fYk);\n free (state->Yk);\n gsl_vector_free (state->dScal);\n gsl_vector_free (state->dYk);\n gsl_permutation_free (state->p);\n gsl_matrix_free (state->IhAJ);\n free (state);\n}\n", "meta": {"hexsha": "1e2f973160c2861cd7f9cbc1f46c8697ac1466e3", "size": 11214, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/ode-initval2/modnewton1.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/ode-initval2/modnewton1.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/ode-initval2/modnewton1.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.262295082, "max_line_length": 81, "alphanum_fraction": 0.5648296772, "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6442101520741235}} {"text": "#include \n#include \n\n#include \n\n#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)\n\n//The Struct that contains the k nearest neighbors of m queries\ntypedef struct knnresult{\n int * nidx; //!< Indices (0-based) of nearest neighbors [m-by-k]\n double * ndist; //!< Distance of nearest neighbors [m-by-k]\n int m; //!< Number of query points [scalar]\n int k; //!< Number of nearest neighbors [scalar]\n} knnresult;\n\n//A sorting alogorithm for the k first items of a list\nvoid k_select(int * nidx, \n double * ndist,\n int k,\n int n)\n{\n for(int i=0; i ndist[j]){\n min = ndist[j];\n minidx = nidx[j];\n SWAP(ndist[i],ndist[j], double);\n SWAP(nidx[i], nidx[j], int);\n }\n } \n }\n}\n\nint partition(int * nidx, \n double * ndist,\n int left,\n int right,\n int pivot)\n{\n\n double val = ndist[pivot];\n\n SWAP(ndist[right], ndist[pivot], double);\n SWAP(nidx[right], nidx[pivot], int);\n \n int storeIdx = left;\n\n for(int i=left; i= right) return;\n \n int pivot = left + rand() % (right - left + 1);\n pivot = partition(nidx, ndist, left, right, pivot);\n\n if(k == pivot){\n return;\n }else if(k< pivot){\n quickselect(nidx, ndist, left, pivot - 1, k);\n }else{\n quickselect(nidx, ndist, pivot + 1, right, k);\n }\n\n\n}\n\n//Calculates a column of the Euclidean distance matrix D \ndouble *calc_Dcol( double *X,\n double *Y,\n int n,\n int d,\n int row)\n{\n double *Dcol= (double *)malloc(n * sizeof(double));\n\n for(int i=0; i max_m){\n \n int iteration_m[m/max_m];\n for(int i=0; i\n#include \n#include \n#include \n#include \n#include \n\nint max(int x, int y){\n if(x > y) return x;\n else return y;\n}\nvoid PrintMatrix(float* pMatrix, const size_t nR, const size_t nC, const CBLAS_ORDER Order) {\n unsigned int i, j;\n if (Order == CblasRowMajor) {\n for (i = 0; i < nR; i++) {\n for (j = 0; j < nC; j++) {\n printf(\"%f \\t \", pMatrix[i * nC + j]); // !!!\n }\n printf(\"\\n\"); // !!!\n }\n } else {\n for (i = 0; i < nR; i++) {\n for (j = 0; j < nC; j++) {\n printf(\"%f \\t \", pMatrix[i + j* nR ]); // !!!\n }\n printf(\"\\n\"); // !!!\n }\n }\n printf(\"\\n\"); // !!!\n}\n\nint main(void)\n{\n const int m = 4;\n const int n = 5;\n const int k = 1;\n\n float A[] = { 8, 4, 7, 3, 5, 1, 1, 3, 2, 1, 2, 3, 2, 0, 1, 1, 2, 3, 4, 1};\n float B[5] = { -1, 2, -1, 1, 2 };\n\n float alpha = 1.0, beta = 0.0;\n int lda, ldb, ldc;\n\n float * C = (float*) malloc(m * k * sizeof(float));\n for (int i = 0; i < m*k; i++) C[i] = 0.0;\n\n\n //working cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, A, n, B, k, beta, C, k);\n //lda = max(1,n); ldb = max(1,k); ldc = max(1,k); // refer manual and switch n and k \n //cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m,k,n, alpha, A, lda, B, ldb, beta, C, ldc);\n\n // working cblas_sgemv(CblasColMajor, CblasNoTrans, m, n, alpha, A, m, B, k, beta, C, k);\n // working cblas_sgemv(CblasColMajor, CblasTrans, m, n, alpha, A, m, B, k, beta, C, k);\n lda = max(1,n); ldb = max(1,n); ldc = max(1,m); // refer manual and switch n and k \n cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, m,k,n, alpha, A, lda, B, ldb, beta, C, ldc);\n\n\n PrintMatrix(C, m, k, CblasRowMajor);\n\n free(C);\n\n return 0;\n}\n", "meta": {"hexsha": "8d87c1d2b11d0710ae74838b6cccd194e1dd081c", "size": 1869, "ext": "c", "lang": "C", "max_stars_repo_path": "2test.c", "max_stars_repo_name": "ramcn/flappie-x-cpp", "max_stars_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-16T17:15:21.000Z", "max_issues_repo_path": "2test.c", "max_issues_repo_name": "ramcn/flappie-x-cpp", "max_issues_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2test.c", "max_forks_repo_name": "ramcn/flappie-x-cpp", "max_forks_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.203125, "max_line_length": 105, "alphanum_fraction": 0.4986623863, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6437895947352439}} {"text": "/* randist/exppow.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 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.\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) \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\t{\n\t return z ;\n\t} \n else \n\t{\n\t return -z ;\n\t}\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 */\n\n double x, y, h, ratio, u ;\n\n /* Scale factor chosen by upper bound on ratio at b = 2 */\n\n double s = 1.4489 ; \n do \n\t{\n\t x = gsl_ran_laplace (r, a) ;\n\t y = gsl_ran_laplace_pdf (x,a) ;\n\t h = gsl_ran_exppow_pdf (x,a,b) ;\n\t ratio = h/(s * y) ;\n\t u = gsl_rng_uniform (r) ;\n\t} \n while (u > ratio) ;\n \n return 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 */\n\n double x, y, h, ratio, u ;\n const double sigma = a / sqrt(2.0) ;\n\n /* Scale factor chosen by upper bound on ratio at b = infinity.\n\t This could be improved by using a rational function\n\t approximation to the bounding curve. */\n\n double s = 2.4091 ; /* this is sqrt(pi) e / 2 */\n\n do \n\t{\n\t x = gsl_ran_gaussian (r, sigma) ;\n\t y = gsl_ran_gaussian_pdf (x, sigma) ;\n\t h = gsl_ran_exppow_pdf (x, a, b) ;\n\t ratio = h/(s * y) ;\n\t u = gsl_rng_uniform (r) ;\n\t} \n while (u > ratio) ;\n\n return 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\n", "meta": {"hexsha": "af085aab04c966073ef2dff1cb98e2e08bf03c41", "size": 3428, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/exppow.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/exppow.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/exppow.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.7744360902, "max_line_length": 72, "alphanum_fraction": 0.6242707118, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6437895796058432}} {"text": "/* cdf/binomial.c\n * \n * Copyright (C) 2004 Jason H. Stover.\n * Copyright (C) 2004 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 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n/* Computes the cumulative distribution function for a binomial\n random variable. For a binomial random variable X with n trials\n and success probability p,\n \n Pr( X <= k ) = Pr( Y >= p )\n \n where Y is a beta random variable with parameters k+1 and n-k.\n \n The binomial distribution has the form,\n\n prob(k) = n!/(k!(n-k)!) * p^k (1-p)^(n-k) for k = 0, 1, ..., n\n\n The cumulated distributions can be expressed in terms of normalized\n incomplete beta functions (see Abramowitz & Stegun eq. 26.5.26 and\n eq. 6.6.3).\n\n Reference: \n \n W. Feller, \"An Introduction to Probability and Its\n Applications,\" volume 1. Wiley, 1968. Exercise 45, page 173,\n chapter 6.\n */\n\n#include \n#include \n#include \n#include \n#include \n\ndouble\ngsl_cdf_binomial_P (const unsigned int k, const double p, const unsigned int n)\n{\n double P;\n double a;\n double b;\n\n if (p > 1.0 || p < 0.0)\n {\n CDF_ERROR (\"p < 0 or p > 1\", GSL_EDOM);\n }\n\n if (k >= n)\n {\n P = 1.0;\n }\n else\n {\n a = (double) k + 1.0;\n b = (double) n - k;\n P = gsl_cdf_beta_Q (p, a, b);\n }\n\n return P;\n}\n\ndouble\ngsl_cdf_binomial_Q (const unsigned int k, const double p, const unsigned int n)\n{\n double Q;\n double a;\n double b;\n\n if (p > 1.0 || p < 0.0)\n {\n CDF_ERROR (\"p < 0 or p > 1\", GSL_EDOM);\n }\n\n if (k >= n)\n {\n Q = 0.0;\n }\n else\n {\n a = (double) k + 1.0;\n b = (double) n - k;\n Q = gsl_cdf_beta_P (p, a, b);\n }\n\n return Q;\n}\n", "meta": {"hexsha": "190945df9cf7986b538b352ed47e7adc14aa1134", "size": 2516, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/cdf/binomial.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/binomial.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/binomial.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.0825688073, "max_line_length": 79, "alphanum_fraction": 0.6291732909, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.643196176870878}} {"text": "// --------------------------------------------------------\n// Dragon\n// Copyright(c) 2017 SeetaTech\n// Written by Ting Pan\n// --------------------------------------------------------\n\n#ifndef DRAGON_UTILS_MATH_FUNCTIONS_H_\n#define DRAGON_UTILS_MATH_FUNCTIONS_H_\n\n#include \n#include \n#include \n\n#ifdef WITH_BLAS\nextern \"C\" {\n#include \n}\n#else // WITH_BLAS\ntypedef enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112} CBLAS_TRANSPOSE;\n#endif\n\n#include \"protos/dragon.pb.h\"\n\nnamespace dragon {\n\nnamespace math {\n\n/******************** Level-0 ********************/\n\ntemplate \nvoid Set(const int n, const T alpha, T* x);\n\ntemplate \nvoid RandomUniform(const int n, const float low, const float high, T *x);\n\ntemplate \nvoid RandomNormal(const int n, const float mu, const float sigma, T* x);\n\ntemplate \nvoid RandomTruncatedNormal(const int n, \n const float mu,\n const float sigma,\n const float low,\n const float high,\n T* x);\n\ntemplate \nvoid RandomBernoulli(const int n, const float p, uint32_t* x);\n\n/******************** Level-1 ********************/\n\ntemplate \nvoid Add(const int n, const T* a, const T* b, T* y);\n\ntemplate \nvoid Sub(const int n, const T* a, const T* b, T* y);\n\ntemplate \nvoid Mul(const int n, const T* a, const T* b, T* y);\n\ntemplate \nvoid Div(const int n, const T* a, const T* b, T* y);\n\ntemplate \nvoid Clip(const int n, const float low, const float high, T* x);\n\ntemplate \nvoid Exp(const int n, const T* x, T* y);\n\ntemplate \nvoid Log(const int n, const T* x, T* y);\n\ntemplate \nvoid Square(const int n, const T* x, T* y);\n\ntemplate \nvoid Sqrt(const int n, const T* x, T* y);\n\ntemplate \nvoid Pow(const int n, const float alpha, const T* x, T* y);\n\ntemplate \nvoid Inv(const int n, const float numerator, const T* x, T* y);\n\n/******************** Level-2 ********************/\n\ntemplate \nvoid Scal(const int n, const float alpha, T* y);\n\ntemplate \nvoid Scale(const int n, const float alpha, const T* x, T* y);\n\ntemplate \nT StridedDot(const int n,\n const T* a,\n const int incx,\n const T* b,\n const int incy);\n\ntemplate \nfloat Dot(const int n, const T* a, const T* b);\n\ntemplate\nfloat ASum(const int n, const T *x);\n\ntemplate\nvoid AddScalar(const int n, const float alpha, T* y);\n\ntemplate\nvoid MulScalar(const int n, const float alpha, T* y);\n\ntemplate\nvoid Axpy(const int n, float alpha, const T* x, T *y);\n\ntemplate\nvoid Axpby(const int n, float alpha, const T* x, float beta, T *y);\n\n/******************** Level-3 ********************/\n\ntemplate \nvoid Gemm(const CBLAS_TRANSPOSE transA,\n const CBLAS_TRANSPOSE transB,\n const int M,\n const int N,\n const int K,\n const float alpha,\n const T* A,\n const T* B,\n const float beta,\n T* C,\n TensorProto_DataType math_type = TensorProto_DataType_FLOAT);\n\ntemplate\nvoid Gemv(const CBLAS_TRANSPOSE transA,\n const int M,\n const int N,\n const float alpha,\n const T* A,\n const T* x,\n const float beta,\n T* y,\n TensorProto_DataType math_type = TensorProto_DataType_FLOAT);\n\n} // namespace math\n\n} // namespace dragon\n\n#endif // DRAGON_UTILS_MATH_FUNCTIONS_H_\n", "meta": {"hexsha": "11b5330eb39ab0581e1a8efa24b4d5d6f8c02fc5", "size": 4130, "ext": "h", "lang": "C", "max_stars_repo_path": "Dragon/include/utils/math_functions.h", "max_stars_repo_name": "neopenx/Dragon", "max_stars_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 212.0, "max_stars_repo_stars_event_min_datetime": "2015-07-05T07:57:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T01:55:35.000Z", "max_issues_repo_path": "Dragon/include/utils/math_functions.h", "max_issues_repo_name": "neopenx/Dragon", "max_issues_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-07-07T14:31:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-12T02:21:15.000Z", "max_forks_repo_path": "Dragon/include/utils/math_functions.h", "max_forks_repo_name": "neopenx/Dragon", "max_forks_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2016-03-24T09:02:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T01:52:41.000Z", "avg_line_length": 27.7181208054, "max_line_length": 80, "alphanum_fraction": 0.611622276, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6431082580668053}} {"text": "/*\n** overall concordance correlation coefficient (OCCC)\n** Barnhart et al. (2002), Biometrics, 58, 1020-1027.\n** \n** G.Lohmann, July 2010\n*/\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#define SQR(x) ((x) * (x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\n\ndouble Cov(double *arr1,double *arr2,int n)\n{\n int i;\n double nx,sum,ave1,ave2;\n\n nx = (double)n;\n\n sum = 0;\n for (i=0; isize1;\n\n if (ave == NULL) {\n ave = gsl_vector_calloc(nsubjects);\n var = gsl_vector_calloc(nsubjects);\n cov = gsl_matrix_calloc(nsubjects,nsubjects);\n }\n\n for (i=0; i 0) {\n for (i=0; i\n#include \n#include \n#include \n#include \"sphere.h\"\n#include \"sphSolv.h\"\n#include \n\n\n#undef __FUNCT__\n#define __FUNCT__ \"CalcEnm\"\nPetscErrorCode CalcEnm(Vec chargeSph, Vec chargeMag, PetscInt n, PetscInt m, PetscReal *rval, PetscReal *ival)\n{\n PetscErrorCode ierr;\n PetscInt numCharges;\n PetscScalar *chargeMagPtr, *chargeSphPtr;\n PetscFunctionBegin;\n\n ierr = VecGetSize(chargeMag, &numCharges);CHKERRQ(ierr);\n \n PetscInt absm = abs(m);\n PetscReal coef = 1;\n for(PetscInt i=n-absm+1; i <= n + absm; ++i)\n coef *= i;\n coef = 1./coef;\n\n *rval = 0;\n *ival = 0;\n\n PetscReal qk, rk, rkton, thetak, phik, lterm, rterm, iterm;\n\n ierr = VecGetArrayRead(chargeMag, &chargeMagPtr);CHKERRQ(ierr);\n ierr = VecGetArrayRead(chargeSph, &chargeSphPtr);CHKERRQ(ierr);\n for(PetscInt k=0; ke1;\n double e2 = problem->e2;\n double b = problem->b;\n \n double val = 1.0;\n for(int i=0; i<2*n+1; ++i) {\n val /= b;\n }\n\n val /= e1;\n \n val *= (e1-e2)*(n+1);\n val /= (e1*n + e2*(n+1));\n //printf(\"VAL: %15.15f\\n\", val);\n *Bnmrval = val*Enmrval;\n *Bnmival = val*Enmival;\n\n}\n\n\nvoid calcCnmFromEnm(int n, int m, double Enmrval, double Enmival, SProblem *problem, double *Cnmrval, double *Cnmival) {\n double e1 = problem->e1;\n double e2 = problem->e2;\n \n double val;\n \n val = n*(e1-e2)/(n*e1+e2*(n+1));\n val = (1./e2)*(1-val);\n \n *Cnmrval = val * Enmrval;\n *Cnmival = val * Enmival;\n\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"CalcSphericalCoulombPotential\"\nPetscErrorCode CalcSphericalCoulombPotential(PetscReal b, PetscReal eps1, PetscReal eps2, PetscInt nCharges, Vec chargeXYZ, Vec chargeMag, PetscInt nSol, Vec solXYZ, PetscInt Nmax, Vec targetSol)\n{\n PetscErrorCode ierr;\n PetscInt numSol;\n Vec chargeSph;\n Vec solSph;\n Vec coulCoefs;\n PetscScalar *vecPtr, *solSphPtr;\n PetscReal solRad, solTheta, solPhi;\n PetscReal lterm, rterm, iterm;\n PetscReal Enmrval, Enmival;\n PetscReal radpow = 1.0;\n PetscFunctionBegin;\n\n //get number of solution points\n ierr = VecGetSize(targetSol, &numSol);CHKERRQ(ierr);\n \n // create charge spherical vec and convert from xyz\n ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nCharges, &chargeSph);CHKERRQ(ierr);\n ierr = CartesianToSpherical(chargeXYZ, chargeSph);CHKERRQ(ierr);\n //create solution spherical vec and convert from xyz\n ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nSol, &solSph);CHKERRQ(ierr);\n ierr = CartesianToSpherical(solXYZ, solSph);CHKERRQ(ierr);\n\n \n //zero solutions vec\n ierr = VecSet(targetSol, 0.0);CHKERRQ(ierr);\n \n ierr = VecGetArrayRead(solSph, &solSphPtr);CHKERRQ(ierr);\n ierr = VecGetArray(targetSol, &vecPtr);CHKERRQ(ierr);\n\n for(PetscInt n=0; n<=Nmax; ++n) {\n for(PetscInt m=-n; m <= n; ++m) {\n \n ierr = CalcEnm(chargeSph, chargeMag, n, m, &Enmrval, &Enmival);CHKERRQ(ierr);\n for(PetscInt k=0; ke1;\n double rad = r->x1;\n double theta = r->x2;\n double phi = r->x3;\n double radpow = 1.0;\n double lterm;\n double Enmrterm, Enmiterm;\n double rterm, iterm;\n\n for(int n=0; n<=maxDeg; ++n) { \n radpow *= rad;\n for(int m=-n; m<=n; ++m) {\n calcEnm(problem->positions, problem->charges, problem->nCharges, n, m, &Enmrterm, &Enmiterm);\n //printf(\"Enm %d %d %15.15f\\n\", n, m, Enm);\n\n //printf(\"cos(theta): %15.15f\\n\", theta);\n lterm = gsl_sf_legendre_Plm(n, abs(m), cos(theta));//boost::math::legendre_p(n, abs(m), cos(theta));//legvals[n+abs(m)];//boost::math::legendre_p(n, m, cos(theta));\n \n rterm = cos(m*phi);\n iterm = sin(m*phi);\n \n val += ((Enmrterm*rterm - Enmiterm*iterm)*lterm)/(e1*radpow);\n //printf(\"lterm: %15.15f\\n\", lterm);\n //printf(\"cos(mphi) = %15.15f\\n\\n\", cos(m*phi));\n }\n printf(\"n = %d\\nval = %15.15f\\n\", n, val);\n }\n\n return 0.0;\n}\n\n\ndouble calcCoulombSphericalGrid(SProblem *problem, int maxDeg, SPoint *r, int nPoints, double *solution) {\n double e1 = problem->e1;\n \n double rad, theta, phi;\n double lterm;\n double Enmrval, Enmival;\n double Bnmrval, Bnmival;\n double Cnmrval, Cnmival;\n double rval, ival;\n\n for(int i=0; ipositions, problem->charges, problem->nCharges, n, m, &Enmrval, &Enmival);\n calcBnmFromEnm(n, m, Enmrval, Enmival, problem, &Bnmrval, &Bnmival);\n calcCnmFromEnm(n, m, Enmrval, Enmival, problem, &Cnmrval, &Cnmival);\n\n for(int k=0; kb) {\n\n\t \n\t solution[k] += (Bnmrval*rval - Bnmival*ival)*lterm*pow(rad,n);\n\n\t}\n\telse if(rad > problem->b) {\n\t \n\n\n\t solution[k] += ((Cnmrval*rval - Cnmival*ival)*lterm)/pow(rad,n+1);\n\n\t}\n\telse {\n\t \n\t printf(\"CALCULATING ON BOUNDARY\\n\");\n\t solution[k] += ((Enmrval*rval - Enmival*ival)*lterm)/(e1*pow(rad,n+1));\n\t}\n }\n }\n printf(\"n = %d\\nval = %15.15f\\n\", n, solution[0]);\n }\n\n return 0.0;\n}\n", "meta": {"hexsha": "ffbc1ebd5eb4086885e88dd6dcdb74f8d579321e", "size": 7940, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sphere/sphSolv.c", "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_issues_repo_path": "src/sphere/sphSolv.c", "max_issues_repo_name": "tom-klotz/ellipsoid-solvation", "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sphere/sphSolv.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": 27.1917808219, "max_line_length": 195, "alphanum_fraction": 0.6236775819, "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6423968067912024}} {"text": "static char help[] =\n\"Coupled reaction-diffusion equations (Pearson 1993). Option prefix -ptn_.\\n\"\n\"Demonstrates form F(t,Y,dot Y) = G(t,Y) where F() is IFunction and G() is\\n\"\n\"RHSFunction(). Implements IJacobian(). Defaults to ARKIMEX (= adaptive\\n\"\n\"Runge-Kutta implicit-explicit) TS type.\\n\\n\";\n\n// compare runs with\n// -dm_mat_type aij|baij|sbaij\n// -dm_mat_type sbaij -ksp_type cg -pc_type icc # 20% speed up?\n\n#include \n\ntypedef struct {\n double u, v;\n} Field;\n\ntypedef struct {\n double L, // domain side length\n Du, // diffusion coefficient: u equation\n Dv, // v equation\n phi, // \"dimensionless feed rate\" (F in Pearson 1993)\n kappa; // \"dimensionless rate constant\" (k in Pearson 1993)\n} PatternCtx;\n\nextern PetscErrorCode InitialState(DM, Vec, double, PatternCtx*);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, double, Field**,\n Field**, PatternCtx*);\nextern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, double, Field**, Field**,\n Field **, PatternCtx*);\nextern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, double, Field**, Field**,\n double, Mat, Mat, PatternCtx*);\n\nint main(int argc,char **argv)\n{\n PetscErrorCode ierr;\n PatternCtx user;\n TS ts;\n Vec x;\n DM da;\n DMDALocalInfo info;\n double noiselevel = -1.0; // negative value means no initial noise\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n // parameter values from pages 21-22 in Hundsdorfer & Verwer (2003)\n user.L = 2.5;\n user.Du = 8.0e-5;\n user.Dv = 4.0e-5;\n user.phi = 0.024;\n user.kappa = 0.06;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"ptn_\", \"options for patterns\", \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-noisy_init\",\n \"initialize u,v with this much random noise (e.g. 0.2) on top of usual initial values\",\n \"pattern.c\",noiselevel,&noiselevel,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-L\",\"square domain side length; recommend L >= 0.5\",\n \"pattern.c\",user.L,&user.L,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Du\",\"diffusion coefficient of first equation\",\n \"pattern.c\",user.Du,&user.Du,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Dv\",\"diffusion coefficient of second equation\",\n \"pattern.c\",user.Dv,&user.Dv,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-phi\",\"dimensionless feed rate (=F in (Pearson, 1993))\",\n \"pattern.c\",user.phi,&user.phi,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-kappa\",\"dimensionless rate constant (=k in (Pearson, 1993))\",\n \"pattern.c\",user.kappa,&user.kappa,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC,\n DMDA_STENCIL_BOX, // for 9-point stencil\n 3,3,PETSC_DECIDE,PETSC_DECIDE,\n 2, 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 = DMDASetFieldName(da,0,\"u\"); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,1,\"v\"); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n if (info.mx != info.my) {\n SETERRQ(PETSC_COMM_WORLD,1,\"pattern.c requires mx == my\");\n }\n ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"running on %d x %d grid with square cells of side h = %.6f ...\\n\",\n info.mx,info.my,user.L/(double)(info.mx)); CHKERRQ(ierr);\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 = DMDATSSetIFunctionLocal(da,INSERT_VALUES,\n (DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr);\n ierr = DMDATSSetIJacobianLocal(da,\n (DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr);\n ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,200.0); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,5.0); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n//ENDTSSETUP\n\n ierr = DMCreateGlobalVector(da,&x); CHKERRQ(ierr);\n ierr = InitialState(da,x,noiselevel,&user); CHKERRQ(ierr);\n ierr = TSSolve(ts,x); CHKERRQ(ierr);\n\n VecDestroy(&x); TSDestroy(&ts); DMDestroy(&da);\n return PetscFinalize();\n}\n\n// Formulas from page 22 of Hundsdorfer & Verwer (2003). Interpretation here is\n// to always generate 0.5 x 0.5 non-trivial patch in (0,L) x (0,L) domain.\nPetscErrorCode InitialState(DM da, Vec Y, double noiselevel, PatternCtx* user) {\n PetscErrorCode ierr;\n DMDALocalInfo info;\n int i,j;\n double sx,sy;\n const double ledge = (user->L - 0.5) / 2.0, // nontrivial initial values on\n redge = user->L - ledge; // ledge < x,y < redge\n DMDACoor2d **aC;\n Field **aY;\n\n ierr = VecSet(Y,0.0); CHKERRQ(ierr);\n if (noiselevel > 0.0) {\n // noise added to usual initial condition is uniform on [0,noiselevel],\n // independently for each location and component\n ierr = VecSetRandom(Y,NULL); CHKERRQ(ierr);\n ierr = VecScale(Y,noiselevel); CHKERRQ(ierr);\n }\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = DMDAGetCoordinateArray(da,&aC); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,Y,&aY); 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 ((aC[j][i].x >= ledge) && (aC[j][i].x <= redge)\n && (aC[j][i].y >= ledge) && (aC[j][i].y <= redge)) {\n sx = sin(4.0 * PETSC_PI * aC[j][i].x);\n sy = sin(4.0 * PETSC_PI * aC[j][i].y);\n aY[j][i].v += 0.5 * sx * sx * sy * sy;\n }\n aY[j][i].u += 1.0 - 2.0 * aY[j][i].v;\n }\n }\n ierr = DMDAVecRestoreArray(da,Y,&aY); CHKERRQ(ierr);\n ierr = DMDARestoreCoordinateArray(da,&aC); CHKERRQ(ierr);\n return 0;\n}\n\n// in system form F(t,Y,dot Y) = G(t,Y), compute G():\n// G^u(t,u,v) = - u v^2 + phi (1 - u)\n// G^v(t,u,v) = + u v^2 - (phi + kappa) v\n//STARTRHSFUNCTION\nPetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,\n double t, Field **aY, Field **aG, PatternCtx *user) {\n int i, j;\n double uv2;\n\n for (j = info->ys; j < info->ys + info->ym; j++) {\n for (i = info->xs; i < info->xs + info->xm; i++) {\n uv2 = aY[j][i].u * aY[j][i].v * aY[j][i].v;\n aG[j][i].u = - uv2 + user->phi * (1.0 - aY[j][i].u);\n aG[j][i].v = + uv2 - (user->phi + user->kappa) * aY[j][i].v;\n }\n }\n return 0;\n}\n//ENDRHSFUNCTION\n\n// in system form F(t,Y,dot Y) = G(t,Y), compute F():\n// F^u(t,u,v,u_t,v_t) = u_t - D_u Laplacian u\n// F^v(t,u,v,u_t,v_t) = v_t - D_v Laplacian v\n//STARTIFUNCTION\nPetscErrorCode FormIFunctionLocal(DMDALocalInfo *info,\n double t, Field **aY, Field **aYdot, Field **aF,\n PatternCtx *user) {\n int i, j;\n const double h = user->L / (double)(info->mx),\n Cu = user->Du / (6.0 * h * h),\n Cv = user->Dv / (6.0 * h * h);\n double u, v, lapu, lapv;\n\n for (j = info->ys; j < info->ys + info->ym; j++) {\n for (i = info->xs; i < info->xs + info->xm; i++) {\n u = aY[j][i].u;\n v = aY[j][i].v;\n lapu = aY[j+1][i-1].u + 4.0*aY[j+1][i].u + aY[j+1][i+1].u\n + 4.0*aY[j][i-1].u - 20.0*u + 4.0*aY[j][i+1].u\n + aY[j-1][i-1].u + 4.0*aY[j-1][i].u + aY[j-1][i+1].u;\n lapv = aY[j+1][i-1].v + 4.0*aY[j+1][i].v + aY[j+1][i+1].v\n + 4.0*aY[j][i-1].v - 20.0*v + 4.0*aY[j][i+1].v\n + aY[j-1][i-1].v + 4.0*aY[j-1][i].v + aY[j-1][i+1].v;\n aF[j][i].u = aYdot[j][i].u - Cu * lapu;\n aF[j][i].v = aYdot[j][i].v - Cv * lapv;\n }\n }\n return 0;\n}\n//ENDIFUNCTION\n\n// in system form F(t,Y,dot Y) = G(t,Y), compute combined/shifted\n// Jacobian of F():\n// J = (shift) dF/d(dot Y) + dF/dY\n//STARTIJACOBIAN\nPetscErrorCode FormIJacobianLocal(DMDALocalInfo *info,\n double t, Field **aY, Field **aYdot, double shift,\n Mat J, Mat P, PatternCtx *user) {\n PetscErrorCode ierr;\n int i, j, s, c;\n const double h = user->L / (double)(info->mx),\n Cu = user->Du / (6.0 * h * h),\n Cv = user->Dv / (6.0 * h * h);\n double val[9], CC;\n MatStencil col[9], row;\n\n for (j = info->ys; j < info->ys + info->ym; j++) {\n row.j = j;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n row.i = i;\n for (c = 0; c < 2; c++) { // u,v equations are c=0,1\n row.c = c;\n CC = (c == 0) ? Cu : Cv;\n for (s = 0; s < 9; s++)\n col[s].c = c;\n col[0].i = i; col[0].j = j;\n val[0] = shift + 20.0 * CC;\n col[1].i = i-1; col[1].j = j; val[1] = - 4.0 * CC;\n col[2].i = i+1; col[2].j = j; val[2] = - 4.0 * CC;\n col[3].i = i; col[3].j = j-1; val[3] = - 4.0 * CC;\n col[4].i = i; col[4].j = j+1; val[4] = - 4.0 * CC;\n col[5].i = i-1; col[5].j = j-1; val[5] = - CC;\n col[6].i = i-1; col[6].j = j+1; val[6] = - CC;\n col[7].i = i+1; col[7].j = j-1; val[7] = - CC;\n col[8].i = i+1; col[8].j = j+1; val[8] = - CC;\n ierr = MatSetValuesStencil(P,1,&row,9,col,val,INSERT_VALUES); CHKERRQ(ierr);\n }\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//ENDIJACOBIAN\n\n", "meta": {"hexsha": "c15d0152a9e43788fc3a4c6d64b0104faafb67be", "size": 10521, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/pattern.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/pattern.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/pattern.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.9163346614, "max_line_length": 98, "alphanum_fraction": 0.5505180116, "num_tokens": 3530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6419093637342772}} {"text": "//\n// Created by peixinho on 19/12/16.\n//\n\n#include \n#include \n#include \n\nMlMatrix* ml_create_matrix(size_t nrow, size_t ncol) {\n MlMatrix* m = NULL;\n m = ml_alloc(MlMatrix);\n m->nrows = nrow;\n m->ncols = ncol;\n m->n = nrow*ncol;\n m->data = ml_alloc_array(m->n, float);\n return m;\n}\n\nvoid mlMultMatrixIp(MlMatrix* A, MlMatrix* B, MlMatrix* M) {\n double alpha = 1.0, beta = 0.0;\n\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->nrows, B->ncols, \\\n A->ncols, alpha, A->data, A->ncols, B->data, B->ncols, beta, \\\n M->data, B->ncols);\n}\n\nMlMatrix* mlMultMatrix(MlMatrix* A, MlMatrix* B) {\n MlMatrix* M = ml_create_matrix(B->ncols, A->nrows);\n mlMultMatrixIp(A, B, M);\n return M;\n}\n\nfloat mlMeanMatrix(MlMatrix* m) {\n float mean = 0.0f;\n for (int i = 0; i < m->n; ++i) {\n mean += m->data[i] / m->n;\n }\n return mean;\n}\n\nMlMatrix* mlMatrixSumCol(MlMatrix* m) {\n MlMatrix* sum = ml_create_matrix(1, m->ncols);\n\n for (int i = 0; i < m->nrows; ++i) {\n for (int j = 0; j < m->ncols; ++j) {\n ml_mat_elem(sum, 0, j) += ml_mat_elem(m, i, j);\n }\n }\n\n return sum;\n}\n\nvoid ml_set_matrix(MlMatrix *m, float val) {\n for (int i = 0; i < m->n; ++i)\n m->data[i] = val;\n}\n\nvoid ml_free_matrix(MlMatrix *m) {\n ml_free(m->data);\n ml_free(m);\n}\n\nvoid ml_print_matrix(MlMatrix *m) {\n printf(\"[\");\n for (int r = 0; r < m->nrows; ++r) {\n printf(\"[\");\n for (int c = 0; c < m->ncols; ++c) {\n printf(\"%4.2f\", ml_mat_elem(m, r, c));\n if(c < m->ncols-1)\n printf(\", \");\n }\n printf(\"]\");\n if(rnrows-1)\n printf(\"\\n\");\n }\n printf(\"]\\n\");\n}\n", "meta": {"hexsha": "6fa07ba471da7eabc68399dfe8c0c726d31a6530", "size": 1769, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ml_matrix.c", "max_stars_repo_name": "alanpeixinho/lib-machine-learning", "max_stars_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4", "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/ml_matrix.c", "max_issues_repo_name": "alanpeixinho/lib-machine-learning", "max_issues_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4", "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/ml_matrix.c", "max_forks_repo_name": "alanpeixinho/lib-machine-learning", "max_forks_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4", "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.6794871795, "max_line_length": 80, "alphanum_fraction": 0.5262860373, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6416559893340756}} {"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 PetscReal D0; // conductivity\n} HeatCtx;\n\nstatic PetscReal f_source(PetscReal x, PetscReal y) {\n return 3.0 * PetscExpReal(-25.0 * (x-0.6) * (x-0.6))\n * PetscSinReal(2.0*PETSC_PI*y);\n}\n\nstatic PetscReal gamma_neumann(PetscReal y) {\n return PetscSinReal(6.0 * PETSC_PI * y);\n}\n\nextern PetscErrorCode Spacings(DMDALocalInfo*, PetscReal*, PetscReal*);\nextern PetscErrorCode EnergyMonitor(TS, PetscInt, PetscReal, Vec, void*);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal, PetscReal**,\n PetscReal**, HeatCtx*);\nextern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, PetscReal, PetscReal**,\n Mat, Mat, HeatCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n HeatCtx user;\n TS ts;\n Vec u;\n DM da;\n DMDALocalInfo info;\n PetscReal t0, tf;\n PetscBool monitorenergy = PETSC_FALSE;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\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, PetscReal *hx, PetscReal *hy) {\n if (hx) *hx = 1.0 / (PetscReal)(info->mx-1);\n if (hy) *hy = 1.0 / (PetscReal)(info->my); // periodic direction\n return 0;\n}\n\n//STARTMONITOR\nPetscErrorCode EnergyMonitor(TS ts, PetscInt step, PetscReal time, Vec u,\n void *ctx) {\n PetscErrorCode ierr;\n HeatCtx *user = (HeatCtx*)ctx;\n PetscReal lenergy = 0.0, energy, dt, hx, hy, **au;\n PetscInt 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,MPIU_REAL,MPIU_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 PetscReal t, PetscReal **au,\n PetscReal **aG, HeatCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j, mx = info->mx;\n PetscReal 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 PetscReal t, PetscReal **au,\n Mat J, Mat P, HeatCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j, ncols;\n const PetscReal D = user->D0;\n PetscReal 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": "14129d6a45631dd80feeee0364de1c56e2a0574c", "size": 8220, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/heat.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/heat.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/heat.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": 38.7735849057, "max_line_length": 91, "alphanum_fraction": 0.5781021898, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6416559789094006}} {"text": "/* sys/pow_int.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n#include \n#include \n#include \n\n#ifndef HIDE_INLINE_STATIC\ndouble gsl_pow_2(const double x) { return x*x; }\ndouble gsl_pow_3(const double x) { return x*x*x; }\ndouble gsl_pow_4(const double x) { double x2 = x*x; return x2*x2; }\ndouble gsl_pow_5(const double x) { double x2 = x*x; return x2*x2*x; }\ndouble gsl_pow_6(const double x) { double x2 = x*x; return x2*x2*x2; }\ndouble gsl_pow_7(const double x) { double x3 = x*x*x; return x3*x3*x; }\ndouble gsl_pow_8(const double x) { double x2 = x*x; double x4 = x2*x2; return x4*x4; }\ndouble gsl_pow_9(const double x) { double x3 = x*x*x; return x3*x3*x3; }\n#endif\n\ndouble gsl_pow_int(double x, int n)\n{\n double value = 1.0;\n\n if(n < 0) {\n x = 1.0/x;\n n = -n;\n }\n\n /* repeated squaring method \n * returns 0.0^0 = 1.0, so continuous in x\n */\n do {\n if(n & 1) value *= x; /* for n odd */\n n >>= 1;\n x *= x;\n } while (n);\n\n return value;\n}\n\n", "meta": {"hexsha": "ebcb0c7e2df1186a012321f73eeb4b35e0d97bba", "size": 1750, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/sys/pow_int.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/sys/pow_int.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/sys/pow_int.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": 31.8181818182, "max_line_length": 88, "alphanum_fraction": 0.6685714286, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6415123549961486}} {"text": "#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \"ccl.h\"\n\n\n/****************************************************************\n\nThis is the famous FFTLog.\n\nFirst imlplemented by the living legend Andrew Hamilton:\n\nhttp://casa.colorado.edu/~ajsh/FFTLog/\n\nThis version is a C version that was adapted from the C++ version found\nin Copter JWG Carlson, another big loss for the cosmology community.\n\nhttps://github.com/jwgcarlson/Copter\n\nI've transformed this from C++ to C99 as the lowest common denominator\nand provided bindings for C++ and python.\n\nThese are the C++ bindings\n\n*****************************************************************/\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n#ifndef M_LN2\n#define M_LN2 0.69314718056\n#endif\n/* This code is FFTLog, which is described in arXiv:astro-ph/9905191 */\n\nstatic double complex lngamma_fftlog(double complex z)\n{\n gsl_sf_result lnr, phi;\n gsl_sf_lngamma_complex_e(creal(z), cimag(z), &lnr, &phi);\n return lnr.val + I*phi.val;\n}\n\nstatic double complex gamma_fftlog(double complex z)\n{\n return cexp(lngamma_fftlog(z));\n}\n\nstatic double complex polar (double r, double phi)\n{\n return (r*cos(phi) +I*(r*sin(phi)));\n}\n\nstatic void lngamma_4(double x, double y, double* lnr, double* arg)\n{\n double complex w = lngamma_fftlog(x+y*I);\n if(lnr) *lnr = creal(w);\n if(arg) *arg = cimag(w);\n}\n\nstatic double goodkr(int N, double mu, double q, double L, double kr)\n{\n double xp = (mu+1+q)/2;\n double xm = (mu+1-q)/2;\n double y = M_PI*N/(2*L);\n double lnr, argm, argp;\n lngamma_4(xp, y, &lnr, &argp);\n lngamma_4(xm, y, &lnr, &argm);\n double arg = log(2/kr) * N/L + (argp + argm)/M_PI;\n double iarg = round(arg);\n if(arg != iarg)\n kr *= exp((arg - iarg)*L/N);\n return kr;\n}\n\n/* Pre-compute the coefficients that appear in the FFTLog implementation of\n * the discrete Hankel transform. The parameters N, mu, and q here are the\n * same as for the function fht(). The parameter L is defined (for whatever\n * reason) to be N times the logarithmic spacing of the input array, i.e.\n * L = N * log(r[N-1]/r[0])/(N-1) */\nstatic void compute_u_coefficients(int N, double mu, double q, double L, double kcrc, double complex *u)\n{\n double y = M_PI/L;\n double k0r0 = kcrc * exp(-L);\n double t = -2*y*log(k0r0/2);\n\n if(q == 0) {\n double x = (mu+1)/2;\n double lnr, phi;\n for(int m = 0; m <= N/2; m++) {\n lngamma_4(x, m*y, &lnr, &phi);\n u[m] = polar(1.0,m*t + 2*phi);\n }\n }\n else {\n double xp = (mu+1+q)/2;\n double xm = (mu+1-q)/2;\n double lnrp, phip, lnrm, phim;\n for(int m = 0; m <= N/2; m++) {\n lngamma_4(xp, m*y, &lnrp, &phip);\n lngamma_4(xm,-m*y, &lnrm, &phim);\n u[m] = polar(exp(q*M_LN2 + lnrp - lnrm), m*t + phip - phim);\n }\n }\n\n for(int m = N/2+1; m < N; m++)\n u[m] = conj(u[N-m]);\n if((N % 2) == 0)\n u[N/2] = (creal(u[N/2]) + I*0.0);\n}\n\n/* Compute the discrete Hankel transform of the function a(r). See the FFTLog\n * documentation (or the Fortran routine of the same name in the FFTLog\n * sources) for a description of exactly what this function computes.\n * If u is NULL, the transform coefficients will be computed anew and discarded\n * afterwards. If you plan on performing many consecutive transforms, it is\n * more efficient to pre-compute the u coefficients. */\nstatic void fht(int npk, int N,\n\t\tdouble *k, double **pk,\n\t\tdouble *r, double **xi,\n\t\tdouble dim, double mu, double q, double kcrc,\n\t\tint noring, double complex* u, int *status)\n{\n fftw_plan forward_plan, reverse_plan;\n double L = log(k[N-1]/k[0]) * N/(N-1.);\n double complex* ulocal = NULL;\n if(u == NULL) {\n if(noring)\n kcrc = goodkr(N, mu, q, L, kcrc);\n\n ulocal = malloc (sizeof(complex double)*N);\n if(ulocal==NULL)\n *status=CCL_ERROR_MEMORY;\n\n if(*status == 0) {\n compute_u_coefficients(N, mu, q, L, kcrc, ulocal);\n u = ulocal;\n }\n }\n\n fftw_complex* a_tmp;\n fftw_complex* b_tmp;\n if(*status == 0) {\n a_tmp = fftw_alloc_complex(N);\n if(a_tmp==NULL)\n *status=CCL_ERROR_MEMORY;\n }\n if(*status == 0) {\n b_tmp = fftw_alloc_complex(N);\n if(b_tmp==NULL)\n *status=CCL_ERROR_MEMORY;\n }\n\n if(*status == 0) {\n /* Compute the convolution b = a*u using FFTs */\n forward_plan = fftw_plan_dft_1d(N,\n (fftw_complex*) a_tmp,\n (fftw_complex*) b_tmp,\n -1, FFTW_ESTIMATE);\n reverse_plan = fftw_plan_dft_1d(N,\n (fftw_complex*) b_tmp,\n (fftw_complex*) b_tmp,\n +1, FFTW_ESTIMATE);\n }\n\n if(*status == 0) {\n #pragma omp parallel default(none) \\\n shared(npk, N, k, pk, r, xi, \\\n dim, mu, q, kcrc, u, status, \\\n forward_plan, reverse_plan, \\\n L, ulocal)\n {\n int local_status = 0;\n\n double *prefac_pk=NULL;\n if(local_status == 0) {\n prefac_pk = malloc(N*sizeof(double));\n if(prefac_pk==NULL)\n local_status=CCL_ERROR_MEMORY;\n }\n\n double *prefac_xi=NULL;\n if(local_status == 0) {\n prefac_xi = malloc(N*sizeof(double));\n if(prefac_xi==NULL)\n local_status=CCL_ERROR_MEMORY;\n }\n\n fftw_complex* a=NULL;\n fftw_complex* b=NULL;\n if(local_status == 0) {\n a = fftw_alloc_complex(N);\n if(a==NULL)\n local_status=CCL_ERROR_MEMORY;\n }\n\n if(local_status == 0) {\n b = fftw_alloc_complex(N);\n if(b==NULL)\n local_status=CCL_ERROR_MEMORY;\n }\n\n if(local_status == 0) {\n for(int i = 0; i < N; i++)\n prefac_pk[i] = pow(k[i], dim/2-q);\n\n /* Compute k's corresponding to input r's */\n double k0r0 = kcrc * exp(-L);\n r[0] = k0r0/k[0];\n for(int n = 1; n < N; n++)\n r[n] = r[0] * exp(n*L/N);\n\n double one_over_2pi_dhalf = pow(2*M_PI,-dim/2);\n for(int i = 0; i < N; i++)\n prefac_xi[i] = one_over_2pi_dhalf * pow(r[i], -dim/2-q);\n\n #pragma omp for\n for(int j = 0; j < npk; j++) {\n for(int i = 0; i < N; i++)\n a[i] = prefac_pk[i] * pk[j][i];\n\n fftw_execute_dft(forward_plan,a,b);\n for(int m = 0; m < N; m++)\n b[m] *= u[m] / (double)(N); // divide by N since FFTW doesn't normalize the inverse FFT\n fftw_execute_dft(reverse_plan,b,b);\n\n /* Reverse b array */\n double complex tmp;\n for(int n = 0; n < N/2; n++) {\n tmp = b[n];\n b[n] = b[N-n-1];\n b[N-n-1] = tmp;\n }\n\n for(int i = 0; i < N; i++)\n xi[j][i] = prefac_xi[i] * creal(b[i]);\n }\n }\n\n free(prefac_pk);\n free(prefac_xi);\n fftw_free(a);\n fftw_free(b);\n\n if (local_status) {\n #pragma omp atomic write\n *status = local_status;\n }\n } //end omp parallel\n }\n\n if(*status == 0) {\n fftw_destroy_plan(forward_plan);\n fftw_destroy_plan(reverse_plan);\n }\n\n free(ulocal);\n //TODO: free this up\n fftw_free(a_tmp);\n fftw_free(b_tmp);\n}\n \nvoid ccl_fftlog_ComputeXi2D(double mu, double epsilon,\n\t\t\t int npk, int N, double *l,double **cl,\n\t\t\t double *th, double **xi, int *status)\n{\n fht(npk, N, l, cl, th, xi, 2., mu, epsilon, 1, 1, NULL, status);\n}\n\nvoid ccl_fftlog_ComputeXi3D(double l, double epsilon,\n\t\t\t int npk, int N, double *k, double **pk,\n\t\t\t double *r, double **xi, int *status)\n{\n fht(npk, N, k, pk, r, xi, 3., l+0.5, epsilon, 1, 1, NULL, status);\n}\n", "meta": {"hexsha": "8a6e1539917d3b71953c80e36d1372d4fe9678e8", "size": 7755, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_fftlog.c", "max_stars_repo_name": "timothydmorton/CCL", "max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_fftlog.c", "max_issues_repo_name": "timothydmorton/CCL", "max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_forks_repo_path": "src/ccl_fftlog.c", "max_forks_repo_name": "timothydmorton/CCL", "max_forks_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7956989247, "max_line_length": 105, "alphanum_fraction": 0.5586073501, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888291, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6414145333074555}} {"text": "#include \n#include \n#include \n#include \n\nint\nmain ()\n{\n size_t i,j;\n\n gsl_matrix *m = gsl_matrix_alloc (10, 10);\n\n for (i = 0; i < 10; i++)\n for (j = 0; j < 10; j++)\n gsl_matrix_set (m, i, j, sin (i) + cos (j));\n\n for (j = 0; j < 10; j++)\n {\n gsl_vector_view column = gsl_matrix_column (m, j);\n double d;\n\n d = gsl_blas_dnrm2 (&column.vector);\n\n printf (\"matrix column %d, norm = %g\\n\", j, d);\n }\n\n gsl_matrix_free (m);\n}\n", "meta": {"hexsha": "d4a8473732ac26c3027d5136c7ce3c439a52ac05", "size": 512, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/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/matrix/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/matrix/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": 17.6551724138, "max_line_length": 56, "alphanum_fraction": 0.546875, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6411071560311022}} {"text": "/*This program is the first step in solving the Merlin-Salgado equation.\nIt produces a .dat file with the scale factor in terms of the conformal time and the cosmic time.\nThe .dat file columns are formatted in the next way:\ncosmic_time conformal_fime scale_factor cosmic_time_der_scale_factor*/\n\n#include \n#include \n#include \n#include \n#include \n\n\n#define NLINES 11\n#define H0 0.1 //Hubble paramater\n#define OMEGAMAT 0.3 //Omega matter\n#define OMEGALAM 0.7 //Omega lambda\n\n/*Structure with parameters needed for the function to integrate\nhubble: The Hubble parameter\nomega_m: Density parameter for matter (dark matter and baryonic)\nomega_l: Density parameter for dark energy*/\nstruct Iparams\n{\n double hubble;\n double omega_m;\n double omega_l;\n};\n\n/*This function multiplied by the differential of the scale factor is the differential of cosmic time*/\ndouble integrando_cosmictime(double a, void *parameters)\n{\n struct Iparams *p = (struct Iparams *) parameters; //Structure of parameters\n \n double h0 = p->hubble;\n double om = p->omega_m;\n double ol = p->omega_l;\n double f = (1/h0)/(sqrt(om*pow(a,-1) + ol*pow(a,2))); //Integrate to cosmic time\n \n return f;\n}\n\n/*This function multiplied by the differential of the scale factor is the differential of conformal time*/\ndouble integrando_conformaltime(double a, void *parameters)\n{\n struct Iparams *p = (struct Iparams *) parameters; //Structure of parameters\n \n double h0 = p->hubble;\n double om = p->omega_m;\n double ol = p->omega_l;\n double f = (1/h0)/(sqrt(om*a + ol*pow(a,4))); //Integrate to conformal time\n \n return f;\n}\n\n/*Derivative of the scale factor as a function of scale factor*/\ndouble der_scale_factor(double a)\n{\n double adot = H0*sqrt(OMEGAMAT*pow(a,-1)+OMEGALAM*pow(a,2));\n return adot;\n}\n\nint main (void)\n{\n /*Variable for temporary saving derivative of scale factor in interations*/\n double adot;\n\n struct Iparams parameters; // Structure of parameters for functions to integrate\n /*Asign values to the structure of parameters*/\n parameters.hubble = H0;\n parameters.omega_m = OMEGAMAT;\n parameters.omega_l = OMEGALAM;\n\n /*File to be written with data*/\n FILE *pf;\n pf = fopen(\"scale_factor.dat\",\"w\");\n\n /*GSL object. Necessary object to separate enough space in memory for integration. 1 and 2 refer to cosmic and conformal time respectively*/\n gsl_integration_workspace *w1;\n gsl_integration_workspace *w2;\n \n /*result: Result of integration. error: Maximum relative error. 1 and 2 refer to cosmic and conformal time respectively*/\n double result1, result2, error1, error2, epsrel = 1.0e-11;\n size_t limit = 1000; //Maximum number of subintervals for integration\n /*a: Inferior integration limit. b: Superior integration limit*/\n double a = 0.0, b = 0.0;\n\n /*GSL object. Contain all information about the integrand.*/\n gsl_function Fcosmic, Fconformal;\n /*Defining Fcosmic*/\n Fcosmic.function = &integrando_cosmictime;\n Fcosmic.params = ¶meters;\n /*Defining Fconformal*/\n Fconformal.function = &integrando_conformaltime;\n Fconformal.params = ¶meters;\n\n /*Allocate space in memory*/\n w1 = gsl_integration_workspace_alloc(limit);\n w2 = gsl_integration_workspace_alloc(limit);\n\n for(b = 0.0001;b <= 1.0;b += 0.0001)\n {\n /*Numerical integration of functions*/\n gsl_integration_qags(&Fcosmic, a, b, 0, epsrel, limit, w1, &result1, &error1);\n gsl_integration_qags(&Fconformal, a, b, 0, epsrel, limit, w2, &result2, &error2);\n adot = der_scale_factor(b);\n fprintf(pf, \"%.12f %.12f %.12f %.12f\\n\", result1, result2, b, adot);\n }\n\n /*Close streams and free space in memory*/\n fclose(pf);\n gsl_integration_workspace_free(w1);\n gsl_integration_workspace_free(w2);\n}\n", "meta": {"hexsha": "b4b0a3a47866bdbded83e16e74f31fba1ae1ed36", "size": 3810, "ext": "c", "lang": "C", "max_stars_repo_path": "scale_factor.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": "scale_factor.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": "scale_factor.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": 33.4210526316, "max_line_length": 142, "alphanum_fraction": 0.7225721785, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6410138231709459}} {"text": "/*\n obtainerr2_par.c\n written by Eunseok Lee\n \n function: solve a linear equation system and obtain the squared error\n \n v1: Feb 2, 2018\n */\n\n#include \n#include \n#include \n//#include \n#include \n#include \n#include \n\ndouble obtainerr2_par(int row_ini, int row_end, double *matA, int n_row, int n_col, int *col_ids, int n_col_ids, double *y) {\n \n int i, j, k, tmp;\n double err[n_row];\n double sum;\n \n gsl_matrix * A = gsl_matrix_alloc (n_row-1,n_col_ids);\n gsl_matrix * V = gsl_matrix_alloc (n_col_ids,n_col_ids);\n gsl_vector * S = gsl_vector_alloc (n_col_ids);\n gsl_vector * work = gsl_vector_alloc (n_col_ids);\n// gsl_matrix * U = gsl_matrix_alloc (n_row-1,n_col_ids);\n gsl_vector * b = gsl_vector_alloc (n_row-1);\n gsl_vector * x = gsl_vector_alloc (n_col_ids);\n \n for (i=0;i\n#include \n#include \n#include \n\n#define REAL(z,i) ((z)[2*(i)])\n#define IMAG(z,i) ((z)[2*(i)+1])\n\nint\nmain (void)\n{\n int i;\n const int n = 630;\n double data[2*n];\n\n gsl_fft_complex_wavetable * wavetable;\n gsl_fft_complex_workspace * workspace;\n\n for (i = 0; i < n; i++)\n {\n REAL(data,i) = 0.0;\n IMAG(data,i) = 0.0;\n }\n\n data[0] = 1.0;\n\n for (i = 1; i <= 10; i++)\n {\n REAL(data,i) = REAL(data,n-i) = 1.0;\n }\n\n for (i = 0; i < n; i++)\n {\n printf (\"%d: %e %e\\n\", i, REAL(data,i), \n IMAG(data,i));\n }\n printf (\"\\n\");\n\n wavetable = gsl_fft_complex_wavetable_alloc (n);\n workspace = gsl_fft_complex_workspace_alloc (n);\n\n for (i = 0; i < (int) wavetable->nf; i++)\n {\n printf (\"# factor %d: %zu\\n\", i, \n wavetable->factor[i]);\n }\n\n gsl_fft_complex_forward (data, 1, n, \n wavetable, workspace);\n\n for (i = 0; i < n; i++)\n {\n printf (\"%d: %e %e\\n\", i, REAL(data,i), \n IMAG(data,i));\n }\n\n gsl_fft_complex_wavetable_free (wavetable);\n gsl_fft_complex_workspace_free (workspace);\n return 0;\n}\n", "meta": {"hexsha": "b12dc7669af4c0972aee4d206291946519f4be24", "size": 1227, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/fftmr.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/fftmr.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/fftmr.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 20.1147540984, "max_line_length": 50, "alphanum_fraction": 0.5093724531, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6404528704528111}} {"text": "//\n// symm.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 1/2/12.\n// Copyright (c) 2012 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _symm_h\n#define _symm_h\n\n/// @file symm.h Performs general symmetric matrix-matrix multiplication.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs general real symmetric matrix-matrix multiplication.\n ///\n /// For real matrices B and C, symmetric matrix A, and real scalars alpha and beta,\n ///\n /// C := alpha*A*B + beta*C or C := alpha*B*A + beta*C \n /// is computed.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param side Specifies whether the matrix A appears on the left or right side as follows:\n ///\n /// if side = 'L' or 'l' then C := alpha*A*B + beta*C,\n /// if side = 'R' or 'r' then C := alpha*B*A + beta*C.\n /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix A\n /// is to be referenced: \n ///\n /// if uplo = 'U' or 'u' then A is upper triangular,\n /// if uplo = 'L' or 'l' then A is lower triangular.\n /// @param m Specifies the number of rows of the matrices B and C. m>=0\n /// @param n Specifies the number of columns of the matrices B and C. n>=0\n /// @param alpha Real scalar.\n /// @param A Pointer to real symmetric matrix A. If side = 'L' or 'l', then A is m-by-m;\n /// if side = 'R' or 'r', then A is n-by-n.\n /// @param ldA Column length of the matrix A. If side = 'L' or 'l', ldA>=m. If side = 'R' or 'r', ldA>=n.\n /// @param B Pointer to real m-by-n matrix B.\n /// @param ldB Column length of the matrix B. ldB>=m.\n /// @param beta Real scalar.\n /// @param C Pointer to real m-by-n matrix C.\n /// @param ldC Column length of the matrix C. ldC>=m.\n /// @ingroup BLAS\n\n template \n int SYMM(char side, char uplo, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC)\n {\n using std::toupper;\n\n const real_t zero(0.0);\n const real_t one(1.0);\n int_t i,j,k;\n real_t *a,*b,*c,*at,*bt;\n real_t s,t;\n\n side=toupper(side);\n uplo=toupper(uplo);\n \n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(ldA<((side=='L')?m:n))\n return -7;\n else if(ldB=0;i--)\n {\n a-=ldA;\n t=alpha*b[i];\n s=zero;\n for(k=i+1;k=0\n /// @param n Specifies the number of columns of the matrices B and C. n>=0\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex symmetric matrix A. If side = 'L' or 'l', then A is m-by-m;\n /// if side = 'R' or 'r', then A is n-by-n.\n /// @param ldA Column length of the matrix A. If side = 'L' or 'l', ldA>=m. If side = 'R' or 'r', ldA>=n.\n /// @param B Pointer to complex m-by-n matrix B.\n /// @param ldB Column length of the matrix B. ldB>=m.\n /// @param beta Complex scalar.\n /// @param C Pointer to complex m-by-n matrix C.\n /// @param ldC Column length of the matrix C. ldC>=m.\n /// @ingroup BLAS\n\n template \n int SYMM(char side, char uplo, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n return SYMM< complex >(side,uplo,m,n,alpha,A,ldA,B,ldB,beta,C,ldC);\n }\n\n#ifdef __latl_cblas\n#include \n template <> int SYMM(char side, char uplo, int_t m, int_t n, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(ldA<((side=='L')?m:n))\n return -7;\n else if(ldB int SYMM(char side, char uplo, int_t m, int_t n, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(ldA<((side=='L')?m:n))\n return -7;\n else if(ldB int SYMM(char side, char uplo, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(ldA<((side=='L')?m:n))\n return -7;\n else if(ldB int SYMM(char side, char uplo, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(ldA<((side=='L')?m:n))\n return -7;\n else if(ldB\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(\"gsl_interp_steffen.txt\", \"w\");\n\n dx = (b-a) / (double) steps;\n\n for (i = 0; i <= steps; ++i) {\n\t 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\n = gsl_interp_accel_alloc ();\n\n gsl_spline *spline\n = gsl_spline_alloc (gsl_interp_steffen, steps + 1);\n\n gsl_spline_init (spline, x, y, steps + 1);\n\n for (xi = a; xi <= b; xi += 0.01) {\n yi = gsl_spline_eval (spline, xi, acc);\n fprintf (output,\"%g %g\\n\", xi, yi);\n\t}\n\n gsl_spline_free (spline);\n gsl_interp_accel_free(acc);\n }\n return 0;\n}\n\n//Porownanie roznych interpolacji\n//Opisanie komend, screeny\n\n//https://stackoverflow.com/questions/10792015/gnuplot-plotting-multiple-line-graphs\n//https://stackoverflow.com/questions/40296851/gnuplot-log-plot-y-axis\n//http://lowrank.net/gnuplot/plot3d2-e.html\n//http://gnuplot-surprising.blogspot.com/2012/05/how-to-pick-out-maximum-and-minimum.html\n//http://gnuplot.sourceforge.net/docs_4.2/node237.html\n//http://gnuplot.sourceforge.net/demo/stats.html\n\n// stats \"dane2.dat\" u 3 nooutput\n// set label 1 \"Maximun\" at STATS_pos_max, STATS_max offset 1,-0.5\n// set label 2 \"Minimun\" at STATS_pos_min, STATS_min offset 1,0.5\n// splot \"dane2.dat\" w p pt 3 lc rgb\"#ff0000\" notitle, \\\n// STATS_min w l lc rgb\"#00ffff\" notitle, \\\n// STATS_max w l lc rgb\"#00ffff\" notitle\n\nstats \"dane2.dat\" u 1:3 nooutput\na = STATS_pos_max_y\nstats \"dane2.dat\" u 2:3 nooutput\nb = STATS_pos_max_y\nstats \"dane2.dat\" u 3 nooutput\nc = STATS_max\nset arrow 1 from -5, -2.1, c+5 to a,b,c fill\nsplot \"dane2.dat\" w p pt 3 lc rgb\"#ff0000\" notitle, \\\n STATS_min w l lc rgb\"#00ffff\" notitle, \\\n STATS_max w l lc rgb\"#00ffff\" notitle\n\nn=100\nmax=3.\nmin=-3.\nwidth=(max-min)/n\nhist(x,width)=width*floor(x/width)+width/2.0\nset xrange [min:max]\nset yrange[-5:5]\nset offset graph 0.05,0.05,0.05,0.0\nset xtics min,(max-min)/5,max\nset boxwidth width*0.82\nset tics out nomirror\nset xlabel \"x\"\nset ylabel \"Frequency\"\nplot 2*cos(x*sin(x)) smooth freq w boxes lc rgb\"blue\", \\\n sin (x**5) lt rgb\"#00ff00\", \\\n 3*sin(x) lt rgb\"red\", \\\n \"fun1.txt\" with yerrorbars lt rgb\"red\"", "meta": {"hexsha": "5bcf894dab5d501d101b6239f8dd34fcce255438", "size": 2629, "ext": "c", "lang": "C", "max_stars_repo_path": "zad2/interpolacja.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": "zad2/interpolacja.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": "zad2/interpolacja.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": 26.8265306122, "max_line_length": 89, "alphanum_fraction": 0.6538607836, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6395109878434878}} {"text": "static const char help[] =\n\"Solves elasto-plastic torsion problem in 2D using SNESVI. Option prefix -el_.\\n\"\n\"Equation is - grad^2 u = f(x,y) where f(x,y) = 2 C. Zero Dirichlet\\n\"\n\"boundary conditions. Domain Omega = (0,1)x(0,1). Constraint is upper bound\\n\"\n\" u(x,y) <= dist((x,y), bdry Omega) = psi(x,y).\\n\"\n\"At locations where the constraint is active, the material experiences plastic\\n\"\n\"failure. Where inactive, the equation represents the elasticity. As with\\n\"\n\"related codes ../obstacle.c and dam.c the code reuses the residual and\\n\"\n\"Jacobian evaluation code from ch6/.\\n\"\n\"Reference: R. Kornhuber (1994) 'Monotone multigrid methods for elliptic\\n\"\n\"variational inequalities I', Numerische Mathematik, 69(2), 167-184.\\n\\n\";\n\n#include \n#include \"../../ch6/poissonfunctions.h\"\n\n// z = psi(x,y) = dist((x,y), bdry Omega) is the upper obstacle\ndouble psi(double x, double y) {\n if (y <= x)\n if (y <= 1.0 - x)\n return y;\n else\n return 1.0 - x;\n else\n if (y <= 1.0 - x)\n return x;\n else\n return 1.0 - y;\n}\n\ndouble zero(double x, double y, double z, void *ctx) {\n return 0.0;\n}\n\nstatic double C = 2.5;\ndouble f_fcn(double x, double y, double z, void *ctx) {\n return 2.0 * C;\n}\n\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 Vec u_initial, u;\n PoissonCtx user;\n SNESConvergedReason reason;\n int snesits;\n double lflops,flops;\n DMDALocalInfo info;\n\n PetscInitialize(&argc,&argv,NULL,help);\n\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"el_\",\n \"elasto-plastic torsion solver options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-C\",\"f(x,y)=2C is source term\",\n \"elasto.c\",C,&C,NULL); 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,0.0,1.0,0.0,1.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 = &zero;\n user.f_rhs = &f_fcn;\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 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 = SNESSetFromOptions(snes);CHKERRQ(ierr);\n\n // initial iterate is zero\n ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr);\n ierr = VecSet(u_initial,0.0); CHKERRQ(ierr);\n\n /* solve; then get solution and 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\n /* 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,&snesits); CHKERRQ(ierr);\n ierr = PetscGetFlops(&lflops); CHKERRQ(ierr);\n ierr = MPI_Allreduce(&lflops,&flops,1,MPI_DOUBLE,MPI_SUM,PETSC_COMM_WORLD); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %4d x %4d grid; total flops = %.3e; SNES iterations %d\\n\",\n info.mx,info.my,flops,snesits); CHKERRQ(ierr);\n\n SNESDestroy(&snes);\n return PetscFinalize();\n}\n\n\n// for call-back: tell SNESVI we want -infty < u <= psi\nPetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {\n PetscErrorCode ierr;\n DM da;\n DMDALocalInfo info;\n int i, j;\n double **aXu, dx, dy, x, y;\n ierr = VecSet(Xu,PETSC_NINFINITY);CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da);CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n dx = 1.0 / (PetscReal)(info.mx-1);\n dy = 1.0 / (PetscReal)(info.my-1);\n ierr = DMDAVecGetArray(da, Xu, &aXu);CHKERRQ(ierr);\n for (j=info.ys; j\n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs multiplcation of real matrices resulting in a symmetric matrix.\n ///\n /// For real matrices A and B, real symmetric matrix C, and real scalars alpha and beta\n ///\n /// C := alpha*A*B'+alpha*B*A'+beta*C\n /// or\n ///\n /// C := alpha*A'*B+alpha*B'*A+beta*C\n /// is computed.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param uplo Specifies whether the upper or lower triangular part of the symmetric matrix C\n /// is to be referenced:\n ///\n /// if uplo = 'U' or 'u' then C is upper triangular,\n /// if uplo = 'L' or 'l' then C is lower triangular.\n /// @param trans Specifies the operation to be perfomed as follows:\n ///\n /// if trans = 'N' or 'n' then C := alpha*A*B'+alpha*B*A'+beta*C\n /// if trans = 'T' or 't' then C := alpha*A'*B+alpha*B'*A+beta*C\n /// if trans = 'C' or 'c' then C := alpha*A'*B+alpha*B'*A+beta*C\n /// @param n Specifies the order of the complex Hermitian matrix C. n>=0\n /// @param k Specifies the other dimension of the complex matrices A and B.\n ///\n /// if trans = 'N' or 'n' then A and B are n-by-k\n /// if trans = 'T' or 't' then A and B are k-by-n\n /// if trans = 'C' or 'c' then A and B are k-by-n\n /// @param alpha Real scalar.\n /// @param A Pointer to real matrix.\n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.\n /// @param B Pointer to real matrix.\n /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k.\n /// @param beta Real scalar.\n /// @param C Pointer to real symmetric n-by-n matrix C.\n /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.\n /// @param ldC Column length of the matrix C. ldC>=n\n /// @ingroup BLAS\n\n template \n int SYR2K(char uplo, char trans, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC)\n {\n using std::toupper;\n\n const real_t zero(0.0);\n const real_t one(1.0);\n int_t i,j,l;\n real_t *a,*b,*c,*at,*bt;\n real_t s,t;\n\n uplo=toupper(uplo);\n trans=toupper(trans);\n\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC=0\n /// @param k Specifies the other dimension of the complex matrices A and B.\n ///\n /// if trans = 'N' or 'n' then A and B are n-by-k\n /// if trans = 'T' or 't' then A and B are k-by-n\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex matrix.\n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.\n /// @param B Pointer to complex matrix.\n /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k.\n /// @param beta Complex scalar.\n /// @param C Pointer to complex symmetric n-by-n matrix C.\n /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.\n /// @param ldC Column length of the matrix C. ldC>=n\n /// @ingroup BLAS\n\n template \n int SYR2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::toupper;\n\n const complex zero(0.0,0.0);\n const complex one(1.0,0.0);\n int_t i,j,l;\n complex *a,*b,*c,*at,*bt;\n complex s,t;\n\n uplo=toupper(uplo);\n trans=toupper(trans);\n\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC\n\n template <> int SYR2K(char uplo, char trans, int_t n, int_t k, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC int SYR2K(char uplo, char trans, int_t n, int_t k, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC int SYR2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC int SYR2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='T'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC.\r\n (C) 2008 mlpy Developers.\r\n \r\n See DWT in the GSL Library.\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n*/\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nstatic PyObject *dwt_dwt(PyObject *self, PyObject *args, PyObject *keywds)\r\n{\r\n PyObject *x = NULL; PyObject *xcopy = NULL;\r\n \r\n char wf;\r\n int k, n;\r\n double *_xcopy;\r\n PyObject *centered = Py_False;\r\n gsl_wavelet *w;\r\n gsl_wavelet_workspace *work;\r\n\r\n /* Parse Tuple*/\r\n static char *kwlist[] = {\"x\", \"wf\", \"k\", \"centered\", NULL};\r\n if (!PyArg_ParseTupleAndKeywords(args, keywds, \"Oci|O\", kwlist,\r\n\t\t\t\t &x, &wf, &k, ¢ered))\r\n return NULL;\r\n\r\n /* Build xcopy */\r\n xcopy = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_OUT_ARRAY | NPY_ENSURECOPY);\r\n if (xcopy == NULL) return NULL;\r\n \r\n n = (int) PyArray_DIM(xcopy, 0);\r\n _xcopy = (double *) PyArray_DATA(xcopy);\r\n \r\n switch (wf)\r\n {\r\n case 'd':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_daubechies, k);\r\n break;\r\n \r\n case 'h':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_haar_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_haar, k);\r\n break;\r\n\r\n case 'b':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_bspline_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_bspline, k);\r\n break;\r\n\r\n default:\r\n PyErr_SetString(PyExc_ValueError, \"wavelet family is not valid\");\r\n return NULL;\r\n }\r\n \r\n work = gsl_wavelet_workspace_alloc (n);\r\n \r\n gsl_wavelet_transform_forward (w, _xcopy, 1, n, work);\r\n \r\n gsl_wavelet_free (w);\r\n gsl_wavelet_workspace_free (work);\r\n \r\n return Py_BuildValue(\"N\", xcopy);\r\n}\r\n\r\n\r\nstatic PyObject *dwt_idwt(PyObject *self, PyObject *args, PyObject *keywds)\r\n{\r\n PyObject *x = NULL; PyObject *xcopy = NULL;\r\n \r\n char wf;\r\n int k, n;\r\n double *_xcopy;\r\n PyObject *centered = Py_False;\r\n gsl_wavelet *w;\r\n gsl_wavelet_workspace *work;\r\n\r\n /* Parse Tuple*/\r\n static char *kwlist[] = {\"X\", \"wf\", \"k\", \"centered\", NULL};\r\n if (!PyArg_ParseTupleAndKeywords(args, keywds, \"Oci|O\", kwlist,\r\n\t\t\t\t &x, &wf, &k, ¢ered))\r\n return NULL;\r\n\r\n \r\n /* Build xcopy */\r\n xcopy = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_OUT_ARRAY | NPY_ENSURECOPY);\r\n if (xcopy == NULL) return NULL;\r\n \r\n n = (int) PyArray_DIM(xcopy, 0);\r\n _xcopy = (double *) PyArray_DATA(xcopy);\r\n \r\n switch (wf)\r\n {\r\n case 'd':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_daubechies, k);\r\n break;\r\n \r\n case 'h':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_haar_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_haar, k);\r\n break;\r\n\r\n case 'b':\r\n if (centered == Py_True)\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_bspline_centered, k);\r\n else\r\n\tw = gsl_wavelet_alloc (gsl_wavelet_bspline, k);\r\n break;\r\n\r\n default:\r\n PyErr_SetString(PyExc_ValueError, \"wavelet family is not valid\");\r\n return NULL;\r\n }\r\n \r\n work = gsl_wavelet_workspace_alloc (n);\r\n \r\n gsl_wavelet_transform_inverse (w, _xcopy, 1, n, work);\r\n \r\n gsl_wavelet_free (w);\r\n gsl_wavelet_workspace_free (work);\r\n \r\n return Py_BuildValue(\"N\", xcopy);\r\n}\r\n\r\n\r\n/* Doc strings: */\r\nstatic char module_doc[] = \"Discrete Wavelet Transform Module from GSL\";\r\n\r\nstatic char dwt_dwt_doc[] =\r\n \"Discrete Wavelet Tranform\\n\\n\"\r\n \":Parameters:\\n\"\r\n \" x : 1d array_like object (the length is restricted to powers of two)\\n\"\r\n \" data\\n\"\r\n \" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\\n\"\r\n \" wavelet family\\n\"\r\n \" k : integer\\n\"\r\n \" member of the wavelet family\\n\\n\"\r\n \" * daubechies : k = 4, 6, ..., 20 with k even\\n\"\r\n \" * haar : the only valid choice of k is k = 2\\n\"\r\n \" * bspline : k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\\n\"\r\n \" centered : bool\\n\"\r\n \" align the coefficients of the various sub-bands on edges.\\n\"\r\n \" Thus the resulting visualization of the coefficients of the\\n\"\r\n \" wavelet transform in the phase plane is easier to understand.\\n\\n\"\r\n \":Returns:\\n\"\r\n \" X : 1d numpy array\\n\"\r\n \" discrete wavelet transformed data\\n\\n\"\r\n \"Example\\n\\n\"\r\n \">>> import numpy as np\\n\"\r\n \">>> import mlpy.wavelet as wave\\n\"\r\n \">>> x = np.array([1,2,3,4,3,2,1,0])\\n\"\r\n \">>> wave.dwt(x=x, wf='d', k=6)\\n\"\r\n \"array([ 5.65685425, 3.41458985, 0.29185347, -0.29185347, -0.28310081,\\n\"\r\n \" -0.07045258, 0.28310081, 0.07045258])\\n\";\r\n\r\nstatic char dwt_idwt_doc[] =\r\n \"Inverse Discrete Wavelet Tranform\\n\\n\"\r\n \":Parameters:\\n\"\r\n \" X : 1d array_like object\\n\"\r\n \" discrete wavelet transformed data\\n\"\r\n \" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\\n\"\r\n \" wavelet type\\n\"\r\n \" k : integer\\n\"\r\n \" member of the wavelet family\\n\\n\"\r\n \" * daubechies : k = 4, 6, ..., 20 with k even\\n\"\r\n \" * haar : the only valid choice of k is k = 2\\n\"\r\n \" * bspline : k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\\n\\n\"\r\n \" centered : bool\\n\"\r\n \" if the coefficients are aligned\\n\\n\"\r\n \":Returns:\\n\"\r\n \" x : 1d numpy array\\n\"\r\n \" data\\n\\n\"\r\n \"Example:\\n\\n\"\r\n \">>> import numpy as np\\n\"\r\n \">>> import mlpy.wavelet as wave\\n\"\r\n \">>> X = np.array([ 5.65685425, 3.41458985, 0.29185347, -0.29185347, -0.28310081,\\n\"\r\n \"... -0.07045258, 0.28310081, 0.07045258])\\n\"\r\n \">>> wave.idwt(X=X, wf='d', k=6)\\n\"\r\n \"array([ 1.00000000e+00, 2.00000000e+00, 3.00000000e+00,\\n\"\r\n \" 4.00000000e+00, 3.00000000e+00, 2.00000000e+00,\\n\"\r\n \" 1.00000000e+00, -3.53954610e-09])\\n\";\r\n\r\n\r\n/* Method table */\r\nstatic PyMethodDef dwt_methods[] = {\r\n {\"dwt\",\r\n (PyCFunction)dwt_dwt,\r\n METH_VARARGS | METH_KEYWORDS,\r\n dwt_dwt_doc},\r\n {\"idwt\",\r\n (PyCFunction)dwt_idwt,\r\n METH_VARARGS | METH_KEYWORDS,\r\n dwt_idwt_doc},\r\n {NULL, NULL, 0, NULL}\r\n};\r\n\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\n\r\nstatic struct PyModuleDef moduledef = {\r\n PyModuleDef_HEAD_INIT,\r\n \"_dwt\",\r\n module_doc,\r\n -1,\r\n dwt_methods,\r\n NULL, NULL, NULL, NULL\r\n};\r\n\r\nPyObject *PyInit__dwt(void)\r\n{\r\n PyObject *m;\r\n m = PyModule_Create(&moduledef);\r\n if (!m) {\r\n return NULL;\r\n }\r\n\r\n import_array();\r\n\r\n return m;\r\n}\r\n\r\n#else\r\n\r\nPyMODINIT_FUNC init_dwt(void)\r\n{\r\n PyObject *m;\r\n \r\n m = Py_InitModule3(\"_dwt\", dwt_methods, module_doc);\r\n if (m == NULL) {\r\n return;\r\n }\r\n \r\n import_array();\r\n}\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "a06cd28c792e3888f559b8f1bbea049562952850", "size": 7448, "ext": "c", "lang": "C", "max_stars_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/dwt.c", "max_stars_repo_name": "xuanxiaoliqu/CRC4Docker", "max_stars_repo_head_hexsha": "5ee26f9a590b727693202d8ad3b6460970304bd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T12:02:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T12:02:08.000Z", "max_issues_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/dwt.c", "max_issues_repo_name": "TonyZPW/CRC4Docker", "max_issues_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/dwt.c", "max_forks_repo_name": "TonyZPW/CRC4Docker", "max_forks_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4833948339, "max_line_length": 89, "alphanum_fraction": 0.6078141783, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6391890323076618}} {"text": "#include \n#include \n#include \n#include \n#include \n\n//DEFINES\n#define SUCCESS 1\n#define FAILURE -1\n#define PROGRESS \"====================\"\n#define PRG_WIDTH 20\n\n//FUNCTIONS DECLARATION\nint dcca_comp(double *, double *, double *, int, int, int, int, double *, int);\nint rows_number(char *);\ndouble mean(double *, int, int);\nvoid cumsum(double *, double *, int);\nvoid slice_vec(double *, double *, int, int);\nvoid polynomialFit(int, int, double *, double *, double *);\n\n//MAIN\nint main(int argc, char **argv)\n{\n //inputs\n int input_args = 7;\n if(argc < input_args){\n printf(\"Not enough input arguments!\\n\");\n return FAILURE;\n }else if(argc > input_args){\n printf(\"Too many input arguments!\\n\");\n return FAILURE;\n }\n char file_name1[255]; //path+name for the first file\n memset(file_name1, 0x00, sizeof(file_name1));\n sprintf(file_name1, \"%s\", argv[1]);\n char file_name2[255]; //path+name for the second file\n memset(file_name2, 0x00, sizeof(file_name2));\n sprintf(file_name2, \"%s\", argv[2]);\n int smallest_win_size = atoi(argv[3]); //minimum size for the sliding window\n int biggest_win_num = atoi(argv[4]); //number of windows in the last step\n int pol_ord = atoi(argv[5]); //polynomial order for fit\n char path_out[255]; //path+name for the output file\n memset(path_out, 0x00, sizeof(path_out));\n sprintf(path_out, \"%s/rho_mw=%d_Mw=%d_pol=%d.txt\", argv[6], smallest_win_size, biggest_win_num, pol_ord);\n //files length\n int N1 = rows_number(file_name1);\n if(N1 == FAILURE){\n printf(\"Cannot open input file (1).\\n\");\n return FAILURE;\n }\n int N2 = rows_number(file_name2);\n if(N2 == FAILURE){\n printf(\"Cannot open input file (2).\\n\");\n return FAILURE;\n }\n //time series\n double *ts1, *ts2;\n ts1 = calloc(N1, sizeof(double));\n if(!ts1){\n printf(\"MALLOC ERROR (ts1)\\n\");\n return FAILURE;\n }\n ts2 = calloc(N2, sizeof(double));\n if(!ts2){\n printf(\"MALLOC ERROR (ts2)\\n\");\n return FAILURE;\n }\n FILE *f1, *f2;\n f1 = fopen(file_name1, \"r\");\n if(!f1){\n printf(\"Cannot open input file (1).\\n\");\n return FAILURE;\n }\n for(int i = 0; i < N1; i++)\n fscanf(f1, \"%lf\", ts1+i);\n fclose(f1);\n f2 = fopen(file_name2, \"r\");\n if(!f2){\n printf(\"Cannot open input file (2).\\n\");\n return FAILURE;\n }\n for(int i = 0; i < N2; i++)\n fscanf(f2, \"%lf\", ts2+i);\n fclose(f2);\n //time series must have the same length\n int L = N1;\n if(N1 < N2){\n printf(\"Series 2 is longer than series 1. Data length reduced to: <%d>\\n\", L);\n slice_vec(ts2, ts2, 0, N1-1);\n }else if(N1 > N2){\n slice_vec(ts1, ts1, 0, N2-1);\n L = N2;\n printf(\"Series 1 is longer than series 2. Data length reduced to: <%d>\\n\", L);\n }else{\n printf(\"Data length: <%d>\\n\", L);\n }\n //time vector\n double *time;\n time = calloc(L, sizeof(double));\n if(!time){\n printf(\"MALLOC ERROR (time)\\n\");\n return FAILURE;\n }\n for(int i = 0; i < L; i++)\n time[i] = (double)(i+1);\n //time series minus its mean\n double ts1_ave = mean(ts1, L, L);\n double ts2_ave = mean(ts2, L, L);\n double *ts1_nomean, *ts2_nomean;\n ts1_nomean = calloc(L, sizeof(double));\n if(!ts1_nomean){\n printf(\"MALLOC ERROR (ts1_nomean)\\n\");\n return FAILURE;\n }\n ts2_nomean = calloc(L, sizeof(double));\n if(!ts2_nomean){\n printf(\"MALLOC ERROR (ts2_nomean)\\n\");\n return FAILURE;\n }\n for(int i = 0; i < L; i++){\n ts1_nomean[i] = ts1[i] - ts1_ave;\n ts2_nomean[i] = ts2[i] - ts2_ave;\n }\n //cumulative sum\n double *ts1_cum, *ts2_cum;\n ts1_cum = calloc(L, sizeof(double));\n if(!ts1_cum){\n printf(\"MALLOC ERROR (ts1_cum)\\n\");\n return FAILURE;\n }\n ts2_cum = calloc(L, sizeof(double));\n if(!ts2_cum){\n printf(\"MALLOC ERROR (ts2_cum)\\n\");\n return FAILURE;\n }\n printf(\"Data integration...\");\n cumsum(ts1_nomean, ts1_cum, L);\n cumsum(ts2_nomean, ts2_cum, L);\n printf(\"done!\\n\");\n //dcca computation\n int biggest_win_size = L / biggest_win_num;\n int win_range = biggest_win_size - smallest_win_size + 1;\n double *F_DCCA, *F_DFA_x, *F_DFA_y, *rho;\n F_DCCA = calloc(win_range, sizeof(double));\n F_DFA_x = calloc(win_range, sizeof(double));\n F_DFA_y = calloc(win_range, sizeof(double));\n rho = calloc(win_range, sizeof(double));\n printf(\"Computing DCCA between series 1 and series 2...\\n\");\n int ret = dcca_comp(time, ts1_cum, ts2_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DCCA, win_range);\n if(ret == FAILURE)\n return FAILURE;\n printf(\"Computing DCCA between series 1 and series 1...\\n\");\n ret = dcca_comp(time, ts1_cum, ts1_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DFA_x, win_range);\n if(ret == FAILURE)\n return FAILURE;\n printf(\"Computing DCCA between series 2 and series 2...\\n\");\n ret = dcca_comp(time, ts2_cum, ts2_cum, L, smallest_win_size, biggest_win_size, pol_ord, F_DFA_y, win_range);\n if(ret == FAILURE)\n return FAILURE;\n FILE *fOut;\n fOut = fopen(path_out, \"w\");\n if(!fOut){\n printf(\"Cannot open output file.\\n\");\n return FAILURE;\n }\n printf(\"Computing rho...\");\n for(int i = 0; i < win_range; i++){\n F_DFA_x[i] = sqrt(F_DFA_x[i]);\n F_DFA_y[i] = sqrt(F_DFA_y[i]);\n rho[i] = F_DCCA[i] / (double)(F_DFA_x[i] * F_DFA_y[i]);\n fprintf(fOut, \"%lf %lf %lf %lf\\n\", F_DCCA[i], F_DFA_x[i], F_DFA_y[i], rho[i]);\n }\n printf(\"done\\n\");\n printf(\"Output file...\");\n fclose(fOut);\n printf(\"done\\n\");\n //free memory\n free(ts1); free(ts2); free(time);\n free(ts1_nomean); free(ts2_nomean);\n free(ts1_cum); free(ts2_cum);\n free(F_DCCA); free(F_DFA_x); free(F_DFA_y); free(rho);\n return 0;\n}\n\n//FUNCTIONS\nint dcca_comp(double *t, double *y1, double *y2, int N, int min_win_size, int last_win_len, int ord, double *F, int range_dcca)\n{\n //fluctuations vector and other arrays\n int F_len = N - min_win_size;\n double *F_nu, *t_fit, *y_fit1, *y_fit2, *diff_vec, *fit_coeffs1, *fit_coeffs2;\n F_nu = calloc(F_len, sizeof(double));\n if(!F_nu){\n printf(\"MALLOC ERROR (F_nu)\\n\");\n return FAILURE;\n }\n t_fit = calloc((last_win_len+1), sizeof(double));\n if(!t_fit){\n printf(\"MALLOC ERROR (t_fit)\\n\");\n return FAILURE;\n }\n y_fit1 = calloc((last_win_len+1), sizeof(double));\n if(!y_fit1){\n printf(\"MALLOC ERROR (y_fit1)\\n\");\n return FAILURE;\n }\n y_fit2 = calloc((last_win_len+1), sizeof(double));\n if(!y_fit2){\n printf(\"MALLOC ERROR (y_fit2)\\n\");\n return FAILURE;\n }\n diff_vec = calloc((last_win_len+1), sizeof(double));\n if(!diff_vec){\n printf(\"MALLOC ERROR (diff_vec)\\n\");\n return FAILURE;\n }\n fit_coeffs1 = calloc(ord+1, sizeof(double));\n if(!fit_coeffs1){\n printf(\"MALLOC ERROR (fit_coeffs1)\\n\");\n return FAILURE;\n }\n fit_coeffs2 = calloc(ord+1, sizeof(double));\n if(!fit_coeffs2){\n printf(\"MALLOC ERROR (fit_coeffs2)\\n\");\n return FAILURE;\n }\n //computation\n int s, N_s, start_lim, end_lim;\n for(int i = 0; i < range_dcca; i++){\n double perc = i * 100 / (double)range_dcca;\n int prg = (i * PRG_WIDTH) / range_dcca;\n printf(\" [%.*s%*s] %.2lf%%\\r\", prg, PROGRESS, PRG_WIDTH-prg, \"\", perc);\n fflush(stdout);\n s = i + min_win_size;\n N_s = N - s;\n for(int v = 0; v < N_s; v++){\n start_lim = v;\n end_lim = v + s;\n slice_vec(t, t_fit, start_lim, end_lim);\n slice_vec(y1, y_fit1, start_lim, end_lim);\n slice_vec(y2, y_fit2, start_lim, end_lim);\n polynomialFit(s+1, ord+1, t_fit, y_fit1, fit_coeffs1);\n polynomialFit(s+1, ord+1, t_fit, y_fit2, fit_coeffs2);\n for(int j = 0; j <= s; j++){\n for(int k = 0; k < ord+1; k++){\n y_fit1[j] -= fit_coeffs1[k] * pow(t_fit[j], k);\n y_fit2[j] -= fit_coeffs2[k] * pow(t_fit[j], k);\n }\n diff_vec[j] = y_fit1[j] * y_fit2[j];\n }\n F_nu[v] = mean(diff_vec, s+1, s-1);\n }\n F[i] = mean(F_nu, N_s, N_s);\n }\n printf(\" [%s] 100.00%%\\r\", PROGRESS);\n fflush(stdout);\n printf(\"\\n\");\n free(F_nu); free(t_fit); free(y_fit1); free(y_fit2);\n free(diff_vec); free(fit_coeffs1); free(fit_coeffs2);\n return SUCCESS;\n}\n\nint rows_number(char *file_name)\n{\n FILE *f;\n int stop;\n int lines = 0;\n f = fopen(file_name,\"r\");\n if(!f){\n printf(\"Cannot open file %s\\n\", file_name);\n return FAILURE;\n }\n while(!feof(f)){\n stop = fgetc(f);\n if(stop == '\\n')\n lines++;\n }\n fclose(f);\n return lines;\n}\n\ndouble mean(double *vec, int vecL, int L)\n{\n double avg = 0.0;\n for(int i = 0; i < vecL; i++)\n avg += vec[i];\n avg /= (double)L;\n return avg;\n}\n\nvoid cumsum(double *vec, double *sum_vec, int L)\n{\n sum_vec[0] = vec[0];\n for(int i = 1; i < L; i++)\n sum_vec[i] = sum_vec[i-1] + vec[i];\n}\n\nvoid slice_vec(double *all_vec, double *sliced_vec, int start, int end)\n{\n for(int i = 0; i <= (end-start); i++)\n sliced_vec[i] = all_vec[start+i];\n}\n\nvoid polynomialFit(int obs, int degree, double *dx, double *dy, double *store)\n{\n gsl_multifit_linear_workspace *ws;\n gsl_matrix *cov, *X;\n gsl_vector *y, *c;\n double chisq;\n int i, j;\n //alloc\n X = gsl_matrix_alloc(obs, degree);\n y = gsl_vector_alloc(obs);\n c = gsl_vector_alloc(degree);\n cov = gsl_matrix_alloc(degree, degree);\n //computation\n for(i = 0; i < obs; i++){\n for(j = 0; j < degree; j++)\n gsl_matrix_set(X, i, j, pow(dx[i], j));\n gsl_vector_set(y, i, dy[i]);\n }\n ws = gsl_multifit_linear_alloc(obs, degree);\n gsl_multifit_linear(X, y, c, cov, &chisq, ws);\n for(i = 0; i < degree; i++)\n store[i] = gsl_vector_get(c, i);\n //free memory\n gsl_multifit_linear_free(ws);\n gsl_matrix_free(X);\n gsl_matrix_free(cov);\n gsl_vector_free(y);\n gsl_vector_free(c);\n}\n", "meta": {"hexsha": "c042649dd9124a6c94f540135944553ac26e5598", "size": 10363, "ext": "c", "lang": "C", "max_stars_repo_path": "dcca.c", "max_stars_repo_name": "stfbnc/C_fa", "max_stars_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "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": "dcca.c", "max_issues_repo_name": "stfbnc/C_fa", "max_issues_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "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": "dcca.c", "max_forks_repo_name": "stfbnc/C_fa", "max_forks_repo_head_hexsha": "d69895fb99113eff284f945e79c8b98e63cbbcb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2138554217, "max_line_length": 127, "alphanum_fraction": 0.5749300396, "num_tokens": 3138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6391890124197955}} {"text": "/*\n * Copyright (c) 2009-2010 Simon van Heeringen \n * \n * This module is free software. You can redistribute it and/or modify it under \n * the terms of the MIT License, see the file COPYING included with this \n * distribution.\n *\n * This module contains all the code to compare motifs\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n\nvoid fill_matrix(double matrix[][4], PyObject *matrix_o) {\n\t// Parse a PyObject matrix into a C array\t\n\t// Structure of the matrix is as follows: [[freqA, freqC, freqG, freqT], ...]\n\tint matrix_len = PyList_Size(matrix_o);\n\tint i,j;\n\tPyObject *item;\n\tfor (i = 0; i < matrix_len; i++) {\n\t\t\n\t\tPyObject *row = PyList_GetItem(matrix_o, i);\n\t\tif (!PyList_Check(row)) {\n\t\t\tPyErr_SetString( PyExc_TypeError, \"wrong matrix structure\");\n\t\t\treturn;\n\t\t}\t\n\t\tif (PyList_Size(row) != 4) {\n\t\t\tPyErr_SetString( PyExc_TypeError, \"4 nucleotides!\");\n\t\t\treturn;\n\t\t}\t\t\n\t\tfor (j = 0; j < 4; j++) {\n\t\t\titem = PyList_GetItem(row, j);\n\t\t\tmatrix[i][j] = PyFloat_AsDouble(item);\n\t\t}\n\t}\n}\n\n\ndouble mean(double array[], double length) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < length; i++) {\n\t\tsum += array[i];\n\t}\n\treturn sum / length;\n}\n\ndouble sum(double array[], double length) {\n\tdouble sum = 0;\n\tint i;\n\tfor (i = 0; i < length; i++) {\n\t\tsum += array[i];\n\t}\n\treturn sum;\n}\n\ndouble wic(double col1[], double col2[]) {\n\t\tint n;\n\t\tdouble x,y;\n\t\tdouble log2 = log(2.0);\n\t\tdouble factor = 2.5;\n\t\tdouble score = 0;;\n\t\tdouble score_a = 0.0;\n\t\tdouble score_b = 0.0;\n\t\tdouble pseudo = 0.0000001;\n\n\t\tfor (n = 0; n < 4; n++) {\n\t\t\tx = col1[n] * log((col1[n] + pseudo) / 0.25) / log2;\n\t\t\ty = col2[n] * log((col2[n] + pseudo) / 0.25) / log2;\n\t\t\tscore += fabs(x - y);\n\t\t\tscore_a += x;\n\t\t\tscore_b += y;\n\t\t}\n\t\treturn sqrt(score_a * score_b) - factor * score;\n}\n\ndouble matrix_wic_mean(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean pcc of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = wic(matrix1[i], matrix2[i]);\n\t}\n\treturn mean(result, length);\n}\n\ndouble matrix_wic_sum(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean pcc of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = wic(matrix1[i], matrix2[i]);\n\t}\n\treturn sum(result, length);\n}\n\ndouble pcc(double col1[], double col2[]) {\n\t// Return the Pearson correlation coefficient of two motif columns\n\tint n;\n\tdouble sum1 = 0;\n\tdouble sum2 = 0;\n\tdouble mean1, mean2;\n\n\tfor (n = 0; n < 4; n++) {\n\t\tsum1 += col1[n];\n\t\tsum2 += col2[n];\n\t}\n\tmean1 = sum1 / 4;\n\tmean2 = sum2 / 4;\n\n\tfloat a = 0;\n\tfloat x = 0;\n\tfloat y = 0;\n\tfor (n = 0; n < 4; n++) {\n\t\tif (((col1[n] - mean1) != 0) && ((col2[n] - mean2) != 0)) {\n\t\t\ta += (col1[n] - mean1) * (col2[n] - mean2);\n\t\t\tx += pow((col1[n] - mean1), 2);\n\t\t\ty += pow((col2[n] - mean2), 2);\n\t\t}\n\t\telse {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn a / sqrt(x * y);\n}\n\ndouble matrix_pcc_mean(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean pcc of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = pcc(matrix1[i], matrix2[i]);\n\t}\n\treturn mean(result, length);\n}\n\ndouble ed(double col1[], double col2[]) {\n\t// Return the euclidian distance of two motif columns\n\tint n;\n\tdouble score = 0;\n\n\tfor (n = 0; n < 4; n++) {\n\t\tscore = score + pow((col1[n] - col2[n]), 2);\n\t}\n\n\treturn -sqrt(score);\n}\n\ndouble matrix_ed_mean(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean euclidian distance of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = ed(matrix1[i], matrix2[i]);\n\t}\n\treturn mean(result, length);\n}\n\ndouble distance(double col1[], double col2[]) {\n\t// Return the distance between two motifs (Harbison et al.) \n\tint n;\n\tdouble d = 0;\n\n\tfor (n = 0; n < 4; n++) {\n\t\td = d + pow(col1[n] - col2[n], 2);\n\t}\n\td = d * 1 / sqrt(2);\n\n\treturn -d;\n}\n\ndouble matrix_distance_mean(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean distance (Harbison et al.) of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = distance(matrix1[i], matrix2[i]);\n\t}\n\treturn mean(result, length);\n}\n\ndouble chisq(double col1[], double col2[]) {\n\t// Return the distance between two motifs (Harbison et al.) \n\tint n;\n\tdouble sum1 = 0;\n\tdouble sum2 = 0;\n\tdouble e1, e2;\t\n\tdouble c = 0;\n\t\n\tfor (n = 0; n < 4; n++) {\n\t\tsum1 += col1[n];\n\t\tsum2 += col2[n];\n\t}\n\n\tfor (n = 0; n < 4; n++) {\n\t\te1 = (sum1 * (col1[n] + col2[n])) / (sum1 + sum2);\n\t\te2 = (sum2 * (col1[n] + col2[n])) / (sum1 + sum2);\n\t\tc += pow((col1[n] - e1), 2) / e1;\n\t\tc += pow((col2[n] - e2), 2) / e2;\n\n\t}\n\n\treturn 1 - gsl_cdf_chisq_P(c, 3.0);\n}\n\ndouble matrix_chisq_mean(double matrix1[][4], double matrix2[][4], int length) {\n\t// Return the mean distance (Harbison et al.) of two matrices \n\tint i;\n\tdouble result[length];\n\n\tfor (i = 0; i < length; i++ ) {\n\t\tresult[i] = chisq(matrix1[i], matrix2[i]);\n\t}\n\treturn mean(result, length);\n}\n\nstatic PyObject * c_metrics_score(PyObject *self, PyObject * args)\n{\n\tPyObject *matrix1_o;\n\tPyObject *matrix2_o;\n\tconst char *metric;\n\tconst char *combine;\n\tint matrix1_len;\n\tint matrix2_len;\n\n\tif (!PyArg_ParseTuple(args, \"OOss\", &matrix1_o, &matrix2_o, &metric, &combine)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error parsing arguments\");\n\t\treturn NULL;\n\t}\n\n\t// Retrieve frequency matrix\n\tif (!PyList_Check(matrix1_o)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error: missing required argument matrix1\");\n\t\treturn NULL;\n\t}\n\n\tif (!PyList_Check(matrix2_o)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error: missing required argument matrix2\");\n\t\treturn NULL;\n\t}\n\t// Fill matrix1\n\tmatrix1_len = PyList_Size(matrix1_o);\n\tdouble matrix1[matrix1_len][4];\n\tfill_matrix(matrix1, matrix1_o);\n\t\n\t// Fill matrix2\n\tmatrix2_len = PyList_Size(matrix2_o);\n\tdouble matrix2[matrix2_len][4];\n\tfill_matrix(matrix2, matrix2_o);\n\n\tif (matrix1_len != matrix2_len) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error: matrices have different sizes\");\n\t\treturn NULL;\n\t}\n\tint i;\n\tdouble result[matrix1_len];\n\tif (!strcmp(metric, \"chisq\")) {\n\t\tfor (i = 0; i < matrix1_len; i++ ) {\n\t\t\tresult[i] = chisq(matrix1[i], matrix2[i]);\n\t\t}\n\t}\n\telse if (!strcmp(metric, \"wic\")) {\n\t\tfor (i = 0; i < matrix1_len; i++ ) {\n\t\t\tresult[i] = wic(matrix1[i], matrix2[i]);\n\t\t}\n\t}\n\telse if (!strcmp(metric, \"ed\")) {\n\t\tfor (i = 0; i < matrix1_len; i++ ) {\n\t\t\tresult[i] = ed(matrix1[i], matrix2[i]);\n\t\t}\n\t}\n\telse if (!strcmp(metric, \"pcc\")) {\n\t\tfor (i = 0; i < matrix1_len; i++ ) {\n\t\t\tresult[i] = pcc(matrix1[i], matrix2[i]);\n\t\t}\n\t}\n\telse if (!strcmp(metric, \"distance\")) {\n\t\tfor (i = 0; i < matrix1_len; i++ ) {\n\t\t\tresult[i] = distance(matrix1[i], matrix2[i]);\n\t\t}\n\t}\n\telse {\n\t\t\tPyErr_SetString( PyExc_TypeError, \"Unknown metric\");\n\t\t\treturn NULL;\n\t}\n\t\n\tif (!strcmp(combine, \"mean\")) {\n\t\treturn Py_BuildValue(\"f\", mean(result, matrix1_len));\n\t}\n\telse if (!strcmp(combine, \"sum\")) {\n\t\treturn Py_BuildValue(\"f\", sum(result, matrix1_len));\n\t}\n\telse {\n\t\t\tPyErr_SetString( PyExc_TypeError, \"Unknown combine\");\n\t\t\treturn NULL;\n\t}\n\n}\n\nint get_truncate_len(len1, len2, pos) {\n\t// \n\t\n\tif (pos < 0) {\n\t\tlen2 += pos;\n\t}\n\telse if (pos > 0) {\n\t\tlen1 -= pos;\n\t}\n\n\tif (len1 > len2) {\n\t\treturn len2;\n\t}\n\telse {\n\t\treturn len1;\n\t}\n\t\n}\n\nvoid fill_tmp_matrices(double matrix1[][4], double matrix2[][4], int pos, int l, double tmp_matrix1[][4], double tmp_matrix2[][4]) {\n\tint start1 = 0;\n\tint start2 = 0;\n\tint i, n;\n\n\tif (pos < 0) {\n\t\tstart2 = -pos;\n\t}\n\telse {\n\t\tstart1 = pos;\n\t}\n\t\n\tfor (i = 0; i < l; i++) {\n\t\tfor (n = 0; n < 4; n++) {\n\t\t\ttmp_matrix1[i][n] = matrix1[start1 + i][n];\n\t\t\ttmp_matrix2[i][n] = matrix2[start2 + i][n];\n\t\t}\n\t}\n\n}\n\nint index_at_max(double scores[], int len) {\n\tdouble max = scores[0];\n\tint i_at_max = 0;\n\tint i;\n\t\n\tif (len == 1) {\n\t\treturn 0;\n\t}\n\t\n\tfor (i = 1; i < len; i++) {\n\t\tif (scores[i] > max) {\n\t\t\tmax = scores[i];\n\t\t\ti_at_max = i;\n\t\t}\n\t}\n\treturn i_at_max;\n}\n\nvoid fill_rc_matrix(double matrix[][4], int len, double rc_matrix[][4]) {\n\tint i = 0;\n\n\tfor (i = 0; i < len; i++) {\n\t\trc_matrix[i][0] = matrix[len - i - 1][3];\n\t\trc_matrix[i][1] = matrix[len - i - 1][2];\t\n\t\trc_matrix[i][2] = matrix[len - i - 1][1];\n\t\trc_matrix[i][3] = matrix[len - i - 1][0];\n\t}\n\n}\n\n\nstatic PyObject * c_metrics_max_subtotal(PyObject *self, PyObject * args)\n{\n\tPyObject *matrix1_o;\n\tPyObject *matrix2_o;\n\tconst char *metric;\n\tconst char *combine;\n\tint matrix1_len;\n\tint matrix2_len;\n\tif (!PyArg_ParseTuple(args, \"OOss\", &matrix1_o, &matrix2_o, &metric, &combine)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error parsing arguments\");\n\t\treturn NULL;\n\t}\n\n\t// Retrieve frequency matrix\n\tif (!PyList_Check(matrix1_o)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error: missing required argument matrix1\");\n\t\treturn NULL;\n\t}\n\n\tif (!PyList_Check(matrix2_o)) {\n\t\tPyErr_SetString( PyExc_TypeError, \"Error: missing required argument matrix2\");\n\t\treturn NULL;\n\t}\n\t// Fill matrix1\n\tmatrix1_len = PyList_Size(matrix1_o);\n\tdouble matrix1[matrix1_len][4];\n\tfill_matrix(matrix1, matrix1_o);\n\t\n\t// Fill matrix2\n\tmatrix2_len = PyList_Size(matrix2_o);\n\tdouble matrix2[matrix2_len][4];\n\tfill_matrix(matrix2, matrix2_o);\n\n\t// Fill rc matrix2\n\tdouble rc_matrix2[matrix2_len][4];\n\tfill_rc_matrix(matrix2, matrix2_len, rc_matrix2);\n\n\t// Assign correct function\n\t\n\t\n\t\n\tint pos = -2;\n\tint l;\n\tfloat max_score;\n\tint min_overlap = 6;\n\tint nr_matches;\n\tint start_pos = -(matrix2_len - min_overlap);\n\tnr_matches = matrix1_len + matrix2_len - 2 * min_overlap + 1;\n\tint i;\t\n\tint positions[nr_matches * 2];\n\tdouble scores[nr_matches * 2];\n\tint orients[nr_matches * 2];\n\n\tdouble (*ptr_metric_function)(double[][4], double[][4], int) = NULL; \n\t\t\n\tif ((!strcmp(metric, \"chisq\")) && (!strcmp(combine, \"mean\"))) {\n\t\tptr_metric_function = &matrix_chisq_mean;\n\t}\n\telse if ((!strcmp(metric, \"wic\")) && (!strcmp(combine, \"mean\"))) {\n\t\tptr_metric_function = &matrix_wic_mean;\n\t}\n\telse if ((!strcmp(metric, \"wic\")) && (!strcmp(combine, \"sum\"))) {\n\t\tptr_metric_function = &matrix_wic_sum;\n\t}\n\telse if ((!strcmp(metric, \"pcc\")) && (!strcmp(combine, \"mean\"))) {\n\t\tptr_metric_function = &matrix_pcc_mean;\n\t}\n\telse if ((!strcmp(metric, \"ed\")) && (!strcmp(combine, \"mean\"))) {\n\t\tptr_metric_function = &matrix_ed_mean;\n\t}\n\telse if ((!strcmp(metric, \"distance\")) && (!strcmp(combine, \"mean\"))) {\n\t\tptr_metric_function = &matrix_distance_mean;\n\t}\n\telse {\n\t\tPyErr_SetString( PyExc_TypeError, \"Unknown metric or combination\");\n\t\treturn NULL;\n\t}\n\t\n\tfor (i = 0; i < nr_matches; i++) {\n\t\tpos = i + start_pos;\n\t\tl = get_truncate_len(matrix1_len, matrix2_len, pos);\n\t\t\n\t\t// Normal matrix\n\t\tdouble tmp_matrix1[l][4];\n\t\tdouble tmp_matrix2[l][4];\n\n\t\tfill_tmp_matrices(matrix1, matrix2, pos, l, tmp_matrix1, tmp_matrix2);\n\t\tmax_score = (*ptr_metric_function) (tmp_matrix1, tmp_matrix2, l);\n\t\tpositions[i] = pos;\n\t\tscores[i] = max_score;\n\t\torients[i] = 1;\n\t\t//printf(\"CC 1 Len %i score %f\\n\", l, max_score);\n\n\t\t// Reverse complement matrix\n\t\tfill_tmp_matrices(matrix1, rc_matrix2, pos, l, tmp_matrix1, tmp_matrix2);\n\t\tmax_score = (*ptr_metric_function) (tmp_matrix1, tmp_matrix2, l);\n\t\tpositions[i + nr_matches] = pos;\n\t\tscores[i + nr_matches] = max_score;\n\t\torients[i+ nr_matches] = -1;\n\n\t\t//printf(\"CC -1 Len %i score %f\\n\", l, max_score);\n\t}\n\t\n\ti = index_at_max(scores, nr_matches * 2);\n\treturn Py_BuildValue(\"fii\", scores[i], positions[i], orients[i]);\n\t\n\n}\nstatic PyObject * c_metrics_pwmscan(PyObject *self, PyObject * args)\n{\n\tPyObject *seq_o;\n\tPyObject *pwm_o;\n\tPyObject *cutoff_o;\n\tchar *seq;\n\tint seq_len;\n\tint n_report;\n\tint pwm_len;\n\tint i, j;\n\tdouble zeta = 0.01;\n\tint scan_rc;\n\n\tif (!PyArg_ParseTuple(args, \"OOOii\", &seq_o, &pwm_o, &cutoff_o, &n_report, &scan_rc))\n\t\treturn NULL;\n\t\n\t// Sequence and length\n\tif (!PyString_Check(seq_o))\n\t\treturn NULL;\n\tseq = PyString_AsString(seq_o);\n\tseq_len = PyString_Size(seq_o);\n\t//Py_DECREF(seq_o);\n\n\n\t// Retrieve frequency matrix\n\tif (!PyList_Check(pwm_o))\n\t\treturn NULL;\n\n\t// Weight matrices\n\tpwm_len = PyList_Size(pwm_o);\n\tdouble pwm[pwm_len][4];\n\tfill_matrix(pwm, pwm_o);\n\t//Py_DECREF(pwm_o);\n\n\t// Cutoff for every spacer length\n\tdouble cutoff;\n\tcutoff = PyFloat_AsDouble(cutoff_o);\n\t\n\t// Scan sequence\n\tint j_max = seq_len - pwm_len + 1;\n\tdouble score_matrix[j_max];\n\tdouble rc_score_matrix[j_max];\n\tdouble score, rc_score;\n\n\tif (j_max < 0) { j_max = 0;}\n\tint m;\n\tdouble g = 0.25;\n\tdouble z = 0.01;\n\tfor (j = 0; j < j_max; j++) {\n\t\tscore = 0;\n\t\trc_score = 0;\n\t\tfor (m = 0; m < pwm_len; m++) {\n\t\t\tswitch(seq[j + m]) {\n\t\t\t\tcase 'A': \n\t\t\t\t\tscore += log(pwm[m][0] / g + z);\n\t\t\t\t\trc_score += log(pwm[pwm_len - m - 1][3] / g + z); \n\t\t\t\t\tbreak;\n\t\t\t\tcase 'C': \n\t\t\t\t\tscore += log(pwm[m][1] / g + z);\n\t\t\t\t\trc_score += log(pwm[pwm_len - m - 1][2] / g + z); \n\t\t\t\t\tbreak;\n\t\t\t\tcase 'G': \n\t\t\t\t\tscore += log(pwm[m][2] / g + z);\n\t\t\t\t\trc_score += log(pwm[pwm_len - m - 1][1] / g + z); \n\t\t\t\t\tbreak;\n\t\t\t\tcase 'T': \n\t\t\t\t\tscore += log(pwm[m][3] / g + z);\n\t\t\t\t\trc_score += log(pwm[pwm_len - m - 1][0] / g + z); \n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\t}\n\t\tscore_matrix[j] = score;\n\t\trc_score_matrix[j] = rc_score;\n\t}\n\n\t// Initialize matrices of n_report highest scores and corresponding positions + strands\n\tdouble maxScores[n_report];\n\tdouble maxPos[n_report];\n\tint maxStrand[n_report];\n\tfor (j = 0; j < n_report; j++) {\n\t\tmaxScores[j] = -100;\n\t\tmaxPos[j] = -1;\n\t\tmaxStrand[j] = 1;\n\t}\n\tPyObject* return_list = PyList_New(0);\n\t\n\tint p,q;\n\tPyObject *x;\n\tfor (j = 0; j < j_max; j++) {\n\t\tscore = score_matrix[j];\n\t\tif (n_report > 0) {\n\t\t\tif (score >= cutoff) {\n\t\t\t\tp = n_report - 1;\n\t\t\t\twhile ((p >= 0) && (score > maxScores[p])) {\n\t\t\t\t\tp--;\n\t\t\t\t}\n\t\t\t\tif (p < (n_report-1)) {\n\t\t\t\t\tfor (q = n_report - 1; q > (p + 1); q--) {\n\t\t\t\t\t\tmaxScores[q] = maxScores[q - 1];\n\t\t\t\t\t\tmaxPos[q] = maxPos[q - 1];\n\t\t\t\t\t\tmaxStrand[q] = maxStrand[q - 1];\n\t\t\t\t\t}\n\t\t\t\t\tmaxScores[p + 1] = score;\n\t\t\t\t\tmaxPos[p + 1] = j;\n\t\t\t\t\tmaxStrand[p + 1] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (score >= cutoff) {\n\t\t\t\tPyObject* row = PyList_New(0);\n\t\t\t\tx = PyFloat_FromDouble(score);\n\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\tx = PyInt_FromLong((long) j);\n\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\tx = PyInt_FromLong((long) 1);\n\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\tPyList_Append(return_list, row);\n\t\t\t\tPy_DECREF(row);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (scan_rc) {\n\t\tfor (j = 0; j < j_max; j++) {\n\t\t\tscore = rc_score_matrix[j];\n\t\t\tif (n_report > 0) {\n\t\t\t\tif (score >= cutoff) {\n\t\t\t\t\tp = n_report - 1;\n\t\t\t\t\twhile ((p >= 0) && (score > maxScores[p])) {\n\t\t\t\t\t\tp--;\n\t\t\t\t\t}\n\t\t\t\t\tif (p < (n_report-1)) {\n\t\t\t\t\t\tfor (q = n_report - 1; q > (p + 1); q--) {\n\t\t\t\t\t\t\tmaxScores[q] = maxScores[q - 1];\n\t\t\t\t\t\t\tmaxPos[q] = maxPos[q - 1];\n\t\t\t\t\t\t\tmaxStrand[q] = maxStrand[q - 1];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaxScores[p + 1] = score;\n\t\t\t\t\t\tmaxPos[p + 1] = j;\n\t\t\t\t\t\tmaxStrand[p + 1] = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (score >= cutoff) {\n\t\t\t\t\tPyObject* row = PyList_New(0);\n\t\t\t\t\tx = PyFloat_FromDouble(score);\n\t\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\t\tx = PyInt_FromLong((long) j);\n\t\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\t\tx = PyInt_FromLong((long) 1);\n\t\t\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\t\t\tPyList_Append(return_list, row);\n\t\t\t\t\tPy_DECREF(row);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < n_report; i++) {\n\t\tif (maxPos[i] > - 1) {\n\t\t\tPyObject* row = PyList_New(0);\n\t\t\tx = PyFloat_FromDouble(maxScores[i]);\n\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\tx = PyInt_FromLong((long)maxPos[i]);\n\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\tx = PyInt_FromLong((long)maxStrand[i]);\n\t\t\tPyList_Append(row, x); Py_DECREF(x);\n\t\t\tPyList_Append(return_list, row);\n\t\t\tPy_DECREF(row);\n\t\t}\n\t}\n\n\treturn return_list;\n}\n\n\n\nstatic PyMethodDef CoreMethods[] = {\n\t{\"score\", c_metrics_score, METH_VARARGS,\"Test\"},\n\t{\"c_max_subtotal\", c_metrics_max_subtotal, METH_VARARGS,\"Test\"},\n\t{\"pwmscan\", c_metrics_pwmscan, METH_VARARGS,\"Test\"},\n\t{NULL, NULL, NULL, 0, NULL}\n};\n\nPyMODINIT_FUNC\ninitc_metrics(void)\n{\n\t(void) Py_InitModule(\"c_metrics\", CoreMethods);\n};\n\n\n", "meta": {"hexsha": "acfa514d04f240367bda09c0f65e4dfdc4590dee", "size": 15918, "ext": "c", "lang": "C", "max_stars_repo_path": "gimmemotifs/c_metrics.c", "max_stars_repo_name": "kipkurui/gimmemotifs", "max_stars_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-14T08:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-14T08:28:25.000Z", "max_issues_repo_path": "gimmemotifs/c_metrics.c", "max_issues_repo_name": "kipkurui/gimmemotifs", "max_issues_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "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": "gimmemotifs/c_metrics.c", "max_forks_repo_name": "kipkurui/gimmemotifs", "max_forks_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "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.3060029283, "max_line_length": 132, "alphanum_fraction": 0.6130167106, "num_tokens": 5280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6390949766220272}} {"text": "#include \n#include \n#include \n#include \n#include \"../inc/knnring.h\"\n\n\n// Application Entry Point\nknnresult kNN(double * X, double * Y, int n, int m, int d, int k)\n{\n\n\t// Calculate distances matrix D - D is row-major and nxm\n\tdouble* tempD = calculateD(X, Y, n, m, d, k);\n\n\tdouble* D = calloc(m*n, sizeof(double)); \n\n\t// Transpose D to mxn\n\t//cblas_dimatcopy(CblasRowMajor, CblasTrans, n, m, 1.0, D, m, n);\n\t\n\tdouble* identityMat = calloc(n*n, sizeof(double));\n\tfor(int f=0; f\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble\nfunc(const size_t n, double x[], void * params)\n{\n const double alpha = *(double *) params;\n\n gsl_sort(x, 1, n);\n\n return gsl_stats_trmean_from_sorted_data(alpha, x, 1, n);\n}\n\nint\nmain(void)\n{\n const size_t N = 1000; /* length of time series */\n const size_t K = 11; /* window size */\n double alpha = 0.1; /* trimmed mean parameter */\n gsl_vector *x = gsl_vector_alloc(N); /* input vector */\n gsl_vector *y = gsl_vector_alloc(N); /* filtered output vector for alpha1 */\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n gsl_movstat_workspace *w = gsl_movstat_alloc(K);\n gsl_movstat_function F;\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 double outlier = (gsl_rng_uniform(r) < 0.01) ? 10.0*GSL_SIGN(ui) : 0.0;\n sum += ui;\n gsl_vector_set(x, i, sum + outlier);\n }\n\n /* apply moving window function */\n F.function = func;\n F.params = α\n gsl_movstat_apply(GSL_MOVSTAT_END_PADVALUE, &F, x, y, w);\n\n /* print results */\n for (i = 0; i < N; ++i)\n {\n double xi = gsl_vector_get(x, i);\n double yi = gsl_vector_get(y, i);\n\n printf(\"%f %f\\n\", xi, yi);\n }\n\n gsl_vector_free(x);\n gsl_vector_free(y);\n gsl_rng_free(r);\n gsl_movstat_free(w);\n\n return 0;\n}\n", "meta": {"hexsha": "5a603140a8f25975ee921cf3b1d327a9fdf692d5", "size": 1597, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/movstat3.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/movstat3.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/movstat3.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.196969697, "max_line_length": 79, "alphanum_fraction": 0.6186599875, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6387441860289091}} {"text": "/* multiroots/test_funcs.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"test_funcs.h\"\n\n/* For information on testing see the following paper,\n\n J.J More, B.S. Garbow, K.E. Hillstrom, \"Testing Unconstrained\n Optimization Software\", ACM Transactions on Mathematical Software,\n Vol 7, No 1, (1981) p 17-41\n\n */\n\n/* Rosenbrock Function */\n\ngsl_multiroot_function_fdf rosenbrock =\n{&rosenbrock_f,\n &rosenbrock_df,\n &rosenbrock_fdf,\n 2, 0};\n\nvoid\nrosenbrock_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, -1.2);\n gsl_vector_set (x, 1, 1.0);\n}\n\nint\nrosenbrock_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double y0 = 1 - x0;\n double y1 = 10 * (x1 - x0 * x0);\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nrosenbrock_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n\n double df00 = -1;\n double df01 = 0;\n double df10 = -20 * x0;\n double df11 = 10;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nrosenbrock_fdf (const gsl_vector * x, void *params,\n\t\tgsl_vector * f, gsl_matrix * df)\n{\n rosenbrock_f (x, params, f);\n rosenbrock_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Freudenstein and Roth function */\n\ngsl_multiroot_function_fdf roth =\n{&roth_f,\n &roth_df,\n &roth_fdf,\n 2, 0};\n\nvoid\nroth_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, 4.5); /* changed from the value in the paper */\n gsl_vector_set (x, 1, 3.5); /* otherwise the problem is too hard */\n}\n\nint\nroth_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double y0 = -13.0 + x0 + ((5.0 - x1)*x1 - 2.0)*x1;\n double y1 = -29.0 + x0 + ((x1 + 1.0)*x1 - 14.0)*x1;\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nroth_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x1 = gsl_vector_get (x, 1);\n\n double df00 = 1;\n double df01 = -3 * x1 * x1 + 10 * x1 - 2;\n double df10 = 1;\n double df11 = 3 * x1 * x1 + 2 * x1 - 14;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nroth_fdf (const gsl_vector * x, void *params,\n\t\tgsl_vector * f, gsl_matrix * df)\n{\n roth_f (x, params, f);\n roth_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n\n/* Powell badly scaled function */\n\ngsl_multiroot_function_fdf powellscal =\n{&powellscal_f,\n &powellscal_df,\n &powellscal_fdf,\n 2, 0};\n\nvoid\npowellscal_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, 0.0);\n gsl_vector_set (x, 1, 1.0);\n}\n\nint\npowellscal_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double y0 = 10000.0 * x0 * x1 - 1.0;\n double y1 = exp (-x0) + exp (-x1) - 1.0001;\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\npowellscal_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double df00 = 10000.0 * x1, df01 = 10000.0 * x0;\n double df10 = -exp (-x0), df11 = -exp (-x1);\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\npowellscal_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n powellscal_f (x, params, f);\n powellscal_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Brown badly scaled function */\n\ngsl_multiroot_function_fdf brownscal =\n{&brownscal_f,\n &brownscal_df,\n &brownscal_fdf,\n 2, 0};\n\nvoid\nbrownscal_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, 1.0);\n gsl_vector_set (x, 1, 1.0);\n}\n\nint\nbrownscal_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double y0 = x0 - 1e6;\n double y1 = x0 * x1 - 2;\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nbrownscal_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double df00 = 1.0, df01 = 0.0;\n double df10 = x1, df11 = x0;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nbrownscal_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n brownscal_f (x, params, f);\n brownscal_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Powell Singular Function */\n\ngsl_multiroot_function_fdf powellsing =\n{&powellsing_f,\n &powellsing_df,\n &powellsing_fdf,\n 4, 0};\n\nvoid\npowellsing_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, 0.0);\n gsl_vector_set (x, 3, 1.0);\n}\n\nint\npowellsing_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n double x2 = gsl_vector_get (x, 2);\n double x3 = gsl_vector_get (x, 3);\n\n double y0 = x0 + 10 * x1;\n double y1 = sqrt (5.0) * (x2 - x3);\n double y2 = pow (x1 - 2 * x2, 2.0);\n double y3 = sqrt (10.0) * pow (x0 - x3, 2.0);\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n gsl_vector_set (f, 2, y2);\n gsl_vector_set (f, 3, y3);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\npowellsing_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n double x2 = gsl_vector_get (x, 2);\n double x3 = gsl_vector_get (x, 3);\n\n double df00 = 1, df01 = 10, df02 = 0, df03 = 0;\n double df10 = 0, df11 = 0, df12 = sqrt (5.0), df13 = -df12;\n double df20 = 0, df21 = 2 * (x1 - 2 * x2), df22 = -2 * df21, df23 = 0;\n double df30 = 2 * sqrt (10.0) * (x0 - x3), df31 = 0, df32 = 0, df33 = -df30;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 0, 2, df02);\n gsl_matrix_set (df, 0, 3, df03);\n\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n gsl_matrix_set (df, 1, 2, df12);\n gsl_matrix_set (df, 1, 3, df13);\n\n gsl_matrix_set (df, 2, 0, df20);\n gsl_matrix_set (df, 2, 1, df21);\n gsl_matrix_set (df, 2, 2, df22);\n gsl_matrix_set (df, 2, 3, df23);\n\n gsl_matrix_set (df, 3, 0, df30);\n gsl_matrix_set (df, 3, 1, df31);\n gsl_matrix_set (df, 3, 2, df32);\n gsl_matrix_set (df, 3, 3, df33);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\npowellsing_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n powellsing_f (x, params, f);\n powellsing_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Wood function */\n\ngsl_multiroot_function_fdf wood =\n{&wood_f,\n &wood_df,\n &wood_fdf,\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\nint\nwood_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n double x2 = gsl_vector_get (x, 2);\n double x3 = gsl_vector_get (x, 3);\n\n double t1 = x1 - x0 * x0;\n double t2 = x3 - x2 * x2;\n\n double y0 = -200.0 * x0 * t1 - (1 - x0);\n double y1 = 200.0 * t1 + 20.2 * (x1 - 1) + 19.8 * (x3 - 1);\n double y2 = -180.0 * x2 * t2 - (1 - x2);\n double y3 = 180.0 * t2 + 20.2 * (x3 - 1) + 19.8 * (x1 - 1);\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n gsl_vector_set (f, 2, y2);\n gsl_vector_set (f, 3, y3);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nwood_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n double x2 = gsl_vector_get (x, 2);\n double x3 = gsl_vector_get (x, 3);\n\n double t1 = x1 - 3 * x0 * x0;\n double t2 = x3 - 3 * x2 * x2;\n\n double df00 = -200.0 * t1 + 1, df01 = -200.0 * x0, df02 = 0, df03 = 0;\n double df10 = -400.0*x0, df11 = 200.0 + 20.2, df12 = 0, df13 = 19.8;\n double df20 = 0, df21 = 0, df22 = -180.0 * t2 + 1, df23 = -180.0 * x2;\n double df30 = 0, df31 = 19.8, df32 = -2 * 180 * x2, df33 = 180.0 + 20.2;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 0, 2, df02);\n gsl_matrix_set (df, 0, 3, df03);\n\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n gsl_matrix_set (df, 1, 2, df12);\n gsl_matrix_set (df, 1, 3, df13);\n\n gsl_matrix_set (df, 2, 0, df20);\n gsl_matrix_set (df, 2, 1, df21);\n gsl_matrix_set (df, 2, 2, df22);\n gsl_matrix_set (df, 2, 3, df23);\n\n gsl_matrix_set (df, 3, 0, df30);\n gsl_matrix_set (df, 3, 1, df31);\n gsl_matrix_set (df, 3, 2, df32);\n gsl_matrix_set (df, 3, 3, df33);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nwood_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n wood_f (x, params, f);\n wood_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Helical Valley Function */\n\ngsl_multiroot_function_fdf helical =\n{&helical_f,\n &helical_df,\n &helical_fdf,\n 3, 0};\n\nvoid\nhelical_initpt (gsl_vector * x)\n{\n gsl_vector_set (x, 0, -1.0);\n gsl_vector_set (x, 1, 0.0);\n gsl_vector_set (x, 2, 0.0);\n}\n\nint\nhelical_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n double x2 = gsl_vector_get (x, 2);\n\n double t1, t2;\n double y0, y1, y2;\n\n if (x0 > 0) \n {\n t1 = atan(x1/x0) / (2.0 * M_PI);\n }\n else if (x0 < 0)\n {\n t1 = 0.5 + atan(x1/x0) / (2.0 * M_PI);\n }\n else\n {\n t1 = 0.25 * (x1 > 0 ? +1 : -1);\n }\n\n t2 = sqrt(x0*x0 + x1*x1) ;\n \n y0 = 10 * (x2 - 10 * t1);\n y1 = 10 * (t2 - 1);\n y2 = x2 ;\n\n gsl_vector_set (f, 0, y0);\n gsl_vector_set (f, 1, y1);\n gsl_vector_set (f, 2, y2);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nhelical_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n double x0 = gsl_vector_get (x, 0);\n double x1 = gsl_vector_get (x, 1);\n\n double t = x0 * x0 + x1 * x1 ;\n double t1 = 2 * M_PI * t ;\n double t2 = sqrt(t) ;\n\n double df00 = 100*x1/t1, df01 = -100.0 * x0/t1, df02 = 10.0;\n double df10 = 10*x0/t2, df11 = 10*x1/t2, df12 = 0;\n double df20 = 0, df21 = 0, df22 = 1.0;\n\n gsl_matrix_set (df, 0, 0, df00);\n gsl_matrix_set (df, 0, 1, df01);\n gsl_matrix_set (df, 0, 2, df02);\n\n gsl_matrix_set (df, 1, 0, df10);\n gsl_matrix_set (df, 1, 1, df11);\n gsl_matrix_set (df, 1, 2, df12);\n\n gsl_matrix_set (df, 2, 0, df20);\n gsl_matrix_set (df, 2, 1, df21);\n gsl_matrix_set (df, 2, 2, df22);\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\nhelical_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n helical_f (x, params, f);\n helical_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n\n/* Discrete Boundary Value Function */\n\n#define N 10\n\ngsl_multiroot_function_fdf dbv =\n{&dbv_f,\n &dbv_df,\n &dbv_fdf,\n N, 0};\n\nvoid\ndbv_initpt (gsl_vector * x)\n{\n size_t i;\n double h = 1.0 / (N + 1.0);\n\n for (i = 0; i < N; i++)\n {\n double t = (i + 1) * h;\n double z = t * (t - 1);\n gsl_vector_set (x, i, z);\n }\n}\n\nint\ndbv_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n size_t i;\n\n double h = 1.0 / (N + 1.0);\n\n for (i = 0; i < N; i++)\n {\n double z, ti = (i + 1) * h;\n double xi = 0, xim1 = 0, xip1 = 0;\n\n xi = gsl_vector_get (x, i);\n \n if (i > 0)\n xim1 = gsl_vector_get (x, i - 1);\n\n if (i < N - 1)\n xip1 = gsl_vector_get (x, i + 1);\n\n z = 2 * xi - xim1 - xip1 + h * h * pow(xi + ti + 1, 3.0) / 2.0;\n\n gsl_vector_set (f, i, z);\n\n }\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\ndbv_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n size_t i, j;\n\n double h = 1.0 / (N + 1.0);\n\n for (i = 0; i < N; i++)\n for (j = 0; j < N; j++)\n gsl_matrix_set (df, i, j, 0.0);\n\n for (i = 0; i < N; i++)\n {\n double dz_dxi, ti = (i + 1) * h;\n\n double xi = gsl_vector_get (x, i);\n \n dz_dxi = 2.0 + (3.0 / 2.0) * h * h * pow(xi + ti + 1, 2.0) ;\n \n gsl_matrix_set (df, i, i, dz_dxi);\n\n if (i > 0)\n gsl_matrix_set (df, i, i-1, -1.0);\n\n if (i < N - 1)\n gsl_matrix_set (df, i, i+1, -1.0);\n\n }\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\ndbv_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n dbv_f (x, params, f);\n dbv_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n\n/* Trigonometric Function */\n\ngsl_multiroot_function_fdf trig =\n{&trig_f,\n &trig_df,\n &trig_fdf,\n N, 0};\n\nvoid\ntrig_initpt (gsl_vector * x)\n{\n size_t i;\n\n for (i = 0; i < N; i++) /* choose an initial point which converges */\n {\n gsl_vector_set (x, i, 0.05); \n }\n}\n\nint\ntrig_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n size_t i;\n double sum = 0;\n\n for (i = 0; i < N; i++)\n {\n sum += cos(gsl_vector_get(x,i));\n }\n\n for (i = 0; i < N; i++)\n {\n double xi = gsl_vector_get (x,i);\n double z = N - sum + (i + 1) * (1 - cos(xi)) - sin(xi);\n\n gsl_vector_set (f, i, z);\n }\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\ntrig_df (const gsl_vector * x, void *params, gsl_matrix * df)\n{\n size_t i, j;\n\n for (i = 0; i < N; i++)\n {\n for (j = 0; j < N; j++)\n {\n double dz;\n double xi = gsl_vector_get(x, i);\n double xj = gsl_vector_get(x, j);\n\n if (j == i)\n dz = sin(xi) + (i + 1) * sin(xi) - cos(xi);\n else\n dz = sin(xj);\n \n gsl_matrix_set(df, i, j, dz);\n }\n }\n\n params = 0;\t\t\t/* avoid warning about unused parameters */\n\n return GSL_SUCCESS;\n}\n\nint\ntrig_fdf (const gsl_vector * x, void *params,\n\t\t gsl_vector * f, gsl_matrix * df)\n{\n trig_f (x, params, f);\n trig_df (x, params, df);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "319b3fd106986e2be87e2f00a5975397a82ed5d2", "size": 15798, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multiroots/test_funcs.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/multiroots/test_funcs.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/multiroots/test_funcs.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.2053691275, "max_line_length": 78, "alphanum_fraction": 0.6052031903, "num_tokens": 6019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6379307338866947}} {"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n $Id$\n*/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"string_f.h\"\n\n#include \n\n/* Numerical threshold for oct_bessel_k0 and oct_bessel_k1 */\n#define BESSEL_K_THRES 1.0e2\n\n/* ---------------------- Interface to GSL functions ------------------------ */\n\n\n/* Mathematical Functions */\ndouble FC_FUNC_(oct_asinh, OCT_ASINH)\n (const double *x)\n{\n return gsl_asinh(*x);\n}\n\n/* Special Functions */\ndouble FC_FUNC_(oct_gamma, OCT_GAMMA)\n (const double *x)\n{\n return gsl_sf_gamma(*x);\n}\n\ndouble FC_FUNC_(oct_hypergeometric, OCT_HYPERGEOMETRIC)\n (const double *a, const double*b, const double *x)\n{\n return gsl_sf_hyperg_U(*a, *b, *x);\n}\n\ndouble FC_FUNC_(oct_incomplete_gamma, OCT_INCOMPLETE_GAMMA)\n (const double *a, const double *x)\n{\n return gsl_sf_gamma_inc_Q(*a, *x);\n}\n\ndouble FC_FUNC_(oct_sph_bessel, OCT_SPH_BESSEL)\n (const fint *l, const double*x)\n{\n return gsl_sf_bessel_jl(*l, *x);\n}\n\ndouble FC_FUNC_(oct_bessel, OCT_BESSEL)\n (const fint *n, const double *x)\n{\n return gsl_sf_bessel_Jn(*n, *x);\n}\n\ndouble FC_FUNC_(oct_bessel_in, OCT_BESSEL_IN)\n (const fint *n, const double *x)\n{\n return gsl_sf_bessel_In(*n, *x);\n}\n\ndouble FC_FUNC_(oct_bessel_j0, OCT_BESSEL_J0)\n (const double *x)\n{\n return gsl_sf_bessel_J0(*x);\n}\n\ndouble FC_FUNC_(oct_bessel_j1, OCT_BESSEL_J1)\n (const double *x)\n{\n return gsl_sf_bessel_J1(*x);\n}\n\ndouble FC_FUNC_(oct_bessel_k0, OCT_BESSEL_K0)\n (const double *x)\n{\n if( *x > BESSEL_K_THRES )\n {\n return 0.0e0; \n } else {\n return gsl_sf_bessel_K0(*x);\n } \n}\n\ndouble FC_FUNC_(oct_bessel_k1, OCT_BESSEL_K1)\n (const double *x)\n{\n if( *x > BESSEL_K_THRES )\n {\n return 0.0e0; \n } else {\n return gsl_sf_bessel_K1(*x);\n } \n}\n\n/* the GSL headers specify double x, not const double x */\ndouble FC_FUNC_(oct_erfc, OCT_ERFC)\n (const double *x)\n{\n /* avoid floating invalids in the asymptotic limit */\n if(*x > 20.0) return 0.0;\n if(*x < -20.0) return 2.0;\n /* otherwise call gsl */\n return gsl_sf_erfc(*x);\n}\n\n/* the GSL headers specify double x, not const double x */\ndouble FC_FUNC_(oct_erf, OCT_ERF)\n (const double *x)\n{\n /* avoid floating invalids in the asymptotic limit */\n if(*x > 20.0) return 1.0;\n if(*x < -20.0) return -1.0;\n /* otherwise call gsl */\n return gsl_sf_erf(*x);\n}\n\ndouble FC_FUNC_(oct_legendre_sphplm, OCT_LEGENDRE_SPHPLM)\n (const fint *l, const int *m, const double *x)\n{\n return gsl_sf_legendre_sphPlm(*l, *m, *x);\n}\n\ndouble FC_FUNC_(oct_sine_integral, OCT_SINE_INTEGRAL)\n (const double *x)\n{\n return gsl_sf_Si(*x);\n}\n\n/* generalized Laguerre polynomials */\ndouble FC_FUNC_(oct_sf_laguerre_n, OCT_SF_LAGUERRE_N)\n (const int *n, const double *a, const double *x)\n{\n return gsl_sf_laguerre_n(*n, *a, *x);\n}\n\n\n/* Vectors and Matrices */\n\n\n/* Permutations */\n\n\n/* Combinations */\n\nvoid FC_FUNC_(oct_combination_init, OCT_COMBINATION_INIT)\n (gsl_combination **c, const fint *n, const fint *k)\n{\n *c = gsl_combination_calloc (*n, *k);\n}\n\nvoid FC_FUNC_(oct_combination_next, OCT_COMBINATION_NEXT)\n (gsl_combination **c, fint *next)\n{\n *next = gsl_combination_next (((gsl_combination *)(*c)));\n}\n\nvoid FC_FUNC_(oct_get_combination, OCT_GET_COMBINATION)\n (gsl_combination **c, fint *comb)\n{\n int i;\n for (i=0;i< ((gsl_combination *)(*c))->k; i++) {\n comb[i]=(fint)((gsl_combination *)(*c))->data[i]; \n }\n}\n\nvoid FC_FUNC_(oct_combination_end, OCT_COMBINATION_END)\n (gsl_combination **c)\n{\n gsl_combination_free (((gsl_combination *)(*c)));\n}\n\n/* Linear Algebra */\n\n\n/* Random Number Generation */\nvoid FC_FUNC_(oct_ran_init, OCT_RAN_INIT)\n (gsl_rng **r)\n{\n gsl_rng_env_setup();\n *r = gsl_rng_alloc(gsl_rng_default);\n}\n\nvoid FC_FUNC_(oct_ran_end, OCT_RAN_END)\n (gsl_rng **r)\n{\n gsl_rng_free(*r);\n}\n\n\n/* Random Number Distributions */ \ndouble FC_FUNC_(oct_ran_gaussian, OCT_RAN_GAUSSIAN)\n (const gsl_rng **r, const double *sigma)\n{\n return gsl_ran_gaussian(*r, *sigma);\n}\n\n\ndouble FC_FUNC_(oct_ran_flat, OCT_RAN_FLAT)\n (const gsl_rng **r, const double *a, const double *b)\n{\n return gsl_ran_flat(*r, *a, *b);\n}\n\n\n/* Interpolation */\nvoid FC_FUNC_(oct_spline_end, OCT_SPLINE_END)\n (void **spl, void **acc)\n{\n gsl_spline_free((gsl_spline *)(*spl));\n gsl_interp_accel_free((gsl_interp_accel *)(*acc));\n}\n\nvoid FC_FUNC_(oct_spline_fit, OCT_SPLINE_FIT)\n\t\t (const fint *nrc, const double *x, const double *y, void **spl, void **acc)\n{\n /* the GSL headers actually specify size_t instead of const int for nrc */\n *acc = (void *)gsl_interp_accel_alloc();\n *spl = (void *)gsl_spline_alloc(gsl_interp_cspline, *nrc);\t\n gsl_spline_init((gsl_spline *)(*spl), x, y, *nrc);\n fflush(stdout);\n}\n\ndouble FC_FUNC_(oct_spline_eval, OCT_SPLINE_EVAL)\n (const double *x, const void **spl, void **acc)\n{\n /* the GSL headers specify double x instead of const double x */\n return gsl_spline_eval((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\n\nvoid FC_FUNC_(oct_spline_eval_array, OCT_SPLINE_EVAL_ARRAY)\n (const fint * nn, double *xf, const void **spl, void **acc)\n{\n int ii;\n for(ii = 0; ii < *nn; ii++){\n xf[ii] = gsl_spline_eval((gsl_spline *)(*spl), xf[ii], (gsl_interp_accel *)(*acc));\n }\n}\n\nvoid FC_FUNC_(oct_spline_eval_array4, OCT_SPLINE_EVAL_ARRAY4)\n (const fint * nn, float *xf, const void **spl, void **acc)\n{\n int ii;\n for(ii = 0; ii < *nn; ii++){\n xf[ii] = (float) gsl_spline_eval((gsl_spline *)(*spl), (double) xf[ii], (gsl_interp_accel *)(*acc));\n }\n}\n\n/* use a stride of 2 to store into just the real part of a Fortran complex array */\nvoid FC_FUNC_(oct_spline_eval_arrayz, OCT_SPLINE_EVAL_ARRAYZ)\n (const fint * nn, double *xf, const void **spl, void **acc)\n{\n int ii;\n for(ii = 0; ii < *nn; ii++){\n xf[ii*2] = gsl_spline_eval((gsl_spline *)(*spl), xf[ii*2], (gsl_interp_accel *)(*acc));\n }\n}\n\n/* use a stride of 2 to store into just the real part of a Fortran complex array */\nvoid FC_FUNC_(oct_spline_eval_arrayc, OCT_SPLINE_EVAL_ARRAYC)\n (const fint * nn, float *xf, const void **spl, void **acc)\n{\n int ii;\n for(ii = 0; ii < *nn; ii++){\n xf[ii*2] = (float) gsl_spline_eval((gsl_spline *)(*spl), (double) xf[ii*2], (gsl_interp_accel *)(*acc));\n }\n}\n\n/* This function returns the number of points with which a spline\n\t was constructed (the size component of the gsl_spline struct). */\nfint FC_FUNC_(oct_spline_npoints, OCT_SPLINE_NPOINTS)\n (const void **spl)\n{\n return (fint)((gsl_spline *)(*spl))->size;\n}\n\n/* This function places in the x array the x values of a given spline spl*/ \nvoid FC_FUNC_(oct_spline_x, OCT_SPLINE_X)\n (const void **spl, double *x)\n{\n int size, i;\n\t\n size = (int)((gsl_spline *)(*spl))->size;\n for(i=0; ix[i];\n}\n\n/* This function places in the y array the y values of a given spline spl*/ \nvoid FC_FUNC_(oct_spline_y, OCT_SPLINE_Y)\n (const void **spl, double *y)\n{\n int size, i;\n\t\n size = (int)((gsl_spline *)(*spl))->size;\n for(i=0; iy[i];\n}\n\n/* Returns the integral of the spline stored in spl, between a and b */\ndouble FC_FUNC_(oct_spline_eval_integ, OCT_SPLINE_EVAL_INTEG)\n (const void **spl, const double *a, const double *b, void **acc)\n{\n /* the GSL headers specify double a, double b */\n return gsl_spline_eval_integ((gsl_spline *)(*spl), *a, *b, (gsl_interp_accel *)(* acc));\n}\n\n/* Performs the derivative of a spline */\ndouble FC_FUNC_(oct_spline_eval_der, OCT_SPLINE_EVAL_DER)\n (const double *x, const void **spl, void **acc)\n{\n /* the GSL headers specify double x */\n return gsl_spline_eval_deriv((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\n/* Performs the second derivative of a spline */\ndouble FC_FUNC_(oct_spline_eval_der2, OCT_SPLINE_EVAL_DER2)\n (const double *x, const void **spl, void **acc)\n{\n /* the GSL headers specify double x */\n return gsl_spline_eval_deriv2((gsl_spline *)(*spl), *x, (gsl_interp_accel *)(*acc));\n}\n\nvoid FC_FUNC_(oct_strerror, OCT_STRERROR)\n (const fint *err, STR_F_TYPE res STR_ARG1)\n{\n const char *c;\n\n c = gsl_strerror(*err);\n TO_F_STR1(c, res);\n}\n\n\n/* Chebyshev Approximations */\n/*\nvoid FC_FUNC_(oct_chebyshev_coeffs, OCT_CHEBYSHEV_COEFFS)\n (gsl_complex *coeffs, int *order)\n{\n int i;\n double f (double x, void *p){return cos(x);}\n double g (double x, void *p){return -sin(x);}\n gsl_cheb_series *cs = gsl_cheb_alloc (*order);\n gsl_function F;\n F.function = f;\n F.params = 0;\n gsl_cheb_init (cs, &F, -1.0, 1.0);\n for(i=0; i<=12; i++){GSL_SET_REAL(&coeffs[i], (*cs).c[i]);}\n F.function = g;\n F.params = 0;\n gsl_cheb_init (cs, &F, -1.0, 1.0);\n for(i=0; i<=12; i++){GSL_SET_IMAG(&coeffs[i], (*cs).c[i]);} \n}\n*/\n\n /* Numerical Derivatives.\n The following is an interface to the GSL support for numerical derivatives,\n in particular the gsl_deriv_central function. It computes a four points\n approximation to the derivative of a function, supplying an error estimation. */\n\n /* This is a type used to communicate with Fortran; func_nd is the type of the\n interface to a Fortran subroutine that calculates the value of the function.\n The first argument is the function argument, whereas the second is the function\n value. For convenience reasons, it is wrapped around the \"param_nd_t\" struct. */\ntypedef void (*func_nd)(double*, double*);\ntypedef struct{\n func_nd func;\n} param_nd_t;\n\n /* This is the function that is called by the GSL function gsl_deriv_central. It\n receives as first argument the function argument, and as second argument\n a pointer to a params data type (a GSL data type), which in this case should\n be a pointer to a param_nd_t data type, where the address of the Fortran\n subroutine is. */\ndouble function_oct_numerical_derivative (double x, void * params)\n{\n double res;\n param_nd_t * p;\n\n p = (param_nd_t *) params;\n p->func(&x, &res);\n return res;\n}\n /* This is the function that should be called by Fortran. The interface is defined\n in loct_math.F90 file. */\nvoid FC_FUNC_(oct_numerical_derivative, OCT_NUMERICAL_DERIVATIVE)\n (const double *x, const double *h, double *result, double *abserr, const func_nd f)\n{\n gsl_function F;\n param_nd_t p;\n\n p.func = f;\n F.function = &function_oct_numerical_derivative;\n F.params = (void *) &p;\n /* the GSL headers specify double x, double h */\n gsl_deriv_central (&F, *x, *h, result, abserr);\n return;\n}\n", "meta": {"hexsha": "659604be1baf030bb6972a60d989794c8fda3ef4", "size": 11643, "ext": "c", "lang": "C", "max_stars_repo_path": "src/math/oct_gsl_f.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/oct_gsl_f.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/oct_gsl_f.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": 26.8891454965, "max_line_length": 108, "alphanum_fraction": 0.6827278193, "num_tokens": 3568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969193, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6377370291185267}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct data {\n size_t n;\n double * y;\n double * sigma;\n};\n\nint\nexpb_f (const gsl_vector * x, void *params, \n gsl_vector * f)\n{\n size_t n = ((struct data *)params)->n;\n double *y = ((struct data *)params)->y;\n double *sigma = ((struct data *) params)->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\nexpb_df (const gsl_vector * x, void *params, \n gsl_matrix * J)\n{\n size_t n = ((struct data *)params)->n;\n double *sigma = ((struct data *) params)->sigma;\n\n double A = gsl_vector_get (x, 0);\n double lambda = gsl_vector_get (x, 1);\n\n size_t i;\n\n for (i = 0; i < n; i++)\n {\n /* Jacobian matrix J(i,j) = dfi / dxj, */\n /* where fi = (Yi - yi)/sigma[i], */\n /* Yi = A * exp(-lambda * i) + b */\n /* and the xj are the parameters (A,lambda,b) */\n double t = i;\n double 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\n }\n return GSL_SUCCESS;\n}\n\nint\nexpb_fdf (const gsl_vector * x, void *params,\n gsl_vector * f, gsl_matrix * J)\n{\n expb_f (x, params, f);\n expb_df (x, params, J);\n\n return GSL_SUCCESS;\n}\n\n#define N 40\n\nint\nmain (void)\n{\n const gsl_multifit_fdfsolver_type *T;\n gsl_multifit_fdfsolver *s;\n\n int status;\n size_t i, iter = 0;\n\n const size_t n = N;\n const size_t p = 3;\n\n gsl_matrix *covar = gsl_matrix_alloc (p, p);\n\n double y[N], sigma[N];\n\n struct data d = { n, y, sigma};\n \n gsl_multifit_function_fdf f;\n\n double x_init[3] = { 1.0, 0.0, 0.0 };\n\n gsl_vector_view x = gsl_vector_view_array (x_init, p);\n\n const gsl_rng_type * type;\n gsl_rng * r;\n\n gsl_rng_env_setup();\n\n type = gsl_rng_default;\n r = gsl_rng_alloc (type);\n\n f.f = &expb_f;\n f.df = &expb_df;\n f.fdf = &expb_fdf;\n f.n = n;\n f.p = p;\n f.params = &d;\n\n /* This is the data to be fitted */\n\n for (i = 0; i < n; i++)\n {\n double t = i;\n y[i] = 1.0 + 5 * exp (-0.1 * t) \n + gsl_ran_gaussian (r, 0.1);\n sigma[i] = 0.1;\n printf (\"data: %d %g %g\\n\", i, y[i], sigma[i]);\n };\n\n\n T = gsl_multifit_fdfsolver_lmsder;\n s = gsl_multifit_fdfsolver_alloc (T, n, p);\n gsl_multifit_fdfsolver_set (s, &f, &x.vector);\n\n print_state (iter, s);\n\n do\n {\n iter++;\n status = gsl_multifit_fdfsolver_iterate (s);\n\n printf (\"status = %s\\n\", gsl_strerror (status));\n\n print_state (iter, s);\n\n if (status)\n break;\n\n status = gsl_multifit_test_delta (s->dx, s->x,\n 1e-4, 1e-4);\n }\n while (status == GSL_CONTINUE && iter < 500);\n\n gsl_multifit_covar (s->J, 0.0, covar);\n\n gsl_matrix_fprintf (stdout, covar, \"%g\");\n\n#define FIT(i) gsl_vector_get(s->x, i)\n#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))\n\n printf (\"A = %.5f +/- %.5f\\n\", FIT(0), ERR(0));\n printf (\"lambda = %.5f +/- %.5f\\n\", FIT(1), ERR(1));\n printf (\"b = %.5f +/- %.5f\\n\", FIT(2), ERR(2));\n\n { \n double chi = gsl_blas_dnrm2(s->f);\n printf(\"chisq/dof = %g\\n\", pow(chi, 2.0)/ (n - p));\n }\n\n printf (\"status = %s\\n\", gsl_strerror (status));\n\n gsl_multifit_fdfsolver_free (s);\n return 0;\n}\n\nint\nprint_state (size_t iter, gsl_multifit_fdfsolver * s)\n{\n printf (\"iter: %3u x = % 15.8f % 15.8f % 15.8f \"\n \"|f(x)| = %g\\n\",\n iter,\n gsl_vector_get (s->x, 0), \n gsl_vector_get (s->x, 1),\n gsl_vector_get (s->x, 2), \n gsl_blas_dnrm2 (s->f));\n}\n", "meta": {"hexsha": "4e583a91d73d3a6f43ea1a93ab4826afa7a46dd1", "size": 3983, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multifit/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/multifit/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/multifit/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": 21.0740740741, "max_line_length": 56, "alphanum_fraction": 0.5495857394, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6364760416073497}} {"text": "/* randist/bernoulli.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 bernoulli distribution has the form,\n\n prob(0) = 1-p, prob(1) = p\n\n */\n\nunsigned int\ngsl_ran_bernoulli (const gsl_rng * r, double p)\n{\n double u = gsl_rng_uniform (r) ;\n\n if (u < p)\n {\n return 1 ;\n }\n else\n {\n return 0 ;\n }\n}\n\ndouble\ngsl_ran_bernoulli_pdf (const unsigned int k, double p)\n{\n if (k == 0)\n {\n return 1 - p ;\n }\n else if (k == 1)\n {\n return p ;\n }\n else\n {\n return 0 ;\n }\n}\n", "meta": {"hexsha": "c10f5a49ae343d9ecdfb607da32a74873e2ede27", "size": 1388, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/bernoulli.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/bernoulli.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/bernoulli.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.3870967742, "max_line_length": 81, "alphanum_fraction": 0.6563400576, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6361593436914492}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// Scaled mass functions\ndouble scaled_mass_function(double sigma, int mode, double *P) {\n double rval;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_WATSON)) { // Watson et al. (2013) universal FoF mass function\n double A = 0.282;\n double alpha = 2.163;\n double beta = 1.406;\n double gamma = 1.210;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {\n A = P[0];\n alpha = P[1];\n beta = P[2];\n gamma = P[3];\n }\n rval = A * (pow(beta / sigma, alpha) + 1.) * exp(-gamma / (sigma * sigma));\n } else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_TIAMAT)) { // Poole et al. (2013) universal FoF mass function for Tiamat\n double A = 0.03331;\n double alpha = 1.153;\n double beta = 12.33;\n double gamma = 1.009;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {\n A = P[0];\n alpha = P[1];\n beta = P[2];\n gamma = P[3];\n }\n rval = A * (pow(beta / sigma, alpha) + 1.) * exp(-gamma / (sigma * sigma));\n } else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_JENKINS)) { // Jenkins et al. (2001)\n double A = 0.315;\n double B = 0.61;\n double C = 3.8;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {\n A = P[0];\n B = P[1];\n C = P[2];\n }\n rval = A * exp(-pow((double)fabs((float)(take_ln(1. / sigma) + B)), C));\n } else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_ST)) { // Sheth-Torman (1999)\n double delta_k = 1.686;\n double A = 0.3222;\n double B = 0.707;\n double C = 0.3;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {\n A = P[0];\n B = P[1];\n C = P[2];\n }\n rval = A * sqrt(2. * B / PI) * (delta_k / sigma) * exp(-B * delta_k * delta_k / (2. * sigma * sigma)) *\n (1. + pow(sigma * sigma / (B * delta_k * delta_k), C));\n } else if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PS)) { // Press-Schechter (1974)\n double delta_k = 1.686;\n if(SID_CHECK_BITFIELD_SWITCH(mode, MF_PASS_PARAMS)) {\n delta_k = P[0];\n }\n rval = sqrt(2. / PI) * (delta_k / sigma) * exp(-delta_k * delta_k / (2. * sigma * sigma));\n } else\n SID_exit_error(\"A valid mass function was not specified with mode (%d) in scaled_mass_function().\\n\",\n SID_ERROR_LOGIC, mode);\n return (rval);\n}\n", "meta": {"hexsha": "abff6cd7c090aa0c0bc6478415e2e62ca405adb1", "size": 2749, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/scaled_mass_function.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/scaled_mass_function.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/mass_functions/scaled_mass_function.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.1805555556, "max_line_length": 121, "alphanum_fraction": 0.5372862859, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632926354617, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6361243511316628}} {"text": "static char help[] =\n\"Solves a 1D advection plus diffusion problem using FD discretization\\n\"\n\"and a structured-grid (DMDA). Option prefix -b1_. Equation is\\n\"\n\" - eps u'' + (a(x) u)' = 0\\n\"\n\"with a(x)=1, on domain [-1,1], and with Dirichlet boundary conditions\\n\"\n\"u(-1) = 1, u(1) = 0. Default eps=0.01. The diffusion discretized by\\n\"\n\"centered, as usual, but advection is by first-order upwinding, centered,\\n\"\n\"or van Leer limiter scheme. An analytic Jacobian is implemented, except\\n\"\n\"for the van Leer limiter. The limiters in the residual and Jacobian\\n\"\n\"evaluations are separately controllable.\\n\\n\";\n\n#include \n\ntypedef enum {NONE, CENTERED, VANLEER} LimiterType;\nstatic const char *LimiterTypes[] = {\"none\",\"centered\",\"vanleer\",\n \"LimiterType\", \"\", NULL};\n\nstatic PetscReal centered(PetscReal theta) {\n return 0.5;\n}\n\nstatic PetscReal vanleer(PetscReal theta) {\n const PetscReal abstheta = PetscAbsReal(theta);\n return 0.5 * (theta + abstheta) / (1.0 + abstheta);\n}\n\nstatic void* limiterptr[] = {NULL, ¢ered, &vanleer};\n\ntypedef struct {\n PetscReal eps; // amount of diffusion; require: eps > 0\n PetscReal (*limiter_fcn)(PetscReal),\n (*jac_limiter_fcn)(PetscReal);\n} AdCtx;\n\nstatic PetscReal u_exact(PetscReal x, AdCtx *usr) {\n return (1.0 - exp((x-1) / usr->eps)) / (1.0 - exp(- 2.0 / usr->eps));\n}\n\nstatic PetscReal wind_a(PetscReal x) {\n return 1.0;\n}\n\nextern PetscErrorCode FormUExact(DMDALocalInfo*, AdCtx*, Vec);\nextern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal*,PetscReal*, AdCtx*);\nextern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, PetscReal*, Mat, Mat, AdCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da, da_after;\n SNES snes;\n Vec u_initial, u, u_exact;\n PetscReal hx, err2, errinf;\n DMDALocalInfo info;\n LimiterType limiter = NONE, jac_limiter;\n PetscBool snesfdset, snesfdcolorset;\n AdCtx user;\n\n PetscInitialize(&argc,&argv,(char*)0,help);\n\n user.eps = 0.01;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"b1_\",\n \"both1d (1D advection-diffusion solver) options\",\"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-eps\",\"positive diffusion coefficient\",\n \"both1d.c\",user.eps,&(user.eps),NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-limiter\",\"flux-limiter type\",\n \"both1d.c\",LimiterTypes,\n (PetscEnum)limiter,(PetscEnum*)&limiter,NULL); CHKERRQ(ierr);\n jac_limiter = limiter;\n ierr = PetscOptionsEnum(\"-jac_limiter\",\"flux-limiter type used in Jacobian evaluation\",\n \"both1d.c\",LimiterTypes,\n (PetscEnum)jac_limiter,(PetscEnum*)&jac_limiter,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n if (user.eps <= 0.0) {\n SETERRQ1(PETSC_COMM_SELF,2,\"eps=%.3f invalid ... eps > 0 required\",user.eps);\n }\n user.limiter_fcn = limiterptr[limiter];\n ierr = PetscOptionsHasName(NULL,NULL,\"-snes_fd\",&snesfdset); CHKERRQ(ierr);\n ierr = PetscOptionsHasName(NULL,NULL,\"-snes_fd_color\",&snesfdcolorset); CHKERRQ(ierr);\n if (snesfdset || snesfdcolorset) {\n user.jac_limiter_fcn = NULL;\n jac_limiter = 4; // corresponds to empty string\n } else\n user.jac_limiter_fcn = limiterptr[jac_limiter];\n\n ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,\n 3, // default to hx=1 grid\n 1,2, // d.o.f., stencil width\n NULL,&da); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr);\n ierr = DMDASetUniformCoordinates(da,-1.0,1.0,-1.0,1.0,-1.0,1.0); CHKERRQ(ierr);\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 = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionLocal,&user);CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr);\n ierr = SNESSetApplicationContext(snes,&user); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);\n\n ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr);\n ierr = VecSet(u_initial,0.0); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);\n ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %d point grid (eps = %g, limiter = %s, jac_limiter = %s)\\n\",\n info.mx,user.eps,LimiterTypes[limiter],LimiterTypes[jac_limiter]); CHKERRQ(ierr);\n\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n ierr = FormUExact(&info,&user,u_exact); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) u_exact\n ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr);\n ierr = VecNorm(u,NORM_2,&err2); CHKERRQ(ierr);\n hx = 2.0 / (info.mx - 1);\n err2 *= PetscSqrtReal(hx);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"numerical error: |u-uexact|_inf = %.4e, |u-uexact|_2 = %.4e\\n\",\n errinf,err2); CHKERRQ(ierr);\n\n VecDestroy(&u_exact); SNESDestroy(&snes);\n return PetscFinalize();\n}\n\nPetscErrorCode FormUExact(DMDALocalInfo *info, AdCtx *usr, Vec uex) {\n PetscErrorCode ierr;\n PetscInt i;\n PetscReal hx, x, *auex;\n\n hx = 2.0 / (info->mx - 1);\n ierr = DMDAVecGetArray(info->da, uex, &auex);CHKERRQ(ierr);\n for (i=info->xs; ixs+info->xm; i++) {\n x = -1.0 + i * hx;\n auex[i] = u_exact(x,usr);\n }\n ierr = DMDAVecRestoreArray(info->da, uex, &auex);CHKERRQ(ierr);\n return 0;\n}\n\n/* compute residuals:\n F_i = (- eps u'' + (a(x) u)') * hx at interior points\n F_i = c (u - (b.c.)) at boundary points */\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal *au,\n PetscReal *aF, AdCtx *usr) {\n const PetscReal eps = usr->eps,\n hx = 2.0 / (info->mx - 1),\n halfx = hx / 2.0,\n hx2 = hx * hx,\n scdiag = (2.0 * eps) / hx + 1.0;\n PetscReal x, uE, uW, uxx, a, u_up, flux, u_dn, u_far, theta;\n PetscInt i;\n\n // for each owned cell, non-advective part of residual at cell center\n for (i=info->xs; ixs+info->xm; i++) {\n if (i == 0) {\n aF[i] = scdiag * (au[i] - 1.0);\n } else if (i == info->mx-1) {\n aF[i] = scdiag * (au[i] - 0.0);\n } else {\n uW = (i == 1) ? 1.0 : au[i-1];\n uE = (i == info->mx-2) ? 0.0 : au[i+1];\n uxx = (uW - 2.0 * au[i] + uE) / hx2;\n aF[i] = - eps * uxx * hx;\n }\n }\n // for each E face of an owned cell, compute flux at the face center\n // and then add that to the correct residual\n // note -1 start to get W faces of owned cells living on ownership\n // boundaries\n for (i=info->xs-1; ixs+info->xm; i++) {\n // if cell center is outside [-1,1], or on x=1 boundary, then no need\n // to compute a flux\n if (i < 0 || i == info->mx-1)\n continue;\n // traverse E cell face center points x_{i+1/2} for flux contributions\n // get pth component of wind and first-order upwind flux\n x = -1.0 + i * hx;\n a = wind_a(x + halfx);\n if (a >= 0.0) {\n if (i == 0) {\n u_up = 1.0;\n } else {\n u_up = au[i];\n }\n } else {\n if (i+1 == info->mx-1) {\n u_up = 0.0;\n } else {\n u_up = au[i+1];\n }\n }\n flux = a * u_up;\n if (usr->limiter_fcn != NULL) {\n // flux correction from high-order formula with psi(theta)\n if (a >= 0)\n u_dn = (i+1 < info->mx-1) ? au[i+1] : 0.0;\n else\n u_dn = au[i];\n if (u_dn != u_up) {\n if (a >= 0)\n u_far = (i-1 > 0) ? au[i-1] : 1.0;\n else\n u_far = (i+2 < info->mx-1) ? au[i+2] : 0.0;\n theta = (u_up - u_far) / (u_dn - u_up);\n flux += a * (*(usr->limiter_fcn))(theta) * (u_dn - u_up);\n }\n }\n // update non-boundary and owned F_i on both sides of computed flux\n // note aF[] does not have stencil width\n if (i > 0 && i >= info->xs)\n aF[i] += flux; // flux out of i at E\n if (i+1 < info->mx-1 && i+1 < info->xs + info->xm)\n aF[i+1] -= flux; // flux into i+1 at W\n }\n return 0;\n}\n\nPetscErrorCode FormJacobianLocal(DMDALocalInfo *info, PetscReal *u,\n Mat J, Mat P, AdCtx *usr) {\n PetscErrorCode ierr;\n const PetscReal eps = usr->eps,\n hx = 2.0 / (info->mx - 1),\n halfx = hx / 2.0,\n scdiag = (2.0 * eps) / hx + 1.0;\n PetscInt i, col[3];\n PetscReal x, aE, aW, v[3];\n\n if (usr->jac_limiter_fcn == &vanleer) {\n SETERRQ(PETSC_COMM_SELF,1,\"Jacobian for vanleer limiter is not implemented\");\n }\n\n ierr = MatZeroEntries(P); CHKERRQ(ierr);\n\n for (i=info->xs; ixs+info->xm; i++) {\n if (i == 0 || i == info->mx-1) {\n v[0] = scdiag;\n ierr = MatSetValues(P,1,&i,1,&i,v,ADD_VALUES); CHKERRQ(ierr);\n } else {\n // diffusive part\n col[0] = i;\n v[0] = (2.0 * eps) / hx;\n col[1] = i-1;\n v[1] = (i-1 > 0) ? - eps / hx : 0.0;\n col[2] = i+1;\n v[2] = (i+1 < info->mx-1) ? - eps / hx : 0.0;\n ierr = MatSetValues(P,1,&i,3,col,v,ADD_VALUES); CHKERRQ(ierr);\n // advective part: from each adjacent face\n x = -1.0 + i * hx;\n aE = wind_a(x + halfx);\n aW = wind_a(x - halfx);\n if (aE >= 0.0) {\n col[0] = i;\n v[0] = aE;\n } else {\n col[0] = i+1;\n v[0] = (i+1 < info->mx-1) ? aE : 0.0; // check if i+1 is boundary\n }\n if (aW >= 0.0) {\n col[1] = i-1;\n v[1] = (i-1 > 0) ? - aW : 0.0; // check if i-1 is boundary\n } else {\n col[1] = i;\n v[1] = - aW;\n }\n ierr = MatSetValues(P,1,&i,2,col,v,ADD_VALUES); CHKERRQ(ierr);\n if (usr->jac_limiter_fcn == ¢ered) {\n col[0] = i+1;\n col[1] = i;\n if (aE >= 0.0) {\n v[0] = (i+1 < info->mx-1) ? aE/2.0 : 0.0; // check if i+1 is boundary\n v[1] = - aE/2.0;\n } else {\n v[0] = (i+1 < info->mx-1) ? - aE/2.0 : 0.0; // check if i+1 is boundary\n v[1] = aE/2.0;\n }\n ierr = MatSetValues(P,1,&i,2,col,v,ADD_VALUES); CHKERRQ(ierr);\n col[0] = i;\n col[1] = i-1;\n if (aW >= 0.0) {\n v[0] = - aW/2.0;\n v[1] = (i-1 > 0) ? aW/2.0 : 0.0; // check if i-1 is boundary\n } else {\n v[0] = aW/2.0;\n v[1] = (i-1 > 0) ? - aW/2.0 : 0.0; // check if i-1 is boundary\n }\n ierr = MatSetValues(P,1,&i,2,col,v,ADD_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\n", "meta": {"hexsha": "8f1fc8dc8643381857654576acbda7f3c6845643", "size": 12076, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch11/solns/both1d.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/ch11/solns/both1d.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/ch11/solns/both1d.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 39.4640522876, "max_line_length": 92, "alphanum_fraction": 0.5271613117, "num_tokens": 3800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6358076894388017}} {"text": "/* linalg/ql.c\n * \n * Copyright (C) 2019 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* Factorise a general M x N matrix A into\n * \n * A = Q L\n *\n * where Q is orthogonal (M x M) and L is lower triangular (M x N).\n *\n * Q is stored as a packed set of Householder transformations in the\n * strict upper triangular part of the input matrix.\n *\n * L is stored in the diagonal and lower triangle of the input matrix.\n *\n * 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 = [A(1,N-k+i), A(2,N-k+i), ... , A(M-k+i,N-k+i), 1, 0, ..., 0]\n *\n * This storage scheme is the same as in LAPACK. */\n\n/*\ngsl_linalg_QL_decomp()\n Perform QL decomposition of a matrix A\n\nInputs: A - M-by-N matrix\n tau - (output) Householder coefficients, length N\n\nNotes:\n1) The K = MIN(M, N) Householder scalars are stored in tau(N-K+1:N)\non output; the rest of tau is used as temporary workspace\n*/\n\nint\ngsl_linalg_QL_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 != N)\n {\n GSL_ERROR (\"size of tau must be N\", GSL_EBADLEN);\n }\n else\n {\n const size_t K = GSL_MIN(M, N);\n size_t i;\n\n for (i = 0; i < K; i++)\n {\n /* compute the Householder transformation to annihilate the (N-K+i)-th\n column of the matrix */\n\n gsl_vector_view c = gsl_matrix_subcolumn (A, N - i - 1, 0, M - i);\n double * alpha = gsl_matrix_ptr(A, M - i - 1, N - i - 1);\n double tau_j = gsl_linalg_householder_transform2 (alpha, &(c.vector));\n\n /* apply the transformation to A(1:M-i,1:N-i-2) from the left */\n if (i + 1 < N)\n {\n gsl_vector_view work = gsl_vector_subvector(tau, 0, N - i - 1);\n gsl_matrix_view m = gsl_matrix_submatrix (A, 0, 0, M - i, N - i - 1);\n double tmp = *alpha;\n\n *alpha = 1.0;\n gsl_linalg_householder_left (tau_j, &(c.vector), &(m.matrix), &work.vector);\n *alpha = tmp;\n }\n\n gsl_vector_set (tau, N - i - 1, tau_j);\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* form the orthogonal matrix Q from the packed QL matrix */\nint\ngsl_linalg_QL_unpack (const gsl_matrix * QL, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * L)\n{\n const size_t M = QL->size1;\n const size_t N = QL->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 (L->size1 != M || L->size2 != N)\n {\n GSL_ERROR (\"L matrix must be M x N\", GSL_ENOTSQR);\n }\n else if (tau->size != N)\n {\n GSL_ERROR (\"size of tau must be N\", GSL_EBADLEN);\n }\n else\n {\n const size_t K = GSL_MIN(M, N);\n size_t i;\n\n /* initialize Q to the identity */\n gsl_matrix_set_identity (Q);\n\n for (i = 0; i < K; ++i)\n {\n gsl_vector_const_view h = gsl_matrix_const_subcolumn (QL, N - K + i, 0, M - K + i + 1);\n gsl_matrix_view m = gsl_matrix_submatrix (Q, 0, 0, M - K + i + 1, M - K + i + 1);\n gsl_vector_view work = gsl_matrix_subcolumn(L, 0, 0, M - K + i + 1);\n double ti = gsl_vector_get (tau, N - K + i);\n double * ptr = gsl_matrix_ptr((gsl_matrix *) QL, M - K + i, N - K + i);\n double tmp = *ptr;\n\n *ptr = 1.0;\n gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector);\n *ptr = tmp;\n }\n\n /* form the left triangular matrix L from a packed QL matrix */\n gsl_matrix_set_zero(L);\n\n if (M >= N)\n {\n gsl_matrix_const_view src = gsl_matrix_const_submatrix(QL, M - N, 0, N, N);\n gsl_matrix_view dest = gsl_matrix_submatrix(L, M - N, 0, N, N);\n gsl_matrix_tricpy(CblasLower, CblasNonUnit, &dest.matrix, &src.matrix);\n }\n else\n {\n gsl_matrix_const_view src1 = gsl_matrix_const_submatrix(QL, 0, 0, M, N - M);\n gsl_matrix_view dest1 = gsl_matrix_submatrix(L, 0, 0, M, N - M);\n\n gsl_matrix_const_view src2 = gsl_matrix_const_submatrix(QL, 0, N - M, M, M);\n gsl_matrix_view dest2 = gsl_matrix_submatrix(L, 0, N - M, M, M);\n\n gsl_matrix_memcpy(&dest1.matrix, &src1.matrix);\n gsl_matrix_tricpy(CblasLower, CblasNonUnit, &dest2.matrix, &src2.matrix);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "0fcabb0ec953cd30e236ceefa192b3e0c274542d", "size": 5395, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/ql.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 31.0057471264, "max_line_length": 100, "alphanum_fraction": 0.5977757183, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6355110932656522}} {"text": "/* linalg/cholesky_band.c\n *\n * Copyright (C) 2018, 2019, 2020 Patrick Alken\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic double cholesky_band_norm1(const gsl_matrix * A);\nstatic int cholesky_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params);\n\n/*\ngsl_linalg_cholesky_band_decomp()\n Cholesky decomposition of a square symmetric positive definite banded\nmatrix\n\nInputs: A - matrix in banded format, N-by-ndiag where N is the size of\n the matrix and ndiag is the number of nonzero diagonals.\n\nNotes:\n1) The main diagonal of the Cholesky factor is stored in the first column\nof A; the first subdiagonal in the second column and so on.\n\n2) If ndiag > 1, the 1-norm of A is stored in A(N,ndiag) on output\n\n3) At each diagonal element, the matrix is factored as\n\nA(j:end,j:end) = [ A11 A21^T ] = [ alpha 0 ] [ alpha v^T ]\n [ A21 A22 ] [ v L ] [ 0 L^T ]\n\nwhere:\n\nalpha = sqrt(A(j,j))\nv = A(j+1:end, j) / alpha\nA22 = L L^T + v v^T\n\nSo we start at A(1,1) and work right. Pseudo-code is:\n\nloop j = 1, ..., N\n alpha = sqrt(A(j,j))\n A(j+1:end, j) := A(j+1:end, j) / alpha (DSCAL)\n A(j+1:end, j+1:end) -= v v^T (DSYR)\n\nDue to the banded structure, v has at most p non-zero elements, where\np is the lower bandwidth\n*/\n\nint\ngsl_linalg_cholesky_band_decomp(gsl_matrix * A)\n{\n const size_t N = A->size1; /* size of matrix */\n const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */\n\n if (ndiag > N)\n {\n GSL_ERROR (\"invalid matrix dimensions\", GSL_EBADLEN);\n }\n else\n {\n const size_t p = ndiag - 1; /* lower bandwidth */\n const int kld = (int) GSL_MAX(1, p);\n size_t j;\n\n if (ndiag > 1)\n {\n /*\n * calculate 1-norm of A and store in lower right of matrix, which is not accessed\n * by rest of routine. gsl_linalg_cholesky_band_rcond() will use this later. If\n * A is diagonal, there is no empty slot to store the 1-norm, so the rcond routine\n * will have to reconstruct it from the Cholesky factor.\n */\n double Anorm = cholesky_band_norm1(A);\n gsl_matrix_set(A, N - 1, p, Anorm);\n }\n\n for (j = 0; j < N; ++j)\n {\n double ajj = gsl_matrix_get(A, j, 0);\n size_t lenv;\n\n if (ajj <= 0.0)\n {\n GSL_ERROR(\"matrix is not positive definite\", GSL_EDOM);\n }\n\n ajj = sqrt(ajj);\n gsl_matrix_set(A, j, 0, ajj);\n\n /* number of elements in v, which will normally be p, unless we\n * are in lower right corner of matrix */\n lenv = GSL_MIN(p, N - j - 1);\n\n if (lenv > 0)\n {\n gsl_vector_view v = gsl_matrix_subrow(A, j, 1, lenv);\n gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, 0, lenv, lenv);\n\n gsl_blas_dscal(1.0 / ajj, &v.vector);\n\n m.matrix.tda = kld;\n gsl_blas_dsyr(CblasUpper, -1.0, &v.vector, &m.matrix);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_band_solve (const gsl_matrix * LLT,\n const gsl_vector * b,\n gsl_vector * x)\n{\n if (LLT->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LLT->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n int status;\n\n /* copy x <- b */\n gsl_vector_memcpy (x, b);\n\n status = gsl_linalg_cholesky_band_svx(LLT, x);\n\n return status;\n }\n}\n\nint\ngsl_linalg_cholesky_band_svx (const gsl_matrix * LLT, gsl_vector * x)\n{\n if (LLT->size1 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* solve for c using forward-substitution, L c = b */\n cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit,\n (int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,\n x->data, x->stride);\n\n /* perform back-substitution, L^T x = c */\n cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasNonUnit,\n (int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,\n x->data, x->stride);\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_band_solvem (const gsl_matrix * LLT,\n const gsl_matrix * B,\n gsl_matrix * X)\n{\n if (LLT->size1 != B->size1)\n {\n GSL_ERROR (\"LLT size1 must match B size1\", GSL_EBADLEN);\n }\n else if (LLT->size1 != X->size1)\n {\n GSL_ERROR (\"LLT size1 must match solution size1\", GSL_EBADLEN);\n }\n else if (B->size2 != X->size2)\n {\n GSL_ERROR (\"B size2 must match X size2\", GSL_EBADLEN);\n }\n else\n {\n int status;\n\n /* copy X <- B */\n gsl_matrix_memcpy (X, B);\n\n status = gsl_linalg_cholesky_band_svxm(LLT, X);\n\n return status;\n }\n}\n\nint\ngsl_linalg_cholesky_band_svxm (const gsl_matrix * LLT, gsl_matrix * X)\n{\n if (LLT->size1 != X->size1)\n {\n GSL_ERROR (\"LLT size1 must match solution size1\", GSL_EBADLEN);\n }\n else\n {\n int status;\n const size_t nrhs = X->size2;\n size_t j;\n\n for (j = 0; j < nrhs; ++j)\n {\n gsl_vector_view xj = gsl_matrix_column(X, j);\n\n status = gsl_linalg_cholesky_band_svx (LLT, &xj.vector);\n if (status)\n return status;\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_band_invert (const gsl_matrix * LLT, gsl_matrix * Ainv)\n{\n if (Ainv->size1 != Ainv->size2)\n {\n GSL_ERROR(\"Ainv must be square\", GSL_ENOTSQR);\n }\n else if (LLT->size1 != Ainv->size1)\n {\n GSL_ERROR(\"cholesky matrix has different dimensions from Ainv\", GSL_EBADLEN);\n }\n else\n {\n int status;\n\n /* unpack Cholesky factor into lower triangle of Ainv */\n status = gsl_linalg_cholesky_band_unpack(LLT, Ainv);\n if (status)\n return status;\n\n /* call the standard Cholesky inversion routine */\n status = gsl_linalg_cholesky_invert(Ainv);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_band_unpack (const gsl_matrix * LLT, gsl_matrix * L)\n{\n const size_t N = LLT->size1;\n\n if (N != L->size1)\n {\n GSL_ERROR(\"L matrix does not match LLT dimensions\", GSL_EBADLEN);\n }\n else if (L->size1 != L->size2)\n {\n GSL_ERROR(\"L matrix is not square\", GSL_ENOTSQR);\n }\n else\n {\n const size_t p = LLT->size2 - 1; /* lower bandwidth */\n size_t i;\n\n for (i = 0; i < p + 1; ++i)\n {\n gsl_vector_const_view v = gsl_matrix_const_subcolumn(LLT, i, 0, N - i);\n gsl_vector_view w = gsl_matrix_subdiagonal(L, i);\n\n gsl_vector_memcpy(&w.vector, &v.vector);\n }\n\n /* zero out remaining subdiagonals */\n for (i = p + 1; i < N; ++i)\n {\n gsl_vector_view w = gsl_matrix_subdiagonal(L, i);\n gsl_vector_set_zero(&w.vector);\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_band_rcond (const gsl_matrix * LLT, double * rcond, gsl_vector * work)\n{\n const size_t N = LLT->size1;\n\n if (work->size != 3 * N)\n {\n GSL_ERROR (\"work vector must have length 3*N\", GSL_EBADLEN);\n }\n else\n {\n int status;\n const size_t ndiag = LLT->size2;\n double Anorm; /* ||A||_1 */\n double Ainvnorm; /* ||A^{-1}||_1 */\n\n if (ndiag == 1)\n {\n /* diagonal matrix, compute 1-norm since it has not been stored */\n gsl_vector_const_view v = gsl_matrix_const_column(LLT, 0);\n Anorm = gsl_vector_max(&v.vector);\n Anorm = Anorm * Anorm;\n }\n else\n {\n /* 1-norm is stored in A(N, ndiag) by gsl_linalg_cholesky_band_decomp() */\n Anorm = gsl_matrix_get(LLT, N - 1, ndiag - 1);\n }\n\n *rcond = 0.0;\n\n /* return if matrix is singular */\n if (Anorm == 0.0)\n return GSL_SUCCESS;\n\n status = gsl_linalg_invnorm1(N, cholesky_band_Ainv, (void *) LLT, &Ainvnorm, work);\n if (status)\n return status;\n\n if (Ainvnorm != 0.0)\n *rcond = (1.0 / Anorm) / Ainvnorm;\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_cholesky_band_scale()\n This function computes scale factors diag(S), such that\n\ndiag(S) A diag(S)\n\nhas a condition number within a factor N of the matrix\nwith the smallest condition number over all possible\ndiagonal scalings. See Corollary 7.6 of:\n\nN. J. Higham, Accuracy and Stability of Numerical Algorithms (2nd Edition),\nSIAM, 2002.\n\nInputs: A - symmetric positive definite matrix\n S - (output) scale factors, S_i = 1 / sqrt(A_ii)\n*/\n\nint\ngsl_linalg_cholesky_band_scale(const gsl_matrix * A, gsl_vector * S)\n{\n const size_t N = A->size1; /* size of matrix */\n const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */\n\n if (ndiag > N)\n {\n GSL_ERROR (\"invalid matrix dimensions\", GSL_EBADLEN);\n }\n else if (N != S->size)\n {\n GSL_ERROR(\"S must have length N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* compute S_i = 1/sqrt(A_{ii}) */\n for (i = 0; i < N; ++i)\n {\n double Aii = gsl_matrix_get(A, i, 0);\n\n if (Aii <= 0.0)\n gsl_vector_set(S, i, 1.0); /* matrix not positive definite */\n else\n gsl_vector_set(S, i, 1.0 / sqrt(Aii));\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_cholesky_band_scale_apply()\n This function applies scale transformation to A:\n\nA <- diag(S) A diag(S)\n\nInputs: A - (input/output)\n on input, symmetric positive definite matrix in banded format\n on output, diag(S) * A * diag(S) in banded format\n S - (input) scale factors\n*/\n\nint\ngsl_linalg_cholesky_band_scale_apply(gsl_matrix * A, const gsl_vector * S)\n{\n const size_t N = A->size1; /* size of matrix */\n const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */\n\n if (ndiag > N)\n {\n GSL_ERROR (\"invalid matrix dimensions\", GSL_EBADLEN);\n }\n else if (N != S->size)\n {\n GSL_ERROR(\"S must have length N\", GSL_EBADLEN);\n }\n else\n {\n size_t i, j;\n\n for (j = 0; j < N; ++j)\n {\n double sj = gsl_vector_get(S, j);\n\n for (i = j; i < GSL_MIN(N, j + ndiag); ++i)\n {\n double si = gsl_vector_get(S, i);\n double * ptr = gsl_matrix_ptr(A, j, i - j);\n *ptr *= sj * si;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/* compute 1-norm of symmetric banded matrix */\nstatic double\ncholesky_band_norm1(const gsl_matrix * A)\n{\n const size_t N = A->size1;\n const size_t ndiag = A->size2; /* number of diagonals in band, including main diagonal */\n double value;\n\n if (ndiag == 1)\n {\n /* diagonal matrix */\n gsl_vector_const_view v = gsl_matrix_const_column(A, 0);\n CBLAS_INDEX_t idx = gsl_blas_idamax(&v.vector);\n value = gsl_vector_get(&v.vector, idx);\n }\n else\n {\n size_t j;\n\n value = 0.0;\n for (j = 0; j < N; ++j)\n {\n size_t ncol = GSL_MIN(ndiag, N - j); /* number of elements in column j below and including main diagonal */\n gsl_vector_const_view v = gsl_matrix_const_subrow(A, j, 0, ncol);\n double sum = gsl_blas_dasum(&v.vector);\n size_t k, l;\n\n /* sum now contains the absolute sum of elements below and including main diagonal for column j; we\n * have to add the symmetric elements above the diagonal */\n k = j;\n l = 1;\n while (k > 0 && l < ndiag)\n {\n double Akl = gsl_matrix_get(A, --k, l++);\n sum += fabs(Akl);\n }\n\n value = GSL_MAX(value, sum);\n }\n }\n\n return value;\n}\n\n/* x := A^{-1} x = A^{-t} x, A = L L^T */\nstatic int\ncholesky_band_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params)\n{\n gsl_matrix * LLT = (gsl_matrix * ) params;\n\n (void) TransA; /* unused parameter warning */\n\n /* compute x := L^{-1} x */\n cblas_dtbsv(CblasColMajor, CblasLower, CblasNoTrans, CblasNonUnit,\n (int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,\n x->data, x->stride);\n\n /* compute x := L^{-T} x */\n cblas_dtbsv(CblasColMajor, CblasLower, CblasTrans, CblasNonUnit,\n (int) LLT->size1, (int) (LLT->size2 - 1), LLT->data, LLT->tda,\n x->data, x->stride);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "2c0b0e26e3c0f5002dfcb4bce4822d212eb3cace", "size": 13527, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/cholesky_band.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/cholesky_band.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/cholesky_band.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.6804733728, "max_line_length": 117, "alphanum_fraction": 0.5845346344, "num_tokens": 4003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6355110932656522}} {"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#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"os-features.h\"\n#include \"gslutils.h\"\n#include \"errors.h\"\n\nstatic void errhandler(const char * reason,\n const char * file,\n int line,\n int gsl_errno) {\n ERROR(\"GSL error: \\\"%s\\\" in %s:%i (gsl errno %i = %s)\",\n reason, file, line,\n gsl_errno,\n gsl_strerror(gsl_errno));\n}\n\nvoid gslutils_use_error_system() {\n gsl_set_error_handler(errhandler);\n}\n\nint gslutils_invert_3x3(const double* A, double* B) {\n gsl_matrix* LU;\n gsl_permutation *p;\n gsl_matrix_view mB;\n int rtn = 0;\n int signum;\n\n p = gsl_permutation_alloc(3);\n gsl_matrix_const_view mA = gsl_matrix_const_view_array(A, 3, 3);\n mB = gsl_matrix_view_array(B, 3, 3);\n LU = gsl_matrix_alloc(3, 3);\n\n gsl_matrix_memcpy(LU, &mA.matrix);\n if (gsl_linalg_LU_decomp(LU, p, &signum) ||\n gsl_linalg_LU_invert(LU, p, &mB.matrix)) {\n ERROR(\"gsl_linalg_LU_decomp() or _invert() failed.\");\n rtn = -1;\n }\n\n gsl_permutation_free(p);\n gsl_matrix_free(LU);\n return rtn;\n}\n\nvoid gslutils_matrix_multiply(gsl_matrix* C,\n const gsl_matrix* A, const gsl_matrix* B) {\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A, B, 0.0, C);\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 * \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 \"ConjugateGradientSolver.h\"\n\nint ConjugateGradientSolver(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 *x, int iterationNumber) {\n\t\n\t//A*x=b\n\n double *Ap=(double *) malloc(nz_vector * sizeof(double));\n double *r=(double *) malloc(nz_vector * sizeof(double));\n double *p=(double *) malloc(nz_vector * sizeof(double));\n\t//double *x=(double *) calloc(nz_vector,sizeof(double));\n\n\t//r = b-A*x\n\t//If we take x=0 the init multiplication is avoided and r=b\n\t\n\tmemcpy(r, b, N*sizeof(double));\n\t\n\t//p=r\n\n\tmemcpy(p, r, N*sizeof(double));\n\t\n\t//rsold = r*r\n\tdouble rsold = cblas_ddot(N,r,1,r,1);\n\t\n\tint stop = 0;\n\t\t\n\tdouble alphaCG = 0.0;\n\t\t\n\tdouble rsnew = 0.0;\n\tunsigned long k = 0;\n\t\n\tunsigned long maxIterations = M*2;\n\t\n\tif(iterationNumber != 0 ){\n\t\tmaxIterations = iterationNumber;\n\t}\n\n\t//int i = 0;\n\t\n\twhile(!stop){\n\t\n\t\t//Ap=A*p\n\t\t// for(i=0; i\n#include \n\n// Function prototype\n// gsl_matrix commute(gsl_matrix, gsl_matrix);\n\nint main(void)\n{\n gsl_matrix *L_x = gsl_matrix_calloc(3,3);\n gsl_matrix *L_y = gsl_matrix_calloc(3,3);\n gsl_matrix *L_z = gsl_matrix_calloc(3,3);\n\n gsl_matrix_set(L_x,1,2,-1);\n gsl_matrix_set(L_x,2,1,1);\n\n gsl_matrix_set(L_y,0,2,1);\n gsl_matrix_set(L_y,2,0,-1);\n\n gsl_matrix_set(L_z,0,1,-1);\n gsl_matrix_set(L_z,1,0,1);\n\n\n for (int i=0;i<3;i++)\n for (int j=0;j<3;j++)\n printf(\"m(%d,%d) = %g\\n\", i, j,\n\t gsl_matrix_get(L_x,i,j));\n\n for (int i=0;i<3;i++)\n for (int j=0;j<3;j++)\n printf(\"m(%d,%d) = %g\\n\", i, j,\n\t gsl_matrix_get(L_y,i,j));\n\n for (int i=0;i<3;i++)\n for (int j=0;j<3;j++)\n printf(\"m(%d,%d) = %g\\n\", i, j,\n\t gsl_matrix_get(L_z,i,j));\n\n \n gsl_matrix_free(L_x);\n gsl_matrix_free(L_y);\n gsl_matrix_free(L_z);\n\n return 0;\n}\n\n//gsl_matrix commute(gsl_matrix x, gsl_matrix y)\n//{\n\n//}\n", "meta": {"hexsha": "59cd92d3edab1f8ba913c6007503f0435ce4bd20", "size": 1335, "ext": "c", "lang": "C", "max_stars_repo_path": "gslExamples/SO3.c", "max_stars_repo_name": "ernestyalumni/CompPhys", "max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z", "max_issues_repo_path": "gslExamples/SO3.c", "max_issues_repo_name": "ernestyalumni/CompPhys", "max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z", "max_forks_repo_path": "gslExamples/SO3.c", "max_forks_repo_name": "ernestyalumni/CompPhys", "max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z", "avg_line_length": 23.4210526316, "max_line_length": 252, "alphanum_fraction": 0.6486891386, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6350474568712554}} {"text": "#include \n#include \n#include \n#include \"matrix.h\"\n\nvoid Matrix_Multiply(Matrix a, Matrix b, Matrix c) {\n /* for dimentions:\n * a[m*k],b[k*n],c[m*n]\n * We use:\n * RowMajor, NoTrans, NoTrans, m, n, k, 1, A, k, B, n, 0, C, n);\n */\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, a.rows, b.cols, a.cols,\n 1, a.values, a.cols, b.values, b.cols, 0, c.values, b.cols);\n}\n\nvoid Matrix_Print(Matrix m) {\n printf(\"=====\\n\");\n printf(\"rows: %lld, columns: %lld\\n\", m.rows, m.cols);\n for (int i = 0; i < m.rows; i++) {\n for (int j = 0; j < m.cols; j++) {\n printf(\"%lf \", m.values[i * m.cols + j]);\n }\n printf(\"\\n\");\n }\n}\n\nvoid Matrix_Add(Matrix a, Matrix b, Matrix c) {\n for (int i = 0; i < a.rows * a.cols; i++) {\n c.values[i] = a.values[i] + b.values[i];\n }\n}\n\nvoid Matrix_Scale(Matrix a, double n) {\n cblas_dscal(a.rows * a.cols, n, a.values, 1);\n}\n\nvoid Matrix_Test(void) {\n double *A, *B, *C;\n int m, n, k, i;\n double alpha, beta;\n m = 2000, k = 200, n = 1000;\n printf(\n \" Initializing data for matrix multiplication C=A*B for matrix \\n\"\n \" A(%ix%i) and matrix B(%ix%i)\\n\",\n m, k, k, n);\n alpha = 1.0;\n beta = 0.0;\n\n A = (double *) malloc(m * k * sizeof(double));\n B = (double *) malloc(k * n * sizeof(double));\n C = (double *) malloc(m * n * sizeof(double));\n if (A == NULL || B == NULL || C == NULL) {\n printf(\"\\n ERROR: Can't allocate memory for matrices. Aborting... \\n\\n\");\n free(A);\n free(B);\n free(C);\n return;\n }\n\n printf(\" Intializing matrix data \\n\");\n for (i = 0; i < (m * k); i++) {\n A[i] = (double) (i + 1);\n }\n\n for (i = 0; i < (k * n); i++) {\n B[i] = (double) (-i - 1);\n }\n\n for (i = 0; i < (m * n); i++) {\n C[i] = 0.0;\n }\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, k,\n B, n, beta, C, n);\n printf(\"\\n Computations completed.\\n\");\n free(A);\n free(B);\n free(C);\n}", "meta": {"hexsha": "fe558c164edc5f3e128f0692ab51607bcf22a622", "size": 2120, "ext": "c", "lang": "C", "max_stars_repo_path": "src/matrix.c", "max_stars_repo_name": "RedisLabsModules/redis-ml", "max_stars_repo_head_hexsha": "18578794d975511b6a20212e67c07e5114d25074", "max_stars_repo_licenses": ["Adobe-2006"], "max_stars_count": 242.0, "max_stars_repo_stars_event_min_datetime": "2016-11-01T20:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T22:18:12.000Z", "max_issues_repo_path": "src/matrix.c", "max_issues_repo_name": "rmikio/redis-ml", "max_issues_repo_head_hexsha": "21480bd580a2620851ffd34f960d83e9f43fc4b5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2017-02-04T01:13:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-11T00:25:55.000Z", "max_forks_repo_path": "src/matrix.c", "max_forks_repo_name": "rmikio/redis-ml", "max_forks_repo_head_hexsha": "21480bd580a2620851ffd34f960d83e9f43fc4b5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2017-01-04T13:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T13:45:43.000Z", "avg_line_length": 26.5, "max_line_length": 82, "alphanum_fraction": 0.4872641509, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.635017546042329}} {"text": "/* fft/hc_main.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"hc_pass.h\"\n\nint\nFUNCTION(gsl_fft_halfcomplex,backward) (BASE data[], const size_t stride, \n const size_t n,\n const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable,\n TYPE(gsl_fft_real_workspace) * work)\n{\n int status = FUNCTION(gsl_fft_halfcomplex,transform) (data, stride, n, wavetable, work) ;\n return status ;\n}\n\nint\nFUNCTION(gsl_fft_halfcomplex,inverse) (BASE data[], const size_t stride, \n const size_t n,\n const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable,\n TYPE(gsl_fft_real_workspace) * work)\n{\n int status = FUNCTION(gsl_fft_halfcomplex,transform) (data, stride, n, wavetable, work);\n\n if (status)\n {\n return status;\n }\n\n /* normalize inverse fft with 1/n */\n\n {\n const double norm = 1.0 / n;\n size_t i;\n for (i = 0; i < n; i++)\n {\n data[stride*i] *= norm;\n }\n }\n return status;\n}\n\nint\nFUNCTION(gsl_fft_halfcomplex,transform) (BASE data[], const size_t stride, const size_t n,\n const TYPE(gsl_fft_halfcomplex_wavetable) * wavetable,\n TYPE(gsl_fft_real_workspace) * work)\n{\n BASE * const scratch = work->scratch;\n\n BASE * in;\n BASE * out;\n size_t istride, ostride ;\n\n\n size_t factor, product, q;\n size_t i;\n size_t nf;\n int state;\n int product_1;\n int tskip;\n TYPE(gsl_complex) *twiddle1, *twiddle2, *twiddle3, *twiddle4;\n\n if (n == 0)\n {\n GSL_ERROR (\"length n must be positive integer\", GSL_EDOM);\n }\n\n if (n == 1)\n { /* FFT of one data point is the identity */\n return 0;\n }\n\n if (n != wavetable->n)\n {\n GSL_ERROR (\"wavetable does not match length of data\", GSL_EINVAL);\n }\n\n if (n != work->n)\n {\n GSL_ERROR (\"workspace does not match length of data\", GSL_EINVAL);\n }\n\n nf = wavetable->nf;\n product = 1;\n state = 0;\n\n for (i = 0; i < nf; i++)\n {\n factor = wavetable->factor[i];\n product_1 = product;\n product *= factor;\n q = n / product;\n\n tskip = (q + 1) / 2 - 1;\n\n if (state == 0)\n {\n in = data;\n istride = stride;\n out = scratch;\n ostride = 1;\n state = 1;\n }\n else\n {\n in = scratch;\n istride = 1;\n out = data;\n ostride = stride;\n state = 0;\n }\n\n if (factor == 2)\n {\n twiddle1 = wavetable->twiddle[i];\n FUNCTION(fft_halfcomplex,pass_2) (in, istride, out, ostride, \n product, n, twiddle1);\n }\n else if (factor == 3)\n {\n twiddle1 = wavetable->twiddle[i];\n twiddle2 = twiddle1 + tskip;\n FUNCTION(fft_halfcomplex,pass_3) (in, istride, out, ostride,\n product, n, twiddle1, twiddle2);\n }\n else if (factor == 4)\n {\n twiddle1 = wavetable->twiddle[i];\n twiddle2 = twiddle1 + tskip;\n twiddle3 = twiddle2 + tskip;\n FUNCTION(fft_halfcomplex,pass_4) (in, istride, out, ostride,\n product, n, twiddle1, twiddle2, \n twiddle3);\n }\n else if (factor == 5)\n {\n twiddle1 = wavetable->twiddle[i];\n twiddle2 = twiddle1 + tskip;\n twiddle3 = twiddle2 + tskip;\n twiddle4 = twiddle3 + tskip;\n FUNCTION(fft_halfcomplex,pass_5) (in, istride, out, ostride,\n product, n, twiddle1, twiddle2, \n twiddle3, twiddle4);\n }\n else\n {\n twiddle1 = wavetable->twiddle[i];\n FUNCTION(fft_halfcomplex,pass_n) (in, istride, out, ostride,\n factor, product, n, twiddle1);\n }\n }\n\n if (state == 1) /* copy results back from scratch to data */\n {\n for (i = 0; i < n; i++)\n {\n data[stride*i] = scratch[i] ;\n }\n }\n\n return 0;\n\n}\n\n\n", "meta": {"hexsha": "591acd42eb834506934b0b43895cf2a46643308f", "size": 5258, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/fft/hc_main.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/hc_main.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/hc_main.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.8201058201, "max_line_length": 95, "alphanum_fraction": 0.5270064663, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262966, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6347436873378041}} {"text": "#ifndef SIR_H\n#define SIR_H\n\n#include \n#include \n#include \n#include \"DiffEq_Sim.h\"\n\nusing namespace std;\n\nclass SIR : public DiffEq_Sim {\n\n private:\n const double beta;\n const double gamma;\n\n public:\n SIR() : beta(0.0), gamma(0.0) { nbins=3;}\n SIR(double b, double g): beta(b), gamma(g) { nbins=3; }\n ~SIR() {};\n\n void initialize( double S, double I, double R) {\n y = new double[nbins];\n y[0] = S; y[1] = I; y[2] = R;\n }\n\n void derivative(double const y[], double dydt[]) {\n dydt[0] = -beta*y[0]*y[1];\n dydt[1] = +beta*y[0]*y[1] - gamma*y[1];\n dydt[2] = +gamma*y[1];\n }\n\n};\n\n#endif\n", "meta": {"hexsha": "59effc687880d42f30e6de9ca85cafe4dbd8bfde", "size": 750, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SIR_Sim.h", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "src/SIR_Sim.h", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "src/SIR_Sim.h", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 20.8333333333, "max_line_length": 63, "alphanum_fraction": 0.512, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730007, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6339147650090686}} {"text": "#pragma once\n\n#include \"rev/Utilities.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace rev {\n\ntemplate \nstruct WeightedControlPoint {\n PointType point;\n typename PointType::value_type weight;\n};\n\ntemplate \nclass NurbsCurve {\npublic:\n using ControlPointType = WeightedControlPoint;\n using ValueType = typename PointType::value_type;\n\n NurbsCurve(size_t order, gsl::span knots,\n gsl::span controlPoints)\n : _order(order)\n , _knots(knots.begin(), knots.end())\n , _controlPoints(controlPoints.begin(), controlPoints.end())\n {\n Expects(order > 1);\n Expects(static_cast(controlPoints.size()) >= order);\n Expects(knots.size() == (controlPoints.size() + order));\n }\n\n ValueType getStart() const { return _knots.front(); }\n\n ValueType getEnd() const { return _knots.back(); }\n\n PointType operator[](ValueType position) const\n {\n auto knotsBegin = _knots.begin();\n auto knotsEnd = _knots.end();\n auto spanStart = std::lower_bound(knotsBegin, knotsEnd, position);\n size_t controlPointIndex = std::distance(knotsBegin, spanStart);\n if (controlPointIndex == 0) {\n // Before the first knot. Just return the value of the first control\n // point.\n return _controlPoints.front().point;\n }\n\n if (spanStart == knotsEnd) {\n // We're past the last knot. Just return the value of the last control\n // point.\n return _controlPoints.back().point;\n }\n\n size_t controlPointsToProcess = _order;\n size_t controlPointCount = _controlPoints.size();\n if (controlPointIndex > controlPointCount) {\n controlPointsToProcess -= (controlPointIndex - controlPointCount);\n }\n\n PointType numerator{ 0 };\n ValueType denominator{ 0 };\n do {\n controlPointIndex--;\n auto& controlPoint = _controlPoints[controlPointIndex];\n ValueType weightedBasis\n = basisValue(position, controlPointIndex, _order) * controlPoint.weight;\n numerator += weightedBasis * _controlPoints[controlPointIndex].point;\n denominator += weightedBasis;\n controlPointsToProcess--;\n } while (controlPointIndex && controlPointsToProcess);\n return numerator / denominator;\n }\n\nprivate:\n ValueType basisValue(ValueType position, size_t controlPointIndex, size_t order) const\n {\n auto& controlPoint = _controlPoints[controlPointIndex];\n ValueType firstKnot = _knots[controlPointIndex];\n ValueType lastKnot = _knots[controlPointIndex + order];\n if (order == 2) {\n // Triangle function\n ValueType middleKnot = _knots[controlPointIndex + 1];\n if (position < middleKnot) {\n return rampUp(position, firstKnot, middleKnot);\n } else {\n return rampDown(position, middleKnot, lastKnot);\n }\n } else {\n size_t lowerOrder = order - 1;\n ValueType secondKnot = _knots[controlPointIndex + 1];\n ValueType secondToLastKnot = _knots[controlPointIndex + lowerOrder];\n\n ValueType result{ 0 };\n if (position < secondToLastKnot) {\n result += rampUp(position, firstKnot, secondToLastKnot)\n * basisValue(position, controlPointIndex, lowerOrder);\n }\n\n if (position > secondKnot) {\n result += rampDown(position, secondKnot, lastKnot)\n * basisValue(position, controlPointIndex + 1, lowerOrder);\n }\n\n return result;\n }\n }\n\n ValueType rampUp(ValueType value, ValueType bottom, ValueType top) const\n {\n if (nearEqual(top, bottom)) {\n return 0.5;\n }\n return (value - bottom) / (top - bottom);\n }\n\n ValueType rampDown(ValueType value, ValueType bottom, ValueType top) const\n {\n if (nearEqual(top, bottom)) {\n return 0.5;\n }\n return (top - value) / (top - bottom);\n }\n\n size_t _order;\n std::vector _knots;\n std::vector _controlPoints;\n};\n} // namespace rev", "meta": {"hexsha": "529b665a111198535de3bb2285fcabbcd4d1ff51", "size": 4438, "ext": "h", "lang": "C", "max_stars_repo_path": "engine/include/rev/NurbsCurve.h", "max_stars_repo_name": "eyebrowsoffire/rev", "max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "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": "engine/include/rev/NurbsCurve.h", "max_issues_repo_name": "eyebrowsoffire/rev", "max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z", "max_forks_repo_path": "engine/include/rev/NurbsCurve.h", "max_forks_repo_name": "eyebrowsoffire/rev", "max_forks_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "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.3684210526, "max_line_length": 90, "alphanum_fraction": 0.6167192429, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.633708150804373}} {"text": "/* specfunc/gegenbauer.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \"gsl_sf_gegenbauer.h\"\n\n#include \"error.h\"\n\n/* See: [Thompson, Atlas for Computing Mathematical Functions] */\n\n\nint\ngsl_sf_gegenpoly_1_e(double lambda, double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(lambda == 0.0) {\n result->val = 2.0*x;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n result->val = 2.0*lambda*x;\n result->err = 4.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_gegenpoly_2_e(double lambda, double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(lambda == 0.0) {\n const double txx = 2.0*x*x;\n result->val = -1.0 + txx;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(txx);\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n result->val = lambda*(-1.0 + 2.0*(1.0+lambda)*x*x);\n result->err = GSL_DBL_EPSILON * (2.0 * fabs(result->val) + fabs(lambda));\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_sf_gegenpoly_3_e(double lambda, double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(lambda == 0.0) {\n result->val = x*(-2.0 + 4.0/3.0*x*x);\n result->err = GSL_DBL_EPSILON * (2.0 * fabs(result->val) + fabs(x));\n return GSL_SUCCESS;\n }\n else {\n double c = 4.0 + lambda*(6.0 + 2.0*lambda);\n result->val = 2.0*lambda * x * ( -1.0 - lambda + c*x*x/3.0 );\n result->err = GSL_DBL_EPSILON * (2.0 * fabs(result->val) + fabs(lambda * x));\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_gegenpoly_n_e(int n, double lambda, double x, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(lambda <= -0.5 || n < 0) {\n DOMAIN_ERROR(result);\n }\n else if(n == 0) {\n result->val = 1.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(n == 1) {\n return gsl_sf_gegenpoly_1_e(lambda, x, result);\n }\n else if(n == 2) {\n return gsl_sf_gegenpoly_2_e(lambda, x, result);\n }\n else if(n == 3) {\n return gsl_sf_gegenpoly_3_e(lambda, x, result);\n }\n else {\n if(lambda == 0.0 && (x >= -1.0 || x <= 1.0)) {\n /* 2 T_n(x)/n */\n const double z = n * acos(x);\n result->val = 2.0 * cos(z) / n;\n result->err = 2.0 * GSL_DBL_EPSILON * fabs(z * result->val);\n return GSL_SUCCESS;\n }\n else {\n int k;\n gsl_sf_result g2;\n gsl_sf_result g3;\n int stat_g2 = gsl_sf_gegenpoly_2_e(lambda, x, &g2);\n int stat_g3 = gsl_sf_gegenpoly_3_e(lambda, x, &g3);\n int stat_g = GSL_ERROR_SELECT_2(stat_g2, stat_g3);\n double gkm2 = g2.val;\n double gkm1 = g3.val;\n double gk = 0.0;\n for(k=4; k<=n; k++) {\n gk = (2.0*(k+lambda-1.0)*x*gkm1 - (k+2.0*lambda-2.0)*gkm2) / k;\n\tgkm2 = gkm1;\n\tgkm1 = gk;\n }\n result->val = gk;\n result->err = 2.0 * GSL_DBL_EPSILON * 0.5 * n * fabs(gk);\n return stat_g;\n }\n }\n}\n\n\nint\ngsl_sf_gegenpoly_array(int nmax, double lambda, double x, double * result_array)\n{\n int k;\n\n /* CHECK_POINTER(result_array) */\n\n if(lambda <= -0.5 || nmax < 0) {\n GSL_ERROR(\"domain error\", GSL_EDOM);\n }\n\n /* n == 0 */\n result_array[0] = 1.0;\n if(nmax == 0) return GSL_SUCCESS;\n\n /* n == 1 */\n if(lambda == 0.0)\n result_array[1] = 2.0*x;\n else\n result_array[1] = 2.0*lambda*x;\n\n /* n <= nmax */\n for(k=2; k<=nmax; k++) {\n double term1 = 2.0*(k+lambda-1.0) * x * result_array[k-1];\n double term2 = (k+2.0*lambda-2.0)\t * result_array[k-2];\n result_array[k] = (term1 - term2) / k;\n }\n \n return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_gegenpoly_1(double lambda, double x)\n{\n EVAL_RESULT(gsl_sf_gegenpoly_1_e(lambda, x, &result));\n}\n\ndouble gsl_sf_gegenpoly_2(double lambda, double x)\n{\n EVAL_RESULT(gsl_sf_gegenpoly_2_e(lambda, x, &result));\n}\n\ndouble gsl_sf_gegenpoly_3(double lambda, double x)\n{\n EVAL_RESULT(gsl_sf_gegenpoly_3_e(lambda, x, &result));\n}\n\ndouble gsl_sf_gegenpoly_n(int n, double lambda, double x)\n{\n EVAL_RESULT(gsl_sf_gegenpoly_n_e(n, lambda, x, &result));\n}\n", "meta": {"hexsha": "ac8b6e57c7b5c9d85063579e06f724641765c88f", "size": 4951, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gegenbauer.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gegenbauer.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gegenbauer.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.3897435897, "max_line_length": 81, "alphanum_fraction": 0.620480711, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.633279597691029}} {"text": "/* min/golden.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\n/* goldensection.c -- goldensection minimum finding algorithm */\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\ntypedef struct\n {\n double dummy;\n }\ngoldensection_state_t;\n\nstatic int goldensection_init (void * vstate, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper);\nstatic int goldensection_iterate (void * vstate, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper);\n\nstatic int\ngoldensection_init (void * vstate, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper)\n{\n goldensection_state_t * state = (goldensection_state_t *) vstate;\n\n /* no initialization required, prevent warnings about unused variables */\n\n state = 0;\n f = 0;\n x_minimum = 0;\n f_minimum = 0;\n x_lower = 0;\n f_lower = 0;\n x_upper = 0;\n f_upper = 0;\n\n return GSL_SUCCESS;\n}\n\nstatic int\ngoldensection_iterate (void * vstate, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper)\n{\n goldensection_state_t * state = (goldensection_state_t *) vstate;\n\n const double x_center = *x_minimum ;\n const double x_left = *x_lower ;\n const double x_right = *x_upper ;\n\n const double f_min = *f_minimum;\n\n const double golden = 0.3819660; /* golden = (3 - sqrt(5))/2 */\n \n const double w_lower = (x_center - x_left);\n const double w_upper = (x_right - x_center);\n\n double x_new, f_new;\n\n state = 0 ; /* avoid warning about unused parameters */\n \n x_new = x_center + golden * ((w_upper > w_lower) ? w_upper : -w_lower) ;\n\n SAFE_FUNC_CALL (f, x_new, &f_new);\n\n if (f_new < f_min)\n {\n *x_minimum = x_new ;\n *f_minimum = f_new ;\n return GSL_SUCCESS;\n }\n else if (x_new < x_center && f_new > f_min)\n {\n *x_lower = x_new ;\n *f_lower = f_new ;\n return GSL_SUCCESS;\n }\n else if (x_new > x_center && f_new > f_min)\n {\n *x_upper = x_new ;\n *f_upper = f_new ;\n return GSL_SUCCESS;\n }\n else\n {\n return GSL_FAILURE;\n }\n}\n\n\nstatic const gsl_min_fminimizer_type goldensection_type =\n{\"goldensection\", /* name */\n sizeof (goldensection_state_t),\n &goldensection_init,\n &goldensection_iterate};\n\nconst gsl_min_fminimizer_type * gsl_min_fminimizer_goldensection = &goldensection_type;\n", "meta": {"hexsha": "49dfddb36cc7aacb1de17bbdb60f3d6c6204ae83", "size": 3431, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/min/golden.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/min/golden.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/min/golden.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": 28.3553719008, "max_line_length": 179, "alphanum_fraction": 0.6922180122, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6331247155012253}} {"text": "#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* dimension of fit */\n#define N_DIM 3\n\n/* number of basis functions for each variable */\n#define N_SUM_R 10\n#define N_SUM_THETA 10\n#define N_SUM_PHI 9\n\n#define R_MAX 3.0\n\ndouble\npsi_real_exact(int k, int l, int m, double r, double theta, double phi)\n{\n double R, T, P;\n\n R = pow(r, (double) l) *\n exp(-r*r) *\n gsl_sf_laguerre_n(k, l + 0.5, 2 * r * r);\n T = gsl_sf_legendre_sphPlm(l, m, cos(theta));\n P = cos(m * phi);\n\n return (R * T * P);\n}\n\n/* basis functions for each variable */\n\nint\nbasis_r(double r, double y[], void *params)\n{\n gsl_bspline_workspace *bw = params;\n gsl_vector_view v = gsl_vector_view_array(y, N_SUM_R);\n int s;\n\n /* use B-splines for r dependence */\n s = gsl_bspline_eval(r, &v.vector, bw);\n\n return s;\n}\n\nint\nbasis_theta(double theta, double y[], void *params)\n{\n size_t i;\n\n /* use Legendre polynomials for theta dependence */\n for (i = 0; i < N_SUM_THETA; ++i)\n y[i] = gsl_sf_legendre_Pl(i, cos(theta));\n\n return GSL_SUCCESS;\n}\n\nint\nbasis_phi(double phi, double y[], void *params)\n{\n size_t i;\n\n /* use standard Fourier basis (sin/cos) for phi dependence */\n for (i = 0; i < N_SUM_PHI; ++i)\n {\n if ((i % 2) == 0)\n y[i] = cos((double)(i/2) * phi);\n else\n y[i] = sin((double)((i+1)/2) * phi);\n }\n\n return GSL_SUCCESS;\n}\n\nint\nmain(int argc, char *argv[])\n{\n const size_t ndim = N_DIM; /* dimension of fit */\n const size_t ndata = 3000; /* number of data points to fit */\n size_t N[N_DIM]; /* upper bounds on model sums */\n int (*u[N_DIM])(double x, double y[], void *params);\n size_t i; /* looping */\n int k, l, m; /* quantum numbers */\n gsl_rng *rng_p;\n gsl_bspline_workspace *bspline_p;\n gsl_multifit_linear_workspace *multifit_p;\n gsl_multifit_ndlinear_workspace *ndlinear_p;\n gsl_vector *data; /* psi data */\n gsl_matrix *vars; /* parameters corresponding to psi data */\n gsl_matrix *X; /* matrix for least squares fit */\n gsl_vector *coeffs; /* fit coefficients */\n gsl_matrix *cov; /* covariance matrix */\n double chisq; /* chi^2 */\n double Rsq; /* R^2 */\n size_t ncoeffs; /* total number of fit coefficients */\n\n gsl_rng_env_setup();\n\n k = 5;\n l = 4;\n m = 2;\n\n N[0] = N_SUM_R;\n N[1] = N_SUM_THETA;\n N[2] = N_SUM_PHI;\n\n u[0] = &basis_r;\n u[1] = &basis_theta;\n u[2] = &basis_phi;\n\n rng_p = gsl_rng_alloc(gsl_rng_default);\n bspline_p = gsl_bspline_alloc(4, N_SUM_R - 2);\n ndlinear_p = gsl_multifit_ndlinear_alloc(ndim, N, u, bspline_p);\n\n ncoeffs = gsl_multifit_ndlinear_ncoeffs(ndlinear_p);\n\n multifit_p = gsl_multifit_linear_alloc(ndata, ncoeffs);\n data = gsl_vector_alloc(ndata);\n vars = gsl_matrix_alloc(ndata, ndim);\n X = gsl_matrix_alloc(ndata, ncoeffs);\n coeffs = gsl_vector_alloc(ncoeffs);\n cov = gsl_matrix_alloc(ncoeffs, ncoeffs);\n\n gsl_bspline_knots_uniform(0.0, R_MAX, bspline_p);\n\n /* this is the data to be fitted */\n\n for (i = 0; i < ndata; ++i)\n {\n double r = gsl_rng_uniform(rng_p) * R_MAX;\n double theta = gsl_rng_uniform(rng_p) * M_PI;\n double phi = gsl_rng_uniform(rng_p) * 2.0 * M_PI;\n double psi = psi_real_exact(k, l, m, r, theta, phi);\n double dpsi = gsl_ran_gaussian(rng_p, 0.05 * psi);\n\n /* keep track of (r, theta, phi) points */\n gsl_matrix_set(vars, i, 0, r);\n gsl_matrix_set(vars, i, 1, theta);\n gsl_matrix_set(vars, i, 2, phi);\n\n /* fill in RHS data vector */\n gsl_vector_set(data, i, psi + dpsi);\n }\n\n /* construct the design matrix X */\n gsl_multifit_ndlinear_design(vars, X, ndlinear_p);\n\n /* now do the actual least squares fit */\n gsl_multifit_linear(X, data, coeffs, cov, &chisq, multifit_p);\n\n /* compute R^2 */\n Rsq = 1.0 - chisq / gsl_stats_tss(data->data, 1, data->size);\n\n fprintf(stderr, \"chisq = %e, Rsq = %f\\n\", chisq, Rsq);\n\n /* now print out the model and the exact solution and compute rms error */\n {\n double eps_rms = 0.0;\n double volume = 0.0;\n double r, theta, phi;\n double dr = 0.05;\n double dtheta = 5.0 * M_PI / 180.0;\n double dphi = 5.0 * M_PI / 180.0;\n double x[N_DIM];\n gsl_vector_view xv = gsl_vector_view_array(x, N_DIM);\n double psi;\n double psi_model;\n double err;\n\n for (r = 0.01; r < R_MAX; r += dr)\n {\n for (theta = 0.0; theta < M_PI; theta += dtheta)\n {\n for (phi = 0.0; phi < 2.0 * M_PI; phi += dphi)\n {\n double dV = r * r * sin(theta) * dr * dtheta * dphi;\n\n x[0] = r;\n x[1] = theta;\n x[2] = phi;\n\n /* compute model value for this (r, theta, phi) */\n psi_model = gsl_multifit_ndlinear_calc(&xv.vector,\n coeffs,\n ndlinear_p);\n\n /* compute exact value for this (r, theta, phi) */\n psi = psi_real_exact(k, l, m, r, theta, phi);\n\n err = psi_model - psi;\n eps_rms += err * err * dV;\n volume += dV;\n\n if (phi == 0.0)\n printf(\"%e %e %e %e\\n\", r, theta, psi, psi_model);\n }\n }\n printf(\"\\n\");\n }\n\n eps_rms /= volume;\n eps_rms = sqrt(eps_rms);\n fprintf(stderr, \"rms error over all parameter space = %e\\n\", eps_rms);\n }\n\n gsl_rng_free(rng_p);\n gsl_bspline_free(bspline_p);\n gsl_multifit_ndlinear_free(ndlinear_p);\n gsl_multifit_linear_free(multifit_p);\n gsl_vector_free(data);\n gsl_matrix_free(vars);\n gsl_matrix_free(X);\n gsl_vector_free(coeffs);\n gsl_matrix_free(cov);\n\n return 0;\n} /* main() */\n", "meta": {"hexsha": "a4872bf1a77cf2a2be99b4c83307d434f54fb98d", "size": 6164, "ext": "c", "lang": "C", "max_stars_repo_path": "src/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c", "max_stars_repo_name": "rennhak/Keyposes", "max_stars_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-26T07:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-05T12:45:52.000Z", "max_issues_repo_path": "src/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c", "max_issues_repo_name": "rennhak/Keyposes", "max_issues_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "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/BodyComponents/archive/ndlinear-1.0/doc/examples/harmosc.c", "max_forks_repo_name": "rennhak/Keyposes", "max_forks_repo_head_hexsha": "e5ffe4c849b0894f27d58985b41ec8edd3432be1", "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.9170305677, "max_line_length": 76, "alphanum_fraction": 0.5850097339, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6329938264962304}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n/*! \\file second_order.c\n * \\brief produce actual ICs from special 2nd order lpt ICs\n */\n\n\n\ndouble F1_Omega(double a)\n{\n double omega_a;\n\n omega_a = All.Omega0 / (All.Omega0 + a * (1 - All.Omega0 - All.OmegaLambda) + a * a * a * All.OmegaLambda);\n\n return pow(omega_a, 5.0 / 9);\n}\n\ndouble F2_Omega(double a)\n{\n double omega_a;\n\n omega_a = All.Omega0 / (All.Omega0 + a * (1 - All.Omega0 - All.OmegaLambda) + a * a * a * All.OmegaLambda);\n\n return 2.0 * pow(omega_a, 6.0 / 11);\n}\n\n\nvoid second_order_ics(void)\n{\n int i, j;\n double a, hubble, fac1, fac2, fac3;\n double ax, ay, az;\n\n if(ThisTask == 0)\n {\n printf(\"\\nNow producing ICs based on 2nd-order LPT\\n\\n\");\n fflush(stdout);\n }\n\n a = All.TimeBegin;\n\n hubble = hubble_function(a);\n\n fac1 = 1.0 / (a * a * hubble * F1_Omega(a));\t/* this factor converts the Zeldovich peculiar velocity \n\t\t\t\t\t\t (expressed as a^2*dX/dt to comoving displacement */\n fac2 = header.lpt_scalingfactor;\n\n fac3 = fac2 * a * a * hubble * F2_Omega(a);\n\n if(ThisTask == 0)\n printf(\"fac1=%g fac2=%g fac3=%g\\n\", fac1, fac2, fac3);\n\n for(i = 0; i < NumPart; i++)\n {\n for(j = 0; j < 3; j++)\n\tP[i].Pos[j] += fac1 * P[i].Vel[j];\t/* Zeldovich displacement */\n\n#ifdef PMGRID\n for(j = 0; j < 3; j++)\n\tP[i].Pos[j] += fac2 * (P[i].GravPM[j] + P[i].g.GravAccel[j]);\t/* second order lpt displacement */\n\n for(j = 0; j < 3; j++)\n\tP[i].Vel[j] += fac3 * (P[i].GravPM[j] + P[i].g.GravAccel[j]);\t/* second order lpt velocity correction */\n#else\n for(j = 0; j < 3; j++)\n\tP[i].Pos[j] += fac2 * (P[i].g.GravAccel[j]);\t/* second order lpt displacement */\n\n for(j = 0; j < 3; j++)\n\tP[i].Vel[j] += fac3 * (P[i].g.GravAccel[j]);\t/* second order lpt velocity correction */\n#endif\n }\n\n\n /* now set the masses correctly */\n\n for(i = 0; i < NumPart; i++)\n {\n P[i].Mass = P[i].OldAcc;\n\n if(All.MassTable[P[i].Type] != 0)\n\tP[i].Mass = All.MassTable[P[i].Type];\n }\n\n if(All.ComovingIntegrationOn)\n if(All.PeriodicBoundariesOn == 1)\n check_omega();\t\t/* check again whether we have plausible mass density */\n\n /* recompute long range force */\n\n All.DoDynamicUpdate = 1;\n domain_Decomposition();\t/* redo domain decomposition because particles may have shifted */\n\n\n CPU_Step[CPU_MISC] += measure_time();\n\n#ifdef PMGRID\n long_range_force();\n#endif\n\n CPU_Step[CPU_MESH] += measure_time();\n\n gravity_tree();\n\n for(i = 0; i < NumPart; i++)\n {\n#ifdef PMGRID\n ax = (P[i].g.GravAccel[0] + P[i].GravPM[0]) / All.G;\n ay = (P[i].g.GravAccel[1] + P[i].GravPM[1]) / All.G;\n az = (P[i].g.GravAccel[2] + P[i].GravPM[2]) / All.G;\n#else\n ax = P[i].g.GravAccel[0] / All.G;\n ay = P[i].g.GravAccel[1] / All.G;\n az = P[i].g.GravAccel[2] / All.G;\n#endif\n P[i].OldAcc = sqrt(ax * ax + ay * ay + az * az);\n }\n\n if(All.TypeOfOpeningCriterion == 1)\n {\n All.ErrTolTheta = 0;\t/* This will switch to the relative opening criterion for the following force computations */\n gravity_tree();\n }\n\n}\n", "meta": {"hexsha": "f98e0e56ba4c07c3763649b671d2d5e7742d5a98", "size": 3182, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/second_order.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9248120301, "max_line_length": 120, "alphanum_fraction": 0.5883092395, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6323917698455859}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\ndouble drand() {\n return (double) rand() / RAND_MAX;\n}\n\nvoid ptime(struct rusage *ru0, struct rusage *ru1) {\n\n double utime = 0, stime = 0, ttime = 0;\n\n utime = (double) ru1->ru_utime.tv_sec\n + 1.e-6 * (double) ru1->ru_utime.tv_usec\n - ru0->ru_utime.tv_sec\n - 1.e-6 * (double) ru0->ru_utime.tv_usec;\n stime = (double) ru1->ru_stime.tv_sec\n + 1.e-6 * (double) ru1->ru_stime.tv_usec\n - ru0->ru_stime.tv_sec\n - 1.e-6 * (double) ru0->ru_stime.tv_usec;\n ttime = stime + utime;\n\n printf(\"%3f\\n\", ttime);\n}\n\nint main(int argc, char *argv[]) {\n\n if (argc < 2) {\n errno = EINVAL;\n perror(\"\");\n return errno;\n }\n int n = strtol(argv[1], NULL, 10);\n if (0 != errno) {\n perror(\"\");\n return errno;\n }\n\n srand(time(NULL));\n\n int els = n * n;\n double *A_data = (double *) malloc(els * sizeof(double));\n for (int i = 0; i < els; i++) {\n A_data[i] = drand();\n }\n double *b_data = (double *) malloc(n * sizeof(double));\n for (int i = 0; i < n; i++) {\n b_data[i] = drand();\n }\n\n gsl_matrix_view A\n = gsl_matrix_view_array(A_data, n, n);\n gsl_matrix *A_copy = gsl_matrix_alloc(n, n);\n gsl_matrix_memcpy(A_copy, &A.matrix);\n fprintf(stderr, \"A = [\\n\");\n gsl_matrix_fprintf(stderr, &A.matrix, \"%g\");\n fprintf(stderr, \"]\\n\");\n\n gsl_vector_view b\n = gsl_vector_view_array(b_data, n);\n fprintf(stderr, \"b = [\\n\");\n gsl_vector_fprintf(stderr, &b.vector, \"%g\");\n fprintf(stderr, \"]\\n\");\n\n gsl_vector *x = gsl_vector_alloc(n);\n\n struct rusage t0, t1, t2;\n int s;\n\n gsl_permutation *p = gsl_permutation_alloc(n);\n\n getrusage(RUSAGE_SELF, &t0);\n gsl_linalg_LU_decomp(&A.matrix, p, &s);\n getrusage(RUSAGE_SELF, &t1);\n gsl_linalg_LU_solve(&A.matrix, p, &b.vector, x);\n getrusage(RUSAGE_SELF, &t2);\n\n fprintf(stderr, \"x = [\\n\");\n gsl_vector_fprintf(stderr, x, \"%g\");\n fprintf(stderr, \"]\\n\");\n\n fprintf(stderr, \"%s \\n\", \"decomposition time:\");\n ptime(&t0, &t1);\n fprintf(stderr, \"%s \\n\", \"solve time:\");\n ptime(&t1, &t2);\n fprintf(stderr, \"%s \\n\", \"together time:\");\n ptime(&t0, &t2);\n\n gsl_vector *y = gsl_vector_alloc(n);\n gsl_blas_dgemv(CblasNoTrans, 1.0, A_copy, x, 0, y);\n fprintf(stderr, \"y = [\\n\");\n gsl_vector_fprintf(stderr, y, \"%g\");\n fprintf(stderr, \"]\\n\");\n\n gsl_permutation_free(p);\n gsl_vector_free(x);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4532e8c4d5bf41b864531dbd7a6aa15c1f6b38b5", "size": 2707, "ext": "c", "lang": "C", "max_stars_repo_path": "lab6/zad.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": "lab6/zad.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": "lab6/zad.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": 25.5377358491, "max_line_length": 61, "alphanum_fraction": 0.5707425194, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6323318789771367}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble rho_NFW(double r, double M_vir, double z, int mode, cosmo_info **cosmo) {\n double c_vir;\n double R_vir;\n double g_c;\n double rho_o;\n double x;\n set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);\n g_c = 1. / (log(1. + c_vir) - c_vir / (1. + c_vir));\n rho_o = M_vir * g_c / (FOUR_PI * pow(R_vir / c_vir, 3.));\n x = r * c_vir / R_vir;\n return (rho_o / (x * pow(1. + x, 2.)));\n}\n", "meta": {"hexsha": "1781ae38f5edf356f97571a6d10fa2078634e98e", "size": 609, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 27.6818181818, "max_line_length": 80, "alphanum_fraction": 0.6124794745, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.960361158630024, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.6323186065756479}} {"text": "/* integration/tests.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include \n#include \n#include \n\n#include \"tests.h\"\n\n/* These are the test functions from table 4.1 of the QUADPACK book */\n\n/* f1(x) = x^alpha * log(1/x) */\n/* integ(f1,x,0,1) = 1/(alpha + 1)^2 */\n\ndouble f1 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(x,alpha) * log(1/x) ;\n}\n\n/* f2(x) = 4^-alpha / ((x-pi/4)^2 + 16^-alpha) */\n/* integ(f2,x,0,1) = arctan((4-pi)4^(alpha-1)) + arctan(pi 4^(alpha-1)) */\n\ndouble f2 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(4.0,-alpha) / (pow((x-M_PI/4.0),2.0) + pow(16.0,-alpha)) ;\n}\n\n/* f3(x) = cos(2^alpha * sin(x)) */\n/* integ(f3,x,0,pi) = pi J_0(2^alpha) */\n\ndouble f3 (double x, void * params) {\n double alpha = *(double *) params ;\n return cos(pow(2.0,alpha) * sin(x)) ;\n}\n\n/* Functions 4, 5 and 6 are duplicates of functions 1, 2 and 3 */\n/* .... */\n\n/* f7(x) = |x - 1/3|^alpha */\n/* integ(f7,x,0,1) = ((2/3)^(alpha+1) + (1/3)^(alpha+1))/(alpha + 1) */\n\ndouble f7 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(fabs(x - (1.0/3.0)),alpha) ;\n}\n\n/* f8(x) = |x - pi/4|^alpha */\n/* integ(f8,x,0,1) = \n ((1 - pi/4)^(alpha+1) + (pi/4)^(alpha+1))/(alpha + 1) */\n\ndouble f8 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(fabs(x - (M_PI/4.0)),alpha) ;\n}\n\n/* f9(x) = sqrt(1 - x^2) / (x + 1 + 2^-alpha) */\n/* integ(f9,x,-1,1) = pi/sqrt((1+2^-alpha)^2-1) */\n\ndouble f9 (double x, void * params) {\n double alpha = *(double *) params ;\n return 1 / ((x + 1 + pow(2.0,-alpha)) * sqrt(1-x*x)) ;\n}\n\n/* f10(x) = sin(x)^(alpha - 1) */\n/* integ(f10,x,0,pi/2) = 2^(alpha-2) ((Gamma(alpha/2))^2)/Gamma(alpha) */\n\ndouble f10 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(sin(x), alpha-1) ;\n}\n\n/* f11(x) = log(1/x)^(alpha - 1) */\n/* integ(f11,x,0,1) = Gamma(alpha) */\n\ndouble f11 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(log(1/x), alpha-1) ;\n}\n\n/* f12(x) = exp(20*(x-1)) * sin(2^alpha * x) */\n/* integ(f12,x,0,1) = \n (20 sin(2^alpha) - 2^alpha cos(2^alpha) + 2^alpha exp(-20))\n /(400 + 4^alpha) */\n\ndouble f12 (double x, void * params) {\n double alpha = *(double *) params ;\n return exp(20*(x-1)) * sin(pow(2.0,alpha) * x) ;\n}\n\n/* f13(x) = cos(2^alpha * x)/sqrt(x(1 - x)) */\n/* integ(f13,x,0,1) = pi cos(2^(alpha-1)) J_0(2^(alpha-1)) */\n\ndouble f13 (double x, void * params) {\n double alpha = *(double *) params ;\n return cos(pow(2.0,alpha)*x)/sqrt(x*(1-x)) ;\n}\n\ndouble f14 (double x, void * params) {\n double alpha = *(double *) params ;\n return exp(-pow(2.0,-alpha)*x)*cos(x)/sqrt(x) ;\n}\n\ndouble f15 (double x, void * params) {\n double alpha = *(double *) params ;\n return x*x * exp(-pow(2.0,-alpha)*x) ;\n}\n\ndouble f16 (double x, void * params) {\n double alpha = *(double *) params ;\n if (x==0 && alpha == 1) return 1 ; /* make the function continuous in x */\n if (x==0 && alpha > 1) return 0 ; /* avoid problems with pow(0,1) */\n return pow(x,alpha-1)/pow((1+10*x),2.0) ;\n}\n\ndouble f17 (double x, void * params) {\n double alpha = *(double *) params ;\n return pow(2.0,-alpha)/(((x-1)*(x-1)+pow(4.0,-alpha))*(x-2)) ;\n}\n\n/* f454(x) = x^3 log|(x^2-1)(x^2-2)| */\n/* integ(f454,x,0,inf) = 61 log(2) + (77/4) log(7) - 27 */\n\ndouble f454 (double x, void * params) {\n double x2 = x * x;\n double x3 = x * x2;\n params = 0 ;\n return x3 * log(fabs((x2 - 1.0) * (x2 - 2.0))) ;\n}\n\n/* f455(x) = log(x)/(1+100*x^2) */\n/* integ(f455,x,0,inf) = -log(10)/20 */\n\ndouble f455 (double x, void * params) {\n params = 0 ;\n return log(x) / (1.0 + 100.0 * x * x) ;\n}\n\n/* f456(x) = log(x) */\n/* integ(f456*sin(10 pi x),x,0,1) = -(gamma + log(10pi) - Ci(10pi))/(10pi) */\n\ndouble f456 (double x, void * params) {\n params = 0 ;\n if (x == 0.0)\n {\n return 0;\n }\n return log(x) ;\n}\n\n/* f457(x) = 1/sqrt(x) */\n/* integ(f457*cos(pi x / 2),x,0,+inf) = 1 */\n\ndouble f457 (double x, void * params) {\n params = 0 ;\n if (x == 0.0)\n {\n return 0;\n }\n return 1/sqrt(x) ;\n}\n\n/* f458(x) = 1/(1 + log(x)^2)^2 */\n/* integ(log(x) f458(x),x,0,1) = (Ci(1) sin(1) + (pi/2 - Si(1)) cos(1))/pi \n = -0.1892752 */\n\ndouble f458 (double x, void * params) {\n params = 0 ;\n\n if (x == 0.0) \n {\n return 0;\n }\n else \n {\n double u = log(x);\n double v = 1 + u * u;\n \n return 1.0 / (v * v) ;\n }\n}\n\n/* f459(x) = 1/(5 x^3 + 6) */\n/* integ(f459/(x-0),x,-1,5) = log(125/631)/18 */\n\ndouble f459 (double x, void * params) {\n params = 0 ;\n return 1.0 / (5.0 * x * x * x + 6.0) ;\n}\n\n/* myfn1(x) = exp(-x - x^2) */\n/* integ(myfn1,x,-inf,inf) = sqrt(pi) exp(-1/4) */\n\ndouble myfn1 (double x, void * params) {\n params = 0;\n return exp(-x - x*x) ;\n}\n\n/* myfn2(x) = exp(alpha*x) */\n/* integ(myfn2,x,-inf,b) = exp(alpha*b)/alpha */\n\ndouble myfn2 (double x, void * params) {\n double alpha = *(double *) params ;\n return exp(alpha*x) ;\n}\n", "meta": {"hexsha": "2e73ab6006cf9e8334d5f85b26991e53e7db4fd8", "size": 5799, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/integration/tests.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/integration/tests.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/em/treba/gsl-1.0/integration/tests.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.2398190045, "max_line_length": 77, "alphanum_fraction": 0.5476806346, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6314905023027271}} {"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 = 1000; /* length of time series */\n const double sigma[] = { 1.0, 5.0, 1.0, 3.0, 5.0 }; /* variances */\n const size_t N_sigma[] = { 200, 450, 600, 850, 1000 }; /* samples where variance changes */\n const size_t K = 41; /* window size */\n gsl_vector *x = gsl_vector_alloc(N);\n gsl_vector *xmedian = gsl_vector_alloc(N);\n gsl_vector *xmad = gsl_vector_alloc(N);\n gsl_vector *xiqr = gsl_vector_alloc(N);\n gsl_vector *xSn = gsl_vector_alloc(N);\n gsl_vector *xQn = gsl_vector_alloc(N);\n gsl_vector *xsd = gsl_vector_alloc(N);\n gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n gsl_movstat_workspace * w = gsl_movstat_alloc(K);\n size_t idx = 0;\n size_t i;\n\n for (i = 0; i < N; ++i)\n {\n double gi = gsl_ran_gaussian(r, sigma[idx]);\n double u = gsl_rng_uniform(r);\n double outlier = (u < 0.01) ? 15.0*GSL_SIGN(gi) : 0.0;\n double xi = gi + outlier;\n\n gsl_vector_set(x, i, xi);\n\n if (i == N_sigma[idx] - 1)\n ++idx;\n }\n\n /* compute moving statistics */\n gsl_movstat_mad(GSL_MOVSTAT_END_TRUNCATE, x, xmedian, xmad, w);\n gsl_movstat_qqr(GSL_MOVSTAT_END_TRUNCATE, x, 0.25, xiqr, w);\n gsl_movstat_Sn(GSL_MOVSTAT_END_TRUNCATE, x, xSn, w);\n gsl_movstat_Qn(GSL_MOVSTAT_END_TRUNCATE, x, xQn, w);\n gsl_movstat_sd(GSL_MOVSTAT_END_TRUNCATE, x, xsd, w);\n\n /* scale IQR by factor to approximate standard deviation */\n gsl_vector_scale(xiqr, 0.7413);\n\n /* print results */\n idx = 0;\n for (i = 0; i < N; ++i)\n {\n printf(\"%zu %f %f %f %f %f %f %f\\n\",\n i,\n gsl_vector_get(x, i),\n sigma[idx],\n gsl_vector_get(xmad, i),\n gsl_vector_get(xiqr, i),\n gsl_vector_get(xSn, i),\n gsl_vector_get(xQn, i),\n gsl_vector_get(xsd, i));\n\n if (i == N_sigma[idx] - 1)\n ++idx;\n }\n\n gsl_vector_free(x);\n gsl_vector_free(xmedian);\n gsl_vector_free(xmad);\n gsl_vector_free(xiqr);\n gsl_vector_free(xSn);\n gsl_vector_free(xQn);\n gsl_vector_free(xsd);\n gsl_rng_free(r);\n gsl_movstat_free(w);\n\n return 0;\n}\n", "meta": {"hexsha": "bc841b1d4ccaf82201f78090bb6cc812ee0918be", "size": 2328, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/movstat2.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/movstat2.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/movstat2.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": 28.3902439024, "max_line_length": 93, "alphanum_fraction": 0.6069587629, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6311906229886851}} {"text": "#include \n#include \n#include \n\n// #include \n// #include \n\n\n\ndouble boxcar_overlap(double rA, double radiiA, double rB, double radiiB)\n{\n\n double F;\n F = pow(rB - rA, 2) / pow(radiiA + radiiB, 2);\n\n return F;\n\n}\n\n\n\n\n\n\n\nsize_t gen_pts_rsa_1d(double *x,\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 x[0] = xn;\n\n\n size_t valid_pts;\n double F;\n int k, flag, step;\n\n step = 0;\n valid_pts = 1;\n\n while ((valid_pts < npoints) & (step < step_limit))\n {\n\n xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;\n\n flag = 1;\n for (k = 0; k < valid_pts; k++)\n {\n\n F = boxcar_overlap(xn, radius, x[k], radius);\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 valid_pts += 1;\n\n }\n\n step += 1;\n \n }\n \n\n gsl_rng_free (r);\n\n return valid_pts;\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nunsigned int metro_md_1d(double *x,\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 dx, xn, F;\n unsigned int step, i, k, flag, success_steps;\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\n if (((xn > radius) & (xn < 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 F = boxcar_overlap(xn, radius, x[k], radius);\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\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\n\n\n\n\n\n\n\nunsigned int metro_pd_1d(double *x,\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 dx, xn, diameter, F;\n unsigned int step, i, k, flag, success_steps;\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\n if (((xn > radius[i]) & (xn < 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 F = boxcar_overlap(xn, radius[i], x[k], radius[k]);\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\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": "d278d235120c7cb846d8124aaec3e3bfb2efe722", "size": 4241, "ext": "c", "lang": "C", "max_stars_repo_path": "particle_packing/cython/c/boxcar.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/boxcar.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/boxcar.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": 15.5919117647, "max_line_length": 73, "alphanum_fraction": 0.4673426079, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6311807565787678}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#define N 5000;\n\nvoid mm_bruteforce_ijk(double *a, double *b, double *c, int I, int K, int J) {\n for(int i = 0; i < I; i++) {\n for(int j = 0; j < J; j++) {\n for(int k = 0; k < K; k++) {\n c[i * J + j] += a[i * K + k] * b[k * J + j];\n }\n }\n }\n}\n\nvoid mm_bruteforce_ikj(double *a, double *b, double *c, int I, int K, int J) {\n for(int i = 0; i < I; i++) {\n for(int k = 0; k < K; k++) {\n double dv = a[i * K + k];\n for(int j = 0; j < J; j++) {\n c[i * J + j] += dv * b[k * J + j];\n }\n }\n }\n}\n\nvoid mm_omp(double *a, double *b, double *c, int I, int K, int J) {\n #pragma omp parallel for \n for(int i = 0; i < I; i++) {\n for(int k = 0; k < K; k++) {\n register double dv = a[i * K + k];\n for(int j = 0; j < J; j++) {\n c[i * J + j] += dv * b[k * J + j];\n }\n }\n }\n}\n\nvoid mm_cblas_dgemm(double *a, double *b, double *c, int p, int q, int r) {\n int l = p;\n int m = q;\n int n = r;\n\n int lda = m;\n int ldb = n;\n int ldc = n;\n\n double alpha = 1.0;\n double beta = 0.0;\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n l, n, m, alpha, a, lda, b, ldb, beta, c, ldc);\n}\n\nvoid init_arange(double *mat, int a, int b) {\n for(int i = 0; i < (a*b); i++) {\n mat[i] = i + 1;\n }\n}\n\nvoid init_value(double *mat, int a, int b, double value) {\n for(int i = 0; i < (a*b); i++) {\n mat[i] = value;\n }\n}\n\nvoid init_zero(double *mat, int a, int b) {\n init_value(mat, a, b, 0);\n}\n\nvoid init_one(double *mat, int a, int b) {\n init_value(mat, a, b, 1);\n}\n\nvoid timer_start(struct timeval *pstv) {\n gettimeofday(pstv, NULL);\n}\n\nvoid timer_end(struct timeval *petv) {\n gettimeofday(petv, NULL);\n}\n\nvoid timer_print(struct timeval *pstv, struct timeval *petv) {\n time_t sec;\n suseconds_t usec;\n sec = petv->tv_sec - pstv->tv_sec;\n usec = petv->tv_usec - pstv->tv_usec;\n if(usec < 0) {\n sec--;\n usec += 1000000;\n }\n printf(\"elapsed time : %ld.%ld\\n\", sec, usec);\n}\n\ntypedef void (*fptr_mm)(double *a, double *b, double *c, int I, int K, int J);\n\nvoid check_etime_mm(double *a, double *b, double *c, int I, int K, int J, fptr_mm mm) {\n struct timeval stv;\n struct timeval etv;\n init_zero(c, I, J);\n timer_start(&stv);\n mm(a, b, c, I, K, J);\n timer_end(&etv);\n timer_print(&stv, &etv);\n}\n\nint main(int argc, char *argv[]) {\n int I, K, J;\n I = K = J = N;\n\n double *a = (double*)malloc(sizeof(double) * I * K);\n double *b = (double*)malloc(sizeof(double) * K * J);\n double *c = (double*)malloc(sizeof(double) * I * J);\n\n init_arange(a, I, K);\n init_arange(b, K, J);\n\n check_etime_mm(a, b, c, I, K, J, mm_bruteforce_ijk);\n check_etime_mm(a, b, c, I, K, J, mm_bruteforce_ikj);\n check_etime_mm(a, b, c, I, K, J, mm_omp);\n check_etime_mm(a, b, c, I, K, J, mm_cblas_dgemm);\n\n return 0;\n}\n", "meta": {"hexsha": "c5e4ce68ae671906e57a9229a357237982df1ff5", "size": 3117, "ext": "c", "lang": "C", "max_stars_repo_path": "mm.c", "max_stars_repo_name": "read2r/omp_matrix_multiplication", "max_stars_repo_head_hexsha": "33b1c27c0db7b93c9d0c6a19c9effa1591814b31", "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": "mm.c", "max_issues_repo_name": "read2r/omp_matrix_multiplication", "max_issues_repo_head_hexsha": "33b1c27c0db7b93c9d0c6a19c9effa1591814b31", "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": "mm.c", "max_forks_repo_name": "read2r/omp_matrix_multiplication", "max_forks_repo_head_hexsha": "33b1c27c0db7b93c9d0c6a19c9effa1591814b31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3515625, "max_line_length": 87, "alphanum_fraction": 0.5088225858, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6299007519966282}} {"text": "#include \n#include \n\n#define M 2\n#define N 2\n#define K 3\n#define X 4\n#define Y 5\n\nvoid print_mat(const char *name, int r, int c, float *m)\n{\n printf(\"%s =\\n\", name);\n for (int i = 0; i < r; i++) {\n for (int j = 0; j < c; j++) {\n printf(\"%.2lf \", m[i * c + j]);\n }\n printf(\"\\n\");\n }\n}\n\nint main()\n{\n float A[M * K] = {\n 1, 2, 3,\n 4, 5, 6,\n };\n float B[K * N] = {\n 0.1, 0.2,\n 0.3, 0.4,\n 0.5, 0.6,\n };\n float C[X * Y] = { 0 };\n\n // M x K, K x N -> M x N (single precision, 's'gemm)\n // Save A x B in C starting from (1, 1)\n cblas_sgemm(\n CblasRowMajor, CblasNoTrans, CblasNoTrans,\n M, N, K,\n 1,\n A, K,\n B, N,\n 0,\n C + Y + 1, Y\n );\n\n print_mat(\"A\", M, K, A);\n print_mat(\"B\", K, N, B);\n print_mat(\"C\", X, Y, C);\n\n return 0;\n}\n", "meta": {"hexsha": "a79e231e37f2630e5e77952a010dedeea6408ebe", "size": 903, "ext": "c", "lang": "C", "max_stars_repo_path": "proj3/examples/openBLAS/openblas_example.c", "max_stars_repo_name": "hsyis/object-detection-yolo2-tiny", "max_stars_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "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": "proj3/examples/openBLAS/openblas_example.c", "max_issues_repo_name": "hsyis/object-detection-yolo2-tiny", "max_issues_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "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": "proj3/examples/openBLAS/openblas_example.c", "max_forks_repo_name": "hsyis/object-detection-yolo2-tiny", "max_forks_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "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.3653846154, "max_line_length": 56, "alphanum_fraction": 0.4097452935, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758842, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.629861879798583}} {"text": "/* integration/qk21.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[11] = /* abscissae of the 21-point kronrod rule */\n{\n 0.995657163025808080735527280689003,\n 0.973906528517171720077964012084452,\n 0.930157491355708226001207180059508,\n 0.865063366688984510732096688423493,\n 0.780817726586416897063717578345042,\n 0.679409568299024406234327365114874,\n 0.562757134668604683339000099272694,\n 0.433395394129247190799265943165784,\n 0.294392862701460198131126603103866,\n 0.148874338981631210884826001129720,\n 0.000000000000000000000000000000000\n};\n\n/* xgk[1], xgk[3], ... abscissae of the 10-point gauss rule. \n xgk[0], xgk[2], ... abscissae to optimally extend the 10-point gauss rule */\n\nstatic const double wg[5] = /* weights of the 10-point gauss rule */\n{\n 0.066671344308688137593568809893332,\n 0.149451349150580593145776339657697,\n 0.219086362515982043995534934228163,\n 0.269266719309996355091226921569469,\n 0.295524224714752870173892994651338\n};\n\nstatic const double wgk[11] = /* weights of the 21-point kronrod rule */\n{\n 0.011694638867371874278064396062192,\n 0.032558162307964727478818972459390,\n 0.054755896574351996031381300244580,\n 0.075039674810919952767043140916190,\n 0.093125454583697605535065465083366,\n 0.109387158802297641899210590325805,\n 0.123491976262065851077958109831074,\n 0.134709217311473325928054001771707,\n 0.142775938577060080797094273138717,\n 0.147739104901338491374841515972068,\n 0.149445554002916905664936468389821\n};\n\n\nvoid\ngsl_integration_qk21 (const gsl_function * f, double a, double b,\n double *result, double *abserr,\n double *resabs, double *resasc)\n{\n double fv1[11], fv2[11];\n gsl_integration_qk (11, xgk, wg, wgk, fv1, fv2, f, a, b, result, abserr, resabs, resasc);\n}\n", "meta": {"hexsha": "1e263ed7b5116554306876f50d8cc101fd052c43", "size": 2783, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/integration/qk21.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/qk21.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/qk21.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": 35.6794871795, "max_line_length": 91, "alphanum_fraction": 0.759971254, "num_tokens": 923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6298349090682746}} {"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 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#ifndef __GSL_SF_BESSEL_H__\n#define __GSL_SF_BESSEL_H__\n\n#include \n#include \n#include \n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* Regular Bessel Function J_0(x)\n *\n * exceptions: none\n */\nGSL_EXPORT int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_J0(const double x);\n\n\n/* Regular Bessel Function J_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nGSL_EXPORT int gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_J1(const double x);\n\n\n/* Regular Bessel Function J_n(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nGSL_EXPORT int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result); \nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_y0(const double x);\n\n\n/* Irregular spherical Bessel function y_1(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nGSL_EXPORT int gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_y1(const double x);\n\n\n/* Irregular spherical Bessel function y_2(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nGSL_EXPORT int gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_y2(const double x);\n\n\n/* Irregular spherical Bessel function y_l(x)\n *\n * exceptions: GSL_EUNDRFLW\n */\nGSL_EXPORT int gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result);\nGSL_EXPORT double gsl_sf_bessel_Jnu(const double nu, const double x);\n\n\n/* Irregular cylindrical Bessel function Y_nu(x)\n *\n * exceptions: \n */\nGSL_EXPORT int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int 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 */\nGSL_EXPORT int gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result);\nGSL_EXPORT double 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 */\nGSL_EXPORT int gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result);\nGSL_EXPORT double 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": "b208e3cbb8bda6459e556bc26574aee61c63b8af", "size": 15195, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6272727273, "max_line_length": 116, "alphanum_fraction": 0.747153669, "num_tokens": 4503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6297867101656013}} {"text": "/*gcc poisson.c /usr/lib/libgsl.a /usr/lib/libm.a -o poisson.exe */\n\n#include \n#include \n#include \n#include \n\nint\nmain (int argc, char *argv[])\n{\n if(argc < 2){\n printf(\"print probability of obtaining N from poisson distribution\\n\");\n printf(\"usage: poisson.exe mean N\\n\");\n return 1;\n }\n\n\n const gsl_rng_type * T;\n gsl_rng * r;\n\t\n int billion = 1000000000;\n int i, n = billion;\n\n double mean = atof(argv[1]);\n unsigned int found = atoi(argv[2]);\n\n double prob = gsl_ran_poisson_pdf(found,mean);\n printf(\"probability %f of getting %d from mean %f\\n\",prob,found,mean);\n\n double totalprob = 0.0;\n for(i=0; i= %d from mean %f\\n\",\n\t 1.0-totalprob,found,mean);\n \n\n /*\n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc (T);\n\n for (i = 0; i < n; i++) \n {\n double u = gsl_rng_uniform (r);\n if(i > billion-5) printf(\"%.5f\\n\", u);\n }\n\n gsl_rng_free (r);\n */\n return 0;\n}\n", "meta": {"hexsha": "d8108fac13afb760a022c7d9f18f793412ae3e66", "size": 1157, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmic/contrib/walta/coincidence/poisson/poisson.c", "max_stars_repo_name": "QuarkNet-HEP/e-Labs", "max_stars_repo_head_hexsha": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9", "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": "cosmic/contrib/walta/coincidence/poisson/poisson.c", "max_issues_repo_name": "QuarkNet-HEP/e-Labs", "max_issues_repo_head_hexsha": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9", "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": "cosmic/contrib/walta/coincidence/poisson/poisson.c", "max_forks_repo_name": "QuarkNet-HEP/e-Labs", "max_forks_repo_head_hexsha": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9", "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": 20.6607142857, "max_line_length": 75, "alphanum_fraction": 0.621434745, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6296994398819783}} {"text": "/*This program evaluates the differential equations for a photon's geodesic in a FRW perturbed spacetime in SPHERICAL coordinates and restricted to photon RADIAL MOTION only.*/\n\n/*This program solves the particular case for flat FRW perturbed spacetime with metric: $g_{ab} = {[g]}_{ab} + h_{ab}$. Where ${[g]}_{ab}$ corresponds to the flat FRW metric and $h_{ab}$ corresponds to the perturbation in the conformal Newtonian gauge. A Plummer potential or a Hernquist potential with adequate parameters can be used to simulate the perturbation.\nThe equations are written in the form $\\frac{d(x or p)^{\\alpha}}{d\\lambda}=f(x^{\\alpha},p^{\\alpha})$ and the indice $\\alpha$ runs from 0 to 1 since the motion is only radial.\nWhere $p^{\\alpha}={\\dot{x}}^{\\alpha}$.\nThe coordinates for the photon's geodesics are then: (ct,r) = (x0,x1).*/\n\n#include \n#include \n#include \n#include //GSL error management module\n#include //GSL interpolation module\n\n/* PHYSICAL CONSTANTS AND PARAMETERS */\n#define A 10.0 //Distance parameter of the perturbations\n#define G 43007.01 //Gravitational constant\n#define M 15000.0 //Mass of the perturbation\n#define C 299792.458 //Speed of light\n#define GAMMA 0.8 //Parameter for halo mass evolution\n\n/* PROGRAM PARAMETERS */\n#define NLINES 100000 //Number of lines in geodesic_solution.dat file\n#define NSTEPS 600000000 //Number of steps for solving geodesics\n#define NLINESFRW 10000 //Number of lines in frw.dat file\n#define DLAMBDA 0.01 //Geodesics parameter step\n\ntypedef long double mydbl;\n\n/*Interpolation of function inside *spline object evaluated at an abscisa 'x'.\nArgument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/\ndouble interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc)\n{\n double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc\n return a; //Return value of interpolated function at x\n}\n\n/*Mass evolution. Function providing the mass at a given z. Mass at present time is obtained at z=0.*/\nmydbl mass(mydbl a)\n{\n mydbl z = 1.0/a - 1.0;\n return M*expl(-GAMMA*z);\n}\n\n/*Plummer model. Provided two variables pointers, this function stores the potential and the derivative of the potential for the Plummer model in these variables at a given radius.*/\nvoid plummer_model(mydbl a, mydbl adot, mydbl r, mydbl *potential, mydbl *der_potential_radial, mydbl *der_potential_temporal)\n{\n *potential = -G*mass(a)/(sqrtl(A*A + r*r));\n *der_potential_radial = G*mass(a)*r/(powl(A*A+r*r, 1.5));\n *der_potential_temporal = *potential*GAMMA*adot/(a*a);\n}\n\n/*Hernquist model. Provided two variables pointers, this function stores the potential and the derivative of the potential for the Hernquist model in these variables at a given radius.*/\nvoid hernquist_model(mydbl a, mydbl adot, mydbl r, mydbl *potential, mydbl *der_potential_radial, mydbl *der_potential_temporal)\n{\n double rsign = copysign(1.0,(double)(1.0*r));\n mydbl absr = fabsl(r);\n if(absr > 2000.0)\n {\n *potential = 0.0;\n *der_potential_radial = 0.0;\n *der_potential_temporal = 0.0;\n }\n else if(rsign == -1.0)\n {\n *potential = -G*mass(a)/(A + absr);\n *der_potential_radial = -G*mass(a)/powl(absr+A,2.0);\n *der_potential_temporal = *potential*GAMMA*adot/(a*a);\n }\n else if(rsign == 1.0)\n {\n *potential = -G*mass(a)/(A + absr);\n *der_potential_radial = G*mass(a)/powl(absr+A,2.0);\n *der_potential_temporal = *potential*GAMMA*adot/(a*a);\n }\n}\n\n/*Function of the 0th momentum component differential equation for the geodesics.\n${p0}^{dot} = f0(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl potential, der_potential_radial, der_potential_temporal;\n (*model)(a, adot, r, &potential, &der_potential_radial, &der_potential_temporal);\n mydbl f = -2.0*p0*(der_potential_temporal*p0/C + der_potential_radial*pr)/(C*C + 2.0*potential) + der_potential_temporal*(p0*p0 + a*a*pr*pr)/(C*C*C) - (1.0 - 2.0*potential/(C*C))*(a*adot)*(pr*pr)/(C + 2.0*potential/C);\n return f;\n}\n\n/*Function of the 1th (radial) momentum component differential equation for the geodesics.\n${p1}^{dot} = f1(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl potential, der_potential_radial, der_potential_temporal;\n (*model)(a, adot, r, &potential, &der_potential_radial, &der_potential_temporal);\n mydbl f = - (der_potential_radial*p0*p0)/(a*a*(C*C - 2.0*potential)) - (2.0*adot*p0*pr)/(C*a) + der_potential_radial*(pr*pr)/(C*C - 2.0*potential) + 2.0*der_potential_temporal*p0*pr/(a*a*C*(C*C - 2.0*potential));\n return f;\n}\n\n/*Function for solving the geodesics differential equations using 4th order Runge-Kutta method.\nArguments are pointer so variables in that memory addresses are changed every time this function is called.*/\nvoid runge_kutta_4(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *p0, mydbl *p1, mydbl *lambda, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n /*Increment in the variables of the differential equation we want to solve*/\n mydbl dx0, dx1, dp0, dp1;\n\n /*dxi = (k1,j + 2*k2,j + 2*k3,j + k4,j)/6. In this sections the ki,j are declared with i=1,2,3,4.*/\n mydbl k1x0, k1x1, k1p0, k1p1;\n mydbl k2x0, k2x1, k2p0, k2p1;\n mydbl k3x0, k3x1, k3p0, k3p1;\n mydbl k4x0, k4x1, k4p0, k4p1;\n\n /*This section calculates the k1 quantities*/\n k1x0 = *p0*DLAMBDA; k1x1 = *p1*DLAMBDA;\n k1p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1, (*model));\n k1p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1, (*model));\n\n /*This section calculates the k2 quantities*/\n k2x0 = DLAMBDA*(*p0 + 0.5*k1p0); k2x1 = DLAMBDA*(*p1 + 0.5*k1p1);\n k2p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, (*model));\n k2p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, (*model));\n\n /*This section calculates the k3 quantities*/\n k3x0 = DLAMBDA*(*p0 + 0.5*k2p0); k3x1 = DLAMBDA*(*p1 + 0.5*k2p1);\n k3p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, (*model));\n k3p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, (*model));\n\n /*This section calculates the k4 quantities*/\n k4x0 = DLAMBDA*(*p0 + k3p0); k4x1 = DLAMBDA*(*p1 + k3p1);\n k4p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *x0 + k3x0, *x1 + k3x1, (*model));\n k4p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *x0 + k3x0, *x1 + k3x1, (*model));\n\n /*Calculation of the increments*/\n dx0 = (k1x0 + 2.0*k2x0 + 2.0*k3x0 + k4x0)/6.0;\n dx1 = (k1x1 + 2.0*k2x1 + 2.0*k3x1 + k4x1)/6.0;\n dp0 = (k1p0 + 2.0*k2p0 + 2.0*k3p0 + k4p0)/6.0;\n dp1 = (k1p1 + 2.0*k2p1 + 2.0*k3p1 + k4p1)/6.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;\n *p0 = *p0 + dp0; *p1 = *p1 + dp1;\n \n /*Increment of parameter of geodesics*/\n *lambda = *lambda + DLAMBDA;\n}\n\n/*To set the initial value of pr, it must hold $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.\nThis factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/\nmydbl condition_factor(mydbl r, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n mydbl potential, der_potential_radial, der_potential_temporal;\n (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal);\n return (mydbl)(1.0/a)*sqrtl((C*C + 2.0*potential)/(C*C - 2.0*potential));\n}\n\n/*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/\nmydbl energy_factor(mydbl r, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n mydbl potential, der_potential_radial, der_potential_temporal;\n (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal);\n mydbl g = sqrtl(1.0 + 2.0*potential/(C*C));\n return g;\n}\n\n/*Violation of null geodesics condition $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.*/\nmydbl violation(mydbl r, mydbl p0, mydbl pr, double a, void (*model)(mydbl, mydbl, mydbl, mydbl *, mydbl *, mydbl *))\n{\n mydbl potential, der_potential_radial, der_potential_temporal;\n (*model)((mydbl)(1.0*a), 0.0, r, &potential, &der_potential_radial, &der_potential_temporal);\n mydbl f = -(1.0+2.0*potential/(C*C))*p0*p0 + (mydbl)(1.0*a*a)*(1.0-2.0*potential/(C*C))*pr*pr;\n return f;\n}\n\nint main(void)\n{\n /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/\n int i; //For array manipulation\n \n /*Pointer to scale_factor.data file*/\n FILE *frw; \n frw = fopen(\"../scale_factor.dat\",\"r\");\n\n /*Variables and arrays to read the data*/\n double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW];\n\n /*Reading the data*/\n for(i=0; i\n#include \n#include \n#include \"parmt_utils.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#else\n#include \n#include \n#endif\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/random/random.h\"\n#include \"iscl/signal/convolve.h\"\n\nint parmt_utils_getEffectiveRank(const double relError,\n const struct parmtNoiseBasis_struct basis)\n{\n double frac;\n int i, rank;\n rank = 1;\n for (i=1; isqrtEvals);\n memory_free64f(&basis->evects);\n memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes the eigenvectors and eigenvalues of the noise\n * autocorrelation matrix which will be further used in the\n * Karhunen-Loeve expansion.\n *\n * @param[in] npts number of data points\n * @param[in] data noise signal from which to compute noise basis.\n *\n * @param[out] basis on successful exit contains the eigendecomposition \n * of the autocorrelation noise matrix for use in the KL\n * expansion.\n *\n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n */\nint parmt_utils_getNoiseBasis64f(const int npts,\n const double *__restrict__ data,\n struct parmtNoiseBasis_struct *basis)\n{\n double *C, *CtC, *s, xnorm;\n int i, ierr, j, ldc, ldctc, m, n, nrows;\n const enum corrMatrixType_enum type = CORRMTX_AUTOCORRELATION;\n //------------------------------------------------------------------------//\n // \n // error checking\n ierr = 0;\n memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));\n if (npts < 1 || data == NULL)\n { \n if (npts < 1)\n {\n fprintf(stderr, \"%s: No points in noise signal\\n\", __func__);\n }\n if (data == NULL)\n {\n fprintf(stderr, \"%s; Noise signal is NULL\\n\", __func__);\n }\n return -1; \n } \n C = NULL;\n CtC = NULL;\n // Normalize the noise energy in the noise signal\n xnorm = cblas_dnrm2(npts, data, 1);\n if (fabs(xnorm) < 1.e-15)\n {\n fprintf(stderr, \"%s: Error division by zero\\n\", __func__);\n return -1;\n }\n xnorm = 1.0/xnorm;\n s = array_copy64f(npts, data, &ierr);\n cblas_dscal(npts, xnorm, s, 1);\n // Figure out the size of the noise correlation matrix\n n = npts;\n m = npts - 1;\n ldc = n;\n if (type == CORRMTX_AUTOCORRELATION)\n {\n nrows = n + m;\n C = memory_calloc64f(ldc*nrows);\n }\n else\n {\n fprintf(stderr, \"%s: Invalid correlation matrix type\\n\", __func__);\n return -1;\n }\n ldctc = n;\n CtC = memory_calloc64f(n*n);\n // Compute the correlation matrix and C'C\n ierr = convolve_corrmtx64f_work(npts, s,\n m, ldc, C,\n type, true, ldctc, CtC);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to compute correlation matrix\\n\", __func__);\n goto ERROR;\n }\n ierr = parmt_utils_getNoiseBasisFromCtC64f(npts, ldctc, CtC, basis);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to compute noise basis\\n\", __func__);\n }\nERROR:;\n memory_free64f(&C);\n memory_free64f(&CtC);\n return ierr;\n}\n \nint parmt_utils_getNoiseBasisFromCtC64f(const int npts, const int ldctc,\n const double *__restrict__ CtC,\n struct parmtNoiseBasis_struct *basis)\n{\n double *CtCw, *w;\n int ierr, i, info, j;\n ierr = 0;\n memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));\n CtCw = memory_calloc64f(npts*ldctc);\n for (i=0; i 0)\n {\n fprintf(stderr, \"%s: Failure to converge on %d'th element\\n\",\n __func__, info);\n }\n else\n {\n fprintf(stderr, \"%s: %d'th parameter is invalid\\n\", __func__, info);\n }\n goto ERROR;\n }\n // Set the basis\n basis->lde = npts;\n basis->nvals = npts;\n basis->npts = npts;\n basis->sqrtEvals = memory_calloc64f(basis->nvals);\n basis->evects = memory_calloc64f(basis->lde*basis->nvals);\n // Put into descending order\n for (i=0; isqrtEvals[i] = sqrt(w[npts-1-i]);\n }\n // Copy corresponding eigenvectors in descending order \n for (j=0; jevects[j*basis->lde+i] = CtCw[i*ldctc+(npts-1-j)];\n }\n }\nERROR:;\n memory_free64f(&w);\n memory_free64f(&CtCw);\n return ierr;\n}\n", "meta": {"hexsha": "ec678c1f495efc56311121a7fa066308a08ee90b", "size": 6897, "ext": "c", "lang": "C", "max_stars_repo_path": "utils/getNoiseBasis.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/getNoiseBasis.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/getNoiseBasis.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7284482759, "max_line_length": 83, "alphanum_fraction": 0.544584602, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156293, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6296107959960555}} {"text": "#ifndef _CSPLINE_H_\n#define _CSPLINE_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate class cspline{\n std::vector y;\n std::vector t;\n std::vector h;\n std::vector z;\n int N;\n \n void h_calc();\n void b_calc(std::vector &b);\n void v_calc(std::vector &v);\n void u_calc(std::vector &u, std::vector &b);\n void z_calc(std::vector &v, std::vector &u);\n \n public:\n cspline();\n \n cspline(std::vector &x, std::vector &fx);\n \n void initialize(std::vector &x, std::vector &fx);\n \n void set_pointer_for_device(std::vector &spline);\n \n void set_pointer_for_device(std::vector &spline);\n \n T evaluate(T x);\n \n};\n\ntemplate void cspline::h_calc() {\n for (int i = 0; i < cspline::N - 1; ++i)\n cspline::h.push_back(t[i + 1] - t[i]);\n}\n\ntemplate void cspline::b_calc(std::vector &b) {\n for (int i = 0; i < cspline::N - 1; ++i)\n b[i] = (cspline::y[i + 1] - cspline::y[i])/h[i];\n}\n\ntemplate void cspline::v_calc(std::vector &v) {\n for (int i = 1; i < cspline::N - 1; ++i)\n v[i - 1] = 2.0*(cspline::h[i - 1] + cspline::h[i]);\n}\n\ntemplate void cspline::u_calc(std::vector &u, std::vector &b) {\n for (int i = 1; i < cspline::N - 1; ++i)\n u[i - 1] = 6.0*(b[i] - b[i - 1]);\n}\n\ntemplate void cspline::z_calc(std::vector &v, std::vector &u) {\n gsl_matrix *A = gsl_matrix_alloc(cspline::N - 2, cspline::N - 2);\n gsl_vector *Z = gsl_vector_alloc(cspline::N - 2);\n gsl_vector *U = gsl_vector_alloc(cspline::N - 2);\n \n for (int i = 1; i < cspline::N - 1; ++i) {\n gsl_vector_set(U, i - 1, u[i - 1]);\n for (int j = 1; j < cspline::N - 1; ++j) {\n if (i == j) gsl_matrix_set(A, i - 1, j - 1, v[i - 1]);\n else if (j == i + 1) gsl_matrix_set(A, i - 1, j - 1, cspline::h[i]);\n else if (j == i - 1) gsl_matrix_set(A, i - 1, j - 1, cspline::h[j]);\n else gsl_matrix_set(A, i - 1, j - 1, 0.0);\n }\n }\n \n int s;\n gsl_permutation *p = gsl_permutation_alloc(cspline::N - 2);\n gsl_linalg_LU_decomp(A, p, &s);\n gsl_linalg_LU_solve(A, p, U, Z);\n \n for (int i = 0; i < cspline::N; ++i) {\n if (i == 0 || i == cspline::N - 1) cspline::z.push_back(0.0);\n else cspline::z.push_back(gsl_vector_get(Z, i - 1));\n }\n \n gsl_vector_free(Z);\n gsl_vector_free(U);\n gsl_matrix_free(A);\n gsl_permutation_free(p);\n}\n\ntemplate cspline::cspline() {\n cspline::N = 1;\n}\n\ntemplate cspline::cspline(std::vector &x, std::vector &fx) {\n cspline::N = fx.size();\n \n for (int i = 0; i < cspline::N; ++i) {\n cspline::t.push_back(x[i]);\n cspline::y.push_back(fx[i]);\n }\n \n std::vector b(cspline::N - 1);\n std::vector v(cspline::N - 2);\n std::vector u(cspline::N - 2);\n \n cspline::h_calc();\n cspline::b_calc(b);\n cspline::v_calc(v);\n cspline::u_calc(u, b);\n cspline::z_calc(v, u);\n}\n\ntemplate void cspline::initialize(std::vector &x, std::vector &fx) {\n cspline::N = fx.size();\n \n for (int i = 0; i < cspline::N; ++i) {\n cspline::t.push_back(x[i]);\n cspline::y.push_back(fx[i]);\n }\n \n std::vector b(cspline::N - 1);\n std::vector v(cspline::N - 2);\n std::vector u(cspline::N - 2);\n \n cspline::h_calc();\n cspline::b_calc(b);\n cspline::v_calc(v);\n cspline::u_calc(u, b);\n cspline::z_calc(v, u);\n}\n\ntemplate void cspline::set_pointer_for_device(std::vector &spline) {\n for (int i = 0; i < cspline::N; ++i) {\n float4 temp = {cspline::t[i], cspline::y[i], cspline::z[i], cspline::h[i]};\n spline.push_back(temp);\n }\n}\n\ntemplate void cspline::set_pointer_for_device(std::vector &spline) {\n for (int i = 0; i < cspline::N; ++i) {\n double4 temp = {cspline::t[i], cspline::y[i], cspline::z[i], cspline::h[i]};\n spline.push_back(temp);\n }\n}\n\ntemplate T cspline::evaluate(T x) {\n if (x < cspline::t[0] || x > cspline::t[cspline::N - 1]) {\n std::stringstream message;\n message << \"The requested x value is outside of the allowed range.\" << std::endl;\n throw std::runtime_error(message.str());\n }\n \n int i = 0;\n while (cspline::t[i] < x) ++i;\n i--;\n \n T val = (cspline::z[i + 1]*(x - cspline::t[i])*(x - cspline::t[i])*(x - cspline::t[i]))/(6.0*cspline::h[i])\n + (cspline::z[i]*(cspline::t[i + 1] - x)*(cspline::t[i + 1] - x)*(cspline::t[i + 1] - x))/(6.0*cspline::h[i])\n + (cspline::y[i + 1]/cspline::h[i] - (cspline::z[i + 1]*cspline::h[i])/6.0)*(x - cspline::t[i])\n + (cspline::y[i]/cspline::h[i] - (cspline::h[i]*cspline::z[i])/6.0)*(cspline::t[i + 1] - x);\n \n return val;\n}\n\n#endif\n", "meta": {"hexsha": "1647a2656a83ad786ffc71dc940dede9d1f6af33", "size": 5433, "ext": "h", "lang": "C", "max_stars_repo_path": "include/cspline.h", "max_stars_repo_name": "dpearson1983/BIMODAL", "max_stars_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "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/cspline.h", "max_issues_repo_name": "dpearson1983/BIMODAL", "max_issues_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "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/cspline.h", "max_forks_repo_name": "dpearson1983/BIMODAL", "max_forks_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "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.3392857143, "max_line_length": 137, "alphanum_fraction": 0.5291735689, "num_tokens": 1882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6296107916362023}} {"text": "/*\n * Tema 2 ASC\n * 2019 Spring\n * Catalin Olaru / Vlad Spoiala\n */\n#include \n\n#include \"utils.h\"\n/* \n * Add your BLAS implementation here\n */\ndouble* my_solver(int N, double *A, double *B) {\n\tdouble *first_multiplication = malloc(N * N * sizeof(double));\n\tdouble *second_multiplication = malloc(N * N * sizeof(double));\n\tdouble *final_result = malloc(N * N * sizeof(double));\n\tdouble alpha = 1.0;\n\tdouble beta = 0.0;\n\tdouble *identity_matrix = malloc(N * N * sizeof(double));\n\tint i, j;\n\n/* Compute identity matrix so we can use it later on. */\n\tfor (i = 0; i < N; ++i)\n\t\tfor (j = 0; j < N; ++j)\n\t\t\tidentity_matrix[i * N + j] = j == i ? 1.0 : 0.0;\n\n/* Compute Transpose(A) * B in first_multiplication. */\n\tcblas_dgemm(CblasRowMajor,\n\t\t\t\tCblasTrans,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\talpha,\n\t\t\t\tA,\n\t\t\t\tN,\n\t\t\t\tB,\n\t\t\t\tN,\n\t\t\t\tbeta,\n\t\t\t\tfirst_multiplication,\n\t\t\t\tN);\n/* Compute Transpose(B) * A in second_multiplication. */\n\tcblas_dgemm(CblasRowMajor,\n\t\t\t\tCblasTrans,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\talpha,\n\t\t\t\tB,\n\t\t\t\tN,\n\t\t\t\tA,\n\t\t\t\tN,\n\t\t\t\tbeta,\n\t\t\t\tsecond_multiplication,\n\t\t\t\tN);\n/* Add the previous 2 results in second multiplication. */\n\tcblas_dgemm(CblasRowMajor,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\talpha,\n\t\t\t\tfirst_multiplication,\n\t\t\t\tN,\n\t\t\t\tidentity_matrix,\n\t\t\t\tN,\n\t\t\t\talpha,\n\t\t\t\tsecond_multiplication,\n\t\t\t\tN);\n\n/* Apply zerotr(second_multiplication) as everything involving\n * CblasLower or CblasUpper didn't work for some reason. :(\n */\n\tfor (i = 0; i < N; ++i)\n\t\tfor (j = 0; j < i; ++j)\n\t\t\tsecond_multiplication[i * N + j] = 0;\n\n/* Multiply second_multiplication by itself so we get the\n * result in final_result. */\n\tcblas_dgemm(CblasRowMajor,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tCblasNoTrans,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\tN,\n\t\t\t\talpha,\n\t\t\t\tsecond_multiplication,\n\t\t\t\tN,\n\t\t\t\tsecond_multiplication,\n\t\t\t\tN,\n\t\t\t\tbeta,\n\t\t\t\tfinal_result,\n\t\t\t\tN);\n\n/* Free everything aside from the return value. */\n\tfree(first_multiplication);\n\tfree(second_multiplication);\n\tfree(identity_matrix);\n\n\treturn final_result;\n}\n", "meta": {"hexsha": "c477747b1d62ee85f0cf00516e8bf22e715d3aa8", "size": 2036, "ext": "c", "lang": "C", "max_stars_repo_path": "solver_blas.c", "max_stars_repo_name": "AlexFazakas/matrix-multiplication-optimizations", "max_stars_repo_head_hexsha": "a51a56f814998561a0960deebb7e6be780c6f512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "solver_blas.c", "max_issues_repo_name": "AlexFazakas/matrix-multiplication-optimizations", "max_issues_repo_head_hexsha": "a51a56f814998561a0960deebb7e6be780c6f512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver_blas.c", "max_forks_repo_name": "AlexFazakas/matrix-multiplication-optimizations", "max_forks_repo_head_hexsha": "a51a56f814998561a0960deebb7e6be780c6f512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7669902913, "max_line_length": 64, "alphanum_fraction": 0.6227897839, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6290892226167761}} {"text": "/*\n * harvest.c -- compute solutions of harvest equation\n *\n * (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil\n */\n#include \n#include \n#define __USE_XOPEN\n#include \n#include \n#include \n\ntypedef struct param_s {\n\tdouble\ta;\n\tdouble\th;\n} param_t;\n\nparam_t\tp0 = { .a = 5, .h = 0.8 };\n\nint\tf(double x, const double y[], double f[], void *params) {\n\tparam_t\t*p = (param_t *)params;\n\tf[0] = p->a * y[0] * (1 - y[0]) - p->h * (1 + sin(2 * M_PI * x));\n\treturn GSL_SUCCESS;\n}\n\nint\tsinglecurve(FILE *out, const char *name, double x0, double y0,\n\t\tint direction) {\n\tprintf(\"%s: %f\\n\", name, y0);\n\tgsl_odeiv2_system\tsystem = { f, NULL, 1, &p0 };\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6 * direction, 1e-6, 0.0);\n\tfprintf(out, \"path %s;\\n\", name);\n\tdouble\tx = x0;\n\tdouble\ty[1] = { y0 };\n\tfprintf(out, \"%s = (%.3f,%.3f)\", name, x, y[0]);\n\tfor (int i = 1; i < 500; i++) {\n\t\tdouble\txnext = x + 0.01 * direction;\n\t\tint\tstatus = gsl_odeiv2_driver_apply(driver, &x, xnext, y);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"error: rc = %d\\n\", status);\n\t\t\tfprintf(out, \";\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (fabs(y[0]) > 100) {\n\t\t\tgoto end;\n\t\t}\n\t\tfprintf(out, \"\\n --(%.3f,%.3f)\", x, y[0]);\n\t}\nend:\n\tfprintf(out, \";\\n\");\n\tgsl_odeiv2_driver_free(driver);\n\treturn 1;\n}\n\nint\tcentercurve(FILE *out, const char *name, double y0) {\n\tprintf(\"%s: %f\\n\", name, y0);\n\tgsl_odeiv2_system\tsystem = { f, NULL, 1, &p0 };\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t-1e-6, 1e-6, 0.0);\n\tfprintf(out, \"path %s;\\n\", name);\n\tdouble\tx = 2.5;\n\tdouble\ty[1] = { y0 };\n\t// integrate backwards to the initial value\n\tgsl_odeiv2_driver_apply(driver, &x, 0, y);\n\tgsl_odeiv2_driver_free(driver);\n\tdriver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6, 1e-6, 0.0);\n\tif (fabs(y[0]) > 100) {\n\t\tgoto end;\n\t}\n\tfprintf(out, \"%s = (%.3f,%.3f)\", name, x, y[0]);\n\tfor (int i = 1; i < 501; i++) {\n\t\tdouble\txnext = x + 0.01;\n\t\tint\tstatus = gsl_odeiv2_driver_apply(driver, &x, xnext, y);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"error: rc = %d\\n\", status);\n\t\t\tfprintf(out, \";\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (fabs(y[0]) > 100) {\n\t\t\tgoto end;\n\t\t}\n\t\tfprintf(out, \"\\n --(%.3f,%.3f)\", x, y[0]);\n\t}\nend:\n\tfprintf(out, \";\\n\");\n\tgsl_odeiv2_driver_free(driver);\n\treturn 1;\n}\n\nint\tlimitcurve(FILE *out, const char *name, int direction) {\n\tgsl_odeiv2_system\tsystem = { f, NULL, 1, &p0 };\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\tdirection * 1e-6, 1e-6, 0.0);\n\tdouble\tx = 0;\n\tdouble\ty[1] = { 0.5 };\n\tdouble\txnext = 1000 * direction;\n\tint\tstatus = gsl_odeiv2_driver_apply(driver, &x, xnext, y);\n\tprintf(\"integration from %f to %f: %f (%d)\\n\", x, xnext, y[0], status);\n\tgsl_odeiv2_driver_free(driver);\n\t// now use this as the initial value\n\treturn singlecurve(out, name, 2.5 * (1 - direction), y[0], direction);\n}\n\nint\tmain(int argc, char *argv[]) {\n\n\tFILE\t*out = fopen(\"harvest.mp\", \"w\");\n\tchar\tsuffix = 'a';\n\tchar\tcurvename[10];\n\tfor (int i = 0; i < 5; i++) {\n\t\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\t\tdouble\ty0 = 0.7 + 0.2 * i;\n\t\tsinglecurve(out, curvename, 0, y0, 1);\n\t}\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 0, 0.318, 1);\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 0, 0.315, 1);\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 0, 0.300, 1);\n\tfor (int i = 0; i < 5; i++) {\n\t\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\t\tdouble\ty0 = 0.3 - 0.2 * i;\n\t\tsinglecurve(out, curvename, 5, y0, -1);\n\t}\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 5, 0.892, -1);\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 5, 0.895, -1);\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tsinglecurve(out, curvename, 5, 0.91, -1);\n\tfor (int i = -3; i <= 3; i++) {\n\t\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\t\tdouble\ty0 = 0.395 + 0.0945 * i;\n\t\tcentercurve(out, curvename, y0);\n\t}\n\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tlimitcurve(out, curvename, -1);\n\tsnprintf(curvename, sizeof(curvename), \"path%c\", suffix++);\n\tlimitcurve(out, curvename, 1);\n\n\tfclose(out);\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "72e00f90f8b2a566deee933786d3e7551a14d4dc", "size": 4480, "ext": "c", "lang": "C", "max_stars_repo_path": "skript/chapters/images/harvest.c", "max_stars_repo_name": "MatthiasRubin/SeminarDGL", "max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z", "max_issues_repo_path": "skript/chapters/images/harvest.c", "max_issues_repo_name": "MatthiasRubin/SeminarDGL", "max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skript/chapters/images/harvest.c", "max_forks_repo_name": "MatthiasRubin/SeminarDGL", "max_forks_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8666666667, "max_line_length": 72, "alphanum_fraction": 0.6303571429, "num_tokens": 1664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6274504177837984}} {"text": "#include \n#include \n#include \n\n#define N 20\n\nint\nmain (void)\n{\n double t[N];\n double sum_accel, err;\n double sum = 0;\n int n;\n \n gsl_sum_levin_u_workspace * w \n = gsl_sum_levin_u_alloc (N);\n\n const double zeta_2 = M_PI * M_PI / 6.0;\n \n /* terms for zeta(2) = \\sum_{n=1}^{\\infty} 1/n^2 */\n\n for (n = 0; n < N; n++)\n {\n double np1 = n + 1.0;\n t[n] = 1.0 / (np1 * np1);\n sum += t[n];\n }\n \n gsl_sum_levin_u_accel (t, N, w, &sum_accel, &err);\n\n printf (\"term-by-term sum = % .16f using %d terms\\n\", \n sum, N);\n\n printf (\"term-by-term sum = % .16f using %zu terms\\n\", \n w->sum_plain, w->terms_used);\n\n printf (\"exact value = % .16f\\n\", zeta_2);\n printf (\"accelerated sum = % .16f using %zu terms\\n\", \n sum_accel, w->terms_used);\n\n printf (\"estimated error = % .16f\\n\", err);\n printf (\"actual error = % .16f\\n\", \n sum_accel - zeta_2);\n\n gsl_sum_levin_u_free (w);\n return 0;\n}\n", "meta": {"hexsha": "65dacc96557f0c78f2d93d927ebf3fd6d3e83099", "size": 1000, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/sum.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/sum.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/sum.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 20.8333333333, "max_line_length": 57, "alphanum_fraction": 0.55, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6274423522248882}} {"text": "/* specfunc/mathieu_angfunc.c\n * \n * Copyright (C) 2002 Lowell Johnson\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: L. Johnson */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint gsl_sf_mathieu_ce_e(int order, double qq, double zz, gsl_sf_result *result)\n{\n int even_odd, ii, status;\n double coeff[GSL_SF_MATHIEU_COEFF], norm, fn, factor;\n gsl_sf_result aa;\n\n\n norm = 0.0;\n even_odd = 0;\n if (order % 2 != 0)\n even_odd = 1;\n \n /* Handle the trivial case where q = 0. */\n if (qq == 0.0)\n {\n norm = 1.0;\n if (order == 0)\n norm = sqrt(2.0);\n\n fn = cos(order*zz)/norm;\n \n result->val = fn;\n result->err = 2.0*GSL_DBL_EPSILON;\n factor = fabs(fn);\n if (factor > 1.0)\n result->err *= factor;\n \n return GSL_SUCCESS;\n }\n \n /* Use symmetry characteristics of the functions to handle cases with\n negative order. */\n if (order < 0)\n order *= -1;\n\n /* Compute the characteristic value. */\n status = gsl_sf_mathieu_a_e(order, qq, &aa);\n if (status != GSL_SUCCESS)\n {\n return status;\n }\n \n /* Compute the series coefficients. */\n status = gsl_sf_mathieu_a_coeff(order, qq, aa.val, coeff);\n if (status != GSL_SUCCESS)\n {\n return status;\n }\n \n if (even_odd == 0)\n {\n fn = 0.0;\n norm = coeff[0]*coeff[0];\n for (ii=0; iival = fn;\n result->err = 2.0*GSL_DBL_EPSILON;\n factor = fabs(fn);\n if (factor > 1.0)\n result->err *= factor;\n \n return GSL_SUCCESS;\n}\n\n\nint gsl_sf_mathieu_se_e(int order, double qq, double zz, gsl_sf_result *result)\n{\n int even_odd, ii, status;\n double coeff[GSL_SF_MATHIEU_COEFF], norm, fn, factor;\n gsl_sf_result aa;\n\n\n norm = 0.0;\n even_odd = 0;\n if (order % 2 != 0)\n even_odd = 1;\n \n /* Handle the trivial cases where order = 0 and/or q = 0. */\n if (order == 0)\n {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n \n if (qq == 0.0)\n {\n norm = 1.0;\n fn = sin(order*zz);\n \n result->val = fn;\n result->err = 2.0*GSL_DBL_EPSILON;\n factor = fabs(fn);\n if (factor > 1.0)\n result->err *= factor;\n \n return GSL_SUCCESS;\n }\n \n /* Use symmetry characteristics of the functions to handle cases with\n negative order. */\n if (order < 0)\n order *= -1;\n\n /* Compute the characteristic value. */\n status = gsl_sf_mathieu_b_e(order, qq, &aa);\n if (status != GSL_SUCCESS)\n {\n return status;\n }\n \n /* Compute the series coefficients. */\n status = gsl_sf_mathieu_b_coeff(order, qq, aa.val, coeff);\n if (status != GSL_SUCCESS)\n {\n return status;\n }\n \n if (even_odd == 0)\n {\n fn = 0.0;\n for (ii=0; iival = fn;\n result->err = 2.0*GSL_DBL_EPSILON;\n factor = fabs(fn);\n if (factor > 1.0)\n result->err *= factor;\n \n return GSL_SUCCESS;\n}\n\n\nint gsl_sf_mathieu_ce_array(int nmin, int nmax, double qq, double zz,\n gsl_sf_mathieu_workspace *work,\n double result_array[])\n{\n int even_odd, order, ii, jj, status;\n double coeff[GSL_SF_MATHIEU_COEFF], *aa = work->aa, norm;\n \n\n /* Initialize the result array to zeroes. */\n for (ii=0; iisize < (unsigned int)nmax)\n {\n GSL_ERROR(\"Work space not large enough\", GSL_EINVAL);\n }\n \n if (nmin < 0 || nmax < nmin)\n {\n GSL_ERROR(\"domain error\", GSL_EDOM);\n }\n\n /* Compute all of the eigenvalues up to nmax. */\n gsl_sf_mathieu_a_array(0, nmax, qq, work, aa);\n\n for (ii=0, order=nmin; order<=nmax; ii++, order++)\n {\n norm = 0.0;\n even_odd = 0;\n if (order % 2 != 0)\n even_odd = 1;\n \n /* Handle the trivial case where q = 0. */\n if (qq == 0.0)\n {\n norm = 1.0;\n if (order == 0)\n norm = sqrt(2.0);\n\n result_array[ii] = cos(order*zz)/norm;\n\n continue;\n }\n \n /* Compute the series coefficients. */\n status = gsl_sf_mathieu_a_coeff(order, qq, aa[order], coeff);\n if (status != GSL_SUCCESS)\n return status;\n \n if (even_odd == 0)\n {\n norm = coeff[0]*coeff[0];\n for (jj=0; jjbb, norm;\n \n\n /* Initialize the result array to zeroes. */\n for (ii=0; iisize < (unsigned int)nmax)\n {\n GSL_ERROR(\"Work space not large enough\", GSL_EINVAL);\n }\n \n if (nmin < 0 || nmax < nmin)\n {\n GSL_ERROR(\"domain error\", GSL_EDOM);\n }\n\n /* Compute all of the eigenvalues up to nmax. */\n gsl_sf_mathieu_b_array(0, nmax, qq, work, bb);\n\n for (ii=0, order=nmin; order<=nmax; ii++, order++)\n {\n norm = 0.0;\n even_odd = 0;\n if (order % 2 != 0)\n even_odd = 1;\n \n /* Handle the trivial cases where order = 0 and/or q = 0. */\n if (order == 0)\n {\n norm = 1.0;\n result_array[ii] = 0.0;\n continue;\n }\n \n if (qq == 0.0)\n {\n norm = 1.0;\n result_array[ii] = sin(order*zz);\n\n continue;\n }\n \n /* Compute the series coefficients. */\n status = gsl_sf_mathieu_b_coeff(order, qq, bb[order], coeff);\n if (status != GSL_SUCCESS)\n {\n return status;\n }\n \n if (even_odd == 0)\n {\n for (jj=0; jj\n#include \n#include \n#include \n\n/* The Rayleigh distribution has the form\n\n p(x) dx = (x / sigma^2) exp(-x^2/(2 sigma^2)) dx\n\n for x = 0 ... +infty */\n\ndouble\ngsl_ran_rayleigh (const gsl_rng * r, const double sigma)\n{\n double u = gsl_rng_uniform_pos (r);\n\n return sigma * sqrt(-2.0 * log (u));\n}\n\ndouble\ngsl_ran_rayleigh_pdf (const double x, const double sigma)\n{\n if (x < 0)\n {\n return 0 ;\n }\n else\n {\n double u = x / sigma ;\n double p = (u / sigma) * exp(-u * u / 2.0) ;\n \n return p;\n }\n}\n\n/* The Rayleigh tail distribution has the form\n\n p(x) dx = (x / sigma^2) exp((a^2 - x^2)/(2 sigma^2)) dx\n\n for x = a ... +infty */\n\ndouble\ngsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma)\n{\n double u = gsl_rng_uniform_pos (r);\n\n return sqrt(a * a - 2.0 * sigma * sigma * log (u));\n}\n\ndouble\ngsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma)\n{\n if (x < a)\n {\n return 0 ;\n }\n else\n {\n double u = x / sigma ;\n double v = a / sigma ;\n\n double p = (u / sigma) * exp((v + u) * (v - u) / 2.0) ;\n \n return p;\n }\n}\n", "meta": {"hexsha": "1600d5b3638d51e308f917bed742e6502e1bdb31", "size": 2019, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/rayleigh.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/rayleigh.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/rayleigh.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.476744186, "max_line_length": 78, "alphanum_fraction": 0.6310054482, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6274423384761786}} {"text": "#ifndef DETERMINISTIC_NETWORK_SIR_H\n#define DETERMINISTIC_NETWORK_SIR_H\n\n#include \n#include \n#include \n#include \n#include \"DiffEq_Sim.h\"\n\nusing namespace std;\n\nclass Deterministic_Network_SIR_Sim : public DiffEq_Sim {\n\n private:\n const double r;\n const double mu;\n const vector deg_dist;\n\n public:\n Deterministic_Network_SIR_Sim() : r(0.0), mu(0.0) { nbins=4;}\n Deterministic_Network_SIR_Sim(double r_param, double mu_param, vector deg_dist_param):\n r(r_param), \n mu(mu_param), \n deg_dist(deg_dist_param) { \n nbins=4; \n }\n ~Deterministic_Network_SIR_Sim() {};\n\n void initialize( double theta, double pS, double pI, double I) {\n y = new double[nbins];\n y[0] = theta; \n y[1] = pS; \n y[2] = pI;\n y[3] = I;\n }\n\n double current_susceptible() { return g( y[0] ); }\n double current_infectious() { return y[3]; }\n double current_recovered() { return 1.0 - current_susceptible() - current_infectious(); }\n\n double g( double theta) {\n double val = 0;\n for (unsigned int i = 0; i\n#include \n#include \n\n/* set up parameters for this simulated annealing run */\n\n/* how many points do we try before stepping */\n#define N_TRIES 200 \n\n/* how many iterations for each T? */\n#define ITERS_FIXED_T 10 \n\n/* max step size in random walk */\n#define STEP_SIZE 10 \n\n/* Boltzmann constant */\n#define K 1.0 \n\n/* initial temperature */\n#define T_INITIAL 0.002 \n\n/* damping factor for temperature */\n#define MU_T 1.005 \n#define T_MIN 2.0e-6\n\ngsl_siman_params_t params \n = {N_TRIES, ITERS_FIXED_T, STEP_SIZE,\n K, T_INITIAL, MU_T, T_MIN};\n\n/* now some functions to test in one dimension */\ndouble E1(void *xp)\n{\n double x = * ((double *) xp);\n\n return exp(-pow((x-1.0),2.0))*sin(8*x);\n}\n\ndouble M1(void *xp, void *yp)\n{\n double x = *((double *) xp);\n double y = *((double *) yp);\n\n return fabs(x - y);\n}\n\nvoid S1(const gsl_rng * r, void *xp, double step_size)\n{\n double old_x = *((double *) xp);\n double new_x;\n\n double u = gsl_rng_uniform(r);\n new_x = u*2*step_size - step_size + old_x;\n\n memcpy(xp, &new_x, sizeof(new_x));\n}\n\nvoid P1(void *xp)\n{\n printf(\"%12g\", *((double *) xp));\n}\n\nint\nmain(int argc, char *argv[])\n{\n gsl_rng_type * T;\n gsl_rng * r;\n\n double x_initial = 15.5;\n\n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc(T);\n\n gsl_siman_solve(r, &x_initial, E1, S1, M1, P1,\n NULL, NULL, NULL, \n sizeof(double), params);\n return 0;\n}\n", "meta": {"hexsha": "72131dc64de682b2f473f469574803e799e8cf07", "size": 1530, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/siman/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/siman/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/siman/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": 19.125, "max_line_length": 56, "alphanum_fraction": 0.6013071895, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6265989335539175}} {"text": "/*\n NAME:\n logsum\n PURPOSE:\n calculate the log of the sum of numbers which are given as logs using as much of the dynamic range as possible\n CALLING SEQUENCE:\n logsum(gsl_matrix * q, int row, bool isrow,bool partial, int partial_indx[3])\n INPUT:\n q - matrix of which we will sum a row/column\n row - row/column number\n isrow - are we summing a row or a column\n OUTPUT:\n log of the sum\n REVISION HISTORY:\n 2008-09-21 - Written Bovy\n*/\n#include \n#include \n#include \n#include \n#include \n\ndouble logsum(gsl_matrix * q, int row, bool isrow){\n double logxmin = log(DBL_MIN);\n double logxmax = log(DBL_MAX);\n int l = (isrow) ? q->size2 : q->size1;\n\n /* First find the maximum and mininum */\n double max, min;\n minmax(q,row,isrow,&min,&max);//,allfixed);\n\n\n min *= -1.;\n min += logxmin;\n max *= -1.;\n max += logxmax - log(l);\n (min > max) ? (max=max) : (max=min);\n double loglike=0.0;\n int dd;\n if (isrow)\n for (dd = 0; dd != q->size2; ++dd)\n\tloglike += exp(gsl_matrix_get(q,row,dd)+max);\n else\n for (dd = 0; dd != q->size1; ++dd)\n\tloglike += exp(gsl_matrix_get(q,dd,row)+max);\n \n\n return log(loglike)-max;\n}\n", "meta": {"hexsha": "824e2f4c31dac0cd076da74cd492cc1025a79b96", "size": 1258, "ext": "c", "lang": "C", "max_stars_repo_path": "src/logsum.c", "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_issues_repo_path": "src/logsum.c", "max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_forks_repo_path": "src/logsum.c", "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "avg_line_length": 25.16, "max_line_length": 115, "alphanum_fraction": 0.6184419714, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6265590190672602}} {"text": "/* linalg/svd.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 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#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"givens.c\"\n#include \"svdstep.c\"\n\n/* Factorise a general M x N matrix A into,\n *\n * A = U D V^T\n *\n * where U is a column-orthogonal M x N matrix (U^T U = I), \n * D is a diagonal N x N matrix, \n * and V is an N x N orthogonal matrix (V^T V = V V^T = I)\n *\n * U is stored in the original matrix A, which has the same size\n *\n * V is stored as a separate matrix (not V^T). You must take the\n * transpose to form the product above.\n *\n * The diagonal matrix D is stored in the vector S, D_ii = S_i\n */\n\nint\ngsl_linalg_SV_decomp (gsl_matrix * A, gsl_matrix * V, gsl_vector * S, \n gsl_vector * work)\n{\n size_t a, b, i, j, iter;\n\n const size_t M = A->size1;\n const size_t N = A->size2;\n const size_t K = GSL_MIN (M, N);\n\n if (M < N)\n {\n GSL_ERROR (\"svd of MxN matrix, Msize1 != N)\n {\n GSL_ERROR (\"square matrix V must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (V->size1 != V->size2)\n {\n GSL_ERROR (\"matrix V must be square\", GSL_ENOTSQR);\n }\n else if (S->size != N)\n {\n GSL_ERROR (\"length of vector S must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (work->size != N)\n {\n GSL_ERROR (\"length of workspace must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n\n /* Handle the case of N = 1 (SVD of a column vector) */\n\n if (N == 1)\n {\n gsl_vector_view column = gsl_matrix_column (A, 0);\n double norm = gsl_blas_dnrm2 (&column.vector);\n\n gsl_vector_set (S, 0, norm); \n gsl_matrix_set (V, 0, 0, 1.0);\n \n if (norm != 0.0)\n {\n gsl_blas_dscal (1.0/norm, &column.vector);\n }\n\n return GSL_SUCCESS;\n }\n \n {\n gsl_vector_view f = gsl_vector_subvector (work, 0, K - 1);\n \n /* bidiagonalize matrix A, unpack A into U S V */\n \n gsl_linalg_bidiag_decomp (A, S, &f.vector);\n gsl_linalg_bidiag_unpack2 (A, S, &f.vector, V);\n \n /* apply reduction steps to B=(S,Sd) */\n \n chop_small_elements (S, &f.vector);\n \n /* Progressively reduce the matrix until it is diagonal */\n \n b = N - 1;\n iter = 0;\n\n while (b > 0)\n {\n double fbm1 = gsl_vector_get (&f.vector, b - 1);\n\n if (fbm1 == 0.0 || gsl_isnan (fbm1))\n {\n b--;\n continue;\n }\n \n /* Find the largest unreduced block (a,b) starting from b\n and working backwards */\n \n a = b - 1;\n \n while (a > 0)\n {\n double fam1 = gsl_vector_get (&f.vector, a - 1);\n\n if (fam1 == 0.0 || gsl_isnan (fam1))\n {\n break;\n }\n \n a--;\n }\n\n iter++;\n \n if (iter > 100 * N) \n {\n GSL_ERROR(\"SVD decomposition failed to converge\", GSL_EMAXITER);\n }\n\n \n {\n const size_t n_block = b - a + 1;\n gsl_vector_view S_block = gsl_vector_subvector (S, a, n_block);\n gsl_vector_view f_block = gsl_vector_subvector (&f.vector, a, n_block - 1);\n \n gsl_matrix_view U_block =\n gsl_matrix_submatrix (A, 0, a, A->size1, n_block);\n gsl_matrix_view V_block =\n gsl_matrix_submatrix (V, 0, a, V->size1, n_block);\n \n qrstep (&S_block.vector, &f_block.vector, &U_block.matrix, &V_block.matrix);\n \n /* remove any small off-diagonal elements */\n \n chop_small_elements (&S_block.vector, &f_block.vector);\n }\n }\n }\n /* Make singular values positive by reflections if necessary */\n \n for (j = 0; j < K; j++)\n {\n double Sj = gsl_vector_get (S, j);\n \n if (Sj < 0.0)\n {\n for (i = 0; i < N; i++)\n {\n double Vij = gsl_matrix_get (V, i, j);\n gsl_matrix_set (V, i, j, -Vij);\n }\n \n gsl_vector_set (S, j, -Sj);\n }\n }\n \n /* Sort singular values into decreasing order */\n \n for (i = 0; i < K; i++)\n {\n double S_max = gsl_vector_get (S, i);\n size_t i_max = i;\n \n for (j = i + 1; j < K; j++)\n {\n double Sj = gsl_vector_get (S, j);\n \n if (Sj > S_max)\n {\n S_max = Sj;\n i_max = j;\n }\n }\n \n if (i_max != i)\n {\n /* swap eigenvalues */\n gsl_vector_swap_elements (S, i, i_max);\n \n /* swap eigenvectors */\n gsl_matrix_swap_columns (A, i, i_max);\n gsl_matrix_swap_columns (V, i, i_max);\n }\n }\n \n return GSL_SUCCESS;\n}\n\n\n/* Modified algorithm which is better for M>>N */\n\nint\ngsl_linalg_SV_decomp_mod (gsl_matrix * A,\n gsl_matrix * X,\n gsl_matrix * V, gsl_vector * S, gsl_vector * work)\n{\n size_t i, j;\n\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"svd of MxN matrix, Msize1 != N)\n {\n GSL_ERROR (\"square matrix V must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (V->size1 != V->size2)\n {\n GSL_ERROR (\"matrix V must be square\", GSL_ENOTSQR);\n }\n else if (X->size1 != N)\n {\n GSL_ERROR (\"square matrix X must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (X->size1 != X->size2)\n {\n GSL_ERROR (\"matrix X must be square\", GSL_ENOTSQR);\n }\n else if (S->size != N)\n {\n GSL_ERROR (\"length of vector S must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (work->size != N)\n {\n GSL_ERROR (\"length of workspace must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n\n if (N == 1)\n {\n gsl_vector_view column = gsl_matrix_column (A, 0);\n double norm = gsl_blas_dnrm2 (&column.vector);\n\n gsl_vector_set (S, 0, norm); \n gsl_matrix_set (V, 0, 0, 1.0);\n \n if (norm != 0.0)\n {\n gsl_blas_dscal (1.0/norm, &column.vector);\n }\n\n return GSL_SUCCESS;\n }\n\n /* Convert A into an upper triangular matrix R */\n\n for (i = 0; i < N; i++)\n {\n gsl_vector_view c = gsl_matrix_column (A, i);\n gsl_vector_view v = gsl_vector_subvector (&c.vector, i, M - i);\n double tau_i = gsl_linalg_householder_transform (&v.vector);\n\n /* Apply the transformation to the remaining columns */\n\n if (i + 1 < N)\n {\n gsl_matrix_view m =\n gsl_matrix_submatrix (A, i, i + 1, M - i, N - (i + 1));\n gsl_linalg_householder_hm (tau_i, &v.vector, &m.matrix);\n }\n\n gsl_vector_set (S, i, tau_i);\n }\n\n /* Copy the upper triangular part of A into X */\n\n for (i = 0; i < N; i++)\n {\n for (j = 0; j < i; j++)\n {\n gsl_matrix_set (X, i, j, 0.0);\n }\n\n {\n double Aii = gsl_matrix_get (A, i, i);\n gsl_matrix_set (X, i, i, Aii);\n }\n\n for (j = i + 1; j < N; j++)\n {\n double Aij = gsl_matrix_get (A, i, j);\n gsl_matrix_set (X, i, j, Aij);\n }\n }\n\n /* Convert A into an orthogonal matrix L */\n\n for (j = N; j-- > 0;)\n {\n /* Householder column transformation to accumulate L */\n double tj = gsl_vector_get (S, j);\n gsl_matrix_view m = gsl_matrix_submatrix (A, j, j, M - j, N - j);\n gsl_linalg_householder_hm1 (tj, &m.matrix);\n }\n\n /* unpack R into X V S */\n\n gsl_linalg_SV_decomp (X, V, S, work);\n\n /* Multiply L by X, to obtain U = L X, stored in U */\n\n {\n gsl_vector_view sum = gsl_vector_subvector (work, 0, N);\n\n for (i = 0; i < M; i++)\n {\n gsl_vector_view L_i = gsl_matrix_row (A, i);\n gsl_vector_set_zero (&sum.vector);\n\n for (j = 0; j < N; j++)\n {\n double Lij = gsl_vector_get (&L_i.vector, j);\n gsl_vector_view X_j = gsl_matrix_row (X, j);\n gsl_blas_daxpy (Lij, &X_j.vector, &sum.vector);\n }\n\n gsl_vector_memcpy (&L_i.vector, &sum.vector);\n }\n }\n\n return GSL_SUCCESS;\n}\n\n\n/* Solves the system A x = b using the SVD factorization\n *\n * A = U S V^T\n *\n * to obtain x. For M x N systems it finds the solution in the least\n * squares sense. \n */\n\nint\ngsl_linalg_SV_solve (const gsl_matrix * U,\n const gsl_matrix * V,\n const gsl_vector * S,\n const gsl_vector * b, gsl_vector * x)\n{\n if (U->size1 != b->size)\n {\n GSL_ERROR (\"first dimension of matrix U must size of vector b\",\n GSL_EBADLEN);\n }\n else if (U->size2 != S->size)\n {\n GSL_ERROR (\"length of vector S must match second dimension of matrix U\",\n GSL_EBADLEN);\n }\n else if (V->size1 != V->size2)\n {\n GSL_ERROR (\"matrix V must be square\", GSL_ENOTSQR);\n }\n else if (S->size != V->size1)\n {\n GSL_ERROR (\"length of vector S must match size of matrix V\",\n GSL_EBADLEN);\n }\n else if (V->size2 != x->size)\n {\n GSL_ERROR (\"size of matrix V must match size of vector x\", GSL_EBADLEN);\n }\n else\n {\n const size_t N = U->size2;\n size_t i;\n\n gsl_vector *w = gsl_vector_calloc (N);\n\n gsl_blas_dgemv (CblasTrans, 1.0, U, b, 0.0, w);\n\n for (i = 0; i < N; i++)\n {\n double wi = gsl_vector_get (w, i);\n double alpha = gsl_vector_get (S, i);\n if (alpha != 0)\n alpha = 1.0 / alpha;\n gsl_vector_set (w, i, alpha * wi);\n }\n\n gsl_blas_dgemv (CblasNoTrans, 1.0, V, w, 0.0, x);\n\n gsl_vector_free (w);\n\n return GSL_SUCCESS;\n }\n}\n\n/* This is a the jacobi version */\n/* Author: G. Jungman */\n\n/*\n * Algorithm due to J.C. Nash, Compact Numerical Methods for\n * Computers (New York: Wiley and Sons, 1979), chapter 3.\n * See also Algorithm 4.1 in\n * James Demmel, Kresimir Veselic, \"Jacobi's Method is more\n * accurate than QR\", Lapack Working Note 15 (LAWN15), October 1989.\n * Available from netlib.\n *\n * Based on code by Arthur Kosowsky, Rutgers University\n * kosowsky@physics.rutgers.edu \n *\n * Another relevant paper is, P.P.M. De Rijk, \"A One-Sided Jacobi\n * Algorithm for computing the singular value decomposition on a\n * vector computer\", SIAM Journal of Scientific and Statistical\n * Computing, Vol 10, No 2, pp 359-371, March 1989.\n * \n */\n\nint\ngsl_linalg_SV_decomp_jacobi (gsl_matrix * A, gsl_matrix * Q, gsl_vector * S)\n{\n if (A->size1 < A->size2)\n {\n /* FIXME: only implemented M>=N case so far */\n\n GSL_ERROR (\"svd of MxN matrix, Msize1 != A->size2)\n {\n GSL_ERROR (\"square matrix Q must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else if (Q->size1 != Q->size2)\n {\n GSL_ERROR (\"matrix Q must be square\", GSL_ENOTSQR);\n }\n else if (S->size != A->size2)\n {\n GSL_ERROR (\"length of vector S must match second dimension of matrix A\",\n GSL_EBADLEN);\n }\n else\n {\n const size_t M = A->size1;\n const size_t N = A->size2;\n size_t i, j, k;\n\n /* Initialize the rotation counter and the sweep counter. */\n int count = 1;\n int sweep = 0;\n int sweepmax = 5*N;\n\n double tolerance = 10 * M * GSL_DBL_EPSILON;\n\n /* Always do at least 12 sweeps. */\n sweepmax = GSL_MAX (sweepmax, 12);\n\n /* Set Q to the identity matrix. */\n gsl_matrix_set_identity (Q);\n\n /* Store the column error estimates in S, for use during the\n orthogonalization */\n\n for (j = 0; j < N; j++)\n {\n gsl_vector_view cj = gsl_matrix_column (A, j);\n double sj = gsl_blas_dnrm2 (&cj.vector);\n gsl_vector_set(S, j, GSL_DBL_EPSILON * sj);\n }\n \n /* Orthogonalize A by plane rotations. */\n\n while (count > 0 && sweep <= sweepmax)\n {\n /* Initialize rotation counter. */\n count = N * (N - 1) / 2;\n\n for (j = 0; j < N - 1; j++)\n {\n for (k = j + 1; k < N; k++)\n {\n double a = 0.0;\n double b = 0.0;\n double p = 0.0;\n double q = 0.0;\n double cosine, sine;\n double v;\n double abserr_a, abserr_b;\n int sorted, orthog, noisya, noisyb;\n\n gsl_vector_view cj = gsl_matrix_column (A, j);\n gsl_vector_view ck = gsl_matrix_column (A, k);\n\n gsl_blas_ddot (&cj.vector, &ck.vector, &p);\n p *= 2.0 ; /* equation 9a: p = 2 x.y */\n\n a = gsl_blas_dnrm2 (&cj.vector);\n b = gsl_blas_dnrm2 (&ck.vector);\n\n q = a * a - b * b;\n v = hypot(p, q);\n\n /* test for columns j,k orthogonal, or dominant errors */\n\n abserr_a = gsl_vector_get(S,j);\n abserr_b = gsl_vector_get(S,k);\n\n sorted = (GSL_COERCE_DBL(a) >= GSL_COERCE_DBL(b));\n orthog = (fabs (p) <= tolerance * GSL_COERCE_DBL(a * b));\n noisya = (a < abserr_a);\n noisyb = (b < abserr_b);\n\n if (sorted && (orthog || noisya || noisyb))\n {\n count--;\n continue;\n }\n\n /* calculate rotation angles */\n if (v == 0 || !sorted)\n {\n cosine = 0.0;\n sine = 1.0;\n }\n else\n {\n cosine = sqrt((v + q) / (2.0 * v));\n sine = p / (2.0 * v * cosine);\n }\n\n /* apply rotation to A */\n for (i = 0; i < M; i++)\n {\n const double Aik = gsl_matrix_get (A, i, k);\n const double Aij = gsl_matrix_get (A, i, j);\n gsl_matrix_set (A, i, j, Aij * cosine + Aik * sine);\n gsl_matrix_set (A, i, k, -Aij * sine + Aik * cosine);\n }\n\n gsl_vector_set(S, j, fabs(cosine) * abserr_a + fabs(sine) * abserr_b);\n gsl_vector_set(S, k, fabs(sine) * abserr_a + fabs(cosine) * abserr_b);\n\n /* apply rotation to Q */\n for (i = 0; i < N; i++)\n {\n const double Qij = gsl_matrix_get (Q, i, j);\n const double Qik = gsl_matrix_get (Q, i, k);\n gsl_matrix_set (Q, i, j, Qij * cosine + Qik * sine);\n gsl_matrix_set (Q, i, k, -Qij * sine + Qik * cosine);\n }\n }\n }\n\n /* Sweep completed. */\n sweep++;\n }\n\n /* \n * Orthogonalization complete. Compute singular values.\n */\n\n {\n double prev_norm = -1.0;\n\n for (j = 0; j < N; j++)\n {\n gsl_vector_view column = gsl_matrix_column (A, j);\n double norm = gsl_blas_dnrm2 (&column.vector);\n\n /* Determine if singular value is zero, according to the\n criteria used in the main loop above (i.e. comparison\n with norm of previous column). */\n\n if (norm == 0.0 || prev_norm == 0.0 \n || (j > 0 && norm <= tolerance * prev_norm))\n {\n gsl_vector_set (S, j, 0.0); /* singular */\n gsl_vector_set_zero (&column.vector); /* annihilate column */\n\n prev_norm = 0.0;\n }\n else\n {\n gsl_vector_set (S, j, norm); /* non-singular */\n gsl_vector_scale (&column.vector, 1.0 / norm); /* normalize column */\n\n prev_norm = norm;\n }\n }\n }\n\n if (count > 0)\n {\n /* reached sweep limit */\n GSL_ERROR (\"Jacobi iterations did not reach desired tolerance\",\n GSL_ETOL);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "32033d860ef7f3c9f699693b40eb43a9cb8a08bb", "size": 17407, "ext": "c", "lang": "C", "max_stars_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/svd.c", "max_stars_repo_name": "mattjr/structured", "max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_stars_repo_licenses": ["Apache-2.0"], "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/svd.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/svd.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 27.6301587302, "max_line_length": 88, "alphanum_fraction": 0.5090480841, "num_tokens": 4753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6259752407887509}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid invert_square_matrix(double *matrix_in, int size, double *inverse_out) {\n gsl_matrix * matrix;\n gsl_matrix * LU_decomp;\n gsl_matrix * inverse;\n gsl_permutation *permutation;\n int signum;\n gsl_matrix_view m;\n double * matrix_copy;\n int i_x, i_y, i_M;\n\n // Allocate some RAM and set some pointers\n matrix_copy = (double *)SID_malloc(sizeof(double) * size * size);\n memcpy(matrix_copy, matrix_in, sizeof(double) * size * size);\n m = gsl_matrix_view_array(matrix_copy, size, size);\n matrix = &m.matrix;\n LU_decomp = matrix;\n inverse = gsl_matrix_alloc(size, size);\n permutation = gsl_permutation_alloc(size);\n\n // Perform LU decomposition. Result ends-up in matrix,\n // which is pointed to by LU_decomp\n gsl_linalg_LU_decomp(matrix, permutation, &signum);\n gsl_linalg_LU_invert(LU_decomp, permutation, inverse);\n\n // Copy result into the out-going array\n for(i_y = 0, i_M = 0; i_y < size; i_y++) {\n for(i_x = 0; i_x < size; i_x++, i_M++) {\n inverse_out[i_M] = gsl_matrix_get(inverse, i_x, i_y);\n }\n }\n\n // Test that the matrix*inverse=identity\n /*\n for(i_x=0;i_x\n#include \n#include \n#include \n\n// y' = 2y + x\n// https://www.wolframalpha.com/input/?i=y%27+%3D+2y+%2B+x%2C+y%280%29+%3D+1%2C+y%281%29\n// https://www.wolframalpha.com/input/?i=1%2F4+*+%285+*+e%5E2+-+3%29\n// 미분 방정식을 푸는 방법\n// 1. 미분 방정식의 표준형을 작성한다.\n// y' <<<--- 미분항의 계수를 1로 만들어야 표준형이됨\n// 2. 표준형의 y항 계수식을 통해 적분 인자를 구한다.\n// 3. 적분 인자를 양변에 곱한다.\n// 2y' + y = 3 -> y' + y / 2 = 3 / 2\n// 여기서 적분 인자는 1 / 2가 됨\n// 좀 더 정확하게는 exp^integral(1/2) 형태가 됨\n// 4. 양변에 대한 계산(적분)을 진행한다.\n// 5. 양변을 exp^적분인자 로 나누어 y에 대해 정리한다.\nint odefunc (double x, const double y[], double f[], void *params)\n{\n\t// 계산하고자 하는 미분 방정식의 표준형식을 여기에 기록함\n f[0] = x+2*y[0]; \n return GSL_SUCCESS;\n}\n\nint * jac;\n\nint main(void)\n{\n\t// 1계 미분 방정식\n\t// 만약 2계 미분 방정식이라면 dim = 2\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// Taylor(테일러) 혹은 Maculaurin(맥클로린) 급수\n\t// 테일러 급수를 활용해서 미분을 4번이상 하여\n\t// 오차를 최소화하는 방식을 룬게쿠타 4-5차라고 표현함\n\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.0 }; /* initial value */\n\n\t// 루프를 돌면서 각 케이스별 미분 방정식을 계산함\n for (i = 1; i <= xf; i++)\n {\n\t\t// 0 ~ 10 - x input\n double xi = x0 + i * (xf-x0) / xf;\n\t\t// 결국 이 코드를 다시 재해석하자면\n\t\t// x가 0일 경우, 1일 경우, ... , 10일 경우에 대해 각각을 해석한다고 보면 됩니다!\n\t\t// 앞서서 룬게쿠타 4-5차 방식으로 미분 방정식을 계산하도록\n\t\t// odefunc을 만들었고 이에 대한 설정값들로 xi를 넣고 이에 대한 y값을 계산한다.\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\t\tprintf (\"x = %lf, xi = %lf\\n\", x, xi);\n }\n\n\t// malloc 혹은 new 처럼 Heap에 메모리를 할당하기 때문에\n\t// free를 사용해서 메모리 해제를 해주셔야 메모리 누수를 방지할 수 있음\n gsl_odeiv2_driver_free (d);\n return 0;\n}\n", "meta": {"hexsha": "b0a39403bf75581305ea39b519b31463308ebebd", "size": 2136, "ext": "c", "lang": "C", "max_stars_repo_path": "ch4/src/main/ode.c", "max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z", "max_issues_repo_path": "ch4/src/main/ode.c", "max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/src/main/ode.c", "max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics", "max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z", "avg_line_length": 28.1052631579, "max_line_length": 105, "alphanum_fraction": 0.5767790262, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6257783377882029}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid inc_gamma_error_msg(const char* fn_name, const char* reason, const char* file, int line, int gsl_errno) {\n\tfprintf(stderr, \"Error in GSL %s\\n\", fn_name);\n\tfprintf(stderr, \"GSL Error %i: %s.\\n\", gsl_errno, gsl_strerror(gsl_errno));\n\tfprintf(stderr, \"%s in %s:%i.\\n\", reason, file, line);\n}\n\nvoid gamma_inc_lower_error_handler(const char* reason, const char* file, int line, int gsl_errno) {\n\tif (gsl_errno != GSL_EUNDRFLW) {\n\t\tinc_gamma_error_msg(\"gamma_inc_P while computing lower incomplete gamma ratio.\", reason, file, line, gsl_errno);\n\t\tabort();\n\t}\n}\n\nvoid gamma_inc_upper_error_handler(const char* reason, const char* file, int line, int gsl_errno) {\n\tif (gsl_errno != GSL_EUNDRFLW) {\n\t\tinc_gamma_error_msg(\"gamma_inc while computing upper incomplete gamma ratio.\", reason, file, line, gsl_errno);\n\t\tabort();\n\t}\n}\n\t\n#define INC_GAMMA_NO_UNDERFLOW(fn, handler) do { \\\n\t\tgsl_error_handler_t* old_handler = gsl_set_error_handler(& handler ); \\\n\t\tfn; \\\n\t\tgsl_set_error_handler(old_handler); \\\n\t} while (0)\n\nvoid inc_gamma_check_value(long double val, const char* fn_name) {\n\tif (isnan(val) || !isfinite(val)) {\n\t\tfprintf(stderr, \"Error while computing %s.\\n\", fn_name);\n\t\tif (isnan(val)) {\n\t\t\tfprintf(stderr, \"NaN detected. \");\n\t\t} else {\n\t\t\tfprintf(stderr, \"Infinity detected. \");\n\t\t}\n\t\tfprintf(stderr, \"This is likely the result of an overflow.\\n\");\n\t\tabort();\n\t}\n}\n\n/*\n\tComputes the upper Gamma(x+y,a)/Gamma(x) for x = [1 ... x_max]\n*/\nvoid inc_gamma_upper_ratio_ary(int x_max, double y, double a, double* result) {\n\t\n\t// x = 1 case\n\tsize_t idx = 0;\n\tint x = 1;\n\tlong double ln_gamma_xp1 = 0;\n\t// With fn(x) = Gamma(x+y, a)/Gamma(x)\n\tlong double fn_x;\n\tINC_GAMMA_NO_UNDERFLOW(fn_x = gsl_sf_gamma_inc(x+y, a), gamma_inc_upper_error_handler);\n\tresult[idx] = fn_x;\n\t\n\tfor (;x < x_max;) {\n\t\tln_gamma_xp1 += logl((long double) x);\n\t\t// Using the recurrence relation Gamma(s+1,a) = s Gamma(s,a) + a^s exp(-a)\n\t\t// We have Gamma((x+1)+y)/Gamma(x+1) = (x+y) ( Gamma(x+y)/Gamma(x) )/x + a^(x+y) exp(-a)/Gamma(x+1)\n\t\t// -> fn(x+1) = (x+y) fn(x)/x + exp((x+y) ln a - a - ln Gamma(x+1))\n\t\tlong double fn_xp1 = (x+y) * fn_x/x + expl((x+y)*logl(a) - a - ln_gamma_xp1);\n\t\tresult[idx+1] = (double)fn_xp1;\n\t\tfn_x = fn_xp1;\n\t\tidx += 1;\n\t\tx += 1;\n\t}\n\t// Make use of the fact that NaNs and infinities will propagate to the last value computed.\n\tinc_gamma_check_value(result[x_max-1], \"upper incomplete gamma ratio\");\n}\n\n/*\n\tComputes the lower gamma(x+y,a)/Gamma(x) for x = [1 ... x_max]\n*/\nvoid inc_gamma_lower_ratio_ary(int x_max, double y, double a, double* result) {\n\t\n\t// x = x_max case\n\tsize_t idx = x_max - 1;\n\tint x = x_max;\n\tlong double ln_gamma_x = gsl_sf_lngamma(x);\n\t// With fn(x) = gamma(x+y, a)/Gamma(x)\n\tlong double fn_x;\n\t//INC_GAMMA_NO_UNDERFLOW(fn_x = expl((x+y)*logl(a) - a - logl(x+y) - ln_gamma_x)*gsl_sf_hyperg_1F1(1, x+y+1, a), hyperg_error_handler);\n\tINC_GAMMA_NO_UNDERFLOW(fn_x = gsl_sf_gamma_inc_P(x+y,a) * expl(gsl_sf_lngamma(x+y) - ln_gamma_x), gamma_inc_lower_error_handler);\n\tresult[idx] = fn_x;\n\t\n\tfor (;x>1;) {\n\t\tx -= 1;\n\t\tidx -= 1;\n\t\tln_gamma_x -= logl((long double) x);\n\t\tlong double fn_xp1 = fn_x;\n\t\t// We have gamma(s,a) = (gamma(s+1, a) + a^s exp(-a))/s\n\t\t// So gamma(x+y,a)/Gamma(x) = ( x gamma((x+1)+y, a)/Gamma(x+1) + a^(x+y) exp(-a)/Gamma(x) ) / s\n\t\t// -> fn(x) = ( x fn(x+1) + exp( (x+y) ln a - a - ln Gamma(x)! ) ) / (x+y)\n\t\tfn_x = ( x*fn_xp1 + expl( (x+y)*logl(a) - a - ln_gamma_x ) ) / (x+y);\n\t\tresult[idx] = (double)fn_x;\n\t}\n\t// Make use of the fact that NaNs and infinities will propagate to the last value computed.\n\tinc_gamma_check_value(result[0], \"lower incomplete gamma ratio\");\n}\n\n", "meta": {"hexsha": "0201c106289582ebecbc11a21186ae93c1a5850d", "size": 3788, "ext": "h", "lang": "C", "max_stars_repo_path": "NPTFit/incgamma_fct.h", "max_stars_repo_name": "bsafdi/NPTFit", "max_stars_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-01-17T20:00:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T03:31:47.000Z", "max_issues_repo_path": "NPTFit/incgamma_fct.h", "max_issues_repo_name": "bsafdi/NPTFit", "max_issues_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-06-22T02:59:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-22T02:59:33.000Z", "max_forks_repo_path": "NPTFit/incgamma_fct.h", "max_forks_repo_name": "bsafdi/NPTFit", "max_forks_repo_head_hexsha": "bb21439905d07e25fcf3351b321616f3ed2fcbd3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-11-23T05:06:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T01:25:15.000Z", "avg_line_length": 35.4018691589, "max_line_length": 136, "alphanum_fraction": 0.6602428722, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6256854746718}} {"text": "// @file im2col_conv.c\n//\n// \\date Created on: Sep 30, 2017\n// \\author Gopalakrishna Hegde\n//\n// Description:\n//\n//\n//\n\n#include \n#include \n#include \"common_types.h\"\n\n//From Berkeley Vision's Caffe\n//Refer to Caffe's license : https://github.com/BVLC/caffe/blob/master/LICENSE\nstatic inline bool is_a_ge_zero_and_a_lt_b(int a, int b) {\n return (unsigned int)a < (unsigned int)(b);\n}\n\nvoid Im2Col(const float *data_im, const int channels,\n const int height, const int width, const int kernel_h, const int kernel_w,\n const int pad_h, const int pad_w,\n const int stride_h, const int stride_w,\n float *data_col) {\n const int output_h = (height + 2 * pad_h -\n ((kernel_h - 1) + 1)) / stride_h + 1;\n const int output_w = (width + 2 * pad_w -\n ((kernel_w - 1) + 1)) / stride_w + 1;\n const int channel_size = height * width;\n for (int channel = channels; channel--; data_im += channel_size) {\n for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) {\n for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) {\n int input_row = -pad_h + kernel_row;\n for (int output_rows = output_h; output_rows; output_rows--) {\n if (!is_a_ge_zero_and_a_lt_b(input_row, height)) {\n for (int output_cols = output_w; output_cols; output_cols--) {\n *(data_col++) = 0;\n }\n } else {\n int input_col = -pad_w + kernel_col;\n for (int output_col = output_w; output_col; output_col--) {\n if (is_a_ge_zero_and_a_lt_b(input_col, width)) {\n *(data_col++) = data_im[input_row * width + input_col];\n } else {\n *(data_col++) = 0;\n }\n input_col += stride_w;\n }\n }\n input_row += stride_h;\n }\n }\n }\n }\n}\n\n\nvoid Im2ColConvLayer(const float *input, const float *weight,\n const float *bias, float *scratchpad, const TensorDim in_dim,\n const TensorDim out_dim, const int ker_size, const int group,\n const int pad, const int stride, const int bias_en, float *output) {\n\n int C = in_dim.c;\n int H = in_dim.h;\n int W = in_dim.w;\n int in_ch_per_group = C / group;\n int out_ch_per_group = out_dim.c / group;\n float alpha = 1;\n float beta = 0;\n\n for (int b = 0; b < in_dim.n; b++) {\n int in_offset = b * C * H * W;\n Im2Col(input + in_offset, C, H, W, ker_size, ker_size, pad, pad, stride,\n stride, scratchpad);\n for (int g = 0; g < group; g++) {\n int weight_offset = g * ker_size * ker_size * in_ch_per_group * out_ch_per_group;\n int data_offset = g * (ker_size * ker_size * in_ch_per_group) *\n (out_dim.h * out_dim.w);\n int out_offset = (b * out_dim.c + g * out_ch_per_group) *\n out_dim.h * out_dim.w;\n\n int m = out_ch_per_group;\n int k = in_ch_per_group * ker_size * ker_size;\n int n = out_dim.h * out_dim.w;\n cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n m, n, k, alpha, weight + weight_offset,\n k, scratchpad + data_offset, n, beta, output + out_offset, n);\n }\n }\n\n}\n", "meta": {"hexsha": "7793eec86c6383602fcdb18bead8ad5dc4a33446", "size": 3136, "ext": "c", "lang": "C", "max_stars_repo_path": "src/im2col_conv.c", "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_issues_repo_path": "src/im2col_conv.c", "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_forks_repo_path": "src/im2col_conv.c", "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "avg_line_length": 33.7204301075, "max_line_length": 87, "alphanum_fraction": 0.6010841837, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6256773283965267}} {"text": "//\n// gemv.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 12/12/11.\n// Copyright (c) 2011 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _gemv_h\n#define _gemv_h\n\n/// @file gemv.h Computes general matrix-vector products.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Computes general real matrix-vector products.\n ///\n /// For a real matrix A and real scalars alpha, beta\n ///\n /// y := alpha * op(A) * x + beta * y\n ///\n /// is computed, where op(A) = A or A'.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param trans Specifies whether the transpose of A is used or not:\n ///\n /// if trans = 'N' or 'n' then op(A) = A\n /// if trans = 'T' or 't' then op(A) = A'\n /// if trans = 'C' or 'c' then op(A) = A'\n ///\n /// @param m The number of rows of the matrix A. m>=0\n /// @param n The number of columns of the matrix A. n>=0\n /// @param alpha Real scalar.\n /// @param A Pointer to real matrix m-by-n matrix A. \n /// @param ldA Column length of the matrix A. ldA>=m.\n /// @param x Pointer to real vector x.\n /// @param incx Increment of the vector x. \n /// @param beta Real scalar.\n /// @param y Pointer to real vector y. \n /// @param incy Increment of the vector y.\n /// @ingroup BLAS\n\n template \n int GEMV(char trans, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *x, int_t incx, real_t beta, real_t *y, int_t incy)\n {\n trans=std::toupper(trans);\n const real_t one(1.0);\n const real_t zero(0.0);\n int_t kx,ky,lenx,leny,i,ix,iy,j,jx,jy;\n real_t temp;\n \n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA0)?0:(1-lenx)*incx;\n ky=(incy>0)?0:(1-leny)*incy;\n \n if(beta==zero)\n {\n if(incy==1)\n {\n for(i=0;i=0\n /// @param n The number of columns of the matrix A. n>=0\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex matrix m-by-n matrix A. \n /// @param ldA Column length of the matrix A. ldA>=m.\n /// @param x Pointer to complex vector x.\n /// @param incx Increment of the vector x. \n /// @param beta Complex scalar.\n /// @param y Pointer to complex vector y. \n /// @param incy Increment of the vector y.\n /// @ingroup BLAS\n\n template \n int GEMV(char trans, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *x, int_t incx, complex beta, complex *y, int_t incy)\n {\n trans=std::toupper(trans);\n using std::conj;\n const complex one(1.0,0.0);\n const complex zero(0.0,0.0);\n int_t kx,ky,lenx,leny,i,ix,iy,j,jx,jy;\n complex temp;\n \n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA0)?0:(1-lenx)*incx;\n ky=(incy>0)?0:(1-leny)*incy;\n \n if(beta==zero)\n {\n if(incy==1)\n {\n for(i=0;i\n\n template <> int GEMV(char trans, int_t m, int_t n, float alpha, float *A, int_t ldA, float *x, int_t incx, float beta, float *y, int_t incy)\n {\n trans=std::toupper(trans);\n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA int GEMV(char trans, int_t m, int_t n, double alpha, double *A, int_t ldA, double *x, int_t incx, double beta, double *y, int_t incy)\n {\n trans=std::toupper(trans);\n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA int GEMV(char trans, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *x, int_t incx, complex beta, complex *y, int_t incy)\n {\n trans=std::toupper(trans);\n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA int GEMV(char trans, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *x, int_t incx, complex beta, complex *y, int_t incy)\n {\n trans=std::toupper(trans);\n if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -1;\n else if(m<0)\n return -2;\n else if(n<0)\n return -3;\n else if(ldA\n#include \n#include \n#include //GSL error management module\n#include //GSL interpolation module\n\n#define A 10.0 //Distance parameter of the perturbations\n#define G 43007.01 //Gravitational constant\n#define M 0.0 //Mass of the perturbation\n#define C 299792.458 //Speed of light\n#define NLINES 100000 //Number of lines in geodesic_solution.dat file\n#define NSTEPS 40000000 //Number of steps for solving geodesics\n#define NLINESFRW 10000 //Number of lines in frw.dat file\n#define DLAMBDA 0.01 //Geodesics parameter step\n\ntypedef long double mydbl;\n\n/*Interpolation of function inside *spline object evaluated at an abscisa 'x'.\nArgument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/\ndouble interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc)\n{\n double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc\n\n return a; //Return value of interpolated function at x\n}\n\n/*Function for the gravitational potential to be used. Potential for Plummer model.*/\nmydbl potential(mydbl r)\n{\n return -G*M/(sqrtl(A*A + r*r));\n}\n\n/*Derivative of potential respecto to radial coordinate.*/\nmydbl der_potential(mydbl r)\n{\n return G*M*r/(powl(A*A+r*r, 1.5));\n}\n\n/*Function of the 0th momentum component differential equation for the geodesics.\n${p0}^{dot} = f0(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = -(2.0/(C*C))*der_potential(r)*p0*pr/(1.0 + 2.0*potential(r)/(C*C)) - (1.0 - 2.0*potential(r)/(C*C))*((a*adot)/C)*(pr*pr + r*r*(powl(sinl(theta),2.0)*pphi*pphi + ptheta*ptheta))/(1.0 + 2.0*potential(r)/(C*C));\n return f;\n}\n\n/*Function of the 1th (radial) momentum component differential equation for the geodesics.\n${p1}^{dot} = f1(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = - (der_potential(r)*p0*p0)/(a*a*C*C*(1.0 - 2.0*potential(r)/(C*C))) - (2.0*adot*p0*pr)/(C*a) + r*(ptheta*ptheta + sinl(theta)*sinl(theta)*pphi*pphi) - (der_potential(r)/(C*C))*(powl(r,2.0)*(powl(ptheta,2.0) + powl(sinl(theta)*pphi,2.0)) - pr*pr)/(1.0 - 2.0*potential(r)/(C*C));\n return f;\n}\n\n/*Function of the 2th (polar) momentum component differential equation for the geodesics.\n${p2}^{dot} = f2(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_theta(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = 0.5*sinl(2.0*theta)*pphi*pphi + 2.0*((der_potential(r)/powl(C,2.0))/(1.0 - 2.0*potential(r)/(C*C)) - 1.0/r)*pr*ptheta - (2.0*adot*p0*ptheta)/(C*a);\n return f;\n}\n\n/*Function of the 3th (azimuthal) momentum component differential equation for the geodesics.\n${p3}^{dot} = f3(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_phi(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, mydbl x0, mydbl r, mydbl theta)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = 2.0*( (der_potential(r)/powl(C,2.0))/(1.0 - 2.0*potential(r)/(C*C)) - 1.0/r)*pr*pphi - 2.0*(1.0/tanl(theta))*ptheta*pphi - (2.0*adot*p0*pphi)/(a*C);\n return f;\n}\n\n/*Function for solving the geodesics differential equations using 4th order Runge-Kutta method.\nArguments are pointer so variables in that memory addresses are changed every time this function is called.*/\nvoid runge_kutta_4(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *x2, mydbl *x3, mydbl *p0, mydbl *p1, mydbl *p2, mydbl *p3, mydbl *lambda)\n{\n /*Increment in the variables of the differential equation we want to solve*/\n mydbl dx0, dx1, dx2, dx3, dp0, dp1, dp2, dp3;\n\n /*dxi = (k1,j + 2*k2,j + 2*k3,j + k4,j)/6. In this sections the ki,j are declared with i=1,2,3,4.*/\n mydbl k1x0, k1x1, k1x2, k1x3, k1p0, k1p1, k1p2, k1p3;\n mydbl k2x0, k2x1, k2x2, k2x3, k2p0, k2p1, k2p2, k2p3;\n mydbl k3x0, k3x1, k3x2, k3x3, k3p0, k3p1, k3p2, k3p3;\n mydbl k4x0, k4x1, k4x2, k4x3, k4p0, k4p1, k4p2, k4p3;\n\n /*This section calculates the k1 quantities*/\n k1x0 = *p0*DLAMBDA; k1x1 = *p1*DLAMBDA; k1x2 = *p2*DLAMBDA; k3x0 = *p3*DLAMBDA;\n k1p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2);\n k1p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2);\n k1p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2);\n k1p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0, *p1, *p2, *p3, *x0, *x1, *x2);\n\n /*This section calculates the k2 quantities*/\n k2x0 = DLAMBDA*(*p0 + 0.5*k1p0); k2x1 = DLAMBDA*(*p1 + 0.5*k1p1); k2x2 = DLAMBDA*(*p2 + 0.5*k1p2); k2x3 = DLAMBDA*(*p3 + 0.5*k1p3);\n k2p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2);\n k2p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2);\n k2p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2);\n k2p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + 0.5*k1p0, *p1 + 0.5*k1p1, *p2 + 0.5*k1p2, *p3 + 0.5*k1p3, *x0 + 0.5*k1x0, *x1 + 0.5*k1x1, *x2 + 0.5*k1x2);\n\n /*This section calculates the k3 quantities*/\n k3x0 = DLAMBDA*(*p0 + 0.5*k2p0); k3x1 = DLAMBDA*(*p1 + 0.5*k2p1); k3x2 = DLAMBDA*(*p2 + 0.5*k2p2); k3x3 = DLAMBDA*(*p3 + 0.5*k2p3);\n k3p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2);\n k3p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2);\n k3p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2);\n k3p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + 0.5*k2p0, *p1 + 0.5*k2p1, *p2 + 0.5*k2p2, *p3 + 0.5*k2p3, *x0 + 0.5*k2x0, *x1 + 0.5*k2x1, *x2 + 0.5*k2x2);\n\n /*This section calculates the k4 quantities*/\n k4x0 = DLAMBDA*(*p0 + k3p0); k4x1 = DLAMBDA*(*p1 + k3p1); k4x2 = DLAMBDA*(*p2 + k3p2); k4x3 = DLAMBDA*(*p3 + k3p3);\n k4p0 = DLAMBDA*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2);\n k4p1 = DLAMBDA*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2);\n k4p2 = DLAMBDA*geodesic_equation_theta(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2);\n k4p3 = DLAMBDA*geodesic_equation_phi(spline1, acc1, spline2, acc2, *p0 + k3p0, *p1 + k3p1, *p2 + k3p2, *p3 + k3p3, *x0 + k3x0, *x1 + k3x1, *x2 + k3x2);\n\n /*Calculation of the increments*/\n dx0 = (k1x0 + 2.0*k2x0 + 2.0*k3x0 + k4x0)/6.0;\n dx1 = (k1x1 + 2.0*k2x1 + 2.0*k3x1 + k4x1)/6.0;\n dx2 = (k1x2 + 2.0*k2x2 + 2.0*k3x2 + k4x2)/6.0;\n dx3 = (k1x3 + 2.0*k2x3 + 2.0*k3x3 + k4x3)/6.0;\n dp0 = (k1p0 + 2.0*k2p0 + 2.0*k3p0 + k4p0)/6.0;\n dp1 = (k1p1 + 2.0*k2p1 + 2.0*k3p1 + k4p1)/6.0;\n dp2 = (k1p2 + 2.0*k2p2 + 2.0*k3p2 + k4p2)/6.0;\n dp3 = (k1p3 + 2.0*k2p3 + 2.0*k3p3 + k4p3)/6.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\n/*To set the initial value of pr, it must hold $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.\nThis factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/\nmydbl condition_factor(mydbl r, double a)\n{\n return (mydbl)(1.0/a)*sqrtl((1.0+2.0*potential(r)/(C*C))/(1.0 - 2.0*potential(r)/(C*C)));\n}\n\n/*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/\nmydbl energy_factor(mydbl r)\n{\n mydbl g = sqrtl(1.0 + 2.0*potential(r)/(C*C));\n return g;\n}\n\n/*Violation of null geodesics condition $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.*/\nmydbl violation(mydbl r, mydbl theta, mydbl p0, mydbl pr, mydbl ptheta, mydbl pphi, double a)\n{\n mydbl f = -(1.0+2.0*potential(r)/(C*C))*p0*p0 + a*a*(1.0-2.0*potential(r)/(C*C))*(pr*pr + r*r*(powl(sinl(theta),2.0)*pphi*pphi + ptheta*ptheta));\n return f;\n}\n\nint main(void)\n{\n /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/\n int i; //For array manipulation\n \n /*Pointer to scale_factor.dat file*/\n FILE *frw; \n frw = fopen(\"scale_factor.dat\",\"r\");\n\n /*Variables and arrays to read the data*/\n double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW];\n\n /*Reading the data*/\n for(i=0; i\n#include \n#include \n#include \n\n/* The logistic distribution has the form,\n\n p(x) dx = (1/a) exp(-x/a) / (1 + exp(-x/a))^2 dx\n\n for -infty < x < infty */\n\ndouble\ngsl_ran_logistic (const gsl_rng * r, const double a)\n{\n double x, z;\n\n do\n {\n x = gsl_rng_uniform_pos (r);\n }\n while (x == 1);\n\n z = log (x / (1 - x));\n\n return a * z;\n}\n\ndouble\ngsl_ran_logistic_pdf (const double x, const double a)\n{\n double u = exp (-fabs(x)/a);\n double p = u / (fabs(a) * (1 + u) * (1 + u));\n return p;\n}\n", "meta": {"hexsha": "c1e05d4f8197d6cb451f417a77a24e5743e83242", "size": 1404, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/logistic.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/logistic.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/logistic.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.0, "max_line_length": 81, "alphanum_fraction": 0.6680911681, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.625160189509568}} {"text": "/* specfunc/gsl_sf_expint.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_EXPINT_H__\n#define __GSL_SF_EXPINT_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/* E_1(x) := Re[ Integrate[ Exp[-xt]/t, {t,1,Infinity}] ]\n *\n * x != 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_expint_E1_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_expint_E1(const double x);\n\n\n/* E_2(x) := Re[ Integrate[ Exp[-xt]/t^2, {t,1,Infinity}] ]\n *\n * x != 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_expint_E2_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_expint_E2(const double x);\n\n\n/* Ei(x) := PV Integrate[ Exp[-t]/t, {t,-x,Infinity}]\n *\n * x != 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_expint_Ei_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_expint_Ei(const double x);\n\n\n/* Shi(x) := Integrate[ Sinh[t]/t, {t,0,x}]\n *\n * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_Shi_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_Shi(const double x);\n\n\n/* Chi(x) := Re[ M_EULER + log(x) + Integrate[(Cosh[t]-1)/t, {t,0,x}] ]\n *\n * x != 0.0\n * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW\n */\nint gsl_sf_Chi_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_Chi(const double x);\n\n\n/* Ei_3(x) := Integral[ Exp[-t^3], {t,0,x}]\n *\n * x >= 0.0\n * exceptions: GSL_EDOM\n */\nint gsl_sf_expint_3_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_expint_3(double x);\n\n\n/* Si(x) := Integrate[ Sin[t]/t, {t,0,x}]\n *\n * exceptions: none\n */\nint gsl_sf_Si_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_Si(const double x);\n\n\n/* Ci(x) := -Integrate[ Cos[t]/t, {t,x,Infinity}]\n *\n * x > 0.0\n * exceptions: GSL_EDOM \n */\nint gsl_sf_Ci_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_Ci(const double x);\n\n\n/* AtanInt(x) := Integral[ Arctan[t]/t, {t,0,x}]\n *\n *\n * exceptions:\n */\nint gsl_sf_atanint_e(const double x, gsl_sf_result * result);\ndouble gsl_sf_atanint(const double x);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_EXPINT_H__ */\n", "meta": {"hexsha": "055c6f5e6688059c363e0ccce9faa3c4cc786819", "size": 3080, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_expint.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_expint.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_expint.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": 25.2459016393, "max_line_length": 72, "alphanum_fraction": 0.6837662338, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6246295278790287}} {"text": "/* specfunc/gsl_sf_ellint.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_ELLINT_H__\n#define __GSL_SF_ELLINT_H__\n\n#include \n#include \n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n\n/* Legendre form of complete elliptic integrals\n *\n * K(k) = Integral[1/Sqrt[1 - k^2 Sin[t]^2], {t, 0, Pi/2}]\n * E(k) = Integral[ Sqrt[1 - k^2 Sin[t]^2], {t, 0, Pi/2}]\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_ellint_Kcomp_e(double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_Kcomp(double k, gsl_mode_t mode);\n\nint gsl_sf_ellint_Ecomp_e(double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_Ecomp(double k, gsl_mode_t mode);\n\nint gsl_sf_ellint_Pcomp_e(double k, double n, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_Pcomp(double k, double n, gsl_mode_t mode);\n\nint gsl_sf_ellint_Dcomp_e(double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_Dcomp(double k, gsl_mode_t mode);\n\n\n/* Legendre form of incomplete elliptic integrals\n *\n * F(phi,k) = Integral[1/Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}]\n * E(phi,k) = Integral[ Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}]\n * P(phi,k,n) = Integral[(1 + n Sin[t]^2)^(-1)/Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}]\n * D(phi,k,n) = R_D(1-Sin[phi]^2, 1-k^2 Sin[phi]^2, 1.0)\n *\n * F: [Carlson, Numerische Mathematik 33 (1979) 1, (4.1)]\n * E: [Carlson, \", (4.2)]\n * P: [Carlson, \", (4.3)]\n * D: [Carlson, \", (4.4)]\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_ellint_F_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_F(double phi, double k, gsl_mode_t mode);\n\nint gsl_sf_ellint_E_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_E(double phi, double k, gsl_mode_t mode);\n\nint gsl_sf_ellint_P_e(double phi, double k, double n, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_P(double phi, double k, double n, gsl_mode_t mode);\n\nint gsl_sf_ellint_D_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_D(double phi, double k, gsl_mode_t mode);\n\n\n/* Carlson's symmetric basis of functions\n *\n * RC(x,y) = 1/2 Integral[(t+x)^(-1/2) (t+y)^(-1)], {t,0,Inf}]\n * RD(x,y,z) = 3/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-3/2), {t,0,Inf}]\n * RF(x,y,z) = 1/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-1/2), {t,0,Inf}]\n * RJ(x,y,z,p) = 3/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-1/2) (t+p)^(-1), {t,0,Inf}]\n *\n * exceptions: GSL_EDOM\n */\nint gsl_sf_ellint_RC_e(double x, double y, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_RC(double x, double y, gsl_mode_t mode);\n\nint gsl_sf_ellint_RD_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_RD(double x, double y, double z, gsl_mode_t mode);\n\nint gsl_sf_ellint_RF_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_RF(double x, double y, double z, gsl_mode_t mode);\n\nint gsl_sf_ellint_RJ_e(double x, double y, double z, double p, gsl_mode_t mode, gsl_sf_result * result);\ndouble gsl_sf_ellint_RJ(double x, double y, double z, double p, gsl_mode_t mode);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_ELLINT_H__ */\n", "meta": {"hexsha": "7f68f0e2989f3e802903d59a6dc10b7764c771fb", "size": 4159, "ext": "h", "lang": "C", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_sf_ellint.h", "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_ellint.h", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/gsl_sf_ellint.h", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "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": 36.8053097345, "max_line_length": 104, "alphanum_fraction": 0.7047367156, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6243797758780054}} {"text": "/*\n LAPACKE Example : Calling DGELS using col-major layout\n =====================================================\n\n The program computes the solution to the system of linear\n equations with a square matrix A and multiple\n right-hand sides B, where A is the coefficient matrix\n and b is the right-hand side matrix:\n\n Description\n ===========\n\n In this example, we wish solve the least squares problem min_x || B - Ax ||\n for two right-hand sides using the LAPACK routine DGELS. For input we will\n use the 5-by-3 matrix\n\n ( 1 1 1 )\n ( 2 3 4 )\n A = ( 3 5 2 )\n ( 4 2 5 )\n ( 5 4 3 )\n and the 5-by-2 matrix\n\n ( -10 -3 )\n ( 12 14 )\n B = ( 14 12 )\n ( 16 16 )\n ( 18 16 )\n We will first store the input matrix as a static C two-dimensional array,\n which is stored in col-major layout, and let LAPACKE handle the work space\n array allocation. The LAPACK base name for this function is gels, and we\n will use double precision (d), so the LAPACKE function name is LAPACKE_dgels.\n\n lda=5 and ldb=5. The output for each right hand side is stored in b as\n consecutive vectors of length 3. The correct answer for this problem is\n the 3-by-2 matrix\n\n ( 2 1 )\n ( 1 1 )\n ( 1 2 )\n\n A complete C program for this example is given below. Note that when the arrays\n are passed to the LAPACK routine, they must be dereferenced, since LAPACK is\n expecting arrays of type double *, not double **.\n\n\n LAPACKE Interface\n =================\n\n LAPACKE_dgels (col-major, high-level) Example Program Results\n\n -- LAPACKE Example routine (version 3.7.0) --\n -- LAPACK is a software package provided by Univ. of Tennessee, --\n -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--\n December 2016\n\n*/\n/* Calling DGELS using col-major layout */\n\n/* Includes */\n#include \n#include \n\n int main() {\n double A[5][3] = {{1,2,3},{4,5,1},{3,5,2},{4,1,4},{2,5,3}};\n double b[5][2] = {{-10,12},{14,16},{18,-3},{14,12},{16,16}};\n\n const lapack_int m = 5;\n const lapack_int n = 3;\n const lapack_int lda = 5;\n const lapack_int ldb = 5;\n const lapack_int nrhs = 2;\n\n printf(\"LAPACKE_dgels (col-major, high-level) Example Program Results\\n\" );\n const lapack_int info = LAPACKE_dgels(LAPACK_COL_MAJOR,'N',m, n, nrhs, *A, lda, *b, ldb);\n printf( \"Solution: %d %d %lf %d\\n\", n, nrhs, b[0][0], ldb);\n\n return info;\n}", "meta": {"hexsha": "2c1196f3630495d8bd91ae685cccdb238b50c3d7", "size": 2506, "ext": "c", "lang": "C", "max_stars_repo_path": "test_package/test_package.c", "max_stars_repo_name": "nabbelbabbel/conan-lapack", "max_stars_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T19:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-03T19:29:57.000Z", "max_issues_repo_path": "test_package/test_package.c", "max_issues_repo_name": "nabbelbabbel/conan-lapack", "max_issues_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-06-26T13:22:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-08T17:19:50.000Z", "max_forks_repo_path": "test_package/test_package.c", "max_forks_repo_name": "nabbelbabbel/conan-lapack", "max_forks_repo_head_hexsha": "f6aeafd21b36f33599dae82605189817f8716219", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-06-25T20:49:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T20:52:07.000Z", "avg_line_length": 31.7215189873, "max_line_length": 92, "alphanum_fraction": 0.6061452514, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6243340544015498}} {"text": "// xll_roots.h - GSL 1-dim root finding\n// http://www.gnu.org/software/gsl/manual/html_node/One-dimensional-Root_002dFinding.html#One-dimensional-Root_002dFinding\n#pragma once\n#include \n#include \n#include \n#include \n#include \"gsl/gsl_errno.h\"\n#include \"gsl/gsl_roots.h\"\n#include \"xll_math.h\"\n\nnamespace gsl {\n\nnamespace root {\n\n\t// root bracketing solvers\n\tclass fsolver {\n\t\tgsl_root_fsolver* s;\n\t\tgsl::function f;\n\tpublic:\n\t\texplicit fsolver(const gsl_root_fsolver_type * type)\n\t\t\t: s{gsl_root_fsolver_alloc(type)}\n\t\t{ }\n\t\tfsolver(const fsolver&) = delete;\n\t\tfsolver& operator=(const fsolver&) = delete;\n\t\t~fsolver()\n\t\t{\n\t\t\tgsl_root_fsolver_free(s);\n\t\t}\n\n\t\t// needed for gsl_root_fsolver_* routines\n\t\tgsl_root_fsolver* get() const\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t\t// syntactic sugar\n\t\toperator gsl_root_fsolver*() const\n\t\t{\n\t\t\treturn get();\n\t\t}\n\n\t\tint set(const std::function& f_, double lo, double hi)\n\t\t{\n\t\t\tf = f_;\n\n\t\t\treturn gsl_root_fsolver_set(s, &f, lo, hi);\n\t\t}\n\n\t\t// forward to gsl_root_fsolver_* functions\n\t\tint iterate()\n\t\t{\n\t\t\treturn gsl_root_fsolver_iterate(s);\n\t\t}\n\t\tdouble x_lower() const\n\t\t{\n\t\t\treturn gsl_root_fsolver_x_lower(s);\n\t\t}\n\t\tdouble x_upper() const\n\t\t{\n\t\t\treturn gsl_root_fsolver_x_upper(s);\n\t\t}\n\t\tdouble root() const\n\t\t{\n\t\t\treturn gsl_root_fsolver_root(s);\n\t\t}\n\n\t\t// specify convergence condition\n\t\tdouble solve(const std::function& done)\n\t\t{\n\t\t\twhile (GSL_SUCCESS == iterate()) {\n\t\t\t\tif (done(*this))\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn root();\n\t\t}\n\t};\n\n\t// convergence helper functions\n\tinline auto test_interval(double epsabs, double epsrel)\n\t{\n\t\treturn [epsabs,epsrel](const fsolver& s) {\n\t\t\treturn GSL_SUCCESS == gsl_root_test_interval(s.x_lower(), s.x_upper(), epsabs, epsrel);\n\t\t};\n\t}\n\n\t// root finding using derivatives\n\tclass fdfsolver {\n\t\tgsl_root_fdfsolver* s;\n\n\t\t// function and its derivative\n\t\tgsl::function_fdf FdF;\n\tpublic:\n\t\tfdfsolver(const gsl_root_fdfsolver_type * type)\n\t\t\t: s{gsl_root_fdfsolver_alloc(type)}\n\t\t{ }\n\t\tfdfsolver(const fdfsolver&) = delete;\n\t\tfdfsolver& operator=(const fdfsolver&) = delete;\n\t\t~fdfsolver()\n\t\t{\n\t\t\tgsl_root_fdfsolver_free(s);\n\t\t}\n\t\t// needed for gsl_root_fdfsolver_* routines\n\t\tgsl_root_fdfsolver* get() const\n\t\t{\n\t\t\treturn s;\n\t\t}\n\t\t// syntactic sugar\n\t\toperator gsl_root_fdfsolver*() const\n\t\t{\n\t\t\treturn s;\n\t\t}\n\n\t\tint set(const std::function& f, const std::function& df, double x0)\n\t\t{\n\t\t\tFdF = gsl::function_fdf(f, df);\n\n\t\t\treturn gsl_root_fdfsolver_set(s, &FdF, x0);\n\t\t}\n\n\t\t// forward to gsl_root_fdfsolver_* functions\n\t\tint iterate()\n\t\t{\n\t\t\treturn gsl_root_fdfsolver_iterate(s);\n\t\t}\n\t\tdouble root() const\n\t\t{\n\t\t\treturn gsl_root_fdfsolver_root(s);\n\t\t}\n\n\t\t// specify convergence condition given previous root\n\t\tdouble solve(const std::function& done)\n\t\t{\n\t\t\tdouble x = root();\n\t\t\twhile (GSL_SUCCESS == iterate()) {\n\t\t\t\tif (done(*this, x))\n\t\t\t\t\tbreak;\n\t\t\t\tx = root();\n\t\t\t}\n\n\t\t\treturn root();\n\t\t}\n\t};\n\n\t// convergence helper functions\n\tinline auto test_delta(double epsabs, double epsrel)\n\t{\n\t\treturn [epsabs,epsrel](const fdfsolver& s, double x) -> bool {\n\t\t\treturn GSL_SUCCESS == gsl_root_test_delta(x, s.root(), epsabs, epsrel);\n\t\t};\n\t}\n\n\t} // root\n} // gsl\n\n#ifdef _DEBUG\n#include \n#include \n//#include \n\n// http://www.gnu.org/software/gsl/manual/html_node/Root-Finding-Examples.html#Root-Finding-Examples\n\n// a x^2 + b x + c\nstruct quadratic_params {\n\tdouble a, b, c;\n};\n\n// This is bad. Why???\ninline double quadratic(double x, void *params)\n{\n\tstruct quadratic_params *p \n\t\t= (struct quadratic_params *) params;\n\n\tdouble a = p->a;\n\tdouble b = p->b;\n\tdouble c = p->c;\n\n\treturn (a * x + b) * x + c;\n}\n\ninline double quadratic_deriv(double x, void *params)\n{\n\tstruct quadratic_params *p \n\t\t= (struct quadratic_params *) params;\n\n\tdouble a = p->a;\n\tdouble b = p->b;\n//\tdouble c = p->c;\n\n\treturn 2.0 * a * x + b;\n}\n\ninline void quadratic_fdf(double x, void *params, double *y, double *dy)\n{\n\tstruct quadratic_params *p \n\t\t= (struct quadratic_params *) params;\n\n\tdouble a = p->a;\n\tdouble b = p->b;\n\tdouble c = p->c;\n\n\t*y = (a * x + b) * x + c;\n\t*dy = 2.0 * a * x + b;\n}\n\ninline void test_gsl_root_fsolver()\n{\n\t// GSL example\n\t{\n\t\tgsl_root_fsolver* s = gsl_root_fsolver_alloc(gsl_root_fsolver_brent);\n\t\t\n\t\tquadratic_params params{1.,0.,-5.}; // x^2 - 5\n\t\tgsl_function F;\n\t\tF.function = quadratic;\n\t\tF.params = ¶ms;\n\t\tdouble x_lo = 0.0, x_hi = 5.0;\n\t\tdouble epsabs = 0, epsrel = 1e-5;\n\n\t\tgsl_root_fsolver_set(s, &F, x_lo, x_hi);\n\t\twhile (GSL_SUCCESS == gsl_root_fsolver_iterate(s)) {\n\t\t\tx_lo = gsl_root_fsolver_x_lower(s);\n\t\t\tx_hi = gsl_root_fsolver_x_upper(s);\n\n\t\t\t// |x_lo - x_hi| < epsabs + epsrel * min(|x_lo|, |x_hi|)\n\t\t\tif (GSL_SUCCESS == gsl_root_test_interval(x_lo, x_hi, epsabs, epsrel))\n\t\t\t\tbreak;\n\t\t}\n\t\tdouble root = gsl_root_fsolver_root(s);\n\t\tdouble sqrt5 = sqrt(5.);\n\t\tassert (fabs(root - sqrt5) < sqrt5*epsrel);\n\n\t\tgsl_root_fsolver_free(s);\n\t}\n\t// root_fsolver class with function\n\t{\n\t\tgsl::root::fsolver s(gsl_root_fsolver_brent);\n\n\t\tstd::vector params{-5,0,1}; // -5 + x^2\n\t\tauto F = [params](double x) { return params[0] + x*(params[1] + x*params[2]); };\n\t\tgsl::function F_(F);\n\t\tassert (F_(0) == -5);\n\t\tassert (F_.call(0) == -5);\n\t\tdouble x_lo = 0.0, x_hi = 5.0, epsrel = 1e-6;\n\t\ts.set(F, x_lo, x_hi);\n\t\t\n\t\tdouble root = s.solve(gsl::root::test_interval(0, epsrel));\n\t\tdouble sqrt5 = sqrt(5.);\n\t\tassert (fabs(root - sqrt5) < sqrt5*epsrel);\n\t}\n}\ninline void test_gsl_root_fdfsolver()\n{\n\t// root_fdfsolver class with function(double)>\n\t{\n\t\tgsl::root::fdfsolver s(gsl_root_fdfsolver_newton);\n\n\t\t// F(x) = x^2 - 5\n\t\tauto F = [](double x) {\n\t\t\treturn x*x - 5;\n\t\t};\n\t\tauto dF = [](double x) { \n\t\t\treturn 2*x;\n\t\t};\n\t\tdouble x = 5.0, epsrel = 1e-6;\n\t\ts.set(F, dF, x);\n\n\t\tdouble root = s.solve(gsl::root::test_delta(0, epsrel));\n\t\tdouble sqrt5 = sqrt(5.);\n\t\tassert (fabs(root - sqrt5) < sqrt5*epsrel);\n\t}\n}\n\n#endif // _DEBUG", "meta": {"hexsha": "19af3f0810fb1f5c32eb14d6084d9249eb0cf104", "size": 6015, "ext": "h", "lang": "C", "max_stars_repo_path": "test/xll_roots.h", "max_stars_repo_name": "keithalewis/fms16", "max_stars_repo_head_hexsha": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45", "max_stars_repo_licenses": ["MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/xll_roots.h", "max_issues_repo_name": "keithalewis/fms16", "max_issues_repo_head_hexsha": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45", "max_issues_repo_licenses": ["MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/xll_roots.h", "max_forks_repo_name": "keithalewis/fms16", "max_forks_repo_head_hexsha": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45", "max_forks_repo_licenses": ["MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.032967033, "max_line_length": 122, "alphanum_fraction": 0.6576891106, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6242327909870773}} {"text": "/* specfunc/coulomb.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/* Evaluation of Coulomb wave functions F_L(eta, x), G_L(eta, x),\n * and their derivatives. A combination of Steed's method, asymptotic\n * results, and power series.\n *\n * Steed's method:\n * [Barnett, CPC 21, 297 (1981)]\n * Power series and other methods:\n * [Biedenharn et al., PR 97, 542 (1954)]\n * [Bardin et al., CPC 3, 73 (1972)]\n * [Abad+Sesma, CPC 71, 110 (1992)]\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"error.h\"\n\n/* the L=0 normalization constant\n * [Abramowitz+Stegun 14.1.8]\n */\nstatic\ndouble\nC0sq(double eta)\n{\n double twopieta = 2.0*M_PI*eta;\n\n if(fabs(eta) < GSL_DBL_EPSILON) {\n return 1.0;\n }\n else if(twopieta > GSL_LOG_DBL_MAX) {\n return 0.0;\n }\n else {\n gsl_sf_result scale;\n gsl_sf_expm1_e(twopieta, &scale);\n return twopieta/scale.val;\n }\n}\n\n\n/* the full definition of C_L(eta) for any valid L and eta\n * [Abramowitz and Stegun 14.1.7]\n * This depends on the complex gamma function. For large\n * arguments the phase of the complex gamma function is not\n * very accurately determined. However the modulus is, and that\n * is all that we need to calculate C_L.\n *\n * This is not valid for L <= -3/2 or L = -1.\n */\nstatic\nint\nCLeta(double L, double eta, gsl_sf_result * result)\n{\n gsl_sf_result ln1; /* log of numerator Gamma function */\n gsl_sf_result ln2; /* log of denominator Gamma function */\n double sgn = 1.0;\n double arg_val, arg_err;\n\n if(fabs(eta/(L+1.0)) < GSL_DBL_EPSILON) {\n gsl_sf_lngamma_e(L+1.0, &ln1);\n }\n else {\n gsl_sf_result p1; /* phase of numerator Gamma -- not used */\n gsl_sf_lngamma_complex_e(L+1.0, eta, &ln1, &p1); /* should be ok */\n }\n\n gsl_sf_lngamma_e(2.0*(L+1.0), &ln2);\n if(L < -1.0) sgn = -sgn;\n\n arg_val = L*M_LN2 - 0.5*eta*M_PI + ln1.val - ln2.val;\n arg_err = ln1.err + ln2.err;\n arg_err += GSL_DBL_EPSILON * (fabs(L*M_LN2) + fabs(0.5*eta*M_PI));\n return gsl_sf_exp_err_e(arg_val, arg_err, result);\n}\n\n\nint\ngsl_sf_coulomb_CL_e(double lam, double eta, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(lam <= -1.0) {\n DOMAIN_ERROR(result);\n }\n else if(fabs(lam) < GSL_DBL_EPSILON) {\n /* saves a calculation of complex_lngamma(), otherwise not necessary */\n result->val = sqrt(C0sq(eta));\n result->err = 2.0 * GSL_DBL_EPSILON * result->val;\n return GSL_SUCCESS;\n }\n else {\n return CLeta(lam, eta, result);\n }\n}\n\n\n/* cl[0] .. cl[kmax] = C_{lam_min}(eta) .. C_{lam_min+kmax}(eta)\n */\nint\ngsl_sf_coulomb_CL_array(double lam_min, int kmax, double eta, double * cl)\n{\n int k;\n gsl_sf_result cl_0;\n gsl_sf_coulomb_CL_e(lam_min, eta, &cl_0);\n cl[0] = cl_0.val;\n\n for(k=1; k<=kmax; k++) {\n double L = lam_min + k;\n cl[k] = cl[k-1] * hypot(L, eta)/(L*(2.0*L+1.0));\n }\n\n return GSL_SUCCESS;\n}\n\n\n/* Evaluate the series for Phi_L(eta,x) and Phi_L*(eta,x)\n * [Abramowitz+Stegun 14.1.5]\n * [Abramowitz+Stegun 14.1.13]\n *\n * The sequence of coefficients A_k^L is\n * manifestly well-controlled for L >= -1/2\n * and eta < 10.\n *\n * This makes sense since this is the region\n * away from threshold, and you expect\n * the evaluation to become easier as you\n * get farther from threshold.\n *\n * Empirically, this is quite well-behaved for\n * L >= -1/2\n * eta < 10\n * x < 10\n */\n#if 0\nstatic\nint\ncoulomb_Phi_series(const double lam, const double eta, const double x,\n double * result, double * result_star)\n{\n int kmin = 5;\n int kmax = 200;\n int k;\n double Akm2 = 1.0;\n double Akm1 = eta/(lam+1.0);\n double Ak;\n\n double xpow = x;\n double sum = Akm2 + Akm1*x;\n double sump = (lam+1.0)*Akm2 + (lam+2.0)*Akm1*x;\n double prev_abs_del = fabs(Akm1*x);\n double prev_abs_del_p = (lam+2.0) * prev_abs_del;\n\n for(k=2; k kmin\n ) break;\n\n /* We need to keep track of the previous delta because when\n * eta is near zero the odd terms of the sum are very small\n * and this could lead to premature termination.\n */\n prev_abs_del = abs_del;\n prev_abs_del_p = abs_del_p;\n\n Akm2 = Akm1;\n Akm1 = Ak;\n }\n\n *result = sum;\n *result_star = sump;\n\n if(k==kmax) {\n GSL_ERROR (\"error\", GSL_EMAXITER);\n }\n else {\n return GSL_SUCCESS;\n }\n}\n#endif /* 0 */\n\n\n/* Determine the connection phase, phi_lambda.\n * See coulomb_FG_series() below. We have\n * to be careful about sin(phi)->0. Note that\n * there is an underflow condition for large \n * positive eta in any case.\n */\nstatic\nint\ncoulomb_connection(const double lam, const double eta,\n double * cos_phi, double * sin_phi)\n{\n if(eta > -GSL_LOG_DBL_MIN/2.0*M_PI-1.0) {\n *cos_phi = 1.0;\n *sin_phi = 0.0;\n GSL_ERROR (\"error\", GSL_EUNDRFLW);\n }\n else if(eta > -GSL_LOG_DBL_EPSILON/(4.0*M_PI)) {\n const double eps = 2.0 * exp(-2.0*M_PI*eta);\n const double tpl = tan(M_PI * lam);\n const double dth = eps * tpl / (tpl*tpl + 1.0);\n *cos_phi = -1.0 + 0.5 * dth*dth;\n *sin_phi = -dth;\n return GSL_SUCCESS;\n }\n else {\n double X = tanh(M_PI * eta) / tan(M_PI * lam);\n double phi = -atan(X) - (lam + 0.5) * M_PI;\n *cos_phi = cos(phi);\n *sin_phi = sin(phi);\n return GSL_SUCCESS;\n }\n}\n\n\n/* Evaluate the Frobenius series for F_lam(eta,x) and G_lam(eta,x).\n * Homegrown algebra. Evaluates the series for F_{lam} and\n * F_{-lam-1}, then uses\n * G_{lam} = (F_{lam} cos(phi) - F_{-lam-1}) / sin(phi)\n * where\n * phi = Arg[Gamma[1+lam+I eta]] - Arg[Gamma[-lam + I eta]] - (lam+1/2)Pi\n * = Arg[Sin[Pi(-lam+I eta)] - (lam+1/2)Pi\n * = atan2(-cos(lam Pi)sinh(eta Pi), -sin(lam Pi)cosh(eta Pi)) - (lam+1/2)Pi\n *\n * = -atan(X) - (lam+1/2) Pi, X = tanh(eta Pi)/tan(lam Pi)\n *\n * Not appropriate for lam <= -1/2, lam = 0, or lam >= 1/2.\n */\nstatic\nint\ncoulomb_FG_series(const double lam, const double eta, const double x,\n gsl_sf_result * F, gsl_sf_result * G)\n{\n const int max_iter = 800;\n gsl_sf_result ClamA;\n gsl_sf_result ClamB;\n int stat_A = CLeta(lam, eta, &ClamA);\n int stat_B = CLeta(-lam-1.0, eta, &ClamB);\n const double tlp1 = 2.0*lam + 1.0;\n const double pow_x = pow(x, lam);\n double cos_phi_lam;\n double sin_phi_lam;\n\n double uA_mm2 = 1.0; /* uA sum is for F_{lam} */\n double uA_mm1 = x*eta/(lam+1.0);\n double uA_m;\n double uB_mm2 = 1.0; /* uB sum is for F_{-lam-1} */\n double uB_mm1 = -x*eta/lam;\n double uB_m;\n double A_sum = uA_mm2 + uA_mm1;\n double B_sum = uB_mm2 + uB_mm1;\n double A_abs_del_prev = fabs(A_sum);\n double B_abs_del_prev = fabs(B_sum);\n gsl_sf_result FA, FB;\n int m = 2;\n\n int stat_conn = coulomb_connection(lam, eta, &cos_phi_lam, &sin_phi_lam);\n\n if(stat_conn == GSL_EUNDRFLW) {\n F->val = 0.0; /* FIXME: should this be set to Inf too like G? */\n F->err = 0.0;\n OVERFLOW_ERROR(G);\n }\n\n while(m < max_iter) {\n double abs_dA;\n double abs_dB;\n uA_m = x*(2.0*eta*uA_mm1 - x*uA_mm2)/(m*(m+tlp1));\n uB_m = x*(2.0*eta*uB_mm1 - x*uB_mm2)/(m*(m-tlp1));\n A_sum += uA_m;\n B_sum += uB_m;\n abs_dA = fabs(uA_m);\n abs_dB = fabs(uB_m);\n if(m > 15) {\n /* Don't bother checking until we have gone out a little ways;\n * a minor optimization. Also make sure to check both the\n * current and the previous increment because the odd and even\n * terms of the sum can have very different behaviour, depending\n * on the value of eta.\n */\n double max_abs_dA = GSL_MAX(abs_dA, A_abs_del_prev);\n double max_abs_dB = GSL_MAX(abs_dB, B_abs_del_prev);\n double abs_A = fabs(A_sum);\n double abs_B = fabs(B_sum);\n if( max_abs_dA/(max_abs_dA + abs_A) < 4.0*GSL_DBL_EPSILON\n && max_abs_dB/(max_abs_dB + abs_B) < 4.0*GSL_DBL_EPSILON\n ) break;\n }\n A_abs_del_prev = abs_dA;\n B_abs_del_prev = abs_dB;\n uA_mm2 = uA_mm1;\n uA_mm1 = uA_m;\n uB_mm2 = uB_mm1;\n uB_mm1 = uB_m;\n m++;\n }\n\n FA.val = A_sum * ClamA.val * pow_x * x;\n FA.err = fabs(A_sum) * ClamA.err * pow_x * x + 2.0*GSL_DBL_EPSILON*fabs(FA.val);\n FB.val = B_sum * ClamB.val / pow_x;\n FB.err = fabs(B_sum) * ClamB.err / pow_x + 2.0*GSL_DBL_EPSILON*fabs(FB.val);\n\n F->val = FA.val;\n F->err = FA.err;\n\n G->val = (FA.val * cos_phi_lam - FB.val)/sin_phi_lam;\n G->err = (FA.err * fabs(cos_phi_lam) + FB.err)/fabs(sin_phi_lam);\n\n if(m >= max_iter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_ERROR_SELECT_2(stat_A, stat_B);\n}\n\n\n/* Evaluate the Frobenius series for F_0(eta,x) and G_0(eta,x).\n * See [Bardin et al., CPC 3, 73 (1972), (14)-(17)];\n * note the misprint in (17): nu_0=1 is correct, not nu_0=0.\n */\nstatic\nint\ncoulomb_FG0_series(const double eta, const double x,\n gsl_sf_result * F, gsl_sf_result * G)\n{\n const int max_iter = 800;\n const double x2 = x*x;\n const double tex = 2.0*eta*x;\n gsl_sf_result C0;\n int stat_CL = CLeta(0.0, eta, &C0);\n gsl_sf_result r1pie;\n int psi_stat = gsl_sf_psi_1piy_e(eta, &r1pie);\n double u_mm2 = 0.0; /* u_0 */\n double u_mm1 = x; /* u_1 */\n double u_m;\n double v_mm2 = 1.0; /* nu_0 */\n double v_mm1 = tex*(2.0*M_EULER-1.0+r1pie.val); /* nu_1 */\n double v_m;\n double u_sum = u_mm2 + u_mm1;\n double v_sum = v_mm2 + v_mm1;\n double u_abs_del_prev = fabs(u_sum);\n double v_abs_del_prev = fabs(v_sum);\n int m = 2;\n double u_sum_err = 2.0 * GSL_DBL_EPSILON * fabs(u_sum);\n double v_sum_err = 2.0 * GSL_DBL_EPSILON * fabs(v_sum);\n double ln2x = log(2.0*x);\n\n while(m < max_iter) {\n double abs_du;\n double abs_dv;\n double m_mm1 = m*(m-1.0);\n u_m = (tex*u_mm1 - x2*u_mm2)/m_mm1;\n v_m = (tex*v_mm1 - x2*v_mm2 - 2.0*eta*(2*m-1)*u_m)/m_mm1;\n u_sum += u_m;\n v_sum += v_m;\n abs_du = fabs(u_m);\n abs_dv = fabs(v_m);\n u_sum_err += 2.0 * GSL_DBL_EPSILON * abs_du;\n v_sum_err += 2.0 * GSL_DBL_EPSILON * abs_dv;\n if(m > 15) {\n /* Don't bother checking until we have gone out a little ways;\n * a minor optimization. Also make sure to check both the\n * current and the previous increment because the odd and even\n * terms of the sum can have very different behaviour, depending\n * on the value of eta.\n */\n double max_abs_du = GSL_MAX(abs_du, u_abs_del_prev);\n double max_abs_dv = GSL_MAX(abs_dv, v_abs_del_prev);\n double abs_u = fabs(u_sum);\n double abs_v = fabs(v_sum);\n if( max_abs_du/(max_abs_du + abs_u) < 40.0*GSL_DBL_EPSILON\n && max_abs_dv/(max_abs_dv + abs_v) < 40.0*GSL_DBL_EPSILON\n ) break;\n }\n u_abs_del_prev = abs_du;\n v_abs_del_prev = abs_dv;\n u_mm2 = u_mm1;\n u_mm1 = u_m;\n v_mm2 = v_mm1;\n v_mm1 = v_m;\n m++;\n }\n\n F->val = C0.val * u_sum;\n F->err = C0.err * fabs(u_sum);\n F->err += fabs(C0.val) * u_sum_err;\n F->err += 2.0 * GSL_DBL_EPSILON * fabs(F->val);\n\n G->val = (v_sum + 2.0*eta*u_sum * ln2x) / C0.val;\n G->err = (fabs(v_sum) + fabs(2.0*eta*u_sum * ln2x)) / fabs(C0.val) * fabs(C0.err/C0.val);\n G->err += (v_sum_err + fabs(2.0*eta*u_sum_err*ln2x)) / fabs(C0.val);\n G->err += 2.0 * GSL_DBL_EPSILON * fabs(G->val);\n\n if(m == max_iter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return GSL_ERROR_SELECT_2(psi_stat, stat_CL);\n}\n\n\n/* Evaluate the Frobenius series for F_{-1/2}(eta,x) and G_{-1/2}(eta,x).\n * Homegrown algebra.\n */\nstatic\nint\ncoulomb_FGmhalf_series(const double eta, const double x,\n gsl_sf_result * F, gsl_sf_result * G)\n{\n const int max_iter = 800;\n const double rx = sqrt(x);\n const double x2 = x*x;\n const double tex = 2.0*eta*x;\n gsl_sf_result Cmhalf;\n int stat_CL = CLeta(-0.5, eta, &Cmhalf);\n double u_mm2 = 1.0; /* u_0 */\n double u_mm1 = tex * u_mm2; /* u_1 */\n double u_m;\n double v_mm2, v_mm1, v_m;\n double f_sum, g_sum;\n double tmp1;\n gsl_sf_result rpsi_1pe;\n gsl_sf_result rpsi_1p2e;\n int m = 2;\n\n gsl_sf_psi_1piy_e(eta, &rpsi_1pe);\n gsl_sf_psi_1piy_e(2.0*eta, &rpsi_1p2e);\n\n v_mm2 = 2.0*M_EULER - M_LN2 - rpsi_1pe.val + 2.0*rpsi_1p2e.val;\n v_mm1 = tex*(v_mm2 - 2.0*u_mm2);\n\n f_sum = u_mm2 + u_mm1;\n g_sum = v_mm2 + v_mm1;\n\n while(m < max_iter) {\n double m2 = m*m;\n u_m = (tex*u_mm1 - x2*u_mm2)/m2;\n v_m = (tex*v_mm1 - x2*v_mm2 - 2.0*m*u_m)/m2;\n f_sum += u_m;\n g_sum += v_m;\n if( f_sum != 0.0\n && g_sum != 0.0\n && (fabs(u_m/f_sum) + fabs(v_m/g_sum) < 10.0*GSL_DBL_EPSILON)) break;\n u_mm2 = u_mm1;\n u_mm1 = u_m;\n v_mm2 = v_mm1;\n v_mm1 = v_m;\n m++;\n }\n \n F->val = Cmhalf.val * rx * f_sum;\n F->err = Cmhalf.err * fabs(rx * f_sum) + 2.0*GSL_DBL_EPSILON*fabs(F->val);\n\n tmp1 = f_sum*log(x);\n G->val = -rx*(tmp1 + g_sum)/Cmhalf.val;\n G->err = fabs(rx)*(fabs(tmp1) + fabs(g_sum))/fabs(Cmhalf.val) * fabs(Cmhalf.err/Cmhalf.val);\n\n if(m == max_iter)\n GSL_ERROR (\"error\", GSL_EMAXITER);\n else\n return stat_CL;\n}\n\n\n/* Evolve the backwards recurrence for F,F'.\n *\n * F_{lam-1} = (S_lam F_lam + F_lam') / R_lam\n * F_{lam-1}' = (S_lam F_{lam-1} - R_lam F_lam)\n * where\n * R_lam = sqrt(1 + (eta/lam)^2)\n * S_lam = lam/x + eta/lam\n *\n */\nstatic\nint\ncoulomb_F_recur(double lam_min, int kmax,\n double eta, double x,\n double F_lam_max, double Fp_lam_max,\n double * F_lam_min, double * Fp_lam_min\n )\n{\n double x_inv = 1.0/x;\n double fcl = F_lam_max;\n double fpl = Fp_lam_max;\n double lam_max = lam_min + kmax;\n double lam = lam_max;\n int k;\n\n for(k=kmax-1; k>=0; k--) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double fc_lm1;\n fc_lm1 = (fcl*sl + fpl)/rl;\n fpl = fc_lm1*sl - fcl*rl;\n fcl = fc_lm1;\n lam -= 1.0;\n }\n\n *F_lam_min = fcl;\n *Fp_lam_min = fpl; \n return GSL_SUCCESS;\n}\n\n\n/* Evolve the forward recurrence for G,G'.\n *\n * G_{lam+1} = (S_lam G_lam - G_lam')/R_lam\n * G_{lam+1}' = R_{lam+1} G_lam - S_lam G_{lam+1}\n *\n * where S_lam and R_lam are as above in the F recursion.\n */\nstatic\nint\ncoulomb_G_recur(const double lam_min, const int kmax,\n const double eta, const double x,\n const double G_lam_min, const double Gp_lam_min,\n double * G_lam_max, double * Gp_lam_max\n )\n{\n double x_inv = 1.0/x;\n double gcl = G_lam_min;\n double gpl = Gp_lam_min;\n double lam = lam_min + 1.0;\n int k;\n\n for(k=1; k<=kmax; k++) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double gcl1 = (sl*gcl - gpl)/rl;\n gpl = rl*gcl - sl*gcl1;\n gcl = gcl1;\n lam += 1.0;\n }\n \n *G_lam_max = gcl;\n *Gp_lam_max = gpl;\n return GSL_SUCCESS;\n}\n\n\n/* Evaluate the first continued fraction, giving\n * the ratio F'/F at the upper lambda value.\n * We also determine the sign of F at that point,\n * since it is the sign of the last denominator\n * in the continued fraction.\n */\nstatic\nint\ncoulomb_CF1(double lambda,\n double eta, double x,\n double * fcl_sign,\n double * result,\n int * count\n )\n{\n const double CF1_small = 1.e-30;\n const double CF1_abort = 1.0e+05;\n const double CF1_acc = 2.0*GSL_DBL_EPSILON;\n const double x_inv = 1.0/x;\n const double px = lambda + 1.0 + CF1_abort;\n\n double pk = lambda + 1.0;\n double F = eta/pk + pk*x_inv;\n double D, C;\n double df;\n\n *fcl_sign = 1.0;\n *count = 0;\n\n if(fabs(F) < CF1_small) F = CF1_small;\n D = 0.0;\n C = F;\n\n do {\n double pk1 = pk + 1.0;\n double ek = eta / pk;\n double rk2 = 1.0 + ek*ek;\n double tk = (pk + pk1)*(x_inv + ek/pk1);\n D = tk - rk2 * D;\n C = tk - rk2 / C;\n if(fabs(C) < CF1_small) C = CF1_small;\n if(fabs(D) < CF1_small) D = CF1_small;\n D = 1.0/D;\n df = D * C;\n F = F * df;\n if(D < 0.0) {\n /* sign of result depends on sign of denominator */\n *fcl_sign = - *fcl_sign;\n }\n pk = pk1;\n if( pk > px ) {\n *result = F;\n GSL_ERROR (\"error\", GSL_ERUNAWAY);\n }\n ++(*count);\n }\n while(fabs(df-1.0) > CF1_acc);\n \n *result = F;\n return GSL_SUCCESS;\n}\n\n\n#if 0\nstatic\nint\nold_coulomb_CF1(const double lambda,\n double eta, double x,\n double * fcl_sign,\n double * result\n )\n{\n const double CF1_abort = 1.e5;\n const double CF1_acc = 10.0*GSL_DBL_EPSILON;\n const double x_inv = 1.0/x;\n const double px = lambda + 1.0 + CF1_abort;\n \n double pk = lambda + 1.0;\n \n double D;\n double df;\n\n double F;\n double p;\n double pk1;\n double ek;\n \n double fcl = 1.0;\n\n double tk;\n\n while(1) {\n ek = eta/pk;\n F = (ek + pk*x_inv)*fcl + (fcl - 1.0)*x_inv;\n pk1 = pk + 1.0;\n if(fabs(eta*x + pk*pk1) > CF1_acc) break;\n fcl = (1.0 + ek*ek)/(1.0 + eta*eta/(pk1*pk1));\n pk = 2.0 + pk;\n }\n\n D = 1.0/((pk + pk1)*(x_inv + ek/pk1));\n df = -fcl*(1.0 + ek*ek)*D;\n \n if(fcl != 1.0) fcl = -1.0;\n if(D < 0.0) fcl = -fcl;\n \n F = F + df;\n\n p = 1.0;\n do {\n pk = pk1;\n pk1 = pk + 1.0;\n ek = eta / pk;\n tk = (pk + pk1)*(x_inv + ek/pk1);\n D = tk - D*(1.0+ek*ek);\n if(fabs(D) < sqrt(CF1_acc)) {\n p += 1.0;\n if(p > 2.0) {\n printf(\"HELP............\\n\");\n }\n }\n D = 1.0/D;\n if(D < 0.0) {\n /* sign of result depends on sign of denominator */\n fcl = -fcl;\n }\n df = df*(D*tk - 1.0);\n F = F + df;\n if( pk > px ) {\n GSL_ERROR (\"error\", GSL_ERUNAWAY);\n }\n }\n while(fabs(df) > fabs(F)*CF1_acc);\n \n *fcl_sign = fcl;\n *result = F;\n return GSL_SUCCESS;\n}\n#endif /* 0 */\n\n\n/* Evaluate the second continued fraction to \n * obtain the ratio\n * (G' + i F')/(G + i F) := P + i Q\n * at the specified lambda value.\n */\nstatic\nint\ncoulomb_CF2(const double lambda, const double eta, const double x,\n double * result_P, double * result_Q, int * count\n )\n{\n int status = GSL_SUCCESS;\n\n const double CF2_acc = 4.0*GSL_DBL_EPSILON;\n const double CF2_abort = 2.0e+05;\n\n const double wi = 2.0*eta;\n const double x_inv = 1.0/x;\n const double e2mm1 = eta*eta + lambda*(lambda + 1.0);\n \n double ar = -e2mm1;\n double ai = eta;\n\n double br = 2.0*(x - eta);\n double bi = 2.0;\n\n double dr = br/(br*br + bi*bi);\n double di = -bi/(br*br + bi*bi);\n\n double dp = -x_inv*(ar*di + ai*dr);\n double dq = x_inv*(ar*dr - ai*di);\n\n double A, B, C, D;\n\n double pk = 0.0;\n double P = 0.0;\n double Q = 1.0 - eta*x_inv;\n\n *count = 0;\n \n do {\n P += dp;\n Q += dq;\n pk += 2.0;\n ar += pk;\n ai += wi;\n bi += 2.0;\n D = ar*dr - ai*di + br;\n di = ai*dr + ar*di + bi;\n C = 1.0/(D*D + di*di);\n dr = C*D;\n di = -C*di;\n A = br*dr - bi*di - 1.;\n B = bi*dr + br*di;\n C = dp*A - dq*B;\n dq = dp*B + dq*A;\n dp = C;\n if(pk > CF2_abort) {\n status = GSL_ERUNAWAY;\n break;\n }\n ++(*count);\n }\n while(fabs(dp)+fabs(dq) > (fabs(P)+fabs(Q))*CF2_acc);\n\n if(Q < CF2_abort*GSL_DBL_EPSILON*fabs(P)) {\n status = GSL_ELOSS;\n }\n\n *result_P = P;\n *result_Q = Q;\n return status;\n}\n\n\n/* WKB evaluation of F, G. Assumes 0 < x < turning point.\n * Overflows are trapped, GSL_EOVRFLW is signalled,\n * and an exponent is returned such that:\n *\n * result_F = fjwkb * exp(-exponent)\n * result_G = gjwkb * exp( exponent)\n *\n * See [Biedenharn et al. Phys. Rev. 97, 542-554 (1955), Section IV]\n *\n * Unfortunately, this is not very accurate in general. The\n * test cases typically have 3-4 digits of precision. One could\n * argue that this is ok for general use because, for instance,\n * F is exponentially small in this region and so the absolute\n * accuracy is still roughly acceptable. But it would be better\n * to have a systematic method for improving the precision. See\n * the Abad+Sesma method discussion below.\n */\nstatic\nint\ncoulomb_jwkb(const double lam, const double eta, const double x,\n gsl_sf_result * fjwkb, gsl_sf_result * gjwkb,\n double * exponent)\n{\n const double llp1 = lam*(lam+1.0) + 6.0/35.0;\n const double llp1_eff = GSL_MAX(llp1, 0.0);\n const double rho_ghalf = sqrt(x*(2.0*eta - x) + llp1_eff);\n const double sinh_arg = sqrt(llp1_eff/(eta*eta+llp1_eff)) * rho_ghalf / x;\n const double sinh_inv = log(sinh_arg + hypot(1.0,sinh_arg));\n\n const double phi = fabs(rho_ghalf - eta*atan2(rho_ghalf,x-eta) - sqrt(llp1_eff) * sinh_inv);\n\n const double zeta_half = pow(3.0*phi/2.0, 1.0/3.0);\n const double prefactor = sqrt(M_PI*phi*x/(6.0 * rho_ghalf));\n \n double F = prefactor * 3.0/zeta_half;\n double G = prefactor * 3.0/zeta_half; /* Note the sqrt(3) from Bi normalization */\n double F_exp;\n double G_exp;\n \n const double airy_scale_exp = phi;\n gsl_sf_result ai;\n gsl_sf_result bi;\n gsl_sf_airy_Ai_scaled_e(zeta_half*zeta_half, GSL_MODE_DEFAULT, &ai);\n gsl_sf_airy_Bi_scaled_e(zeta_half*zeta_half, GSL_MODE_DEFAULT, &bi);\n F *= ai.val;\n G *= bi.val;\n F_exp = log(F) - airy_scale_exp;\n G_exp = log(G) + airy_scale_exp;\n\n if(G_exp >= GSL_LOG_DBL_MAX) {\n fjwkb->val = F;\n gjwkb->val = G;\n fjwkb->err = 1.0e-3 * fabs(F); /* FIXME: real error here ... could be smaller */\n gjwkb->err = 1.0e-3 * fabs(G);\n *exponent = airy_scale_exp;\n GSL_ERROR (\"error\", GSL_EOVRFLW);\n }\n else {\n fjwkb->val = exp(F_exp);\n gjwkb->val = exp(G_exp);\n fjwkb->err = 1.0e-3 * fabs(fjwkb->val);\n gjwkb->err = 1.0e-3 * fabs(gjwkb->val);\n *exponent = 0.0;\n return GSL_SUCCESS;\n }\n}\n\n\n/* Asymptotic evaluation of F and G below the minimal turning point.\n *\n * This is meant to be a drop-in replacement for coulomb_jwkb().\n * It uses the expressions in [Abad+Sesma]. This requires some\n * work because I am not sure where it is valid. They mumble\n * something about |x| < |lam|^(-1/2) or 8|eta x| > lam when |x| < 1.\n * This seems true, but I thought the result was based on a uniform\n * expansion and could be controlled by simply using more terms.\n */\n#if 0\nstatic\nint\ncoulomb_AS_xlt2eta(const double lam, const double eta, const double x,\n gsl_sf_result * f_AS, gsl_sf_result * g_AS,\n double * exponent)\n{\n /* no time to do this now... */\n}\n#endif /* 0 */\n\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_coulomb_wave_FG_e(const double eta, const double x,\n const double lam_F,\n const int k_lam_G, /* lam_G = lam_F - k_lam_G */\n gsl_sf_result * F, gsl_sf_result * Fp,\n gsl_sf_result * G, gsl_sf_result * Gp,\n double * exp_F, double * exp_G)\n{\n const double lam_G = lam_F - k_lam_G;\n\n if(x < 0.0 || lam_F <= -0.5 || lam_G <= -0.5) {\n GSL_SF_RESULT_SET(F, 0.0, 0.0);\n GSL_SF_RESULT_SET(Fp, 0.0, 0.0);\n GSL_SF_RESULT_SET(G, 0.0, 0.0);\n GSL_SF_RESULT_SET(Gp, 0.0, 0.0);\n *exp_F = 0.0;\n *exp_G = 0.0;\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(x == 0.0) {\n gsl_sf_result C0;\n CLeta(0.0, eta, &C0);\n GSL_SF_RESULT_SET(F, 0.0, 0.0);\n GSL_SF_RESULT_SET(Fp, 0.0, 0.0);\n GSL_SF_RESULT_SET(G, 0.0, 0.0); /* FIXME: should be Inf */\n GSL_SF_RESULT_SET(Gp, 0.0, 0.0); /* FIXME: should be Inf */\n *exp_F = 0.0;\n *exp_G = 0.0;\n if(lam_F == 0.0){\n GSL_SF_RESULT_SET(Fp, C0.val, C0.err);\n }\n if(lam_G == 0.0) {\n GSL_SF_RESULT_SET(Gp, 1.0/C0.val, fabs(C0.err/C0.val)/fabs(C0.val));\n }\n GSL_ERROR (\"domain error\", GSL_EDOM);\n /* After all, since we are asking for G, this is a domain error... */\n }\n else if(x < 1.2 && 2.0*M_PI*eta < 0.9*(-GSL_LOG_DBL_MIN) && fabs(eta*x) < 10.0) {\n /* Reduce to a small lambda value and use the series\n * representations for F and G. We cannot allow eta to\n * be large and positive because the connection formula\n * for G_lam is badly behaved due to an underflow in sin(phi_lam) \n * [see coulomb_FG_series() and coulomb_connection() above].\n * Note that large negative eta is ok however.\n */\n const double SMALL = GSL_SQRT_DBL_EPSILON;\n const int N = (int)(lam_F + 0.5);\n const int span = GSL_MAX(k_lam_G, N);\n const double lam_min = lam_F - N; /* -1/2 <= lam_min < 1/2 */\n double F_lam_F, Fp_lam_F;\n double G_lam_G, Gp_lam_G;\n double F_lam_F_err, Fp_lam_F_err;\n double Fp_over_F_lam_F;\n double F_sign_lam_F;\n double F_lam_min_unnorm, Fp_lam_min_unnorm;\n double Fp_over_F_lam_min;\n gsl_sf_result F_lam_min;\n gsl_sf_result G_lam_min, Gp_lam_min;\n double F_scale;\n double Gerr_frac;\n double F_scale_frac_err;\n double F_unnorm_frac_err;\n\n /* Determine F'/F at lam_F. */\n int CF1_count;\n int stat_CF1 = coulomb_CF1(lam_F, eta, x, &F_sign_lam_F, &Fp_over_F_lam_F, &CF1_count);\n\n int stat_ser;\n int stat_Fr;\n int stat_Gr;\n\n /* Recurse down with unnormalized F,F' values. */\n F_lam_F = SMALL;\n Fp_lam_F = Fp_over_F_lam_F * F_lam_F;\n if(span != 0) {\n stat_Fr = coulomb_F_recur(lam_min, span, eta, x,\n F_lam_F, Fp_lam_F,\n &F_lam_min_unnorm, &Fp_lam_min_unnorm\n );\n }\n else {\n F_lam_min_unnorm = F_lam_F;\n Fp_lam_min_unnorm = Fp_lam_F;\n stat_Fr = GSL_SUCCESS;\n }\n\n /* Determine F and G at lam_min. */\n if(lam_min == -0.5) {\n stat_ser = coulomb_FGmhalf_series(eta, x, &F_lam_min, &G_lam_min);\n }\n else if(lam_min == 0.0) {\n stat_ser = coulomb_FG0_series(eta, x, &F_lam_min, &G_lam_min);\n }\n else if(lam_min == 0.5) {\n /* This cannot happen. */\n F->val = F_lam_F;\n F->err = 2.0 * GSL_DBL_EPSILON * fabs(F->val);\n Fp->val = Fp_lam_F;\n Fp->err = 2.0 * GSL_DBL_EPSILON * fabs(Fp->val);\n G->val = G_lam_G;\n G->err = 2.0 * GSL_DBL_EPSILON * fabs(G->val);\n Gp->val = Gp_lam_G;\n Gp->err = 2.0 * GSL_DBL_EPSILON * fabs(Gp->val);\n *exp_F = 0.0;\n *exp_G = 0.0;\n GSL_ERROR (\"error\", GSL_ESANITY);\n }\n else {\n stat_ser = coulomb_FG_series(lam_min, eta, x, &F_lam_min, &G_lam_min);\n }\n\n /* Determine remaining quantities. */\n Fp_over_F_lam_min = Fp_lam_min_unnorm / F_lam_min_unnorm;\n Gp_lam_min.val = Fp_over_F_lam_min*G_lam_min.val - 1.0/F_lam_min.val;\n Gp_lam_min.err = fabs(Fp_over_F_lam_min)*G_lam_min.err;\n Gp_lam_min.err += fabs(1.0/F_lam_min.val) * fabs(F_lam_min.err/F_lam_min.val);\n F_scale = F_lam_min.val / F_lam_min_unnorm;\n\n /* Apply scale to the original F,F' values. */\n F_scale_frac_err = fabs(F_lam_min.err/F_lam_min.val);\n F_unnorm_frac_err = 2.0*GSL_DBL_EPSILON*(CF1_count+span+1);\n F_lam_F *= F_scale;\n F_lam_F_err = fabs(F_lam_F) * (F_unnorm_frac_err + F_scale_frac_err);\n Fp_lam_F *= F_scale;\n Fp_lam_F_err = fabs(Fp_lam_F) * (F_unnorm_frac_err + F_scale_frac_err);\n\n /* Recurse up to get the required G,G' values. */\n stat_Gr = coulomb_G_recur(lam_min, GSL_MAX(N-k_lam_G,0), eta, x,\n G_lam_min.val, Gp_lam_min.val,\n &G_lam_G, &Gp_lam_G\n );\n\n F->val = F_lam_F;\n F->err = F_lam_F_err;\n F->err += 2.0 * GSL_DBL_EPSILON * fabs(F_lam_F);\n\n Fp->val = Fp_lam_F;\n Fp->err = Fp_lam_F_err;\n Fp->err += 2.0 * GSL_DBL_EPSILON * fabs(Fp_lam_F);\n\n Gerr_frac = fabs(G_lam_min.err/G_lam_min.val) + fabs(Gp_lam_min.err/Gp_lam_min.val);\n\n G->val = G_lam_G;\n G->err = Gerr_frac * fabs(G_lam_G);\n G->err += 2.0 * (CF1_count+1) * GSL_DBL_EPSILON * fabs(G->val);\n\n Gp->val = Gp_lam_G;\n Gp->err = Gerr_frac * fabs(Gp->val);\n Gp->err += 2.0 * (CF1_count+1) * GSL_DBL_EPSILON * fabs(Gp->val);\n\n *exp_F = 0.0;\n *exp_G = 0.0;\n\n return GSL_ERROR_SELECT_4(stat_ser, stat_CF1, stat_Fr, stat_Gr);\n }\n else if(x < 2.0*eta) {\n /* Use WKB approximation to obtain F and G at the two\n * lambda values, and use the Wronskian and the\n * continued fractions for F'/F to obtain F' and G'.\n */\n gsl_sf_result F_lam_F, G_lam_F;\n gsl_sf_result F_lam_G, G_lam_G;\n double exp_lam_F, exp_lam_G;\n int stat_lam_F;\n int stat_lam_G;\n int stat_CF1_lam_F;\n int stat_CF1_lam_G;\n int CF1_count;\n double Fp_over_F_lam_F;\n double Fp_over_F_lam_G;\n double F_sign_lam_F;\n double F_sign_lam_G;\n\n stat_lam_F = coulomb_jwkb(lam_F, eta, x, &F_lam_F, &G_lam_F, &exp_lam_F);\n if(k_lam_G == 0) {\n stat_lam_G = stat_lam_F;\n F_lam_G = F_lam_F;\n G_lam_G = G_lam_F;\n exp_lam_G = exp_lam_F;\n }\n else {\n stat_lam_G = coulomb_jwkb(lam_G, eta, x, &F_lam_G, &G_lam_G, &exp_lam_G);\n }\n\n stat_CF1_lam_F = coulomb_CF1(lam_F, eta, x, &F_sign_lam_F, &Fp_over_F_lam_F, &CF1_count);\n if(k_lam_G == 0) {\n stat_CF1_lam_G = stat_CF1_lam_F;\n F_sign_lam_G = F_sign_lam_F;\n Fp_over_F_lam_G = Fp_over_F_lam_F;\n }\n else {\n stat_CF1_lam_G = coulomb_CF1(lam_G, eta, x, &F_sign_lam_G, &Fp_over_F_lam_G, &CF1_count);\n }\n\n F->val = F_lam_F.val;\n F->err = F_lam_F.err;\n\n G->val = G_lam_G.val;\n G->err = G_lam_G.err;\n\n Fp->val = Fp_over_F_lam_F * F_lam_F.val;\n Fp->err = fabs(Fp_over_F_lam_F) * F_lam_F.err;\n Fp->err += 2.0*GSL_DBL_EPSILON*fabs(Fp->val);\n\n Gp->val = Fp_over_F_lam_G * G_lam_G.val - 1.0/F_lam_G.val;\n Gp->err = fabs(Fp_over_F_lam_G) * G_lam_G.err;\n Gp->err += fabs(1.0/F_lam_G.val) * fabs(F_lam_G.err/F_lam_G.val);\n\n *exp_F = exp_lam_F;\n *exp_G = exp_lam_G;\n\n if(stat_lam_F == GSL_EOVRFLW || stat_lam_G == GSL_EOVRFLW) {\n GSL_ERROR (\"overflow\", GSL_EOVRFLW);\n }\n else {\n return GSL_ERROR_SELECT_2(stat_lam_F, stat_lam_G);\n }\n }\n else {\n /* x > 2 eta, so we know that we can find a lambda value such\n * that x is above the turning point. We do this, evaluate\n * using Steed's method at that oscillatory point, then\n * use recursion on F and G to obtain the required values.\n *\n * lam_0 = a value of lambda such that x is below the turning point\n * lam_min = minimum of lam_0 and the requested lam_G, since\n * we must go at least as low as lam_G\n */\n const double SMALL = GSL_SQRT_DBL_EPSILON;\n const double C = sqrt(1.0 + 4.0*x*(x-2.0*eta));\n const int N = ceil(lam_F - C + 0.5);\n const double lam_0 = lam_F - GSL_MAX(N, 0);\n const double lam_min = GSL_MIN(lam_0, lam_G);\n double F_lam_F, Fp_lam_F;\n double G_lam_G, Gp_lam_G;\n double F_lam_min_unnorm, Fp_lam_min_unnorm;\n double F_lam_min, Fp_lam_min;\n double G_lam_min, Gp_lam_min;\n double Fp_over_F_lam_F;\n double Fp_over_F_lam_min;\n double F_sign_lam_F, F_sign_lam_min;\n double P_lam_min, Q_lam_min;\n double alpha;\n double gamma;\n double F_scale;\n\n int CF1_count;\n int CF2_count;\n int stat_CF1 = coulomb_CF1(lam_F, eta, x, &F_sign_lam_F, &Fp_over_F_lam_F, &CF1_count);\n int stat_CF2;\n int stat_Fr;\n int stat_Gr;\n\n int F_recur_count;\n int G_recur_count;\n\n double err_amplify;\n\n F_lam_F = F_sign_lam_F * SMALL; /* unnormalized */\n Fp_lam_F = Fp_over_F_lam_F * F_lam_F;\n\n /* Backward recurrence to get F,Fp at lam_min */\n F_recur_count = GSL_MAX(k_lam_G, N);\n stat_Fr = coulomb_F_recur(lam_min, F_recur_count, eta, x,\n F_lam_F, Fp_lam_F,\n &F_lam_min_unnorm, &Fp_lam_min_unnorm\n );\n Fp_over_F_lam_min = Fp_lam_min_unnorm / F_lam_min_unnorm;\n\n /* Steed evaluation to complete evaluation of F,Fp,G,Gp at lam_min */\n stat_CF2 = coulomb_CF2(lam_min, eta, x, &P_lam_min, &Q_lam_min, &CF2_count);\n alpha = Fp_over_F_lam_min - P_lam_min;\n gamma = alpha/Q_lam_min;\n\n F_sign_lam_min = GSL_SIGN(F_lam_min_unnorm) ;\n\n F_lam_min = F_sign_lam_min / sqrt(alpha*alpha/Q_lam_min + Q_lam_min);\n Fp_lam_min = Fp_over_F_lam_min * F_lam_min;\n G_lam_min = gamma * F_lam_min;\n Gp_lam_min = (P_lam_min * gamma - Q_lam_min) * F_lam_min;\n\n /* Apply scale to values of F,Fp at lam_F (the top). */\n F_scale = F_lam_min / F_lam_min_unnorm; \n F_lam_F *= F_scale;\n Fp_lam_F *= F_scale;\n\n /* Forward recurrence to get G,Gp at lam_G (the top). */\n G_recur_count = GSL_MAX(N-k_lam_G,0);\n stat_Gr = coulomb_G_recur(lam_min, G_recur_count, eta, x,\n G_lam_min, Gp_lam_min,\n &G_lam_G, &Gp_lam_G\n );\n\n err_amplify = CF1_count + CF2_count + F_recur_count + G_recur_count + 1;\n\n F->val = F_lam_F;\n F->err = 8.0*err_amplify*GSL_DBL_EPSILON * fabs(F->val);\n\n Fp->val = Fp_lam_F;\n Fp->err = 8.0*err_amplify*GSL_DBL_EPSILON * fabs(Fp->val);\n\n G->val = G_lam_G;\n G->err = 8.0*err_amplify*GSL_DBL_EPSILON * fabs(G->val);\n\n Gp->val = Gp_lam_G;\n Gp->err = 8.0*err_amplify*GSL_DBL_EPSILON * fabs(Gp->val);\n\n *exp_F = 0.0;\n *exp_G = 0.0;\n\n return GSL_ERROR_SELECT_4(stat_CF1, stat_CF2, stat_Fr, stat_Gr);\n }\n}\n\n\nint\ngsl_sf_coulomb_wave_F_array(double lam_min, int kmax,\n double eta, double x, \n double * fc_array,\n double * F_exp)\n{\n if(x == 0.0) {\n int k;\n *F_exp = 0.0;\n for(k=0; k<=kmax; k++) {\n fc_array[k] = 0.0;\n }\n if(lam_min == 0.0){\n gsl_sf_result f_0;\n CLeta(0.0, eta, &f_0);\n fc_array[0] = f_0.val;\n }\n return GSL_SUCCESS;\n }\n else {\n const double x_inv = 1.0/x;\n const double lam_max = lam_min + kmax;\n gsl_sf_result F, Fp;\n gsl_sf_result G, Gp;\n double G_exp;\n\n int stat_FG = gsl_sf_coulomb_wave_FG_e(eta, x, lam_max, 0,\n &F, &Fp, &G, &Gp, F_exp, &G_exp);\n\n double fcl = F.val;\n double fpl = Fp.val;\n double lam = lam_max;\n int k;\n\n fc_array[kmax] = F.val;\n\n for(k=kmax-1; k>=0; k--) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double fc_lm1 = (fcl*sl + fpl)/rl;\n fc_array[k] = fc_lm1;\n fpl = fc_lm1*sl - fcl*rl;\n fcl = fc_lm1;\n lam -= 1.0;\n }\n\n return stat_FG;\n }\n}\n\n\nint\ngsl_sf_coulomb_wave_FG_array(double lam_min, int kmax,\n double eta, double x,\n double * fc_array, double * gc_array,\n double * F_exp, double * G_exp)\n{\n const double x_inv = 1.0/x;\n const double lam_max = lam_min + kmax;\n gsl_sf_result F, Fp;\n gsl_sf_result G, Gp;\n\n int stat_FG = gsl_sf_coulomb_wave_FG_e(eta, x, lam_max, kmax,\n &F, &Fp, &G, &Gp, F_exp, G_exp);\n\n double fcl = F.val;\n double fpl = Fp.val;\n double lam = lam_max;\n int k;\n\n double gcl, gpl;\n\n fc_array[kmax] = F.val;\n\n for(k=kmax-1; k>=0; k--) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double fc_lm1;\n fc_lm1 = (fcl*sl + fpl)/rl;\n fc_array[k] = fc_lm1;\n fpl = fc_lm1*sl - fcl*rl;\n fcl = fc_lm1;\n lam -= 1.0;\n }\n\n gcl = G.val;\n gpl = Gp.val;\n lam = lam_min + 1.0;\n\n gc_array[0] = G.val;\n\n for(k=1; k<=kmax; k++) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double gcl1 = (sl*gcl - gpl)/rl;\n gc_array[k] = gcl1;\n gpl = rl*gcl - sl*gcl1;\n gcl = gcl1;\n lam += 1.0;\n }\n\n return stat_FG;\n}\n\n\nint\ngsl_sf_coulomb_wave_FGp_array(double lam_min, int kmax,\n double eta, double x,\n double * fc_array, double * fcp_array,\n double * gc_array, double * gcp_array,\n double * F_exp, double * G_exp)\n\n{\n const double x_inv = 1.0/x;\n const double lam_max = lam_min + kmax;\n gsl_sf_result F, Fp;\n gsl_sf_result G, Gp;\n\n int stat_FG = gsl_sf_coulomb_wave_FG_e(eta, x, lam_max, kmax,\n &F, &Fp, &G, &Gp, F_exp, G_exp);\n\n double fcl = F.val;\n double fpl = Fp.val;\n double lam = lam_max;\n int k;\n\n double gcl, gpl;\n\n fc_array[kmax] = F.val;\n fcp_array[kmax] = Fp.val;\n\n for(k=kmax-1; k>=0; k--) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double fc_lm1;\n fc_lm1 = (fcl*sl + fpl)/rl;\n fc_array[k] = fc_lm1;\n fpl = fc_lm1*sl - fcl*rl;\n fcp_array[k] = fpl;\n fcl = fc_lm1;\n lam -= 1.0;\n }\n\n gcl = G.val;\n gpl = Gp.val;\n lam = lam_min + 1.0;\n\n gc_array[0] = G.val;\n gcp_array[0] = Gp.val;\n\n for(k=1; k<=kmax; k++) {\n double el = eta/lam;\n double rl = hypot(1.0, el);\n double sl = el + lam*x_inv;\n double gcl1 = (sl*gcl - gpl)/rl;\n gc_array[k] = gcl1;\n gpl = rl*gcl - sl*gcl1;\n gcp_array[k] = gpl;\n gcl = gcl1;\n lam += 1.0;\n }\n\n return stat_FG;\n}\n\n\nint\ngsl_sf_coulomb_wave_sphF_array(double lam_min, int kmax,\n double eta, double x,\n double * fc_array,\n double * F_exp)\n{\n if(x < 0.0 || lam_min < -0.5) {\n GSL_ERROR (\"domain error\", GSL_EDOM);\n }\n else if(x < 10.0/GSL_DBL_MAX) {\n int k;\n for(k=0; k<=kmax; k++) {\n fc_array[k] = 0.0;\n }\n if(lam_min == 0.0) {\n fc_array[0] = sqrt(C0sq(eta));\n }\n *F_exp = 0.0;\n if(x == 0.0)\n return GSL_SUCCESS;\n else\n GSL_ERROR (\"underflow\", GSL_EUNDRFLW);\n }\n else {\n int k;\n int stat_F = gsl_sf_coulomb_wave_F_array(lam_min, kmax,\n eta, x, \n fc_array,\n F_exp);\n\n for(k=0; k<=kmax; k++) {\n fc_array[k] = fc_array[k] / x;\n }\n return stat_F;\n }\n}\n\n\n", "meta": {"hexsha": "7c68076f9abc1b3073d10d0594eb319370987c89", "size": 39439, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/coulomb.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/coulomb.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/coulomb.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.8131170663, "max_line_length": 95, "alphanum_fraction": 0.5875656076, "num_tokens": 13964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6240971296103388}} {"text": "#include \n#include \n#include \n#include \n#include \"zero_crossing.h\"\n\n/* \\fn double zero_crossing(double (*model)(double, void *), void *params, double *x_lo, double *x_hi)\n * \\brief Find a zero crossing of the supplied model. */\ndouble zero_crossing(double (*model)(double, void *), void *params, double *x_lo, double *x_hi)\n{\n\tint status;\n\tint iter=0;\n\tint max_iter = 100;\n\n\tdouble x;\t//root\n\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\n\tgsl_function F;\n\n\tF.function = model;\n\tF.params = params;\n\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\n\tgsl_root_fsolver_set(s,&F, *x_lo, *x_hi);\n\n\tdo{\n\t\titer++;\n\t\tstatus = gsl_root_fsolver_iterate(s);\n\t\tx = gsl_root_fsolver_root(s);\n\n\t\t*x_lo = gsl_root_fsolver_x_lower(s);\n\t\t*x_hi = gsl_root_fsolver_x_upper(s);\n\n\t\tstatus = gsl_root_test_interval(*x_lo, *x_hi,0,0.001);\n\n\t\t//printf(\"iter %d x_lo %e x %e x_hi %e\\n\",iter,*x_lo,x,*x_hi);\n\t\t\n\t}while((status==GSL_CONTINUE)&&(iter\n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid Normalise(gsl_vector *Single_eigvector_ptr, int Dim, double dx, FILE *fp_2)\n{\n int n;\n double temp;\n double norm_factor, vector_sum=0;\n for (n=0; nE_well && eigenvalue<0) /*select confined states*/\n {\n fprintf(fp_1, \"n%E\", (eigenvalue/1.6E-22));\n /*output in meV*/\n subband_ptr[n] = eigenvalue; /*For Fermi-Dirac */\n N = N+1;\n /* sum the number of eigenstates*/\n }\n }\n /*output eigenvectors*/\n for (n = 0; n < N; n++){ /*retrieve eigenvectors for confined states only*/\n fprintf(fp_2, \"nnnn\");\n gsl_matrix_get_col(s_eigvector_ptr, Eigvector_ptr, n);\n /*retrieve nth eigenvector*/\n Normalise(s_eigvector_ptr, Dim, dx, fp_2);\n /*normalise eigenvector*/\n gsl_matrix_set_col(Norm_Eigvector_ptr, n, s_eigvector_ptr);\n }\n return N;\n}\n\ndouble FD_Bisect(double *Subband_f, double E_fermi_super, double E_fermi_diff, double c_doping_yz, double Meff, int N, int T)\n{\n double n_sp = 0, n_s = 0;\n double Hbar=1.054571E-34, Kb = 1.38065E-23;\n int n, m;\n /*temperature set to 300K*/\n double DOS = Meff/(Hbar*Hbar*3.14159);\n double E_fermi_sub = E_fermi_super + E_fermi_diff;\n double E_fermi_mid = (E_fermi_sub + E_fermi_super)/2;\n for (n=0; n<50; n++){\n for (m = 0; m < N; m++){ /*add contributions from all subbands*/\n n_sp = DOS*Kb*T*log(exp((E_fermi_mid - Subband_f[m])/(Kb*T)) + 1);\n n_s = n_sp + n_s;\n }\n if (n_s > c_doping_yz){\n E_fermi_super = E_fermi_mid;\n E_fermi_mid = (E_fermi_super + E_fermi_sub)/2;\n }\n else {\n E_fermi_sub = E_fermi_mid;\n E_fermi_mid = (E_fermi_sub + E_fermi_super)/2;\n }\n n_s = 0;\n }\n printf(\"nPrecise Fermi energy is %E eV\", E_fermi_mid);\n return E_fermi_mid;\n}\n\ndouble FermiDiracPopulate(double *Subband_f, double c_doping_yz, double Meff, double E_fermi, int N, int T)\n{\n int m;\n double FL_precise, n_sp = 0, n_s = 0;\n /* initial fermi-energy roughly at intrinsic level (@300K)*/\n double Hbar=1.054571E-34, Kb = 1.38065E-23;\n double d_E_fermi = E_fermi/100;\n double DOS = Meff/(Hbar*Hbar*3.14159);\n for (n_s = 0; E_fermi < 0; E_fermi = E_fermi - d_E_fermi){\n printf(\"n%E\", E_fermi);\n for (m = 0; m < N; m++){ /*add contributions from all subbands*/\n n_sp = DOS*Kb*T*log(exp((E_fermi - Subband_f[m])/(Kb*T)) + 1);\n /*NB. subband energies were calculated to be positive (should be negative)*/\n n_s = n_sp + n_s;\n }\n //printf(\"ncharge density for E_fermi of %E is %E per meter squared\", E_fermi, n_s);\n if (n_s > c_doping_yz){\n printf(\"nRaw Fermi energy is %E eV\", E_fermi);\n FL_precise = FD_Bisect(Subband_f, E_fermi, d_E_fermi, c_doping_yz, Meff, N, T);\n break;\n }\n n_s = 0;\n }\n return FL_precise;\n}\n\ndouble subband_contrib(double E_fermi, double E, double Meff, int T)\n{\n double n_sp = 0;\n double Hbar=1.054571E-34, Kb = 1.38065E-23;\n double DOS = Meff/(Hbar*Hbar*3.14159);\n n_sp = DOS*Kb*T*log(exp((E_fermi + E)/(Kb*T)) + 1);\n return n_sp;\n}\n\nvoid Charge_Density(gsl_matrix *Norm_eigenvector_ptr, gsl_vector *s_eigvector_ptr, gsl_vector *Charge_Density_ptr, double *subband_ptr, double E_fermi, double dx, double c_doping_yz, double Meff, int Dim, int N, int T, FILE *fp_3)\n{\n int n, m;\n double phi, n_sp, temp;\n double c_doping_xyz, q = 1.602176E-19;\n temp = sqrt(c_doping_yz);\n c_doping_xyz = temp*temp*temp;\n for (n=0; n=barrier_R){\n // gsl_vector_set(Main_Diagonal_ptr, n, -2*abs_permitt_Si);\n // }\n // if(n=barrier_L){\n // gsl_vector_set(Main_Diagonal_ptr, n, -2*abs_permitt_Ge);\n // }\n // if (n=(barrier_R-1)){\n // gsl_vector_set(Sub_Diagonal_ptr, n, 1*abs_permitt_Si);\n // }\n // if(n<(barrier_R-1) && n>(barrier_L-2)){\n // gsl_vector_set(Sub_Diagonal_ptr, n, 1*abs_permitt_Ge);\n // }\n // if (n<(barrier_L-1)){\n // gsl_vector_set(Sub_Diagonal_ptr, n, 1*abs_permitt_Si);\n // }\n //}\n //for (n=0; n<(Dim-1); n++) {\n // if(n>=barrier_R){\n // gsl_vector_set(Super_Diagonal_ptr, n, 1*abs_permitt_Si);\n // }\n // if(n=barrier_L){\n // gsl_vector_set(Super_Diagonal_ptr, n, 1*abs_permitt_Ge);\n // }\n // if (n=barrier_R){\n gsl_vector_set(Potential_ptr, n, 0);\n }\n if(n=barrier_L){\n gsl_vector_set(Potential_ptr, n, E_well);\n }\n if (nbarrier_R && nbarrier_L){\n Meff_ptr[n]=Meff_well;\n }\n if (n<(barrier_L) && n>0){\n Meff_ptr[n] = Meff_barrier;\n }\n if (n==0 || n==Dim){\n Meff_ptr[n]= Meff_barrier/2;\n }\n if (n==barrier_R || n==(barrier_R-1) || n==barrier_L || n==(barrier_L-1)){\n Meff_ptr[n]= (Meff_barrier+Meff_well)/2;\n }\n }\n N = Schrodinger_Solve(dx, Dim, barrier_L, barrier_R, E_well, Meff_ptr, Subband_ptr, Workspace, Hamil_ptr, Eigvalue_ptr, Eigvector_ptr, S_Eigvector_ptr, Potential_ptr, Norm_Eigvector_ptr, fp_1, fp_2);\n E_fermi = FermiDiracPopulate(Subband_ptr, c_doping_yz, Meff_well, E_well, N, T);\n Charge_Density(Norm_Eigvector_ptr, S_Eigvector_ptr, Charge_Density_ptr, Subband_ptr, E_fermi, dx, c_doping_yz, Meff_well, Dim, N, T, fp_3);\n double Charge_tot = charge_density_check(Charge_Density_ptr, Dim);\n printf(\"n%E\", Charge_tot);\n //Poisson_Solve(Dim, barrier_R, barrier_L, dx, Main_Diagonal_ptr, Super_Diagonal_ptr, Sub_Diagonal_ptr, Charge_Density_ptr, Elec_Potential_ptr, fp_3, fp_4);\n //Convergence_Check()\n //Subband_store()\n /*free memory*/\n gsl_matrix_free(Eigvector_ptr);\n gsl_vector_free(Eigvalue_ptr);\n gsl_matrix_free(Hamil_ptr);\n gsl_eigen_symmv_free(Workspace);\n gsl_matrix_free(Norm_Eigvector_ptr);\n gsl_vector_free (S_Eigvector_ptr);\n free(Subband_ptr);\n free(Meff_ptr);\n gsl_vector_free(Charge_Density_ptr);\n //gsl_vector_free (Main_Diagonal_ptr);\n //gsl_vector_free (Super_Diagonal_ptr);\n //gsl_vector_free(Sub_Diagonal_ptr);\n //gsl_vector_free(Elec_Potential_ptr);\n //free(Subband_prev_ptr)\n return 0;\n}", "meta": {"hexsha": "e59148638e061c0c88ea174c14fabb86f40abd8d", "size": 14046, "ext": "c", "lang": "C", "max_stars_repo_path": "Schrodinger-Poison.c", "max_stars_repo_name": "CRJFisher/Schrodinger-Poisson-Finite-Difference-Solver", "max_stars_repo_head_hexsha": "e3522de0d7dcbd3b8b4017991aaeb481f2032b3f", "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": "Schrodinger-Poison.c", "max_issues_repo_name": "CRJFisher/Schrodinger-Poisson-Finite-Difference-Solver", "max_issues_repo_head_hexsha": "e3522de0d7dcbd3b8b4017991aaeb481f2032b3f", "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": "Schrodinger-Poison.c", "max_forks_repo_name": "CRJFisher/Schrodinger-Poisson-Finite-Difference-Solver", "max_forks_repo_head_hexsha": "e3522de0d7dcbd3b8b4017991aaeb481f2032b3f", "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.8011049724, "max_line_length": 230, "alphanum_fraction": 0.6047985192, "num_tokens": 4438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6231470288729215}} {"text": "/* linalg/householder.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007, 2010 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#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\ndouble\ngsl_linalg_householder_transform (gsl_vector * v)\n{\n /* replace v[0:n-1] with a householder vector (v[0:n-1]) and\n coefficient tau that annihilate v[1:n-1] */\n\n const size_t n = v->size ;\n\n if (n == 1)\n {\n return 0.0; /* tau = 0 */\n }\n else\n { \n double alpha, beta, tau ;\n \n gsl_vector_view x = gsl_vector_subvector (v, 1, n - 1) ; \n \n double xnorm = gsl_blas_dnrm2 (&x.vector);\n \n if (xnorm == 0) \n {\n return 0.0; /* tau = 0 */\n }\n \n alpha = gsl_vector_get (v, 0) ;\n beta = - (alpha >= 0.0 ? +1.0 : -1.0) * hypot(alpha, xnorm) ;\n tau = (beta - alpha) / beta ;\n \n {\n double s = (alpha - beta);\n \n if (fabs(s) > GSL_DBL_MIN) \n {\n gsl_blas_dscal (1.0 / s, &x.vector);\n gsl_vector_set (v, 0, beta) ;\n }\n else\n {\n gsl_blas_dscal (GSL_DBL_EPSILON / s, &x.vector);\n gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, &x.vector);\n gsl_vector_set (v, 0, beta) ;\n }\n }\n \n return tau;\n }\n}\n\nint\ngsl_linalg_householder_hm (double tau, const gsl_vector * v, gsl_matrix * A)\n{\n /* applies a householder transformation v,tau to matrix m */\n\n if (tau == 0.0)\n {\n return GSL_SUCCESS;\n }\n\n#ifdef USE_BLAS\n {\n gsl_vector_const_view v1 = gsl_vector_const_subvector (v, 1, v->size - 1);\n gsl_matrix_view A1 = gsl_matrix_submatrix (A, 1, 0, A->size1 - 1, A->size2);\n size_t j;\n\n for (j = 0; j < A->size2; j++)\n {\n double wj = 0.0;\n gsl_vector_view A1j = gsl_matrix_column(&A1.matrix, j);\n gsl_blas_ddot (&A1j.vector, &v1.vector, &wj);\n wj += gsl_matrix_get(A,0,j);\n\n {\n double A0j = gsl_matrix_get (A, 0, j);\n gsl_matrix_set (A, 0, j, A0j - tau * wj);\n }\n\n gsl_blas_daxpy (-tau * wj, &v1.vector, &A1j.vector);\n }\n }\n#else\n {\n size_t i, j;\n \n for (j = 0; j < A->size2; j++)\n {\n /* Compute wj = Akj vk */\n \n double wj = gsl_matrix_get(A,0,j); \n \n for (i = 1; i < A->size1; i++) /* note, computed for v(0) = 1 above */\n {\n wj += gsl_matrix_get(A,i,j) * gsl_vector_get(v,i);\n }\n \n /* Aij = Aij - tau vi wj */\n \n /* i = 0 */\n {\n double A0j = gsl_matrix_get (A, 0, j);\n gsl_matrix_set (A, 0, j, A0j - tau * wj);\n }\n \n /* i = 1 .. M-1 */\n \n for (i = 1; i < A->size1; i++)\n {\n double Aij = gsl_matrix_get (A, i, j);\n double vi = gsl_vector_get (v, i);\n gsl_matrix_set (A, i, j, Aij - tau * vi * wj);\n }\n }\n }\n#endif\n \n return GSL_SUCCESS;\n}\n\nint\ngsl_linalg_householder_mh (double tau, const gsl_vector * v, gsl_matrix * A)\n{\n /* applies a householder transformation v,tau to matrix m from the\n right hand side in order to zero out rows */\n\n if (tau == 0)\n return GSL_SUCCESS;\n\n /* A = A - tau w v' */\n\n#ifdef USE_BLAS\n {\n gsl_vector_const_view v1 = gsl_vector_const_subvector (v, 1, v->size - 1);\n gsl_matrix_view A1 = gsl_matrix_submatrix (A, 0, 1, A->size1, A->size2-1);\n size_t i;\n\n for (i = 0; i < A->size1; i++)\n {\n double wi = 0.0;\n gsl_vector_view A1i = gsl_matrix_row(&A1.matrix, i);\n gsl_blas_ddot (&A1i.vector, &v1.vector, &wi);\n wi += gsl_matrix_get(A,i,0); \n \n {\n double Ai0 = gsl_matrix_get (A, i, 0);\n gsl_matrix_set (A, i, 0, Ai0 - tau * wi);\n }\n \n gsl_blas_daxpy(-tau * wi, &v1.vector, &A1i.vector);\n }\n }\n#else\n {\n size_t i, j;\n \n for (i = 0; i < A->size1; i++)\n {\n double wi = gsl_matrix_get(A,i,0); \n \n for (j = 1; j < A->size2; j++) /* note, computed for v(0) = 1 above */\n {\n wi += gsl_matrix_get(A,i,j) * gsl_vector_get(v,j);\n }\n \n /* j = 0 */\n \n {\n double Ai0 = gsl_matrix_get (A, i, 0);\n gsl_matrix_set (A, i, 0, Ai0 - tau * wi);\n }\n \n /* j = 1 .. N-1 */\n \n for (j = 1; j < A->size2; j++) \n {\n double vj = gsl_vector_get (v, j);\n double Aij = gsl_matrix_get (A, i, j);\n gsl_matrix_set (A, i, j, Aij - tau * wi * vj);\n }\n }\n }\n#endif\n \n return GSL_SUCCESS;\n}\n\nint\ngsl_linalg_householder_hv (double tau, const gsl_vector * v, gsl_vector * w)\n{\n /* applies a householder transformation v to vector w */\n const size_t N = v->size;\n \n if (tau == 0)\n return GSL_SUCCESS ;\n\n {\n /* compute d = v'w */\n\n double d0 = gsl_vector_get(w,0);\n double d1, d;\n\n gsl_vector_const_view v1 = gsl_vector_const_subvector(v, 1, N-1);\n gsl_vector_view w1 = gsl_vector_subvector(w, 1, N-1);\n\n gsl_blas_ddot (&v1.vector, &w1.vector, &d1);\n \n d = d0 + d1;\n\n /* compute w = w - tau (v) (v'w) */\n \n {\n double w0 = gsl_vector_get (w,0);\n gsl_vector_set (w, 0, w0 - tau * d);\n }\n \n gsl_blas_daxpy (-tau * d, &v1.vector, &w1.vector);\n }\n \n return GSL_SUCCESS;\n}\n\n\nint\ngsl_linalg_householder_hm1 (double tau, gsl_matrix * A)\n{\n /* applies a householder transformation v,tau to a matrix being\n build up from the identity matrix, using the first column of A as\n a householder vector */\n\n if (tau == 0)\n {\n size_t i,j;\n\n gsl_matrix_set (A, 0, 0, 1.0);\n \n for (j = 1; j < A->size2; j++)\n {\n gsl_matrix_set (A, 0, j, 0.0);\n }\n\n for (i = 1; i < A->size1; i++)\n {\n gsl_matrix_set (A, i, 0, 0.0);\n }\n\n return GSL_SUCCESS;\n }\n\n /* w = A' v */\n\n#ifdef USE_BLAS\n {\n gsl_matrix_view A1 = gsl_matrix_submatrix (A, 1, 0, A->size1 - 1, A->size2);\n gsl_vector_view v1 = gsl_matrix_column (&A1.matrix, 0);\n size_t j;\n\n for (j = 1; j < A->size2; j++)\n {\n double wj = 0.0; /* A0j * v0 */\n \n gsl_vector_view A1j = gsl_matrix_column(&A1.matrix, j);\n gsl_blas_ddot (&A1j.vector, &v1.vector, &wj);\n\n /* A = A - tau v w' */\n \n gsl_matrix_set (A, 0, j, - tau * wj);\n \n gsl_blas_daxpy(-tau*wj, &v1.vector, &A1j.vector);\n }\n\n gsl_blas_dscal(-tau, &v1.vector);\n \n gsl_matrix_set (A, 0, 0, 1.0 - tau);\n }\n#else\n {\n size_t i, j;\n \n for (j = 1; j < A->size2; j++)\n {\n double wj = 0.0; /* A0j * v0 */\n \n for (i = 1; i < A->size1; i++)\n {\n double vi = gsl_matrix_get(A, i, 0);\n wj += gsl_matrix_get(A,i,j) * vi;\n }\n \n /* A = A - tau v w' */\n \n gsl_matrix_set (A, 0, j, - tau * wj);\n \n for (i = 1; i < A->size1; i++)\n {\n double vi = gsl_matrix_get (A, i, 0);\n double Aij = gsl_matrix_get (A, i, j);\n gsl_matrix_set (A, i, j, Aij - tau * vi * wj);\n }\n }\n \n for (i = 1; i < A->size1; i++)\n {\n double vi = gsl_matrix_get(A, i, 0);\n gsl_matrix_set(A, i, 0, -tau * vi);\n }\n \n gsl_matrix_set (A, 0, 0, 1.0 - tau);\n }\n#endif\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "65a6385cc91be94a7959a8831939e19c2ac82d27", "size": 8269, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/linalg/householder.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/linalg/householder.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/linalg/householder.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": 24.3205882353, "max_line_length": 91, "alphanum_fraction": 0.5125166284, "num_tokens": 2681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6231470109268232}} {"text": "#include \n#include \n\nint main(void)\n{\n double x = 5.0;\n double y = gsl_sf_bessel_J0(x);\n printf(\"J0(%g) = %.18e\\n\", x, y);\n return 0;\n}", "meta": {"hexsha": "f87c49b4c5263382284660bd7637de98c92f1afd", "size": 169, "ext": "c", "lang": "C", "max_stars_repo_path": "numericalAnalysis/gnulibrary/bessel.c", "max_stars_repo_name": "jbelmont/algorithms-workshop", "max_stars_repo_head_hexsha": "0fab83dea364f0a3850c52c8c607908676573a2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-23T00:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-17T01:57:43.000Z", "max_issues_repo_path": "numericalAnalysis/gnulibrary/bessel.c", "max_issues_repo_name": "jbelmont/algorithms-workshop", "max_issues_repo_head_hexsha": "0fab83dea364f0a3850c52c8c607908676573a2e", "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": "numericalAnalysis/gnulibrary/bessel.c", "max_forks_repo_name": "jbelmont/algorithms-workshop", "max_forks_repo_head_hexsha": "0fab83dea364f0a3850c52c8c607908676573a2e", "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": 16.9, "max_line_length": 35, "alphanum_fraction": 0.6094674556, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6228274099628193}} {"text": "#include \n#include \n#include \n#include \"nmcalc.h\"\n\nvoid get_ab(struct variant_table *v, struct variant_counts **a, struct variant_counts **b);\n\n// Convenience function to mimic MATLAB function\nstatic inline double binopdf(unsigned int x, unsigned int n, double p) {\n\treturn gsl_ran_binomial_pdf(x, p, n);\n}\n\n#define NONZERO_OR_NAN(X, NAN_CODE) ((X) == (X) ? (X) : nan(#NAN_CODE))\n\nvoid nmcalc(struct context *context,\n struct variant_table *v,\n double prior_map_error,\n int ploidy,\n struct nm_entry *out)\n{\n\t(void) context;\n\n\tdouble a_read_depth, b_read_depth;\n\tdouble a_mean_mq, b_mean_mq;\n\n\tdouble prior_hom, prior_het;\n\tdouble p_data_map_error, p_data_hom, p_data_het, p_data;\n\tdouble p_map_error;\n\n\tdouble per_read_pass, ab_frac;\n\n\tstruct variant_counts *a, *b;\n\n\tget_ab(v, &a, &b);\n\n\t// Initialization of useful variables\n\n\ta_read_depth = (a->count_f + a->count_r) / 2.0;\n\tb_read_depth = (b->count_f + b->count_r) / 2.0;\n\n\ta_mean_mq = a->total_mq / NONZERO_OR_NAN(a_read_depth, 200);\n\tb_mean_mq = b->total_mq / NONZERO_OR_NAN(b_read_depth, 200);\n\n\t// Normal metrics calculation starts here\n\n\t// priors\n\tif (ploidy == 2) {\n\t\tprior_het = 2 * a->pop_af * b->pop_af;\n\t} else {\n\t\tprior_het = 0;\n\t}\n\n\tprior_hom = a->pop_af * a->pop_af;\n\n\t// likelihoods\n\tp_data_map_error = pow(10, -fmin(a_mean_mq, b_mean_mq)/10);\n\tp_data_hom = binopdf(b_read_depth, v->read_count_pass, pow(10, (-b_mean_mq / 10)));\n\tp_data_het = binopdf(b_read_depth, v->read_count_pass, 0.5);\n\n\tp_data = prior_map_error * p_data_map_error + prior_het * p_data_het + prior_hom * p_data_hom;\n\n\t// posteriors\n\tif (v->read_count_pass > 0) {\n\t\tp_map_error = prior_map_error * p_data_map_error / p_data;\n\t} else {\n\t\tp_map_error = nan(\"300\");\n\t}\n\n\t// other metrics\n\tper_read_pass = v->read_count_pass / NONZERO_OR_NAN(v->read_count, 200);\n\n\tab_frac = (a_read_depth + b_read_depth) / NONZERO_OR_NAN(v->read_count_pass, 200);\n\n\tout->pos = v->offset;\n\n\tif (ploidy == 1 || ploidy == 2) {\n\t\tout->norm_read_depth = (3-ploidy) * v->read_count_pass; // sneak\n\t\tout->prob_map_err = p_map_error;\n\t\tout->read_pass = per_read_pass;\n\t\tout->a_or_b = ab_frac;\n\t} else {\n\t\tout->norm_read_depth = nan(\"101\");\n\t\tout->prob_map_err = nan(\"102\");\n\t\tout->read_pass = nan(\"103\");\n\t\tout->a_or_b = nan(\"104\");\n\t}\n}\n", "meta": {"hexsha": "08c456412c2fa0bca8145c2d6580d380dc30f2c2", "size": 2333, "ext": "c", "lang": "C", "max_stars_repo_path": "src/nmcalc.c", "max_stars_repo_name": "tgen/gvm", "max_stars_repo_head_hexsha": "eaa664f584b23864244b33d27797e31d12c4ab07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T02:18:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-12T11:40:43.000Z", "max_issues_repo_path": "src/nmcalc.c", "max_issues_repo_name": "tgen/gvm", "max_issues_repo_head_hexsha": "eaa664f584b23864244b33d27797e31d12c4ab07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T22:37:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T20:44:42.000Z", "max_forks_repo_path": "src/nmcalc.c", "max_forks_repo_name": "tgen/gvm", "max_forks_repo_head_hexsha": "eaa664f584b23864244b33d27797e31d12c4ab07", "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.5113636364, "max_line_length": 95, "alphanum_fraction": 0.6853836262, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6227361856816079}} {"text": "static char help[] =\n\"Solves structured-grid Poisson problem in 1D, 2D, 3D. Option prefix fsh_.\\n\"\n\"Equation is\\n\"\n\" - cx u_xx - cy u_yy - cz u_zz = f,\\n\"\n\"subject to Dirichlet boundary conditions. Solves three different problems\\n\"\n\"where exact solution is known. Uses DMDA and SNES. Equation is put in form\\n\"\n\"F(u) = - grad^2 u - f. Call-backs fully-rediscretize for the supplied grid.\\n\"\n\"Defaults to 2D, a SNESType of KSPONLY, and a KSPType of CG.\\n\\n\";\n\n#include \n#include \"poissonfunctions.h\"\n\n// exact solutions u(x,y), for boundary condition and error calculation\n\nstatic double u_exact_1Dmanupoly(double x, double y, double z, void *ctx) {\n return x*x * (1.0 - x*x);\n}\n\nstatic double u_exact_2Dmanupoly(double x, double y, double z, void *ctx) {\n return x*x * (1.0 - x*x) * y*y *(y*y - 1.0);\n}\n\nstatic double u_exact_3Dmanupoly(double x, double y, double z, void *ctx) {\n return x*x * (1.0 - x*x) * y*y * (y*y - 1.0) * z*z * (z*z - 1.0);\n}\n\nstatic double u_exact_1Dmanuexp(double x, double y, double z, void *ctx) {\n return - exp(x);\n}\n\nstatic double u_exact_2Dmanuexp(double x, double y, double z, void *ctx) {\n return - x * exp(y);\n}\n\nstatic double u_exact_3Dmanuexp(double x, double y, double z, void *ctx) {\n return - x * exp(y + z);\n}\n\nstatic double zero(double x, double y, double z, void *ctx) {\n return 0.0;\n}\n\n// right-hand-side functions f(x,y) = - laplacian u\n\nstatic double f_rhs_1Dmanupoly(double x, double y, double z, void *ctx) {\n PoissonCtx* user = (PoissonCtx*)ctx;\n return user->cx * 12.0 * x*x - 2.0;\n}\n\nstatic double f_rhs_2Dmanupoly(double x, double y, double z, void *ctx) {\n PoissonCtx* user = (PoissonCtx*)ctx;\n double aa, bb, ddaa, ddbb;\n aa = x*x * (1.0 - x*x);\n bb = y*y * (y*y - 1.0);\n ddaa = 2.0 * (1.0 - 6.0 * x*x);\n ddbb = 2.0 * (6.0 * y*y - 1.0);\n return - (user->cx * ddaa * bb + user->cy * aa * ddbb);\n}\n\nstatic double f_rhs_3Dmanupoly(double x, double y, double z, void *ctx) {\n PoissonCtx* user = (PoissonCtx*)ctx;\n double aa, bb, cc, ddaa, ddbb, ddcc;\n aa = x*x * (1.0 - x*x);\n bb = y*y * (y*y - 1.0);\n cc = z*z * (z*z - 1.0);\n ddaa = 2.0 * (1.0 - 6.0 * x*x);\n ddbb = 2.0 * (6.0 * y*y - 1.0);\n ddcc = 2.0 * (6.0 * z*z - 1.0);\n return - (user->cx * ddaa * bb * cc + user->cy * aa * ddbb * cc + user->cz * aa * bb * ddcc);\n}\n\nstatic double f_rhs_1Dmanuexp(double x, double y, double z, void *ctx) {\n return exp(x);\n}\n\nstatic double f_rhs_2Dmanuexp(double x, double y, double z, void *ctx) {\n return x * exp(y); // note f = - (u_xx + u_yy) = - u\n}\n\nstatic double f_rhs_3Dmanuexp(double x, double y, double z, void *ctx) {\n return 2.0 * x * exp(y + z); // note f = - laplacian u = - 2 u\n}\n\n// functions simply to put u_exact()=g_bdry() into a grid\n// these are irritatingly-dimension-dependent inside ...\nextern PetscErrorCode Form1DUExact(DMDALocalInfo*, Vec, PoissonCtx*);\nextern PetscErrorCode Form2DUExact(DMDALocalInfo*, Vec, PoissonCtx*);\nextern PetscErrorCode Form3DUExact(DMDALocalInfo*, Vec, PoissonCtx*);\n\n//STARTPTRARRAYS\n// arrays of pointers to functions: ..._ptr[DIMS]\nstatic void* residual_ptr[3]\n = {&Poisson1DFunctionLocal, &Poisson2DFunctionLocal, &Poisson3DFunctionLocal};\n\nstatic void* jacobian_ptr[3]\n = {&Poisson1DJacobianLocal, &Poisson2DJacobianLocal, &Poisson3DJacobianLocal};\n\nstatic void* getuexact_ptr[3]\n = {&Form1DUExact, &Form2DUExact, &Form3DUExact};\n//ENDPTRARRAYS\n\ntypedef enum {MANUPOLY, MANUEXP, ZERO} ProblemType;\nstatic const char* ProblemTypes[] = {\"manupoly\",\"manuexp\",\"zero\",\n \"ProblemType\", \"\", NULL};\n\n// more arrays of pointers to functions: ..._ptr[DIMS][PROBLEMS]\nstatic void* g_bdry_ptr[3][3]\n = {{&u_exact_1Dmanupoly, &u_exact_1Dmanuexp, &zero},\n {&u_exact_2Dmanupoly, &u_exact_2Dmanuexp, &zero},\n {&u_exact_3Dmanupoly, &u_exact_3Dmanuexp, &zero}};\n\nstatic void* f_rhs_ptr[3][3]\n = {{&f_rhs_1Dmanupoly, &f_rhs_1Dmanuexp, &zero},\n {&f_rhs_2Dmanupoly, &f_rhs_2Dmanuexp, &zero},\n {&f_rhs_3Dmanupoly, &f_rhs_3Dmanuexp, &zero}};\n\nstatic const char* InitialTypes[] = {\"zeros\",\"random\",\n \"InitialType\", \"\", NULL};\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;\n PoissonCtx user;\n DMDALocalInfo info;\n double errinf, normconst2h, err2h;\n char gridstr[99];\n PetscErrorCode (*getuexact)(DMDALocalInfo*,Vec,PoissonCtx*);\n\n // fish defaults:\n int dim = 2; // 2D\n ProblemType problem = MANUEXP; // manufactured problem using exp()\n InitialType initial = ZEROS; // set u=0 for initial iterate\n PetscBool gonboundary = PETSC_TRUE; // initial iterate has u=g on boundary\n\n // get options and configure context\n user.Lx = 1.0;\n user.Ly = 1.0;\n user.Lz = 1.0;\n user.cx = 1.0;\n user.cy = 1.0;\n user.cz = 1.0;\n PetscInitialize(&argc,&argv,NULL,help);\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD,\"fsh_\", \"options for fish.c\", \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-cx\",\n \"set coefficient of x term u_xx in equation\",\n \"fish.c\",user.cx,&user.cx,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-cy\",\n \"set coefficient of y term u_yy in equation\",\n \"fish.c\",user.cy,&user.cy,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-cz\",\n \"set coefficient of z term u_zz in equation\",\n \"fish.c\",user.cz,&user.cz,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsInt(\"-dim\",\n \"dimension of problem (=1,2,3 only)\",\n \"fish.c\",dim,&dim,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-initial_gonboundary\",\n \"set initial iterate to have correct boundary values\",\n \"fish.c\",gonboundary,&gonboundary,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-initial_type\",\n \"type of initial iterate\",\n \"fish.c\",InitialTypes,(PetscEnum)initial,(PetscEnum*)&initial,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Lx\",\n \"set Lx in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)\",\n \"fish.c\",user.Lx,&user.Lx,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Ly\",\n \"set Ly in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)\",\n \"fish.c\",user.Ly,&user.Ly,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Lz\",\n \"set Ly in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)\",\n \"fish.c\",user.Lz,&user.Lz,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnum(\"-problem\",\n \"problem type; determines exact solution and RHS\",\n \"fish.c\",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem,NULL); CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n user.g_bdry = g_bdry_ptr[dim-1][problem];\n user.f_rhs = f_rhs_ptr[dim-1][problem];\n if ( user.cx <= 0.0 || user.cy <= 0.0 || user.cz <= 0.0 ) {\n SETERRQ(PETSC_COMM_WORLD,2,\"positivity required for coefficients cx,cy,cz\\n\");\n }\n if ((problem == MANUEXP) && ( user.cx != 1.0 || user.cy != 1.0 || user.cz != 1.0)) {\n SETERRQ(PETSC_COMM_WORLD,3,\"cx=cy=cz=1 required for problem MANUEXP\\n\");\n }\n\n//STARTCREATE\n // DMDA in chosen dimension\n switch (dim) {\n case 1:\n ierr = DMDACreate1d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE,3,1,1, NULL, &da); CHKERRQ(ierr);\n break;\n case 2:\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,\n 3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);\n break;\n case 3:\n ierr = DMDACreate3d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE,\n DMDA_STENCIL_STAR,\n 3,3,3,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE,\n 1,1,NULL,NULL,NULL,&da); CHKERRQ(ierr);\n break;\n default:\n SETERRQ(PETSC_COMM_WORLD,1,\"invalid dim for DMDA creation\\n\");\n }\n ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr); // call BEFORE SetUniformCoordinates\n ierr = DMDASetUniformCoordinates(da,0.0,user.Lx,0.0,user.Ly,0.0,user.Lz); CHKERRQ(ierr);\n\n // create SNES supply call-backs\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)(residual_ptr[dim-1]),&user); CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)(jacobian_ptr[dim-1]),&user); CHKERRQ(ierr);\n\n // default to KSPONLY+CG because problem is linear and SPD\n ierr = SNESSetType(snes,SNESKSPONLY); 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 and solve\n ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr);\n ierr = InitialState(da, initial, gonboundary, u_initial, &user); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);\n//ENDCREATE\n\n//STARTGETSOLUTION\n // -snes_grid_sequence could change grid resolution\n ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n\n // evaluate error and report\n ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); // SNES owns u; do not destroy it\n ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr); // SNES owns da_after; do not destroy it\n ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);\n getuexact = getuexact_ptr[dim-1];\n ierr = (*getuexact)(&info,u_exact,&user); CHKERRQ(ierr);\n ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact\n ierr = VecDestroy(&u_exact); CHKERRQ(ierr); // no longer needed\n ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr);\n ierr = VecNorm(u,NORM_2,&err2h); CHKERRQ(ierr);\n//ENDGETSOLUTION\n\n switch (dim) {\n case 1:\n normconst2h = PetscSqrtReal((double)(info.mx-1));\n snprintf(gridstr,99,\"%d point 1D\",info.mx);\n break;\n case 2:\n normconst2h = PetscSqrtReal((double)(info.mx-1)*(info.my-1));\n snprintf(gridstr,99,\"%d x %d point 2D\",info.mx,info.my);\n break;\n case 3:\n normconst2h = PetscSqrtReal((double)(info.mx-1)*(info.my-1)*(info.mz-1));\n snprintf(gridstr,99,\"%d x %d x %d point 3D\",info.mx,info.my,info.mz);\n break;\n default:\n SETERRQ(PETSC_COMM_WORLD,4,\"invalid dim value in final report\\n\");\n }\n err2h /= normconst2h; // like continuous L2\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"problem %s on %s grid:\\n\"\n \" error |u-uexact|_inf = %.3e, |u-uexact|_h = %.3e\\n\",\n ProblemTypes[problem],gridstr,errinf,err2h); CHKERRQ(ierr);\n\n // destroy what we explicitly Created\n ierr = SNESDestroy(&snes); CHKERRQ(ierr);\n return PetscFinalize();\n}\n\nPetscErrorCode Form1DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {\n PetscErrorCode ierr;\n int i;\n double xmax[1], xmin[1], hx, x, *au;\n ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);\n hx = (xmax[0] - xmin[0]) / (info->mx - 1);\n ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);\n for (i=info->xs; ixs+info->xm; i++) {\n x = xmin[0] + i * hx;\n au[i] = user->g_bdry(x,0.0,0.0,user);\n }\n ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode Form2DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {\n PetscErrorCode ierr;\n int i, j;\n double xymin[2], xymax[2], hx, hy, x, y, **au;\n ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);\n hx = (xymax[0] - xymin[0]) / (info->mx - 1);\n hy = (xymax[1] - xymin[1]) / (info->my - 1);\n ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);\n for (j=info->ys; jys+info->ym; j++) {\n y = xymin[1] + j * hy;\n for (i=info->xs; ixs+info->xm; i++) {\n x = xymin[0] + i * hx;\n au[j][i] = user->g_bdry(x,y,0.0,user);\n }\n }\n ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode Form3DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {\n PetscErrorCode ierr;\n int i, j, k;\n double xyzmin[3], xyzmax[3], hx, hy, hz, x, y, z, ***au;\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 ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);\n for (k=info->zs; kzs+info->zm; k++) {\n z = xyzmin[2] + k * hz;\n for (j=info->ys; jys+info->ym; j++) {\n y = xyzmin[1] + j * hy;\n for (i=info->xs; ixs+info->xm; i++) {\n x = xyzmin[0] + i * hx;\n au[k][j][i] = user->g_bdry(x,y,z,user);\n }\n }\n }\n ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);\n return 0;\n}\n\n", "meta": {"hexsha": "7fe36007c28c45b140cff10c6ae37bba048c87c3", "size": 13387, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch6/fish.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/fish.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/fish.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": 39.8422619048, "max_line_length": 97, "alphanum_fraction": 0.6069320983, "num_tokens": 4367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928951399098, "lm_q2_score": 0.7981867873410141, "lm_q1q2_score": 0.6225800231205411}} {"text": "// Use the geodesic solver code to create a gsl implementation so you can\n// compare the speeds. The template needs to get close to ,ideally better than,\n// exactly to the gsl run times\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst double alpha = 1.32754125e20;\nint odefunc (double x, const double y[], double f[], void *params)\n{\n f[0] = y[3];\n f[1] = y[4];\n f[2] = y[5];\n double r = sqrt(y[0]*y[0]+y[1]*y[1]+y[2]*y[2]);\n\n f[3] = -(alpha*y[0]) / (r*r*r);\n f[4] = -(alpha*y[1]) / (r*r*r);\n f[5] = -(alpha*y[2]) / (r*r*r);\n return GSL_SUCCESS;\n}\n\n\nint main ()\n{\n double AU = 1.496e11; // astronomical unit\n double V = 30000.0; // initial velocity\n // initial conditions\n double y0[] = {0.0,AU,0.0,-V,0.0,0.0}; \n double T0 = 0.0;\n double Tf = 7.2e6;\n double hi = 7.2e3/3;\n int dim = 6;\n gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};\n\n gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, hi, 1e-5, 0.0);\n auto Nruns = 5000;\n auto totalDuration = 0;\n auto t1 = std::chrono::high_resolution_clock::now();\n double T;\n for (int i = 1; i <= Nruns; i++)\n {\n T0 = 0.0;\n T = Tf;\n y0[0]=0.0;\n y0[1] = AU;\n y0[2] = 0.0;\n y0[3] = -V;\n y0[4] = 0.0;\n y0[5] = 0.0;\n gsl_odeiv2_driver_apply (d, &T0, T, y0);\n }\n\n auto t2 = std::chrono::high_resolution_clock::now();\n auto duration = std::chrono::duration_cast( t2 - t1 ).count();\n totalDuration += duration;\n std::cout << \"GSL runs\" << std::endl;\n std::cout << totalDuration/Nruns << std::endl;\n for(int j = 0 ; j < 6 ; j++)\n {\n std::cout << y0[j] << \",\";\n }\n std::cout << std::endl;\n gsl_odeiv2_driver_free (d);\n return 0;\n}", "meta": {"hexsha": "0ea776fb8b030e6e2d3cf0474496ae4e6a38d8b3", "size": 1921, "ext": "c", "lang": "C", "max_stars_repo_path": "gccExample/newton.c", "max_stars_repo_name": "jman27182818/RKF45", "max_stars_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d", "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": "gccExample/newton.c", "max_issues_repo_name": "jman27182818/RKF45", "max_issues_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-06-28T22:42:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T00:55:14.000Z", "max_forks_repo_path": "gccExample/newton.c", "max_forks_repo_name": "jman27182818/RKF45", "max_forks_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T17:13:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T17:13:40.000Z", "avg_line_length": 27.4428571429, "max_line_length": 103, "alphanum_fraction": 0.5611660593, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6221827377690023}} {"text": "//\n// trsm.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 1/5/12.\n// Copyright (c) 2012 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _trsm_h\n#define _trsm_h\n\n/// @file trsm.h Solves triangular matrix equations.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Solves a real triangular matrix equation.\n /// \n /// For a real upper or lower triangular matrix A, real rectangular matrix B and real scalar alpha,\n ///\n /// A*X=alpha*B or A'*X=alpha*B or X*A=alpha*B or X*A'=alpha*B\n /// is solved for the matrix X.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param side Specifies whether the matrix A appears on the left or right side as follows:\n ///\n /// if side = 'L' or 'l' then A*X=alpha*B or A'*X=alpha*B is solved\n /// if side = 'R' or 'r' then X*A=alpha*B or X*A'=alpha*B is solved\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 /// @param trans Specifies whether the transpose or conjugate transpose of A is to be used:\n ///\n /// if trans = 'N' or 'n' then A*X=alpha*B or X*A=alpha*B is solved\n /// if trans = 'T' or 't' then A'*X=alpha*B or X*A'=alpha*B is solved\n /// if trans = 'C' or 'c' then A'*X=alpha*B or X*A'=alpha*B is solved\n /// @param diag specifies whether or not A is unit triangular as follows:\n ///\n /// if diag = 'U' or 'u' then A is assumed to be unit triangular\n /// if diag = 'N' or 'n' then A is not assumed to be unit triangular.\n /// If A is unit triangular, the diagonal elements are assumed to be unity and are not referenced.\n /// @param m Specifies the number of rows of the matrix B. m>=0\n /// @param n Specifies the number of columns of the matrix B. n>=0\n /// @param alpha Real scalar.\n /// @param A Pointer to real triangular matrix A. The order of A is n if side = 'L' or 'l';\n /// the order of A is m is side = 'R' or 'r'.\n /// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced. \n /// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced.\n /// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then ldA>=m.\n /// @param B Pointer to real m-by-n matrix B. On entry, B contains the right hand side matrix B. \n /// On exit, B is overwritten with the solution matrix X.\n /// @param ldB Column length of the matrix B. ldB>=m.\n /// @ingroup BLAS\n\n template \n int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB)\n {\n using std::toupper;\n\n const real_t zero(0.0);\n const real_t one(1.0);\n int_t i,j,k;\n real_t *a,*b,*bt;\n real_t t;\n bool nounit;\n\n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n\n nounit=(diag=='N')?1:0;\n \n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB=0;k--)\n {\n a-=ldA;\n if(nounit)\n b[k]=b[k]/a[k];\n for(i=0;i=0;i--)\n {\n a-=ldA;\n t=alpha*b[i];\n for(k=i+1;k=0;j--)\n {\n a-=ldA;\n b-=ldB;\n for(i=0;i=0;k--)\n {\n a-=ldA;\n b-=ldB;\n if(nounit)\n {\n t=one/a[k];\n for(i=0;i=0\n /// @param n Specifies the number of columns of the matrix B. n>=0\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex triangular matrix A. The order of A is n if side = 'L' or 'l';\n /// the order of A is m is side = 'R' or 'r'.\n /// If uplo = 'U' or 'u, A is upper triangular and the lower triangular part is not referenced. \n /// If uplo = 'L' or 'l A is lower triangular and the upper triangular part is not referenced.\n /// @param ldA Column length of the matrix A. If side='L' or 'l' then ldA>=n; if side='R' or 'r' then ldA>=m.\n /// @param B Pointer to complex m-by-n matrix B. On entry, B contains the right hand side matrix B. \n /// On exit, B is overwritten with the solution matrix X.\n /// @param ldB Column length of the matrix B. ldB>=m.\n /// @ingroup BLAS\n\n template \n int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB)\n {\n \n using std::conj;\n using std::toupper;\n const complex zero(0.0,0.0);\n const complex one(1.0,0.0);\n int_t i,j,k;\n complex *a,*b,*bt;\n complex t;\n bool nounit;\n \n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n\n nounit=(diag=='N')?1:0;\n \n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB=0;k--)\n {\n a-=ldA;\n if(nounit)\n b[k]=b[k]/a[k];\n for(i=0;i=0;i--)\n {\n a-=ldA;\n t=alpha*b[i];\n for(k=i+1;k=0;i--)\n {\n a-=ldA;\n t=alpha*b[i];\n for(k=i+1;k=0;j--)\n {\n a-=ldA;\n b-=ldB;\n for(i=0;i=0;k--)\n {\n a-=ldA;\n b-=ldB;\n if(nounit)\n {\n t=one/a[k];\n for(i=0;i=0;k--)\n {\n a-=ldA;\n b-=ldB;\n if(nounit)\n {\n t=one/conj(a[k]);\n for(i=0;i\n\n template <> int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, float alpha, float *A, int_t ldA, float *B, int_t ldB)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, double alpha, double *A, int_t ldA, double *B, int_t ldB)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB int TRSM(char side, char uplo, char trans, char diag, int_t m, int_t n, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB)\n {\n using std::toupper;\n side=toupper(side);\n uplo=toupper(uplo);\n trans=toupper(trans);\n diag=toupper(diag);\n if((side!='L')&&(side!='R'))\n return -1;\n else if((uplo!='U')&&(uplo!='L'))\n return -2;\n else if((trans!='N')&&(trans!='T')&&(trans!='C'))\n return -3;\n else if((diag!='U')&&(diag!='N'))\n return -4;\n else if(m<0)\n return -5;\n else if(n<0)\n return -6;\n else if(ldA<((side=='L')?m:n))\n return -9;\n else if(ldB\n\nint main(int argc,char **args) {\n PetscErrorCode ierr;\n Vec x, b;\n Mat A;\n KSP ksp;\n PetscInt i, j[4] = {0, 1, 2, 3}; // j = column index\n PetscReal ab[4] = {7.0, 1.0, 1.0, 3.0}, // vector entries\n aA[4][4] = {{ 1.0, 2.0, 3.0, 0.0}, // matrix entries\n { 2.0, 1.0, -2.0, -3.0},\n {-1.0, 1.0, 1.0, 0.0},\n { 0.0, 1.0, 1.0, -1.0}};\n\n ierr = PetscInitialize(&argc,&args,NULL,help); if (ierr) return ierr;\n\n ierr = VecCreate(PETSC_COMM_WORLD,&b); CHKERRQ(ierr);\n ierr = VecSetSizes(b,PETSC_DECIDE,4); CHKERRQ(ierr);\n ierr = VecSetFromOptions(b); CHKERRQ(ierr);\n ierr = VecSetValues(b,4,j,ab,INSERT_VALUES); CHKERRQ(ierr);\n ierr = VecAssemblyBegin(b); CHKERRQ(ierr);\n ierr = VecAssemblyEnd(b); CHKERRQ(ierr);\n\n ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);\n ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,4,4); CHKERRQ(ierr);\n ierr = MatSetFromOptions(A); CHKERRQ(ierr);\n ierr = MatSetUp(A); CHKERRQ(ierr);\n for (i=0; i<4; i++) { // set entries one row at a time\n ierr = MatSetValues(A,1,&i,4,j,aA[i],INSERT_VALUES); CHKERRQ(ierr);\n }\n ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);\n\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 = VecDuplicate(b,&x); CHKERRQ(ierr);\n ierr = KSPSolve(ksp,b,x); CHKERRQ(ierr);\n ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);\n\n KSPDestroy(&ksp); MatDestroy(&A);\n VecDestroy(&x); VecDestroy(&b);\n return PetscFinalize();\n}\n//ENDWHOLE\n\n", "meta": {"hexsha": "10d8f2d7455bf859fbf725bbd5348b64cf575c74", "size": 1915, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch2/vecmatksp.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/ch2/vecmatksp.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/ch2/vecmatksp.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": 38.3, "max_line_length": 75, "alphanum_fraction": 0.5859007833, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.62208416508097}} {"text": "/* \n* C functions for the NIG marginal distribution.\n*\n* This file is part of Fieldosophy, a toolkit for random fields.\n*\n* Copyright (C) 2021 Anders Gunnar Felix Hildeman \n*\n* This Source Code is subject to the terms of the BSD 3-Clause License.\n* If a copy of the license was not distributed with this file, you can obtain one at https://opensource.org/licenses/BSD-3-Clause.\n*\n*\n* Author: Anders Gunnar Felix Hildeman\n* Date: 2020-04\n*/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\nextern \"C\"\n{\n \n // Make sure that alpha tilde is not too large\n void NIG_filterParams( double *pAlphaTilde, double *pBetaTilde)\n { \n if (*pAlphaTilde > 100.0d)\n {\n *pBetaTilde = *pBetaTilde * ( 100.0d / (*pAlphaTilde) );\n *pAlphaTilde = 100.0d; \n }\n \n return; \n }\n \n \n\n\n // Modified Bessel function of the second kind\n double Kv(const int v, const double x)\n {\n double lOut = 0.0d;\n int status;\n \n gsl_sf_result result;\n \n switch(v)\n {\n case 0:\n status = gsl_sf_bessel_K0_e(x, &result);\n break;\n case 1:\n status = gsl_sf_bessel_K1_e(x, &result);\n break;\n default:\n status = gsl_sf_bessel_Kn_e(v, x, &result);\n break; \n }\n \n // If some kind of error\n if (status != 0)\n {\n //printf(\"Error code: %d in Kv\", status);\n lOut = GSL_NAN;\n }\n else\n {\n lOut = result.val;\n }\n \n \n return lOut;\n }\n \n // Logarithm of modified Bessel function of second kind\n double lKv(const int v, const double x)\n {\n double lOut = Kv( v, x ); \n // Logarithmize\n lOut = log( lOut );\n \n return lOut;\n } \n\n\n\n // logarithm of PDF for NIG distribution\n unsigned int NIG_lpdf( double * const pX, const unsigned int pN, const double alphaTilde, const double betaTilde, const double mu, const double delta ) \n {\n // turn off gsl error handler\n gsl_set_error_handler_off();\n \n // Loop through each element in vector \n #pragma omp parallel for\n for ( unsigned int iter = 0; iter < pN; iter++)\n {\n // Get normalized data value\n const double lCur = (pX[iter] - mu) / delta;\n // Compute q function\n const double lQ = sqrt( (1.0d + lCur * lCur) );\n // Compute bessel function\n const double lLogK = lKv(1, alphaTilde * lQ);\n \n // compute log pdf \n double lCurOut = lLogK;\n lCurOut -= log(lQ);\n lCurOut += betaTilde * lCur;\n // Add constants\n lCurOut += log( alphaTilde / M_PI ) + sqrt( alphaTilde * alphaTilde - betaTilde * betaTilde );\n lCurOut -= log(delta);\n \n // Store full log pdf\n pX[iter] = lCurOut;\n }\n \n return pN;\n }\n \n \n // Compute log-likelihood\n double NIG_logLikelihood( double * lOut, const double * const pX, const unsigned int pN, const double alphaTilde, const double betaTilde, const double mu, const double delta )\n { \n // Copy content \n memcpy( lOut, pX, sizeof(double) * pN );\n \n // Compute log-pdf\n NIG_lpdf( lOut, pN, alphaTilde, betaTilde, mu, delta );\n // Sum \n double lSum = 0.0d;\n for (unsigned int iter = 0; iter < pN; iter++)\n {\n lSum += lOut[iter];\n } \n \n return lSum;\n }\n \n \n \n // EM-algorithm for finding MLE of NIG\n unsigned int NIG_MLE( double * const pLogLik, double * const pX, const unsigned int pN, \n double * const pAlphaTilde, double * const pBetaTilde, double * const pMu, double * const pDelta,\n const double pXBar, const unsigned int pM, const double pTol ) \n {\n \n // turn off gsl error handler\n gsl_set_error_handler_off();\n \n // Init\n double lAlphaTilde = *pAlphaTilde;\n double lBetaTilde = *pBetaTilde;\n double lMu = *pMu;\n double lDelta = *pDelta;\n // Filter tilde parameters\n NIG_filterParams( &lAlphaTilde, &lBetaTilde);\n \n // Preallocate arrays\n double * lTempArray1 = (double*) malloc(sizeof(double) * pN);\n double * lTempArray2 = (double*) malloc(sizeof(double) * pN);\n if (lTempArray1 == NULL || lTempArray2 == NULL)\n return 1;\n \n // Compute log-likelihood \n *pLogLik = NIG_logLikelihood( lTempArray1, pX, pN, lAlphaTilde, lBetaTilde, lMu, lDelta );\n \n // If likelihood is bad\n if (isnan(*pLogLik))\n return 1;\n \n \n // Iterate EM-algorithm\n for (unsigned int iter = 0; iter < pM; iter++)\n {\n // --- E-step ---\n \n double lSBar = 0.0d;\n double lWBar = 0.0d; \n #pragma omp parallel for reduction(+:lSBar) reduction(+:lWBar)\n for (unsigned int iter2 = 0; iter2 < pN; iter2++)\n { \n const double lPhiSqrt = sqrt( 1.0d + ( (pX[iter2]-lMu)/lDelta ) * ( (pX[iter2]-lMu)/lDelta ) ); \n // compute besselk function values\n const double lK0 = Kv( 0, lAlphaTilde * lPhiSqrt );\n const double lK1 = Kv( 1, lAlphaTilde * lPhiSqrt );\n const double lK2 = Kv( 2, lAlphaTilde * lPhiSqrt );\n // Compute pseudo values\n lTempArray1[iter2] = ( lDelta * lPhiSqrt * lK0 ) / ( (lAlphaTilde * lK1) / lDelta ); // S\n lTempArray2[iter2] = ( (lAlphaTilde * lK2) / lDelta ) / ( lDelta * lPhiSqrt * lK1 ); // W\n lSBar += lTempArray1[iter2];\n lWBar += lTempArray2[iter2];\n }\n lSBar /= ((double)pN);\n lWBar /= ((double)pN);\n \n \n // --- M-step --- \n \n \n // Compute delta \n lDelta = sqrt( 1.0d / ( lWBar - (1.0d / lSBar) ) );\n double lGamma = lDelta / lSBar;\n // Compute beta\n double lBeta = 0.0d;\n for (unsigned int iter2 = 0; iter2 < pN; iter2++)\n {\n lBeta += pX[iter2] * lTempArray2[iter2];\n }\n lBeta = lBeta - pXBar * lWBar * ((double)pN);\n lBeta /= ( (double)pN - lSBar * lWBar * ((double)pN) );\n lBetaTilde = lBeta * lDelta;\n // Compute alpha \n double lAlpha = sqrt( lGamma * lGamma + lBeta * lBeta ); \n lAlphaTilde = lAlpha * lDelta;\n // Filter tilde values\n NIG_filterParams( &lAlphaTilde, &lBetaTilde);\n lGamma = sqrt( lAlphaTilde * lAlphaTilde - lBetaTilde * lBetaTilde ) / lDelta;\n // Compute mu\n lMu = pXBar - lBetaTilde / lGamma;\n \n // Compute loglik\n const double llLikNew = NIG_logLikelihood( lTempArray1, pX, pN, lAlphaTilde, lBetaTilde, lMu, lDelta ); \n \n // If likelihood is bad\n if (isnan(llLikNew))\n return(iter+2); // Mark that likelihood went bad during iterations\n \n // Compute likelihood difference\n const double lLLikDiff = llLikNew - *pLogLik;\n \n // If new likelihood is higher\n if (lLLikDiff > 0) \n {\n // Set new log-likelihood as old one\n *pLogLik = llLikNew;\n // Update output parameters\n *pAlphaTilde = lAlphaTilde;\n *pBetaTilde = lBetaTilde;\n *pMu = lMu;\n *pDelta = lDelta;\n \n // If should break due to tolerance\n if ( lLLikDiff < pTol )\n break; \n }\n \n } // end of EM-iterations\n \n // Free allocated arrays\n free(lTempArray1);\n free(lTempArray2);\n \n // Return no problem \n return( 0 ); \n } \n \n \n \n\n}\n\n\n", "meta": {"hexsha": "f7f52d63ecf8a94df1cf3be48ab5b41ab6811197", "size": 8558, "ext": "c", "lang": "C", "max_stars_repo_path": "fieldosophy/src/marginal/NIG.c", "max_stars_repo_name": "andyGFHill/fieldosophy", "max_stars_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-03T10:07:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:24:28.000Z", "max_issues_repo_path": "fieldosophy/src/marginal/NIG.c", "max_issues_repo_name": "andyGFHill/fieldosophy", "max_issues_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "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": "fieldosophy/src/marginal/NIG.c", "max_forks_repo_name": "andyGFHill/fieldosophy", "max_forks_repo_head_hexsha": "8677048d56b382a45a80383fe8ff84d75a5f9760", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-27T11:49:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T11:49:02.000Z", "avg_line_length": 31.9328358209, "max_line_length": 179, "alphanum_fraction": 0.4943912129, "num_tokens": 2242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.621781441688667}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\nint mcmc_sampling(char *fname_mcmc, double (* prob_fun)(double *theta))\n{\n const int n_cov_update=10000;\n double prob, prob_new, scale, ratio, u;\n double theta[ntheta], theta_new[ntheta];\n double var_cov_mat[ntheta*ntheta], Pmatrix[ntheta*ntheta], Prandvec[ntheta], Py[ntheta];\n double *theta_mcmc;\n int istep, iaccpt, i, j, info, flag;\n\n FILE *fmcmc;\n fmcmc = fopen(fname_mcmc, \"w\");\n theta_mcmc = array_malloc(ntheta*n_cov_update);\n\n/* \n * sampling in logrithm space.\n */\n memcpy(theta, theta_input, ntheta*sizeof(double));\n \n for(i=0; itheta_range[i][1])\n {\n flag = 1;\n break;\n }\n }\n }\n }\n \n prob_new = prob_fun(theta_new);\n \n ratio = prob_new - prob;\n if(ratio > 0.0)\n {\n memcpy(theta, theta_new, ntheta*sizeof(double));\n prob = prob_new;\n iaccpt++;\n }\n else\n {\n u = gsl_rng_uniform(gsl_r);\n if(log(u) < ratio)\n { \n memcpy(theta, theta_new, ntheta*sizeof(double));\n prob = prob_new;\n iaccpt++;\n }\n }\n\n for(i=0; i\n#include \n#include \n#include \n#include \n#include \n\nnamespace sens_loc::math {\n\n/// This function calculates the bearing angle between two neighbouring range\n/// measurements.\n/// \\param b reference depth and > 0\n/// \\param c prior depth and > 0\n/// \\param cos_alpha == std::cos(alpha) of the angle between two measurements\n/// \\returns bearing angle in radians\n/// \\pre b and c and positive values\n/// \\pre \\f$0 < \\cos \\alpha < 1\\f$\n/// \\post \\f$0 < result < \\pi\\f$\n///\n/// The bearing angle is angle between the ray to 'b' and the connecting line\n/// from 'c' to 'b'.\n/// It is bigger 0° and smaller 180° due to triangle constraints.\ntemplate \ninline Real\nbearing_angle(const Real b, const Real c, const Real cos_alpha) noexcept {\n static_assert(std::is_arithmetic_v);\n\n Expects(b > 0.);\n Expects(c > 0.);\n // => alpha is smaller 90°\n Expects(cos_alpha > 0.);\n // => alpha is bigger 0°\n Expects(cos_alpha < 1.);\n\n // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n const Real delta = Real(10.) * std::numeric_limits::epsilon();\n\n const Real nom = b - c * cos_alpha;\n const Real den = [&]() {\n const Real d = std::sqrt(b * b + c * c - Real(2.) * b * c * cos_alpha);\n return d == Real(0.) ? d + delta : d;\n }();\n Ensures(den != 0.);\n\n // Note: Because of inaccuracy of floating point operations it is possible\n // to get abs(ratio) == 1. This is not an error in the implementation\n // but rather an numerical artifact. To not hit the post-conditions\n // it is ok to subtract a tiny epsilon.\n const Real ratio =\n std::clamp(nom / den, Real(-1.) + delta, Real(1.) - delta);\n\n Ensures(ratio > -1.);\n Ensures(ratio < +1.);\n\n const Real result = std::acos(ratio);\n\n Ensures(result > 0.);\n Ensures(result < math::pi);\n\n return result;\n}\n\n/// This function implements the bearing angle with formula from Lin, which is\n/// incorrect.\n/// This implementation is here to verify the difference in the results\n/// and testing covers that as well.\ntemplate \ninline Real reference_lin_bearing_angle(const Real b,\n const Real c,\n const Real cos_alpha) noexcept {\n static_assert(std::is_arithmetic_v);\n\n Expects(b > 0.);\n Expects(c > 0.);\n // => alpha is smaller 90°\n Expects(cos_alpha > 0.);\n // => alpha is bigger 0°\n Expects(cos_alpha < 1.);\n\n const Real nom = (b - c * cos_alpha);\n const Real denom = (b * b + c * c - 2. * b * c * cos_alpha);\n\n const Real ratio = nom / denom;\n\n Ensures(ratio > -1.);\n Ensures(ratio < +1.);\n\n const Real result = std::acos(ratio);\n\n Ensures(result > 0.);\n Ensures(result < math::pi);\n\n return result;\n}\n\n} // namespace sens_loc::math\n\n#endif /* end of include guard: TRIANGLES_H_XWPDRVKT */\n", "meta": {"hexsha": "2353d4826fd72718ed0f410db1ff9c1d30651589", "size": 3051, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/math/triangles.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/triangles.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/triangles.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": 29.9117647059, "max_line_length": 79, "alphanum_fraction": 0.6260242543, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6216275041647245}} {"text": "static char help[] =\n\"Coupled reaction-diffusion equations (Pearson 1993). Option prefix -ptn_.\\n\"\n\"Demonstrates form F(t,Y,dot Y) = G(t,Y) where F() is IFunction and G() is\\n\"\n\"RHSFunction(). Implements IJacobian() and RHSJacobian(). Defaults to\\n\"\n\"ARKIMEX (= adaptive Runge-Kutta implicit-explicit) TS type.\\n\\n\";\n\n#include \n\ntypedef struct {\n PetscReal u, v;\n} Field;\n\ntypedef struct {\n PetscReal L, // domain side length\n Du, // diffusion coefficient: u equation\n Dv, // v equation\n phi, // \"dimensionless feed rate\" (F in Pearson 1993)\n kappa; // \"dimensionless rate constant\" (k in Pearson 1993)\n PetscBool IFcn_called, IJac_called, RHSFcn_called, RHSJac_called;\n} PatternCtx;\n\nextern PetscErrorCode InitialState(DM, Vec, PetscReal, PatternCtx*);\nextern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal, Field**,\n Field**, PatternCtx*);\nextern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, PetscReal, Field**,\n Mat, Mat, PatternCtx*);\nextern PetscErrorCode FormIFunctionLocal(DMDALocalInfo*, PetscReal, Field**, Field**,\n Field **, PatternCtx*);\nextern PetscErrorCode FormIJacobianLocal(DMDALocalInfo*, PetscReal, Field**, Field**,\n PetscReal, Mat, Mat, PatternCtx*);\n\nint main(int argc,char **argv)\n{\n PetscErrorCode ierr;\n PatternCtx user;\n TS ts;\n Vec x;\n DM da;\n DMDALocalInfo info;\n PetscReal noiselevel = -1.0; // negative value means no initial noise\n PetscBool no_rhsjacobian = PETSC_FALSE,\n no_ijacobian = PETSC_FALSE,\n call_back_report = PETSC_FALSE;\n TSType type;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\n\n // parameter values from pages 21-22 in Hundsdorfer & Verwer (2003)\n user.L = 2.5;\n user.Du = 8.0e-5;\n user.Dv = 4.0e-5;\n user.phi = 0.024;\n user.kappa = 0.06;\n user.IFcn_called = PETSC_FALSE;\n user.IJac_called = PETSC_FALSE;\n user.RHSFcn_called = PETSC_FALSE;\n user.RHSJac_called = PETSC_FALSE;\n ierr = PetscOptionsBegin(PETSC_COMM_WORLD, \"ptn_\", \"options for patterns\", \"\"); CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-call_back_report\",\"report on which user-supplied call-backs were actually called\",\n \"pattern.c\",call_back_report,&(call_back_report),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Du\",\"diffusion coefficient of first equation\",\n \"pattern.c\",user.Du,&user.Du,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-Dv\",\"diffusion coefficient of second equation\",\n \"pattern.c\",user.Dv,&user.Dv,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-kappa\",\"dimensionless rate constant (=k in (Pearson, 1993))\",\n \"pattern.c\",user.kappa,&user.kappa,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-L\",\"square domain side length; recommend L >= 0.5\",\n \"pattern.c\",user.L,&user.L,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-no_ijacobian\",\"do not set call-back DMDATSSetIJacobian()\",\n \"pattern.c\",no_ijacobian,&(no_ijacobian),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsBool(\"-no_rhsjacobian\",\"do not set call-back DMDATSSetRHSJacobian()\",\n \"pattern.c\",no_rhsjacobian,&(no_rhsjacobian),NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-noisy_init\",\n \"initialize u,v with this much random noise (e.g. 0.2) on top of usual initial values\",\n \"pattern.c\",noiselevel,&noiselevel,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsReal(\"-phi\",\"dimensionless feed rate (=F in (Pearson, 1993))\",\n \"pattern.c\",user.phi,&user.phi,NULL);CHKERRQ(ierr);\n ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_PERIODIC, DM_BOUNDARY_PERIODIC,\n DMDA_STENCIL_BOX, // for 9-point stencil\n 3,3,PETSC_DECIDE,PETSC_DECIDE,\n 2, 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 = DMDASetFieldName(da,0,\"u\"); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,1,\"v\"); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n if (info.mx != info.my) {\n SETERRQ(PETSC_COMM_SELF,1,\"pattern.c requires mx == my\");\n }\n ierr = DMDASetUniformCoordinates(da, 0.0, user.L, 0.0, user.L, -1.0, -1.0); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"running on %d x %d grid with square cells of side h = %.6f ...\\n\",\n info.mx,info.my,user.L/(PetscReal)(info.mx)); CHKERRQ(ierr);\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 if (!no_rhsjacobian) {\n ierr = DMDATSSetRHSJacobianLocal(da,\n (DMDATSRHSJacobianLocal)FormRHSJacobianLocal,&user); CHKERRQ(ierr);\n }\n ierr = DMDATSSetIFunctionLocal(da,INSERT_VALUES,\n (DMDATSIFunctionLocal)FormIFunctionLocal,&user); CHKERRQ(ierr);\n if (!no_ijacobian) {\n ierr = DMDATSSetIJacobianLocal(da,\n (DMDATSIJacobianLocal)FormIJacobianLocal,&user); CHKERRQ(ierr);\n }\n ierr = TSSetType(ts,TSARKIMEX); CHKERRQ(ierr);\n ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);\n ierr = TSSetMaxTime(ts,200.0); CHKERRQ(ierr);\n ierr = TSSetTimeStep(ts,5.0); CHKERRQ(ierr);\n ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);\n ierr = TSSetFromOptions(ts);CHKERRQ(ierr);\n//ENDTSSETUP\n\n ierr = DMCreateGlobalVector(da,&x); CHKERRQ(ierr);\n ierr = InitialState(da,x,noiselevel,&user); CHKERRQ(ierr);\n ierr = TSSolve(ts,x); CHKERRQ(ierr);\n\n // optionally report on call-backs\n if (call_back_report) {\n ierr = TSGetType(ts,&type);CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\"CALL-BACK REPORT\\n solver type: %s\\n\",type); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" IFunction: %D | IJacobian: %D\\n\",\n (int)user.IFcn_called,(int)user.IJac_called); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\" RHSFunction: %D | RHSJacobian: %D\\n\",\n (int)user.RHSFcn_called,(int)user.RHSJac_called); CHKERRQ(ierr);\n }\n\n VecDestroy(&x); TSDestroy(&ts); DMDestroy(&da);\n return PetscFinalize();\n}\n\n// Formulas from page 22 of Hundsdorfer & Verwer (2003). Interpretation here is\n// to always generate 0.5 x 0.5 non-trivial patch in (0,L) x (0,L) domain.\nPetscErrorCode InitialState(DM da, Vec Y, PetscReal noiselevel, PatternCtx* user) {\n PetscErrorCode ierr;\n DMDALocalInfo info;\n PetscInt i,j;\n PetscReal sx,sy;\n const PetscReal ledge = (user->L - 0.5) / 2.0, // nontrivial initial values on\n redge = user->L - ledge; // ledge < x,y < redge\n DMDACoor2d **aC;\n Field **aY;\n\n ierr = VecSet(Y,0.0); CHKERRQ(ierr);\n if (noiselevel > 0.0) {\n // noise added to usual initial condition is uniform on [0,noiselevel],\n // independently for each location and component\n ierr = VecSetRandom(Y,NULL); CHKERRQ(ierr);\n ierr = VecScale(Y,noiselevel); CHKERRQ(ierr);\n }\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n ierr = DMDAGetCoordinateArray(da,&aC); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,Y,&aY); 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 ((aC[j][i].x >= ledge) && (aC[j][i].x <= redge)\n && (aC[j][i].y >= ledge) && (aC[j][i].y <= redge)) {\n sx = PetscSinReal(4.0 * PETSC_PI * aC[j][i].x);\n sy = PetscSinReal(4.0 * PETSC_PI * aC[j][i].y);\n aY[j][i].v += 0.5 * sx * sx * sy * sy;\n }\n aY[j][i].u += 1.0 - 2.0 * aY[j][i].v;\n }\n }\n ierr = DMDAVecRestoreArray(da,Y,&aY); CHKERRQ(ierr);\n ierr = DMDARestoreCoordinateArray(da,&aC); CHKERRQ(ierr);\n return 0;\n}\n\n// in system form F(t,Y,dot Y) = G(t,Y), compute G():\n// G^u(t,u,v) = - u v^2 + phi (1 - u)\n// G^v(t,u,v) = + u v^2 - (phi + kappa) v\n//STARTRHSFUNCTION\nPetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,\n PetscReal t, Field **aY, Field **aG, PatternCtx *user) {\n PetscInt i, j;\n PetscReal uv2;\n\n user->RHSFcn_called = PETSC_TRUE;\n for (j = info->ys; j < info->ys + info->ym; j++) {\n for (i = info->xs; i < info->xs + info->xm; i++) {\n uv2 = aY[j][i].u * aY[j][i].v * aY[j][i].v;\n aG[j][i].u = - uv2 + user->phi * (1.0 - aY[j][i].u);\n aG[j][i].v = + uv2 - (user->phi + user->kappa) * aY[j][i].v;\n }\n }\n return 0;\n}\n//ENDRHSFUNCTION\n\nPetscErrorCode FormRHSJacobianLocal(DMDALocalInfo *info,\n PetscReal t, Field **aY,\n Mat J, Mat P, PatternCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j;\n PetscReal v[2], uv, v2;\n MatStencil col[2],row;\n\n user->RHSJac_called = PETSC_TRUE;\n for (j = info->ys; j < info->ys+info->ym; j++) {\n row.j = j; col[0].j = j; col[1].j = j;\n for (i = info->xs; i < info->xs+info->xm; i++) {\n row.i = i; col[0].i = i; col[1].i = i;\n uv = aY[j][i].u * aY[j][i].v;\n v2 = aY[j][i].v * aY[j][i].v;\n // u equation\n row.c = 0; col[0].c = 0; col[1].c = 1;\n v[0] = - v2 - user->phi;\n v[1] = - 2.0 * uv;\n ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);\n // v equation\n row.c = 1; col[0].c = 0; col[1].c = 1;\n v[0] = v2;\n v[1] = 2.0 * uv - (user->phi + user->kappa);\n ierr = MatSetValuesStencil(P,1,&row,2,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\n// in system form F(t,Y,dot Y) = G(t,Y), compute F():\n// F^u(t,u,v,u_t,v_t) = u_t - D_u Laplacian u\n// F^v(t,u,v,u_t,v_t) = v_t - D_v Laplacian v\n//STARTIFUNCTION\nPetscErrorCode FormIFunctionLocal(DMDALocalInfo *info, PetscReal t,\n Field **aY, Field **aYdot, Field **aF,\n PatternCtx *user) {\n PetscInt i, j;\n const PetscReal h = user->L / (PetscReal)(info->mx),\n Cu = user->Du / (6.0 * h * h),\n Cv = user->Dv / (6.0 * h * h);\n PetscReal u, v, lapu, lapv;\n\n user->IFcn_called = PETSC_TRUE;\n for (j = info->ys; j < info->ys + info->ym; j++) {\n for (i = info->xs; i < info->xs + info->xm; i++) {\n u = aY[j][i].u;\n v = aY[j][i].v;\n lapu = aY[j+1][i-1].u + 4.0*aY[j+1][i].u + aY[j+1][i+1].u\n + 4.0*aY[j][i-1].u - 20.0*u + 4.0*aY[j][i+1].u\n + aY[j-1][i-1].u + 4.0*aY[j-1][i].u + aY[j-1][i+1].u;\n lapv = aY[j+1][i-1].v + 4.0*aY[j+1][i].v + aY[j+1][i+1].v\n + 4.0*aY[j][i-1].v - 20.0*v + 4.0*aY[j][i+1].v\n + aY[j-1][i-1].v + 4.0*aY[j-1][i].v + aY[j-1][i+1].v;\n aF[j][i].u = aYdot[j][i].u - Cu * lapu;\n aF[j][i].v = aYdot[j][i].v - Cv * lapv;\n }\n }\n return 0;\n}\n//ENDIFUNCTION\n\n// in system form F(t,Y,dot Y) = G(t,Y), compute combined/shifted\n// Jacobian of F():\n// J = (shift) dF/d(dot Y) + dF/dY\n//STARTIJACOBIAN\nPetscErrorCode FormIJacobianLocal(DMDALocalInfo *info,\n PetscReal t, Field **aY, Field **aYdot,\n PetscReal shift, Mat J, Mat P,\n PatternCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j, s, c;\n const PetscReal h = user->L / (PetscReal)(info->mx),\n Cu = user->Du / (6.0 * h * h),\n Cv = user->Dv / (6.0 * h * h);\n PetscReal val[9], CC;\n MatStencil col[9], row;\n\n ierr = MatZeroEntries(P); CHKERRQ(ierr); // workaround to address PETSc issue #734\n user->IJac_called = PETSC_TRUE;\n for (j = info->ys; j < info->ys + info->ym; j++) {\n row.j = j;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n row.i = i;\n for (c = 0; c < 2; c++) { // u,v equations are c=0,1\n row.c = c;\n CC = (c == 0) ? Cu : Cv;\n for (s = 0; s < 9; s++)\n col[s].c = c;\n col[0].i = i; col[0].j = j;\n val[0] = shift + 20.0 * CC;\n col[1].i = i-1; col[1].j = j; val[1] = - 4.0 * CC;\n col[2].i = i+1; col[2].j = j; val[2] = - 4.0 * CC;\n col[3].i = i; col[3].j = j-1; val[3] = - 4.0 * CC;\n col[4].i = i; col[4].j = j+1; val[4] = - 4.0 * CC;\n col[5].i = i-1; col[5].j = j-1; val[5] = - CC;\n col[6].i = i-1; col[6].j = j+1; val[6] = - CC;\n col[7].i = i+1; col[7].j = j-1; val[7] = - CC;\n col[8].i = i+1; col[8].j = j+1; val[8] = - CC;\n ierr = MatSetValuesStencil(P,1,&row,9,col,val,INSERT_VALUES); CHKERRQ(ierr);\n }\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//ENDIJACOBIAN\n\n", "meta": {"hexsha": "1d06e3b273ac32c4b77d192457ba15534dd1cd43", "size": 14041, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/pattern.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/pattern.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/pattern.c", "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "avg_line_length": 43.6055900621, "max_line_length": 110, "alphanum_fraction": 0.5609999288, "num_tokens": 4554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6213105661555547}} {"text": "#include \n#include \n#include \n#include \"mersenne.h\"\n#include \n#include \n\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846264338327 \n#endif\n\n/* Lattice size and dimensions */\n#define NT 48\n#define NX 6\n\n#define ND 2\n#define NDIRS (2*ND)\n\n#define TUP 0\n#define XUP 1\n#define TDN 2\n#define XDN 3\n\n#define VOLUME (NT*NX)\n\n//One staggered fermion\n#define Nf 2 \n\n//#define ANTISYMMETRIC //Antisymmetric boundaries\n//#define SYMMETRIC //implemented in Thirring_hop\n#define OPENX //open in space, (anti)symmetric in time\n\n#define CG_ACCURACY 1e-30\n#define CG_MAX_ITER 10000\n\n/* Simulation parameters */\ndouble m;\ndouble g;\ndouble mu;\n\n\n/* Neighbour index arrays, to be filled at the beginning\n */\nint *tup,*xup,*tdn,*xdn;\n\ndouble ***A;\nint ***eta; //Staggered eta matrix\n\n/* Functions for fetching neighboring coordinates */\nstatic inline int tdir(int t, int dir){\n if( dir == TUP ) return tup[t];\n if( dir == TDN ) return tdn[t];\n return(t);\n}\n\nstatic inline int xdir(int x, int dir){\n if( dir == XUP ) return xup[x];\n if( dir == XDN ) return xdn[x];\n return(x);\n}\n\n/* Opposite of a direction */\nstatic inline int opp_dir(int dir){\n return ( dir + ND ) % NDIRS;\n}\n\ndouble gauge_action(){\n double S = 0;\n for( int t=0;t t ) M[index] = 0.5 * (cA + sA*I) * eta[t][x][0] * expmu ;\n else M[index] = -0.5 * (cA + sA*I) * eta[t][x][0] * expmu ;\n \n t2 = tdn[t];\n sA = sin(A[t2][x][0]);\n cA = cos(A[t2][x][0]);\n index = (NX*t + x) + (NX*t2+x)*VOLUME;\n if( t2 > t ) M[index] = 0.5 * (cA - sA*I) * eta[t2][x][0] * expmmu ;\n else M[index] = -0.5 * (cA - sA*I) * eta[t2][x][0] * expmmu ;\n \n int x2 = xup[x];\n index = (NX*t + x) + (NX*t+x2)*VOLUME;\n sA = sin(A[t][x][1]);\n cA = cos(A[t][x][1]);\n if( x2 > x ) M[index] = 0.5 * (cA + sA*I) * eta[t][x][1] ;\n else M[index] = -0.5 * (cA + sA*I) * eta[t][x][1] ;\n \n x2 = xdn[x];\n index = (NX*t + x) + (NX*t+x2)*VOLUME;\n sA = sin(A[t][x2][1]);\n cA = cos(A[t][x2][1]);\n if( x2 > x ) M[index] = 0.5 * (cA - sA*I) * eta[t][x2][1] ;\n else M[index] = -0.5 * (cA - sA*I) * eta[t][x2][1] ;\n }\n}\n\n\n\ndouble complex determinant(){\n double complex * M; //The matrix\n M = (_Complex double *)malloc( VOLUME*VOLUME*sizeof(_Complex double) );\n fermion_matrix(M);\n int n=VOLUME;\n int info;\n int *ipiv;\n ipiv = malloc( n*sizeof(int) ); \n double complex det = 1;\n \n /*for( int i=0;i 0 ) printf(\"error %d\\n\", info);\n \n for(int i=0; i 0) ? 1 : -1;\n sign += this_sign;\n \n for( int t=0;t\n#include \n#include \n#include \n#include \n#include \n\n/* Algorithm 8.4.3 - Cyclic Jacobi. Golub & Van Loan, Matrix Computations */\n\nstatic inline double\nsymschur2 (gsl_matrix * A, size_t p, size_t q, double *c, double *s)\n{\n double Apq = gsl_matrix_get (A, p, q);\n\n if (Apq != 0.0)\n {\n double App = gsl_matrix_get (A, p, p);\n double Aqq = gsl_matrix_get (A, q, q);\n double tau = (Aqq - App) / (2.0 * Apq);\n double t, c1;\n\n if (tau >= 0.0)\n {\n t = 1.0 / (tau + hypot (1.0, tau));\n }\n else\n {\n t = -1.0 / (-tau + hypot (1.0, tau));\n }\n\n c1 = 1.0 / hypot (1.0, t);\n\n *c = c1;\n *s = t * c1;\n }\n else\n {\n *c = 1.0;\n *s = 0.0;\n }\n\n /* reduction in off(A) is 2*(A_pq)^2 */\n\n return fabs (Apq);\n}\n\ninline static void\napply_jacobi_L (gsl_matrix * A, size_t p, size_t q, double c, double s)\n{\n size_t j;\n const size_t N = A->size2;\n\n /* Apply rotation to matrix A, A' = J^T A */\n\n for (j = 0; j < N; j++)\n {\n double Apj = gsl_matrix_get (A, p, j);\n double Aqj = gsl_matrix_get (A, q, j);\n gsl_matrix_set (A, p, j, Apj * c - Aqj * s);\n gsl_matrix_set (A, q, j, Apj * s + Aqj * c);\n }\n}\n\ninline static void\napply_jacobi_R (gsl_matrix * A, size_t p, size_t q, double c, double s)\n{\n size_t i;\n const size_t M = A->size1;\n\n /* Apply rotation to matrix A, A' = A J */\n\n for (i = 0; i < M; i++)\n {\n double Aip = gsl_matrix_get (A, i, p);\n double Aiq = gsl_matrix_get (A, i, q);\n gsl_matrix_set (A, i, p, Aip * c - Aiq * s);\n gsl_matrix_set (A, i, q, Aip * s + Aiq * c);\n }\n}\n\ninline static double\nnorm (gsl_matrix * A)\n{\n size_t i, j, M = A->size1, N = A->size2;\n double sum = 0.0, scale = 0.0, ssq = 1.0;\n\n for (i = 0; i < M; i++)\n {\n for (j = 0; j < N; j++)\n {\n double Aij = gsl_matrix_get (A, i, j);\n\n if (Aij != 0.0)\n {\n double ax = fabs (Aij);\n\n if (scale < ax)\n {\n ssq = 1.0 + ssq * (scale / ax) * (scale / ax);\n scale = ax;\n }\n else\n {\n ssq += (ax / scale) * (ax / scale);\n }\n }\n\n }\n }\n\n sum = scale * sqrt (ssq);\n\n return sum;\n}\n\nint\ngsl_eigen_jacobi (gsl_matrix * a,\n gsl_vector * eval,\n gsl_matrix * evec, unsigned int max_rot, unsigned int *nrot)\n{\n size_t i, p, q;\n const size_t M = a->size1, N = a->size2;\n double red, redsum = 0.0;\n\n if (M != N)\n {\n GSL_ERROR (\"eigenproblem requires square matrix\", GSL_ENOTSQR);\n }\n else if (M != evec->size1 || M != evec->size2)\n {\n GSL_ERROR (\"eigenvector matrix must match input matrix\", GSL_EBADLEN);\n }\n else if (M != eval->size)\n {\n GSL_ERROR (\"eigenvalue vector must match input matrix\", GSL_EBADLEN);\n }\n\n gsl_vector_set_zero (eval);\n gsl_matrix_set_identity (evec);\n\n for (i = 0; i < max_rot; i++)\n {\n double nrm = norm (a);\n\n if (nrm == 0.0)\n break;\n\n for (p = 0; p < N; p++)\n {\n for (q = p + 1; q < N; q++)\n {\n double c, s;\n\n red = symschur2 (a, p, q, &c, &s);\n redsum += red;\n\n /* Compute A <- J^T A J */\n apply_jacobi_L (a, p, q, c, s);\n apply_jacobi_R (a, p, q, c, s);\n\n /* Compute V <- V J */\n apply_jacobi_R (evec, p, q, c, s);\n }\n }\n }\n\n *nrot = i;\n\n for (p = 0; p < N; p++)\n {\n double ep = gsl_matrix_get (a, p, p);\n gsl_vector_set (eval, p, ep);\n }\n\n if (i == max_rot)\n {\n return GSL_EMAXITER;\n }\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_eigen_invert_jacobi (const gsl_matrix * a,\n gsl_matrix * ainv, unsigned int max_rot)\n{\n if (a->size1 != a->size2 || ainv->size1 != ainv->size2)\n {\n GSL_ERROR(\"jacobi method requires square matrix\", GSL_ENOTSQR);\n }\n else if (a->size1 != ainv->size2)\n {\n GSL_ERROR (\"inverse matrix must match input matrix\", GSL_EBADLEN);\n }\n \n {\n const size_t n = a->size2;\n size_t i,j,k;\n unsigned int nrot = 0;\n int status;\n\n gsl_vector * eval = gsl_vector_alloc(n);\n gsl_matrix * evec = gsl_matrix_alloc(n, n);\n gsl_matrix * tmp = gsl_matrix_alloc(n, n);\n\n gsl_matrix_memcpy (tmp, a);\n\n status = gsl_eigen_jacobi(tmp, eval, evec, max_rot, &nrot);\n \n for(i=0; i\n#include \n#include \n\n#include \"utils.h\"\n#include \"potential.h\"\n\n#include \n\n#include \"ferrers.h\"\n\n#define Sq(X) ((X) * (X))\n\ndouble\n_lambda(double x_sq, double y_sq, double z_sq, double a_sq, double b_sq, double c_sq)\n{\n #define EQS(u) (x_sq / (a_sq + u) + y_sq / (b_sq + u) + z_sq / (c_sq + u) - 1.)\n double J = 0, K = 0., L = (x_sq + y_sq + z_sq);\n for(;EQS(L) > 0;) L *= 2.;//, printf(\"doubled!\\n\");\n\n // solve the eqs using bisection method.\n for(;L - J > 1.e-8;)\n {\n K = (L + J) / 2.;\n //printf(\"%f, %f, %f\\n\", J, K, L);\n if(EQS(K) > 0) J = K;\n else L = K;\n }\n\n return K;\n\n #undef EQS\n}\n\nint\n_orbita_potential_ferrers2_evaluate_wijk(double x, double y, double z,\n double a, double b, double c,\n double * W, int init,\n struct orbita_potential_ferrers2_paramset * ws)\n{\n double a_sq = a * a, b_sq = b * b, c_sq = c * c,\n x_sq = x * x, y_sq = y * y, z_sq = z * z;\n\n // outside the bar region?\n if(x_sq / a_sq + y_sq / b_sq + z_sq / c_sq >= 1 || init)\n {\n // using the root-finding eqs. this is NOT the unique positive root.\n // now use bisection method instead.\n /*\n double A = (a_sq + b_sq + c_sq) - (x_sq + y_sq + z_sq),\n B = (a_sq * b_sq + b_sq * c_sq + c_sq * a_sq) -\n (x_sq * (b_sq + c_sq) + y_sq * (c_sq + a_sq) + z_sq * (a_sq + b_sq)),\n C = (a_sq * b_sq * c_sq) -\n (x_sq * b_sq * c_sq + a_sq * y_sq * c_sq + a_sq * b_sq * z_sq);\n\n double A_sq = A * A, B_sq = B * B, C_sq = C * C;\n double A_cb = A_sq * A, B_cb = B_sq * B;\n double CBR_2 = pow(2., 1. / 3.);\n\n double lambda =\n pow(-2. * A_cb + 3. * sqrt(3.) * sqrt(4. * A_cb * C - A_sq * B_sq - 18. * A * B * C\n + 4. * B_cb + 27. * C_sq) + 9. * A * B - 27. * C, 1. / 3.) / (3. * CBR_2)\n - (CBR_2 * (2187. * B - 729. * A_sq)) / (2187. * pow(-2. * A_cb + 3. * sqrt(3.)\n * sqrt(4. * A_cb * C - A_sq * B_sq - 18. * A * B * C + 4. * B_cb + 27. * C_sq)\n + 9. * A * B - 27. * C, 1. / 3.)) - A / 3.;\n */\n\n double lambda = _lambda(x_sq, y_sq, z_sq, a_sq, b_sq, c_sq);\n if(init) lambda = 0.;\n\n double p = asin(sqrt((a_sq - c_sq) / (a_sq + lambda))),\n k = sqrt((a_sq - b_sq) / (a_sq - c_sq));\n\n /*\n double F = gsl_sf_ellint_F(p, k, GSL_PREC_DOUBLE),\n E = gsl_sf_ellint_E(p, k, GSL_PREC_DOUBLE);\n */\n\n double F = gsl_sf_ellint_F(p, k, GSL_PREC_SINGLE),\n E = gsl_sf_ellint_E(p, k, GSL_PREC_SINGLE);\n\n double delta_lambda = sqrt((a_sq + lambda) * (b_sq + lambda) * (c_sq + lambda));\n\n /* W_000 */ W[ 0] = 2. * F / sqrt(a_sq - c_sq),\n /* W_100 */ W[ 1] = 2. * (F - E) / ((a_sq - b_sq) * sqrt(a_sq - c_sq)),\n /* W_001 */ W[ 3] = (2. / (b_sq - c_sq)) * sqrt((b_sq + lambda) / ((a_sq + lambda) * (c_sq + lambda)))\n -2. * E / ((b_sq - c_sq) * sqrt(a_sq - c_sq)),\n /* W_010 */ W[ 2] = 2. / delta_lambda - W[1] - W[3],\n /* W_110 */ W[ 4] = (W[2] - W[1]) / (a_sq - b_sq),\n /* W_011 */ W[ 5] = (W[3] - W[2]) / (b_sq - c_sq),\n /* W_101 */ W[ 6] = (W[1] - W[3]) / (c_sq - a_sq),\n /* W_200 */ W[ 7] = (2. / (delta_lambda * (a_sq + lambda)) - W[4] - W[6]) / 3.,\n /* W_020 */ W[ 8] = (2. / (delta_lambda * (b_sq + lambda)) - W[5] - W[4]) / 3.,\n /* W_002 */ W[ 9] = (2. / (delta_lambda * (c_sq + lambda)) - W[6] - W[5]) / 3.,\n /* W_111 */ W[10] = (W[4] - W[5]) / (c_sq - a_sq),\n /* W_120 */ W[11] = (W[8] - W[4]) / (a_sq - b_sq),\n /* W_012 */ W[12] = (W[9] - W[5]) / (b_sq - c_sq),\n /* W_201 */ W[13] = (W[7] - W[6]) / (c_sq - a_sq),\n /* W_210 */ W[14] = (W[7] - W[4]) / (b_sq - a_sq), // NOTE Fixed. Nov. 15, 2015\n /* W_021 */ W[15] = (W[8] - W[5]) / (c_sq - b_sq), //\n /* W_102 */ W[16] = (W[9] - W[6]) / (a_sq - c_sq), //\n /* W_300 */ W[17] = (2. / (delta_lambda * Sq(a_sq + lambda)) - W[14] - W[13]) / 5.,\n /* W_030 */ W[18] = (2. / (delta_lambda * Sq(b_sq + lambda)) - W[15] - W[11]) / 5.,\n /* W_003 */ W[19] = (2. / (delta_lambda * Sq(c_sq + lambda)) - W[16] - W[12]) / 5.;\n }\n else\n {\n int i_ijk;\n for(i_ijk = 0; i_ijk < 20; ++ i_ijk)\n W[i_ijk] = (ws -> W_i)[i_ijk];\n }\n\n return 0;\n}\n\ndouble\n_orbita_potential_ferrers2_psi(const void * par, const double * pos)\n{\n struct orbita_potential_ferrers2_paramset * ws =\n (struct orbita_potential_ferrers2_paramset *) par;\n\n double W[20];\n _orbita_potential_ferrers2_evaluate_wijk(\n pos[0], pos[1], pos[2], ws -> a, ws -> b, ws -> c, W, 0, ws);\n\n double x_sq = pos[0] * pos[0], y_sq = pos[1] * pos[1], z_sq = pos[2] * pos[2];\n\n /*\n return (-(ws -> C) / 6.) *\n (\n W[0] - 6. * x_sq * y_sq * z_sq * W[10] \n + x_sq * (x_sq * (3. * W[7] - x_sq * W[17]) \n + 3. * (y_sq * (2 * W[4] - y_sq * W[11] - x_sq * W[14]) - W[1])) \n + y_sq * (y_sq * (3. * W[8] - y_sq * W[18])\n + 3. * (z_sq * (2 * W[5] - z_sq * W[12] - y_sq * W[15]) - W[2])) \n + z_sq * (z_sq * (3. * W[9] - z_sq * W[19]) \n + 3. * (x_sq * (2 * W[6] - x_sq * W[13] - z_sq * W[16]) - W[3])) \n );\n */\n \n // This is to test if Del^2 Psi == 4 Pi G rho. Returns rho from W_jkl.\n return ((ws -> a) * (ws -> b) * (ws -> c) * (ws -> rho) / 2.) *\n (\n (W[1] + W[2] + W[3])\n - 2. * ((y_sq + x_sq) * W[4] + (z_sq + y_sq) * W[5] + (x_sq + z_sq) * W[6])\n - 6. * (x_sq * W[7] + y_sq * W[8] + z_sq * W[9])\n + 2. * (x_sq * y_sq + y_sq * z_sq + z_sq * x_sq) * W[10]\n + (y_sq * y_sq + 6. * x_sq * y_sq) * W[11]\n + (z_sq * z_sq + 6. * y_sq * z_sq) * W[12]\n + (x_sq * x_sq + 6. * z_sq * x_sq) * W[13]\n + (6. * x_sq * y_sq + x_sq * x_sq) * W[14]\n + (6. * y_sq * z_sq + y_sq * y_sq) * W[15]\n + (6. * z_sq * x_sq + z_sq * z_sq) * W[16]\n + 5. * (x_sq * x_sq * W[17] + y_sq * y_sq * W[18] + z_sq * z_sq * W[19])\n ); \n}\n\nint\n_orbita_potential_ferrers2_f(const void * par,\n const double * pos, double * F)\n{\n struct orbita_potential_ferrers2_paramset * ws =\n (struct orbita_potential_ferrers2_paramset *) par;\n\n double W[20];\n _orbita_potential_ferrers2_evaluate_wijk(\n pos[0], pos[1], pos[2], ws -> a, ws -> b, ws -> c, W, 0, ws);\n\n double x_sq = pos[0] * pos[0], y_sq = pos[1] * pos[1], z_sq = pos[2] * pos[2]; //\n\n F[0] = -pos[0] * (ws -> C) * //\n (\n W[1] + x_sq * (x_sq * W[17] + 2. * (y_sq * W[14] - W[7]))\n + y_sq * (y_sq * W[11] + 2. * (z_sq * W[10] - W[4]))\n + z_sq * (z_sq * W[16] + 2. * (x_sq * W[13] - W[6]))\n ),\n F[1] = -pos[1] * (ws -> C) * //\n (\n W[2] + x_sq * (x_sq * W[14] + 2. * (y_sq * W[11] - W[4]))\n + y_sq * (y_sq * W[18] + 2. * (z_sq * W[15] - W[8]))\n + z_sq * (z_sq * W[12] + 2. * (x_sq * W[10] - W[5]))\n ),\n F[2] = -pos[2] * (ws -> C) * //\n (\n W[3] + x_sq * (x_sq * W[13] + 2. * (y_sq * W[10] - W[6]))\n + y_sq * (y_sq * W[15] + 2. * (z_sq * W[12] - W[5]))\n + z_sq * (z_sq * W[19] + 2. * (x_sq * W[16] - W[9]))\n );\n\n return 0;\n}\n\ndouble\n_orbita_potential_ferrers2_rho(const void * par, const double * pos)\n{\n struct orbita_potential_ferrers2_paramset * ws =\n (struct orbita_potential_ferrers2_paramset *) par;\n\n double m_sq = Sq(pos[0]) / Sq(ws -> a) + Sq(pos[1]) / Sq(ws -> b) + Sq(pos[2]) / Sq(ws -> c);\n if(m_sq < 1.) return (ws -> rho) * Sq(1 - m_sq);\n else return 0.;\n}\n\ndouble\n_orbita_potential_ferrers2_Mr(const void * par, const double R)\n{\n orbita_err(\"Method not supported.\");\n return 0.;\n}\n\ndouble\n_orbita_potential_ferrers2_Mt(const void * par)\n{\n struct orbita_potential_ferrers2_paramset * ws =\n (struct orbita_potential_ferrers2_paramset *) par;\n return (ws -> rho) * (ws -> a) * (ws -> b) * (ws -> c) * (32. * Pi / 105.);\n}\n\nint\n_orbita_potential_ferrers2_kill(struct orbita_potential * psi)\n{\n free(psi -> param);\n return 0;\n}\n\nstruct orbita_potential *\norbita_potential_ferrers2(double rho, double a, double b, double c)\n{\n struct orbita_potential * psi =\n (struct orbita_potential *) malloc(sizeof(struct orbita_potential));\n struct orbita_potential_ferrers2_paramset * ws =\n (struct orbita_potential_ferrers2_paramset *)\n malloc(sizeof(struct orbita_potential_ferrers2_paramset));\n psi -> param = (void *)ws;\n\n // initialize w_i\n _orbita_potential_ferrers2_evaluate_wijk(0., 0., 0., a, b, c, ws -> W_i, 1, ws);\n ws -> C = 2. * Pi * rho * a * b * c;\n ws -> a = a, ws -> b = b, ws -> c = c, ws -> rho = rho;\n\n // set other parameters\n psi -> symmetry = 0,\n psi -> coordinates = ORBITA_COORD_CARTESIAN;\n\n psi -> rho = & _orbita_potential_ferrers2_rho,\n psi -> psi = & _orbita_potential_ferrers2_psi,\n psi -> f = & _orbita_potential_ferrers2_f,\n psi -> Mr = & _orbita_potential_ferrers2_Mr,\n psi -> Mt = & _orbita_potential_ferrers2_Mt;\n\n psi -> is_variable = 0,\n psi -> init_param = NULL,\n psi -> param_func = NULL;\n\n psi -> kill = & _orbita_potential_ferrers2_kill;\n\n psi -> is_composite = 0;\n\n return psi;\n}\n", "meta": {"hexsha": "41fdda9d420d9453972356e0668add0bef3adeb0", "size": 9416, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ferrers.c", "max_stars_repo_name": "shiaki/orbita", "max_stars_repo_head_hexsha": "98cc210922d123e7570ec40c4145190e1876cc69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T18:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T02:06:46.000Z", "max_issues_repo_path": "src/ferrers.c", "max_issues_repo_name": "shiaki/orbita", "max_issues_repo_head_hexsha": "98cc210922d123e7570ec40c4145190e1876cc69", "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/ferrers.c", "max_forks_repo_name": "shiaki/orbita", "max_forks_repo_head_hexsha": "98cc210922d123e7570ec40c4145190e1876cc69", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.265917603, "max_line_length": 108, "alphanum_fraction": 0.4810960068, "num_tokens": 3701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6207813341608472}} {"text": "/**\n *\n * @generated s 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 s_check_orthogonality(int M, int N, int LDQ, float *Q)\n{\n float alpha, beta;\n float normQ;\n int info_ortho;\n int i;\n int minMN = min(M, N);\n float eps;\n float *work = (float *)malloc(minMN*sizeof(float));\n\n eps = LAPACKE_slamch_work('e');\n alpha = 1.0;\n beta = -1.0;\n\n /* Build the idendity matrix USE DLASET?*/\n float *Id = (float *) malloc(minMN*minMN*sizeof(float));\n memset((void*)Id, 0, minMN*minMN*sizeof(float));\n for (i = 0; i < minMN; i++)\n Id[i*minMN+i] = (float)1.0;\n\n /* Perform Id - Q'Q */\n if (M >= N)\n cblas_ssyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N);\n else\n cblas_ssyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M);\n\n normQ = LAPACKE_slansy_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 s_check_QRfactorization(int M, int N, float *A1, float *A2, int LDA, float *Q)\n{\n float Anorm, Rnorm;\n float alpha, beta;\n int info_factorization;\n int i,j;\n float eps;\n\n eps = LAPACKE_slamch_work('e');\n\n float *Ql = (float *)malloc(M*N*sizeof(float));\n float *Residual = (float *)malloc(M*N*sizeof(float));\n float *work = (float *)malloc(max(M,N)*sizeof(float));\n\n alpha=1.0;\n beta=0.0;\n\n if (M >= N) {\n /* Extract the R */\n float *R = (float *)malloc(N*N*sizeof(float));\n memset((void*)R, 0, N*N*sizeof(float));\n LAPACKE_slacpy_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(float));\n cblas_sgemm(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 float *L = (float *)malloc(M*M*sizeof(float));\n memset((void*)L, 0, M*M*sizeof(float));\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M);\n\n /* Perform Ql=LQ */\n memset((void*)Ql, 0, M*N*sizeof(float));\n cblas_sgemm(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_slange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work);\n Anorm = LAPACKE_slange_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 s_check_LLTfactorization(int N, float *A1, float *A2, int LDA, int uplo)\n{\n float Anorm, Rnorm;\n float alpha;\n int info_factorization;\n int i,j;\n float eps;\n\n eps = LAPACKE_slamch_work('e');\n\n float *Residual = (float *)malloc(N*N*sizeof(float));\n float *L1 = (float *)malloc(N*N*sizeof(float));\n float *L2 = (float *)malloc(N*N*sizeof(float));\n float *work = (float *)malloc(N*sizeof(float));\n\n memset((void*)L1, 0, N*N*sizeof(float));\n memset((void*)L2, 0, N*N*sizeof(float));\n\n alpha= 1.0;\n\n LAPACKE_slacpy_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_slacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N);\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N);\n cblas_strmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N);\n }\n else{\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N);\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N);\n cblas_strmm(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_slange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work);\n Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work);\n\n printf(\"============\\n\");\n printf(\"Checking the Cholesky Factorization \\n\");\n printf(\"-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n\n if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){\n printf(\"-- Factorization is suspicious ! \\n\");\n info_factorization = 1;\n }\n else{\n printf(\"-- Factorization is CORRECT ! \\n\");\n info_factorization = 0;\n }\n\n free(Residual); free(L1); free(L2); free(work);\n\n return info_factorization;\n}\n\n/*--------------------------------------------------------------\n * Check the gemm\n */\nfloat s_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n float alpha, float *A, int LDA,\n float *B, int LDB,\n float beta, float *Cplasma,\n float *Cref, int LDC,\n float *Cinitnorm, float *Cplasmanorm, float *Clapacknorm )\n{\n float beta_const = -1.0;\n float Rnorm;\n float *work = (float *)malloc(max(K,max(M, N))* sizeof(float));\n\n *Cinitnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n *Cplasmanorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work);\n\n cblas_sgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K,\n (alpha), A, LDA, B, LDB, (beta), Cref, LDC);\n\n *Clapacknorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n cblas_saxpy(LDC * N, (beta_const), Cplasma, 1, Cref, 1);\n\n Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the trsm\n */\nfloat s_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag,\n int M, int NRHS, float alpha,\n float *A, int LDA,\n float *Bplasma, float *Bref, int LDB,\n float *Binitnorm, float *Bplasmanorm, float *Blapacknorm )\n{\n float beta_const = -1.0;\n float Rnorm;\n float *work = (float *)malloc(max(M, NRHS)* sizeof(float));\n /*float eps = LAPACKE_slamch_work('e');*/\n\n *Binitnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work);\n *Bplasmanorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work);\n\n cblas_strsm(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_slange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n\n cblas_saxpy(LDB * NRHS, (beta_const), Bplasma, 1, Bref, 1);\n\n Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);\n Rnorm = Rnorm / *Blapacknorm; \n /* max(M,NRHS) * eps);*/\n\n free(work);\n\n return Rnorm;\n}\n\n/*--------------------------------------------------------------\n * Check the solution\n */\n\nfloat s_check_solution(int M, int N, int NRHS, float *A, int LDA,\n float *B, float *X, int LDB,\n float *anorm, float *bnorm, float *xnorm )\n{\n/* int info_solution; */\n float Rnorm = -1.00;\n float zone = 1.0;\n float mzone = -1.0;\n float *work = (float *)malloc(max(M, N)* sizeof(float));\n\n *anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work);\n *xnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work);\n *bnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, (zone), A, LDA, X, LDB, (mzone), B, LDB);\n\n Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);\n\n free(work);\n\n return Rnorm;\n}\n", "meta": {"hexsha": "b5a211584cfd2e3fdfa80ecab9f766d5fe3a1f10", "size": 9613, "ext": "c", "lang": "C", "max_stars_repo_path": "timing/sauxiliary.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/sauxiliary.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/sauxiliary.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.2583892617, "max_line_length": 114, "alphanum_fraction": 0.5517528347, "num_tokens": 3150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.6204886203389076}} {"text": "/* integration/qng.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"err.c\"\n#include \"qng.h\"\n\nint\ngsl_integration_qng (const gsl_function *f,\n double a, double b,\n double epsabs, double epsrel,\n double * result, double * abserr, size_t * neval)\n{\n double fv1[5], fv2[5], fv3[5], fv4[5];\n double savfun[21]; /* array of function values which have been computed */\n double res10, res21, res43, res87; /* 10, 21, 43 and 87 point results */\n double result_kronrod, err ; \n double resabs; /* approximation to the integral of abs(f) */\n double resasc; /* approximation to the integral of abs(f-i/(b-a)) */\n\n const double half_length = 0.5 * (b - a);\n const double abs_half_length = fabs (half_length);\n const double center = 0.5 * (b + a);\n const double f_center = GSL_FN_EVAL(f, center);\n\n int k ;\n\n if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))\n {\n * result = 0;\n * abserr = 0;\n * neval = 0;\n GSL_ERROR (\"tolerance cannot be acheived with given epsabs and epsrel\",\n GSL_EBADTOL);\n };\n\n /* Compute the integral using the 10- and 21-point formula. */\n\n res10 = 0;\n res21 = w21b[5] * f_center;\n resabs = w21b[5] * fabs (f_center);\n\n for (k = 0; k < 5; k++)\n {\n const double abscissa = half_length * x1[k];\n const double fval1 = GSL_FN_EVAL(f, center + abscissa);\n const double fval2 = GSL_FN_EVAL(f, center - abscissa);\n const double fval = fval1 + fval2;\n res10 += w10[k] * fval;\n res21 += w21a[k] * fval;\n resabs += w21a[k] * (fabs (fval1) + fabs (fval2));\n savfun[k] = fval;\n fv1[k] = fval1;\n fv2[k] = fval2;\n }\n\n for (k = 0; k < 5; k++)\n {\n const double abscissa = half_length * x2[k];\n const double fval1 = GSL_FN_EVAL(f, center + abscissa);\n const double fval2 = GSL_FN_EVAL(f, center - abscissa);\n const double fval = fval1 + fval2;\n res21 += w21b[k] * fval;\n resabs += w21b[k] * (fabs (fval1) + fabs (fval2));\n savfun[k + 5] = fval;\n fv3[k] = fval1;\n fv4[k] = fval2;\n }\n\n resabs *= abs_half_length ;\n\n { \n const double mean = 0.5 * res21;\n \n resasc = w21b[5] * fabs (f_center - mean);\n \n for (k = 0; k < 5; k++)\n {\n resasc +=\n (w21a[k] * (fabs (fv1[k] - mean) + fabs (fv2[k] - mean))\n + w21b[k] * (fabs (fv3[k] - mean) + fabs (fv4[k] - mean)));\n }\n resasc *= abs_half_length ;\n }\n\n result_kronrod = res21 * half_length;\n \n err = rescale_error ((res21 - res10) * half_length, resabs, resasc) ;\n\n /* test for convergence. */\n\n if (err < epsabs || err < epsrel * fabs (result_kronrod))\n {\n * result = result_kronrod ;\n * abserr = err ;\n * neval = 21;\n return GSL_SUCCESS;\n }\n\n /* compute the integral using the 43-point formula. */\n\n res43 = w43b[11] * f_center;\n\n for (k = 0; k < 10; k++)\n {\n res43 += savfun[k] * w43a[k];\n }\n\n for (k = 0; k < 11; k++)\n {\n const double abscissa = half_length * x3[k];\n const double fval = (GSL_FN_EVAL(f, center + abscissa) \n + GSL_FN_EVAL(f, center - abscissa));\n res43 += fval * w43b[k];\n savfun[k + 10] = fval;\n }\n\n /* test for convergence */\n\n result_kronrod = res43 * half_length;\n err = rescale_error ((res43 - res21) * half_length, resabs, resasc);\n\n if (err < epsabs || err < epsrel * fabs (result_kronrod))\n {\n * result = result_kronrod ;\n * abserr = err ;\n * neval = 43;\n return GSL_SUCCESS;\n }\n\n /* compute the integral using the 87-point formula. */\n\n res87 = w87b[22] * f_center;\n\n for (k = 0; k < 21; k++)\n {\n res87 += savfun[k] * w87a[k];\n }\n\n for (k = 0; k < 22; k++)\n {\n const double abscissa = half_length * x4[k];\n res87 += w87b[k] * (GSL_FN_EVAL(f, center + abscissa) \n + GSL_FN_EVAL(f, center - abscissa));\n }\n\n /* test for convergence */\n\n result_kronrod = res87 * half_length ;\n \n err = rescale_error ((res87 - res43) * half_length, resabs, resasc);\n \n if (err < epsabs || err < epsrel * fabs (result_kronrod))\n {\n * result = result_kronrod ;\n * abserr = err ;\n * neval = 87;\n return GSL_SUCCESS;\n }\n\n /* failed to converge */\n\n * result = result_kronrod ;\n * abserr = err ;\n * neval = 87;\n\n GSL_ERROR(\"failed to reach tolerance with highest-order rule\", GSL_ETOL) ;\n}\n", "meta": {"hexsha": "ecf8e624b6aa8d38538a9c89fafb3e0950af8d67", "size": 5359, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/integration/qng.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/integration/qng.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/integration/qng.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": 28.057591623, "max_line_length": 81, "alphanum_fraction": 0.5853704049, "num_tokens": 1683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6202007106672781}} {"text": "#ifndef METHODS_HELLER_H\n#define METHODS_HELLER_H\n\n#include \n\nnamespace method {\n// use your method name to create a subspace for your\n// implementation of details\nnamespace heller_cwa {\nnamespace details {\n\nstruct HellerParam {\n\n // exp(a[0] p^2 + a[1] p + a[2] p q + a[3] q + a[4] q^2 + a[5])\n // alpha = 0.5 / a[0]\n // delta = a[1]\n // epsilon = a[2]\n\n arma::cx_vec a;\n arma::mat points;\n math::Polynomial V_eff_0;\n double mass;\n};\n\ninline\ncx_double heller_gaussian(const arma::cx_vec & a,\n const double q,\n const double p) {\n return std::exp(a(0) * std::pow(p, 2)\n + a(1) * p\n + a(2) * p * q\n + a(3) * q\n + a(4) * std::pow(q, 2)\n + a(5));\n}\n\ninline\narma::cx_vec heller_gaussian(const arma::cx_vec & a,\n const arma::mat & points) {\n if (points.n_rows != 2) {\n throw Error(\"heller_gaussian only supports one-dimensional phase space\");\n }\n\n arma::cx_vec result(points.n_cols);\n#pragma omp parallel for\n for (arma::uword i = 0; i < result.n_elem; i++) {\n result(i) = heller_gaussian(a, points(0, i), points(1, i));\n }\n\n return result;\n}\n\ninline\nmath::Gaussian heller_gaussian(const arma::cx_vec & a) {\n\n const arma::cx_mat binomial{{{-a(4) * 2.0, -a(2)}, {-a(2), -a(0) * 2.0}}};\n const arma::cx_mat covariance = arma::inv(binomial);\n const arma::cx_vec center = covariance * arma::cx_vec{a(3),a(1)};\n\n return math::Gaussian(covariance, center,\n std::exp(a(5)) * std::exp(0.5 * arma::dot(center, arma::cx_vec{a(3),a(1)})));\n\n}\n\ntemplate\narma::mat force(const Potential & potential,\n const arma::mat & positions) {\n arma::mat result = arma::mat(arma::size(positions));\n\n#pragma omp parallel for\n for (arma::uword i = 0; i < positions.n_cols; i++) {\n const arma::vec position = positions.col(i);\n for (arma::uword j = 0; j < positions.n_rows; j++) {\n result(j, i) = -potential.derivative(j).at(position);\n }\n }\n\n return result;\n}\n\ntemplate\ninline\nauto effective_potential(const Function & potential,\n const cx_double alpha,\n const cx_double delta,\n const cx_double epsilon,\n const arma::uword l,\n const arma::uword cut_off) {\n\n if (potential.dim() > 1) {\n throw Error(\"Currently effective potential is only valid \"\n \"for one dimensional potential\");\n }\n\n const auto functor = [alpha](const Function & function) -> Function {\n return function.derivative(0).derivative(0) / 8.0 / alpha;\n };\n\n const auto a = exp(functor, derivative(potential, arma::uvec{l}), cut_off) *\n std::pow(-1, l + 1);\n const auto b = exp(functor, derivative(potential, arma::uvec{l}), cut_off);\n\n const std::vector>\n a_inner =\n {math::Polynomial(\n arma::cx_vec{1.0 + epsilon / 2.0,\n cx_double{0.0, 1.0} / 2.0 / alpha,\n 0.5 * delta},\n lmat{{1, 0, 0},\n {0, 1, 0}})};\n\n const std::vector>\n b_inner =\n {math::Polynomial(\n arma::cx_vec{1.0 - epsilon / 2.0,\n -cx_double{0.0, 1.0} / 2.0 / alpha,\n -0.5 * delta},\n lmat{{1, 0, 0},\n {0, 1, 0}})};\n\n const auto combined = (a(a_inner) + b(b_inner)) * 0.5;\n\n return combined;\n}\n\ninline\nmath::Polynomial E_function(const arma::cx_vec & a,\n const arma::cx_vec & a_derivatives,\n const math::Polynomial & V_eff_0,\n const double mass) {\n\n if (a.n_elem != 6 || a_derivatives.n_elem != 6) {\n throw Error(\n \"The number of elements for a's or their derivatives is invalid for E function\");\n }\n\n const math::Polynomial without_derivatives(\n arma::cx_vec{-a(2) / mass, -2.0 * a(4) / mass, -a(3) / mass},\n lmat{{{0, 1, 0}, {2, 1, 1}}}\n );\n\n const math::Polynomial derivatives(\n arma::cx_vec{-a_derivatives(0),\n -a_derivatives(1),\n -a_derivatives(2),\n -a_derivatives(3),\n -a_derivatives(4),\n -a_derivatives(5)},\n lmat{{{0, 0, 1, 1, 2, 0}, {2, 1, 1, 0, 0, 0}}}\n );\n\n return without_derivatives + derivatives - V_eff_0 * cx_double{0.0, 2.0};\n\n}\n\ninline\ndouble I_function(\n const arma::cx_vec & a,\n const arma::cx_vec & a_derivatives,\n const arma::mat & points,\n const math::Polynomial & V_eff_0,\n const double mass) {\n\n return arma::sum(arma::pow(arma::abs(\n at(E_function(a, a_derivatives, V_eff_0, mass), points)\n % heller_gaussian(a, points)), 2));\n\n}\n\ninline\narma::vec I_function_derivative(\n const arma::cx_vec & a,\n const arma::cx_vec & a_derivatives,\n const arma::mat & points,\n const math::Polynomial & V_eff_0,\n const double mass\n) {\n\n arma::vec result(12);\n\n const auto E_func = E_function(a, a_derivatives, V_eff_0, mass);\n\n const auto polynomial_term_list = lmat{{{0, 0, 1, 1, 2, 0}, {2, 1, 1, 0, 0, 0}}};\n\n#pragma omp parallel for\n for (arma::uword i = 0; i < 6; i++) {\n\n const lvec E_derivative_term = polynomial_term_list.col(i);\n const auto E_derivative =\n math::polynomial::Term(1.0, E_derivative_term);\n\n result(i) = -arma::sum(2.0 *\n arma::real(at(E_func.conj() * E_derivative, points))\n %\n arma::pow(arma::abs(heller_gaussian(a, points)), 2));\n\n result(i + 6) = arma::sum(2.0 *\n arma::imag(\n at(E_func.conj() * E_derivative, points))\n %\n arma::pow(arma::abs(heller_gaussian(a, points)),\n 2));\n }\n\n return result;\n}\n\ninline\ndouble I_function_gsl_wrapper(\n const gsl_vector * a_derivatives,\n void * param\n) {\n const HellerParam heller_param = *(HellerParam *) param;\n const arma::cx_vec a = heller_param.a;\n const arma::vec a_derivatives_all = gsl::convert_vec(a_derivatives);\n const arma::cx_vec a_derivatives_arma =\n arma::cx_vec{a_derivatives_all.rows(0, 5),\n a_derivatives_all.rows(6, 11)};\n\n return I_function(a,\n a_derivatives_arma,\n heller_param.points,\n heller_param.V_eff_0,\n heller_param.mass);\n\n}\n\ninline\nvoid I_function_derivative_gsl_wrapper(\n const gsl_vector * a_derivatives,\n void * param,\n gsl_vector * g\n) {\n const HellerParam heller_param = *(HellerParam *) param;\n const arma::cx_vec a = heller_param.a;\n const arma::vec a_derivatives_all = gsl::convert_vec(a_derivatives);\n\n const arma::cx_vec a_derivatives_arma =\n arma::cx_vec{a_derivatives_all.rows(0, 5),\n a_derivatives_all.rows(6, 11)};\n\n const auto result_pointer =\n gsl::convert_vec(I_function_derivative(a,\n a_derivatives_arma,\n heller_param.points,\n heller_param.V_eff_0,\n heller_param.mass));\n\n gsl_vector_memcpy(g, result_pointer);\n\n gsl_vector_free(result_pointer);\n}\n\ninline\nvoid I_function_fdf_gsl_wrapper(\n const gsl_vector * a_derivatives,\n void * param,\n double * f,\n gsl_vector * g\n) {\n I_function_derivative_gsl_wrapper(a_derivatives, param, g);\n\n *f = I_function_gsl_wrapper(a_derivatives, param);\n}\n\n\ninline\narma::cx_vec a_derivative(HellerParam input,\n const double initial_step_size,\n const double tolerance,\n const double gradient_tolerance,\n const size_t total_steps) {\n\n /* allocate memory for minimization process */\n const auto minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2;\n auto minimizer_environment = gsl_multimin_fdfminimizer_alloc(minimizer_type,\n 12);\n\n /* assigning function to minimizer object */\n gsl_multimin_function_fdf minimizer_object;\n minimizer_object.f = &I_function_gsl_wrapper;\n minimizer_object.df = &I_function_derivative_gsl_wrapper;\n minimizer_object.fdf = &I_function_fdf_gsl_wrapper;\n minimizer_object.n = 12;\n minimizer_object.params = (void *) &input;\n\n /* starting point */\n const auto a_derivatives = gsl_vector_calloc(12);\n\n /* set environment */\n gsl_multimin_fdfminimizer_set(minimizer_environment,\n &minimizer_object, a_derivatives,\n initial_step_size, tolerance);\n\n size_t iter = 0;\n int status = GSL_CONTINUE;\n do {\n iter++;\n status = gsl_multimin_fdfminimizer_iterate(minimizer_environment);\n\n if (status) {\n throw Error(gsl_strerror(status));\n }\n\n status = gsl_multimin_test_gradient(minimizer_environment->gradient,\n gradient_tolerance);\n\n if (status == GSL_SUCCESS) {\n const arma::vec result = gsl::convert_vec(minimizer_environment->x);\n\n gsl_multimin_fdfminimizer_free(minimizer_environment);\n gsl_vector_free(a_derivatives);\n\n return arma::cx_vec{result.rows(arma::span(0, 5)),\n result.rows(arma::span(6, 11))};\n }\n } while (status == GSL_CONTINUE && iter < total_steps);\n\n return arma::ones(6) * 2.8375;\n}\n\n} // namespace details\n\nstruct State {\npublic:\n arma::mat points;\n arma::vec weights;\n arma::vec masses;\n\n // Establish an easy way to construct your State\n template\n State(const PhaseSpaceDistribution & initial,\n const arma::uvec & grid,\n const arma::mat & range,\n const arma::vec & masses) :\n points(math::space::points_generate(grid, range)),\n weights(arma::real(at(initial, points))),\n masses(masses) {\n if (grid.n_rows != range.n_rows) {\n throw Error(\"Different dimension between the grid and the range\");\n }\n if (grid.n_rows != 2 * masses.n_rows) {\n throw Error(\"Different dimension between the grid and the masses\");\n }\n }\n\n template\n State(const PhaseSpaceDistribution & initial,\n const arma::uvec & grid,\n const arma::mat & range) :\n points(math::space::points_generate(grid, range)),\n weights(arma::real(at(initial, points))),\n masses(arma::ones(grid.n_elem / 2)) {\n if (grid.n_elem % 2 != 0) {\n throw Error(\"Odd number of dimension - it is not likely a phase space\");\n }\n if (grid.n_rows != range.n_rows) {\n throw Error(\"Different dimension between the grid and the range\");\n }\n if (grid.n_rows != 2 * masses.n_rows) {\n throw Error(\"Different dimension between the grid and the masses\");\n }\n }\n\n inline\n State(const arma::mat & points,\n const arma::vec & weights,\n const arma::vec & masses) :\n points(points),\n weights(weights),\n masses(masses) {\n if (points.n_cols != weights.n_elem) {\n throw Error(\"Different number of points and corresponding weights\");\n }\n\n if (points.n_rows != 2 * masses.n_rows) {\n throw Error(\"Different dimension between the points and the masses\");\n }\n }\n\n inline\n arma::uword dim() const {\n return points.n_rows / 2;\n }\n\n inline\n State normalise() const {\n return State(this->points, this->weights / arma::sum(this->weights),\n this->masses);\n }\n\n template\n arma::vec expectation(const std::vector & function) const {\n arma::vec result(function.size());\n\n#pragma omp parallel for\n for (arma::uword i = 0; i < result.n_elem; i++) {\n\n if (function[i].dim() != this->dim() * 2) {\n throw Error(\n \"The dimension of the function is invalid for the calculation of expectation\");\n }\n result(i) = arma::dot(at(function[i], this->points), weights) /\n arma::sum(weights);\n }\n\n return result;\n }\n\n template\n double expectation(const Function & function) const {\n const arma::vec result = at(function, this->points);\n\n return arma::dot(result, weights) / arma::sum(weights);\n }\n\n inline\n arma::vec positional_expectation() const {\n arma::uword dim = this->dim();\n\n return this->points.rows(0, dim - 1) * this->weights /\n arma::sum(this->weights);\n }\n\n inline\n arma::vec momentum_expectation() const {\n arma::uword dim = this->dim();\n\n return this->points.rows(dim, 2 * dim - 1) * this->weights /\n arma::sum(this->weights);\n }\n\n State operator+(const State & B) const {\n if (!arma::approx_equal(this->weights, B.weights, \"abs_diff\", 1e-16) ||\n !arma::approx_equal(this->masses, B.masses, \"abs_diff\", 1e-16)) {\n throw Error(\"Different cwa states are being added\");\n }\n\n return State(this->points + B.points, this->weights, this->masses);\n }\n\n State operator*(const double B) const {\n return State(this->points * B, this->weights, this->masses);\n }\n};\n\ntemplate\nstruct Operator {\n\nprivate:\n PropagationType type = Classic;\n\npublic:\n Potential potential;\n\n Operator(const State & state,\n const Potential & potential) :\n potential(potential) {}\n\n\n inline\n PropagationType propagation_type() const {\n return Classic;\n }\n\n State operator()(const State & state) const {\n\n arma::mat p_submatrix = state.points.rows(state.dim(), 2 * state.dim() - 1);\n p_submatrix.each_col() /= state.masses;\n\n const arma::mat change_list =\n arma::join_cols(p_submatrix,\n details::force(potential,\n state.points.rows(0, state.dim() - 1)));\n\n return State(change_list, state.weights, state.masses);\n }\n\n};\n\n} // namespace heller\n}\n\n#endif //METHODS_HELLER_H\n", "meta": {"hexsha": "265ad30b4648fbe888e96e8e5d8fa51e6eeb10aa", "size": 14290, "ext": "h", "lang": "C", "max_stars_repo_path": "include/quartz_internal/details/methods/heller_cwa.h", "max_stars_repo_name": "Walter-Feng/Quartz", "max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z", "max_issues_repo_path": "include/quartz_internal/details/methods/heller_cwa.h", "max_issues_repo_name": "Walter-Feng/Quartz", "max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z", "max_forks_repo_path": "include/quartz_internal/details/methods/heller_cwa.h", "max_forks_repo_name": "Walter-Feng/Quartz", "max_forks_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b", "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.4639175258, "max_line_length": 91, "alphanum_fraction": 0.5911126662, "num_tokens": 3672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.6201987203085145}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\nvoid test_nonlinear_corrfunc(void)\n{\n double lnrmin = log(1e-5);\n double lnrmax = log(3e2);\n int N = 10000;\n double r,dlnr = (lnrmax - lnrmin)/N;\n int i;\n FILE *fp;\n double a;\n \n a = 1.0;\n fp = fopen(\"xinltest.txt\",\"w\");\n for(i=0;i= mmin)\n {\n m = pow(10.0,lgm);\n fprintf(fp,\"%.20e \\t %.20e \\n\",1.686/sigmaMtophat(m,a),bias_function(m,a));\n lgm -= dm;\n }\n fclose(fp);\n\n}\n\nvoid test_massfunc(void)\n{\n FILE *fp;\n double m,lgm;\n double mmin = 10.0;\n double mmax = 16.0;\n double dm = 0.01;\n double a = 1.0;\n \n fp = fopen(\"mftest.txt\",\"w\");\n lgm = mmax;\n while(lgm >= mmin)\n {\n m = pow(10.0,lgm);\n fprintf(fp,\"%.20e \\t %.20e \\n\",m,mass_function(m,a)*m*m/RHO_CRIT/cosmoData.OmegaM);\n lgm -= dm;\n }\n fclose(fp);\n}\n\nvoid test_peakheight(void)\n{\n FILE *fp;\n double r;\n double rmin = 1e-40;\n double rmax = 1e3;\n double dr = 0.99;\n double a = 1.0;\n double numin = 0.15;\n double numax = 6.0;\n double dnu = 0.99;\n double nu;\n \n double kmin=1e-10;\n double kmax=1e10;\n long i,Ntest = 1000;\n double dlnk = log(kmax/kmin)/Ntest;\n double k,p = 1e-6;\n \n fp = fopen(\"phtest_integ.txt\",\"w\");\n for(i=0;i= rmin)\n {\n fprintf(fp,\"%.20e \\t %.20e \\t %.20e \\n\",r,sigmaRtophat(r,a),sigmaRtophat_exact(r,a));\n r *= dr;\n }\n fclose(fp);\n\n fp = fopen(\"phtestrev.txt\",\"w\");\n nu = numax;\n while(nu >= numin)\n {\n fprintf(fp,\"%.20e \\t %.20e \\n\",inverse_nuRtophat(nu,a),DELTAC/nu);\n nu *= dnu;\n }\n fclose(fp);\n}\n\nvoid test_gf(void)\n{\n FILE *fp;\n double a;\n double amin = 0.1;\n double amax = 1.0;\n double da = 0.0001;\n \n fp = fopen(\"gftest.txt\",\"w\");\n a = amax;\n while(a >= amin)\n {\n fprintf(fp,\"%.20e \\t %.20e \\t %.20e \\n\",a,growth_function(a),growth_function_exact(a));\n a -= da;\n }\n fclose(fp);\n}\n\nvoid test_linpk(void)\n{\n double kmin=1e-8;\n double kmax=1e40;\n long i,Ntest = 10000;\n double dlnk = log(kmax/kmin)/Ntest;\n FILE *fp;\n double k;\n double a = 1.0;\n \n fp = fopen(\"pktest.txt\",\"w\");\n for(i=0;i= amin)\n {\n fprintf(fp,\"%.20e \\t %.20e \\t %.20e \\n\",a,comvdist(a),comvdist_exact(a));\n a -= da;\n }\n fclose(fp);\n \n fp = fopen(\"disttest_d2a.txt\",\"w\");\n d = dmin;\n while(d <= dmax)\n {\n a = acomvdist(d);\n fprintf(fp,\"%.20e \\t %.20e \\t %.20e \\n\",d,a,comvdist_exact(a));\n d += dd;\n }\n fclose(fp);\n}\n", "meta": {"hexsha": "4d9322b9b257f3c97ab77f0b288cb939e6127d19", "size": 7587, "ext": "c", "lang": "C", "max_stars_repo_path": "src/test_code.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/test_code.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/test_code.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": 21.075, "max_line_length": 112, "alphanum_fraction": 0.5484381178, "num_tokens": 3004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6201987186194661}} {"text": "/////////////////\n//example25.5.c\n/////////////////\n#include \n#include \n#include \n#include \n#include \n\ntypedef struct{\n double g;//gravity\n double M;//mass of the car\n double m;//mass of the load\n double r;//length of the rope\n double C;//damping coefficient\n\n double F;//input force proportional to torque\n double T;//tension to the rope\n\n double x,x0;//x position of the load\n double y,y0;//y position of the load\n double X;//X position of the car\n double a;//angle (theta)\n\n double dx,dx0;\n double dy,dy0;\n double dX,dX0;\n double dr;\n double da,da0;\n\n double ddx;\n double ddy;\n double ddX;\n double ddr;\n double dda;\n double dXmax;\n double ddXmax;\n double Fmax;//Force\n\n double h;\n int nh;\n double _h;\n int _dim;\n double *_y;\n double *_y_err;\n double *_dydt_in;\n double *_dydt_out;\n const gsl_odeiv_step_type *_T;\n gsl_odeiv_step *_s;\n gsl_odeiv_system _sys;\n double _t;\n} CRANE;\n\n#define dim_crane 4\nint cranefunc (double t, const double y[], double f[], void *params)\n{\n CRANE *c = (CRANE *)params;\n //y[0]=crane.p, y[1]=crane.da, y[2]=crane.X, y[3]=crane.dX\n f[0] = y[1];\n f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n f[2] = y[3]; \n // f[3] = c->ddX;\n f[3] = (c->F+c->T*sin(y[0]))/c->M;\n return GSL_SUCCESS;\n}\n////////////////\n#define square(x) ((x)*(x))\nCRANE crane;\nint initialize()\n{\n \n crane.Fmax=20.0;//check// crane.Fmax=30;//check\n // crane.dXmax=1.0;\n crane.dXmax=1.0;\n crane.ddXmax=0.2;\n crane.g=9.8;\n crane.M=100;\n crane.m=20;//10;//10;//20\n crane.r=5;//5;\n crane.C=1;//5;\n crane.dr=crane.ddr=0;\n crane.x0=0;\n crane.y0=crane.r;\n crane.dX0=crane.dx0=crane.dy0=crane.da0=0;\n#ifdef CRANESUB\n // crane.Fmax=_crane_Fmax;//check// crane.Fmax=30;//check\n crane.m=_crane_m;\n crane.C=_crane_C;\n crane.r=_crane_r;\n crane.h=AP_tS;\n crane.dXmax=_crane_dXmax;\n if(_AP_umax>0) AP_u_max=crane.Fmax=_AP_umax;\n else AP_u_max=crane.Fmax;\n AP_u_min=-AP_u_max;\n // starttime=0;\n // totaltime=100;// totaltime=40;\n // totaltime=50;// totaltime=40;\n // int kmax=totaltime/AP_tS;\n // _rr=(double*)malloc(kmax*sizeof(double));\n rr=AP_r=_AP_r;//10\n // int k;for(k=0;kcrane.Fmax) uu=crane.Fmax; \n else if(uu<-crane.Fmax) uu=-crane.Fmax; \n int n;\n for(n=0;n=crane.dXmax && crane.F>0) crane.F=0;\n else if(crane.dX<=-crane.dXmax && crane.F<0) crane.F=0;\n int status = gsl_odeiv_step_apply (crane._s, crane._t, crane._h, \n\t\t\t\t crane._y, crane._y_err, \n\t\t\t\t crane._dydt_in, \n\t\t\t\t crane._dydt_out, \n\t\t\t\t &crane._sys);\n if (status != GSL_SUCCESS) break;\n \n int i;for(i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\nstatic double linear_corrfunc_integ_funct(double k, void *p);\n\nstatic double linear_corrfunc_integ_funct(double k, void *p)\n{\n double r = ((double*)p)[0];\n double a = ((double*)p)[1];\n return linear_powspec(k,a)*k/r;\n}\n\ndouble linear_corrfunc_exact(double r, double a)\n{\n double I0;\n double abserr,p[2];\n gsl_integration_workspace *workspace;\n gsl_function F;\n gsl_integration_qawo_table *wf;\n gsl_integration_workspace *cycle_workspace;\n \n#define WORKSPACE_NUM 70\n#define ABSERR 1e-3\n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n cycle_workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n wf = gsl_integration_qawo_table_alloc(r,1.0,GSL_INTEG_SINE,(size_t) WORKSPACE_NUM);\n \n F.function = &linear_corrfunc_integ_funct;\n p[0] = r;\n p[1] = a;\n F.params = p;\n gsl_integration_qawf(&F,1e-8,ABSERR,(size_t) WORKSPACE_NUM,workspace,cycle_workspace,wf,&I0,&abserr);\n \n gsl_integration_qawo_table_free(wf);\n gsl_integration_workspace_free(cycle_workspace);\n gsl_integration_workspace_free(workspace);\n#undef ABSERR\n#undef WORKSPACE_NUM\n \n return I0/2.0/M_PI/M_PI;\n}\n\ndouble linear_corrfunc(double r, double a)\n{\n static int initFlag = 1;\n static int currCosmoNum;\n static gsl_spline *cosmocalc_linear_corrfunc_spline = NULL;\n static gsl_interp_accel *cosmocalc_linear_corrfunc_acc = NULL; \n \n double linear_corrfunc_table[COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH];\n double r_table[COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH];\n long i;\n double gf;\n \n if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)\n {\n initFlag = 0;\n currCosmoNum = cosmoData.cosmoNum;\n \n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"matrix/gslmatrix.h\"\n#include \"stream/stream.h\"\n#include \"common/mlist.h\"\n\n#include \n#include \n\n/**\n @brief calculate the auto-correlation vector, r, with the time-discrete signal, x[n].\n Each component, r[k], represents the auto-correlation function of the input sample for lag, k.\n Accordingly, r[k] can be expressed as \\cE{ x[n] x[n-k] }.\n @param const gsl_vector *samples[in] time-discrete signal which corresponds to x[n].\n @param gsl_vector *autoCorrelationVector[out] auto-correlation vector which corresponds to r. \n @note the size of \"autoCorrelationVector\" should be \"order+1\" in order to calculate the LP model of the order, \"order\".\n */\nvoid calcAutoCorrelationVector( const gsl_vector_float *samples, gsl_vector *autoCorrelationVector );\n\n/**\n @brief calculate the linear prediction coefficients (LPC) with the Levinson-Durbin Algorithm.\n @param gsl_vector_float *autoCorrelationVector[in] \n @param gsl_vector_float *lpcs[out] lpcs[0,...,p-1] where p is the order of the model.\n @return prediction error\n @notice The estimated signal is defined as \n \\hat{x}[n] = sum_{k=1}^p lpcs[k-1] * x[n-k].\n That is different from the definition in MATLAB lpc()\n\t where it is \\hat{x}(n) = 1.0 - sum_{k=1}^p lpcs(k+1) * x(n-k).\n */\nfloat calcLPCswithLevinsonDurbin( gsl_vector_float *autoCorrelationVector, gsl_vector_float *lpcs );\n\n// ----- definition for class `LPCSpectrumEstimator' -----\n//\n\n/**\n @class calculate LPCs with the Levinson-Durbin algorithm, and estimate the LPC envelope.\n @note You can feed samples to this object with calcLPCs( const gsl_vector_float* samples ), \n\t and the LPCs are then computed.\n */\nclass LPCSpectrumEstimator : public VectorFloatFeatureStream {\npublic:\n LPCSpectrumEstimator( const VectorFloatFeatureStreamPtr& samp, unsigned order, unsigned fftLen, const String& nm = \"LPCSpectrumEstimator\");\n ~LPCSpectrumEstimator();\n\n const gsl_vector_float* next(int frame_no = -5);\n void reset();\n\n /**\n @brief get the auto-correlation vector, r[0,...,order-1], \n where r[k] represents the auto-correlation function of the input sample for lag, k+1.\n @note you have to call calcLPCs() before you call this method.\n */\n const gsl_vector_float* getAutoCorrelationVector(){\n return (const gsl_vector_float*)_r;\n }\n /**\n @brief get the prediction error of the LP model. \n @note you have to call calcLPCs() before you call this method.\n */\n float getPredictionError(){\n return _e;\n }\n /**\n @brief get the LPCs.\n @note you have to call calcLPCs() before you call this method.\n */\n const gsl_vector_float* getLPCs(){\n return _lpcs; //_vector;\n }\n\n gsl_vector_complex* getFTLPCs(){\n return _ftlpcs;\n }\n\n const gsl_vector_float* calcLPCs( const gsl_vector_float* samples );\n void calcLPEnvelope();\n\nprivate:\n void complexPackedArrayUnpack(const double* halfcomplex_coefficient, gsl_vector_complex* complex_coefficient) const;\nprivate:\n static const double _epsilon;\n VectorFloatFeatureStreamPtr _samp;\n unsigned _order; /* the LP model of the order */\n unsigned _fftLen;\n unsigned _fftLen2;\n float _e; /* prediction error */\n gsl_vector_float* _r; /* _order x 1 auto-correlation vector _r[1,...,p]; See [1] */\n gsl_vector* _autoCorrelation; /* (_order+1) x 1 auto-correlation vector, where the first element corresponds to the power */\n gsl_vector_float* _lpcs; /* LPCs */\n double* _wslpcs; /* workspace for the LPCs */\n gsl_vector_complex* _ftlpcs;\n};\n\ntypedef Inherit LPCSpectrumEstimatorPtr;\n\n\n// ----- definition for class `CepstralSpectrumEstimator' -----\n//\nclass CepstralSpectrumEstimator : public VectorFloatFeatureStream {\npublic:\n CepstralSpectrumEstimator(const VectorComplexFeatureStreamPtr& source, unsigned order = 14, unsigned fftLen = 256,\n\t\t\t double logPadding = 1.0, const String& nm = \"CepstralSpectrumEstimator\");\n ~CepstralSpectrumEstimator();\n\n const gsl_vector_float* next(int frame_no = -5);\n void reset() { _source->reset(); VectorFloatFeatureStream::reset(); }\n\nprivate:\n VectorComplexFeatureStreamPtr\t\t\t_source;\n const unsigned\t\t\t\t_order;\n const unsigned\t\t\t\t_fftLen;\n const double\t\t\t\t\t_logPadding;\n\n double*\t\t\t\t\t_samples;\n gsl_vector_complex*\t\t\t\t_spectrum;\n gsl_vector_complex*\t\t\t\t_cepstrum;\n};\n\ntypedef Inherit CepstralSpectrumEstimatorPtr;\n\n\n// ----- definition for class `SEMNB' -----\n//\n\n/**\n @class \n */\n\nclass SEMNB : public Countable {\npublic:\n SEMNB( unsigned order, unsigned fftLen, const String& nm = \"SEMNB\");\n ~SEMNB();\n\n const gsl_vector*\tcalcDerivativeOfDeviation( LPCSpectrumEstimatorPtr &lpcSEPtr );\n virtual void\t\treset();\n const gsl_vector*\tgetLPEnvelope() const { return _lpEnvelope; }\n\nprivate:\n void\t\t\t_calcEigen();\n void\t\t\t_calcLambda_bar();\n\n double\t\t_dLambdak_dPm(unsigned k, unsigned m);\n void\t\t\t_dLambdabar_dPm(unsigned m);\n void\t\t\t_da_dPm(unsigned m);\n float\t\t\t_dSigma_dP(const gsl_vector_float* lpcs, double epsilonp, unsigned m);\n\n double\t\t_dSp_dan(const gsl_vector_float* lpcs, unsigned m, unsigned n);\n double\t\t_dSp_dPm(const gsl_vector_float* lpcs, unsigned m);\n double\t\t_depsilonp_dPm(const gsl_vector_float* lpcs, unsigned m);\n void\t\t\t_calc_dr_dPm(unsigned m);\n double\t\t_dPhat_dP(const gsl_vector_float* lpcs, double epsilonp, unsigned m);\n\n\n const unsigned\t\t\t\t_order;\n const unsigned\t\t\t\t_fftLen;\n const unsigned\t\t\t\t_fftLen2;\n\n gsl_vector*\t\t\t\t\t_derivative;\n gsl_matrix*\t\t\t\t\t_R;\n gsl_matrix*\t\t\t\t\t_Rcopy;\n gsl_eigen_symmv_workspace*\t\t\t_workSpace;\n gsl_vector*\t\t\t\t\t_evalues;\n gsl_matrix*\t\t\t\t\t_evectors;\n gsl_vector*\t _lpEnvelope;\n gsl_vector_complex* _ftlpcs;\n \n gsl_vector*\t\t\t\t\t_r;\n gsl_vector*\t\t\t\t\t_dr_dPm;\n gsl_vector*\t\t\t\t\t_dak_dPm;\n gsl_matrix*\t\t\t\t\t_Lambda_bar;\n gsl_matrix*\t\t\t\t\t_dLambdamatrix;\n\n gsl_matrix*\t\t\t\t\t_C;\n gsl_matrix*\t\t\t\t\t_D;\n};\n\ntypedef refcountable_ptr SEMNBPtr;\n\n#endif\n\n", "meta": {"hexsha": "34005d8792bec80978e1516c091a121b19870a40", "size": 6748, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/feature/spectralestimator.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/feature/spectralestimator.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/feature/spectralestimator.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 33.9095477387, "max_line_length": 141, "alphanum_fraction": 0.6939834025, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.618806374694215}} {"text": "/* randist/gumbel.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n/* The Type I Gumbel distribution has the form,\n\n p(x) dx = a b exp(-(b exp(-ax) + ax)) dx\n\n and the Type II Gumbel distribution has the form,\n\n p(x) dx = b a x^-(a+1) exp(-b x^-a)) dx\n\n */\n\ndouble\ngsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b)\n{\n double x = gsl_rng_uniform_pos (r);\n\n double z = (log(b) - log(-log(x))) / a;\n\n return z;\n}\n\ndouble\ngsl_ran_gumbel1_pdf (const double x, const double a, const double b)\n{\n double p = a * b * exp (-(b * exp(-a * x) + a * x));\n return p;\n}\n\ndouble\ngsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b)\n{\n double x = gsl_rng_uniform_pos (r);\n\n double z = pow(-b / log(x), 1/a);\n\n return z;\n}\n\ndouble\ngsl_ran_gumbel2_pdf (const double x, const double a, const double b)\n{\n if (x <= 0)\n {\n return 0 ;\n }\n else\n {\n double p = b * a * pow(x,-(a+1)) * exp (-b * pow(x, -a));\n return p;\n }\n}\n\n\n\n\n", "meta": {"hexsha": "65aff8d3d5b24c7d3318eff7c86cea8b5c989e93", "size": 1834, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/gumbel.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/gumbel.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/gumbel.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.2151898734, "max_line_length": 81, "alphanum_fraction": 0.6553980371, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257655, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6187874901013576}} {"text": "//\n// beta.h\n//\n// code using beta distribution\n//\n// copyright 2020 Peter Andrews\n//\n\n#ifndef PAA_BETA_H_\n#define PAA_BETA_H_\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"error.h\"\n#include \"utility.h\"\n\nnamespace paa {\n\nclass GSLRNG {\n public:\n explicit GSLRNG(const uint64_t seed) : gen{gsl_rng_alloc(gsl_rng_mt19937)} {\n if (!gen) throw Error(\"Problem creating gsl generator\");\n gsl_rng_set(gen, seed);\n }\n ~GSLRNG() { gsl_rng_free(gen); }\n operator gsl_rng * () const { return gen; }\n GSLRNG(const GSLRNG &) = delete;\n GSLRNG & operator=(const GSLRNG &) = delete;\n void lock() { mutex.lock(); }\n void unlock() { mutex.unlock(); }\n\n private:\n gsl_rng * gen;\n std::mutex mutex{};\n};\n\ntemplate\nclass BetaT {\n public:\n using Params = std::pair;\n BetaT(const Val alpha__, const Val beta__) :\n alpha_{alpha__}, beta_{beta__} {\n if (alpha_ <= 0) throw Error(\"Nonpositive alpha in Beta distribution\");\n if (beta_ <= 0) throw Error(\"Nonpositive beta in Beta distribution\");\n }\n explicit BetaT(const Params params) :\n BetaT{params.first, params.second} {}\n BetaT(const Val mean_, const Val stdev_, const bool) :\n alpha_{get_alpha(mean_, stdev_)},\n beta_{get_beta(mean_, stdev_)} {\n if (stdev_ >= max_stdev(mean_))\n throw Error(\"Maximum stdev for basic Beta distribution is\")\n << max_stdev(mean_);\n }\n Val alpha() const { return alpha_; }\n Val beta() const { return beta_; }\n Val low() const { return 0.0; }\n Val high() const { return 1.0; }\n Val range() const { return 1.0; }\n Val middle() const { return 0.5; }\n static Val get_alpha(const Val mean_, const Val stdev_) {\n return mean_ * (mean_ * (1 - mean_) / sqr(stdev_) - 1);\n }\n static Val get_beta(const Val mean_, const Val stdev_) {\n return (1 - mean_) * (mean_ * (1 - mean_) / sqr(stdev_) - 1);\n }\n static Val max_stdev(const Val mean_) {\n return sqrt(mean_ * (1 - mean_));\n }\n Val mean() const { return alpha_ / (alpha_ + beta_); }\n Val stdev() const {\n return sqrt((alpha_ * beta_) /\n (sqr(alpha_ + beta_) * (alpha_ + beta_ + 1)));\n }\n Val operator()(const Val val) const {\n return gsl_ran_beta_pdf(val, alpha_, beta_);\n }\n Val operator()(gsl_rng * gen) const {\n return gsl_ran_beta(gen, alpha_, beta_);\n }\n\n private:\n Val alpha_;\n Val beta_;\n};\nusing Beta = BetaT;\nusing fBeta = BetaT;\n\ntemplate\nclass Beta4T {\n public:\n Beta4T(const Val alpha__, const Val beta__,\n const Val low__, const Val high__) :\n beta_dist{alpha__, beta__}, low_{low__}, high_{high__} {\n if (mean() < low())\n throw Error(\"Mean less than low in Beta distribution\");\n if (mean() > high())\n throw Error(\"Mean greater than high in Beta distribution\");\n }\n Beta4T(const Val mean_, const Val stdev_,\n const Val low__, const Val high__,\n const bool) :\n beta_dist{get_alpha_beta(mean_, stdev_, low__, high__)},\n low_{low__}, high_{high__} {}\n\n Val alpha() const { return beta_dist.alpha(); }\n Val beta() const { return beta_dist.beta(); }\n Val low() const { return low_; }\n Val high() const { return high_; }\n Val range() const { return (high_ - low_); }\n Val middle() const { return (high_ - low_) / 2; }\n Val mean() const { return low_ + scale * beta_dist.mean(); }\n Val stdev() const { return scale * beta_dist.stdev(); }\n static Val max_stdev(const Val mean_, const Val low__, const Val high__) {\n const Val sf{high__ - low__};\n const Val m{(mean_ - low__) / sf};\n return sf * BetaT::max_stdev(m);\n }\n Val operator()(const Val val) const {\n return static_cast(beta_dist((val - low_) / scale)) / scale;\n }\n Val operator()(gsl_rng * gen) const {\n return low_ + scale * static_cast(beta_dist(gen));\n }\n\n private:\n static typename BetaT::Params get_alpha_beta(\n const Val mean_, const Val stdev_,\n const Val low__, const Val high__) {\n const Val sf{high__ - low__};\n const Val m{(mean_ - low__) / sf};\n const Val sd{stdev_ / sf};\n return typename BetaT::Params{\n BetaT::get_alpha(m, sd), BetaT::get_beta(m, sd)};\n }\n\n BetaT beta_dist;\n Val low_;\n Val high_;\n Val scale{high_ - low_};\n};\nusing Beta4 = Beta4T;\nusing fBeta4 = Beta4T;\n\n} // namespace paa\n\n\n\n#endif // PAA_BETA_H_\n", "meta": {"hexsha": "8d6ec89085f8b1b78956570d07f4ae513878347a", "size": 4459, "ext": "h", "lang": "C", "max_stars_repo_path": "utility/beta.h", "max_stars_repo_name": "docpaa/mumdex", "max_stars_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_stars_repo_licenses": ["Zlib", "MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-07T15:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-23T00:58:54.000Z", "max_issues_repo_path": "utility/beta.h", "max_issues_repo_name": "docpaa/mumdex", "max_issues_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_issues_repo_licenses": ["Zlib", "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": "utility/beta.h", "max_forks_repo_name": "docpaa/mumdex", "max_forks_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1", "max_forks_repo_licenses": ["Zlib", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T15:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T15:47:54.000Z", "avg_line_length": 28.7677419355, "max_line_length": 79, "alphanum_fraction": 0.6337743889, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6187864316275622}} {"text": "#include \n#include \n#include \n#include \n#include \n\n\ntypedef struct Vortex\n{\n double x, y;\n double vorticity;\n\n int active;\n} Vortex;\n\n\n/* possibly should be replaced with one function? */\ndouble Qfield_x(double x, double y)\n{\n double r = x*x+y*y;\n return -y/(2*M_PI*fmax(r,1/1024/1024));\n// return -y/(2*M_PI*fmax(r,1/1024));\n}\n\ndouble Qfield_y(double x, double y)\n{\n double r = x*x+y*y;\n return x/(2*M_PI*fmax(r,1/1024/1024));\n}\n\n\n\ndouble Pfield_x(double x, double y)\n{\n double r = hypot(x,y);\n if(r == 0)\n return 1.;\n return x/r*exp(-r);\n}\n\ndouble Pfield_y(double x, double y)\n{\n double r = hypot(x,y);\n if(r == 0)\n return 1.;\n return y/r*exp(-r);\n}\n\n\n\n\ndouble Mfield(double x, double y)\n{\n double r2= x*x+y*y;\n double r = sqrt(r2);\n if(x==0 && y==0)\n return 0.;\n return (r+1.)*exp(-r)/r2;\n}\n\nint VortexInBody(double x, double y)\n{\n if(x*x+y*y<1)\n return 1;\n else\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n int NumberOfPanels = 12, MaxVortexes = 16500, Niterations = 200, i,j,k,m,n, iterator;\n double nu = 1/13, tau = 0.005/*, eps = 0.002*/, rho = 1.;\n double vx_inf = 1., vy_inf = 0.;\n\n double PanelNodes [NumberOfPanels][2],\n PanelMids [NumberOfPanels][2],\n PanelNorms [NumberOfPanels][2],\n PanelTaus [NumberOfPanels][2],\n PanelLength[NumberOfPanels];\n\n double DeployPoints[NumberOfPanels][2];\n\n Vortex InFlow[MaxVortexes], NextInFlow[MaxVortexes];\n\n int ActiveVortexesInFLow=0;\n\n\n\n if(1)/* cylinder profile forming & deploys */\n {\n\n for(i=0;i5 && 0)\n {\n double sq1=1., sq2=1., sq3=1.;\n for(j=0;j0\n )\n {\n sq1 = temp;\n sq2 = sq1;\n sq3 = sq2;\n }\n }\n eps = sqrt( (sq1+sq2+sq3)/3 );\n }\n\n //Vortex-caused part of velocity\n for(j=0;j 1/1024.*0.25 && fabs(ry) > 1/1024.*0.25*/ )\n {\n u_x += InFlow[j].vorticity*Qfield_x(rx,ry);\n u_y += InFlow[j].vorticity*Qfield_y(rx,ry);\n }\n }\n\n\n\n //Viscous component of velocity\n for(j=0;j 1.)\n {\n NextInFlow[i].active = InFlow[i].active;\n NextInFlow[i].vorticity = InFlow[i].vorticity;\n }\n else\n {\n NextInFlow[i].active = 3;\n NextInFlow[i].vorticity = InFlow[i].vorticity;\n }\n }\n else\n {\n NextInFlow[i].x = InFlow[i].x;\n NextInFlow[i].y = InFlow[i].y;\n NextInFlow[i].active = 2;\n NextInFlow[i].vorticity = InFlow[i].vorticity;\n }\n// if(NextInFlow[i].vorticity<0.01)\n }\n\n for(m = 0; m < NumberOfPanels; m++)\n {\n f_x += -rho*(gsl_vector_get(NewVorticities,m)/tau* PanelMids[m][1]);\n f_y += rho*(gsl_vector_get(NewVorticities,m)/tau* PanelMids[m][0]);\n }\n\n fprintf(forces,\"%f %f %f\\n\",iterator*tau, f_x, f_y);\n\n //updating coords\n for(i=0;i\n *\n * Based on the R function rmvnorm, from the mvtnorm package\n * by Friedrich Leisch and Fabian Scheipl, implemented\n * using the GSL libraries\n */\n\n#include \n#include \n#include \n#include \n#include \n\nint mvn(gsl_rng * rng, const gsl_vector * mean, gsl_matrix * covar, gsl_vector * ANS)\n{\n\tint i;\n\tsize_t n = mean->size;\n\n\t/* Calculate eigenvalues and eigenvectors of covar matrix */\n\tgsl_vector *eval = gsl_vector_alloc (n);\n\tgsl_matrix *evec = gsl_matrix_alloc (n, n);\n\tgsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (n);\n\tgsl_eigen_symmv (covar, eval, evec, w);\n\tgsl_eigen_symmv_free (w);\n//\tgsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC);\n\n\n\t\n\t/* Setup for: evec * matrix(diag(eval)) * transpose(evec) */\n\tgsl_matrix *eval_mx = gsl_matrix_calloc (n, n);\n\tgsl_matrix * x_M = gsl_matrix_alloc (n,n);\n\tgsl_matrix * x_M_x = gsl_matrix_alloc (n,n);\n\n\n\tgsl_vector_view diagonal = gsl_matrix_diagonal(eval_mx);\n\tgsl_vector_memcpy(&diagonal.vector, eval);\n\tfor(i=0;i c d s\n *\n **/\n#include \n#include \n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup dplasma_cores_complex64\n *\n * CORE_zpltmg_circul is a kernel used in circulant matrix generation\n *\n * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999880\n *\n * Circulant matrix\n *\n * A circulant matrix has the property that each row is obtained from the\n * previous one by cyclically permuting the entries one step forward. It is a\n * special Toeplitz matrix in which the diagonals \"wrap around.\"\n *\n * The eigensystem of C (n-by-n) is known explicitly: If t is an nth root of\n * unity, then the inner product of v and w = [1 t t2 ... t(n – 1)] is an\n * eigenvalue of C and w(n:-1:1) is an eigenvector, where v is the first column of\n * C.\n *\n *\n *******************************************************************************\n *\n * @param[in] M\n * The number of rows of the tile A to initialize. M >= 2.\n *\n * @param[in] N\n * The number of columns of the tile A to initialize. N >= 0.\n *\n * @param[out] A\n * On entry, the M-by-N tile to be initialized.\n *\n * @param[in] LDA\n * The leading dimension of the tile A. LDA >= max(1,M).\n *\n * @param[in] gM\n * The global number of rows of the full matrix, A is belonging to. gM >= (m0+gM).\n *\n * @param[in] m0\n * The index of the first row of tile A in the full matrix. m0 >= 0.\n *\n * @param[in] n0\n * The index of the first column of tile A in the full matrix. n0 >= 0.\n *\n * @param[in] V\n * Workspace of size gM, that contains the first clumn of the full matrix\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if INFO = -k, the k-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zpltmg_circul = PCORE_zpltmg_circul\n#define CORE_zpltmg_circul PCORE_zpltmg_circul\n#endif\nint CORE_zpltmg_circul( int M, int N, PLASMA_Complex64_t *A, int LDA,\n int gM, int m0, int n0,\n const PLASMA_Complex64_t *V )\n{\n int i, j, ii, jj;\n\n /* Check input arguments */\n if (M < 0) {\n coreblas_error(1, \"Illegal value of M\");\n return -1;\n }\n if (N < 0) {\n coreblas_error(2, \"Illegal value of N\");\n return -2;\n }\n if ((LDA < max(1,M)) && (M > 0)) {\n coreblas_error(4, \"Illegal value of LDA\");\n return -4;\n }\n if (m0 < 0) {\n coreblas_error(6, \"Illegal value of m0\");\n return -6;\n }\n if (n0 < 0) {\n coreblas_error(7, \"Illegal value of n0\");\n return -7;\n }\n if (gM < m0+M) {\n coreblas_error(5, \"Illegal value of gM\");\n return -5;\n }\n\n for (j=0, jj=n0; j\n#include /* used for NULL, also fprintf(stderr,...) */\n#include /* used for malloc's */\n#include \n#include \n#include \n#include \n#define DEBUG 0\n#define KNUTH_CONVENTION 1 /* Saves a few steps of arithmetic\n * in the call to gsl_ran_discrete()\n */\n\n/*** Begin Stack (this code is used just in this file) ***/\n\n/* Stack code converted to use unsigned indices (i.e. s->i == 0 now\n means an empty stack, instead of -1), for consistency and to give a\n bigger allowable range. BJG */\n\ntypedef struct {\n size_t N; /* max number of elts on stack */\n size_t *v; /* array of values on the stack */\n size_t i; /* index of top of stack */\n} gsl_stack_t;\n\nstatic gsl_stack_t *\nnew_stack(size_t N) {\n gsl_stack_t *s;\n s = (gsl_stack_t *)malloc(sizeof(gsl_stack_t));\n s->N = N;\n s->i = 0; /* indicates stack is empty */\n s->v = (size_t *)malloc(sizeof(size_t)*N);\n return s;\n}\n\nstatic int\npush_stack(gsl_stack_t *s, size_t v)\n{\n if ((s->i) >= (s->N)) {\n return -1; /* stack overflow (shouldn't happen) */\n }\n (s->v)[s->i] = v;\n s->i += 1;\n return 0;\n}\n\nstatic size_t pop_stack(gsl_stack_t *s)\n{\n if ((s->i) == 0) {\n GSL_ERROR (\"internal error - stack exhausted\", GSL_ESANITY);\n }\n s->i -= 1;\n return ((s->v)[s->i]);\n}\n\nstatic inline size_t size_stack(const gsl_stack_t *s)\n{\n return s->i;\n}\n\nstatic void free_stack(gsl_stack_t *s)\n{\n free((char *)(s->v));\n free((char *)s);\n}\n\n/*** End Stack ***/\n\n\n/*** Begin Walker's Algorithm ***/\n\ngsl_ran_discrete_t *\ngsl_ran_discrete_preproc(size_t Kevents, const double *ProbArray)\n{\n size_t k,b,s;\n gsl_ran_discrete_t *g;\n size_t nBigs, nSmalls;\n gsl_stack_t *Bigs;\n gsl_stack_t *Smalls;\n double *E;\n double pTotal = 0.0, mean, d;\n \n if (Kevents < 1) {\n /* Could probably treat Kevents=1 as a special case */\n\n GSL_ERROR_VAL (\"number of events must be a positive integer\", \n GSL_EINVAL, 0);\n }\n\n /* Make sure elements of ProbArray[] are positive.\n * Won't enforce that sum is unity; instead will just normalize\n */\n\n for (k=0; kK = Kevents;\n g->F = (double *)malloc(sizeof(double)*Kevents);\n g->A = (size_t *)malloc(sizeof(size_t)*Kevents);\n\n E = (double *)malloc(sizeof(double)*Kevents);\n\n if (E==NULL) {\n GSL_ERROR_VAL (\"Cannot allocate memory for randevent\", GSL_ENOMEM, 0);\n }\n\n for (k=0; kA[k] to indicate small or large */\n size_t * const which = g->A;\n\n for (k=0; k 0) {\n s = pop_stack(Smalls);\n if (size_stack(Bigs) == 0) {\n (g->A)[s]=s;\n (g->F)[s]=1.0;\n continue;\n }\n b = pop_stack(Bigs);\n (g->A)[s]=b;\n (g->F)[s]=Kevents*E[s];\n#if DEBUG\n fprintf(stderr,\"s=%2d, A=%2d, F=%.4f\\n\",s,(g->A)[s],(g->F)[s]);\n#endif \n d = mean - E[s];\n E[s] += d; /* now E[s] == mean */\n E[b] -= d;\n if (E[b] < mean) {\n push_stack(Smalls,b); /* no longer big, join ranks of the small */\n }\n else if (E[b] > mean) {\n push_stack(Bigs,b); /* still big, put it back where you found it */\n }\n else {\n /* E[b]==mean implies it is finished too */\n (g->A)[b]=b;\n (g->F)[b]=1.0;\n }\n }\n while (size_stack(Bigs) > 0) {\n b = pop_stack(Bigs);\n (g->A)[b]=b;\n (g->F)[b]=1.0;\n }\n /* Stacks have been emptied, and A and F have been filled */\n\n if ( size_stack(Smalls) != 0) {\n GSL_ERROR_VAL (\"Smalls stack has not been emptied\",\n GSL_ESANITY, 0 );\n }\n \n#if 0\n /* if 1, then artificially set all F[k]'s to unity. This will\n * give wrong answers, but you'll get them faster. But, not\n * that much faster (I get maybe 20%); that's an upper bound\n * on what the optimal preprocessing would give.\n */\n for (k=0; kF)[k] = 1.0;\n }\n#endif\n\n#if KNUTH_CONVENTION\n /* For convenience, set F'[k]=(k+F[k])/K */\n /* This saves some arithmetic in gsl_ran_discrete(); I find that\n * it doesn't actually make much difference.\n */\n for (k=0; kF)[k] += k;\n (g->F)[k] /= Kevents;\n }\n#endif \n\n free_stack(Bigs);\n free_stack(Smalls);\n free((char *)E);\n\n return g;\n}\n\nsize_t\ngsl_ran_discrete(const gsl_rng *r, const gsl_ran_discrete_t *g)\n{\n size_t c=0;\n double u,f;\n u = gsl_rng_uniform(r);\n#if KNUTH_CONVENTION\n c = (u*(g->K));\n#else\n u *= g->K;\n c = u;\n u -= c;\n#endif\n f = (g->F)[c];\n /* fprintf(stderr,\"c,f,u: %d %.4f %f\\n\",c,f,u); */\n if (f == 1.0) return c;\n\n if (u < f) {\n return c;\n }\n else {\n return (g->A)[c];\n }\n}\n\nvoid gsl_ran_discrete_free(gsl_ran_discrete_t *g)\n{\n RETURN_IF_NULL (g);\n free((char *)(g->A));\n free((char *)(g->F));\n free((char *)g);\n}\n\ndouble\ngsl_ran_discrete_pdf(size_t k, const gsl_ran_discrete_t *g)\n{\n size_t i,K;\n double f,p=0;\n K= g->K;\n if (k>K) return 0;\n for (i=0; iF)[i];\n#if KNUTH_CONVENTION\n f = K*f-i;\n#endif \n if (i==k) {\n p += f;\n } else if (k == (g->A)[i]) {\n p += 1.0 - f;\n }\n }\n return p/K;\n}\n", "meta": {"hexsha": "a1400eebade8ace37e0c7dee8e68f1f6f040dbb3", "size": 13420, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/randist/discrete.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/discrete.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/discrete.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 32.972972973, "max_line_length": 84, "alphanum_fraction": 0.6219076006, "num_tokens": 3814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6180089197917225}} {"text": "#include \n#include \n#include \"cs.h\"\n#include \n#include \n#include \"adkCSparse.h\"\n#include \"adkGSL.h\"\n\n\n\n//gslMatrixToCSsparse -- returns new cs_sparse object. compressed\nstruct cs_di_sparse *gslMatrixToCSsparse(gsl_matrix *gm, int numNonZero){\n\tint i, j;\n\tstruct cs_di_sparse *triplet, *compmat;\n\tdouble tmp;\n\t\n\n\t//now allocate new cs_sparse obj\n\ttriplet = cs_spalloc(gm->size1, gm->size2, numNonZero, 1, 1);\n\tfor(i=0;isize1;i++){\n\t\tfor(j=0;jsize2;j++){\n\t\t\ttmp = gsl_matrix_get(gm,i,j);\n\t\t\tif(tmp != 0.0) cs_entry(triplet,i,j,tmp);\n\t\t}\n\t}\n\tcompmat = cs_compress(triplet);\n\tcs_spfree(triplet);\n\treturn(compmat);\n}\n\n\n//gslMatrixToCSsparse -- returns new cs_sparse object. compressed\nstruct cs_di_sparse *arraysToCSsparse(int rank, int numNonZero, int *dim1, int *dim2,double *x){\n\tint i;\n\tstruct cs_di_sparse *triplet, *compmat;\n\t\n\t//now allocate new cs_sparse obj\n\ttriplet = cs_spalloc(rank, rank, numNonZero, 1, 1);\n\tfor(i=0;inz < 0){\n\t\tfor (j = 0 ; j < mat->n ; j++){\n\t\t\tfor(p = mat->p[j] ; p < mat->p[j+1] ; p++){\n\t\t\t\tval = mat->x[p];\n\t\t\t\tif(val >max){\n\t\t\t\t\tmax=val;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse{ //below is untested\n\t\tfor(j=0;jnzmax;j++){\n\t\t\tif(mat->x[j] > max){\n\t\t\t\tmax = mat->x[j];\n\t\t\t}\n\t\t}\n\t}\n\treturn(max);\n}\n\n//cs_scale -- scales each value by some constant\nvoid cs_scale(struct cs_di_sparse *mat, double c){\n\tint i;\n\tfor(i=0;inzmax;i++){\n\t\tmat->x[i] *= c;\n\t}\n}\n\n//cs_scale -- scales each value by some constant\nvoid cs_print_adk(struct cs_di_sparse *mat){\n\tint i,j,col,row,p;\n\tdouble val;\n\tgsl_matrix *gm;\n\tgm = gsl_matrix_alloc(mat->m,mat->n);\n\tgsl_matrix_set_zero(gm);\n\n\n\tif (mat->nz < 0){\n\t\tfor (j = 0 ; j < mat->n ; j++){\n\t\t\tcol=j;\n\t\t\tfor(p = mat->p[j] ; p < mat->p[j+1] ; p++){\n\t\t\t\trow = mat->i [p];\n\t\t\t\tval = mat->x[p];\n\t\t\t\tgsl_matrix_set(gm,row,col,val);\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\n\t\tfor(i=0;inz;i++){\n\t\t\tgsl_matrix_set(gm,mat->p[i],mat->i[i],mat->x[i]);\n\t\t}\n\t}\n\tgsl_matrix_prettyPrint(gm);\n\tgsl_matrix_free(gm);\n\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6f8808b643aab564fb1187d80085b39af2177815", "size": 2296, "ext": "c", "lang": "C", "max_stars_repo_path": "adkCSparse.c", "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_issues_repo_path": "adkCSparse.c", "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_forks_repo_path": "adkCSparse.c", "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4576271186, "max_line_length": 96, "alphanum_fraction": 0.6297909408, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6177050907154096}} {"text": "/* \n** pseudoinverse\n**\n** G.Lohmann, July 2004\n*/\n#include \n#include \n#include \n#include \"viaio/Vlib.h\"\n\n#include \n#include \n#include \n#include \n\nextern void printmat(gsl_matrix *R,char *str);\nextern void printvec(gsl_vector *x,char *str);\n\n\n/*\n** B = A^-1 = A^+\n*/\ngsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B)\n{\n int j,k,l,n,m;\n double u,x;\n gsl_matrix *U=NULL,*V=NULL;\n gsl_vector *w=NULL;\n\n m = A->size1;\n n = A->size2;\n\n if (B == NULL) {\n B = gsl_matrix_calloc (n,m);\n }\n\n U = gsl_matrix_calloc (m, n);\n V = gsl_matrix_calloc (n, n);\n w = gsl_vector_calloc (n);\n\n\n /* singular value decomposition */\n gsl_matrix_memcpy (U,A);\n gsl_linalg_SV_decomp_jacobi(U,V,w);\n gsl_matrix_set_zero(B);\n\n \n k=0;\n for (j=0; jdata[j]) > 1.0e-6) k++;\n }\n if (k < 1) VError(\" Design matrix is singular\\n\");\n \n\n for (k=0; k 1.0e-6) {\n x = gsl_matrix_get(B,k,l);\n\t x += gsl_matrix_get(V,k,j)*gsl_matrix_get(U,l,j)/u;\n gsl_matrix_set(B,k,l,x);\n }\n }\n }\n }\n gsl_matrix_free(U);\n gsl_matrix_free(V);\n gsl_vector_free(w);\n return B;\n}\n", "meta": {"hexsha": "aafd1c8740551e30413dcef0a1192a233d9b596d", "size": 1325, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_2ndlevel/pseudoinv.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_2ndlevel/pseudoinv.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_2ndlevel/pseudoinv.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": 18.4027777778, "max_line_length": 54, "alphanum_fraction": 0.5811320755, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6177047509256264}} {"text": "#include \n#include \n#include \n#include \n\n/* set up parameters for this simulated annealing run */\n\n/* how many points do we try before stepping */\n#define N_TRIES 200 \n\n/* how many iterations for each T? */\n#define ITERS_FIXED_T 1000\n\n/* max step size in random walk */\n#define STEP_SIZE 1.0 \n\n/* Boltzmann constant */\n#define K 1.0 \n\n/* initial temperature */\n#define T_INITIAL 0.008 \n\n/* damping factor for temperature */\n#define MU_T 1.003 \n#define T_MIN 2.0e-6\n\ngsl_siman_params_t params \n = {N_TRIES, ITERS_FIXED_T, STEP_SIZE,\n K, T_INITIAL, MU_T, T_MIN};\n\n/* now some functions to test in one dimension */\ndouble E1(void *xp)\n{\n double x = * ((double *) xp);\n\n return exp(-pow((x-1.0),2.0))*sin(8*x);\n}\n\ndouble M1(void *xp, void *yp)\n{\n double x = *((double *) xp);\n double y = *((double *) yp);\n\n return fabs(x - y);\n}\n\nvoid S1(const gsl_rng * r, void *xp, double step_size)\n{\n double old_x = *((double *) xp);\n double new_x;\n\n double u = gsl_rng_uniform(r);\n new_x = u * 2 * step_size - step_size + old_x;\n\n memcpy(xp, &new_x, sizeof(new_x));\n}\n\nvoid P1(void *xp)\n{\n printf (\"%12g\", *((double *) xp));\n}\n\nint\nmain(int argc, char *argv[])\n{\n const gsl_rng_type * T;\n gsl_rng * r;\n\n double x_initial = 15.5;\n\n gsl_rng_env_setup();\n\n T = gsl_rng_default;\n r = gsl_rng_alloc(T);\n\n gsl_siman_solve(r, &x_initial, E1, S1, M1, P1,\n NULL, NULL, NULL, \n sizeof(double), params);\n\n gsl_rng_free (r);\n return 0;\n}\n", "meta": {"hexsha": "50f08e06ef9fb8bb1349822c3132d9c2093e5d1f", "size": 1577, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/siman.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/doc/examples/siman.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/doc/examples/siman.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 19.0, "max_line_length": 56, "alphanum_fraction": 0.6049461002, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6176270268127673}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble bisect_array_function(double x_interp, void *params) {\n double interp;\n double r_val;\n interp = interpolate(((bisect_af_params *)params)->interp, x_interp);\n r_val = interp - ((bisect_af_params *)params)->value;\n return (r_val);\n}\n\ndouble bisect_array(interp_info *interp, double value, double threshold) {\n double * x;\n double * y;\n double * d2y;\n double x_lo;\n double x_hi;\n double r_val;\n int i;\n int alloc_flag = GBP_FALSE;\n int iter = 0;\n int max_iter = 500;\n int status = GSL_CONTINUE;\n bisect_af_params params;\n gsl_function F;\n const gsl_root_fsolver_type *T;\n gsl_root_fsolver * s;\n\n params.interp = interp;\n params.value = value;\n F.function = bisect_array_function;\n F.params = (void *)(¶ms);\n\n x_lo = interp->x[0];\n x_hi = interp->x[interp->n - 1];\n\n if(fabs(bisect_array_function(x_lo, ¶ms)) < threshold)\n return (x_lo);\n if(fabs(bisect_array_function(x_hi, ¶ms)) < threshold)\n return (x_hi);\n\n T = gsl_root_fsolver_brent;\n s = gsl_root_fsolver_alloc(T);\n gsl_root_fsolver_set(s, &F, x_lo, x_hi);\n\n while(status == GSL_CONTINUE && iter < max_iter) {\n status = gsl_root_fsolver_iterate(s);\n r_val = gsl_root_fsolver_root(s);\n x_lo = gsl_root_fsolver_x_lower(s);\n x_hi = gsl_root_fsolver_x_upper(s);\n status = gsl_root_test_interval(x_lo, x_hi, 0, threshold);\n iter++;\n }\n\n // Clean-up\n gsl_root_fsolver_free(s);\n\n return (r_val);\n}\n", "meta": {"hexsha": "0afe24ff7d874819c145e69963788aace0c39365", "size": 2004, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMisc/bisect_array.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/gbpMisc/bisect_array.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/gbpMisc/bisect_array.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": 30.8307692308, "max_line_length": 74, "alphanum_fraction": 0.5469061876, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6175552733655294}} {"text": "/*! \\file Integrate.h\n * \\brief header file for integrating functions or data.\n */\n\n#ifndef INTEGRATE_H\n#define INTEGRATE_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\nusing namespace std;\nnamespace Math\n{\n /// Integrate function f(x) from x[lower] to x[upper]. Uses some\n /// algorithm I found somewhere, sometime.\n Double_t IntegrateData(const Double_t x[], const Double_t f[], const int lower, \n const int upper);\n\n /// Integrate function f(x) from x[lower] to x[upper]. Uses trapeziod\n /// algorithm.\n Double_t IntegrateTrap(const Double_t x[], const Double_t f[], const int a,\n const int b);\n ///uses adaptive trapezoidal rule based on numerical recipes\n Double_t IntegrateTrapezoidal(const math_function * f, const Double_t a,\n const Double_t b, const int n);\n Double_t IntegrateQTrap(const math_function * f, const Double_t a,\n const Double_t b, const Double_t epsrel, int IMAX=16);\n ///uses simple trapezoidal\n Double_t IntegrateSimpleTrapezoidal(const math_function * f, const Double_t a,\n const Double_t b, const int n);\n\n ///extended closed integration\n Double_t IntegrateClosed(const math_function * f, const Double_t a,\n const Double_t b, const int n);\n\n ///simpsons 3/8 rule\n Double_t IntegrateSimpson(const math_function * f, const Double_t a,\n const Double_t b);\n\n\n ///Romberg integration based on numerical recipes\n Double_t IntegrateRomberg(const math_function * f, const Double_t a,\n const Double_t b, const Double_t epsrel, const int n, const int K);\n\n ///integration based vegas monte carlo integrator. can also return error and chisq\n ///vegas monte is either gsl or NR based vegas integrator.\n Double_t IntegrateVegasMonte(math_multidim_function * f, Double_t *a, Double_t *b, const int n, Double_t *error=0,Double_t*chisq=0,int interations=6);\n double IntegrateVegasMonte(gsl_monte_function * f, double *a, double *b, const int n, double *error=0,double *chisq=0);\n\n ///Romberg integration based on numerical recipes but uses vegas monte carlo integrator.\n Double_t IntegrateRombergMonte(math_multidim_function * f, Double_t *a,\n Double_t *b, const Double_t epsrel, const int sampling, const int n, const int K, int interations=6);\n\n ///subroutine used in my nr vegas integrator.\n void rebin(Double_t rc, int nd, Double_t r[], Double_t xin[], Double_t xi[]);\n ///numerical recipes vegas integrator. for simplicity use IntegrateVegasMonte as interface\n void vegas(math_multidim_function *fxn, Double_t regn[], int ndim, int init,\n unsigned long ncall, int itmx, int nprn, long int idum, Double_t *tgral, Double_t *sd,\n Double_t *chi2a);\n}\n\n#endif\n", "meta": {"hexsha": "6b6ddc7f4c42287f71d2a4150e1b7eb67570744f", "size": 3174, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Math/Integrate.h", "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math/Integrate.h", "max_issues_repo_name": "ICRAR/NBodylib", "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z", "max_forks_repo_path": "src/Math/Integrate.h", "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z", "avg_line_length": 42.8918918919, "max_line_length": 154, "alphanum_fraction": 0.6868304978, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6175307681230666}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ccl.h\"\n\nstatic double einasto_norm_integrand(double x, void *params)\n{\n double alpha = *((double *)(params));\n return x*x*exp(-2*(pow(x,alpha)-1)/alpha);\n}\n\nvoid ccl_einasto_norm_integral(int n_m, double *r_s, double *r_delta, double *alpha,\n\t\t\t double *norm_out,int *status)\n{\n#pragma omp parallel default(none)\t\t\t\\\n shared(n_m, r_s, r_delta, alpha, norm_out, status)\n {\n int ii;\n int status_this=0;\n gsl_function F;\n gsl_integration_workspace *w = gsl_integration_workspace_alloc(1000);\n \n if (w == NULL)\n status_this = CCL_ERROR_MEMORY;\n \n if(status_this == 0) {\n#pragma omp for\n for(ii=0;ii\r\n#include \r\n#include \r\n\r\ngboolean imgproc_to_HSL(CoreImage *src, CoreImage **dst) {\r\n CoreSize *size;\r\n CoreColorSpace src_color_space;\r\n CorePixelType src_pixel_type;\r\n gdouble *src_data_cast, *dst_data;\r\n gdouble *hsl_pixel, *rgb_pixel, c_max, c_min, c;\r\n gsize i, j, area;\r\n\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n src_color_space = core_image_get_color_space(src);\r\n src_pixel_type = core_image_get_pixel_type(src);\r\n\r\n g_return_val_if_fail(src_color_space == CORE_COLOR_SPACE_RGB, FALSE);\r\n\r\n if (core_pixel_is_double(src_pixel_type)) {\r\n src_data_cast = core_image_get_data(src);\r\n } else if (core_pixel_is_uint8(src_pixel_type)) {\r\n src_data_cast = malloc(sizeof(gdouble) * core_size_get_area(size));\r\n for (i = 0; i < core_size_get_area(size) * 3; ++i) {\r\n src_data_cast[i] = ((guint8 *) core_image_get_data(src))[i] / core_pixel_get_range(src_pixel_type);\r\n }\r\n } else {\r\n return FALSE;\r\n }\r\n\r\n dst_data = g_malloc(sizeof(gdouble) * core_size_get_area(size));\r\n for (i = 0; i < area; ++i) {\r\n hsl_pixel = dst_data + i * 3;\r\n rgb_pixel = src_data_cast + i * 3;\r\n c_min = 1;\r\n c_max = 0;\r\n c = c_max - c_min;\r\n for (j = 0; j < 3; ++j) {\r\n if (rgb_pixel[j] > c_max) {\r\n c_max = rgb_pixel[j];\r\n }\r\n if (rgb_pixel[j] < c_min) {\r\n c_max = rgb_pixel[j];\r\n }\r\n }\r\n\r\n /* Lightness */\r\n hsl_pixel[2] = (c_min + c_max) / 2;\r\n\r\n /* Saturation */\r\n if (!c) {\r\n hsl_pixel[1] = 0;\r\n } else {\r\n hsl_pixel[1] = c / (1 - fabs(hsl_pixel[2] * 2 - 1));\r\n }\r\n\r\n /* Hue */\r\n if (!c) {\r\n hsl_pixel[0] = 0;\r\n } else {\r\n if (rgb_pixel[0] == c_max) {\r\n hsl_pixel[0] = 1.0 / 6 * (rgb_pixel[1] - rgb_pixel[2]) / c;\r\n } else if (rgb_pixel[1] == c_max) {\r\n hsl_pixel[0] = 1.0 / 6 * (2 + (rgb_pixel[2] - rgb_pixel[0]) / c);\r\n } else if (rgb_pixel[2] == c_max) {\r\n hsl_pixel[0] = 1.0 / 6 * (4 + (rgb_pixel[0] - rgb_pixel[1]) / c);\r\n }\r\n }\r\n }\r\n\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);\r\n }\r\n\r\n if (core_pixel_is_uint8(src_pixel_type)) {\r\n free(src_data_cast);\r\n }\r\n g_object_unref(size);\r\n\r\n return TRUE;\r\n}\r\n\r\ngboolean imgproc_to_RGB(CoreImage *src, CoreImage **dst) {\r\n CoreSize *size;\r\n CoreColorSpace color_space;\r\n CorePixelType pixel_type;\r\n gdouble *src_data, *dst_data;\r\n gdouble *hsl_pixel, *rgb_pixel;\r\n gdouble c, h, h_ceil, x, m, r, g, b;\r\n gsize i, area;\r\n\r\n g_return_val_if_fail(src, FALSE);\r\n color_space = core_image_get_color_space(src);\r\n pixel_type = core_image_get_pixel_type(src);\r\n g_return_val_if_fail(color_space == CORE_COLOR_SPACE_HSL, FALSE);\r\n g_return_val_if_fail(pixel_type == CORE_PIXEL_D3, FALSE);\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n src_data = core_image_get_data(src);\r\n dst_data = g_malloc(sizeof(gdouble) * area);\r\n for (i = 0; i < area; ++i) {\r\n hsl_pixel = src_data + i * 3;\r\n rgb_pixel = dst_data + i * 3;\r\n\r\n c = (1 - fabs(2 * hsl_pixel[2] - 1));\r\n h = hsl_pixel[0] * 6.0;\r\n x = c * (1 - fabs(h - floor(h / 2) * 2 - 1));\r\n h_ceil = ceil(h) + DBL_EPSILON;\r\n if (h_ceil >= 6) {\r\n r = c;\r\n g = 0;\r\n b = x;\r\n } else if (h_ceil >= 5) {\r\n r = x;\r\n g = 0;\r\n b = c;\r\n } else if (h_ceil >= 4) {\r\n r = 0;\r\n g = x;\r\n b = c;\r\n } else if (h_ceil >= 3) {\r\n r = 0;\r\n g = c;\r\n b = x;\r\n } else if (h_ceil >= 2) {\r\n r = x;\r\n g = c;\r\n b = 0;\r\n } else if (h_ceil >= 1) {\r\n r = c;\r\n g = x;\r\n b = 0;\r\n } else {\r\n r = g = b = 0;\r\n }\r\n m = hsl_pixel[2] - c / 2;\r\n rgb_pixel[0] = r + m;\r\n rgb_pixel[1] = g + m;\r\n rgb_pixel[2] = b + m;\r\n }\r\n\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_RGB, CORE_PIXEL_D3, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_RGB, CORE_PIXEL_D3, size, FALSE);\r\n }\r\n\r\n g_object_unref(size);\r\n return TRUE;\r\n}\r\n\r\ngboolean imgproc_to_grayscale(CoreImage *src, CoreImage **dst) {\r\n gsize i;\r\n CoreSize *size;\r\n gdouble *dst_data_cast, *src_data_cast;\r\n gpointer src_data, dst_data;\r\n gsize channel, area;\r\n CorePixelType pixel_type;\r\n g_return_val_if_fail(src != NULL, FALSE);\r\n g_return_val_if_fail(dst != NULL, FALSE);\r\n\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n pixel_type = core_image_get_pixel_type(src);\r\n channel = core_image_get_channel(src);\r\n src_data = core_image_get_data(src);\r\n\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n src_data_cast = g_malloc(area * sizeof(gdouble) * channel);\r\n for (i = 0; i < area * channel; ++i) {\r\n src_data_cast[i] = (gdouble) ((guint8 *) src_data)[i];\r\n }\r\n } else {\r\n /* do not need to cast if pixel type is Dx */\r\n src_data_cast = src_data;\r\n }\r\n dst_data_cast = g_malloc(area * sizeof(gdouble));\r\n\r\n cblas_dcopy(area, src_data_cast, channel, dst_data_cast, 1);\r\n for (i = 1; i < channel; ++i) {\r\n cblas_daxpy(area, 1.0, src_data_cast + i, channel, dst_data_cast, 1);\r\n }\r\n if (channel > 1) {\r\n cblas_daxpy(area, 1.0 / channel - 1.0, dst_data_cast, 1, dst_data_cast, 1);\r\n }\r\n\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n pixel_type = CORE_PIXEL_U1;\r\n } else if (core_pixel_is_double(pixel_type)) {\r\n pixel_type = CORE_PIXEL_D1;\r\n } else {\r\n g_return_val_if_fail(FALSE, FALSE);\r\n }\r\n\r\n /* cast dst_data from double back to uchar if needed */\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n for (i = 0; i < area; ++i) {\r\n ((guint8 *) dst_data_cast)[i] = dst_data_cast[i];\r\n }\r\n }\r\n dst_data = dst_data_cast;\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n dst_data = g_realloc(dst_data, sizeof(guint8) * area);\r\n }\r\n\r\n /* assign result */\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_GRAY_SCALE, pixel_type, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_GRAY_SCALE, pixel_type, size, FALSE);\r\n }\r\n\r\n /* free additional allocated memory */\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n g_free(src_data_cast);\r\n }\r\n g_object_unref(size);\r\n return TRUE;\r\n}\r\n\r\ngboolean imgproc_to_binary_threshold(CoreImage *src, CoreImage **dst, gdouble threshold, gboolean inverse) {\r\n CoreImage *gray_src = NULL;\r\n CoreSize *size;\r\n gsize i, area;\r\n gdouble *src_data, *dst_data;\r\n CoreColorSpace color_space;\r\n CorePixelType pixel_type;\r\n g_return_val_if_fail(src != NULL, FALSE);\r\n g_return_val_if_fail(dst != NULL, FALSE);\r\n\r\n if (core_image_get_channel(src) > 1) {\r\n imgproc_to_grayscale(src, &gray_src);\r\n } else {\r\n gray_src = g_object_ref(src);\r\n }\r\n size = core_image_get_size(gray_src);\r\n area = core_size_get_area(size);\r\n src_data = core_image_get_data(gray_src);\r\n dst_data = g_malloc(sizeof(gdouble) * area);\r\n for (i = 0; i < area; ++i) {\r\n dst_data[i] = ((unsigned) (src_data[i] > threshold) ^ (unsigned) inverse) * 255.0;\r\n }\r\n if (*dst == NULL) {\r\n core_image_new_with_data(dst_data, CORE_COLOR_SPACE_BIN, CORE_PIXEL_U1, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_BIN, CORE_PIXEL_U1, size, FALSE);\r\n }\r\n g_object_unref(size);\r\n g_object_unref(gray_src);\r\n return TRUE;\r\n}\r\n", "meta": {"hexsha": "15e03a4463d18abee181c83a4e62c0915a24df89", "size": 8312, "ext": "c", "lang": "C", "max_stars_repo_path": "imgproc/color-convert.c", "max_stars_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_stars_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "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": "imgproc/color-convert.c", "max_issues_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_issues_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imgproc/color-convert.c", "max_forks_repo_name": "zhengbanbufengbi/EasyPhotoshop", "max_forks_repo_head_hexsha": "de62bdd6fe0c7359453ce83fa6efa6592d9bf821", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2170542636, "max_line_length": 112, "alphanum_fraction": 0.5581087584, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6172997195717452}} {"text": "/*---\n Flow*: A Verification Tool for Cyber-Physical Systems.\n Authors: Xin Chen, Sriram Sankaranarayanan, and Erika Abraham.\n Email: Xin Chen if you have questions or comments.\n \n The code is released as is under the GNU General Public License (GPL).\n---*/\n\n#ifndef MATRIX_H_\n#define MATRIX_H_\n\n#include \"include.h\"\n#include \n#include \n\nnamespace flowstar\n{\n\nclass Real;\nclass Interval;\nclass UnivariatePolynomial;\nclass Polynomial;\nclass RowVector;\nclass ColVector;\nclass rMatrix;\nclass iMatrix;\nclass upMatrix;\nclass mpMatrix;\nclass iMatrix2;\nclass HybridSystem;\nclass TaylorModelVec;\n\n\n// The matrix class is implemented based on the data structure of gsl matrix.\nclass Matrix\n{\nprivate:\n\tgsl_matrix *data;\npublic:\n\tMatrix();\n\tMatrix(const int m, const int n);\t// Create an m x n matrix, all of the entries are 0.\n\tMatrix(const int n);\t\t\t\t// Create an n x n matrix, all of the entries are 0.\n\tMatrix(const Matrix & A);\n\t~Matrix();\n\n\tdouble get(const int i, const int j) const;\t\t\t\t// Get the entry at position [i,j].\n\tvoid set(const double v, const int i, const int j);\t\t// Set A[i,j] = v.\n\n\tint rows() const;\n\tint cols() const;\n\n\tvoid row(RowVector & result, const int i) const;\t\t\t// Return the (i+1)-st row.\n\n\tvoid sortColumns();\t\t// Sort the columns by size in descending order.\n\tint rank() const;\n\n\tvoid neg(Matrix & result) const;\n\tvoid neg_assign();\n\n\tvoid inverse(Matrix & result) const;\n\tvoid inverse_assign();\n\n\tvoid transpose(Matrix & result) const;\n\tvoid svd(Matrix & U) const;\n\n\tvoid QR(Matrix & D);\n\tvoid QRfactor(Matrix & Q);\n\n\tvoid output(FILE *fp) const;\n\n\tMatrix & operator += (const Matrix & A);\n\tMatrix & operator -= (const Matrix & A);\n\tMatrix & operator *= (const Matrix & A);\n\n\tMatrix operator + (const Matrix & A) const;\n\tMatrix operator - (const Matrix & A) const;\n\tMatrix operator * (const Matrix & A) const;\n\n\tMatrix & operator = (const Matrix & A);\n};\n\nclass RowVector\n{\nprivate:\n\tMatrix vec;\npublic:\n\tRowVector();\n\tRowVector(const int n);\n\tRowVector(const RowVector & v);\n\t~RowVector();\n\n\tvoid set(const double v, const int pos);\n\tdouble get(const int pos) const;\n\tint size() const;\n\n\tvoid transpose(ColVector & result) const;\n\n\tvoid neg(RowVector & result) const;\n\tvoid neg_assign();\n\n\tvoid dump(FILE *fp) const;\n\n\tdouble innerProd(const RowVector & v) const;\n\tdouble EuclideanNorm() const;\n\tvoid normalize();\n\n\tbool operator == (const RowVector & v) const;\n\n\tRowVector & operator += (const RowVector & v);\n\tRowVector & operator -= (const RowVector & v);\n\tRowVector operator + (const RowVector & v) const;\n\tRowVector operator - (const RowVector & v) const;\n\n\tRowVector & operator = (const RowVector & v);\n\n\tfriend class ColVector;\n};\n\nclass ColVector\n{\nprivate:\n\tMatrix vec;\npublic:\n\tColVector();\n\tColVector(const int n);\n\tColVector(const ColVector & v);\n\t~ColVector();\n\n\tvoid set(const double v, const int pos);\n\tdouble get(const int pos) const;\n\tint size() const;\n\n\tvoid transpose(RowVector & result) const;\n\n\tvoid neg(ColVector & result) const;\n\tvoid neg_assign();\n\n\tvoid mul(ColVector & result, const Matrix & m) const;\n\tvoid mul_assign(const Matrix & m);\n\n\tColVector & operator += (const ColVector & v);\n\tColVector & operator -= (const ColVector & v);\n\tColVector operator + (const ColVector & v) const;\n\tColVector operator - (const ColVector & v) const;\n\n\tColVector & operator = (const ColVector & v);\n\n\tfriend class RowVector;\n};\n\n\nclass bMatrix\n{\nprotected:\n\tbool *data;\n\tint size1;\n\tint size2;\n\npublic:\n\tbMatrix();\n\tbMatrix(const int m, const int n);\n\tbMatrix(const bMatrix & B);\n\t~bMatrix();\n\n\tint rows() const;\n\tint cols() const;\n\n\tvoid output(FILE *fp) const;\n\n\tbMatrix & operator += (const bMatrix & B);\n\tbool * operator [] (const int i);\n\n\tbMatrix & operator = (const bMatrix & B);\n};\n\n\nclass rMatrix\n{\nprotected:\n\tReal *data;\n\tint size1;\n\tint size2;\n\npublic:\n\trMatrix();\n\trMatrix(const int m, const int n);\t// zero matrix\n\trMatrix(const int n);\t\t\t\t// identity matrix\n\trMatrix(const rMatrix & rmatrix);\n\t~rMatrix();\n\n\tint rows() const;\n\tint cols() const;\n\n\tvoid abs(rMatrix & result) const;\n\tvoid transpose(rMatrix & result) const;\n\n\tvoid add_RNDD(rMatrix & result, const rMatrix & rmatrix) const;\n\tvoid add_assign_RNDD(const rMatrix & rmatrix);\n\tvoid add_RNDU(rMatrix & result, const rMatrix & rmatrix) const;\n\tvoid add_assign_RNDU(const rMatrix & rmatrix);\n\n\tvoid mul_RNDD(rMatrix & result, const rMatrix & rmatrix) const;\n\tvoid mul_RNDU(rMatrix & result, const rMatrix & rmatrix) const;\n\n\tvoid output(FILE *fp) const;\n\n\trMatrix & operator += (const rMatrix & B);\n\trMatrix & operator -= (const rMatrix & B);\n\trMatrix & operator *= (const rMatrix & B);\n\trMatrix operator + (const rMatrix & B) const;\n\trMatrix operator - (const rMatrix & B) const;\n\trMatrix operator * (const rMatrix & B) const;\n\n\trMatrix & operator *= (const Real & r);\n\trMatrix & operator *= (const double d);\n\n\trMatrix & operator = (const rMatrix & rmatrix);\t\t// should always be the same precision\n\n\tReal * operator [] (const int i);\n\n\tfriend void to_iMatrix2(iMatrix2 & result, const rMatrix & lo, const rMatrix & up);\n\n\tfriend class iMatrix;\n\tfriend class iMatrix2;\n\tfriend class upMatrix;\n};\n\n\n\n// matrix for intervals\nclass iMatrix\n{\nprotected:\n\tInterval *data;\n\tint size1;\n\tint size2;\n\npublic:\n\tiMatrix();\n\tiMatrix(const int m, const int n);\t// zero matrix\n\tiMatrix(const int n);\t\t\t\t// identity matrix\n\tiMatrix(const iMatrix & A);\n\tiMatrix(const rMatrix & A);\n\tiMatrix(const iMatrix2 & A);\n\tiMatrix(const std::vector & box);\n\tiMatrix(const std::string & matlab_format);\n\t~iMatrix();\n\n\tvoid clear();\n\n\tvoid mul(iMatrix & result, iMatrix & A);\n\n\tint rows() const;\n\tint cols() const;\n\n\tbool isZero() const;\n\n\tvoid pow(iMatrix & result, const int order) const;\n\tvoid pow_assign(const int order);\n\n\tdouble max_norm() const;\n\tvoid max_norm(Real & norm) const;\n\n\tvoid transpose(iMatrix & result) const;\n\tvoid times_pars(mpMatrix & result) const;\n\tvoid center();\n\n\tvoid linearTrans(std::vector & result, const std::vector & polyVec) const;\n\n\tvoid right_scale_assign(const std::vector & scalars);\n\n\tvoid to_iMatrix2(iMatrix2 & A) const;\n\n\tvoid output(FILE *fp) const;\n\n\tiMatrix & operator += (const iMatrix & A);\n\tiMatrix & operator += (const Real & rad);\n\tiMatrix & operator -= (const iMatrix & A);\n\tiMatrix & operator *= (const iMatrix & A);\n\tiMatrix & operator *= (const Interval & I);\n\tiMatrix & operator *= (const double c);\n\tiMatrix & operator /= (const Interval & I);\n\tiMatrix & operator /= (const double c);\n\n\tiMatrix operator + (const iMatrix & A) const;\n\tiMatrix operator - (const iMatrix & A) const;\n\tiMatrix operator * (const iMatrix & A) const;\n\tiMatrix operator * (const Interval & I) const;\n\tiMatrix operator * (const double c) const;\n\tupMatrix operator * (const upMatrix & upm) const;\n\n\tmpMatrix operator * (const mpMatrix & mpm) const;\n\tTaylorModelVec operator * (const TaylorModelVec & tmv) const;\n\n\tInterval * operator [] (const int i);\n\tiMatrix & operator = (const iMatrix & A);\n\tiMatrix & operator = (const rMatrix & A);\n\tiMatrix & operator = (const iMatrix2 & A);\n\tiMatrix & operator = (const std::vector & box);\n\n\tfriend class upMatrix;\n\tfriend class mpMatrix;\n\tfriend class rMatrix;\n\tfriend class iMatrix2;\n\tfriend class Zonotope;\n};\n\n\nclass iMatrix2\n{\npublic:\n\trMatrix center;\n\trMatrix radius;\n\npublic:\n\tiMatrix2();\n\tiMatrix2(const int m, const int n);\t// zero matrix\n\tiMatrix2(const int n);\t\t\t\t// identity matrix\n\tiMatrix2(const iMatrix2 & A);\n\tiMatrix2(const iMatrix & A);\n\tiMatrix2(const std::vector & box);\n\t~iMatrix2();\n\n\tint rows() const;\n\tint cols() const;\n\n\tvoid to_iMatrix(iMatrix & A) const;\n\tvoid transpose(iMatrix2 & result) const;\n\tvoid mag(Interval & I, const int i, const int j);\n\tvoid mag(Real & r, const int i, const int j);\n\tvoid add_assign(const Interval & I, const int i, const int j);\n\n\tiMatrix2 & operator += (const iMatrix2 & A);\n\tiMatrix2 & operator += (const iMatrix & A);\n\tiMatrix2 & operator += (const Real & rad);\n\tiMatrix2 & operator *= (const iMatrix2 & A);\n\tiMatrix2 & operator *= (const Interval & I);\n\n\tiMatrix2 operator + (const iMatrix2 & A) const;\n\tiMatrix2 operator * (const iMatrix2 & A) const;\n\tiMatrix operator * (const iMatrix & A) const;\n\tupMatrix operator * (const upMatrix & upm) const;\n\tTaylorModelVec operator * (const TaylorModelVec & tmv) const;\n\n\tiMatrix2 & operator = (const iMatrix2 & A);\n\n\tvoid output(FILE *fp) const;\n\n\tfriend void to_iMatrix2(iMatrix2 & result, const rMatrix & lo, const rMatrix & up);\n\n\tfriend class upMatrix;\n\tfriend class mpMatrix;\n\tfriend class rMatrix;\n\tfriend class iMatrix;\n\tfriend class Zonotope;\n\tfriend class Polynomial;\n\tfriend class HybridSystem;\n};\n\n\n// matrix for univariate polynomials\nclass upMatrix\n{\nprotected:\n\tUnivariatePolynomial *data;\n\tint size1;\n\tint size2;\n\npublic:\n\tupMatrix();\n\tupMatrix(const int m, const int n);\n\tupMatrix(const int n);\n\tupMatrix(const iMatrix & A);\n\tupMatrix(const iMatrix2 & A);\n\tupMatrix(const upMatrix & upm);\n\t~upMatrix();\n\n\tint rows() const;\n\tint cols() const;\n\tint degree() const;\n\n\tbool isZero() const;\n\n\tvoid intEval(iMatrix & result, const std::vector & val_exp_table) const;\t// interval evaluation based on the monomial form\n\tvoid intEval(iMatrix & result, const Interval & val) const;\t\t\t\t\t\t\t// interval evaluation based on the Horner form\n\n\tvoid intEval(iMatrix2 & result, const std::vector & val_exp_table) const;\n\tvoid intEval(iMatrix2 & result, const Interval & val) const;\n\n\tvoid integral();\n\tvoid times_x(const int order);\n\tvoid transpose(upMatrix & result) const;\n\n\tvoid times_pars(mpMatrix & result) const;\n\n\tvoid ctrunc(iMatrix & rem, const int order, const std::vector & val_exp_table);\n\tvoid ctrunc(iMatrix & rem, const int order, const Interval & val);\n\n\tvoid ctrunc(iMatrix & rem1, iMatrix & rem2, const int order, const std::vector & val1_exp_table, const std::vector & val2_exp_table);\n\tvoid ctrunc(iMatrix & rem1, iMatrix & rem2, const int order, const Interval & val1, const Interval & val2);\n\n\tvoid ctrunc(const int order, const std::vector & val_exp_table);\n\tvoid ctrunc(const int order, const Interval & val);\n\n\tvoid nctrunc(const int order);\n\n\tvoid substitute(upMatrix & result, const std::vector & t_exp_table) const;\n\tvoid substitute(upMatrix & result, const UnivariatePolynomial & t) const;\n\n\tvoid output(FILE *fp) const;\n\n\tvoid decompose(upMatrix & positive, upMatrix & negative, iMatrix2 & im2_rem) const;\n\n\tupMatrix & operator += (const upMatrix & upm);\n\tupMatrix & operator += (const iMatrix & A);\n\tupMatrix & operator += (const Real & rad);\n\tupMatrix & operator -= (const upMatrix & upm);\n\tupMatrix & operator -= (const iMatrix & A);\n\tupMatrix & operator *= (const upMatrix & upm);\n\tupMatrix & operator *= (const iMatrix & A);\n\tupMatrix & operator *= (const Interval & I);\n\n\tupMatrix operator + (const upMatrix & upm) const;\n\tupMatrix operator + (const iMatrix & A) const;\n\tupMatrix operator - (const upMatrix & upm) const;\n\tupMatrix operator - (const iMatrix & A) const;\n\tupMatrix operator * (const upMatrix & upm) const;\n\tupMatrix operator * (const iMatrix & A) const;\n\tupMatrix operator * (const iMatrix2 & A) const;\n\tupMatrix operator * (const Interval & I) const;\n\tmpMatrix operator * (const mpMatrix & mpm) const;\n\n\tUnivariatePolynomial * operator [] (const int i);\n\n\tupMatrix & operator = (const upMatrix & upm);\n\n\tfriend class iMatrix;\n\tfriend class iMatrix2;\n};\n\n\n\n\n// matrix for multivariate polynomials\nclass mpMatrix\n{\nprotected:\n\tPolynomial *data;\n\tint size1;\n\tint size2;\n\npublic:\n\tmpMatrix();\n\tmpMatrix(const int m, const int n);\n\tmpMatrix(const int n);\n\tmpMatrix(const mpMatrix & mpm);\n\t~mpMatrix();\n\n\tint rows() const;\n\tint cols() const;\n\n\tvoid intEval(mpMatrix & result, const std::vector & val_exp_table) const;\n\tvoid intEval(iMatrix & result, const std::vector & domain) const;\n\n\tvoid output(FILE *fp, const std::vector & varNames) const;\n\n\tmpMatrix & operator += (const mpMatrix & mpm);\n\n\tmpMatrix operator + (const mpMatrix & mpm) const;\n\n\tPolynomial * operator [] (const int i);\n\tmpMatrix & operator = (const mpMatrix & mpm);\n\n\tfriend class iMatrix;\n\tfriend class upMatrix;\n};\n\n\nclass MatrixParseSetting\n{\npublic:\n\tstd::string strExpression;\n\tiMatrix result;\n\npublic:\n\tMatrixParseSetting();\n\tMatrixParseSetting(const MatrixParseSetting & setting);\n\t~MatrixParseSetting();\n\n\tMatrixParseSetting & operator = (const MatrixParseSetting & setting);\n};\n\n\nvoid to_iMatrix2(iMatrix2 & result, const rMatrix & lo, const rMatrix & up);\n\nextern MatrixParseSetting matrixParseSetting;\n\n}\n\nvoid parse_Matrix();\n\n#endif /* MATRIX_H_ */\n", "meta": {"hexsha": "107ce6bbbcf1cb1aa105c514dc35afe939295749", "size": 12679, "ext": "h", "lang": "C", "max_stars_repo_path": "flowstar-release/Matrix.h", "max_stars_repo_name": "souradeep-111/sherlock", "max_stars_repo_head_hexsha": "bf34fb4713e5140b893c98382055fb963230d69d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2018-02-17T14:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T19:21:00.000Z", "max_issues_repo_path": "flowstar-release/Matrix.h", "max_issues_repo_name": "souradeep-111/sherlock_2", "max_issues_repo_head_hexsha": "763e5817cca2b69f0e96560835a442434980b3a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-09T07:58:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T14:32:02.000Z", "max_forks_repo_path": "flowstar-release/Matrix.h", "max_forks_repo_name": "souradeep-111/sherlock_2", "max_forks_repo_head_hexsha": "763e5817cca2b69f0e96560835a442434980b3a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T15:13:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T04:16:44.000Z", "avg_line_length": 25.2067594433, "max_line_length": 154, "alphanum_fraction": 0.7051029261, "num_tokens": 3291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6169367513161783}} {"text": "#include \n#include \n\n#include \n#include \n\n#define N (4096*4*16)\n\nint main (void)\n{\n long countsq;\n double x, r2;\n //6 dimensional space\n int dim = 6;\n\n gsl_rng *r;\n\n r = gsl_rng_alloc (gsl_rng_taus2);\n gsl_rng_set (r, 1UL);\n\n long i, j, nn;\n\n printf (\"# Iter Npoints Volume AbsErr\\n\");\n nn = N;\n for (j = 0; j < 16; j++)\n {\n countsq = 0L;\n for (i = 0; i < nn; i++)\n {\n // 4-dimensional distance from the origin, squared\n r2 = 0.;\n for (int k = 0; k < dim; k++)\n {\n x = 2 * gsl_rng_uniform (r) - 1.;\n r2 += x * x;\n }\n\n // are we inside the unit ball\n if (r2 <= 1.)\n {\n countsq++;\n }\n }\n // ratio of the volume of the 4-dimensional unit ball and \n // and 4-dimensional cube of side length 2.\n double vol = ((double) countsq) * pow (2, (double) dim) / nn;\n double exact = M_PI * M_PI / 2;\n\n printf (\"%3ld %16ld %f %f\\n\", j, nn, vol, fabs (exact - vol));\n nn *= 2;\n }\n\n gsl_rng_free (r);\n\n return 0;\n}\n", "meta": {"hexsha": "7d09f24ee1e5d5abd3473442fea5f8c4bac38a25", "size": 1229, "ext": "c", "lang": "C", "max_stars_repo_path": "example.c", "max_stars_repo_name": "jlichtman13/fin2", "max_stars_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0", "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": "example.c", "max_issues_repo_name": "jlichtman13/fin2", "max_issues_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0", "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": "example.c", "max_forks_repo_name": "jlichtman13/fin2", "max_forks_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0", "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.5614035088, "max_line_length": 75, "alphanum_fraction": 0.4540276648, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.616783399023126}} {"text": "#include \n#include \n#include \n#include \n\ndouble fn1 (double x, void * params)\n{\n return cos(x) + 1.0;\n}\n\nint\nmain (void)\n{\n int status;\n int iter = 0, max_iter = 100;\n const gsl_min_fminimizer_type *T;\n gsl_min_fminimizer *s;\n double m = 2.0, m_expected = M_PI;\n double a = 0.0, b = 6.0;\n gsl_function F;\n\n F.function = &fn1;\n F.params = 0;\n\n T = gsl_min_fminimizer_brent;\n s = gsl_min_fminimizer_alloc (T);\n gsl_min_fminimizer_set (s, &F, m, a, b);\n\n printf (\"using %s method\\n\",\n gsl_min_fminimizer_name (s));\n\n printf (\"%5s [%9s, %9s] %9s %10s %9s\\n\",\n \"iter\", \"lower\", \"upper\", \"min\",\n \"err\", \"err(est)\");\n\n printf (\"%5d [%.7f, %.7f] %.7f %+.7f %.7f\\n\",\n iter, a, b,\n m, m - m_expected, b - a);\n\n do\n {\n iter++;\n status = gsl_min_fminimizer_iterate (s);\n\n m = gsl_min_fminimizer_x_minimum (s);\n a = gsl_min_fminimizer_x_lower (s);\n b = gsl_min_fminimizer_x_upper (s);\n\n status \n = gsl_min_test_interval (a, b, 0.001, 0.0);\n\n if (status == GSL_SUCCESS)\n printf (\"Converged:\\n\");\n\n printf (\"%5d [%.7f, %.7f] \"\n \"%.7f %+.7f %.7f\\n\",\n iter, a, b,\n m, m - m_expected, b - a);\n }\n while (status == GSL_CONTINUE && iter < max_iter);\n\n gsl_min_fminimizer_free (s);\n\n return status;\n}\n", "meta": {"hexsha": "45d79a94fe3fb2085be5d0295471cb18a75bc1dc", "size": 1401, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/min.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/min.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/doc/examples/min.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": 21.2272727273, "max_line_length": 52, "alphanum_fraction": 0.5524625268, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6165701043678437}} {"text": "/*\n * cube.c -- solutions of a cubic system\n *\n * (c) 2016 Prof Dr Andreas Mueller, Hochschule Rapperswil\n */\n#include \n#include \n#include \n#include \n#include \n\nint\tf(double x, const double y[], double f[], void *params) {\n\tf[0] = (y[0] - 1) * y[0] * (y[0] + 1);\n\treturn GSL_SUCCESS;\n}\n\nint\tsinglecurve(FILE *out, const char *name, double x0, double y0) {\n\tprintf(\"%s: %f\\n\", name, y0);\n\tgsl_odeiv2_system\tsystem = { f, NULL, 1, NULL };\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6, 1e-6, 0.0);\n\tfprintf(out, \"path %s;\\n\", name);\n\tdouble\tx = x0;\n\tdouble\ty[1] = { y0 };\n\tfprintf(out, \"%s = (%.3f,%.3f)\", name, x, y[0]);\n\tfor (int i = 1; i <= 400; i++) {\n\t\tdouble\txnext = x + 0.01;\n\t\tint\tstatus = gsl_odeiv2_driver_apply(driver, &x, xnext, y);\n\t\tif (status != GSL_SUCCESS) {\n\t\t\tfprintf(stderr, \"error: rc = %d\\n\", status);\n\t\t\tfprintf(out, \";\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (fabs(y[0]) > 100) {\n\t\t\tgoto end;\n\t\t}\n\t\tfprintf(out, \"\\n --(%.3f,%.3f)\", x, y[0]);\n\t}\nend:\n\tfprintf(out, \";\\n\");\n\tgsl_odeiv2_driver_free(driver);\n\treturn 1;\n}\n\nint\tcentercurve(FILE *out, const char *name, double y0) {\n\tgsl_odeiv2_system\tsystem = { f, NULL, 1, NULL };\n\tgsl_odeiv2_driver\t*driver\n\t\t= gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t-1e-6, 1e-6, 0.0);\n\tdouble\tx = 0;\n\tdouble\ty[1] = { y0 };\n\tdouble\txnext = -2;\n\t// integrate backwards to the initial value\n\tint\tstatus = gsl_odeiv2_driver_apply(driver, &x, xnext, y);\n\tgsl_odeiv2_driver_free(driver);\n\tdriver = gsl_odeiv2_driver_alloc_y_new(&system, gsl_odeiv2_step_rk8pd,\n\t\t\t1e-6, 1e-6, 0.0);\n/*\n\tif (fabs(y[0]) > 100) {\n\t\treturn -1;\n\t}\n*/\n\tsinglecurve(out, name, -2, y[0]);\n\treturn 1;\n}\n\nint\tmain(int argc, char *argv[]) {\n\tFILE\t*out = fopen(\"cube.mp\", \"w\");\n\tchar\tsuffix = 'a';\n\tchar\tpathname[6];\n\n\tfor (int i = 0; i < 16; i++) {\n\t\tdouble\ty0 = -1.5 + i * 0.2;\n\t\tsnprintf(pathname, sizeof(pathname), \"path%c\", suffix++);\n\t\tcentercurve(out, pathname, y0);\n\t}\n\t\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f2387aee419b800594c4d26919b52fedee994e5d", "size": 2055, "ext": "c", "lang": "C", "max_stars_repo_path": "skript/chapters/images/cube.c", "max_stars_repo_name": "MatthiasRubin/SeminarDGL", "max_stars_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T07:48:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T07:48:28.000Z", "max_issues_repo_path": "skript/chapters/images/cube.c", "max_issues_repo_name": "MatthiasRubin/SeminarDGL", "max_issues_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skript/chapters/images/cube.c", "max_forks_repo_name": "MatthiasRubin/SeminarDGL", "max_forks_repo_head_hexsha": "a7c452c44097ca851c661d3bc1093204ddae7f67", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3703703704, "max_line_length": 71, "alphanum_fraction": 0.6218978102, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6164913222228859}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#define PI 3.1416\n#define USAGE \"./mcmc_solar.x n_steps n_burn\"\n\nvoid likelihood(float *chi, float *y_obs, float *y_model, int n_puntos);\nvoid my_model(float *mine, float *anio ,float a, float b, float c, float d, int n_puntos);\nvoid mcmc(int n_steps, float *a, float *b, float *c, float *d, float *l, float *x_obs, float *y_obs,int n_puntos, float *mine);\nvoid min(float *mine, float *x_obs, float *a, float *b, float *c, float *d, float *l, int n_steps, int n_puntos);\n\nvoid leer(float *anio, float *manc, int n_puntos);\nfloat *reserva(int n_puntos);\nvoid print_array(float *a, float *b, float *c, float *d , float *l, int n_steps, int n_burn);\n\nint main(int argc, char **argv){\n\t\n\tsrand48(time(NULL));\n\t\n\t//Valores que entran\n\tint n_steps=atof(argv[1]);\n\tint n_burn=atof(argv[2]);\n\t//Inicializacion de los arrays que guardan los datos\n\tint n_puntos= 4141;\n\tfloat *manc;\n\tfloat *anio;\n\tanio=reserva(n_puntos);\n\tmanc=reserva(n_puntos);\n\t\n\tleer(anio, manc, n_puntos);\n\t\n\t//Array con los resultados del ajuste\n\tfloat *mine;\n\tmine=reserva(n_puntos);\n\t\n\t//Arrays que guardan los datos de las variables\n\tfloat *a;\n\tfloat *b;\n\tfloat *c;\n\tfloat *d;\n\tfloat *l;\n\ta=reserva(n_steps);\n\tb=reserva(n_steps);\n\tc=reserva(n_steps);\n\td=reserva(n_steps);\n\tl=reserva(n_steps);\n\t//Primer paso en la cadena\n\ta[0]=drand48();\n\tb[0]=drand48();\n\tc[0]=drand48();\n\td[0]=drand48();\n\tfloat chi;\n\tmy_model(mine,anio,a[0],b[0],c[0],d[0],n_puntos);\n\tlikelihood(&chi,manc,mine,n_puntos);\n\tl[0]=chi;\n\t\n\t//Iteraciones\n\tmcmc(n_steps,a,b,c,d,l,anio,manc,n_puntos,mine);\n\tmin(mine,anio,a,b,c,d,l,n_steps,n_puntos);\n\t\n\tprint_array(a,b,c,d,l,n_steps,n_burn);\n\t\n\tfree(mine);\n\tfree(anio);\n\tfree(manc);\n\tfree(a);\n\tfree(b);\n\tfree(c);\n\tfree(d);\n\t\n\treturn 0;\n}\n\n//OBTENCION DEL MEJOR AJUSTE\nvoid min(float *mine, float *x_obs, float *a, float *b, float *c, float *d, float *l, int n_steps, int n_puntos){\n\tint i;\n\tfloat temp, a2, b2, c2, d2;\n\ttemp=l[0];\n\ta2=a[0];\n\tb2=b[0];\n\tc2=c[0];\n\td2=d[0];\n\tfor(i=1;i l[i] ){\n\t\t\ttemp=l[i];\n\t\t\ta2=a[i];\n\t\t\tb2=b[i];\n\t\t\tc2=c[i];\n\t\t\td2=d[i];\n\t\t}\n\t}\n\tmy_model(mine,x_obs,a2,b2,c2,d2,n_puntos);\n}\n\n//ITERACIONES\nvoid mcmc(int n_steps, float *a, float *b, float *c, float *d, float *l, float *x_obs, float *y_obs,int n_puntos, float *mine){\n\tint i;\n\tfloat a2,b2,c2,d2, chi, chi2, alpha, beta;\n\tconst gsl_rng_type * T;\n\tgsl_rng * r;\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\t\n for(i=0;i<(n_steps-1);i++){\n\t\ta2 = a[i] + gsl_ran_gaussian(r, 0.1);\n\t\tb2 = b[i] + gsl_ran_gaussian(r, 0.1);\n\t\tc2 = c[i] + gsl_ran_gaussian(r, 0.1);\n\t\td2 = c[i] + gsl_ran_gaussian(r, 0.1);\n\t\t\n\t\tfloat *y_init;\n\t\tfloat *y_prime;\n\t\ty_init=reserva(n_puntos);\n\t\ty_prime=reserva(n_puntos);\n\t\t\n\t\tmy_model(y_init,x_obs,a[i],b[i],c[i],d[i],n_puntos);\n\t\tmy_model(y_prime,x_obs,a2,b2,c2,d2,n_puntos);\n\t\n\t\tlikelihood(&chi,y_obs,y_init,n_puntos);\n\t\tlikelihood(&chi2,y_obs,y_prime,n_puntos);\n\t\t\n\t\talpha = -chi2 + chi;\n\t\tif(alpha >= 0.0){\n\t\t\ta[i+1]=a2;\n\t\t\tb[i+1]=b2;\n\t\t\tc[i+1]=c2;\n\t\t\td[i+1]=d2;\n\t\t\tl[i+1]=chi2;\n\t\t}\n\t\telse{\n\t\t\tbeta = drand48();\n\t\t\tif(alpha < -6000.0 ){\n\t\t\t\ta[i+1]=a[i];\n\t\t\t\tb[i+1]=b[i];\n\t\t\t\tc[i+1]=c[i];\n\t\t\t\td[i+1]=d[i];\n\t\t\t\tl[i+1]=chi;\n\t\t\t}\n\t\t\telse if(beta <= exp(alpha)){\n\t\t\t\ta[i+1]=a2;\n\t\t\t\tb[i+1]=b2;\n\t\t\t\tc[i+1]=c2;\n\t\t\t\td[i+1]=d2;\n\t\t\t\tl[i+1]=chi2;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ta[i+1]=a[i];\n\t\t\t\tb[i+1]=b[i];\n\t\t\t\tc[i+1]=c[i];\n\t\t\t\td[i+1]=d[i];\n\t\t\t\tl[i+1]=chi;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfree(y_init);\n\t\tfree(y_prime);\n\t}\n\n gsl_rng_free (r);\n}\n\n//LECTURA DEL ARCHIVO\nvoid leer(float *anio, float *manc, int n_puntos){\n\t\n\tfloat *mes;\n\tmes=reserva(n_puntos);\n\t\n\tFILE *in;\n\tint i;\n\tin=fopen(\"monthrg.dat\",\"r\");\n\tif(!in){\n printf(\"problems opening the file %s\\n\",\"monthrg.dat\");\n exit(1);\n\t}\n\tfloat temp1;\n\tfloat temp2;\n\tfor(i=0;i\n#include \n#include \n\ndouble myfunc(unsigned n, const double *x, double *grad, void *my_func_data)\n{\n //printf(\"%f\\t%f\\t\", grad[0], grad[1]);\n //printf(\"%f\\t%f\\n\", x[0], x[1]); \n if (grad) {\n grad[0] = 0.0;\n grad[1] = 0.5 / sqrt(x[1]);\n }\n //printf(\"%f\\n\", sqrt(x[1]));\n //sleep(1);\n return sqrt(x[1]);\n}\n\ntypedef struct {\n double a, b;\n} my_constraint_data;\n\ndouble myconstraint(unsigned n, const double *x, double *grad, void *data)\n{\n my_constraint_data *d = (my_constraint_data *) data;\n double a = d->a, b = d->b;\n if (grad) {\n grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);\n grad[1] = -1.0;\n }\n return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);\n }\n\n\nint main(){\n double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */\n nlopt_opt opt;\n\n //opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */\n opt = nlopt_create(NLOPT_LN_COBYLA, 2); /* algorithm and dimensionality */\n nlopt_set_lower_bounds(opt, lb);\n nlopt_set_min_objective(opt, myfunc, NULL);\n\n my_constraint_data data[2] = { {2,0}, {-1,1} };\n\n nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);\n nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);\n\n //nlopt_set_xtol_rel(opt, 1e-4);\n nlopt_set_stopval(opt, (sqrt(8./27.) + 1e-3));\n\n double x[2] = { 1.234, 5.678 }; /* `*`some` `initial` `guess`*` */\n double minf; /* `*`the` `minimum` `objective` `value,` `upon` `return`*` */\n if (nlopt_optimize(opt, x, &minf) < 0) {\n\tprintf(\"nlopt failed!\\n\");\n }\n else {\n\tprintf(\"found minimum at f(%g,%g) = %0.10g\\n\", x[0], x[1], minf);\n }\n\n nlopt_destroy(opt);\n}\n", "meta": {"hexsha": "7d37c2d73dc0ce01b173dd166a34305476ed6d5c", "size": 1731, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/tutorial.c", "max_stars_repo_name": "Vindaar/nimnlopt", "max_stars_repo_head_hexsha": "3833ae907beab3da8151c4d364db37686747c082", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-03-22T15:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T07:36:25.000Z", "max_issues_repo_path": "examples/tutorial.c", "max_issues_repo_name": "Vindaar/nimnlopt", "max_issues_repo_head_hexsha": "3833ae907beab3da8151c4d364db37686747c082", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-01T23:55:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-19T16:16:44.000Z", "max_forks_repo_path": "examples/tutorial.c", "max_forks_repo_name": "Vindaar/nimnlopt", "max_forks_repo_head_hexsha": "3833ae907beab3da8151c4d364db37686747c082", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9193548387, "max_line_length": 79, "alphanum_fraction": 0.56152513, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6157631912926194}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n#include \"weaklens.h\"\n\ndouble chiLim;\n\nstatic void comp_lens_power_spectrum(lensPowerSpectra lps);\n\ndouble lens_power_spectrum(double ell, lensPowerSpectra lps)\n{\n if(lps->initFlag == 1 || lps->currCosmoNum != cosmoData.cosmoNum || lps->currWLNum != wlData.wlNum)\n {\n lps->initFlag = 0;\n lps->currCosmoNum = cosmoData.cosmoNum;\n lps->currWLNum = wlData.wlNum;\n \n comp_lens_power_spectrum(lps);\n }\n \n return exp(gsl_spline_eval(lps->spline,log(ell),lps->accel));\n}\n\ndouble nonlinear_powspec_for_lens(double k, double a)\n{\n return nonlinear_powspec(k,a);\n}\n\nstatic double lenskern(double chi, double chis)\n{\n if(chi > chis)\n return 0.0;\n else\n return 1.5*cosmoData.OmegaM*(100.0/CSOL)*(100.0/CSOL)/acomvdist(chi)*(chis-chi)/chis;\n}\n\nstatic double lenspk_integrand(double chi, void *p)\n{\n lensPowerSpectra lps = (lensPowerSpectra) p;\n double sn = lps->sn;\n \n if(chi == 0.0 || chi < chiLim)\n return 0.0;\n else\n return lenskern(chi,lps->chis1)*lenskern(chi,lps->chis2)*(nonlinear_powspec_for_lens(lps->ell/chi,acomvdist(chi)) + sn);\n}\n\nstatic void comp_lens_power_spectrum(lensPowerSpectra lps)\n{\n#define WORKSPACE_NUM 100000\n#define ABSERR 1e-12\n#define RELERR 1e-12\n#define TABLE_LENGTH 1000\n \n gsl_integration_workspace *workspace;\n gsl_function F;\n double result,abserr;\n double logltab[TABLE_LENGTH];\n double logpkltab[TABLE_LENGTH];\n double chimax;\n int i;\n \n //fill in bin information\n chiLim = lps->chiLim;\n if(lps->chis1 > lps->chis2)\n chimax = lps->chis1;\n else\n chimax = lps->chis2;\n \n fprintf(stderr,\"doing lens pk - chiLim = %lf, chiMax = %lf\\n\",chiLim,chimax);\n \n //init\n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n F.function = &lenspk_integrand;\n F.params = lps;\n \n //make table\n double lnlmin = log(wlData.lmin);\n double lnlmax = log(wlData.lmax);\n for(i=0;iell = exp(logltab[i]);\n gsl_integration_qag(&F,0.0,chimax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);\n \n logpkltab[i] = log(result);\n }\n \n //free\n gsl_integration_workspace_free(workspace);\n \n //init splines and accels\n if(lps->spline != NULL)\n gsl_spline_free(lps->spline);\n lps->spline = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));\n gsl_spline_init(lps->spline,logltab,logpkltab,(size_t) (TABLE_LENGTH));\n if(lps->accel != NULL)\n gsl_interp_accel_reset(lps->accel);\n else\n lps->accel = gsl_interp_accel_alloc();\n \n#undef TABLE_LENGTH\n#undef ABSERR\n#undef RELERR\n#undef WORKSPACE_NUM\n}\n\nlensPowerSpectra init_lens_power_spectrum(double zs1, double zs2)\n{\n lensPowerSpectra lps;\n \n lps = (lensPowerSpectra)malloc(sizeof(_lensPowerSpectra));\n assert(lps != NULL);\n \n lps->initFlag = 1;\n lps->zs1 = zs1;\n lps->zs2 = zs2;\n lps->chis1 = comvdist(1.0/(1.0 + zs1));\n lps->chis2 = comvdist(1.0/(1.0 + zs2));\n lps->spline = NULL;\n lps->accel = NULL;\n \n return lps;\n}\n\nvoid free_lens_power_spectrum(lensPowerSpectra lps)\n{\n if(lps->spline != NULL)\n gsl_spline_free(lps->spline);\n if(lps->accel != NULL)\n gsl_interp_accel_free(lps->accel);\n free(lps);\n}\n\n////////////////////////////////////////\n// corr. funcs!\n//////////////////////////////////////\n\nstatic double lenscfp_integrand(double ell, void *p)\n{\n lensCorrFunc lcf = (lensCorrFunc) p;\n \n return ell/2.0/M_PI*lens_power_spectrum(ell,lcf->lps)*gsl_sf_bessel_J0(ell*lcf->theta/60.0/180.0*M_PI);\n \n}\n\nstatic double lenscfm_integrand(double ell, void *p)\n{\n lensCorrFunc lcf = (lensCorrFunc) p;\n \n return ell/2.0/M_PI*lens_power_spectrum(ell,lcf->lps)*gsl_sf_bessel_Jn(4,ell*lcf->theta/60.0/180.0*M_PI);\n}\n\nstatic void comp_lens_corr_funcs(lensCorrFunc lcf)\n{\n#define WORKSPACE_NUM 100000\n#define ABSERR 1e-12\n#define RELERR 1e-12\n#define TABLE_LENGTH 1000\n \n gsl_integration_workspace *workspace;\n gsl_function F;\n double result,abserr;\n double logttab[TABLE_LENGTH];\n double logcfptab[TABLE_LENGTH];\n double logcfmtab[TABLE_LENGTH];\n int i;\n double lntmin;\n double lntmax;\n \n //init\n workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);\n F.params = lcf;\n lntmin = log(wlData.tmin);\n lntmax = log(wlData.tmax);\n \n //make tables\n F.function = &lenscfp_integrand;\n for(i=0;itheta = exp(logttab[i]);\n gsl_integration_qag(&F,wlData.lmin,wlData.lmax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);\n \n logcfptab[i] = log(result);\n }\n \n F.function = &lenscfm_integrand;\n for(i=0;itheta = exp(logttab[i]);\n gsl_integration_qag(&F,wlData.lmin,wlData.lmax,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);\n \n logcfmtab[i] = log(result);\n }\n \n //free\n gsl_integration_workspace_free(workspace);\n \n //init splines and accels\n if(lcf->splineP != NULL)\n gsl_spline_free(lcf->splineP);\n lcf->splineP = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));\n gsl_spline_init(lcf->splineP,logttab,logcfptab,(size_t) (TABLE_LENGTH));\n if(lcf->accelP != NULL)\n gsl_interp_accel_reset(lcf->accelP);\n else\n lcf->accelP = gsl_interp_accel_alloc();\n \n if(lcf->splineM != NULL)\n gsl_spline_free(lcf->splineM);\n lcf->splineM = gsl_spline_alloc(gsl_interp_akima,(size_t) (TABLE_LENGTH));\n gsl_spline_init(lcf->splineM,logttab,logcfmtab,(size_t) (TABLE_LENGTH));\n if(lcf->accelM != NULL)\n gsl_interp_accel_reset(lcf->accelM);\n else\n lcf->accelM = gsl_interp_accel_alloc();\n \n#undef TABLE_LENGTH\n#undef ABSERR\n#undef RELERR\n#undef WORKSPACE_NUM \n}\n\ndouble lens_corr_func_minus(double theta, lensCorrFunc lcf)\n{\n if(lcf->initFlag == 1 || lcf->currCosmoNum != cosmoData.cosmoNum || lcf->currWLNum != wlData.wlNum)\n {\n lcf->initFlag = 0;\n lcf->currCosmoNum = cosmoData.cosmoNum;\n lcf->currWLNum = wlData.wlNum;\n\n comp_lens_corr_funcs(lcf);\n }\n\n return exp(gsl_spline_eval(lcf->splineM,log(theta),lcf->accelM));\n}\n\ndouble lens_corr_func_plus(double theta, lensCorrFunc lcf)\n{\n if(lcf->initFlag == 1 || lcf->currCosmoNum != cosmoData.cosmoNum || lcf->currWLNum != wlData.wlNum)\n {\n lcf->initFlag = 0;\n lcf->currCosmoNum = cosmoData.cosmoNum;\n lcf->currWLNum = wlData.wlNum;\n\n comp_lens_corr_funcs(lcf);\n }\n\n return exp(gsl_spline_eval(lcf->splineP,log(theta),lcf->accelP));\n}\n\nlensCorrFunc init_lens_corr_func(lensPowerSpectra lps)\n{\n lensCorrFunc lcf;\n \n lcf = (lensCorrFunc)malloc(sizeof(_lensCorrFunc));\n assert(lcf != NULL);\n \n lcf->initFlag = 1;\n lcf->lps = lps;\n lcf->splineM = NULL;\n lcf->accelM = NULL;\n lcf->splineP = NULL;\n lcf->accelP = NULL;\n \n return lcf;\n}\n\nvoid free_lens_corr_func(lensCorrFunc lcf)\n{\n if(lcf->splineM != NULL)\n gsl_spline_free(lcf->splineM);\n if(lcf->accelM != NULL)\n gsl_interp_accel_free(lcf->accelM);\n \n if(lcf->splineP != NULL)\n gsl_spline_free(lcf->splineP);\n if(lcf->accelP != NULL)\n gsl_interp_accel_free(lcf->accelP);\n \n free(lcf);\n}\n", "meta": {"hexsha": "44ff672b1b1a51d6b925b640610e2b0178488f6f", "size": 7567, "ext": "c", "lang": "C", "max_stars_repo_path": "src/weaklens.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/weaklens.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/weaklens.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": 25.4781144781, "max_line_length": 135, "alphanum_fraction": 0.684154883, "num_tokens": 2550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.6157429888727881}} {"text": "/** @file\n * Based on the paper:\n * Quintana, F.A. (1998) ``Nonparametric Bayesian analysis for assessing homogeneity in $ k\\times l$\n * contingency tables with fixed right margin totals''.\n * Also as Technical Report PUC/FM-96/7. Journal of the American Statistical Association, 93(443), 1140-1149.\n * Available as compressed postscript.\n * http://www.mat.puc.cl/~quintana/hcttr.ps.gz\n */\n\n#ifndef BIO_CONTINGENCY_HOMOGENEITY_H_\n#define BIO_CONTINGENCY_HOMOGENEITY_H_\n\n#include \"bio/defs.h\"\n#include \"bio/partition.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nBIO_NS_START\n\ntypedef std::vector gamma_vec_t;\nextern gamma_vec_t contingency_gamma_exponential_prior;\n\ntemplate \ndouble\ncalculate_ln_D(\n\tLambdaIt lambda_begin,\n\tLambdaIt lambda_end)\n{\n\tdouble result = gsl_sf_lngamma(std::accumulate(lambda_begin, lambda_end, double(0)));\n\tfor (LambdaIt i = lambda_begin; lambda_end != i; ++i)\n\t{\n\t\tresult -= gsl_sf_lngamma(*i);\n\t}\n\n\treturn result;\n}\n\n/** Calculate natural logarithm of a term for one partition in Lm(n). */\ntemplate \ndouble\ncontingency_calculate_ln_L_term(\n\tPartitionIt part_it,\n\tunsigned m,\n\tCountIt n_begin,\n\tCountIt n_end,\n\tLambdaIt lambda_begin,\n\tLambdaIt lambda_end)\n{\n\tdouble ln_result = 1.0;\n\n#ifdef BIO_CONTINGENCY_PRINT_PARTITIONS\n\t//can only do this for smallish numbers\n\tif (26 >= part_it.M.size())\n\t{\n\t\tstd::vector v;\n\t\tfor (unsigned i = 0; i != part_it.M.size(); ++i)\n\t\t{\n\t\t\tv.push_back('a' + i);\n\t\t}\n\t\tstd::cout << *part_it[v] << '\\n';\n\t}\n#endif //BIO_CONTINGENCY_PRINT_PARTITIONS\n\n\t//for each set in the partition\n\tfor (unsigned i = 0; i < m; ++i)\n\t{\n\t\t//calculate lambda + n\n\t\ttypedef std::vector lambda_vec_t;\n\t\tlambda_vec_t lambda_plus_n;\n\t\t{\n\t\t\tstd::copy(lambda_begin, lambda_end, std::inserter(lambda_plus_n, lambda_plus_n.begin()));\n\t\t\tunsigned e_i = 0;\n\t\t\tunsigned j = 0;\n\t\t\t//for each index\n\t\t\tfor (CountIt n = n_begin; n_end != n; ++j, ++n)\n\t\t\t{\n\t\t\t\t//is this j in this partition?\n\t\t\t\tif (i == part_it.M[j])\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned k = 0; k != (*n).size(); ++k)\n\t\t\t\t\t{\n\t\t\t\t\t\tlambda_plus_n[k] += (*n)[k];\n\t\t\t\t\t}\n\t\t\t\t\tif (1 < e_i)\n\t\t\t\t\t{\n\t\t\t\t\t\tln_result += gsl_sf_log(double(e_i)); //the factorial term\n\t\t\t\t\t}\n\t\t\t\t\t++e_i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tln_result += calculate_ln_D(lambda_begin, lambda_end);\n\t\tln_result -= calculate_ln_D(lambda_plus_n.begin(), lambda_plus_n.end());\n\t}\n\n\treturn ln_result;\n}\n\n/** Calculate Lm(n). */\ntemplate \ndouble\ncontingency_calculate_L(\n\tunsigned m,\n\tCountIt n_begin,\n\tCountIt n_end,\n\tLambdaIt lambda_begin,\n\tLambdaIt lambda_end)\n{\n\tunsigned set_size = unsigned(n_end - n_begin);\n\tBOOST_ASSERT(unsigned(lambda_end - lambda_begin) == set_size);\n\n\tdouble result = 0;\n\n\t//iterate over all the partitions\n\tpartition::iterator_k part_it(set_size, m);\n\ttry\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\tconst double ln_L_term =\n\t\t\t\tcontingency_calculate_ln_L_term(\n\t\t\t\t\tpart_it,\n\t\t\t\t\tm,\n\t\t\t\t\tn_begin,\n\t\t\t\t\tn_end,\n\t\t\t\t\tlambda_begin,\n\t\t\t\t\tlambda_end);\n\n\t\t\t//check for underflow - in which case it will be 0.\n\t\t\tif (ln_L_term > GSL_LOG_DBL_MIN)\n\t\t\t{\n\t\t\t\tresult += gsl_sf_exp(ln_L_term);\n\t\t\t}\n\n\t\t\t++part_it;\n\t\t}\n\t}\n\tcatch (std::overflow_error&) //how the partition code determines there are no more partitions!\n\t{\n\t}\n\n\treturn result;\n}\n\ntemplate \nValue\nfactorial(Value value)\n{\n\tValue result = Value(1);\n\twhile (value != 0)\n\t{\n\t\tresult *= value;\n\t\t--value;\n\t}\n\treturn result;\n}\n\ntypedef double(* contingency_cluster_prior)(double c, void * void_params);\n\nstruct ContingencyClusterPrior\n{\n\tvirtual double operator()(double c) = 0;\n\tvirtual double get_ln_prior(double c);\n};\n\nstruct ExponentialPrior : ContingencyClusterPrior\n{\n\tdouble mean;\n\tExponentialPrior(double mean = 1.0);\n\tdouble operator()(double c);\n\tdouble get_ln_prior(double c);\n};\n\nstruct GammaParams\n{\n\tunsigned m;\n\tunsigned k;\n\tContingencyClusterPrior * prior;\n};\n\ndouble\ngamma_exponential_prior_integrand(double c, void * void_params);\n\ndouble\ncontingency_calculate_gamma(\n\tunsigned m,\n\tunsigned k,\n\tContingencyClusterPrior * prior);\n\n\ntemplate \ndouble\ncontingency_calculate_bayes_factor(\n\tGammaIt gamma_begin,\n\tGammaIt gamma_end,\n\tCountIt n_begin,\n\tCountIt n_end,\n\tLambdaIt lambda_begin,\n\tLambdaIt lambda_end)\n{\n\tconst unsigned k = unsigned(n_end == n_begin ? 0 : n_begin->end() - n_begin->begin());\n\n\tdouble result = contingency_calculate_L(1, n_begin, n_end, lambda_begin, lambda_end);\n\n\tresult *= (1 - factorial(k-1) * (*gamma_begin));\n\n\tresult /= factorial(k-1);\n\n\tdouble sum = 0;\n\tfor (unsigned i = 2; k + 1 != i; ++i)\n\t{\n\t\tsum += *(gamma_begin + i - 1) * contingency_calculate_L(i, n_begin, n_end, lambda_begin, lambda_end);\n\t}\n\tresult /= sum;\n\n\treturn result;\n}\n\n/** Contains the data for a contingency table and defines types. */\ntemplate \nstruct ContingencyTable\n{\n\ttypedef boost::array row_t;\n\ttypedef boost::array table_t;\n\ttypedef boost::array lambda_vec_t;\n\n\ttable_t data;\n\n\tstatic unsigned get_k() { return K; }\n\tstatic unsigned get_l() { return L; }\n};\n\ntemplate \nstd::ostream &\noperator<<(std::ostream & os, const ContingencyTable & table)\n{\n\tfor (unsigned l = 0; L != l; ++l)\n\t{\n\t\tfor (unsigned k = 0; K != k; ++k)\n\t\t{\n\t\t\tos << table.data[l][k] << '\\t';\n\t\t}\n\t\tos << '\\n';\n\t}\n\treturn os;\n}\n\n\n\nBIO_NS_END\n\n\n#endif //BIO_CONTINGENCY_HOMOGENEITY_H_\n", "meta": {"hexsha": "99f1c77f03a8412f4cef7aa86e591c708c4e7bbc", "size": 5576, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/bio/contingency_homogeneity.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/contingency_homogeneity.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/contingency_homogeneity.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": 21.2015209125, "max_line_length": 109, "alphanum_fraction": 0.693687231, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6154238739004423}} {"text": "//\n// her2.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 _her2_h\n#define _her2_h\n\n/// @file her2.h Performs complex outer product of two vectors.\n\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs a vector outer product of two complex vectors.\n ///\n /// For a complex Hermitian matrix A, complex vectors x and y, and complex scalar alpha,\n ///\n /// A := alpha * x * y' + conj(alpha) * y * 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 Complex scalar.\n /// @param x Pointer to complex vector x.\n /// @param incx Increment of the vector x. x!=0\n /// @param y Pointer to complex vector y.\n /// @param incy Increment of the vector y. y!=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 HER2(char uplo, int_t n, complex alpha, complex *x, int_t incx, complex *y, int_t incy, complex *A, int_t ldA)\n {\n using std::conj;\n using std::real;\n using std::toupper;\n const complex zero(0.0,0.0);\n complex tx,ty;\n int_t i,j,kx,ky,jx,ix,jy,iy;\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(incy==0)\n return -7;\n else if(ldA0)?0:(1-n)*incx;\n ky=(incy>0)?0:(1-n)*incy;\n if(uplo=='U')\n {\n jx=kx;\n jy=ky;\n for(j=0;j\n\n template <> int HER2(char uplo, int_t n, complex alpha, complex *x, int_t incx, complex *y, int_t incy, 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 HER2(char uplo, int_t n, complex alpha, complex *x, int_t incx, complex *y, int_t incy, 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 \"angle.h\"\n#include \n#include \"halley/text/string_converter.h\"\n#include \n\n#ifdef min\n#undef min\n#endif\n#ifdef max\n#undef max\n#endif\n\nnamespace Halley {\n\t//////////////////////////////\n\t// Vector2D class declaration\n\ttemplate >\n\tclass Vector2D {\n\tprivate:\n\t\tconstexpr T mod(T a, T b) const { return a % b; }\n\n\tpublic:\n\t\tT x,y;\n\n\t\t// Constructors\n\t\tconstexpr Vector2D () : x(0), y(0) {}\n\t\t\n\t\tconstexpr Vector2D (T _x, T _y) : x(_x), y(_y) {}\n\t\t\n\t\ttemplate \n\t\tconstexpr explicit Vector2D (Vector2D vec) : x(T(vec.x)), y(T(vec.y)) {}\n\n\t\tVector2D (T length, U angle)\n\t\t{\n\t\t\tfloat s, c;\n\t\t\tangle.sincos(s, c);\n\t\t\tx = s*length;\n\t\t\ty = c*length;\n\t\t}\n\n\t\t// Getter\n\t\tconstexpr inline T& operator[](size_t n)\n\t\t{\n\t\t\tExpects(n <= 1);\n\t\t\treturn (&x)[n];\n\t\t}\n\t\tconstexpr inline T operator[](size_t n) const\n\t\t{\n\t\t\tExpects(n <= 1);\n\t\t\treturn (&x)[n];\n\t\t}\n\n\t\t// Assignment and comparison\n\t\tconstexpr inline Vector2D& operator = (Vector2D param) { x = param.x; y = param.y; return *this; }\n\t\tconstexpr inline Vector2D& operator = (T param) { x = param; y = param; return *this; }\n\t\tconstexpr inline bool operator == (Vector2D param) const { return x == param.x && y == param.y; }\n\t\tconstexpr inline bool operator != (Vector2D param) const { return x != param.x || y != param.y; }\n\t\tconstexpr inline bool operator < (Vector2D param) const { return y != param.y ? y < param.y : x < param.x; }\n\n\t\t// Basic algebra\n\t\tconstexpr inline Vector2D operator + (Vector2D param) const { return Vector2D(x + param.x,y + param.y); }\n\t\tconstexpr inline Vector2D operator - (Vector2D param) const { return Vector2D(x - param.x,y - param.y); }\n\t\tconstexpr inline Vector2D operator * (Vector2D param) const { return Vector2D(x * param.x,y * param.y); }\n\t\tconstexpr inline Vector2D operator / (Vector2D param) const { return Vector2D(x / param.x,y / param.y); }\n\t\tconstexpr inline Vector2D operator % (Vector2D param) const { return Vector2D(mod(x, param.x), mod(y, param.y)); }\n\n\t\tconstexpr inline Vector2D modulo(Vector2D param) const { return Vector2D(Halley::modulo(x, param.x), Halley::modulo(y, param.y)); }\n\t\tconstexpr inline Vector2D floorDiv(Vector2D param) const { return Vector2D(Halley::floorDiv(x, param.x), Halley::floorDiv(y, param.y)); }\n\n\t\tconstexpr inline Vector2D operator - () const { return Vector2D(-x,-y); }\n\n\t\ttemplate \n\t\tconstexpr inline Vector2D operator * (V param) const { return Vector2D(T(x * param), T(y * param)); }\n\n\t\ttemplate \n\t\tconstexpr inline Vector2D operator / (V param) const { return Vector2D(T(x / param), T(y / param)); }\n\n\t\t// In-place operations\n\t\tconstexpr inline Vector2D& operator += (Vector2D param) { x += param.x; y += param.y; return *this; }\n\t\tconstexpr inline Vector2D& operator -= (Vector2D param) { x -= param.x; y -= param.y; return *this; }\n\t\tconstexpr inline Vector2D& operator *= (const T param) { x *= param; y *= param; return *this; }\n\t\tconstexpr inline Vector2D& operator /= (const T param) { x /= param; y /= param; return *this; }\n\n\t\t// Get the normalized vector (unit vector)\n\t\tconstexpr inline Vector2D unit () const\n\t\t{\n\t\t\tfloat len = length();\n\t\t\tif (len != 0) {\n\t\t\t\treturn (*this) / len;\n\t\t\t} else {\n\t\t\t\treturn Vector2D(0, 0);\n\t\t\t}\n\t\t}\n\t\tconstexpr inline Vector2D normalized() const\n\t\t{\n\t\t\treturn unit();\n\t\t}\n\t\tconstexpr inline void normalize()\n\t\t{\n\t\t\t*this = unit();\n\t\t}\n\n\t\t// Get the orthogonal vector\n\t\tconstexpr inline Vector2D orthoLeft () const { return Vector2D(-y, x); }\n\t\tconstexpr inline Vector2D orthoRight () const { return Vector2D(y, -x); }\n\n\t\t// Cross product (the Z component of it)\n\t\tconstexpr inline T cross (Vector2D param) const { return x * param.y - y * param.x; }\n\n\t\t// Dot product\n\t\tconstexpr inline T dot (Vector2D param) const { return (x * param.x) + (y * param.y); }\n\n\t\t// Length\n\t\tconstexpr inline T length () const { return static_cast(std::sqrt(squaredLength())); }\n\t\tconstexpr inline T len () const { return length(); }\n\t\tconstexpr inline T manhattanLength() const { return std::abs(x) + std::abs(y); }\n\n\t\t// Squared length, often useful and much faster\n\t\tconstexpr inline T squaredLength () const { return x*x+y*y; }\n\n\t\t// Projection on another vector\n\t\tinline Vector2D projection (Vector2D param) const\n\t\t{\n\t\t\tVector2D unit = param.unit();\n\t\t\treturn this->dot(unit) * unit;\n\t\t}\n\t\tinline T projectionLength (Vector2D param) const\n\t\t{\n\t\t\treturn this->dot(param.unit());\n\t\t}\n\n\t\t// Rounding\n\t\tconstexpr inline Vector2D floor() const { return Vector2D(std::floor(x), std::floor(y)); }\n\t\tconstexpr inline Vector2D ceil() const { return Vector2D(std::ceil(x), std::ceil(y)); }\n\t\tconstexpr inline Vector2D round() const { return Vector2D(std::round(x), std::round(y)); }\n\n\t\t// Gets the angle that this vector is pointing to\n\t\tinline U angle () const\n\t\t{\n\t\t\tU angle;\n\t\t\tangle.setRadians(atan2(y, x));\n\t\t\treturn angle;\n\t\t}\n\n\t\t// Rotates vector by an angle\n\t\tinline Vector2D rotate (U angle) const\n\t\t{\n\t\t\tT cos, sin;\n\t\t\tangle.sincos(sin, cos);\n\t\t\treturn Vector2D(x*cos - y*sin, x*sin + y*cos);\n\t\t}\n\n\t\t// Rotates vector by sine and cosine\n\t\tinline Vector2D rotate (T sine, T cosine) const\n\t\t{\n\t\t\treturn Vector2D(x*cosine - y*sine, x*sine + y*cosine);\n\t\t}\n\n\t\t// Removes the length of the vector along the given axis\n\t\tconstexpr inline Vector2D neutralize (Vector2D param) const\n\t\t{\n\t\t\treturn *this - dot(param)*param;\n\t\t}\n\n\t\tString toString() const\n\t\t{\n\t\t\treturn String(\"(\") + x + \", \" + y + \")\";\n\t\t}\n\n\t\tconstexpr Vector2D abs() const\n\t\t{\n\t\t\treturn Vector2D(std::abs(x), std::abs(y));\n\t\t}\n\n\t\tconstexpr inline static Vector2D min(Vector2D a, Vector2D b)\n\t\t{\n\t\t\treturn Vector2D(std::min(a.x, b.x), std::min(a.y, b.y));\n\t\t}\n\n\t\tconstexpr inline static Vector2D max(Vector2D a, Vector2D b)\n\t\t{\n\t\t\treturn Vector2D(std::max(a.x, b.x), std::max(a.y, b.y));\n\t\t}\n\t};\n\n\n\t////////////////////\n\t// Global operators\n\ttemplate \n\tinline Vector2D operator * (V f, const Vector2D &v)\n\t{\n\t\treturn Vector2D(T(v.x * f),T(v.y * f));\n\t}\n\n\ttemplate \n\tstd::ostream& operator<< (std::ostream& ostream, const Vector2D& v)\n\t{\n\t\tostream << \"(\" << v.x << \",\" << v.y << \")\" ; return ostream;\n\t}\n\t\n\t////////////\n\t// Typedefs\n\ttypedef Vector2D > Vector2d;\n\ttypedef Vector2D<> Vector2f;\n\ttypedef Vector2D Vector2i;\n\ttypedef Vector2D Vector2s;\n\ttypedef Vector2D Vector2c;\n\ttypedef Vector2f Position;\n\ttypedef Vector2f Size;\n}\n\nnamespace std {\n\ttemplate<>\n\tstruct hash\n\t{\n\t\tsize_t operator()(const Halley::Vector2i& v) const \n\t\t{\n\t\t\treturn std::hash()(*reinterpret_cast(&v));\n\t\t}\n\t};\n\n\ttemplate<>\n\tstruct hash\n\t{\n\t\tsize_t operator()(const Halley::Vector2f& v) const \n\t\t{\n\t\t\treturn std::hash()(*reinterpret_cast(&v));\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "32529e8d6908379a563faca0ef64b3f4bb0bf981", "size": 7854, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/utils/include/halley/maths/vector2.h", "max_stars_repo_name": "lye/halley", "max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "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/engine/utils/include/halley/maths/vector2.h", "max_issues_repo_name": "lye/halley", "max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "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/engine/utils/include/halley/maths/vector2.h", "max_forks_repo_name": "lye/halley", "max_forks_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6796875, "max_line_length": 139, "alphanum_fraction": 0.60236822, "num_tokens": 2298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6147472738787623}} {"text": "/* =======================================\n * Code for 8.06 Term Paper (Spring 2015)\n *\n * Author : To Chin Yu (ytc@mit.edu)\n * Purpose: 1D lattice simulation\n * V(x) = alpha*x^2 + lambda*x^4\n * =======================================\n */\n#include \n#include \n#include \n#define sq(x) pow((x),2.0)\n#define cb(x) pow((x),3.0)\n#define qd(x) pow((x),4.0)\n\n// GSL Random Number Generator (https://www.gnu.org/software/gsl/)\n#include \nconst gsl_rng_type * T; gsl_rng * r;\n\n// Parameters\n#define N_lat 5000 // Lattice size\n#define a 0.1 // Lattice spacing\n#define N_therm 500 // Thermalization\n#define N_meas 1000 // Number of configuration to measure\n#define N_skip 100 // Decorrelation\n#define alpha 0 // Strength of potential (harmonic)\n#define lambda 1 // Strength of potential (anharmonic)\n#define epsilon 0.2 // Size of fluctuation\n\n#define N_bin 1000\n#define dx 0.01\n#define x_range 5.0 // x in [-range, range]\n\n// Globals\ndouble x[N_lat]; // Lattice\nint acc,tot; // Acceptance rate = acc/tot\ndouble E0; // Ground state energy\ndouble C[N_lat]; // Correlator\ndouble psi[N_bin]; // Wavefunction\n\n// Output Files\nFILE *fE0, *fCorRatio, *fpsi;\n\n// Prototypes\nvoid setup();\nvoid cleanup();\nvoid update();\n\nint main(void){\n setup();\n\n // Thermalize\n for(int n=0;n0){\n if(exp(-d)\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct data\n{\n double *t;\n double *y;\n size_t n;\n};\n\n/* model function: a * exp( -1/2 * [ (t - b) / c ]^2 ) */\ndouble\ngaussian(const double a, const double b, const double c, const double t)\n{\n const double z = (t - b) / c;\n return (a * exp(-0.5 * z * z));\n}\n\nint\nfunc_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n struct data *d = (struct data *) params;\n double a = gsl_vector_get(x, 0);\n double b = gsl_vector_get(x, 1);\n double c = gsl_vector_get(x, 2);\n size_t i;\n\n for (i = 0; i < d->n; ++i)\n {\n double ti = d->t[i];\n double yi = d->y[i];\n double y = gaussian(a, b, c, ti);\n\n gsl_vector_set(f, i, yi - y);\n }\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_df (const gsl_vector * x, void *params, gsl_matrix * J)\n{\n struct data *d = (struct data *) params;\n double a = gsl_vector_get(x, 0);\n double b = gsl_vector_get(x, 1);\n double c = gsl_vector_get(x, 2);\n size_t i;\n\n for (i = 0; i < d->n; ++i)\n {\n double ti = d->t[i];\n double zi = (ti - b) / c;\n double ei = exp(-0.5 * zi * zi);\n\n gsl_matrix_set(J, i, 0, -ei);\n gsl_matrix_set(J, i, 1, -(a / c) * ei * zi);\n gsl_matrix_set(J, i, 2, -(a / c) * ei * zi * zi);\n }\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_fvv (const gsl_vector * x, const gsl_vector * v,\n void *params, gsl_vector * fvv)\n{\n struct data *d = (struct data *) params;\n double a = gsl_vector_get(x, 0);\n double b = gsl_vector_get(x, 1);\n double c = gsl_vector_get(x, 2);\n double va = gsl_vector_get(v, 0);\n double vb = gsl_vector_get(v, 1);\n double vc = gsl_vector_get(v, 2);\n size_t i;\n\n for (i = 0; i < d->n; ++i)\n {\n double ti = d->t[i];\n double zi = (ti - b) / c;\n double ei = exp(-0.5 * zi * zi);\n double Dab = -zi * ei / c;\n double Dac = -zi * zi * ei / c;\n double Dbb = a * ei / (c * c) * (1.0 - zi*zi);\n double Dbc = a * zi * ei / (c * c) * (2.0 - zi*zi);\n double Dcc = a * zi * zi * ei / (c * c) * (3.0 - zi*zi);\n double sum;\n\n sum = 2.0 * va * vb * Dab +\n 2.0 * va * vc * Dac +\n vb * vb * Dbb +\n 2.0 * vb * vc * Dbc +\n vc * vc * Dcc;\n\n gsl_vector_set(fvv, i, sum);\n }\n\n return GSL_SUCCESS;\n}\n\nvoid\ncallback(const size_t iter, void *params,\n const gsl_multifit_nlinear_workspace *w)\n{\n gsl_vector *f = gsl_multifit_nlinear_residual(w);\n gsl_vector *x = gsl_multifit_nlinear_position(w);\n double avratio = gsl_multifit_nlinear_avratio(w);\n double rcond;\n\n (void) params; /* not used */\n\n /* compute reciprocal condition number of J(x) */\n gsl_multifit_nlinear_rcond(&rcond, w);\n\n fprintf(stderr, \"iter %2zu: a = %.4f, b = %.4f, c = %.4f, |a|/|v| = %.4f cond(J) = %8.4f, |f(x)| = %.4f\\n\",\n iter,\n gsl_vector_get(x, 0),\n gsl_vector_get(x, 1),\n gsl_vector_get(x, 2),\n avratio,\n 1.0 / rcond,\n gsl_blas_dnrm2(f));\n}\n\nvoid\nsolve_system(gsl_vector *x, gsl_multifit_nlinear_fdf *fdf,\n gsl_multifit_nlinear_parameters *params)\n{\n const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;\n const size_t max_iter = 200;\n const double xtol = 1.0e-8;\n const double gtol = 1.0e-8;\n const double ftol = 1.0e-8;\n const size_t n = fdf->n;\n const size_t p = fdf->p;\n gsl_multifit_nlinear_workspace *work =\n gsl_multifit_nlinear_alloc(T, params, n, p);\n gsl_vector * f = gsl_multifit_nlinear_residual(work);\n gsl_vector * y = gsl_multifit_nlinear_position(work);\n int info;\n double chisq0, chisq, rcond;\n\n /* initialize solver */\n gsl_multifit_nlinear_init(x, fdf, work);\n\n /* store initial cost */\n gsl_blas_ddot(f, f, &chisq0);\n\n /* iterate until convergence */\n gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol,\n callback, NULL, &info, work);\n\n /* store final cost */\n gsl_blas_ddot(f, f, &chisq);\n\n /* store cond(J(x)) */\n gsl_multifit_nlinear_rcond(&rcond, work);\n\n gsl_vector_memcpy(x, y);\n\n /* print summary */\n\n fprintf(stderr, \"NITER = %zu\\n\", gsl_multifit_nlinear_niter(work));\n fprintf(stderr, \"NFEV = %zu\\n\", fdf->nevalf);\n fprintf(stderr, \"NJEV = %zu\\n\", fdf->nevaldf);\n fprintf(stderr, \"NAEV = %zu\\n\", fdf->nevalfvv);\n fprintf(stderr, \"initial cost = %.12e\\n\", chisq0);\n fprintf(stderr, \"final cost = %.12e\\n\", chisq);\n fprintf(stderr, \"final x = (%.12e, %.12e, %12e)\\n\",\n gsl_vector_get(x, 0), gsl_vector_get(x, 1), gsl_vector_get(x, 2));\n fprintf(stderr, \"final cond(J) = %.12e\\n\", 1.0 / rcond);\n\n gsl_multifit_nlinear_free(work);\n}\n\nint\nmain (void)\n{\n const size_t n = 300; /* number of data points to fit */\n const size_t p = 3; /* number of model parameters */\n const double a = 5.0; /* amplitude */\n const double b = 0.4; /* center */\n const double c = 0.15; /* width */\n const gsl_rng_type * T = gsl_rng_default;\n gsl_vector *f = gsl_vector_alloc(n);\n gsl_vector *x = gsl_vector_alloc(p);\n gsl_multifit_nlinear_fdf fdf;\n gsl_multifit_nlinear_parameters fdf_params =\n gsl_multifit_nlinear_default_parameters();\n struct data fit_data;\n gsl_rng * r;\n size_t i;\n \n gsl_rng_env_setup ();\n r = gsl_rng_alloc (T);\n\n fit_data.t = malloc(n * sizeof(double));\n fit_data.y = malloc(n * sizeof(double));\n fit_data.n = n;\n\n /* generate synthetic data with noise */\n for (i = 0; i < n; ++i)\n {\n double t = (double)i / (double) n;\n double y0 = gaussian(a, b, c, t);\n double dy = gsl_ran_gaussian (r, 0.1 * y0);\n\n fit_data.t[i] = t;\n fit_data.y[i] = y0 + dy;\n }\n\n /* define function to be minimized */\n fdf.f = func_f;\n fdf.df = func_df;\n fdf.fvv = func_fvv;\n fdf.n = n;\n fdf.p = p;\n fdf.params = &fit_data;\n\n /* starting point */\n gsl_vector_set(x, 0, 1.0);\n gsl_vector_set(x, 1, 0.0);\n gsl_vector_set(x, 2, 1.0);\n\n fdf_params.trs = gsl_multifit_nlinear_trs_lmaccel;\n solve_system(x, &fdf, &fdf_params);\n\n /* print data and model */\n {\n double A = gsl_vector_get(x, 0);\n double B = gsl_vector_get(x, 1);\n double C = gsl_vector_get(x, 2);\n\n for (i = 0; i < n; ++i)\n {\n double ti = fit_data.t[i];\n double yi = fit_data.y[i];\n double fi = gaussian(A, B, C, ti);\n\n printf(\"%f %f %f\\n\", ti, yi, fi);\n }\n }\n\n gsl_vector_free(f);\n gsl_vector_free(x);\n gsl_rng_free(r);\n\n return 0;\n}\n", "meta": {"hexsha": "34145cfa4aa524ec79a0829043dd65c3006bac50", "size": 6569, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/doc_texinfo/examples/nlfit2b.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/doc_texinfo/examples/nlfit2b.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/doc_texinfo/examples/nlfit2b.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.7607843137, "max_line_length": 109, "alphanum_fraction": 0.5865428528, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6143857560527225}} {"text": "/* randist/chisq.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 chisq distribution has the form\n\n p(x) dx = (1/(2*Gamma(nu/2))) (x/2)^(nu/2 - 1) exp(-x/2) dx\n\n for x = 0 ... +infty */\n\ndouble\ngsl_ran_chisq (const gsl_rng * r, const double nu)\n{\n double chisq = 2 * gsl_ran_gamma (r, nu / 2, 1.0);\n return chisq;\n}\n\ndouble\ngsl_ran_chisq_pdf (const double x, const double nu)\n{\n if (x < 0)\n {\n return 0 ;\n }\n else\n {\n if(nu == 2.0)\n {\n return exp(-x/2.0) / 2.0;\n }\n else\n {\n double p;\n double lngamma = gsl_sf_lngamma (nu / 2);\n\n p = exp ((nu / 2 - 1) * log (x/2) - x/2 - lngamma) / 2;\n return p;\n }\n }\n}\n", "meta": {"hexsha": "aef22ec36bdf519f2fc74a997116ed4d8f89f9be", "size": 1608, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/chisq.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/chisq.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/chisq.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.935483871, "max_line_length": 81, "alphanum_fraction": 0.6274875622, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6143349275439515}} {"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\n/**\n * Spline wrapper\n * Used to take care of evaluations outside the supported range\n */\ntypedef struct {\n gsl_interp_accel *intacc; //GSL spline\n gsl_spline *spline;\n double x0,xf; //Interpolation limits\n double y0,yf; //Constant values to use beyond interpolation limit\n} SplPar;\n\nSplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf);\n\ndouble ccl_spline_eval(double x,SplPar *spl);\n\nvoid ccl_spline_free(SplPar *spl);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "7694e68b2328bf6064c23f26ed8078702722a4f3", "size": 2082, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_utils.h", "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ccl_utils.h", "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ccl_utils.h", "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0307692308, "max_line_length": 101, "alphanum_fraction": 0.7252641691, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.614292043280129}} {"text": "/* -*- Mode: c++ -*- */\n// copyright (c) 2006-2010 by Christos Dimitrakakis\n// \n/***************************************************************************\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 ***************************************************************************/\n\n#ifndef MATRIX_H\n#define MATRIX_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Vector.h\"\n#include \"real.h\"\n//#include \n\n#undef REFERENCE_ACCESS\n\n#define ACCURACY_LIMIT 1e-12\n\n/** \\brief An n-by-m dimensional matrix.\n\n TODO: Use the BLAS interface for some / most routines.\n */\nclass Matrix {\n public:\n /// Check bounds?\n enum BoundsCheckingStatus { NO_CHECK_BOUNDS = 0, CHECK_BOUNDS = 1 };\n#ifdef NDEBUG\n static Matrix Null(int rows, int columns,\n enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);\n static Matrix Unity(int rows, int columns,\n enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);\n\n Matrix(int rows = 1, int columns = 1,\n enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);\n Matrix(int rows, int columns, real* y,\n enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);\n explicit Matrix(const Vector& v,\n enum BoundsCheckingStatus check_ = NO_CHECK_BOUNDS);\n#else\n static Matrix Null(int rows, int columns,\n enum BoundsCheckingStatus check = CHECK_BOUNDS);\n static Matrix Unity(int rows, int columns,\n enum BoundsCheckingStatus check = CHECK_BOUNDS);\n\n Matrix(int rows = 1, int columns = 1,\n enum BoundsCheckingStatus check = CHECK_BOUNDS);\n Matrix(int rows, int columns, real* y,\n enum BoundsCheckingStatus check = CHECK_BOUNDS);\n explicit Matrix(const Vector& v,\n enum BoundsCheckingStatus check_ = CHECK_BOUNDS);\n#endif\n Matrix(const Matrix& rhs, bool clone = true);\n ~Matrix();\n void Resize(int rows_, int columns_);\n Matrix AddRow(const Vector& rhs);\n Matrix AddColumn(const Vector& rhs);\n Matrix& operator=(const Matrix& rhs);\n bool operator==(const Matrix& rhs) const;\n bool operator!=(const Matrix& rhs) const;\n Matrix operator+(const Matrix& rhs);\n Matrix& operator+=(const Matrix& rhs);\n Matrix operator-(const Matrix& rhs);\n Matrix& operator-=(const Matrix& rhs);\n Matrix& operator*=(const real& rhs);\n Matrix operator*(const Matrix& rhs);\n Matrix operator*(const real& rhs);\n Matrix operator+(const real& rhs);\n Matrix operator-(const real& rhs);\n Matrix operator/(const real& rhs);\n /// Matrix inversion (defaults to GSL with LU)\n Matrix Inverse(real epsilon = ACCURACY_LIMIT) const {\n return GSL_Inverse();\n // return Inverse_LU();\n }\n Vector SVD_Solve(const Vector& b) const;\n\n Matrix GSL_Inverse() const;\n\n /** Matrix inversion using the Cholesky decomposition.\n\n First call Cholesky with accuracy epsilon to obtain $\\fL,\n L'\\f$ such that \\f$A = LL'\\f$. Then solve for \\f$X = A^{-1}\\f$:\n \\f[\n LL'X = I,\n \\f]\n by dynamic programming.\n */\n Matrix Inverse_Cholesky(real epsilon = ACCURACY_LIMIT) const {\n Matrix U = Cholesky(epsilon);\n Matrix L(U, false);\n L.Transpose();\n return Inverse(L, U);\n }\n /** Matrix inversion using the LU decomposition.\n\n First call LUDecomposition with accuracy epsilon to obtain $\\fL,\n U\\f$ such that \\f$A = LU\\f$. Then solve for \\f$X = A^{-1}\\f$:\n \\f[\n LUX = I,\n \\f]\n by dynamic programming.\n */\n Matrix Inverse_LU(real epsilon = ACCURACY_LIMIT) const {\n real det;\n Matrix tmp(*this);\n std::vector A = tmp.LUDecomposition(det, epsilon);\n return Inverse(A[0], A[1]);\n }\n\n Matrix Inverse(const Matrix& L, const Matrix& U) const;\n bool isSymmetric() const;\n bool isTriangular() const;\n bool isUpperTriangular() const;\n bool isLowerTriangular() const;\n real det() const;\n real tr() const;\n real L1Norm() const;\n real L2Norm() const;\n Matrix Multiple(const Matrix& rhs) const;\n Matrix Kron(const Matrix& rhs) const;\n real ColumnSum(int c) const;\n real RowSum(int r) const;\n real compute_det_triangular() const;\n real gaussian_elimination_forward(real epsilon = ACCURACY_LIMIT);\n std::vector QRDecomposition() const;\n std::vector LUDecomposition(real& determinant,\n real epsilon = ACCURACY_LIMIT);\n Matrix Cholesky(real epsilon = ACCURACY_LIMIT) const;\n void Cholesky(Matrix& chol, real epsilon = ACCURACY_LIMIT) const;\n void Clear();\n void Transpose();\n Vector getColumn(int c) const;\n Vector getRow(int r) const;\n void setColumn(int c, const Vector& x);\n void setRow(int r, const Vector& x);\n void SortRow(int r);\n void SortColumn(int r);\n int Rows() const;\n int Columns() const;\n Vector Vec() const;\n void Vec(const Vector& x);\n Vector RowMax() const;\n Vector ColumnMax() const;\n Vector RowMin() const;\n Vector ColumnMin() const;\n real& operator()(int i, int j);\n const real& operator()(int i, int j) const;\n void print(FILE* f) const;\n friend Matrix operator*(const real& lhs, const Matrix& rhs);\n friend Matrix operator*(const Vector& lhs, const Matrix& rhs);\n friend Vector operator*(const Matrix& lhs, const Vector& rhs);\n\n protected:\n int rows; ///< number of rows in the matrix\n int columns; ///< number of columns in the matrix\n real* x; ///< data\n#ifdef REFERENCE_ACCESS\n real** x_list; ///< data pointers\n void MakeReferences();\n#endif\n const enum BoundsCheckingStatus checking_bounds;\n bool transposed;\n bool clear_data;\n const real& qGet(int i, int j);\n void qSet(int i, int j, real v);\n};\n\nMatrix operator*(const real& lhs, const Matrix& rhs);\nMatrix operator*(const Vector& lhs, const Matrix& rhs);\nVector operator*(const Matrix& lhs, const Vector& rhs);\nreal Mahalanobis2(const Vector& x, const Matrix& A, const Vector& y);\n\n/// Kronecker product\ninline Matrix Kron(const Matrix& lhs, const Matrix& rhs) {\n return lhs.Kron(rhs);\n}\n\ninline Matrix OuterProduct(const Vector& lhs, const Vector& rhs) {\n Matrix R(lhs.n, rhs.n);\n MatrixProduct(lhs, rhs, R);\n return R;\n}\n\nMatrix Transpose(const Matrix& rhs);\n\n/// In-place transpose matrix\ninline void Matrix::Transpose() { transposed = !transposed; }\n\ninline int Matrix::Rows() const {\n if (transposed) {\n return columns;\n }\n return rows;\n}\n\ninline int Matrix::Columns() const {\n if (transposed) {\n return rows;\n }\n return columns;\n}\n\ninline real& Matrix::operator()(int i, int j) {\n if (transposed) {\n int tmp = i;\n i = j;\n j = tmp;\n }\n\n if (checking_bounds) {\n if (i < 0 || j < 0 || i >= rows || j >= columns) {\n fprintf(stderr, \"bad access: (%d, %d) on a %d x %d matrix\\n\", i, j, rows,\n columns);\n fflush(stderr);\n throw std::out_of_range(\"matrix index out of range\");\n }\n }\n#ifdef REFERENCE_ACCESS\n return x_list[i][j];\n#else\n return x[i * columns + j];\n#endif\n}\n\ninline const real& Matrix::operator()(int i, int j) const {\n if (transposed) {\n int tmp = i;\n i = j;\n j = tmp;\n }\n\n if (checking_bounds) {\n if (i < 0 || j < 0 || i >= rows || j >= columns) {\n fprintf(stderr, \"bad access: (%d, %d) on a %d x %d matrix\\n\", i, j, rows,\n columns);\n fflush(stderr);\n throw std::out_of_range(\"matrix index out of range\");\n }\n }\n#ifdef REFERENCE_ACCESS\n return x_list[i][j];\n#else\n return x[i * columns + j];\n#endif\n}\n\n#if 0\ninline const real& Matrix::qGet(int i, int j) {\n#ifdef REFERENCE_ACCESS\n return x_list[i][j];\n#else\n return x[i * columns + j];\n#endif\n}\n\ninline void Matrix::qSet(int i, int j, real v) {\n#ifdef REFERENCE_ACCESS\n x_list[i][j] = v;\n#else\n x[i * columns + j] = v;\n#endif\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "1e907875c8c4681aa5b38d42c1d47b81767bace3", "size": 8220, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/Matrix.h", "max_stars_repo_name": "litlpoet/beliefbox", "max_stars_repo_head_hexsha": "6b303e49017f8054f43c6c840686fcc632205e4e", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/Matrix.h", "max_issues_repo_name": "litlpoet/beliefbox", "max_issues_repo_head_hexsha": "6b303e49017f8054f43c6c840686fcc632205e4e", "max_issues_repo_licenses": ["OLDAP-2.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/Matrix.h", "max_forks_repo_name": "litlpoet/beliefbox", "max_forks_repo_head_hexsha": "6b303e49017f8054f43c6c840686fcc632205e4e", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5683453237, "max_line_length": 79, "alphanum_fraction": 0.6319951338, "num_tokens": 2091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6135592503724829}} {"text": "/* specfunc/elljac.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \n\n\n/* GJ: See [Thompson, Atlas for Computing Mathematical Functions] */\n\n/* BJG 2005-07: New algorithm based on Algorithm 5 from Numerische\n Mathematik 7, 78-90 (1965) \"Numerical Calculation of Elliptic\n Integrals and Elliptic Functions\" R. Bulirsch.\n\n Minor tweak is to avoid division by zero when sin(x u_l) = 0 by\n computing reflected values sn(K-u) cn(K-u) dn(K-u) and using\n transformation from Abramowitz & Stegun table 16.8 column \"K-u\"*/\n\nint\ngsl_sf_elljac_e(double u, double m, double * sn, double * cn, double * dn)\n{\n if(fabs(m) > 1.0) {\n *sn = 0.0;\n *cn = 0.0;\n *dn = 0.0;\n GSL_ERROR (\"|m| > 1.0\", GSL_EDOM);\n }\n else if(fabs(m) < 2.0*GSL_DBL_EPSILON) {\n *sn = sin(u);\n *cn = cos(u);\n *dn = 1.0;\n return GSL_SUCCESS;\n }\n else if(fabs(m - 1.0) < 2.0*GSL_DBL_EPSILON) {\n *sn = tanh(u);\n *cn = 1.0/cosh(u);\n *dn = *cn;\n return GSL_SUCCESS;\n }\n else {\n int status = GSL_SUCCESS;\n const int N = 16;\n double mu[16];\n double nu[16];\n double c[16];\n double d[16];\n double sin_umu, cos_umu, t, r;\n int n = 0;\n\n mu[0] = 1.0;\n nu[0] = sqrt(1.0 - m);\n\n while( fabs(mu[n] - nu[n]) > 4.0 * GSL_DBL_EPSILON * fabs(mu[n]+nu[n])) {\n mu[n+1] = 0.5 * (mu[n] + nu[n]);\n nu[n+1] = sqrt(mu[n] * nu[n]);\n ++n;\n if(n >= N - 1) {\n status = GSL_EMAXITER;\n break;\n }\n }\n\n sin_umu = sin(u * mu[n]);\n cos_umu = cos(u * mu[n]);\n\n /* Since sin(u*mu(n)) can be zero we switch to computing sn(K-u),\n cn(K-u), dn(K-u) when |sin| < |cos| */\n\n if (fabs(sin_umu) < fabs(cos_umu))\n {\n t = sin_umu / cos_umu;\n \n c[n] = mu[n] * t;\n d[n] = 1.0;\n \n while(n > 0) {\n n--;\n c[n] = d[n+1] * c[n+1];\n r = (c[n+1] * c[n+1]) / mu[n+1];\n d[n] = (r + nu[n]) / (r + mu[n]);\n }\n \n *dn = sqrt(1.0-m) / d[n];\n *cn = (*dn) * GSL_SIGN(cos_umu) / gsl_hypot(1.0, c[n]);\n *sn = (*cn) * c[n] /sqrt(1.0-m);\n }\n else\n {\n t = cos_umu / sin_umu;\n \n c[n] = mu[n] * t;\n d[n] = 1.0;\n \n while(n > 0) {\n --n;\n c[n] = d[n+1] * c[n+1];\n r = (c[n+1] * c[n+1]) / mu[n+1];\n d[n] = (r + nu[n]) / (r + mu[n]);\n }\n \n *dn = d[n];\n *sn = GSL_SIGN(sin_umu) / gsl_hypot(1.0, c[n]);\n *cn = c[n] * (*sn);\n }\n \n return status;\n }\n}\n", "meta": {"hexsha": "340306e485d506799c8772c8fc910e176400e22f", "size": 3440, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/elljac.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/elljac.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/elljac.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.6666666667, "max_line_length": 81, "alphanum_fraction": 0.5334302326, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6135592363558952}} {"text": "static char help[] =\n\"Solve the linear biharmonic equation in 2D. Equation is\\n\"\n\" Lap^2 u = f\\n\"\n\"where Lap = - grad^2 is the positive Laplacian, equivalently\\n\"\n\" u_xxxx + 2 u_xxyy + u_yyyy = f(x,y)\\n\"\n\"Domain is unit square S = (0,1)^2. Boundary conditions are homogeneous\\n\"\n\"simply-supported: u = 0, Lap u = 0. The equation is rewritten as a\\n\"\n\"2x2 block system with SPD Laplacian blocks on the diagonal:\\n\"\n\" | Lap | 0 | | v | | f | \\n\"\n\" |-----|-----| |---| = |---| \\n\"\n\" | -I | Lap | | u | | 0 | \\n\"\n\"Includes manufactured, polynomial exact solution. The discretization is\\n\"\n\"structured-grid (DMDA) finite differences. Includes analytical Jacobian.\\n\"\n\"Recommended preconditioning combines fieldsplit:\\n\"\n\" -pc_type fieldsplit -pc_fieldsplit_type multiplicative|additive \\n\"\n\"with multigrid as the preconditioner for the diagonal blocks:\\n\"\n\" -fieldsplit_v_pc_type mg|gamg -fieldsplit_u_pc_type mg|gamg\\n\"\n\"(GMG requires setting levels and Galerkin coarsening.) One can also do\\n\"\n\"monolithic multigrid (-pc_type mg|gamg).\\n\\n\";\n\n#include \n\ntypedef struct {\n PetscReal v, u;\n} Field;\n\ntypedef struct {\n PetscReal (*f)(PetscReal x, PetscReal y); // right-hand side\n} BiharmCtx;\n\nstatic PetscReal c(PetscReal x) {\n return x*x*x * (1.0-x)*(1.0-x)*(1.0-x);\n}\n\nstatic PetscReal ddc(PetscReal x) {\n return 6.0 * x * (1.0-x) * (1.0 - 5.0 * x + 5.0 * x*x);\n}\n\nstatic PetscReal d4c(PetscReal x) {\n return - 72.0 * (1.0 - 5.0 * x + 5.0 * x*x);\n}\n\nstatic PetscReal u_exact_fcn(PetscReal x, PetscReal y) {\n return c(x) * c(y);\n}\n\nstatic PetscReal lap_u_exact_fcn(PetscReal x, PetscReal y) {\n return - ddc(x) * c(y) - c(x) * ddc(y); // Lap u = - grad^2 u\n}\n\nstatic PetscReal f_fcn(PetscReal x, PetscReal y) {\n return d4c(x) * c(y) + 2.0 * ddc(x) * ddc(y) + c(x) * d4c(y); // Lap^2 u = grad^4 u\n}\n\nextern PetscErrorCode FormExactWLocal(DMDALocalInfo*, Field**, BiharmCtx*);\nextern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, Field**, Field **FF, BiharmCtx*);\nextern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, Field**, Mat, Mat, BiharmCtx*);\n\nint main(int argc,char **argv) {\n PetscErrorCode ierr;\n DM da;\n SNES snes;\n Vec w, w_initial, w_exact;\n BiharmCtx user;\n Field **aW;\n PetscReal normv, normu, errv, erru;\n DMDALocalInfo info;\n\n ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;\n\n user.f = &f_fcn;\n ierr = DMDACreate2d(PETSC_COMM_WORLD,\n DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,\n 3,3,PETSC_DECIDE,PETSC_DECIDE,\n 2,1, // degrees of freedom, stencil width\n NULL,NULL,&da); CHKERRQ(ierr);\n ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);\n ierr = DMSetFromOptions(da); CHKERRQ(ierr);\n ierr = DMSetUp(da); CHKERRQ(ierr); // this must be called BEFORE SetUniformCoordinates\n ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,-1.0); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,0,\"v\"); CHKERRQ(ierr);\n ierr = DMDASetFieldName(da,1,\"u\"); CHKERRQ(ierr);\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);\n ierr = SNESSetDM(snes,da); CHKERRQ(ierr);\n ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,\n (DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);\n ierr = DMDASNESSetJacobianLocal(da,\n (DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr);\n ierr = SNESSetType(snes,SNESKSPONLY); CHKERRQ(ierr);\n ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);\n\n ierr = DMGetGlobalVector(da,&w_initial); CHKERRQ(ierr);\n ierr = VecSet(w_initial,0.0); CHKERRQ(ierr);\n ierr = SNESSolve(snes,NULL,w_initial); CHKERRQ(ierr);\n ierr = DMRestoreGlobalVector(da,&w_initial); CHKERRQ(ierr);\n ierr = DMDestroy(&da); CHKERRQ(ierr);\n\n ierr = SNESGetSolution(snes,&w); CHKERRQ(ierr);\n ierr = SNESGetDM(snes,&da); CHKERRQ(ierr);\n ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);\n\n ierr = DMCreateGlobalVector(da,&w_exact); CHKERRQ(ierr);\n ierr = DMDAVecGetArray(da,w_exact,&aW); CHKERRQ(ierr);\n ierr = FormExactWLocal(&info,aW,&user); CHKERRQ(ierr);\n ierr = DMDAVecRestoreArray(da,w_exact,&aW); CHKERRQ(ierr);\n ierr = VecStrideNorm(w_exact,0,NORM_INFINITY,&normv); CHKERRQ(ierr);\n ierr = VecStrideNorm(w_exact,1,NORM_INFINITY,&normu); CHKERRQ(ierr);\n ierr = VecAXPY(w,-1.0,w_exact); CHKERRQ(ierr);\n ierr = VecStrideNorm(w,0,NORM_INFINITY,&errv); CHKERRQ(ierr);\n ierr = VecStrideNorm(w,1,NORM_INFINITY,&erru); CHKERRQ(ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD,\n \"done on %d x %d grid ...\\n\"\n \" errors |v-vex|_inf/|vex|_inf = %.5e, |u-uex|_inf/|uex|_inf = %.5e\\n\",\n info.mx,info.my,errv/normv,erru/normu); CHKERRQ(ierr);\n\n ierr = VecDestroy(&w_exact); CHKERRQ(ierr);\n ierr = SNESDestroy(&snes); CHKERRQ(ierr);\n return PetscFinalize();\n}\n\nPetscErrorCode FormExactWLocal(DMDALocalInfo *info, Field **aW, BiharmCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j;\n PetscReal xymin[2], xymax[2], hx, hy, x, y;\n ierr = DMGetBoundingBox(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 for (j = info->ys; j < info->ys + info->ym; j++) {\n y = j * hy;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n x = i * hx;\n aW[j][i].u = u_exact_fcn(x,y);\n aW[j][i].v = lap_u_exact_fcn(x,y);\n }\n }\n return 0;\n}\n\nPetscErrorCode FormFunctionLocal(DMDALocalInfo *info, Field **aW,\n Field **FF, BiharmCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j;\n PetscReal xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, x, y,\n ve, vw, vn, vs, ue, uw, un, us;\n ierr = DMGetBoundingBox(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; // multiply FD equations by this\n scx = hy / hx;\n scy = 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 FF[j][i].v = scdiag * aW[j][i].v;\n FF[j][i].u = scdiag * aW[j][i].u;\n } else {\n ve = (i+1 == info->mx-1) ? 0.0 : aW[j][i+1].v;\n vw = (i-1 == 0) ? 0.0 : aW[j][i-1].v;\n vn = (j+1 == info->my-1) ? 0.0 : aW[j+1][i].v;\n vs = (j-1 == 0) ? 0.0 : aW[j-1][i].v;\n FF[j][i].v = scdiag * aW[j][i].v - scx * (vw + ve) - scy * (vs + vn)\n - darea * (*(user->f))(x,y);\n ue = (i+1 == info->mx-1) ? 0.0 : aW[j][i+1].u;\n uw = (i-1 == 0) ? 0.0 : aW[j][i-1].u;\n un = (j+1 == info->my-1) ? 0.0 : aW[j+1][i].u;\n us = (j-1 == 0) ? 0.0 : aW[j-1][i].u;\n FF[j][i].u = - darea * aW[j][i].v\n + scdiag * aW[j][i].u - scx * (uw + ue) - scy * (us + un);\n }\n }\n }\n ierr = PetscLogFlops(18.0*info->xm*info->ym);CHKERRQ(ierr);\n return 0;\n}\n\nPetscErrorCode FormJacobianLocal(DMDALocalInfo *info, Field **aW,\n Mat J, Mat Jpre, BiharmCtx *user) {\n PetscErrorCode ierr;\n PetscInt i, j, c, ncol;\n PetscReal xymin[2], xymax[2], hx, hy, darea, scx, scy, scdiag, val[6];\n MatStencil col[6], row;\n\n ierr = DMGetBoundingBox(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; // multiply FD equations by this\n scx = hy / hx;\n scy = hx / hy;\n scdiag = 2.0 * (scx + scy); // diagonal scaling\n for (j = info->ys; j < info->ys + info->ym; j++) {\n row.j = j;\n for (i = info->xs; i < info->xs + info->xm; i++) {\n row.i = i;\n for (c = 0; c < 2; c++) { // v,u equations are c=0,1\n row.c = c;\n col[0].c = c; col[0].i = i; col[0].j = j;\n val[0] = scdiag;\n if (i==0 || i==info->mx-1 || j==0 || j==info->my-1) {\n ierr = MatSetValuesStencil(Jpre,1,&row,1,col,val,INSERT_VALUES);\n CHKERRQ(ierr);\n } else {\n ncol = 1;\n if (i+1 < info->mx-1) {\n col[ncol].c = c; col[ncol].i = i+1; col[ncol].j = j;\n val[ncol++] = -scx;\n }\n if (i-1 > 0) {\n col[ncol].c = c; col[ncol].i = i-1; col[ncol].j = j;\n val[ncol++] = -scx;\n }\n if (j+1 < info->my-1) {\n col[ncol].c = c; col[ncol].i = i; col[ncol].j = j+1;\n val[ncol++] = -scy;\n }\n if (j-1 > 0) {\n col[ncol].c = c; col[ncol].i = i; col[ncol].j = j-1;\n val[ncol++] = -scy;\n }\n if (c == 1) { // u equation; has off-diagonal block entry\n col[ncol].c = 0;\n col[ncol].i = i; col[ncol].j = j;\n val[ncol++] = - darea;\n }\n ierr = MatSetValuesStencil(Jpre,1,&row,ncol,col,val,INSERT_VALUES);\n CHKERRQ(ierr);\n }\n }\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\n", "meta": {"hexsha": "6bcf7d8b450455724b16f4fd0469a18d84cb9f32", "size": 10211, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch7/biharm.c", "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_issues_repo_path": "c/ch7/biharm.c", "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_forks_repo_path": "c/ch7/biharm.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": 41.8483606557, "max_line_length": 91, "alphanum_fraction": 0.5251199687, "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6134604197025894}} {"text": "//\r\n// Created by karl_ on 2020-5-3.\r\n//\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"color-convert.h\"\r\n\r\n\r\n// ref: https://www.math.uci.edu/icamp/courses/math77c/demos/hist_eq.pdf\r\nstatic void\r\nhisteq(double const *src, unsigned src_stride, double *dst, unsigned dst_stride, size_t area, unsigned range) {\r\n unsigned *cdf;\r\n size_t i;\r\n cdf = calloc(range, sizeof(unsigned));\r\n for (i = 0; i < area; ++i) {\r\n cdf[(int) (src[i * src_stride] * range)] += 1;\r\n }\r\n for (i = 1; i < range; ++i) {\r\n cdf[i] += cdf[i - 1];\r\n }\r\n for (i = 0; i < area; ++i) {\r\n dst[i * dst_stride] = floor((double) (range - 1) * cdf[(int) (src[i * src_stride] * range)] / area) / range;\r\n }\r\n free(cdf);\r\n}\r\n\r\nstatic gboolean histeq_grayscale(CoreImage *src, CoreImage **dst) {\r\n gdouble *src_data_cast = NULL;\r\n gdouble *dst_data_cast = NULL;\r\n gpointer src_data, dst_data;\r\n CoreSize *size = NULL;\r\n guint8 channel;\r\n gsize i, area;\r\n CoreColorSpace color_space;\r\n CorePixelType pixel_type;\r\n gdouble range, inv_range;\r\n g_return_val_if_fail(src != NULL, FALSE);\r\n g_return_val_if_fail(dst != NULL, FALSE);\r\n\r\n channel = core_image_get_channel(src);\r\n g_return_val_if_fail(channel == 1, FALSE);\r\n\r\n src = g_object_ref(src);\r\n src_data = core_image_get_data(src);\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n color_space = core_image_get_color_space(src);\r\n pixel_type = core_image_get_pixel_type(src);\r\n range = core_pixel_get_range(pixel_type);\r\n inv_range = 1.0 / range;\r\n\r\n /* cast to double and normalize pixel data to [0, 1] */\r\n if (core_pixel_is_double(pixel_type)) {\r\n src_data_cast = src_data;\r\n } else if (core_pixel_is_uint8(pixel_type)) {\r\n src_data_cast = g_malloc(sizeof(gdouble) * area);\r\n for (i = 0; i < area; ++i) {\r\n src_data_cast[i] = ((guint8 *) src_data)[i] * inv_range;\r\n }\r\n } else {\r\n g_return_val_if_fail(FALSE, FALSE);\r\n }\r\n dst_data_cast = g_malloc(sizeof(gdouble) * area);\r\n\r\n /* run the algorithm */\r\n histeq(src_data_cast, 1, dst_data_cast, 1, area, 256);\r\n\r\n /* cast back to uchar */\r\n if (core_pixel_is_double(pixel_type)) {\r\n /* exactly do nothing */\r\n } else if (core_pixel_is_uint8(pixel_type)) {\r\n /* reuse allocated memory */\r\n for (i = 0; i < area; ++i) {\r\n ((guint8 *) dst_data_cast)[i] = dst_data_cast[i] * 255.0;\r\n }\r\n } else {\r\n g_return_val_if_fail(FALSE, FALSE);\r\n }\r\n dst_data = dst_data_cast;\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n /* release useless memory, can be removed for speed */\r\n dst_data = g_realloc(dst_data, sizeof(guint8) * area);\r\n }\r\n\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, color_space, pixel_type, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, color_space, pixel_type, size, FALSE);\r\n }\r\n\r\n /* free allocated additional memory */\r\n if (core_pixel_is_uint8(pixel_type)) {\r\n g_free(src_data_cast);\r\n }\r\n g_object_unref(size);\r\n g_object_unref(src);\r\n return TRUE;\r\n}\r\n\r\n\r\nstatic gboolean histeq_hsl(CoreImage *src, CoreImage **dst) {\r\n gdouble *src_data, *dst_data;\r\n CoreSize *size;\r\n gsize area, block_size;\r\n\r\n src_data = core_image_get_data(src);\r\n size = core_image_get_size(src);\r\n area = core_size_get_area(size);\r\n block_size = area * 3 * sizeof(gdouble);\r\n dst_data = g_malloc(block_size);\r\n memcpy(dst_data, src_data, block_size);\r\n histeq(src_data + 2, 3, dst_data + 2, 3, area, 255);\r\n\r\n if (*dst == NULL) {\r\n *dst = core_image_new_with_data(dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);\r\n } else {\r\n core_image_assign_data(*dst, dst_data, CORE_COLOR_SPACE_HSL, CORE_PIXEL_D3, size, FALSE);\r\n }\r\n\r\n g_object_unref(size);\r\n}\r\n\r\ngboolean imgproc_histogram_equalization(CoreImage *src, CoreImage **dst) {\r\n CoreColorSpace src_color_space = core_image_get_color_space(src);\r\n CoreImage *dummy = NULL;\r\n gboolean ret;\r\n\r\n if (src_color_space == CORE_COLOR_SPACE_GRAY_SCALE) {\r\n ret = histeq_grayscale(src, dst);\r\n } else {\r\n if (src_color_space == CORE_COLOR_SPACE_RGB) {\r\n imgproc_to_HSL(src, &dummy);\r\n } else {\r\n dummy = g_object_ref(src);\r\n }\r\n ret = histeq_hsl(dummy, dst);\r\n g_object_unref(dummy);\r\n if (src_color_space == CORE_COLOR_SPACE_RGB) {\r\n imgproc_to_RGB(*dst, dst);\r\n }\r\n }\r\n return ret;\r\n}\r\n", "meta": {"hexsha": "2526733226a04c49b317549dad62410a97cddc57", "size": 4733, "ext": "c", "lang": "C", "max_stars_repo_path": "imgproc/histogram-equalization.c", "max_stars_repo_name": "Mr9567/EasyPhotoshop", "max_stars_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T15:33:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T01:09:35.000Z", "max_issues_repo_path": "imgproc/histogram-equalization.c", "max_issues_repo_name": "Mr9567/EasyPhotoshop", "max_issues_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T06:45:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-08T09:03:35.000Z", "max_forks_repo_path": "imgproc/histogram-equalization.c", "max_forks_repo_name": "Mr9567/EasyPhotoshop", "max_forks_repo_head_hexsha": "cb40bfe3b46b2cd06e871eb059e12b19a7cac5dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T14:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T11:19:18.000Z", "avg_line_length": 31.9797297297, "max_line_length": 117, "alphanum_fraction": 0.614198183, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6134565189694104}} {"text": "/* Cholesky Decomposition\n *\n * Copyright (C) 2000 Thomas Walter\n *\n * 03 May 2000: Modified for GSL by Brian Gough\n * 29 Jul 2005: Additions by Gerard Jungman\n * Copyright (C) 2000,2001, 2002, 2003, 2005, 2007 Brian Gough, Gerard Jungman\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n */\n\n/*\n * Cholesky decomposition of a symmetrix positive definite matrix.\n * This is useful to solve the matrix arising in\n * periodic cubic splines\n * approximating splines\n *\n * This algorithm does:\n * A = L * L'\n * with\n * L := lower left triangle matrix\n * L' := the transposed form of L.\n *\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic inline \ndouble\nquiet_sqrt (double x) \n /* avoids runtime error, for checking matrix for positive definiteness */\n{\n return (x >= 0) ? sqrt(x) : GSL_NAN;\n}\n\nint\ngsl_linalg_cholesky_decomp (gsl_matrix * A)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (M != N)\n {\n GSL_ERROR(\"cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else\n {\n size_t i,j,k;\n int status = 0;\n\n /* Do the first 2 rows explicitly. It is simple, and faster. And\n * one can return if the matrix has only 1 or 2 rows. \n */\n\n double A_00 = gsl_matrix_get (A, 0, 0);\n \n double L_00 = quiet_sqrt(A_00);\n \n if (A_00 <= 0)\n {\n status = GSL_EDOM ;\n }\n\n gsl_matrix_set (A, 0, 0, L_00);\n \n if (M > 1)\n {\n double A_10 = gsl_matrix_get (A, 1, 0);\n double A_11 = gsl_matrix_get (A, 1, 1);\n \n double L_10 = A_10 / L_00;\n double diag = A_11 - L_10 * L_10;\n double L_11 = quiet_sqrt(diag);\n \n if (diag <= 0)\n {\n status = GSL_EDOM;\n }\n\n gsl_matrix_set (A, 1, 0, L_10); \n gsl_matrix_set (A, 1, 1, L_11);\n }\n \n for (k = 2; k < M; k++)\n {\n double A_kk = gsl_matrix_get (A, k, k);\n \n for (i = 0; i < k; i++)\n {\n double sum = 0;\n\n double A_ki = gsl_matrix_get (A, k, i);\n double A_ii = gsl_matrix_get (A, i, i);\n\n gsl_vector_view ci = gsl_matrix_row (A, i);\n gsl_vector_view ck = gsl_matrix_row (A, k);\n\n if (i > 0) {\n gsl_vector_view di = gsl_vector_subvector(&ci.vector, 0, i);\n gsl_vector_view dk = gsl_vector_subvector(&ck.vector, 0, i);\n \n gsl_blas_ddot (&di.vector, &dk.vector, &sum);\n }\n\n A_ki = (A_ki - sum) / A_ii;\n gsl_matrix_set (A, k, i, A_ki);\n } \n\n {\n gsl_vector_view ck = gsl_matrix_row (A, k);\n gsl_vector_view dk = gsl_vector_subvector (&ck.vector, 0, k);\n \n double sum = gsl_blas_dnrm2 (&dk.vector);\n double diag = A_kk - sum * sum;\n\n double L_kk = quiet_sqrt(diag);\n \n if (diag <= 0)\n {\n status = GSL_EDOM;\n }\n \n gsl_matrix_set (A, k, k, L_kk);\n }\n }\n\n /* Now copy the transposed lower triangle to the upper triangle,\n * the diagonal is common. \n */\n \n for (i = 1; i < M; i++)\n {\n for (j = 0; j < i; j++)\n {\n double A_ij = gsl_matrix_get (A, i, j);\n gsl_matrix_set (A, j, i, A_ij);\n }\n } \n \n if (status == GSL_EDOM)\n {\n GSL_ERROR (\"matrix must be positive definite\", GSL_EDOM);\n }\n \n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_linalg_cholesky_solve (const gsl_matrix * LLT,\n const gsl_vector * b,\n gsl_vector * x)\n{\n if (LLT->size1 != LLT->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else if (LLT->size1 != b->size)\n {\n GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n }\n else if (LLT->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 c using forward-substitution, L c = b */\n\n gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);\n\n /* Perform back-substitution, U x = c */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);\n\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_cholesky_svx (const gsl_matrix * LLT,\n gsl_vector * x)\n{\n if (LLT->size1 != LLT->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else if (LLT->size2 != x->size)\n {\n GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n }\n else\n {\n /* Solve for c using forward-substitution, L c = b */\n\n gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);\n\n /* Perform back-substitution, U x = c */\n\n gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_cholesky_invert()\n Compute the inverse of a symmetric positive definite matrix in\nCholesky form.\n\nInputs: LLT - matrix in cholesky form on input\n A^{-1} = L^{-t} L^{-1} on output\n\nReturn: success or error\n*/\n\nint\ngsl_linalg_cholesky_invert(gsl_matrix * LLT)\n{\n if (LLT->size1 != LLT->size2)\n {\n GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n }\n else\n {\n size_t N = LLT->size1;\n size_t i, j;\n double sum;\n gsl_vector_view v1, v2;\n\n /* invert the lower triangle of LLT */\n for (i = 0; i < N; ++i)\n {\n double ajj;\n\n j = N - i - 1;\n\n gsl_matrix_set(LLT, j, j, 1.0 / gsl_matrix_get(LLT, j, j));\n ajj = -gsl_matrix_get(LLT, j, j);\n\n if (j < N - 1)\n {\n gsl_matrix_view m;\n \n m = gsl_matrix_submatrix(LLT, j + 1, j + 1,\n N - j - 1, N - j - 1);\n v1 = gsl_matrix_subcolumn(LLT, j, j + 1, N - j - 1);\n\n gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit,\n &m.matrix, &v1.vector);\n\n gsl_blas_dscal(ajj, &v1.vector);\n }\n } /* for (i = 0; i < N; ++i) */\n\n /*\n * The lower triangle of LLT now contains L^{-1}. Now compute\n * A^{-1} = L^{-t} L^{-1}\n *\n * The (ij) element of A^{-1} is column i of L^{-1} dotted into\n * column j of L^{-1}\n */\n\n for (i = 0; i < N; ++i)\n {\n for (j = i + 1; j < N; ++j)\n {\n v1 = gsl_matrix_subcolumn(LLT, i, j, N - j);\n v2 = gsl_matrix_subcolumn(LLT, j, j, N - j);\n\n /* compute Ainv_{ij} = sum_k Linv_{ki} Linv_{kj} */\n gsl_blas_ddot(&v1.vector, &v2.vector, &sum);\n\n /* store in upper triangle */\n gsl_matrix_set(LLT, i, j, sum);\n }\n\n /* now compute the diagonal element */\n v1 = gsl_matrix_subcolumn(LLT, i, i, N - i);\n gsl_blas_ddot(&v1.vector, &v1.vector, &sum);\n gsl_matrix_set(LLT, i, i, sum);\n }\n\n /* copy the transposed upper triangle to the lower triangle */\n\n for (j = 1; j < N; j++)\n {\n for (i = 0; i < j; i++)\n {\n double A_ij = gsl_matrix_get (LLT, i, j);\n gsl_matrix_set (LLT, j, i, A_ij);\n }\n } \n\n return GSL_SUCCESS;\n }\n} /* gsl_linalg_cholesky_invert() */\n\nint\ngsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D)\n{\n const size_t N = A->size1;\n size_t i, j;\n\n /* initial Cholesky */\n int stat_chol = gsl_linalg_cholesky_decomp(A);\n\n if(stat_chol == GSL_SUCCESS)\n {\n /* calculate D from diagonal part of initial Cholesky */\n for(i = 0; i < N; ++i)\n {\n const double C_ii = gsl_matrix_get(A, i, i);\n gsl_vector_set(D, i, C_ii*C_ii);\n }\n\n /* multiply initial Cholesky by 1/sqrt(D) on the right */\n for(i = 0; i < N; ++i)\n {\n for(j = 0; j < N; ++j)\n {\n gsl_matrix_set(A, i, j, gsl_matrix_get(A, i, j) / sqrt(gsl_vector_get(D, j)));\n }\n }\n\n /* Because the initial Cholesky contained both L and transpose(L),\n the result of the multiplication is not symmetric anymore;\n but the lower triangle _is_ correct. Therefore we reflect\n it to the upper triangle and declare victory.\n */\n for(i = 0; i < N; ++i)\n for(j = i + 1; j < N; ++j)\n gsl_matrix_set(A, i, j, gsl_matrix_get(A, j, i));\n }\n\n return stat_chol;\n}\n", "meta": {"hexsha": "8519fdce77e82b952153f77923fc99bc98c3d6e2", "size": 9283, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/linalg/cholesky.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/linalg/cholesky.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/linalg/cholesky.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": 25.8579387187, "max_line_length": 86, "alphanum_fraction": 0.5290315631, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6128502527626212}} {"text": "#include \n#include \n#include \n#include \n#include \"my_timer.h\"\n\n#define N 5\n\nint cal_index_offset(int ndim, int *darr, int *position) {\n int size = 1;\n int offset = 0;\n for(int i = ndim-1; i >= 0; i--) {\n offset += position[i] * size;\n size *= darr[i];\n }\n return offset;\n}\n\nvoid print_mat_recursive(double *mat, int ndim, int *darr, int pdim, int *position) {\n if(pdim >= ndim) {\n int index_offset = cal_index_offset(ndim, darr, position);\n printf(\"%lf \", mat[index_offset]);\n return;\n }\n\n printf(\"[ \");\n for(int i = 0; i < darr[pdim]; i++) {\n position[pdim] = i;\n print_mat_recursive(mat, ndim, darr, pdim+1, position);\n }\n printf(\"]\");\n}\n\nvoid print_mat(double *mat, int ndim, ...) {\n int position[ndim];\n int darr[ndim];\n\n va_list args;\n va_start(args, ndim);\n for(int i = 0; i < ndim; i++) {\n darr[i] = va_arg(args, int);\n }\n va_end(args);\n\n print_mat_recursive(mat, ndim, darr, 0, position);\n printf(\"\\n\");\n}\n\nvoid mm_brute_force(double *a, double *b, double *c, int p, int q, int r) {\n for(int i = 0; i < p; i++) {\n for(int k = 0; k < q; k++) {\n for(int j = 0; j < r; j++) {\n c[i * r + j] += a[i * q + k] * b[k * r + j];\n }\n }\n }\n}\n\nvoid mm_dgemm(double *a, double *b, double *c, int p, int q, int r) {\n int l = p;\n int m = q;\n int n = r;\n\n int lda = m;\n int ldb = n;\n int ldc = n;\n\n double alpha = 1.0;\n double beta = 0.0;\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n l, n, m, alpha, a, lda, b, ldb, beta, c, ldc);\n}\n\n\nvoid example_dgemm() {\n int l, m, n;\n l = m = n = N;\n\n double *mat_a = (double*)malloc(sizeof(double) * l * m);\n double *mat_b = (double*)malloc(sizeof(double) * m * n);\n double *mat_c = (double*)malloc(sizeof(double) * l * n);\n\n for(int i = 0; i < (l*m); i++) {\n mat_a[i] = i + 1;\n }\n\n for(int i = 0; i < (m*n); i++) {\n mat_b[i] = i + 1;\n }\n\n for(int i = 0; i < (l*n); i++) {\n mat_c[i] = 0;\n }\n\n my_timer_t mt;\n my_timer_start(&mt);\n mm_dgemm(mat_a, mat_b, mat_c, l, m, n);\n my_timer_end(&mt);\n my_timer_print(&mt);\n printf(\"\\n\");\n\n print_mat(mat_a, 2, l, m);\n printf(\"\\n\");\n print_mat(mat_b, 2, m, n);\n printf(\"\\n\");\n print_mat(mat_c, 2, l, n);\n printf(\"\\n\");\n\n free(mat_a);\n free(mat_b);\n free(mat_c);\n}\n\nint main(void) {\n example_dgemm();\n return 0;\n}\n", "meta": {"hexsha": "03dd4fc6b041eb33807ec4c4cc528d913ac37650", "size": 2556, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "read2r/blas_practice", "max_stars_repo_head_hexsha": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf", "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": "read2r/blas_practice", "max_issues_repo_head_hexsha": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf", "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": "read2r/blas_practice", "max_forks_repo_head_hexsha": "80a0579c890bbb1a4d3ee6ee323f23d1204d0bdf", "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.4789915966, "max_line_length": 85, "alphanum_fraction": 0.5082159624, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6126838745072667}} {"text": "#include \n#include \n#include \n#include \n#include \n#define COMPEARTH_PRIVATE_DET3X3 1\n#define COMPEARTH_PRIVATE_CROSS3 1\n#define COMPEARTH_PRIVATE_NORM3 1\n#define COMPEARTH_PRIVATE_GEM3 1\n#define COMPEARTH_PRIVATE_GEMT3 1\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//#include \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \n//#include \n#endif\n\n#define LWORK 15\n\n/*!\n * @brief Converts a nearly orthogonal matrix into a numerically orthogonal\n * matrix.\n *\n * @param[in] n Number of bases.\n * @param[in] itype Orthogonalization strategy. \\n\n * CE_ORTH_SVD orthgonalizes with the SVD. \\n\n * CE_ORTH_TAPE2012 orthogalizes with Tape 2012c \n * Appendix E. \\n\n * CE_ORTH_QUAT orthogonalizes with quaternions.\n * @param[in] Uin [3 x 3 x n] set of bases where each [3 x 3] basis is\n * in column major order.\n *\n * @param[out] Uout [3 x 3 x n] set of re-orthgonalized bases where\n * each [3 x 3] bais is in column major order.\n * @param[out] dtUin If NULL then this will be ignored. \\n\n * Otherwise, this is an array of dimension [n] holding\n * the determinants of the input basis.\n * @param[out] dtUout If NULL then this will be ignored. \\n\n * Otherwise, this is an array of dimension [n] holding\n * the determinants of the output basis.\n * \n * @result 0 indicates success.\n *\n * @author Carl Tape and converted to C by Ben Baker.\n *\n */\nint compearth_Uorth(const int n,\n const enum ceOrthoType_enum itype,\n const double *__restrict__ Uin,\n double *__restrict__ Uout,\n double *__restrict__ dtUin,\n double *__restrict__ dtUout)\n{\n double Ut[9] __attribute__((aligned(64)));\n double U[9] __attribute__((aligned(64)));\n double Vt[9] __attribute__((aligned(64)));\n double work[LWORK], s[3], p[3], det, normb, normp;\n int i, ierr;\n bool lwantDetIn;\n const double tol = DBL_EPSILON*100.0;\n // Check inputs\n if (n < 1 || Uin == NULL || Uout == NULL)\n {\n if (n < 1){fprintf(stderr, \"%s: No matrices\\n\", __func__);}\n if (Uin == NULL){fprintf(stderr, \"%s: Uin is NULL\\n\", __func__);}\n if (Uout == NULL){fprintf(stderr, \"%s: Uout is NULL\\n\", __func__);}\n return -1;\n }\n lwantDetIn = false;\n if (dtUin != NULL){lwantDetIn = true;}\n // Orthogonalize basis with SVD\n if (itype == CE_ORTH_SVD)\n {\n for (i=0; i 1.e-12)\n {\n // Compute SVD\n memcpy(Ut, &Uin[9*i], 9*sizeof(double));\n ierr = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'A', 'A',\n 3, 3, Ut, 3, s, U, 3,\n Vt, 3, work, LWORK);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error computing Ut\\n\", __func__);\n return -1;\n }\n // Compute U*V' - note Vt is already computed by SVD\n gemm3_colMajorNoTransNoTrans(U, Vt, &Uout[9*i]);\n // N.B. I could get the determinant here from the singular\n // values but i'll wait\n }\n else\n {\n memcpy(&Uout[9*i], &Uin[9*i], 9*sizeof(double));\n }\n if (lwantDetIn){dtUin[i] = det;}\n }\n }\n // Orthgonalize with suggestion in TapeTape2012c Appendix E\n else if (itype == CE_ORTH_TAPE2012)\n {\n for (i=0; i tol)\n {\n cross3(&Uin[9*i], &Uin[9*i+3], p);\n normb = norm3(&Uin[9*i+3]);\n normp = norm3(p);\n Uout[9*i] = Uin[9*i];\n Uout[9*i+1] = Uin[9*i+1];\n Uout[9*i+2] = Uin[9*i+2];\n Uout[9*i+3] = Uin[9*i+3]/normb;\n Uout[9*i+4] = Uin[9*i+4]/normb;\n Uout[9*i+5] = Uin[9*i+5]/normb;\n Uout[9*i+6] = Uin[9*i+6]/normp;\n Uout[9*i+7] = Uin[9*i+7]/normp;\n Uout[9*i+8] = Uin[9*i+8]/normp;\n }\n else\n {\n memcpy(&Uout[9*i], &Uin[9*i], 9*sizeof(double));\n }\n if (lwantDetIn){dtUin[i] = det;}\n }\n }\n else if (itype == CE_ORTH_QUAT)\n {\n fprintf(stderr, \"%s: Error quaternions not yet programmed\\n\",\n __func__);\n return -1;\n }\n else if (itype == CE_NO_ORTH)\n {\n memcpy(Uout, Uin, 9*(size_t) n*sizeof(double));\n //cblas_dcopy(9*n, Uin, 1, Uout, 1);\n }\n else\n {\n fprintf(stderr, \"%s: Only itype=1 is programmed\\n\", __func__);\n return -1;\n }\n //if (dtUin != NULL)\n //{\n // for (i=0; i\n#include \n#include \n#include \n#include \n#include \n\nint\nfunc_f (const gsl_vector * x, void *params, gsl_vector * f)\n{\n double x1 = gsl_vector_get(x, 0);\n double x2 = gsl_vector_get(x, 1);\n\n gsl_vector_set(f, 0, 100.0 * (x2 - x1*x1));\n gsl_vector_set(f, 1, 1.0 - x1);\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_df (const gsl_vector * x, void *params, gsl_matrix * J)\n{\n double x1 = gsl_vector_get(x, 0);\n\n gsl_matrix_set(J, 0, 0, -200.0*x1);\n gsl_matrix_set(J, 0, 1, 100.0);\n gsl_matrix_set(J, 1, 0, -1.0);\n gsl_matrix_set(J, 1, 1, 0.0);\n\n return GSL_SUCCESS;\n}\n\nint\nfunc_fvv (const gsl_vector * x, const gsl_vector * v,\n void *params, gsl_vector * fvv)\n{\n double v1 = gsl_vector_get(v, 0);\n\n gsl_vector_set(fvv, 0, -200.0 * v1 * v1);\n gsl_vector_set(fvv, 1, 0.0);\n\n return GSL_SUCCESS;\n}\n\nvoid\ncallback(const size_t iter, void *params,\n const gsl_multifit_nlinear_workspace *w)\n{\n gsl_vector * x = gsl_multifit_nlinear_position(w);\n\n /* print out current location */\n printf(\"%f %f\\n\",\n gsl_vector_get(x, 0),\n gsl_vector_get(x, 1));\n}\n\nvoid\nsolve_system(gsl_vector *x0, gsl_multifit_nlinear_fdf *fdf,\n gsl_multifit_nlinear_parameters *params)\n{\n const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;\n const size_t max_iter = 200;\n const double xtol = 1.0e-8;\n const double gtol = 1.0e-8;\n const double ftol = 1.0e-8;\n const size_t n = fdf->n;\n const size_t p = fdf->p;\n gsl_multifit_nlinear_workspace *work =\n gsl_multifit_nlinear_alloc(T, params, n, p);\n gsl_vector * f = gsl_multifit_nlinear_residual(work);\n gsl_vector * x = gsl_multifit_nlinear_position(work);\n int info;\n double chisq0, chisq, rcond;\n\n /* initialize solver */\n gsl_multifit_nlinear_init(x0, fdf, work);\n\n /* store initial cost */\n gsl_blas_ddot(f, f, &chisq0);\n\n /* iterate until convergence */\n gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol,\n callback, NULL, &info, work);\n\n /* store final cost */\n gsl_blas_ddot(f, f, &chisq);\n\n /* store cond(J(x)) */\n gsl_multifit_nlinear_rcond(&rcond, work);\n\n /* print summary */\n\n fprintf(stderr, \"NITER = %zu\\n\", gsl_multifit_nlinear_niter(work));\n fprintf(stderr, \"NFEV = %zu\\n\", fdf->nevalf);\n fprintf(stderr, \"NJEV = %zu\\n\", fdf->nevaldf);\n fprintf(stderr, \"NAEV = %zu\\n\", fdf->nevalfvv);\n fprintf(stderr, \"initial cost = %.12e\\n\", chisq0);\n fprintf(stderr, \"final cost = %.12e\\n\", chisq);\n fprintf(stderr, \"final x = (%.12e, %.12e)\\n\",\n gsl_vector_get(x, 0), gsl_vector_get(x, 1));\n fprintf(stderr, \"final cond(J) = %.12e\\n\", 1.0 / rcond);\n\n printf(\"\\n\\n\");\n\n gsl_multifit_nlinear_free(work);\n}\n\nint\nmain (void)\n{\n const size_t n = 2;\n const size_t p = 2;\n gsl_vector *f = gsl_vector_alloc(n);\n gsl_vector *x = gsl_vector_alloc(p);\n gsl_multifit_nlinear_fdf fdf;\n gsl_multifit_nlinear_parameters fdf_params =\n gsl_multifit_nlinear_default_parameters();\n\n /* print map of Phi(x1, x2) */\n {\n double x1, x2, chisq;\n double *f1 = gsl_vector_ptr(f, 0);\n double *f2 = gsl_vector_ptr(f, 1);\n\n for (x1 = -1.2; x1 < 1.3; x1 += 0.1)\n {\n for (x2 = -0.5; x2 < 2.1; x2 += 0.1)\n {\n gsl_vector_set(x, 0, x1);\n gsl_vector_set(x, 1, x2);\n func_f(x, NULL, f);\n\n chisq = (*f1) * (*f1) + (*f2) * (*f2);\n printf(\"%f %f %f\\n\", x1, x2, chisq);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\\n\");\n }\n\n /* define function to be minimized */\n fdf.f = func_f;\n fdf.df = func_df;\n fdf.fvv = func_fvv;\n fdf.n = n;\n fdf.p = p;\n fdf.params = NULL;\n\n /* starting point */\n gsl_vector_set(x, 0, -0.5);\n gsl_vector_set(x, 1, 1.75);\n\n fprintf(stderr, \"=== Solving system without acceleration ===\\n\");\n fdf_params.trs = gsl_multifit_nlinear_trs_lm;\n solve_system(x, &fdf, &fdf_params);\n\n fprintf(stderr, \"=== Solving system with acceleration ===\\n\");\n fdf_params.trs = gsl_multifit_nlinear_trs_lmaccel;\n solve_system(x, &fdf, &fdf_params);\n\n gsl_vector_free(f);\n gsl_vector_free(x);\n\n return 0;\n}\n", "meta": {"hexsha": "f9ff23573f9bd31d21d2af3170ef5872a29bd701", "size": 4208, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/doc/examples/nlfit2.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/nlfit2.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/nlfit2.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.3493975904, "max_line_length": 77, "alphanum_fraction": 0.6257129278, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.612331641874947}} {"text": "#include \"cones.h\"\n#ifdef LAPACK_LIB_FOUND\n#include \n#include \n#endif\nvoid projectsdc(double * X, int n, Work * w); \n\n/* in place projection (with branches) */\nvoid projCone(double *x, Cone * k, Work * w)\n{\n\tint i;\n\tint count;\n\n\t/* project onto positive orthant */\n\tfor(i = k->f; i < k->f+k->l; ++i)\n\t{\n\t\tif(x[i] < 0.0) x[i] = 0.0;\n\t\t//x[i] = (x[i] < 0.0) ? 0.0 : x[i];\n\t}\n\tcount = k->l+k->f;\n\t/* project onto SOC */\n\tfor(i = 0; i < k->qsize; ++i)\n\t{\n\t\tdouble v1 = x[count];\n\t\tdouble s = calcNorm(&(x[count+1]),k->q[i]-1);\n\t\tdouble alpha = (s + v1)/2.0;\n\n\t\tif(s <= v1) { /* do nothing */ }\n\t\telse if (s <= - v1) {\n\t\t\tmemset(&(x[count]), 0, k->q[i]*sizeof(double));\n\t\t} else { \n\t\t\tx[count] = alpha;\n\t\t\tscaleArray(&(x[count+1]), alpha/s, k->q[i]-1);\n //cblas_dscal(k->q[i]-1, alpha/s, &(x[count+1]),1);\n\t\t} \n\t\tcount += k->q[i];\n\t}\n#ifdef LAPACK_LIB_FOUND\n\t/* project onto PSD cone */\n\tfor (i=0; i < k->ssize; ++i){\n\t\tprojectsdc(&(x[count]),k->s[i],w);\n\t\tcount += (k->s[i])*(k->s[i]);\n\t}\n#else\n if(k->ssize > 0){\n coneOS_printf(\"WARNING: solving SDP, no lapack library specified in makefile!\\n\");\n coneOS_printf(\"ConeOS will return a wrong answer!\\n\");\n}\n#endif\n\t/* project onto OTHER cones */\n}\n\n#ifdef LAPACK_LIB_FOUND\nvoid projectsdc(double *X, int n, Work * w)\n{ /* project onto the positive semi-definite cone */\n if (n == 1) {\n if(X[0] < 0.0) X[0] = 0.0; \n return;\n }\n\n int i, j, m=0;\n double * Xs = w->Xs;\n double * Z = w->Z;\n double * e = w->e;\n memcpy(Xs,X,n*n*sizeof(double));\n\n // Xs = X + X', save div by 2 for eigen-recomp\n for (i = 0; i < n; ++i){\n cblas_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);\n //b_daxpy(n, 1, &(X[i]), n, &(Xs[i*n]), 1);\n }\n \n double EIG_TOL = 1e-8;\n double vupper = calcNorm(Xs,n*n);\n LAPACKE_dsyevr( LAPACK_COL_MAJOR, 'V', 'V', 'U', n, Xs, n, 0.0, vupper, -1, -1, EIG_TOL, &m, e, Z, n , NULL);\n\n memset(X, 0, n*n*sizeof(double));\n for (i = 0; i < m; ++i) {\n cblas_dsyr(CblasColMajor, CblasLower, n, e[i]/2, &(Z[i*n]), 1, X, n);\n //b_dsyr('L', n, -e[i]/2, &(Z[i*n]), 1, Xs, n);\n }\n // fill in upper half \n for (i = 0; i < n; ++i){ \n for (j = i+1; j < n; ++j){ \n X[i + j*n] = X[j + i*n]; \n } \n }\n}\n#endif\n\n", "meta": {"hexsha": "65e2f6412f5d2d070a5f997d8005001c7d1fb5c6", "size": 2238, "ext": "c", "lang": "C", "max_stars_repo_path": "coneOSdense/cones.c", "max_stars_repo_name": "cvxgrp/coneos", "max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z", "max_issues_repo_path": "coneOSdense/cones.c", "max_issues_repo_name": "cvxgrp/coneos", "max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coneOSdense/cones.c", "max_forks_repo_name": "cvxgrp/coneos", "max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z", "avg_line_length": 24.5934065934, "max_line_length": 111, "alphanum_fraction": 0.5165326184, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6123227276259559}} {"text": "\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/* binomial coefficient, n choose k */\ndouble binom (int n,int k)\n{\n double prod,ix,nx,kx;\n int i;\n nx = (double)n;\n kx = (double)k;\n\n prod = ix = 1;\n for (i=1; i<=k; i++) {\n prod *= (nx-kx+ix)/ix;\n ix++;\n }\n return prod;\n}\n\nchar **randomCombinations(long maxiter,int n,unsigned long int seed)\n{\n size_t iter,i,j,k;\n size_t znum,maxnum=90000;\n\n /* ini random */\n fprintf(stderr,\" random shuffle\\n\");\n gsl_rng_env_setup();\n const gsl_rng_type *T = gsl_rng_default;\n gsl_rng *rx = gsl_rng_alloc(T);\n gsl_rng_set(rx,(unsigned long int)seed);\n\n\n /* ini data structs */\n int *src = (int *) calloc(n,sizeof(int));\n char *tmp = (char *)calloc(n,sizeof(char));\n for (i=0; i= maxnum) VError(\" znum %d\",znum);\n k = n/2;\n if (n%2 == 1 && iter%2 == 0) k++; /* for odd number of images */\n gsl_ran_shuffle (rx,src,n,sizeof(int));\n \n memset(tmp,'0',n*sizeof(char));\n for (j=0; j 0) {\n\ttmp[j] = '1';\n\tic++;\n }\n }\n for (j=0; j 0) {\n b=num%2;\n if (b == 1) tmp[j] = '1';\n num=num/2;\n j++;\n }\n /* fprintf(stderr,\" iter: %5d %s\\n\",iter,tmp); */\n memcpy(table[iter],tmp,(size_t)n);\n iter++;\n if (iter >= maxiter) return table;\n }\n return table;\n}\n", "meta": {"hexsha": "8908ddbd76d65a8d85e7aa329cf026bf8aae182a", "size": 3355, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/utils/genCombinations.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/utils/genCombinations.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/utils/genCombinations.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.3666666667, "max_line_length": 70, "alphanum_fraction": 0.5737704918, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6122801853562456}} {"text": "#pragma once\r\n\r\n#include \r\n#include \r\n\r\n#include \"Exponentials.h\"\r\n#include \"HyperionUtils/Concepts.h\"\r\n#include \"HyperionUtils/Macros.h\"\r\n#include \"HyperionUtils/OptionAndResult.h\"\r\n\r\nnamespace hyperion::math {\r\n\tusing utils::None;\r\n\tusing utils::Option;\r\n\tusing utils::Some;\r\n\tusing utils::concepts::FloatingPoint;\r\n\t/// @brief The possible kinds of value interpolation possible by `Interpolator`\r\n\tenum class InterpolationType\r\n\t{\r\n\t\tLinear = 0,\r\n\t\tLogarithmic,\r\n\t\tExponential\r\n\t};\r\n\r\n\tIGNORE_PADDING_START\r\n\t/// @brief Interpolates from a starting value to a final value in the way prescribed by `Type`\r\n\t/// @note `T` must be a floating point type\r\n\t/// @note The start value must be in [0, target value] and the target value must be > 0\r\n\t///\r\n\t/// @tparam T - The floating point type to perform operations in\r\n\t/// @tparam Type - The type of interpolation\r\n\ttemplate\r\n\tclass Interpolator {\r\n\t public:\r\n\t\tstatic constexpr T DEFAULT_TARGET_VALUE = gsl::narrow_cast(1.0);\r\n\t\tstatic constexpr T DEFAULT_INITIAL_VALUE = gsl::narrow_cast(0.0);\r\n\t\tstatic constexpr T DEFAULT_TRANSITION_LENGTH = gsl::narrow_cast(0.1);\r\n\t\tstatic constexpr size_t DEFAULT_SAMPLE_RATE = 44100ULL;\r\n\r\n\t\t/// @brief Creates a default `Interpolator`\r\n\t\tconstexpr Interpolator() noexcept = default;\r\n\r\n\t\t/// @brief Creates an `Interpolator` with the given target value\r\n\t\t///\r\n\t\t/// @param targetValue - The target final value to interpolate to\r\n\t\tconstexpr explicit Interpolator(T targetValue) noexcept\r\n\t\t\t: m_target_value(targetValue),\r\n\t\t\t mLinearTransitionStep(\r\n\t\t\t\t (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds)),\r\n\t\t\t m_samples_to_transition(get_samples_to_transition()) {\r\n\t\t}\r\n\r\n\t\t/// @brief Creates an `Interpolator` with the given target value and sample rate\r\n\t\t///\r\n\t\t/// @param targetValue - The target final value to interpolate to\r\n\t\t/// @param sampleRate - The sample rate to process at\r\n\t\tconstexpr explicit Interpolator(T targetValue, size_t sampleRate) noexcept\r\n\t\t\t: m_sample_rate(sampleRate), m_target_value(targetValue),\r\n\t\t\t mLinearTransitionStep(\r\n\t\t\t\t (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds)),\r\n\t\t\t m_samples_to_transition(get_samples_to_transition()) {\r\n\t\t}\r\n\r\n\t\t/// @brief Creates an `Interpolator` with the given target and initial values, and sample\r\n\t\t/// rate\r\n\t\t///\r\n\t\t/// @param targetValue - The target final value to interpolate to\r\n\t\t/// @param initial_value - The initial value to start interpolation from\r\n\t\t/// @param sampleRate - The sample rate to process at\r\n\t\tconstexpr Interpolator(T targetValue, T initial_value, size_t sampleRate) noexcept\r\n\t\t\t: m_sample_rate(sampleRate), m_target_value(targetValue),\r\n\t\t\t m_current_value(initial_value), m_initial_value(m_current_value),\r\n\t\t\t mLinearTransitionStep(\r\n\t\t\t\t (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds)),\r\n\t\t\t m_samples_to_transition(get_samples_to_transition()) {\r\n\t\t}\r\n\r\n\t\t/// @brief Creates an `Interpolator` with the given target and initial values, time to\r\n\t\t/// interpolate over, and sample rate\r\n\t\t///\r\n\t\t/// @param targetValue - The target final value to interpolate to\r\n\t\t/// @param initial_value - The initial value to start interpolation from\r\n\t\t/// @param transitionLengthSeconds - The transition time to interpolate over\r\n\t\t/// @param sampleRate - The sample rate to process at\r\n\t\tconstexpr Interpolator(T targetValue,\r\n\t\t\t\t\t\t\t T initial_value,\r\n\t\t\t\t\t\t\t T transitionLengthSeconds,\r\n\t\t\t\t\t\t\t size_t sampleRate) noexcept\r\n\t\t\t: m_sample_rate(sampleRate), m_target_value(targetValue),\r\n\t\t\t m_current_value(initial_value), m_initial_value(m_current_value),\r\n\t\t\t m_transition_lengthSeconds(transitionLengthSeconds),\r\n\t\t\t mLinearTransitionStep(\r\n\t\t\t\t (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds)),\r\n\t\t\t m_samples_to_transition(get_samples_to_transition()) {\r\n\t\t}\r\n\t\tconstexpr Interpolator(const Interpolator& interpolator) noexcept = default;\r\n\t\tconstexpr Interpolator(Interpolator&& interpolator) noexcept = default;\r\n\t\t~Interpolator() noexcept = default;\r\n\r\n\t\t/// @brief Gets the next value in the interpolation sequence\r\n\t\t/// If `currentSample` is given, gets the value in the sequence for the given sample index\r\n\t\t/// @note This is only available for `Interpolator`s of type\r\n\t\t/// `InterpolationType::Logarithmic` or `InterpolationType::Exponential`\r\n\t\t/// @param currentSample - The (optional) sample in the sequence to get the value for\r\n\t\t///\r\n\t\t/// @return - The interpolation value\r\n\t\tinline auto get_next_value(Option currentSample = None()) noexcept -> T {\r\n\t\t\tif(currentSample.is_some()) {\r\n\t\t\t\tm_current_transition_sample = currentSample.unwrap();\r\n\t\t\t}\r\n\r\n\t\t\tif(m_current_transition_sample <= m_samples_to_transition) {\r\n\t\t\t\tm_current_value = interpolate(m_current_transition_sample);\r\n\t\t\t\tm_current_transition_sample++;\r\n\t\t\t}\r\n\r\n\t\t\treturn m_current_value;\r\n\t\t}\r\n\r\n\t\t/// @brief Resets the `Interpolator`.\r\n\t\t/// - If `initial_value` is given, the `Interpolator` will start at the given one instead of\r\n\t\t/// `DEFAULT_INITIAL_VALUE`\r\n\t\t/// - If `transitionLengthSeconds` is also given, the `Interpolator` will interpolate over\r\n\t\t/// that length of time instead of the current one\r\n\t\t///\r\n\t\t/// @param initial_value - The initial value to start interpolation from\r\n\t\t/// @param transitionLengthSeconds - The transition time to interpolate over\r\n\t\tinline auto\r\n\t\treset(Option initial_value, Option transitionLengthSeconds) noexcept -> void {\r\n\t\t\tif(initial_value.is_some()) {\r\n\t\t\t\tm_current_value = initial_value.unwrap();\r\n\t\t\t\tm_initial_value = m_current_value;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tm_current_value = DEFAULT_INITIAL_VALUE;\r\n\t\t\t\tm_initial_value = m_current_value;\r\n\t\t\t}\r\n\r\n\t\t\tif(transitionLengthSeconds.is_some()) {\r\n\t\t\t\tm_transition_lengthSeconds = transitionLengthSeconds.unwrap();\r\n\t\t\t}\r\n\r\n\t\t\tmLinearTransitionStep\r\n\t\t\t\t= (m_target_value - m_current_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds);\r\n\t\t\tm_samples_to_transition = get_samples_to_transition();\r\n\t\t\tm_current_transition_sample = 0ULL;\r\n\t\t}\r\n\r\n\t\t/// @brief Sets the target value to interpolate to, to the given one\r\n\t\t///\r\n\t\t/// @param targetValue - The value to interpolate to\r\n\t\tconstexpr inline auto set_target(T targetValue) noexcept -> void {\r\n\t\t\tm_target_value = targetValue;\r\n\t\t\tm_initial_value = m_current_value;\r\n\t\t\tmLinearTransitionStep\r\n\t\t\t\t= (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds);\r\n\t\t\tm_samples_to_transition = get_samples_to_transition();\r\n\t\t}\r\n\r\n\t\t/// @brief Sets the sample rate to use for interpolation\r\n\t\t///\r\n\t\t/// @param sampleRate - The sample rate to use for interpolation\r\n\t\tinline auto set_sample_rate(size_t sampleRate) noexcept -> void {\r\n\t\t\tm_sample_rate = sampleRate;\r\n\t\t\tmLinearTransitionStep\r\n\t\t\t\t= (m_target_value - m_initial_value)\r\n\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds);\r\n\t\t\tm_samples_to_transition = get_samples_to_transition();\r\n\t\t\tm_current_transition_sample = 0ULL;\r\n\t\t}\r\n\r\n\t\tconstexpr auto\r\n\t\toperator=(const Interpolator& interpolator) noexcept -> Interpolator& = default;\r\n\t\tconstexpr auto operator=(Interpolator&& interpolator) noexcept -> Interpolator& = default;\r\n\r\n\t private:\r\n\t\tstatic constexpr T LOG_TIME_FACTOR = gsl::narrow_cast(5.0);\r\n\t\tstatic constexpr T EXP_TIME_FACTOR = gsl::narrow_cast(0.693);\r\n\r\n\t\tsize_t m_sample_rate = DEFAULT_SAMPLE_RATE;\r\n\t\tT m_target_value = DEFAULT_TARGET_VALUE;\r\n\t\tT m_current_value = DEFAULT_INITIAL_VALUE;\r\n\t\tT m_initial_value = DEFAULT_INITIAL_VALUE;\r\n\t\tT m_transition_lengthSeconds = DEFAULT_TRANSITION_LENGTH;\r\n\t\tT mLinearTransitionStep\r\n\t\t\t= (m_target_value - m_initial_value)\r\n\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds);\r\n\t\tsize_t m_samples_to_transition = get_samples_to_transition();\r\n\t\tsize_t m_current_transition_sample = 0;\r\n\r\n\t\t/// @brief Gets the interpolated value for the given sample\r\n\t\t///\r\n\t\t/// @param sample - The sample to get the interpolated value for\r\n\t\t///\r\n\t\t/// @return The interpolated value\r\n\t\tinline auto interpolate(size_t sample) noexcept -> T {\r\n\t\t\tif constexpr(Type == InterpolationType::Linear) {\r\n\t\t\t\treturn linear_interpolation(sample);\r\n\t\t\t}\r\n\t\t\telse if constexpr(Type == InterpolationType::Logarithmic) {\r\n\t\t\t\treturn log_interpolation(sample);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\treturn exp_interpolation(sample);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tinline auto linear_interpolation(size_t sample) noexcept -> T {\r\n\t\t\treturn m_initial_value + (mLinearTransitionStep * gsl::narrow_cast(sample));\r\n\t\t}\r\n\r\n\t\t/// @brief Performs \"logarithmic\" interpolation.\r\n\t\t/// In reality, this is a pseudo logarithmic shape:\r\n\t\t///\r\n\t\t/// y = transition_factor *\r\n\t\t/// [1 + (peak_factor - 1) * (-e^{1 - t / (transtionLength / time_factor) } ) ]\r\n\t\t///\r\n\t\t/// where t = sample / sampleRate\r\n\t\t///\r\n\t\t/// which has a horizontal asymptote at ~ the target value and more pronouced slope\r\n\t\t///\r\n\t\t/// @param sample - The sample to get the interpolation value for\r\n\t\t///\r\n\t\t/// @return - The interpolated value\r\n\t\tinline auto log_interpolation(size_t sample) noexcept -> T {\r\n\t\t\treturn (m_initial_value - m_target_value)\r\n\t\t\t\t\t * math::Exponentials::exp(-gsl::narrow_cast(sample)\r\n\t\t\t\t\t\t\t\t\t\t\t\t / (gsl::narrow_cast(m_sample_rate)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t* m_transition_lengthSeconds / LOG_TIME_FACTOR))\r\n\t\t\t\t + m_target_value;\r\n\t\t}\r\n\r\n\t\t/// @brief Performs exponential interpolation:\r\n\t\t///\r\n\t\t/// y = e^{t / (transitionLength / time_factor) } - 1\r\n\t\t///\r\n\t\t/// where t = sample / sampleRate\r\n\t\t///\r\n\t\t/// @param sample The sample to get the interpolation value for\r\n\t\t///\r\n\t\t/// @return - The interpolated value\r\n\t\tinline auto exp_interpolation(size_t sample) noexcept -> T {\r\n\t\t\treturn (m_target_value - m_initial_value)\r\n\t\t\t\t\t * (math::Exponentials::exp(\r\n\t\t\t\t\t\t\t gsl::narrow_cast(sample)\r\n\t\t\t\t\t\t\t / (gsl::narrow_cast(m_sample_rate) * m_transition_lengthSeconds\r\n\t\t\t\t\t\t\t\t / EXP_TIME_FACTOR))\r\n\t\t\t\t\t\t - gsl::narrow_cast(1.0))\r\n\t\t\t\t + m_initial_value;\r\n\t\t}\r\n\r\n\t\t/// @brief Gets the number of samples necessary to fully complete the interpolation sequence\r\n\t\t///\r\n\t\t/// @return The number of samples in the interpolation sequence\r\n\t\tinline auto get_samples_to_transition() noexcept -> size_t {\r\n\t\t\treturn gsl::narrow_cast(gsl::narrow_cast(m_sample_rate)\r\n\t\t\t\t\t\t\t\t\t\t\t* m_transition_lengthSeconds);\r\n\t\t}\r\n\t};\r\n\tIGNORE_PADDING_STOP\r\n\r\n} // namespace hyperion::math\r\n", "meta": {"hexsha": "7725a7a290b181b156ba15d541fcd2fad8699428", "size": 10697, "ext": "h", "lang": "C", "max_stars_repo_path": "include/HyperionMath/Interpolator.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/Interpolator.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/Interpolator.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": 39.9141791045, "max_line_length": 96, "alphanum_fraction": 0.7076750491, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.6122801802347105}} {"text": "/**\nCopyright (c) 2014, Konstantinos Chatzilygeroudis\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer\n in the documentation and/or other materials provided with the distribution.\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**/\n\n#ifndef GEOMETRIC_TOOLS_MATH_VECTOR_H\n#define GEOMETRIC_TOOLS_MATH_VECTOR_H\n\n/**\n* Includes\n**/\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace GeometricTools { namespace Math {\n\ntemplate\nclass Matrix;\n\n/**\n* General Vector Class\n* Supports N-dimension vectors\n**/\ntemplate\nclass Vector\n{\nprotected:\n // values of vector\n double values_[N];\n // helper variable for initialization\n unsigned int index_;\n\n\n /**\n * Initialize Vector from double values\n * C++11 feature - variadic templates for multiple arguments\n **/\n template\n void initialize(double h, Args&&... args)\n {\n if(index_>=N)\n index_=0;\n // add first argument to the vector data\n values_[index_] = h;\n index_++;\n // Initialize with rest of arguments\n initialize(std::forward(args)...);\n }\n\n /**\n * Initialize Vector from double values\n * C++11 feature - variadic templates for multiple arguments\n * Terminating Case - end of arguments\n **/\n template\n void initialize()\n {\n index_ = 0;\n }\n\npublic:\t\n\n /**\n * Default Constructor\n * initialize all data to zero\n **/\n Vector()\n {\n memset(values_,0,N*sizeof(double));\n }\n\n /**\n * Copy Constructor\n * @param other - Vector to copy from\n **/\n Vector(const Vector& other)\n {\n memcpy(values_,other.values_,N*sizeof(double));\n }\n\n /**\n * Constructor\n * @param h - list of double values\n **/\n template\n Vector(double h, Args&&... args)\n {\n index_ = 0;\n memset(values_,0,N*sizeof(double));\n // use recursive initialization\n initialize(h, args...);\n }\n\n /**\n * Overloading += operator\n * Addition of 2 Vectors\n * @param other - vector to perform addition with\n * @return Vector - self (as the result is saved there)\n **/\n Vector operator+=(const Vector& other)\n {\n cblas_daxpy(N, 1.0, &other.values_[0], 1, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading -= operator\n * Subtraction of 2 Vectors\n * @param other - vector to perform subtraction with\n * @return Vector - self (as the result is saved there)\n **/\n Vector operator-=(const Vector& other)\n {\n cblas_daxpy(N, -1.0, &other.values_[0], 1, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading += operator\n * Addition with scalar (double)\n * @param other - double to add with\n * @return Vector - self (result)\n **/\n Vector operator+=(const double& other)\n {\n Vector tmp;\n tmp.ones();\n cblas_daxpy(N, other, &tmp.values_[0], 1, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading -= operator\n * Subtraction of scalar (double)\n * @param other - double to substract\n * @return Vector - self (result)\n **/\n Vector operator-=(const double& other)\n {\n Vector tmp;\n tmp.ones();\n cblas_daxpy(N, -other, &tmp.values_[0], 1, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading *= operator\n * Multiplication with scalar (double)\n * @param other - double to multiply with\n * @return Vector - self (result)\n **/\n Vector operator*=(const double& other)\n {\n cblas_dscal(N, other, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading /= operator\n * Division with scalar (double) - if zero ignores division (returns self)\n * @param other - double to divide with\n * @return Vector - self (result)\n **/\n Vector operator/=(const double& other)\n {\n if(std::abs(other) < std::numeric_limits::epsilon())\n return (*this);\n cblas_dscal(N, 1.0/other, &values_[0], 1);\n return *this;\n }\n\n /**\n * Overloading + operator\n * Addition of 2 Vectors\n * @return Vector - the result of the addition\n **/\n Vector operator+(const Vector& lh) const\n {\n Vector t = (*this);\n t += lh;\n return t;\n }\n\n /**\n * Overloading - operator\n * Subtraction of 2 Vectors\n * @return Vector - the result of the subtraction\n **/\n Vector operator-(const Vector& lh) const\n {\n Vector t = (*this);\n t -= lh;\n return t;\n }\n\n /**\n * Overloading * operator\n * Multiplication of 2 Vectors (Dot product)\n * @return double - the result of the multiplication\n **/\n double operator*(const Vector& lh) const\n {\n double s = 0.0;\n for(unsigned int i=0;i::epsilon());\n }\n\n /**\n * Overloading != operator\n * @param other - Vector to compare\n * @return bool\n **/\n bool operator!=(const Vector& other) const\n {\n Vector tmp = (*this)-other;\n return (tmp.lengthSq()>=std::numeric_limits::epsilon());\n }\n\n // !-- THIS NEEDS TO BE REMOVED --! //\n /**\n * Get pointer to values array\n * @return pointer to array\n **/\n double* data()\n {\n return values_;\n }\n\n /**\n * Get Length of Vector\n * @return double - length\n **/\n double length() const\n {\n return cblas_dnrm2(N, &values_[0], 1);\n }\n\n /**\n * Set vector to 1s\n **/\n void ones()\n {\n memset(&values_[0], 1, N*sizeof(double));\n }\n\n\n /**\n * Get LengthSq of Vector\n * @return double - length squared\n **/\n double lengthSq() const\n {\n double s = cblas_dnrm2(N, &values_[0], 1);\n return s*s;\n }\n\n\n /**\n * Normalize Vector\n **/\n void normalize()\n {\n double l = length();\n if(l>std::numeric_limits::epsilon())\n *this /= l;\n }\n\n /**\n * Normalized Vector\n **/\n Vector normalized()\n {\n Vector tmp = Vector(*this);\n tmp.normalize();\n return tmp;\n }\n\n /**\n * Overloading () operator\n * Access Vector Matlab-like\n * @param i - index to return\n * @return double - value of i-th element\n **/\n double& operator()(int i) //needs assert legal index\n {\n return values_[i];\n }\n\n /**\n * Overloading () operator - const version\n * Access Vector Matlab-like\n * @param i - index to return\n * @return double - value of i-th element\n **/\n double operator()(int i) const //needs assert legal index\n {\n return values_[i];\n }\n\n /**\n * Overloading [] operator\n * Access Vector Array-like\n * @param i - index to return\n * @return double - value of i-th element\n **/\n double& operator[](int i) //assert legal index\n {\n return values_[i];\n }\n\n /**\n * Overloading [] operator - const version\n * Access Vector Array-like\n * @param i - index to return\n * @return double - value of i-th element\n **/\n double operator[](int i) const //assert legal index\n {\n return values_[i];\n }\n\n /**\n * Get ith unit vector with size N\n * @param i\n * @return Vector - unit vector\n **/\n static Vector e(const unsigned int& i)\n {\n Vector k;\n k[i] = 1;\n return k;\n }\n\n /**\n * Destructor\n **/\n ~Vector(void)\n {\n }\n\n template\n friend class Matrix;\n};\n\n/**\n* Cross Product\n* Applies only to 3D Vectors\n* @return Vector - the result of the cross product\n**/\ninline Vector<3> cross(const Vector<3>& rh, const Vector<3>& lh)\n{\n return Vector<3>(rh[1]*lh[2]-rh[2]*lh[1], rh[2]*lh[0]-rh[0]*lh[2], rh[0]*lh[1]-rh[1]*lh[0]);\n}\n\n/**\n* Projection of a to e\n* @return Vector - the result of the cross product\n**/\ntemplate \nVector projection(const Vector& a, const Vector& e)\n{\n return ((e*a)*e/(e*e));\n}\n\n/**\n* Overloading << operator\n* \"print\" vector to stream\n* @param ostream - stream to print the vector to\n* @param Vector - vector to print\n**/\ntemplate \nstd::ostream& operator<<(std::ostream& os, const Vector& obj)\n{\n for(unsigned int i=0;i> operator\n* read vector from stream\n* @param istream - stream to read the vector from\n* @param Vector - vector to read\n**/\ntemplate \nstd::istream& operator>>(std::istream& in, Vector& obj)\n{\n for(unsigned int i=0;i>obj[i];\n return in;\n}\n\n/**\n* Overloading / operator\n* Division with scalar (double)\n* Perform Vector / scalar (as opposed to Vector / scalar inside Class)\n**/\ntemplate \nVector operator/(const double& a, const Vector& b)\n{\n if(std::abs(a) < std::numeric_limits::epsilon())\n return Vector();\n Vector tmp = Vector(b);\n for(unsigned int i=0;i::epsilon())\n return b;\n tmp[i] = a/tmp[i];\n }\n return tmp;\n}\n\n/**\n* Overloading * operator\n* Multiplication with scalar (double)\n* Perform scalar * Vector (as opposed to Vector * scalar inside Class)\n**/\ntemplate \nVector operator*(const double& a, const Vector& b)\n{\n return b*a;\n}\n\n/**\n* Typedefs for frequently used types\n**/\ntypedef Vector<2> Vector2;\ntypedef Vector<3> Vector3;\ntypedef Vector<4> Vector4;\n\n} }\n\n#endif\n", "meta": {"hexsha": "32a8c2fe2c9eb0ac0cbdfa3c184c810b6e758784", "size": 12582, "ext": "h", "lang": "C", "max_stars_repo_path": "include/geometric_tools/Math/Vector.h", "max_stars_repo_name": "costashatz/GeometricTools", "max_stars_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T11:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T06:44:13.000Z", "max_issues_repo_path": "include/geometric_tools/Math/Vector.h", "max_issues_repo_name": "costashatz/GeometricTools", "max_issues_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f", "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/geometric_tools/Math/Vector.h", "max_forks_repo_name": "costashatz/GeometricTools", "max_forks_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-15T00:32:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-28T02:34:33.000Z", "avg_line_length": 24.1034482759, "max_line_length": 142, "alphanum_fraction": 0.5956127802, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6120149821628157}} {"text": "/* **************************************** *\n *\t\tODE integration functions\t\t\t*\n *\tProvides GSL ode integrator and\t\t\t*\n *\ta simple euler integrator\t\t\t\t*\n * **************************************** */\n\n\n#include \"canonical.h\"\n#include \n#include \n#include \n#define DIM 2\n#define NPTS 100.0 // number of points to print out, best as double notation\n\n\n\n\n/* Many good algorithms don't need the Jacobian, so we'll just pass a null pointer */\ndouble *jac = NULL;\n\nvoid\ngslode(void *params, double MAX_TIME, FILE *theory)\n{\n\tPAR pars = *(PAR *)params;\n\n\t/* Create our ODE system */\n\tgsl_odeiv_system sys = {func, jac, DIM, params};\n\n\t/* Range of time to simulate*/\n\tdouble t = 0.0, t1 = MAX_TIME;\n\t/* Initial step size, will be modified as needed by adaptive alogorithm */\n\tdouble h = 1e-6;\n\t/* initial conditions */\n\tdouble y[DIM] = { pars.Xo, 0.0 };\n\n\n\t/* Define method as Embedded Runge-Kutta Prince-Dormand (8,9) method */\n\tconst gsl_odeiv_step_type * T\n\t = gsl_odeiv_step_rk4;\n//\t = gsl_odeiv_step_rk8pd;\n\t/* allocate stepper for our method of correct dimension*/\n\tgsl_odeiv_step * s\n\t = gsl_odeiv_step_alloc (T, DIM);\n\t/* control will maintain absolute and relative error */\n\tgsl_odeiv_control * c\n\t = gsl_odeiv_control_y_new (1e-6, 0.0);\n\t/* allocate the evolver */\n\tgsl_odeiv_evolve * e\n\t = gsl_odeiv_evolve_alloc (DIM);\n\n\t/*dummy to make easy to switch to regular printing */\n\tdouble ti = t1;\n\tint i;\n\n\t/* Uncomment the outer for loop to print *\n\t * 100 sample pts at regular intervals */\n\tfor (i = 1; i <= NPTS; i++){ ti = i * t1 / NPTS;\n\t\twhile (t < ti)\n\t\t{\n\t\t\tint status = gsl_odeiv_evolve_apply (e, c, s,\n\t\t\t\t\t\t\t\t\t\t\t\t&sys,\n\t\t\t\t\t\t\t\t\t\t\t\t&t, t1,\n\t\t\t\t\t\t\t\t\t\t\t\t&h, y);\n\t\t\tif (status != GSL_SUCCESS)\n\t\t\t break;\n//\t\t\tfprintf(theory,\"%.6e %.6e %.6e\\n\",t,y[0],y[1]); //adaptive mesh\n\t\t}\n\t\tfprintf(theory,\"%.6e %.6e %.6e\\n\",t,y[0],y[1]); }\n\n\tgsl_odeiv_evolve_free (e);\n\tgsl_odeiv_control_free (c);\n\tgsl_odeiv_step_free (s);\n}\n\n\nvoid euler(void *params, double MAX_TIME, FILE *theory){\n\tPAR pars = *(PAR *)params;\n\n\tdouble dt = .01;\n\tint sample;\n\n\tdouble y[DIM] = { pars.Xo, 0.0 };\n\tdouble f[DIM];\n\tdouble t=0.0;\n\n\tfor(sample = 0; sample < MAX_TIME/dt; sample++){\n\n\t\tif( sample % (int) (1/dt) == 0)\n\t\t{\n\t\t\tfprintf\n\t\t\t(\n\t\t\t\ttheory, \"%.6e %.6e %.6e\\n\",\n\t\t\t\tdt*sample,\n\t\t\t\ty[0],\n\t\t\t\ty[1]\n\t\t\t);\n\t\t}\n\t\tint status = func(t, y, f, &pars);\n\t\tif(status != GSL_SUCCESS)\n\t\t\tbreak;\n\t\ty[0] = y[0] + dt*f[0];\n\t\ty[1] = y[1] + dt*f[1];\n\t}\n\n}\n", "meta": {"hexsha": "8e34b44536ecdaba2771e31fe0068983a043a26e", "size": 2478, "ext": "c", "lang": "C", "max_stars_repo_path": "src/odeintegrators.c", "max_stars_repo_name": "cboettig/fluctuationDomains", "max_stars_repo_head_hexsha": "e547c62fd9ae8361d601302200bbc90b26299007", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/odeintegrators.c", "max_issues_repo_name": "cboettig/fluctuationDomains", "max_issues_repo_head_hexsha": "e547c62fd9ae8361d601302200bbc90b26299007", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-18T20:44:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T20:55:31.000Z", "max_forks_repo_path": "src/odeintegrators.c", "max_forks_repo_name": "cboettig/fluctuationDomains", "max_forks_repo_head_hexsha": "e547c62fd9ae8361d601302200bbc90b26299007", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-11-09T18:14:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T07:21:19.000Z", "avg_line_length": 23.3773584906, "max_line_length": 85, "alphanum_fraction": 0.6004842615, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6119108779226473}} {"text": "#include \n#include \n\nint\nmain (void)\n{\n int i;\n /* coefficients of P(x) = -1 + x^5 */\n double a[6] = { -1, 0, 0, 0, 0, 1 }; \n double z[10];\n\n gsl_poly_complex_workspace * w \n = 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\", \n i, z[2*i], z[2*i+1]);\n }\n\n return 0;\n}\n", "meta": {"hexsha": "6debbd54b63a37bfdeb04ea0b0de0c8369fda1e6", "size": 465, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/polyroots.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/polyroots.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/polyroots.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": 17.2222222222, "max_line_length": 45, "alphanum_fraction": 0.5268817204, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6113057336685794}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#define max(A, B) ((A) > (B) ? (A) : (B))\n#define min(A, B) ((A) < (B) ? (A) : (B))\n\ndouble R0(double flock_size, double housing_period, double prob_dam_to_lamb, int maxage, double *params)\n{\n int n_age_classes = (maxage+1)*12;\n int c, a, i, y, t;\n int infectious_period, years_infectious, period_infectious_to_lambs;\n \n int latent_period = lrint(params[5]);\n double beta_field = params[0];\n double beta_housed = params[1];\n \n double p_mort, p_cull, sum, lambs_per_dam;\n double removal_rate[n_age_classes], infection_rate;\n double cohort_size_age_0;\n double cohort_size[maxage+1][n_age_classes];\n double infecteds[maxage+1][n_age_classes];\n double R0[n_age_classes][n_age_classes];\n\n // age-specific mortality and cull probabilities from Andrew's data\n double prob_mortality[] = {\n 0.01,\n 0.012,\n 0.027,\n 0.041,\n 0.019,\n 0.021,\n 0.034,\n };\n\n double prob_culled[] = {\n 0,\n 0.046,\n 0.065,\n 0.093,\n 0.134,\n 0.196,\n 0.295,\n };\n\n // create vector of removal rates of a cohort from ages 0 to n_age_classes\n for (a = 0; a < n_age_classes; a++) {\n p_mort = prob_mortality[a/12];\n p_cull = prob_culled[a/12];\n removal_rate[a] = -(log(1.-p_mort)+log(1.-p_cull))/12.;\n }\n\n // these two ways are equivalent\n // create vector of infection rates within a year starting in April\n infection_rate = ((12-housing_period)*beta_field+housing_period*beta_housed)/12.;\n // for (a = 0; a < 12; a++)\n // if (a < 12-housing_period)\n // infection_rate[a] = beta_field;\n // else\n // infection_rate[a] = beta_housed;\n\n // find intial cohort size in a non-infected flock\n // take initial cohort size as 1\n // find size of cohort as it ages\n cohort_size[0][0] = 1;\n for (a = 1; a < n_age_classes; a++)\n cohort_size[0][a] = cohort_size[0][a-1]*exp(-removal_rate[a]);\n // sum size of all existent cohorts in April\n sum = 0;\n for (y = 0; y <= maxage; y++)\n sum += cohort_size[0][12*y];\n cohort_size_age_0 = flock_size/sum;\n\n // for cohorts of y years old at first exposure\n // assuming that the infectious ewe is starts to be infectious in April - but\n // this is not necessary, just convenient\n for (y = 0; y <= maxage; y++) {\n // cohort size at age 0\n cohort_size[y][0] = cohort_size_age_0;\n\n // just removal for first y years before exposure\n for (a = 1; a < 12*y; a++)\n cohort_size[y][a] = cohort_size[y][a-1]*exp(-removal_rate[a]);\n // then removal and infection for rest of lifespan\n for (; a < n_age_classes; a++)\n cohort_size[y][a] = cohort_size[y][a-1]*exp(-removal_rate[a]-infection_rate);\n\n // calculate number of infecteds\n infecteds[y][0] = 0;\n for (a = 1; a < n_age_classes; a++)\n infecteds[y][a] = infection_rate/(removal_rate[a]+infection_rate)*(cohort_size[y][a-1]-cohort_size[y][a]);\n }\n\n // set matrix elements to zero\n for (a = 0; a < n_age_classes; a++)\n for (i = 0; i < n_age_classes; i++)\n R0[a][i] = 0;\n\n // for a ewe infected at age a, sum the number of ewes it infects of age i\n for (a = 0; a < n_age_classes; a++) {\n infectious_period = max(0, n_age_classes-a-latent_period);\n for (t = 0; t < infectious_period; t++) {\n // for all cohorts from past to future \n for (y = maxage; y >= -maxage; y--) {\n // get cohort\n // +ve y are cohorts in the past\n // -ve y are future cohorts (identical to cohort 0)\n c = max(0, y);\n // age of cohort y at time t\n i = 12*y+t;\n if (0 <= i && i < n_age_classes)\n R0[a][i] += infecteds[c][i];\n }\n }\n }\n\n // contribution of vertical transmission to an infectious ewe's lambs\n lambs_per_dam = cohort_size_age_0/(flock_size-cohort_size_age_0);\n\n for (a = 0; a < n_age_classes; a++) {\n // a ewe infected at age a is infectious for max_age-a-1-latent_period months\n infectious_period = max(0, n_age_classes-a-latent_period);\n if (a < 24)\n // only 2 year olds and older give birth\n // so ewes infectious before 24 months cannot infect their lambs \n // until they are 2 years old\n period_infectious_to_lambs = max(0, n_age_classes-24-latent_period);\n else\n period_infectious_to_lambs = infectious_period;\n years_infectious = period_infectious_to_lambs/12;\n R0[a][0] += lambs_per_dam*prob_dam_to_lamb*years_infectious;\n }\n\n gsl_matrix *A = gsl_matrix_alloc(n_age_classes, n_age_classes);\n gsl_vector_complex *v = gsl_vector_complex_alloc(n_age_classes);\n gsl_eigen_nonsymm_workspace *w = gsl_eigen_nonsymm_alloc(n_age_classes);\n for (a = 0; a < n_age_classes; a++)\n for (i = 0; i < n_age_classes; i++)\n gsl_matrix_set(A, a, i, R0[a][i]);\n gsl_eigen_nonsymm(A, v, w);\n double max_eigenvalue = 0, e;\n for (a = 0; a < n_age_classes; a++) {\n e = GSL_REAL(gsl_vector_complex_get(v, a));\n if (e > max_eigenvalue)\n max_eigenvalue = e;\n }\n gsl_eigen_nonsymm_free(w);\n gsl_vector_complex_free(v);\n gsl_matrix_free(A);\n\n return max_eigenvalue;\n}\n", "meta": {"hexsha": "c84bcfae05a9361835b6d635f629eb705f559f92", "size": 5568, "ext": "c", "lang": "C", "max_stars_repo_path": "Peterson/R0.c", "max_stars_repo_name": "nicksavill/maedi-visna-epidemiology", "max_stars_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_stars_repo_licenses": ["CC-BY-4.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": "Peterson/R0.c", "max_issues_repo_name": "nicksavill/maedi-visna-epidemiology", "max_issues_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_issues_repo_licenses": ["CC-BY-4.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": "Peterson/R0.c", "max_forks_repo_name": "nicksavill/maedi-visna-epidemiology", "max_forks_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9225806452, "max_line_length": 118, "alphanum_fraction": 0.5926724138, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.611280604271339}} {"text": "/* multifit/covar.c\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#include \n#include \n#include \n#include \n#include \n#include \n\n/* Compute the covariance matrix\n\n cov = inv (J^T J)\n\n by QRP^T decomposition of J\n*/\n\nint\ngsl_multifit_covar (const gsl_matrix * J, double epsrel, gsl_matrix * covar)\n{\n double tolr;\n\n size_t i, j, k;\n size_t kmax = 0;\n\n gsl_matrix * r;\n gsl_vector * tau;\n gsl_vector * norm;\n gsl_permutation * perm;\n\n size_t m = J->size1, n = J->size2 ;\n \n if (m < n) \n {\n GSL_ERROR (\"Jacobian be rectangular M x N with M >= N\", GSL_EBADLEN);\n }\n\n if (covar->size1 != covar->size2 || covar->size1 != n)\n {\n GSL_ERROR (\"covariance matrix must be square and match second dimension of jacobian\", GSL_EBADLEN);\n }\n\n r = gsl_matrix_alloc (m, n);\n tau = gsl_vector_alloc (n);\n perm = gsl_permutation_alloc (n) ;\n norm = gsl_vector_alloc (n) ;\n \n {\n int signum = 0;\n gsl_matrix_memcpy (r, J);\n gsl_linalg_QRPT_decomp (r, tau, perm, &signum, norm);\n }\n \n \n /* Form the inverse of R in the full upper triangle of R */\n\n tolr = epsrel * fabs(gsl_matrix_get(r, 0, 0));\n\n for (k = 0 ; k < n ; k++)\n {\n double rkk = gsl_matrix_get(r, k, k);\n\n if (fabs(rkk) <= tolr)\n {\n break;\n }\n\n gsl_matrix_set(r, k, k, 1.0/rkk);\n\n for (j = 0; j < k ; j++)\n {\n double t = gsl_matrix_get(r, j, k) / rkk;\n gsl_matrix_set (r, j, k, 0.0);\n\n for (i = 0; i <= j; i++)\n {\n double rik = gsl_matrix_get (r, i, k);\n double rij = gsl_matrix_get (r, i, j);\n \n gsl_matrix_set (r, i, k, rik - t * rij);\n }\n }\n kmax = k;\n }\n\n /* Form the full upper triangle of the inverse of R^T R in the full\n upper triangle of R */\n\n for (k = 0; k <= kmax ; k++)\n {\n for (j = 0; j < k; j++)\n {\n double rjk = gsl_matrix_get (r, j, k);\n\n for (i = 0; i <= j ; i++)\n {\n double rij = gsl_matrix_get (r, i, j);\n double rik = gsl_matrix_get (r, i, k);\n\n gsl_matrix_set (r, i, j, rij + rjk * rik);\n }\n }\n \n {\n double t = gsl_matrix_get (r, k, k);\n\n for (i = 0; i <= k; i++)\n {\n double rik = gsl_matrix_get (r, i, k);\n\n gsl_matrix_set (r, i, k, t * rik);\n };\n }\n }\n\n /* Form the full lower triangle of the covariance matrix in the\n strict lower triangle of R and in w */\n\n for (j = 0 ; j < n ; j++)\n {\n size_t pj = gsl_permutation_get (perm, j);\n \n for (i = 0; i <= j; i++)\n {\n size_t pi = gsl_permutation_get (perm, i);\n\n double rij;\n\n if (j > kmax)\n {\n gsl_matrix_set (r, i, j, 0.0);\n rij = 0.0 ;\n }\n else \n {\n rij = gsl_matrix_get (r, i, j);\n }\n\n if (pi > pj)\n {\n gsl_matrix_set (r, pi, pj, rij); \n } \n else if (pi < pj)\n {\n gsl_matrix_set (r, pj, pi, rij);\n }\n\n }\n \n { \n double rjj = gsl_matrix_get (r, j, j);\n gsl_matrix_set (covar, pj, pj, rjj);\n }\n }\n\n \n /* symmetrize the covariance matrix */\n\n for (j = 0 ; j < n ; j++)\n {\n for (i = 0; i < j ; i++)\n {\n double rji = gsl_matrix_get (r, j, i);\n\n gsl_matrix_set (covar, j, i, rji);\n gsl_matrix_set (covar, i, j, rji);\n }\n }\n\n gsl_matrix_free (r);\n gsl_permutation_free (perm);\n gsl_vector_free (tau);\n gsl_vector_free (norm);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "36591406a2a9b29ffdde49f20e271182bd93597a", "size": 4566, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/multifit/covar.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/covar.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/multifit/covar.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.6580310881, "max_line_length": 105, "alphanum_fraction": 0.5249671485, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6106621974035795}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic PyObject* g_engineError;\nstatic gsl_rng* g_rng;\n\n/** low level helpers **/\n\n/** numpy helpers **/\n\n/**\n * Check that PyArrayObject is a double (Float) type and a vector\n * \treturn 1 if an error and raise exception.\n */\nstatic int not_doublevector(PyArrayObject *vec) {\n\tif (vec->descr->type_num != NPY_DOUBLE || vec->nd != 1) {\n\t\tPyErr_SetString(PyExc_ValueError,\n\t\t\t\"In not_doublevector: array must be of type Float and 1 dimensional (n).\");\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nstatic double lognormal(double m, double stddev) {\n/*\nm: mean of x\nstddev: std of x\n*/\n\treturn gsl_ran_lognormal(g_rng,\n\t\t\tlog(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m)),\n\t\t\tsqrt(log((stddev*stddev)/(m*m) + 1)) );\n}\n\n/** python callables **/\n\nstatic PyObject* engine_bivariate_gaussian(PyObject *self, PyObject *args) {\n\tfloat sx, sy;\n\tif (!PyArg_ParseTuple(args, \"ff\", &sx, &sy))\n return NULL;\n\tdouble x, y;\n\tgsl_ran_bivariate_gaussian(g_rng, sx, sy, 0.0, &x, &y);\n\treturn Py_BuildValue(\"(ff)\", (float)x, (float)y);\n}\n\nstatic PyObject* engine_beta(PyObject *self, PyObject *args) {\n\tfloat a = 0;\n\tfloat b = 0;\n\tif (!PyArg_ParseTuple(args, \"ff\", &a, &b))\n return NULL;\n\tdouble sample = (float)gsl_ran_beta(g_rng, a, b);\n\treturn Py_BuildValue(\"f\", (float)sample);\n}\n\nstatic PyObject* engine_lognormal(PyObject *self, PyObject *args) {\n\tfloat m = 0;\n\tfloat stddev = 0;\n\tif (!PyArg_ParseTuple(args, \"ff\", &m, &stddev))\n return NULL;\n\treturn Py_BuildValue(\"f\", (float)lognormal(m, stddev));\n}\t\n\nstatic PyObject* engine_lognormal_cdf(PyObject *self, PyObject *args) {\n\tfloat m = 0;\n\tfloat stddev = 0;\n\tfloat x = 0;\n\tif (!PyArg_ParseTuple(args, \"fff\", &x, &m, &stddev))\n return NULL;\n\tdouble m2 = log(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m));\n\tdouble s2 = sqrt(log((stddev*stddev)/(m*m) + 1));\n\treturn Py_BuildValue(\"f\", (float)gsl_cdf_lognormal_P(x, m2, s2));\n}\n\nstatic PyObject* engine_lognormal_cdf_inv(PyObject *self, PyObject *args) {\n\tfloat m = 0;\n\tfloat stddev = 0;\n\tfloat p = 0;\n\tif (!PyArg_ParseTuple(args, \"fff\", &p, &m, &stddev))\n\t\treturn NULL;\n\tdouble m2 = log(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m));\n\tdouble s2 = sqrt(log((stddev*stddev)/(m*m) + 1));\n\treturn Py_BuildValue(\"f\", (float)gsl_cdf_lognormal_Pinv(p, m2, s2));\n}\n\nstatic PyObject* engine_percentileofscore(PyObject *self, PyObject *args) {\n\t// python: engine.percentileofscore([scores], score)\n\tdouble score = 0;\n\tPyObject* listObj;\n\tif (!PyArg_ParseTuple(args, \"O!d\", &PyList_Type, &listObj, &score))\n return NULL;\n\t\n\t// loop through python list of doubles, counting scores less than or equal to score\n\tint arrsz = PyList_Size(listObj);\n\tif (arrsz == 0)\n\t\treturn NULL;\n\tint i;\n\tint count=0;\n\tfor (i=0; idata;\n\tint arrsz = arrayObj->dimensions[0];\n\tif (arrsz == 0)\n\t\treturn NULL;\n\tint i;\n\tint count=0;\n\tfor (i=0; i\n#include \n#include \n#include \n#include \n\n/*-*-*-*-*-*-*-*-*-*-*-* Allocators *-*-*-*-*-*-*-*-*-*-*-*/\n\ngsl_cheb_series * \ngsl_cheb_alloc(const size_t order)\n{\n gsl_cheb_series * cs = (gsl_cheb_series *) malloc(sizeof(gsl_cheb_series));\n \n if(cs == 0) {\n GSL_ERROR_VAL(\"failed to allocate gsl_cheb_series struct\", GSL_ENOMEM, 0);\n }\n \n cs->order = order;\n cs->order_sp = order;\n\n cs->c = (double *) malloc((order+1) * sizeof(double));\n\n if(cs->c == 0) {\n GSL_ERROR_VAL(\"failed to allocate cheb coefficients\", GSL_ENOMEM, 0);\n }\n\n cs->f = (double *) malloc((order+1) * sizeof(double));\n\n if(cs->f == 0) {\n GSL_ERROR_VAL(\"failed to allocate cheb function space\", GSL_ENOMEM, 0);\n }\n\n return cs;\n}\n\n\nvoid gsl_cheb_free(gsl_cheb_series * cs)\n{\n RETURN_IF_NULL (cs);\n free(cs->f);\n free(cs->c);\n free(cs);\n}\n\n/*-*-*-*-*-*-*-*-*-*-*-* Initializer *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_cheb_init(gsl_cheb_series * cs, const gsl_function *func,\n const double a, const double b)\n{\n size_t k, j;\n\n if(a >= b) {\n GSL_ERROR_VAL(\"null function interval [a,b]\", GSL_EDOM, 0);\n }\n cs->a = a;\n cs->b = b;\n /* cs->err = 0.0; */\n\n { \n double bma = 0.5 * (cs->b - cs->a);\n double bpa = 0.5 * (cs->b + cs->a);\n double fac = 2.0/(cs->order +1.0);\n\n for(k = 0; k<=cs->order; k++) {\n double y = cos(M_PI * (k+0.5)/(cs->order+1));\n cs->f[k] = GSL_FN_EVAL(func, (y*bma + bpa));\n }\n \n for(j = 0; j<=cs->order; j++) {\n double sum = 0.0;\n for(k = 0; k<=cs->order; k++) \n sum += cs->f[k]*cos(M_PI * j*(k+0.5)/(cs->order+1));\n cs->c[j] = fac * sum;\n }\n \n }\n return GSL_SUCCESS;\n}\n\nsize_t\ngsl_cheb_order (const gsl_cheb_series * cs)\n{\n return cs->order;\n}\n\nsize_t\ngsl_cheb_size (const gsl_cheb_series * cs)\n{\n return (cs->order + 1);\n}\n\ndouble *\ngsl_cheb_coeffs (const gsl_cheb_series * cs)\n{\n return cs->c;\n}\n\n", "meta": {"hexsha": "a923377d5dc5e1af96da0eadf46937586feb11be", "size": 2823, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/cheb/init.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/cheb/init.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/cheb/init.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.9237288136, "max_line_length": 81, "alphanum_fraction": 0.6089266738, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6104711689703279}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cosmocalc.h\"\n\n#define ODEGROWTH //the integral formulation is onyl correct for LCDM, any wCDM cosmology will not work\n\n#ifdef ODEGROWTH\n\n#define LNAINITGROWTH (log(AEXPN_MIN_GROWTH))\n#define ABSERR 1e-8\n#define RELERR 1e-8\n#define HSTART 1e-4\n#define ODE_TYPE gsl_odeiv2_step_rk8pd\n\nstatic int growth_ode_sys_w0wa(double t, const double y[], double dydt[], void *params);\n\n//ODE for growth from Komatsu et al. 2009, ApJS, 180, 330 (WMAP5 paper)\nstatic int growth_ode_sys_w0wa(double t, const double y[], double dydt[], void *params)\n{\n double a = exp(t); //t = log(a)\n double weffa = weff(a);\n double ha = hubble_noscale(a);\n double omegaDEa = cosmoData.OmegaL/ha/ha/pow(a,3.0*(1.0 + weffa));\n double omegaKa = cosmoData.OmegaK/a/a/ha/ha;\n \n dydt[0] = y[1];\n dydt[1] = (1.5*weffa*omegaDEa - 0.5*omegaKa - 2.5)*y[1] - (2.0*omegaKa + 1.5*(1.0 - weffa)*omegaDEa)*y[0]; \n\n return GSL_SUCCESS;\n}\n\ndouble growth_function_exact(double a)\n{\n gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};\n gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);\n \n double lna_init;\n double lna_final,y[2];\n double ga,gnorm;\n int status;\n \n //do g(a) unormalized\n y[0] = 1.0;\n y[1] = 0.0;\n lna_init = LNAINITGROWTH;\n lna_final = log(a);\n \n status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);\n ga = y[0]*a;\n if(status != GSL_SUCCESS)\n {\n fprintf(stderr,\"error in integrating growth function! a = %lf\\n\",a);\n assert(status == GSL_SUCCESS);\n }\n\n //do g(a = 1.0) to get normalization\n y[0] = 1.0;\n y[1] = 0.0;\n lna_init = LNAINITGROWTH;\n lna_final = 0.0;\n \n status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);\n gnorm = y[0];\n if(status != GSL_SUCCESS)\n {\n fprintf(stderr,\"error in integrating growth function! a = %lf\\n\",a);\n assert(status == GSL_SUCCESS);\n }\n \n gsl_odeiv2_driver_free(d);\n \n return ga/gnorm;\n}\n\ndouble growth_function_exact_nonorm(double a)\n{\n gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};\n gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);\n \n double lna_init;\n double lna_final,y[2];\n double ga;\n int status;\n \n //do g(a) unormalized\n y[0] = 1.0;\n y[1] = 0.0;\n lna_init = LNAINITGROWTH;\n lna_final = log(a);\n \n status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);\n ga = y[0]*a;\n if(status != GSL_SUCCESS)\n {\n fprintf(stderr,\"error in integrating growth function! a = %lf\\n\",a);\n assert(status == GSL_SUCCESS);\n }\n\n return ga;\n}\n\ndouble growth_function(double a)\n{\n static int initFlag = 1;\n static int currCosmoNum;\n static double growth_function_norm;\n static gsl_spline *cosmocalc_growth_function_spline = NULL;\n static gsl_interp_accel *cosmocalc_growth_function_acc = NULL;\n \n double growth_function_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];\n double a_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];\n long i;\n \n gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};\n gsl_odeiv2_driver *d;\n double afact,lna_init;\n double lna_final,y[2];\n int status;\n \n if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)\n {\n initFlag = 0;\n currCosmoNum = cosmoData.cosmoNum;\n \n //init ODE integrator\n d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);\n \n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n\n#define TINY 1.0e-12\n\nusing namespace std;\n\nenum SITE_LABEL { A, B, N_SITE };\nenum QUADRATURE { REAL, IMAG };\ntypedef struct {\n double Omegaa;// frequency of A site (rad/s)\n double Omegab;// frequency of B site (rad/s)\n double kab;\t// reaction rate constant, A -> B (1/s)\n double kba;\t// reaction rate constant, B -> A (1/s)\n double R20a;\t// transverse relaxation rate of A site (1/s)\n double R20b;\t// transverse relaxation rate of B site\t(1/s)\n double M0a;\t// initial magnetization\n double M0b;\t// initial magnetization\n SITE_LABEL site;\t// A or B\n QUADRATURE quad;\t// REAL or IMAG\n } two_site_exchange;\n\n//\n// Magnetization (two-site exchange)\n//\n\nvoid N (double t, double &R, double &I, void * params) {\n two_site_exchange * x = (two_site_exchange *) params;\n complex c1,c2,c3,lp,lm,a11,a12,a21,a22;\n complex Omegaa = sqrt(complex(-1.))*x->Omegaa;\n complex Omegab = sqrt(complex(-1.))*x->Omegab;\n double mag;\n c1 = (-Omegaa - Omegab + x->R20a + x->R20b + x->kab + x->kba);\n c2 = (-Omegaa + Omegab + x->R20a - x->R20b + x->kab - x->kba);\n c3 = sqrt(c2*c2+4.*x->kab*x->kba);\n lp = 0.5*(c1+c3);\n lm = 0.5*(c1-c3);\n if (x->site == A) {\n a11 = 0.5*((1.-c2/c3)*exp(-t*lm)+(1.+c2/c3)*exp(-t*lp)); \n a12 = x->kba/c3*(exp(-t*lm)-exp(-t*lp));\n R += real(a11*x->M0a+a12*x->M0b);\n I += imag(a11*x->M0a+a12*x->M0b);\n } \n if (x->site == B) {\n a22 = 0.5*((1.+c2/c3)*exp(-t*lm)+(1.-c2/c3)*exp(-t*lp)); \n a21 = x->kab/c3*(exp(-t*lm)-exp(-t*lp));\n R += real(a21*x->M0a+a22*x->M0b);\n I += imag(a21*x->M0a+a22*x->M0b);\n }\n}\n\nint main (int argc, char *argv[])\n{\n\n if (argc < 7 || argc > 17) {\n printf(\"\\t\\t\\t\\t\\t\\t\\tSung-Hun Bae 2008.11\\n\");\n printf(\" \");\n printf(\"Usage: xpshape [-model AB|ACB]\\n\");\n printf(\" \");\n printf(\" [-dw #(Hz)] [-kab #(1/s)] [-kba #(1/s)]\\n\");\n printf(\" \");\n printf(\" [-R20a #(1/s)] [-R20b #(1/s)]\\n\");\n printf(\" \");\n printf(\" [-a0 conc(M)] [-c0 conc(M)]\\n\");\n printf(\" \");\n printf(\" [-swh Hz(600)] [-fid pts(8192)]\\n\\n\");\n printf(\" \");\n printf(\"simulate NMR peakshape for two-site chemical exchange\\n\\n\");\n printf(\" \");\n printf(\"-model,AB : A = B (dw,kab,kba,R20a,R20b required)\\n\");\n printf(\" \");\n printf(\" ACB : A + C = B (dw,kab,kba,R20a,R20b,a0,c0 required)\\n\");\n printf(\"\\n\");\n printf(\" \");\n printf(\"-dw, (A.frequency= -dw/2, B.frequency= +dw/2)\\n\");\n printf(\" \");\n printf(\"-R20a,(exchange-free R2 of A state)\\n\"); \n printf(\" \");\n printf(\"-R20b,(exchange-free R2 of B state)\\n\"); \n printf(\" \");\n printf(\"-kab, (rate constant of A->B)\\n\"); \n printf(\" \");\n printf(\"-kba, (rate constant of B->A)\\n\"); \n printf(\" \");\n printf(\"-a0, (initial concentration of A)\\n\"); \n printf(\" \");\n printf(\"-c0, (initial concentration of C)\\n\"); \n printf(\" \");\n printf(\"-swh, (spectrum = -swh/2 ... +swh/2)\\n\");\n printf(\" \");\n printf(\"-fid, (must be ...,1024,2048,4096,8192,16384,32768,65536,..)\\n\");\n printf(\"\\n\");\n \n exit (1);\n }\n\n // default settings\n\n double SWH = 600;\t\t // (Hz)\n unsigned int FID_SIZE = 8192;\t // (complex data points)\n\n\n // receiving parameters\n\n unsigned int i = 1;\n\n string model;\n double dw,R20a,R20b,kab,kba,concA0,concC0;\n bool dw_,R20a_,R20b_,kab_,kba_,concA0_,concC0_;\n double pb,Kd,concA,concB,concC,C,u,v;\n\n dw_ = R20a_ = R20b_ = kab_ = kba_ = concA0_ = concC0_ = false;\n\n while ((argc - i) > 0) {\n if ((argc-i) > 0 && !strcmp(argv[i],\"-model\")) {\n model = string(argv[++i]); \n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-dw\")) {\n dw = 2.*M_PI*atof(argv[++i]); // (Hz) -> (rad/s)\n dw_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-kab\")) {\n kab = atof(argv[++i]);\n kab_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-kba\")) {\n kba = atof(argv[++i]);\n kba_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-R20a\")) {\n R20a = atof(argv[++i]);\n R20a_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-R20b\")) {\n R20b = atof(argv[++i]);\n R20b_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-a0\")) {\n concA0 = atof(argv[++i]);\n concA0_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-c0\")) {\n concC0 = atof(argv[++i]);\n concC0_ = true;\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-swh\")) {\n SWH = atof(argv[++i]);\n i++;\n }\n if ((argc-i) > 0 && !strcmp(argv[i],\"-fid\")) {\n FID_SIZE = atoi(argv[++i]);\n i++;\n }\n }\n\n double fid[2*FID_SIZE];\t // complex points\n double dwell = 1./(SWH);\t // (sec)\n double norm = 1./sqrt(FID_SIZE); // scaling factor\n\n if (model == \"AB\" && dw_ && R20a_ && R20b_ && kab_ && kba_) {\n // dw, R20a, R20b, kab, kba\n Kd = kba/kab;\n pb = 1./(1.+Kd);\n C = 1.0;\n }\n else if (model == \"ACB\" && dw_ && R20a_ && R20b_ && kab_ && kba_ \n && concA0_ && concC0_) {\n // dw, R20a, R20b, kab(=kon), kba(=koff), concA0, concC0\n kab = (concC0 > TINY ? kab : 0.0);\n kba = (concC0 > TINY ? kba : 0.0);\n Kd = ((kab > TINY) && (kba > TINY) ? kba/kab : 0.0);\n u = 0.5*(concA0+concC0+Kd);\n v = (concC0 > TINY ? (u-sqrt(u*u-concA0*concC0)) : 0.0);\n concA = (v > TINY ? concA0-v : concA0);\n concB = (v > TINY ? v : 0.0);\n concC = (v > TINY ? concC0 - v : concC0);\n pb = (concC0 > TINY ? kab*concC/(kab*concC+kba) : 0.0);\n C = concC;\n }\n else {\n printf(\"error: missing parameter(s)\\n\");\n exit(1);\n }\n\n two_site_exchange x = {-dw/2.,dw/2.,kab*C,kba,R20a,R20b,(1.-pb),pb,A,REAL};\n\n // header information\n printf(\"# peak shape simulation \");\n if (model == \"AB\") printf(\"[A = B]\\n\");\n if (model == \"ACB\") printf(\"[A + C = B]\\n\");\n\n printf(\"# dw = %g (rad/s)\\n\", dw);\n printf(\"# kab = %g (1/s)\\n\",kab);\n printf(\"# kba = %g (1/s)\\n\",kba);\n printf(\"# R20a = %g (1/s)\\n\",R20a);\n printf(\"# R20b = %g (1/s)\\n\",R20b);\n if (model == \"AB\") {\n printf(\"# pb = %g\\n\", pb);\n }\n if (model == \"ACB\") {\n printf(\"# kon = %g (1/s)\\n\",kab);\n printf(\"# koff = %g (1/s)\\n\",kba);\n printf(\"# Kd = %g (M)\\n\",Kd);\n printf(\"# pb = %g\\n\",pb);\n printf(\"# [A]ini = %g (M)\\n\",concA0);\n printf(\"# [C]ini = %g (M)\\n\",concC0);\n printf(\"# [A] = %g (M)\\n\",concA);\n printf(\"# [C] = %g (M)\\n\",concC);\n printf(\"# [B] = %g (M)\\n\",concB);\n }\n printf(\"# FID = %d (complex points)\\n\",FID_SIZE);\n printf(\"# SWH = %g (Hz)\\n\",SWH);\n printf(\"# X-axis unit: (Hz)\\n\");\n \n // creating complex data points\n for (i = 0; i < FID_SIZE; i++) {\n fid[2*i] = fid[2*i+1] = 0.0;\n x.site = A;\n N (i*dwell, fid[2*i], fid[2*i+1], &x); // A\n x.site = B;\n N (i*dwell, fid[2*i], fid[2*i+1], &x); // B\n }\n\n // Fast Fourier Transform (FFT)\n gsl_fft_complex_radix2_forward (fid, 1, FID_SIZE);\n\n // spectrum \n for (i = FID_SIZE/2; i < FID_SIZE; i++)\n printf(\"%g %g\\n\",(-0.5*SWH + SWH*(i-FID_SIZE/2)/FID_SIZE),norm*fid[2*i]);\n for (i = 0; i <= FID_SIZE/2; i++)\n printf(\"%g %g\\n\",(-0.5*SWH + SWH*(i+FID_SIZE/2)/FID_SIZE),norm*fid[2*i]);\n printf(\"&\\n\");\n\n return 0;\n}\n\n/*\n\n For physical applications it is important to remember that the index \n appearing in the DFT does not correspond directly to a physical frequency.\n If the time-step of the DFT is \\Delta then the frequency-domain includes \n both positive and negative frequencies, ranging from -1/(2\\Delta) through \n 0 to +1/(2\\Delta). \n The positive frequencies are stored from the beginning of the array up to \n the middle, and the negative frequencies are stored backwards from the \n end of the array.\n \n index z x = FFT(z)\n \n 0 z(t = 0) x(f = 0)\n 1 z(t = 1) x(f = 1/(N Delta))\n 2 z(t = 2) x(f = 2/(N Delta))\n . ........ ..................\n N/2 z(t = N/2) x(f = +1/(2 Delta),\n -1/(2 Delta))\n . ........ ..................\n N-3 z(t = N-3) x(f = -3/(N Delta))\n N-2 z(t = N-2) x(f = -2/(N Delta))\n N-1 z(t = N-1) x(f = -1/(N Delta))\n\n*/\n", "meta": {"hexsha": "f4a10e7a572f01f42096669e5267b77501ec423f", "size": 8572, "ext": "c", "lang": "C", "max_stars_repo_path": "source/xpshape.c", "max_stars_repo_name": "sunghunbae/xpshape", "max_stars_repo_head_hexsha": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "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/xpshape.c", "max_issues_repo_name": "sunghunbae/xpshape", "max_issues_repo_head_hexsha": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "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/xpshape.c", "max_forks_repo_name": "sunghunbae/xpshape", "max_forks_repo_head_hexsha": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "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.2897526502, "max_line_length": 77, "alphanum_fraction": 0.4996500233, "num_tokens": 3206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.610376925616022}} {"text": "/* eigen/gsl_eigen.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007 Gerard Jungman, Brian Gough, Patrick Alken\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_EIGEN_H__\r\n#define __GSL_EIGEN_H__\r\n\r\n#if !defined( GSL_FUN )\r\n# if !defined( GSL_DLL )\r\n# define GSL_FUN extern\r\n# elif defined( BUILD_GSL_DLL )\r\n# define GSL_FUN extern __declspec(dllexport)\r\n# else\r\n# define GSL_FUN extern __declspec(dllimport)\r\n# endif\r\n#endif\r\n\r\n#include \r\n#include \r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct {\r\n size_t size;\r\n double * d;\r\n double * sd;\r\n} gsl_eigen_symm_workspace;\r\n\r\nGSL_FUN gsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_symm_free (gsl_eigen_symm_workspace * w);\r\nGSL_FUN int gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size;\r\n double * d;\r\n double * sd;\r\n double * gc;\r\n double * gs;\r\n} gsl_eigen_symmv_workspace;\r\n\r\nGSL_FUN gsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w);\r\nGSL_FUN int gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size;\r\n double * d;\r\n double * sd;\r\n double * tau;\r\n} gsl_eigen_herm_workspace;\r\n\r\nGSL_FUN gsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_herm_free (gsl_eigen_herm_workspace * w);\r\nGSL_FUN int gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval,\r\n gsl_eigen_herm_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size;\r\n double * d;\r\n double * sd;\r\n double * tau;\r\n double * gc;\r\n double * gs;\r\n} gsl_eigen_hermv_workspace;\r\n\r\nGSL_FUN gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w);\r\nGSL_FUN int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, \r\n gsl_matrix_complex * evec,\r\n gsl_eigen_hermv_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* matrix size */\r\n size_t max_iterations; /* max iterations since last eigenvalue found */\r\n size_t n_iter; /* number of iterations since last eigenvalue found */\r\n size_t n_evals; /* number of eigenvalues found so far */\r\n\r\n int compute_t; /* compute Schur form T = Z^t A Z */\r\n\r\n gsl_matrix *H; /* pointer to Hessenberg matrix */\r\n gsl_matrix *Z; /* pointer to Schur vector matrix */\r\n} gsl_eigen_francis_workspace;\r\n\r\nGSL_FUN gsl_eigen_francis_workspace * gsl_eigen_francis_alloc (void);\r\nGSL_FUN void gsl_eigen_francis_free (gsl_eigen_francis_workspace * w);\r\nGSL_FUN void gsl_eigen_francis_T (const int compute_t,\r\n gsl_eigen_francis_workspace * w);\r\nGSL_FUN int gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval,\r\n gsl_eigen_francis_workspace * w);\r\nGSL_FUN int gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval,\r\n gsl_matrix * Z,\r\n gsl_eigen_francis_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_vector *diag; /* diagonal matrix elements from balancing */\r\n gsl_vector *tau; /* Householder coefficients */\r\n gsl_matrix *Z; /* pointer to Z matrix */\r\n int do_balance; /* perform balancing transformation? */\r\n size_t n_evals; /* number of eigenvalues found */\r\n\r\n gsl_eigen_francis_workspace *francis_workspace_p;\r\n} gsl_eigen_nonsymm_workspace;\r\n\r\nGSL_FUN gsl_eigen_nonsymm_workspace * gsl_eigen_nonsymm_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w);\r\nGSL_FUN void gsl_eigen_nonsymm_params (const int compute_t, const int balance,\r\n gsl_eigen_nonsymm_workspace *w);\r\nGSL_FUN int gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,\r\n gsl_eigen_nonsymm_workspace * w);\r\nGSL_FUN int gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,\r\n gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_vector *work; /* scratch workspace */\r\n gsl_vector *work2; /* scratch workspace */\r\n gsl_vector *work3; /* scratch workspace */\r\n\r\n gsl_matrix *Z; /* pointer to Schur vectors */\r\n\r\n gsl_eigen_nonsymm_workspace *nonsymm_workspace_p;\r\n} gsl_eigen_nonsymmv_workspace;\r\n\r\nGSL_FUN gsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w);\r\nGSL_FUN void gsl_eigen_nonsymmv_params (const int balance,\r\n gsl_eigen_nonsymmv_workspace *w);\r\nGSL_FUN int gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,\r\n gsl_matrix_complex * evec,\r\n gsl_eigen_nonsymmv_workspace * w);\r\nGSL_FUN int gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,\r\n gsl_matrix_complex * evec, gsl_matrix * Z,\r\n gsl_eigen_nonsymmv_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_eigen_symm_workspace *symm_workspace_p;\r\n} gsl_eigen_gensymm_workspace;\r\n\r\nGSL_FUN gsl_eigen_gensymm_workspace * gsl_eigen_gensymm_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_gensymm_free (gsl_eigen_gensymm_workspace * w);\r\nGSL_FUN int gsl_eigen_gensymm (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector * eval, gsl_eigen_gensymm_workspace * w);\r\nGSL_FUN int gsl_eigen_gensymm_standardize (gsl_matrix * A, const gsl_matrix * B);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_eigen_symmv_workspace *symmv_workspace_p;\r\n} gsl_eigen_gensymmv_workspace;\r\n\r\nGSL_FUN gsl_eigen_gensymmv_workspace * gsl_eigen_gensymmv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_gensymmv_free (gsl_eigen_gensymmv_workspace * w);\r\nGSL_FUN int gsl_eigen_gensymmv (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector * eval, gsl_matrix * evec,\r\n gsl_eigen_gensymmv_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_eigen_herm_workspace *herm_workspace_p;\r\n} gsl_eigen_genherm_workspace;\r\n\r\nGSL_FUN gsl_eigen_genherm_workspace * gsl_eigen_genherm_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_genherm_free (gsl_eigen_genherm_workspace * w);\r\nGSL_FUN int gsl_eigen_genherm (gsl_matrix_complex * A, gsl_matrix_complex * B,\r\n gsl_vector * eval, gsl_eigen_genherm_workspace * w);\r\nGSL_FUN int gsl_eigen_genherm_standardize (gsl_matrix_complex * A,\r\n const gsl_matrix_complex * B);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_eigen_hermv_workspace *hermv_workspace_p;\r\n} gsl_eigen_genhermv_workspace;\r\n\r\nGSL_FUN gsl_eigen_genhermv_workspace * gsl_eigen_genhermv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_genhermv_free (gsl_eigen_genhermv_workspace * w);\r\nGSL_FUN int gsl_eigen_genhermv (gsl_matrix_complex * A, gsl_matrix_complex * B,\r\n gsl_vector * eval, gsl_matrix_complex * evec,\r\n gsl_eigen_genhermv_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n gsl_vector *work; /* scratch workspace */\r\n\r\n size_t n_evals; /* number of eigenvalues found */\r\n size_t max_iterations; /* maximum QZ iterations allowed */\r\n size_t n_iter; /* number of iterations since last eigenvalue found */\r\n double eshift; /* exceptional shift counter */\r\n\r\n int needtop; /* need to compute top index? */\r\n\r\n double atol; /* tolerance for splitting A matrix */\r\n double btol; /* tolerance for splitting B matrix */\r\n\r\n double ascale; /* scaling factor for shifts */\r\n double bscale; /* scaling factor for shifts */\r\n\r\n gsl_matrix *H; /* pointer to hessenberg matrix */\r\n gsl_matrix *R; /* pointer to upper triangular matrix */\r\n\r\n int compute_s; /* compute generalized Schur form S */\r\n int compute_t; /* compute generalized Schur form T */\r\n\r\n gsl_matrix *Q; /* pointer to left Schur vectors */\r\n gsl_matrix *Z; /* pointer to right Schur vectors */\r\n} gsl_eigen_gen_workspace;\r\n\r\nGSL_FUN gsl_eigen_gen_workspace * gsl_eigen_gen_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_gen_free (gsl_eigen_gen_workspace * w);\r\nGSL_FUN void gsl_eigen_gen_params (const int compute_s, const int compute_t,\r\n const int balance, gsl_eigen_gen_workspace * w);\r\nGSL_FUN int gsl_eigen_gen (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector_complex * alpha, gsl_vector * beta,\r\n gsl_eigen_gen_workspace * w);\r\nGSL_FUN int gsl_eigen_gen_QZ (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector_complex * alpha, gsl_vector * beta,\r\n gsl_matrix * Q, gsl_matrix * Z,\r\n gsl_eigen_gen_workspace * w);\r\n\r\ntypedef struct {\r\n size_t size; /* size of matrices */\r\n\r\n gsl_vector *work1; /* 1-norm of columns of A */\r\n gsl_vector *work2; /* 1-norm of columns of B */\r\n gsl_vector *work3; /* real part of eigenvector */\r\n gsl_vector *work4; /* imag part of eigenvector */\r\n gsl_vector *work5; /* real part of back-transformed eigenvector */\r\n gsl_vector *work6; /* imag part of back-transformed eigenvector */\r\n\r\n gsl_matrix *Q; /* pointer to left Schur vectors */\r\n gsl_matrix *Z; /* pointer to right Schur vectors */\r\n\r\n gsl_eigen_gen_workspace *gen_workspace_p;\r\n} gsl_eigen_genv_workspace;\r\n\r\nGSL_FUN gsl_eigen_genv_workspace * gsl_eigen_genv_alloc (const size_t n);\r\nGSL_FUN void gsl_eigen_genv_free (gsl_eigen_genv_workspace * w);\r\nGSL_FUN int gsl_eigen_genv (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector_complex * alpha, gsl_vector * beta,\r\n gsl_matrix_complex * evec,\r\n gsl_eigen_genv_workspace * w);\r\nGSL_FUN int gsl_eigen_genv_QZ (gsl_matrix * A, gsl_matrix * B,\r\n gsl_vector_complex * alpha, gsl_vector * beta,\r\n gsl_matrix_complex * evec,\r\n gsl_matrix * Q, gsl_matrix * Z,\r\n gsl_eigen_genv_workspace * w);\r\n\r\n\r\n\r\ntypedef enum {\r\n GSL_EIGEN_SORT_VAL_ASC,\r\n GSL_EIGEN_SORT_VAL_DESC,\r\n GSL_EIGEN_SORT_ABS_ASC,\r\n GSL_EIGEN_SORT_ABS_DESC\r\n}\r\ngsl_eigen_sort_t;\r\n\r\n/* Sort eigensystem results based on eigenvalues.\r\n * Sorts in order of increasing value or increasing\r\n * absolute value.\r\n *\r\n * exceptions: GSL_EBADLEN\r\n */\r\n\r\nGSL_FUN int gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec,\r\n gsl_eigen_sort_t sort_type);\r\n\r\nGSL_FUN int gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec,\r\n gsl_eigen_sort_t sort_type);\r\n\r\nGSL_FUN int gsl_eigen_nonsymmv_sort(gsl_vector_complex * eval,\r\n gsl_matrix_complex * evec,\r\n gsl_eigen_sort_t sort_type);\r\n\r\nGSL_FUN int gsl_eigen_gensymmv_sort (gsl_vector * eval, gsl_matrix * evec, \r\n gsl_eigen_sort_t sort_type);\r\n\r\nGSL_FUN int gsl_eigen_genhermv_sort (gsl_vector * eval, gsl_matrix_complex * evec, \r\n gsl_eigen_sort_t sort_type);\r\n\r\nGSL_FUN int gsl_eigen_genv_sort (gsl_vector_complex * alpha, gsl_vector * beta,\r\n gsl_matrix_complex * evec,\r\n gsl_eigen_sort_t sort_type);\r\n\r\n/* Prototypes for the schur module */\r\n\r\nGSL_FUN int gsl_schur_gen_eigvals(const gsl_matrix *A, const gsl_matrix *B,\r\n double *wr1, double *wr2, double *wi,\r\n double *scale1, double *scale2);\r\n\r\nGSL_FUN int gsl_schur_solve_equation(double ca, const gsl_matrix *A, double z,\r\n double d1, double d2, const gsl_vector *b,\r\n gsl_vector *x, double *s, double *xnorm,\r\n double smin);\r\n\r\nGSL_FUN int gsl_schur_solve_equation_z(double ca, const gsl_matrix *A,\r\n gsl_complex *z, double d1, double d2,\r\n const gsl_vector_complex *b,\r\n gsl_vector_complex *x, double *s,\r\n double *xnorm, double smin);\r\n\r\n\r\n/* The following functions are obsolete: */\r\n\r\n/* Eigensolve by Jacobi Method\r\n *\r\n * The data in the matrix input is destroyed.\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int\r\ngsl_eigen_jacobi(gsl_matrix * matrix,\r\n gsl_vector * eval,\r\n gsl_matrix * evec,\r\n unsigned int max_rot, \r\n unsigned int * nrot);\r\n\r\n\r\n/* Invert by Jacobi Method\r\n *\r\n * exceptions: \r\n */\r\nGSL_FUN int\r\ngsl_eigen_invert_jacobi(const gsl_matrix * matrix,\r\n gsl_matrix * ainv,\r\n unsigned int max_rot);\r\n\r\n\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_EIGEN_H__ */\r\n", "meta": {"hexsha": "366670bc273124fc44786a0f3acf2e0d27aee80c", "size": 14352, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_eigen.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_eigen.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_eigen.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 40.0893854749, "max_line_length": 115, "alphanum_fraction": 0.6504319955, "num_tokens": 3529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6101656863098401}} {"text": "/* specfunc/bessel_J0.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author: G. Jungman */\n\n#include \n#include \n#include \n#include \n#include \"bessel.h\"\n#include \"bessel_amp_phase.h\"\n#include \n#include \n\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n/* based on SLATEC besj0, 1977 version, w. fullerton */\n\n/* chebyshev expansions for Bessel functions\n\n series for bj0 on the interval 0. to 1.60000d+01\n with weighted error 7.47e-18\n log weighted error 17.13\n significant figures required 16.98\n decimal places required 17.68\n\n*/\n\nstatic double bj0_data[13] = {\n 0.100254161968939137, \n -0.665223007764405132, \n 0.248983703498281314, \n -0.0332527231700357697,\n 0.0023114179304694015,\n -0.0000991127741995080,\n 0.0000028916708643998,\n -0.0000000612108586630,\n 0.0000000009838650793,\n -0.0000000000124235515,\n 0.0000000000001265433,\n -0.0000000000000010619,\n 0.0000000000000000074,\n};\nstatic cheb_series bj0_cs = {\n bj0_data,\n 12,\n -1, 1,\n 9\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result)\n{\n double y = fabs(x);\n\n /* CHECK_POINTER(result) */\n\n if(y < 2.0*GSL_SQRT_DBL_EPSILON) {\n result->val = 1.0;\n result->err = y*y;\n return GSL_SUCCESS;\n }\n else if(y <= 4.0) {\n return cheb_eval_e(&bj0_cs, 0.125*y*y - 1.0, result);\n }\n else {\n const double z = 32.0/(y*y) - 1.0;\n gsl_sf_result ca;\n gsl_sf_result ct;\n gsl_sf_result cp;\n const int stat_ca = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bm0_cs, z, &ca);\n const int stat_ct = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bth0_cs, z, &ct);\n const int stat_cp = gsl_sf_bessel_cos_pi4_e(y, ct.val/y, &cp);\n const double sqrty = sqrt(y);\n const double ampl = (0.75 + ca.val) / sqrty;\n result->val = ampl * cp.val;\n result->err = fabs(cp.val) * ca.err/sqrty + fabs(ampl) * cp.err;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_3(stat_ca, stat_ct, stat_cp);\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_J0(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_J0_e(x, &result));\n}\n", "meta": {"hexsha": "a0fc5810fc820bc9224e7b649ae9eefd15b38eb6", "size": 3262, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_J0.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_J0.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_J0.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.125, "max_line_length": 81, "alphanum_fraction": 0.638258737, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.610024183128684}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../inc/knnring.h\"\n\n\nknnresult kNN(double *X, double *Y, int n, int m, int d, int k){\n\n\tknnresult k_nearest;\n\n\t//initalize the result's variable\n\tk_nearest.nidx = (int *)malloc(m*k*sizeof(int));\n\tk_nearest.ndist = (double *)malloc(m*k*sizeof(double));\n\tk_nearest.m = m;\n\tk_nearest.k = k;\n\n //compute the distance Matrix D\n\tdouble *D = compute_D(X,Y,n,m,d,k);\n\n //select k-nearest neighbors for every point in QUERY\n\tk_select(D,k_nearest.ndist, k_nearest.nidx,n,m,k);\n\treturn k_nearest;\n}\n\n\ndouble *compute_D(double *X, double *Y, int n, int m, int d, int k){\n\n\n\t//compute distances using\n\t//D = (X*X)ee_t - 2XY_t + ee_t(Y*Y)_t\n\tdouble *tempD = (double *)malloc(n*m*sizeof(double));\n\tdouble *e_1 = (double *)malloc(d*m*sizeof(double));\n\tdouble *XX = (double *)malloc(n*d*sizeof(double));\n\n\tfor(int i=0;i \n#include \n#include \n#include \n#include \n#include \n#include \n\n//** Init Multinomial \ngsl_rng* init_gsl_rng(){\n\t\tgsl_rng* r;\n \t\tconst gsl_rng_type* T2;\n \n srand(time(NULL));\n unsigned int seed;\n seed= rand(); \n\n gsl_rng_env_setup();\n\n T2 = gsl_rng_default;\n r = gsl_rng_alloc (T2);\n gsl_rng_set (r, seed);\n\t\n\t\treturn r; \n}\n\n\nunsigned int substract(unsigned int val){\n\tif(val>0)\n\t\treturn val-1;\n\telse\n\t\treturn 0;\n}\n\n\n\n//** Data must be dictionated\n//** Doc-Word-topic\nvoid dt2b_inference(int** data , unsigned int** uKu, unsigned int** pKp, unsigned int** KuKp, const int it, const int Ku,const int Kp, const int nusers, const int nplaces, const int nrecs){\n\n\tfloat l,prev_l,prob=0;\n\t\n \t//** Allocate Dynamic Tables\n\tunsigned int zu[Ku];\n\tmemset( zu, 0, Ku*sizeof(unsigned int) );\n\tunsigned int zp[Kp];\n\tmemset( zp, 0, Kp*sizeof(unsigned int) );\n\tdouble p_zuzp[Ku][Kp];\n\t\n\n\n //** Initialization\n\tgsl_rng * r;\n\tr=init_gsl_rng();\n\t\n\n\t//** Initialize Dynamic Tables\n\tunsigned int oneutopic,oneptopic;\n\tsize_t rowid;\n\tfor(rowid=0;rowid0){\n \t\t\t\t\t\n \t\t\t\t\t//get two indexes from one\n \t\t\t\t\tchosen_ku=(unsigned int) (s/Kp);\n \t\t\t\t\tchosen_kp=(unsigned int) (s%Kp);\n \t\t\t\t\t\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n \t\t\n \t\t\n \t\t\t//** Update\n \t\t\tdata[rowid][2]=chosen_ku;\n \t\t\tdata[rowid][3]=chosen_kp;\n \t\t\tuKu[curr_u][chosen_ku]+=1;\n \t\t\tpKp[curr_p][chosen_kp]+=1;\n \t\t\tKuKp[chosen_ku][chosen_kp]+=1;\n \t\t\tzu[chosen_ku]+=1;\n \t\t\tzp[chosen_kp]+=1;\n \t\t\t\n\t\t}\n\t\t\n\tif (i==0)\n\t\tprev_l=l;\n\t\n\t//** Check convergence\n\t\tif (l50){\n\t\t\tprintf(\"Stopped at iteration %zu\",i);\n\t\t\tbreak;\n\t\t}\n\t\t\t\t\n\t\tprintf(\"Likelihood at iteration %zu: %f \\n\",i,l);\n\t\t\n\t}\n\n\tgsl_rng_free (r); \t\n}\n\t\n \n", "meta": {"hexsha": "4660b5d285cd2a125be188536a015537f3c914a3", "size": 2991, "ext": "c", "lang": "C", "max_stars_repo_path": "C/DT2B/dt2b_inference.c", "max_stars_repo_name": "danrugeles/YLDA", "max_stars_repo_head_hexsha": "284730d538167342f9d215b6fea0c1a3c186568a", "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/DT2B/dt2b_inference.c", "max_issues_repo_name": "danrugeles/YLDA", "max_issues_repo_head_hexsha": "284730d538167342f9d215b6fea0c1a3c186568a", "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/DT2B/dt2b_inference.c", "max_forks_repo_name": "danrugeles/YLDA", "max_forks_repo_head_hexsha": "284730d538167342f9d215b6fea0c1a3c186568a", "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.3469387755, "max_line_length": 191, "alphanum_fraction": 0.5994650619, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6097667707368277}} {"text": "#include\n#include\n#include\"recur.c\"\n#include \n#include\"gsl_integration.c\"\n#define NMAX 100\n#include\"timer.h\"\n#include\"timer.c\"\n#include\"adjust.c\"\n\n/* The integral is evaluated for n=0 to n=100 using both a derived recursion formula\n * and the GSL general integrator. The values of both are stored in their own \n * respective arrays. The values and their absolute error are printed in order to\n * compare the accuracy of the two methods. Then, both functions are timed to \n * determine which one is faster at generating the results. Finally, the timings of\n * the two functions are divided to provide a ratio describing the difference in \n * efficiency of the two methods.\n*/\nint main (void)\n{\n double vals1[NMAX + 1], vals2[NMAX + 1], time1a, time1b, time2a, time2b, tmin = 1., tmax = 2.; // Initializing all the \"double\" variables for use in the program//\n int nmin = 0, nmax = NMAX, count1 = 1000, count2 = 800;\n\n integral_recur (nmin, nmax, vals1); // Recursion formula stores I(0) to I(100) in the array vals1//\n integral_gen (nmin, nmax, vals2); // GSL integration algorithm stores I(0) to I(100) in the array vals2//\n\n printf\n (\" --n-- --Recur-- --GSL Integrator-- --Absolute Error*10^9--\\n\");\n int k;\n\n for (k = 0; k < 101; k++)\n {\n printf (\" %6d %15.15f %15.15f %15.15f \\n\", k, vals1[k],\n vals2[k], fabs (1.e9 * (vals1[k] - vals2[k])));\n } // Prints the values for each term in the sequence as generated by both of the algorithms //\n int p;\n\n printf\n (\"\\n--Timing for recurrence function--\\nTime per call (usec) Total Time (sec) Count\\n\");\n do\n {\n timer_start (); // The timer is started.\n for (p = 0; p < count1; p++) // The function is called \"count1\" times.\n {\n integral_recur (nmin, nmax, vals1); // The recursion formula stores each of the sequence values in the array vals1//\n }\n time1a = timer_stop (); // The timer is stopped.\n time1b = time1a / count1; // The time per function call is calculated as the total time divided by the number of function calls.\n printf (\" %10.2f usec %10.6f sec %10d\\n\", time1b * 1.e6,\n time1a, count1);\n count1 = adjust_rep_count (count1, time1a, tmin, tmax); // The number of function calls \"count1\" is adjusted. \n }\n while ((time1a > tmax) || (time1a < tmin)); // This is repeated until the total time is within the desired range.\n printf (\"Time per recur function call = %f usec \\n\", time1b * 1.e6);\n printf\n (\"\\n--Timing for GSL integration function--\\nTime per call (usec) Total Time (sec) Count\\n\");\n do\n {\n timer_start (); // The timer is started.\n for (p = 0; p < count2; p++) // The function is called \"count2\" times.\n {\n integral_gen (nmin, nmax, vals2); // The GSL integration formula stores each of the sequence values in the array vals1//\n }\n time2a = timer_stop (); // The timer is stopped.\n time2b = time2a / count2; // The time per function call is calculated as the total time divided by the number of function calls.\n printf (\" %10.2f usec %10.6f sec %10d\\n\", time2b * 1.e6,\n time2a, count2);\n count2 = adjust_rep_count (count2, time2a, tmin, tmax); // The number of function calls \"count2\" is adjusted. \n }\n while ((time2a > tmax) || (time2a < tmin)); // This is repeated until the total time is within the desired range.\n printf (\"Time per GSL function call = %f usec \\n\", time2b * 1.e6);\n\n printf (\"Ratio of times Tgsl / Trecur = %f\\n\", time2b / time1b); // The ratio of times per function call of each function is printed//\n return 0;\n}\n", "meta": {"hexsha": "39d021332daed9bc2a06702998b9d541748d2435", "size": 3843, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "fbergabo/hw07", "max_stars_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "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": "fbergabo/hw07", "max_issues_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "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": "fbergabo/hw07", "max_forks_repo_head_hexsha": "00507c760b4820c73736a7987beb6ba21fb892d1", "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": 50.5657894737, "max_line_length": 171, "alphanum_fraction": 0.6185271923, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6097667698543358}} {"text": "/**\n * @brief handle cosmological functions like power spectrum, growth, etc.\n * \n * @file core_power.h\n * @author Michal Vrastil\n * @date 2018-06-21\n */\n\n#pragma once\n#include \"precision.hpp\"\n#include \n\n/*******************//**\n* FORWARD DECLARATIONS *\n************************/\n\nclass Cosmo_Param; ///< declaration in params.hpp\nclass Sim_Param; ///< declaration in params.hpp\ntemplate class Data_Vec; ///< declaration in class_data_vec.hpp\n\n/**\n * @brief Initialize CCL power spectrum\n * \n * @param cosmo cosmological parameters\n */\nvoid norm_pwr(Cosmo_Param& cosmo);\n\n/**\n * @brief when computing growth factor outside CCL range we need to normalize the growth factor; \\f$D(a=1)\\equiv1\\f$\n * \n * @param cosmo cosmological parameters\n * @return FTYPE_t unnormalized growth factor at 'a = 1'\n */\nFTYPE_t norm_growth_factor(const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t growth_factor(FTYPE_t a, const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t growth_rate(FTYPE_t a, const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t growth_change(FTYPE_t a, const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t Omega_lambda(FTYPE_t a, const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param k \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t lin_pow_spec(FTYPE_t a, FTYPE_t k, const Cosmo_Param& cosmo);\n\n/**\n * @brief \n * \n * @param a \n * @param k \n * @param cosmo cosmological parameters\n * @return FTYPE_t \n */\nFTYPE_t non_lin_pow_spec(FTYPE_t a, FTYPE_t k, const Cosmo_Param& cosmo);\n\n/**\n * @class:\tInterp_obj\n * @brief:\tlinear interpolation (Steffen) of data [x, y]\n */\nclass Interp_obj\n{\npublic:\n Interp_obj(): is_init(false) {}\n ~Interp_obj();\n double operator()(double x) const;\n template \n void init(const Data_Vec& data);\n double x_min, x_max;\n\nprivate:\n bool is_init;\n gsl_spline* spline;\n gsl_interp_accel* acc;\n};\n\n/**\n * @class:\tExtrap_Pk\n * @brief:\tlinear interpolation of data [k, P(k)] within 'useful' range\n * fit to primordial P_i(k) below the 'useful' range\n * fit to Padé approximant R [0/3] above the 'useful' range\n *\n * Steffen interpolation of data [k, P(k)] within range k_min, k_max\n * fit to primordial P_i(k) below this range, fit A*k^ns above\n */\ntemplate \nclass Extrap_Pk : public Interp_obj\n{\npublic:\n Extrap_Pk(const Data_Vec& data, const Sim_Param& sim);\n Extrap_Pk(const Data_Vec& data, const Sim_Param& sim, const size_t m_l, const size_t n_u);\n Extrap_Pk(const Data_Vec& data, const Sim_Param& sim, const size_t m_l, const size_t n_l,\n const size_t m_u, const size_t n_u);\n double operator()(double k) const;\n\n void fit_lin(const Data_Vec& data, const size_t m, const size_t n, double& A);\n void fit_power_law(const Data_Vec& data, const size_t m, const size_t n, double& A, double& n_s);\n\n double A_low; ///< amplitude of linear power in lower range\n const Cosmo_Param& cosmo;\n double A_up, n_s; ///< scale-free power spectrum in upper range\n T k_min, k_max; ///< interpolation range\n};\n\n/**\n * @class:\tExtrap_Pk_Nl\n * @brief:\tcreates Extrapolate object (linear power spectrum) from data and store non-linear parameters\n call 'operator()(k)' based on k_split (upper range of the linear)\n */\ntemplate \nclass Extrap_Pk_Nl : public Extrap_Pk\n{\npublic:\n Extrap_Pk_Nl(const Data_Vec& data, const Sim_Param &sim, T A_nl, T a_eff);\n const T A_nl, a_eff, k_split;\n double operator()(double k) const;\n};\n\n/**\n * @brief compute correlation function and store results\n * \n * @tparam P callable object with 'operator()(double)'\n * @param sim simulation parameters\n * @param P_k power spectrum (callable)\n * @param corr_func_binned object to store binned correlation function\n */\ntemplate\nvoid gen_corr_func_binned_gsl_qawf(const Sim_Param &sim, const P& P_k, Data_Vec& corr_func_binned);\n\n/**\n * @brief compute linear correlation function and store results\n * \n * @param sim simulation parameters\n * @param a scale factor\n * @param corr_func_binned object to store binned correlation function\n */\nvoid gen_corr_func_binned_gsl_qawf_lin(const Sim_Param &sim, FTYPE_t a, Data_Vec& corr_func_binned);\n\n/**\n * @brief compute non-linear correlation function and store results\n * \n * @param sim simulation parameters\n * @param a scale factor\n * @param corr_func_binned object to store binned correlation function\n */\nvoid gen_corr_func_binned_gsl_qawf_nl(const Sim_Param &sim, FTYPE_t a, Data_Vec& corr_func_binned);\n\n/**\n * @brief compute amplitude of density fluctuation and store results\n * \n * @tparam P callable object with 'operator()(double)'\n * @param sim simulation parameters\n * @param P_k power spectrum (callable)\n * @param sigma_binned object to store binned correlation function\n */\ntemplate\nvoid gen_sigma_binned_gsl_qawf(const Sim_Param &sim, const P& P_k, Data_Vec& sigma_binned);\n\n/**\n * @brief compute linear amplitude of density fluctuation and store results\n * \n * @param sim simulation parameters\n * @param a scale factor\n * @param sigma_binned object to store binned correlation function\n */\nvoid gen_sigma_func_binned_gsl_qawf_lin(const Sim_Param &sim, FTYPE_t a, Data_Vec& sigma_binned);\n\n/**\n * @brief compute non-linear amplitude of density fluctuation and store results\n * \n * @param sim simulation parameters\n * @param a scale factor\n * @param sigma_binned object to store binned correlation function\n */\nvoid gen_sigma_func_binned_gsl_qawf_nl(const Sim_Param &sim, FTYPE_t a, Data_Vec& sigma_binned);\n", "meta": {"hexsha": "9fedcf1856254f1a52147a3f42b75edd151f54f0", "size": 6060, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/include/core_power.h", "max_stars_repo_name": "sjvs/FastSim", "max_stars_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55", "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/core/include/core_power.h", "max_issues_repo_name": "sjvs/FastSim", "max_issues_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2017-06-27T07:34:02.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-17T07:36:21.000Z", "max_forks_repo_path": "src/core/include/core_power.h", "max_forks_repo_name": "sjvs/FastSim", "max_forks_repo_head_hexsha": "7a17b61c5463112e40b12f1842d03a73c342ef55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T13:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T12:48:40.000Z", "avg_line_length": 28.7203791469, "max_line_length": 116, "alphanum_fraction": 0.7069306931, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6097495353854697}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include // dgemv\r\n#include // dstegr\r\n\r\n#define abs1(a) ((a) < 0.0 ? -(a) : (a))\r\n#define sign1(a) ((a)==0) ? 0 : (((a)>0.0)?1:(-1))\r\n#define max1(a,b) ((a) > (b) ? (a) : (b))\r\n#define min1(a,b) ((a) < (b) ? (a) : (b))\r\n\r\ndouble dot1(const double*a,const double*b,const ptrdiff_t n)\r\n{\r\n double ret = 0;\r\n ptrdiff_t i;\r\n for(i=0;i val)\r\n {\r\n val = abs1(a[i]);\r\n pos = i;\r\n }\r\n }\r\n return pos;\r\n}\r\nvoid pvec(const double*a,const ptrdiff_t n)\r\n{\r\n // print the vector a\r\n ptrdiff_t i;\r\n printf(\"[ \");\r\n for (i=0;i\n#include \n#include \n\n/// GSL fft of complex array, z_i = x_i + j*y_i\n/// data are stored in one real array A that A[2i] = x_i and A[2i+1] = y_i\n#define REAL(z,i) ((z)[2*(i)])\n#define IMAG(z,i) ((z)[2*(i)+1])\n\ndouble const sqrt2 = std::sqrt(2);\nconstexpr double TINY = 1e-12;\nconstexpr int relative_skew_switch = 1;\nconstexpr int absolute_skew_switch = 2;\n/// the mean of the rapidity distribution as function of Ta(x,y),\n/// Tb(x,y) and exp(y_beam).\n/// For the case both Ta and Tb are tiny small, mean = 0.0 is returned.\n/// For the case only Ta(Tb) = 0, it returns +(-)y_beam,\n/// For the case y_beam >> 1, mean ~ 0.5*log(Ta/Tb)\ndouble inline mean_function(double ta, double tb, double exp_ybeam){\n if (ta < TINY && tb < TINY) return 0.;\n return 0.5 * std::log((ta*exp_ybeam + tb/exp_ybeam) / std::max(ta/exp_ybeam + tb*exp_ybeam, TINY));\n}\n\n/// The coefficient of normalized width of the rapidity distribution\n/// Currently, it is simply a constant independent of Ta(x,y) and Tb(x,y)\ndouble inline std_function(double ta, double tb){\n (void)ta;\n (void)tb;\n return 1.;\n}\n\n/// The normalized skewness as function of Ta(x,y) and Tb(x,y)\n\ndouble inline skew_function(double ta, double tb, int type_switch){\n if (type_switch == relative_skew_switch)\n return (ta - tb)/std::max(ta + tb, TINY);\n else if(type_switch == absolute_skew_switch)\n return ta-tb;\n else return 0.;\n}\n\n/// A fast pseudorapidity to rapidity transformer using pretabulated values\n/// It returns the transfoamtion y(eta) and the jacobian dy/deta(eta)\nclass fast_eta2y {\nprivate:\n double etamax_;\n double deta_;\n std::size_t neta_;\n std::vector y_;\n std::vector dydeta_;\npublic:\n fast_eta2y(double J, double etamax, double deta)\n : etamax_(etamax),\n deta_(deta),\n neta_(std::ceil(2.*etamax_/(deta_+1e-15))+1),\n y_(neta_, 0.),\n dydeta_(neta_, 0.) {\n\n for (std::size_t ieta = 0; ieta < neta_; ++ieta) {\n double eta = -etamax_ + ieta*deta_;\n double Jsh = J*std::sinh(eta);\n double sq = std::sqrt(1. + Jsh*Jsh);\n y_[ieta] = std::log(sq + Jsh);\n dydeta_[ieta] = J*std::cosh(eta)/sq;\n }\n }\n\n double rapidity(double eta){\n double steps = (eta + etamax_)/deta_;\n double xi = std::fmod(steps, 1.);\n std::size_t index = std::floor(steps);\n return y_[index]*(1. - xi) + y_[index+1]*xi;\n }\n\n double Jacobian(double eta){\n double steps = (eta + etamax_)/deta_;\n double xi = std::fmod(steps, 1.);\n std::size_t index = std::floor(steps);\n return dydeta_[index]*(1. - xi) + dydeta_[index+1]*xi;\n }\n\n};\n\n\n/// A class for cumulant generating function inversion\n/// This class handles inverse fourier transform the cumulant generating function\n/// A direct transformation F^{-1} exp(i*m*k-(std*k)^2/2-skew*(std*k)^3/6) results\n/// in an ill-behaved function. Instead, skew is replaced by skew*exp(-(std*k)^2/2).\n/// In this way higher order cumulant are included to regulated the function.\n/// The reconstruction range is taken to be [-3.33, 3.33]*std, which does not \n/// seem to be very large, however, by trail and error, this range elimiates \n/// oscillations at large rapidity and leaves the details close to mid-rapidity \n/// unchanged. We used GSL FFT library (more specialized library would be FFTW, \n/// e.g.), with 256 points. The transformed results are stored and interpolated. \nclass cumulant_generating{\nprivate:\n size_t const N;\n double * data, * dsdy;\n double eta_max;\n double deta;\n double center;\n\npublic:\n cumulant_generating(): N(256), data(new double[2*N]), dsdy(new double[2*N]){};\n\n /// This function set the mean, std and skew of the profile and use FFT to\n /// transform cumulant generating function at zero mean.\n void calculate_dsdy(double mean, double std, double skew){\n double k1, k2, k3, amp, arg;\n // adaptive eta_max = 3.33*std;\n center = mean;\n eta_max = std*3.33;\n deta = 2.*eta_max/(N-1.);\n double fftmean = eta_max/std;\n for(size_t i=0;i(i%2 == 0)-1.0);\n }\n }\n\n /// When interpolating the funtion, the mean is put back by simply shifting \n /// the function by y = y - mean + dy/2, the last term is correcting for\n /// interpolating bin edge instead of bin center\n double interp_dsdy(double y){\n y = y-center+deta/2.;\n if (y < -eta_max || y >= eta_max) return 0.0;\n double xy = (y+eta_max)/deta;\n size_t iy = std::floor(xy);\n double ry = xy-iy;\n return dsdy[iy]*(1.-ry) + dsdy[iy+1]*ry;\n }\n};\n#endif\n", "meta": {"hexsha": "bf683e05fc703aeeb86eb9ce368d28cdd364e2e1", "size": 5149, "ext": "h", "lang": "C", "max_stars_repo_path": "src/rapidity_profile.h", "max_stars_repo_name": "K-JW/trento", "max_stars_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-02T08:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-02T08:46:01.000Z", "max_issues_repo_path": "src/rapidity_profile.h", "max_issues_repo_name": "K-JW/trento", "max_issues_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "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/rapidity_profile.h", "max_forks_repo_name": "K-JW/trento", "max_forks_repo_head_hexsha": "9f8f74add763ef95757f4d448d6e3f2e77ab54de", "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.4350649351, "max_line_length": 101, "alphanum_fraction": 0.6506117693, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6087267977669739}} {"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\ntypedef struct gsl_quad_tensor\n{\n int i;\n int j;\n int k;\n int l;\n\n gsl_matrix *** element;\n}gsl_quad_tensor;\n\ngsl_quad_tensor * gsl_quad_tensor_alloc(int i, int j, int k, int l);\ngsl_quad_tensor * gsl_quad_tensor_calloc(int i,int j, int k, int l);\nvoid gsl_quad_tensor_free(gsl_quad_tensor * q);\n\ndouble gsl_quad_tensor_get(gsl_quad_tensor * q, int i, int j, int k, int l);\nvoid gsl_quad_tensor_get_matrix(gsl_matrix * m, gsl_quad_tensor * q, int i, int j);\n\nvoid gsl_quad_tensor_set(gsl_quad_tensor * q, int i, int j, int k, int l, double x);\nvoid gsl_quad_tensor_set_matrix(gsl_quad_tensor * q, int i, int j, const gsl_matrix * m);\n\nvoid gsl_quad_tensor_add(gsl_quad_tensor * A, gsl_quad_tensor * b);\nvoid gsl_quad_tensor_sub(gsl_quad_tensor * A, gsl_quad_tensor * b);\nvoid gsl_quad_tensor_scale(gsl_quad_tensor * q, double x);\n\n\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);\n\n\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);\n\n\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);\n\n\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);\n\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);\n\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);\n\nvoid gsl_matrix_square_root(gsl_matrix * dest, gsl_matrix * src, int length);\nvoid gsl_matrix_inverse_square_root(gsl_matrix* dest, gsl_matrix * src, int length);\nvoid gsl_eigen_Lowdin_diag(gsl_matrix * m, gsl_matrix * S, gsl_vector * eigen, gsl_matrix * eigenvec, int length);\nvoid gsl_matrix_normalize(gsl_matrix * coef,int length, int columns);\nvoid gsl_matrix_flip(gsl_matrix * dest,int height,int width);\n\n\n#endif\n", "meta": {"hexsha": "eb404d7654c27b204c73acf9d7a808e653ff237d", "size": 3558, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslextra.h", "max_stars_repo_name": "Walter-Feng/Overlap", "max_stars_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "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/gslextra.h", "max_issues_repo_name": "Walter-Feng/Overlap", "max_issues_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "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/gslextra.h", "max_forks_repo_name": "Walter-Feng/Overlap", "max_forks_repo_head_hexsha": "daddeb4b81bd93cd5450b1a172c8653dbbfc26d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3571428571, "max_line_length": 137, "alphanum_fraction": 0.7906127038, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6085775075410144}} {"text": "#include \n#include \n#include \"acceleration.h\"\n\nint func(double t, const double y[], double f[], void *params) {\n /*\n y[0], y[1], y[2] are x, y, z\n y[3], y[4], y[5] are v_x, v_y, v_z\n */\n\n (void)(t); /* avoid unused parameter warning */\n struct HernquistParams pars = *(struct HernquistParams *)params;\n\n double r;\n double dPhi_dr;\n\n r = sqrt(y[0]*y[0] + y[1]*y[1] + y[2]*y[2]);\n dPhi_dr = pars.G * pars.m / pow(r + pars.c, 2);\n\n // Derivative of position is just velocity\n f[0] = y[3];\n f[1] = y[4];\n f[2] = y[5];\n\n // Derivative of velocity is acceleration from potential\n f[3] = -dPhi_dr * y[0] / r;\n f[4] = -dPhi_dr * y[1] / r;\n f[5] = -dPhi_dr * y[2] / r;\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "65aca17613c0ba93a615b95341875149112cd41c", "size": 774, "ext": "c", "lang": "C", "max_stars_repo_path": "4-package-advanced/gsl_integrate/src/acceleration.c", "max_stars_repo_name": "HaifengWangNAOC/Somethingnew", "max_stars_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2017-11-07T21:48:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T14:26:36.000Z", "max_issues_repo_path": "4-package-advanced/gsl_integrate/src/acceleration.c", "max_issues_repo_name": "achapkowski/cython-tutorial", "max_issues_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c", "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": "4-package-advanced/gsl_integrate/src/acceleration.c", "max_forks_repo_name": "achapkowski/cython-tutorial", "max_forks_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-11-10T09:26:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:37:32.000Z", "avg_line_length": 24.1875, "max_line_length": 68, "alphanum_fraction": 0.5413436693, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6083213220768384}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"chmath.h\"\n#include \"err.h\"\n\nstatic char* me = \"chmath\";\n\nstatic double get(const gsl_matrix* m, int i, int j) {\n return gsl_matrix_get(m, i, j);\n}\n\nint chmath_eig_values(const double A[6], /**/ double VAL[3]) {\n enum { XX, XY, XZ, YY, YZ, ZZ };\n enum { YX = XY, ZX = XZ, ZY = YZ };\n enum { X, Y, Z };\n\n double B[3 * 3];\n gsl_matrix_view m;\n gsl_vector* val;\n gsl_matrix* vec;\n gsl_eigen_symmv_workspace* w;\n int i, status;\n\n val = gsl_vector_alloc(3);\n vec = gsl_matrix_alloc(3, 3);\n w = gsl_eigen_symmv_alloc(3);\n\n i = 0;\n B[i++] = A[XX];\n B[i++] = A[XY];\n B[i++] = A[XZ];\n B[i++] = A[YX];\n B[i++] = A[YY];\n B[i++] = A[YZ];\n B[i++] = A[ZX];\n B[i++] = A[ZY];\n B[i++] = A[ZZ];\n\n m = gsl_matrix_view_array(B, 3, 3);\n status = gsl_eigen_symmv(&m.matrix, val, vec, w);\n if (status != GSL_SUCCESS) ERR((\"gsl_eigen_symmv failed\"));\n gsl_eigen_symmv_sort(val, vec, GSL_EIGEN_SORT_ABS_ASC);\n\n i = 0;\n VAL[i] = gsl_vector_get(val, i);\n i++;\n VAL[i] = gsl_vector_get(val, i);\n i++;\n VAL[i] = gsl_vector_get(val, i);\n\n gsl_vector_free(val);\n gsl_matrix_free(vec);\n gsl_eigen_symmv_free(w);\n return 0;\n}\n\nint chmath_eig_vectors(\n const double A[6], /**/ double a[3], double b[3], double c[3]) {\n enum { XX, XY, XZ, YY, YZ, ZZ };\n enum { YX = XY, ZX = XZ, ZY = YZ };\n enum { X, Y, Z };\n\n double B[3 * 3];\n gsl_matrix_view m;\n gsl_vector* val;\n gsl_matrix* vec;\n gsl_eigen_symmv_workspace* w;\n int i, status;\n\n val = gsl_vector_alloc(3);\n vec = gsl_matrix_alloc(3, 3);\n w = gsl_eigen_symmv_alloc(3);\n\n i = 0;\n B[i++] = A[XX];\n B[i++] = A[XY];\n B[i++] = A[XZ];\n B[i++] = A[YX];\n B[i++] = A[YY];\n B[i++] = A[YZ];\n B[i++] = A[ZX];\n B[i++] = A[ZY];\n B[i++] = A[ZZ];\n\n m = gsl_matrix_view_array(B, 3, 3);\n status = gsl_eigen_symmv(&m.matrix, val, vec, w);\n if (status != GSL_SUCCESS) ERR((\"gsl_eigen_symmv failed\"));\n gsl_eigen_symmv_sort(val, vec, GSL_EIGEN_SORT_ABS_ASC);\n\n i = 0;\n a[X] = get(vec, X, X);\n a[Y] = get(vec, Y, X);\n a[Z] = get(vec, Z, X);\n b[X] = get(vec, X, Y);\n b[Y] = get(vec, Y, Y);\n b[Z] = get(vec, Z, Y);\n c[X] = get(vec, X, Z);\n c[Y] = get(vec, Y, Z);\n c[Z] = get(vec, Z, Z);\n gsl_vector_free(val);\n gsl_matrix_free(vec);\n gsl_eigen_symmv_free(w);\n return 0;\n}\n", "meta": {"hexsha": "4829610191622a264c53d05a38df981dc07e8333", "size": 2432, "ext": "c", "lang": "C", "max_stars_repo_path": "deploy/lib/chmath/main.c", "max_stars_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_stars_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "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": "deploy/lib/chmath/main.c", "max_issues_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_issues_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "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": "deploy/lib/chmath/main.c", "max_forks_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_forks_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "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.9099099099, "max_line_length": 68, "alphanum_fraction": 0.5760690789, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248208414329, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.6082986183238085}} {"text": "/* -*- c -*- */\n/*\n * Copyright 2002-2018 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio 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, or (at your option)\n * any later version.\n *\n * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n/*\n * generate MMSE FIR interpolation table values\n */\n\n#include \n#include \n#include \n\n#define\tMU\t0.5\t\t\t/* the MU for which we're computing coeffs */\n\n#define\tTs\t(1.0)\t\t\t/* sampling period \t\t*/\n#define\tB\t(1.0/(4*Ts))\t\t/* one-sided signal bandwidth \t*/\n//#define\tB\t(1.0/(8./3*Ts))\t\t/* one-sided signal bandwidth \t*/\n\nstatic unsigned global_n;\nstatic double *global_h;\ndouble\t\tglobal_mu = MU;\ndouble\t\tglobal_B = B;\n\ngsl_integration_workspace *global_gsl_int_workspace = NULL;\n\n/*\n * This function computes the difference squared between the ideal\n * interpolator frequency response at frequency OMEGA and the\n * approximation defined by the FIR coefficients in global_h[]\n *\n * See eqn (9-7), \"Digital Communication Receivers\", Meyr, Moeneclaey\n * and Fechtel, Wiley, 1998.\n */\n\nstatic double\nintegrand (double omega, void *params)\n{\n double real_ideal;\n double real_approx;\n double real_diff;\n double imag_ideal;\n double imag_approx;\n double imag_diff;\n\n int\t i, n;\n int\t I1;\n double *h;\n\n real_ideal = cos (omega * Ts * global_mu);\n imag_ideal = sin (omega * Ts * global_mu);\n\n n = global_n;\n h = global_h;\n I1 = -(n / 2);\n\n real_approx = 0;\n imag_approx = 0;\n\n for (i = 0; i < n; i++){\n real_approx += h[i] * cos (-omega * Ts * (i + I1));\n imag_approx += h[i] * sin (-omega * Ts * (i + I1));\n }\n\n real_diff = real_ideal - real_approx;\n imag_diff = imag_ideal - imag_approx;\n\n return real_diff * real_diff + imag_diff * imag_diff;\n}\n\n/*\n * Integrate the difference squared over all frequencies of interest.\n */\ndouble\nc_fcn (double *x, int n)\n{\n gsl_function F;\n double result, error;\n\n F.function = integrand;\n F.params = NULL;\n\n assert ((n & 1) == 0);\t/* assert n is even */\n global_n = n;\n global_h = x;\n gsl_integration_qag(&F, -2 * M_PI * global_B, 2 * M_PI * global_B,\n 0.0, 1e-12, 1000, GSL_INTEG_GAUSS61,\n global_gsl_int_workspace, &result, &error);\n return result;\n}\n\n/* this is the interface expected by the calling fortran code */\n\ndouble\nobjective (double x[], int *ndim)\n{\n return c_fcn (x, *ndim);\n}\n\nstatic double\nsi (double x)\n{\n if (fabs (x) < 1e-9)\n return 1.0;\n\n return sin(x) / x;\n}\n\n/*\n * starting guess for optimization\n */\nvoid initpt (double x[], int ndim)\n{\n int i;\n for (i = 0; i < ndim; i++){\n x[i] = si (M_PI * ((double) (i - ndim/2) + global_mu));\n }\n}\n", "meta": {"hexsha": "061fdf4970eb8e176bcb8c3d3732fbb985f78322", "size": 3240, "ext": "c", "lang": "C", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/objective_fct.c", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8235294118, "max_line_length": 71, "alphanum_fraction": 0.6592592593, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6081841399684067}} {"text": "/* diff/diff.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 David Morrison\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 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\nint\ngsl_diff_backward (const gsl_function * f,\n double x, double *result, double *abserr)\n{\n /* Construct a divided difference table with a fairly large step\n size to get a very rough estimate of f''. Use this to estimate\n the step size which will minimize the error in calculating f'. */\n\n int i, k;\n double h = GSL_SQRT_DBL_EPSILON;\n double a[3], d[3], a2;\n\n /* Algorithm based on description on pg. 204 of Conte and de Boor\n (CdB) - coefficients of Newton form of polynomial of degree 2. */\n\n for (i = 0; i < 3; i++)\n {\n a[i] = x + (i - 2.0) * h;\n d[i] = GSL_FN_EVAL (f, a[i]);\n }\n\n for (k = 1; k < 4; k++)\n {\n for (i = 0; i < 3 - k; i++)\n {\n d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]);\n }\n }\n\n /* Adapt procedure described on pg. 282 of CdB to find best value of\n step size. */\n\n a2 = fabs (d[0] + d[1] + d[2]);\n\n if (a2 < 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n a2 = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n h = sqrt (GSL_SQRT_DBL_EPSILON / (2.0 * a2));\n\n if (h > 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n h = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n *result = (GSL_FN_EVAL (f, x) - GSL_FN_EVAL (f, x - h)) / h;\n *abserr = fabs (10.0 * a2 * h);\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_diff_forward (const gsl_function * f,\n double x, double *result, double *abserr)\n{\n /* Construct a divided difference table with a fairly large step\n size to get a very rough estimate of f''. Use this to estimate\n the step size which will minimize the error in calculating f'. */\n\n int i, k;\n double h = GSL_SQRT_DBL_EPSILON;\n double a[3], d[3], a2;\n\n /* Algorithm based on description on pg. 204 of Conte and de Boor\n (CdB) - coefficients of Newton form of polynomial of degree 2. */\n\n for (i = 0; i < 3; i++)\n {\n a[i] = x + i * h;\n d[i] = GSL_FN_EVAL (f, a[i]);\n }\n\n for (k = 1; k < 4; k++)\n {\n for (i = 0; i < 3 - k; i++)\n {\n d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]);\n }\n }\n\n /* Adapt procedure described on pg. 282 of CdB to find best value of\n step size. */\n\n a2 = fabs (d[0] + d[1] + d[2]);\n\n if (a2 < 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n a2 = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n h = sqrt (GSL_SQRT_DBL_EPSILON / (2.0 * a2));\n\n if (h > 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n h = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n *result = (GSL_FN_EVAL (f, x + h) - GSL_FN_EVAL (f, x)) / h;\n *abserr = fabs (10.0 * a2 * h);\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_diff_central (const gsl_function * f,\n double x, double *result, double *abserr)\n{\n /* Construct a divided difference table with a fairly large step\n size to get a very rough estimate of f'''. Use this to estimate\n the step size which will minimize the error in calculating f'. */\n\n int i, k;\n double h = GSL_SQRT_DBL_EPSILON;\n double a[4], d[4], a3;\n\n /* Algorithm based on description on pg. 204 of Conte and de Boor\n (CdB) - coefficients of Newton form of polynomial of degree 3. */\n\n for (i = 0; i < 4; i++)\n {\n a[i] = x + (i - 2.0) * h;\n d[i] = GSL_FN_EVAL (f, a[i]);\n }\n\n for (k = 1; k < 5; k++)\n {\n for (i = 0; i < 4 - k; i++)\n {\n d[i] = (d[i + 1] - d[i]) / (a[i + k] - a[i]);\n }\n }\n\n /* Adapt procedure described on pg. 282 of CdB to find best\n value of step size. */\n\n a3 = fabs (d[0] + d[1] + d[2] + d[3]);\n\n if (a3 < 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n a3 = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n h = pow (GSL_SQRT_DBL_EPSILON / (2.0 * a3), 1.0 / 3.0);\n\n if (h > 100.0 * GSL_SQRT_DBL_EPSILON)\n {\n h = 100.0 * GSL_SQRT_DBL_EPSILON;\n }\n\n *result = (GSL_FN_EVAL (f, x + h) - GSL_FN_EVAL (f, x - h)) / (2.0 * h);\n *abserr = fabs (100.0 * a3 * h * h);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "83aae18b7fb8b822fa824fc1713e2f4f8d58472d", "size": 4770, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/diff/diff.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/diff/diff.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/diff/diff.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.3535911602, "max_line_length": 81, "alphanum_fraction": 0.5805031447, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6081595662578807}} {"text": "/*\n * test_suite.h\n *\n * Created on: Oct 16, 2013\n * Author: vbonnici\n */\n\n#ifndef TEST_SUITE_H_\n#define TEST_SUITE_H_\n\n\n/*\n * a set of functions for binomial tests, or other distribution\n */\n\n//#define DEBUG_TEST_SUITE_H_\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"data_ts.h\"\n\n#include \n#include \n\n\nnamespace dolierlib{\n\n\n/*\n * Pietro's binomial test\n */\ninline\ndouble dolier_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){\n\tdouble p = (double)b_dcount / (double)b_total;\n\tdouble result = 0;\n\tfor(usize_t i = f_dcount; i<=f_total; i++){\n\t\tresult += gsl_ran_binomial_pdf(static_cast(i), p, static_cast(f_total));\n\t}\n\treturn result;\n}\n\n\n/*\n * a more efficient binomial test, thanks to gsl\n */\ninline\ndouble dolier_binomial_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){\n\tdouble p = (double)b_dcount / (double)b_total;\n\t//return gsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total));\n\treturn gsl_ran_binomial_pdf(static_cast(f_dcount), p, static_cast(f_total))\n\t\t\t+ gsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total));\n}\n\n\n/*\n * Pietro's binomial test with Bon Ferroni correction\n */\ninline\ndouble dolier_binomial_bonf(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){\n\tdouble p = (double)b_dcount / (double)b_total;\n\tdouble result = 0;\n\tfor(usize_t i = f_dcount; i<=f_total; i++){\n\t\tresult += gsl_ran_binomial_pdf(static_cast(i), p, static_cast(f_total));\n\t}\n\treturn double(nof_kmers) * result;\n}\n\n\n/*\n * a more efficient binomial test with Bon Ferroni correction, thanks to gsl\n */\ninline\ndouble dolier_binomial_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){\n\tdouble p = (double)b_dcount / (double)b_total;\n\t//return gsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total)) * nof_kmers;\n\treturn (\n\t\t\tgsl_ran_binomial_pdf(static_cast(f_dcount), p, static_cast(f_total))\n\t\t\t+\n\t\t\tgsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total))\n\t\t\t)\n\t\t\t* nof_kmers;\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 * other distributions tried during tests\n */\n\n\n\n\ninline\ndouble dolier_poisson_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){\n\tdouble p = (double)b_dcount / (double)b_total;\n\tdouble mu = p * static_cast(f_total);\n\treturn gsl_ran_poisson_pdf(static_cast(f_dcount),mu)\n\t\t\t+ gsl_cdf_poisson_Q(static_cast(f_dcount), mu);\n//\treturn gsl_ran_binomial_pdf(static_cast(f_dcount), p, static_cast(f_total))\n//\t\t\t+ gsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total));\n}\n\ninline\ndouble dolier_poisson_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){\n\tdouble p = (double)b_dcount / (double)b_total;\n\tdouble mu = p * static_cast(f_total);\n\tif(mu==0) std::cout<<\"#mu=0#\\t\"<(f_dcount),mu)\n\t\t\t\t+ gsl_cdf_poisson_Q(static_cast(f_dcount), mu))\n\t\t\t* nof_kmers;\n//\treturn (\n//\t\t\tgsl_ran_binomial_pdf(static_cast(f_dcount), p, static_cast(f_total))\n//\t\t\t+\n//\t\t\tgsl_cdf_binomial_Q(static_cast(f_dcount), p, static_cast(f_total))\n//\t\t\t)\n//\t\t\t* nof_kmers;\n}\n\n\n\ninline\ndouble dolier_poisson_mu1_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){\n\treturn gsl_ran_poisson_pdf(static_cast(f_dcount),1)\n\t\t\t+ gsl_cdf_poisson_Q(static_cast(f_dcount), 1);\n}\ninline\ndouble dolier_poisson_mu1_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){\n\treturn \t\t(gsl_ran_poisson_pdf(static_cast(f_dcount),1)\n\t\t\t\t+ gsl_cdf_poisson_Q(static_cast(f_dcount), 1))\n\t\t\t* nof_kmers;\n}\n\n\n\n\n\nconst double SQRT_PI = sqrt(3.141592653589793238462);\n\ninline\ndouble dolier_normal(double x, double sigma, double mu){\n\treturn (1/(sigma * SQRT_PI))*(exp(-(((x-mu)*(x-mu)) / (2*sigma*sigma))));\n}\n\n\ninline\ndouble dolier_approx_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){\n\tdouble p = (double)b_dcount / (double)b_total;\n\tdouble result = 0;\n\n\tdouble np = static_cast(f_total) * p;\n\tdouble npp = np * (1-p);\n\n\tfor(usize_t i = f_dcount; i<=f_total; i++){\n\t\tresult += dolier_normal(static_cast(i), np, npp);\n\t}\n\treturn result;\n}\n\n\n\n\ninline\ndouble dolier_binomial(unsigned int x, double p, unsigned int total){\n\treturn gsl_ran_binomial_pdf(x, p, total);\n}\n\ninline\ndouble dolier_normall(unsigned int x, double p, unsigned int total){\n\tdouble np = static_cast(total) * p;\n\tdouble npp = np * (1-p);\n\treturn dolier_normal(static_cast(x), np, npp);\n}\n\n\n\n}\n\n\n\n#endif /* TEST_SUITE_H_ */\n", "meta": {"hexsha": "93211e10d2f6959c5337de03a4984f285f76d419", "size": 5468, "ext": "h", "lang": "C", "max_stars_repo_path": "dolierlib/test_suite.h", "max_stars_repo_name": "vbonnici/DoLiER", "max_stars_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "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": "dolierlib/test_suite.h", "max_issues_repo_name": "vbonnici/DoLiER", "max_issues_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "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": "dolierlib/test_suite.h", "max_forks_repo_name": "vbonnici/DoLiER", "max_forks_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26", "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.2884615385, "max_line_length": 152, "alphanum_fraction": 0.737746891, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6075819353729156}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// FFT of NFW profile from White '01\ndouble rho_NFW_fft(double k, double M_vir, double z, int mode, cosmo_info **cosmo) {\n double c_vir;\n double R_vir;\n double r_s;\n double z_k;\n double g_c;\n double rho_o;\n double x1;\n double x2;\n double Ci1;\n double Ci2;\n double Si1;\n double Si2;\n double r_val;\n set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);\n r_s = R_vir / c_vir;\n z_k = k * r_s;\n g_c = 1. / (log(1. + c_vir) - c_vir / (1. + c_vir));\n rho_o = M_vir * g_c / (FOUR_PI * r_s * r_s * r_s);\n x1 = 1. + c_vir;\n x2 = c_vir * z_k;\n Ci1 = gsl_sf_Ci((1. + c_vir) * z_k);\n Si1 = gsl_sf_Si((1. + c_vir) * z_k);\n Ci2 = gsl_sf_Ci(z_k);\n Si2 = gsl_sf_Si(z_k);\n r_val = (FOUR_PI * rho_o * r_s * r_s * r_s / M_vir) * (cos(z_k) * (Ci1 - Ci2) + sin(z_k) * (Si1 - Si2) - sin(c_vir * z_k) / (z_k * (1. + c_vir)));\n return (r_val);\n}\n", "meta": {"hexsha": "14d1c041609e0172852b3c36591647741a52077c", "size": 1108, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW_fft.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": 28.4102564103, "max_line_length": 150, "alphanum_fraction": 0.5758122744, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9637799415341644, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.6069641343039268}} {"text": "/* linalg/cod.c\n * \n * Copyright (C) 2016, 2017 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * This module contains routines for factoring an M-by-N matrix A as:\n *\n * A P = Q R Z^T\n *\n * known as the Complete Orthogonal Decomposition, where:\n *\n * P is a N-by-N permutation matrix\n * Q is M-by-M orthogonal\n * R has an r-by-r upper triangular block\n * Z is N-by-N orthogonal\n *\n * When A is full rank, Z = I and this becomes the QR decomposition\n * with column pivoting. When A is rank deficient, then\n *\n * R = [ R11 0 ] where R11 is r-by-r and r = rank(A)\n * [ 0 0 ]\n */\n\nstatic int cod_RZ(gsl_matrix * A, gsl_vector * tau);\nstatic double cod_householder_transform(double *alpha, gsl_vector * v);\nstatic int cod_householder_mh(const double tau, const gsl_vector * v,\n gsl_matrix * A, gsl_vector * work);\nstatic int cod_householder_hv(const double tau, const gsl_vector * v, gsl_vector * w);\nstatic int cod_householder_Zvec(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank,\n gsl_vector * v);\nstatic int cod_trireg_solve(const gsl_matrix * R, const double lambda, const gsl_vector * b,\n gsl_matrix * S, gsl_vector * x, gsl_vector * work);\n\nint\ngsl_linalg_COD_decomp_e(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z,\n gsl_permutation * p, double tol, size_t * rank, gsl_vector * work)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (tau_Q->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau_Q must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (tau_Z->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau_Z must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (p->size != N)\n {\n GSL_ERROR (\"permutation size must be N\", GSL_EBADLEN);\n }\n else if (work->size != N)\n {\n GSL_ERROR (\"work size must be N\", GSL_EBADLEN);\n }\n else\n {\n int status, signum;\n size_t r;\n\n /* decompose: A P = Q R */\n status = gsl_linalg_QRPT_decomp(A, tau_Q, p, &signum, work);\n if (status)\n return status;\n\n /* estimate rank of A */\n r = gsl_linalg_QRPT_rank(A, tol);\n\n if (r < N)\n {\n /*\n * matrix is rank-deficient, so that the R factor is\n *\n * R = [ R11 R12 ] =~ [ R11 R12 ]\n * [ 0 R22 ] [ 0 0 ]\n *\n * compute RZ decomposition of upper trapezoidal matrix\n * [ R11 R12 ] = [ R11~ 0 ] Z\n */\n gsl_matrix_view R_upper = gsl_matrix_submatrix(A, 0, 0, r, N);\n gsl_vector_view t = gsl_vector_subvector(tau_Z, 0, r);\n\n cod_RZ(&R_upper.matrix, &t.vector);\n }\n\n *rank = r;\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_COD_decomp(gsl_matrix * A, gsl_vector * tau_Q, gsl_vector * tau_Z,\n gsl_permutation * p, size_t * rank, gsl_vector * work)\n{\n return gsl_linalg_COD_decomp_e(A, tau_Q, tau_Z, p, -1.0, rank, work);\n}\n\n/*\ngsl_linalg_COD_lssolve()\n Find the least squares solution to the overdetermined system \n\nmin ||b - A x||^2\n\nfor M >= N using the COD factorization A P = Q R Z\n\nInputs: QRZT - matrix A, in COD compressed format, M-by-N\n tau_Q - Householder scalars for Q, length min(M,N)\n tau_Z - Householder scalars for Z, length min(M,N)\n perm - permutation matrix\n rank - rank of A\n b - rhs vector, length M\n x - (output) solution vector, length N\n residual - (output) residual vector, b - A x, length M\n*/\n\nint\ngsl_linalg_COD_lssolve (const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z,\n const gsl_permutation * perm, const size_t rank, const gsl_vector * b,\n gsl_vector * x, gsl_vector * residual)\n{\n const size_t M = QRZT->size1;\n const size_t N = QRZT->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"QRZT 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 (rank > GSL_MIN (M, N))\n {\n GSL_ERROR (\"rank must be <= MIN(M,N)\", 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 R11 = gsl_matrix_const_submatrix (QRZT, 0, 0, rank, rank);\n gsl_vector_view QTb1 = gsl_vector_subvector(residual, 0, rank);\n gsl_vector_view x1 = gsl_vector_subvector(x, 0, rank);\n\n gsl_vector_set_zero(x);\n\n /* compute residual = Q^T b = [ c1 ; c2 ] */\n gsl_vector_memcpy(residual, b);\n gsl_linalg_QR_QTvec (QRZT, tau_Q, residual);\n\n /* solve x1 := R11^{-1} (Q^T b)(1:r) */\n gsl_vector_memcpy(&(x1.vector), &(QTb1.vector));\n gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &(R11.matrix), &(x1.vector));\n\n /* compute Z ( R11^{-1} x1; 0 ) */\n cod_householder_Zvec(QRZT, tau_Z, rank, x);\n\n /* compute x = P Z^T ( R11^{-1} x1; 0 ) */\n gsl_permute_vector_inverse(perm, x);\n\n /* compute residual = b - A x = Q (Q^T b - R [ R11^{-1} x1; 0 ]) = Q [ 0 ; c2 ] */\n gsl_vector_set_zero(&(QTb1.vector));\n gsl_linalg_QR_Qvec(QRZT, tau_Q, residual);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_COD_lssolve2()\n Find the least squares solution to the Tikhonov regularized\nsystem in standard form:\n\nmin ||b - A x||^2 + lambda^2 ||x||^2\n\nfor M >= N using the COD factorization A P = Q R Z\n\nInputs: lambda - parameter\n QRZT - matrix A, in COD compressed format, M-by-N\n tau_Q - Householder scalars for Q, length min(M,N)\n tau_Z - Householder scalars for Z, length min(M,N)\n perm - permutation matrix\n rank - rank of A\n b - rhs vector, length M\n x - (output) solution vector, length N\n residual - (output) residual vector, b - A x, length M\n S - workspace, rank-by-rank\n work - workspace, length rank\n*/\n\nint\ngsl_linalg_COD_lssolve2 (const double lambda, const gsl_matrix * QRZT, const gsl_vector * tau_Q, const gsl_vector * tau_Z,\n const gsl_permutation * perm, const size_t rank, const gsl_vector * b,\n gsl_vector * x, gsl_vector * residual, gsl_matrix * S, gsl_vector * work)\n{\n const size_t M = QRZT->size1;\n const size_t N = QRZT->size2;\n\n if (M < N)\n {\n GSL_ERROR (\"QRZT 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 (rank > GSL_MIN (M, N))\n {\n GSL_ERROR (\"rank must be <= MIN(M,N)\", 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 if (S->size1 != rank || S->size2 != rank)\n {\n GSL_ERROR (\"S must be rank-by-rank\", GSL_EBADLEN);\n }\n else if (work->size != rank)\n {\n GSL_ERROR (\"work must be length rank\", GSL_EBADLEN);\n }\n else\n {\n gsl_matrix_const_view R11 = gsl_matrix_const_submatrix (QRZT, 0, 0, rank, rank);\n gsl_vector_view c1 = gsl_vector_subvector(residual, 0, rank);\n gsl_vector_view y1 = gsl_vector_subvector(x, 0, rank);\n\n gsl_vector_set_zero(x);\n\n /* compute residual = Q^T b = [ c1 ; c2 ]*/\n gsl_vector_memcpy(residual, b);\n gsl_linalg_QR_QTvec (QRZT, tau_Q, residual);\n\n /* solve [ R11 ; lambda*I ] y1 = [ (Q^T b)(1:r) ; 0 ] */\n cod_trireg_solve(&(R11.matrix), lambda, &(c1.vector), S, &(y1.vector), work);\n\n /* save y1 for later residual calculation */\n gsl_vector_memcpy(work, &(y1.vector));\n\n /* compute Z [ y1; 0 ] */\n cod_householder_Zvec(QRZT, tau_Z, rank, x);\n\n /* compute x = P Z^T ( y1; 0 ) */\n gsl_permute_vector_inverse(perm, x);\n\n /* compute residual = b - A x = Q (Q^T b - [ R11 y1; 0 ]) = Q [ c1 - R11*y1 ; c2 ] */\n\n /* work = R11*y1 */\n gsl_blas_dtrmv(CblasUpper, CblasNoTrans, CblasNonUnit, &(R11.matrix), work);\n\n gsl_vector_sub(&(c1.vector), work);\n gsl_linalg_QR_Qvec(QRZT, tau_Q, residual);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_COD_unpack()\n Unpack encoded COD decomposition into the matrices Q,R,Z,P\n\nInputs: QRZT - encoded COD decomposition\n tau_Q - Householder scalars for Q\n tau_Z - Householder scalars for Z\n rank - rank of matrix (as determined from gsl_linalg_COD_decomp)\n Q - (output) M-by-M matrix Q\n R - (output) M-by-N matrix R\n Z - (output) N-by-N matrix Z\n*/\n\nint\ngsl_linalg_COD_unpack(const gsl_matrix * QRZT, const gsl_vector * tau_Q,\n const gsl_vector * tau_Z, const size_t rank, gsl_matrix * Q,\n gsl_matrix * R, gsl_matrix * Z)\n{\n const size_t M = QRZT->size1;\n const size_t N = QRZT->size2;\n\n if (tau_Q->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau_Q must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (tau_Z->size != GSL_MIN (M, N))\n {\n GSL_ERROR (\"size of tau_Z must be MIN(M,N)\", GSL_EBADLEN);\n }\n else if (rank > GSL_MIN (M, N))\n {\n GSL_ERROR (\"rank must be <= MIN(M,N)\", GSL_EBADLEN);\n }\n else if (Q->size1 != M || Q->size2 != M)\n {\n GSL_ERROR (\"Q must by M-by-M\", GSL_EBADLEN);\n }\n else if (R->size1 != M || R->size2 != N)\n {\n GSL_ERROR (\"R must by M-by-N\", GSL_EBADLEN);\n }\n else if (Z->size1 != N || Z->size2 != N)\n {\n GSL_ERROR (\"Z must by N-by-N\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n gsl_matrix_view R11 = gsl_matrix_submatrix(R, 0, 0, rank, rank);\n gsl_matrix_const_view QRZT11 = gsl_matrix_const_submatrix(QRZT, 0, 0, rank, rank);\n\n /* form Q matrix */\n\n gsl_matrix_set_identity(Q);\n\n for (i = GSL_MIN (M, N); i-- > 0;)\n {\n gsl_vector_const_view h = gsl_matrix_const_subcolumn (QRZT, i, 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_Q, i);\n gsl_linalg_householder_hm (ti, &h.vector, &m.matrix);\n }\n\n /* form Z matrix */\n gsl_matrix_set_identity(Z);\n\n if (rank < N)\n {\n gsl_vector_view work = gsl_matrix_row(R, 0); /* temporary workspace, size N */\n\n /* multiply I by Z from the right */\n gsl_linalg_COD_matZ(QRZT, tau_Z, rank, Z, &work.vector);\n }\n\n /* copy rank-by-rank upper triangle of QRZT into R and zero the rest */\n gsl_matrix_set_zero(R);\n gsl_matrix_tricpy('U', 1, &R11.matrix, &QRZT11.matrix);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_linalg_COD_matZ\n Multiply an M-by-N matrix A on the right by Z (N-by-N)\n\nInputs: QRZT - encoded COD matrix\n tau_Z - Householder scalars for Z\n rank - matrix rank\n A - on input, M-by-N matrix\n on output, A * Z\n work - workspace of length M\n*/\n\nint\ngsl_linalg_COD_matZ(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank,\n gsl_matrix * A, gsl_vector * work)\n{\n const size_t M = A->size1;\n const size_t N = A->size2;\n\n if (tau_Z->size != GSL_MIN (QRZT->size1, QRZT->size2))\n {\n GSL_ERROR(\"tau_Z must be GSL_MIN(M,N)\", GSL_EBADLEN);\n }\n else if (QRZT->size2 != N)\n {\n GSL_ERROR(\"QRZT must have N columns\", GSL_EBADLEN);\n }\n else if (work->size != M)\n {\n GSL_ERROR(\"workspace must be length M\", GSL_EBADLEN);\n }\n else\n {\n /* if rank == N, then Z = I and there is nothing to do */\n if (rank < N)\n {\n size_t i;\n\n for (i = rank; i > 0 && i--; )\n {\n gsl_vector_const_view h = gsl_matrix_const_subrow (QRZT, i, rank, N - rank);\n gsl_matrix_view m = gsl_matrix_submatrix (A, 0, i, M, N - i);\n double ti = gsl_vector_get (tau_Z, i);\n cod_householder_mh (ti, &h.vector, &m.matrix, work);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n\n/*********************************************\n * INTERNAL ROUTINES *\n *********************************************/\n\n/*\ncod_RZ()\n Perform RZ decomposition of an upper trapezoidal matrix,\n\nA = [ A11 A12 ] = [ R 0 ] Z\n\nwhere A is M-by-N with N >= M, A11 is M-by-M upper triangular,\nand A12 is M-by-(N-M). On output, Z is stored as Householder\nreflectors in the A12 portion of A,\n\nZ = Z(1) Z(2) ... Z(M)\n\nInputs: A - M-by-N matrix with N >= M\n On input, upper trapezoidal matrix [ A11 A12 ]\n On output, A11 is overwritten by R (subdiagonal elements\n are not touched), and A12 is overwritten by Z in packed storage\n tau - (output) Householder scalars, size M\n*/\n\nstatic int\ncod_RZ(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 != M)\n {\n GSL_ERROR(\"tau has wrong size\", GSL_EBADLEN);\n }\n else if (N < M)\n {\n GSL_ERROR(\"N must be >= M\", GSL_EINVAL);\n }\n else if (M == N)\n {\n /* quick return */\n gsl_vector_set_all(tau, 0.0);\n return GSL_SUCCESS;\n }\n else\n {\n size_t k;\n\n for (k = M; k > 0 && k--; )\n {\n double *alpha = gsl_matrix_ptr(A, k, k);\n gsl_vector_view z = gsl_matrix_subrow(A, k, M, N - M);\n double tauk;\n\n /* compute Householder reflection to zero [ A(k,k) A(k,M+1:N) ] */\n tauk = cod_householder_transform(alpha, &z.vector);\n gsl_vector_set(tau, k, tauk);\n\n if ((tauk != 0) && (k > 0))\n {\n gsl_vector_view w = gsl_vector_subvector(tau, 0, k);\n gsl_matrix_view B = gsl_matrix_submatrix(A, 0, k, k, N - k);\n\n cod_householder_mh(tauk, &z.vector, &B.matrix, &w.vector);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\nstatic double\ncod_householder_transform(double *alpha, gsl_vector * v)\n{\n double beta, tau;\n double xnorm = gsl_blas_dnrm2(v);\n\n if (xnorm == 0)\n {\n return 0.0; /* tau = 0 */\n }\n\n beta = - (*alpha >= 0.0 ? +1.0 : -1.0) * gsl_hypot(*alpha, xnorm);\n tau = (beta - *alpha) / beta;\n\n {\n double s = (*alpha - beta);\n \n if (fabs(s) > GSL_DBL_MIN) \n {\n gsl_blas_dscal (1.0 / s, v);\n }\n else\n {\n gsl_blas_dscal (GSL_DBL_EPSILON / s, v);\n gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);\n }\n\n *alpha = beta;\n }\n \n return tau;\n}\n\n/*\ncod_householder_hv\n Apply Householder reflection H = (I - tau*v*v') to vector v from the left,\n\nw' = H * w\n\nInputs: tau - Householder scalar\n v - Householder vector, size M\n w - on input, w vector, size M\n on output, H * w\n\nNotes:\n1) Based on LAPACK routine DLARZ\n*/\n\nstatic int\ncod_householder_hv(const double tau, const gsl_vector * v, gsl_vector * w)\n{\n if (tau == 0)\n {\n return GSL_SUCCESS; /* H = I */\n }\n else\n {\n const size_t M = w->size;\n const size_t L = v->size;\n double w0 = gsl_vector_get(w, 0);\n gsl_vector_view w1 = gsl_vector_subvector(w, M - L, L);\n double d1, d;\n\n /* d1 := v . w(M-L:M) */\n gsl_blas_ddot(v, &w1.vector, &d1);\n\n /* d := w(1) + v . w(M-L:M) */\n d = w0 + d1;\n\n /* w(1) = w(1) - tau * d */\n gsl_vector_set(w, 0, w0 - tau * d);\n\n /* w(M-L:M) = w(M-L:M) - tau * d * v */\n gsl_blas_daxpy(-tau * d, v, &w1.vector);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ncod_householder_mh\n Apply Householder reflection H = (I - tau*v*v') to matrix A from the right\n\nInputs: tau - Householder scalar\n v - Householder vector, size N-M\n A - matrix, size M-by-N\n work - workspace, size M\n\nNotes:\n1) Based on LAPACK routine DLARZ\n*/\n\nstatic int\ncod_householder_mh(const double tau, const gsl_vector * v, gsl_matrix * A,\n gsl_vector * work)\n{\n if (tau == 0)\n {\n return GSL_SUCCESS; /* H = I */\n }\n else\n {\n const size_t M = A->size1;\n const size_t N = A->size2;\n const size_t L = v->size;\n gsl_vector_view A1 = gsl_matrix_subcolumn(A, 0, 0, M);\n gsl_matrix_view C = gsl_matrix_submatrix(A, 0, N - L, M, L);\n\n /* work(1:M) = A(1:M,1) */\n gsl_vector_memcpy(work, &A1.vector);\n\n /* work(1:M) = work(1:M) + A(1:M,M+1:N) * v(1:N-M) */\n gsl_blas_dgemv(CblasNoTrans, 1.0, &C.matrix, v, 1.0, work);\n\n /* A(1:M,1) = A(1:M,1) - tau * work(1:M) */\n gsl_blas_daxpy(-tau, work, &A1.vector);\n\n /* A(1:M,M+1:N) = A(1:M,M+1:N) - tau * work(1:M) * v(1:N-M)' */\n gsl_blas_dger(-tau, work, v, &C.matrix);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ncod_householder_Zvec\n Multiply a vector by Z\n\nInputs: QRZT - encoded COD matrix\n tau_Z - Householder scalars for Z\n rank - matrix rank\n v - on input, vector of length N\n on output, Z^T * v\n*/\n\nstatic int\ncod_householder_Zvec(const gsl_matrix * QRZT, const gsl_vector * tau_Z, const size_t rank,\n gsl_vector * v)\n{\n const size_t M = QRZT->size1;\n const size_t N = QRZT->size2;\n\n if (tau_Z->size != GSL_MIN (M, N))\n {\n GSL_ERROR(\"tau_Z must be GSL_MIN(M,N)\", GSL_EBADLEN);\n }\n else if (v->size != N)\n {\n GSL_ERROR(\"v must be length N\", GSL_EBADLEN);\n }\n else\n {\n if (rank < N)\n {\n size_t i;\n\n for (i = 0; i < rank; ++i)\n {\n gsl_vector_const_view h = gsl_matrix_const_subrow (QRZT, i, rank, N - rank);\n gsl_vector_view w = gsl_vector_subvector (v, i, N - i);\n double ti = gsl_vector_get (tau_Z, i);\n cod_householder_hv(ti, &h.vector, &w.vector);\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ncod_trireg_solve()\n\n This function computes the solution to the least squares system\n\n [ R ] x = [ b ]\n [ lambda*I ] [ 0 ]\n\nwhere R is an N-by-N upper triangular matrix, lambda is a scalar parameter,\nand b is a vector of length N. This is done by computing the QR factorization\n\n[ R ] = W S^T\n[ lambda*I ]\n\nwhere S^T is upper triangular, and solving\n\nS^T x = W^T [ b ]\n [ 0 ]\n\nInputs: R - full rank upper triangular matrix; the diagonal\n elements are modified but restored on output\n lambda - scalar parameter lambda\n b - right hand side vector b\n S - workspace, N-by-N\n x - (output) least squares solution of the system\n work - workspace of length N\n*/\n\nstatic int\ncod_trireg_solve (const gsl_matrix * R, const double lambda, const gsl_vector * b,\n gsl_matrix * S, gsl_vector * x, gsl_vector * work)\n{\n const size_t N = R->size2;\n gsl_vector_const_view diag = gsl_matrix_const_diagonal(R);\n size_t i, j, k;\n\n if (lambda <= 0.0)\n {\n GSL_ERROR(\"lambda must be positive\", GSL_EINVAL);\n }\n\n /* copy R and b to preserve input and initialise S; store diag(R) in work */\n gsl_matrix_transpose_tricpy('U', 0, S, R);\n gsl_vector_memcpy(work, &diag.vector);\n gsl_vector_memcpy(x, b);\n\n /* eliminate the diagonal matrix lambda*I using Givens rotations */\n\n for (j = 0; j < N; j++)\n {\n double bj = 0.0;\n\n gsl_matrix_set (S, j, j, lambda);\n\n for (k = j + 1; k < N; k++)\n {\n gsl_matrix_set (S, k, k, 0.0);\n }\n\n /* the transformations to eliminate the row of lambda*I modify only a\n single element of b beyond the first n, which is initially\n zero */\n\n for (k = j; k < N; k++)\n {\n /* determine a Givens rotation which eliminates the\n appropriate element in the current row of lambda*I */\n\n double sine, cosine;\n\n double xk = gsl_vector_get (x, k);\n double rkk = gsl_vector_get (work, k);\n double skk = gsl_matrix_get (S, k, k);\n\n if (skk == 0)\n {\n continue;\n }\n\n if (fabs (rkk) < fabs (skk))\n {\n double cotangent = rkk / skk;\n sine = 0.5 / sqrt (0.25 + 0.25 * cotangent * cotangent);\n cosine = sine * cotangent;\n }\n else\n {\n double tangent = skk / rkk;\n cosine = 0.5 / sqrt (0.25 + 0.25 * tangent * tangent);\n sine = cosine * tangent;\n }\n\n /* Compute the modified diagonal element of r and the\n modified element of [b,0] */\n\n {\n double new_rkk = cosine * rkk + sine * skk;\n double new_xk = cosine * xk + sine * bj;\n \n bj = -sine * xk + cosine * bj;\n\n gsl_vector_set(work, k, new_rkk);\n gsl_matrix_set(S, k, k, new_rkk);\n gsl_vector_set(x, k, new_xk);\n }\n\n /* Accumulate the transformation in the row of s */\n\n for (i = k + 1; i < N; i++)\n {\n double sik = gsl_matrix_get (S, i, k);\n double sii = gsl_matrix_get (S, i, i);\n \n double new_sik = cosine * sik + sine * sii;\n double new_sii = -sine * sik + cosine * sii;\n\n gsl_matrix_set(S, i, k, new_sik);\n gsl_matrix_set(S, i, i, new_sii);\n }\n }\n }\n\n /* solve: S^T x = rhs in place */\n gsl_blas_dtrsv(CblasLower, CblasTrans, CblasNonUnit, S, x);\n\n return GSL_SUCCESS;\n}\n", "meta": {"hexsha": "53d12e81732c25357371464d363e3f921107a83f", "size": 22516, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/linalg/cod.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/cod.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/cod.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3220125786, "max_line_length": 122, "alphanum_fraction": 0.5670634216, "num_tokens": 6625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6068640380638407}} {"text": "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n#include \n#include \n\n#include \"php_ext.h\"\n#include \"kernel/operators.h\"\n\nvoid tensor_matmul(zval * return_value, zval * a, zval * b)\n{\n unsigned int i, j;\n Bucket * row;\n zval rowC, c;\n\n zend_zephir_globals_def * zephir_globals = ZEPHIR_VGLOBAL;\n\n openblas_set_num_threads(zephir_globals->num_threads);\n\n zend_array * aHat = Z_ARR_P(a);\n zend_array * bHat = Z_ARR_P(b);\n\n Bucket * ba = aHat->arData;\n Bucket * bb = bHat->arData;\n\n unsigned int m = zend_array_count(aHat);\n unsigned int p = zend_array_count(bHat);\n unsigned int n = zend_array_count(Z_ARR(bb[0].val));\n\n double * va = emalloc(m * p * sizeof(double));\n double * vb = emalloc(n * p * sizeof(double));\n double * vc = emalloc(m * n * sizeof(double));\n\n for (i = 0; i < m; ++i) {\n row = Z_ARR(ba[i].val)->arData;\n\n for (j = 0; j < p; ++j) {\n va[i * p + j] = zephir_get_doubleval(&row[j].val);\n }\n }\n\n for (i = 0; i < p; ++i) {\n row = Z_ARR(bb[i].val)->arData;\n\n for (j = 0; j < n; ++j) {\n vb[i * n + j] = zephir_get_doubleval(&row[j].val);\n }\n }\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, p, 1.0, va, p, vb, n, 0.0, vc, n);\n\n array_init_size(&c, m);\n\n for (i = 0; i < m; ++i) {\n array_init_size(&rowC, n);\n\n for (j = 0; j < n; ++j) {\n add_next_index_double(&rowC, vc[i * n + j]);\n }\n\n add_next_index_zval(&c, &rowC);\n }\n\n RETVAL_ARR(Z_ARR(c));\n\n efree(va);\n efree(vb);\n efree(vc);\n}\n\nvoid tensor_dot(zval * return_value, zval * a, zval * b)\n{\n unsigned int i;\n\n zend_array * aHat = Z_ARR_P(a);\n zend_array * bHat = Z_ARR_P(b);\n\n Bucket * ba = aHat->arData;\n Bucket * bb = bHat->arData;\n\n unsigned int n = zend_array_count(aHat);\n\n double sigma = 0.0;\n\n for (i = 0; i < n; ++i) {\n sigma += zephir_get_doubleval(&ba[i].val) * zephir_get_doubleval(&bb[i].val);\n }\n\n RETVAL_DOUBLE(sigma);\n}\n\nvoid tensor_inverse(zval * return_value, zval * a)\n{\n unsigned int i, j;\n Bucket * row;\n zval rowB, b;\n\n zend_zephir_globals_def * zephir_globals = ZEPHIR_VGLOBAL;\n\n openblas_set_num_threads(zephir_globals->num_threads);\n\n zend_array * aHat = Z_ARR_P(a);\n\n Bucket * ba = aHat->arData;\n\n unsigned int n = zend_array_count(aHat);\n\n double * va = emalloc(n * n * sizeof(double));\n\n for (i = 0; i < n; ++i) {\n row = Z_ARR(ba[i].val)->arData;\n\n for (j = 0; j < n; ++j) {\n va[i * n + j] = zephir_get_doubleval(&row[j].val);\n }\n }\n\n lapack_int status;\n\n int pivots[n];\n\n status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots);\n\n if (status != 0) {\n RETURN_NULL();\n }\n \n status = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, va, n, pivots);\n\n if (status != 0) {\n RETURN_NULL();\n }\n\n array_init_size(&b, n);\n\n for (i = 0; i < n; ++i) {\n array_init_size(&rowB, n);\n\n for (j = 0; j < n; ++j) {\n add_next_index_double(&rowB, va[i * n + j]);\n }\n\n add_next_index_zval(&b, &rowB);\n }\n\n RETVAL_ARR(Z_ARR(b));\n\n efree(va);\n}\n", "meta": {"hexsha": "53c62228a83df7cfa4b4272508a82e0f645b667b", "size": 3243, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/include/linear_algebra.c", "max_stars_repo_name": "remicollet/Tensor", "max_stars_repo_head_hexsha": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "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": "ext/include/linear_algebra.c", "max_issues_repo_name": "remicollet/Tensor", "max_issues_repo_head_hexsha": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "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": "ext/include/linear_algebra.c", "max_forks_repo_name": "remicollet/Tensor", "max_forks_repo_head_hexsha": "2dd4fd8c14feb570c1efb611848ee7ba0a5d8b19", "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.3355263158, "max_line_length": 99, "alphanum_fraction": 0.5519580635, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6066564737480938}} {"text": "/* integration/err.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\nstatic double rescale_error (double err, const double result_abs, const double result_asc) ;\n\nstatic double\nrescale_error (double err, const double result_abs, const double result_asc)\n{\n err = fabs(err) ;\n\n if (result_asc != 0 && err != 0)\n {\n double scale = pow((200 * err / result_asc), 1.5) ;\n \n if (scale < 1)\n {\n err = result_asc * scale ;\n }\n else \n {\n err = result_asc ;\n }\n }\n if (result_abs > GSL_DBL_MIN / (50 * GSL_DBL_EPSILON))\n {\n double min_err = 50 * GSL_DBL_EPSILON * result_abs ;\n\n if (min_err > err) \n {\n err = min_err ;\n }\n }\n \n return err ;\n}\n\n", "meta": {"hexsha": "a9f9f008824ef856bc04bf1590b9ffb30da5195c", "size": 1634, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/integration/err.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/integration/err.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/integration/err.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.6949152542, "max_line_length": 92, "alphanum_fraction": 0.6407588739, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6065120247062882}} {"text": "#include \"compute_signal.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"parameters.h\"\n\nvoid compute_signal(double * signal, const size_t length, const double delta,\n gsl_rng * r, gsl_histogram * hist){\n\n static double x0 = XINIT;\n\n puts(\"Building signal ...\");\n\n double x = x0;\n double t_begin = 0.0; //Distance from the beginning of time discretization\n //interval to current point in time\n\n for(size_t j=0; j XOVER) {x = XINIT; puts(\"Too large\");}\n if(x < 0) {x = -x; puts(\"Negative\");}\n\n delta_t = KAPPA*KAPPA/(SIGMA*SIGMA*x);\n\n gsl_histogram_accumulate(hist, x, delta_t);\n\n t_begin += delta_t; //increase distance from the beginning\n }\n\n t_begin -= delta;\n\n /* remaining part of the time step is equal to the difference of the full\n * time step and of the part of the time step outside the interval.\n * Part outside the interval is t_begin */\n sum += x*(delta_t - t_begin);\n signal[j] = sum/delta; //assign effective height to the signal.\n }\n\n x0 = x;\n}\n", "meta": {"hexsha": "91fafc8cb82d0883ba3127b778f042a1f469238a", "size": 1643, "ext": "c", "lang": "C", "max_stars_repo_path": "compute_signal.c", "max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z", "max_issues_repo_path": "compute_signal.c", "max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "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": "compute_signal.c", "max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_forks_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8245614035, "max_line_length": 77, "alphanum_fraction": 0.6378575776, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.6064062832534804}} {"text": "/* specfunc/gsl_sf_erf.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_ERF_H__\n#define __GSL_SF_ERF_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/* Complementary Error Function\n * erfc(x) := 2/Sqrt[Pi] Integrate[Exp[-t^2], {t,x,Infinity}]\n *\n * exceptions: none\n */\nint gsl_sf_erfc_e(double x, gsl_sf_result * result);\ndouble gsl_sf_erfc(double x);\n\n\n/* Log Complementary Error Function\n *\n * exceptions: none\n */\nint gsl_sf_log_erfc_e(double x, gsl_sf_result * result);\ndouble gsl_sf_log_erfc(double x);\n\n\n/* Error Function\n * erf(x) := 2/Sqrt[Pi] Integrate[Exp[-t^2], {t,0,x}]\n *\n * exceptions: none\n */\nint gsl_sf_erf_e(double x, gsl_sf_result * result);\ndouble gsl_sf_erf(double x);\n\n\n/* Probability functions:\n * Z(x) : Abramowitz+Stegun 26.2.1\n * Q(x) : Abramowitz+Stegun 26.2.3\n *\n * exceptions: none\n */\nint gsl_sf_erf_Z_e(double x, gsl_sf_result * result);\nint gsl_sf_erf_Q_e(double x, gsl_sf_result * result);\ndouble gsl_sf_erf_Z(double x);\ndouble gsl_sf_erf_Q(double x);\n\n\n/* Hazard function, also known as the inverse Mill's ratio.\n *\n * H(x) := Z(x)/Q(x)\n * = Sqrt[2/Pi] Exp[-x^2 / 2] / Erfc[x/Sqrt[2]]\n *\n * exceptions: GSL_EUNDRFLW\n */\nint gsl_sf_hazard_e(double x, gsl_sf_result * result);\ndouble gsl_sf_hazard(double x);\n\n\n__END_DECLS\n\n#endif /* __GSL_SF_ERF_H__ */\n", "meta": {"hexsha": "d63b3176e18401badace06fd91f5a76f7eee64d4", "size": 2295, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_erf.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_erf.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_erf.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": 24.9456521739, "max_line_length": 81, "alphanum_fraction": 0.7137254902, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6061353219554471}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2014 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\n#define N 5\n\nint main() {\n int i, j, info;\n double w[N];\n double a[N][N] = {\n 5, 4, 3, 2, 1,\n 4, 4, 3, 2, 1,\n 3, 3, 3, 2, 1,\n 2, 2, 2, 2, 1,\n 1, 1, 1, 1, 1 \n };\n info = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', N, a[0], N, w);\n printf(\"Eigenvalues of Frank matrix: \");\n for (i = 0; i < N; ++i) {\n printf(\" %6.2f\", w[i]);\n }\n printf(\"\\n\");\n printf(\"Eigenvectors of Frank matrix (column by column):\\n\");\n for (i = 0; i < N; ++i) {\n for (j = 0; j < N; ++j) {\n printf(\" %6.2f\", a[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}\n", "meta": {"hexsha": "82eb6520a32422a3a7780ae823698fd3ff695055", "size": 1086, "ext": "c", "lang": "C", "max_stars_repo_path": "example/cxx/dense/dsyev.c", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cxx/dense/dsyev.c", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cxx/dense/dsyev.c", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2558139535, "max_line_length": 78, "alphanum_fraction": 0.4815837937, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6061353178339731}} {"text": "/* linalg/hesstri.c\n * \n * Copyright (C) 2006, 2007 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"givens.c\"\n\n/*\n * This module contains routines related to the Hessenberg-Triangular\n * reduction of two general real matrices\n *\n * See Golub & Van Loan, \"Matrix Computations\", 3rd ed, sec 7.7.4\n */\n\n/*\ngsl_linalg_hesstri_decomp()\n Perform a reduction to generalized upper Hessenberg form.\nGiven A and B, this function overwrites A with an upper Hessenberg\nmatrix H = U^T A V and B with an upper triangular matrix R = U^T B V\nwith U and V orthogonal.\n\nSee Golub & Van Loan, \"Matrix Computations\" (3rd ed) algorithm 7.7.1\n\nInputs: A - real square matrix\n B - real square matrix\n U - (output) if non-null, U is stored here on output\n V - (output) if non-null, V is stored here on output\n work - workspace (length n)\n\nReturn: success or error\n*/\n\nint\ngsl_linalg_hesstri_decomp(gsl_matrix * A, gsl_matrix * B, gsl_matrix * U,\n gsl_matrix * V, gsl_vector * work)\n{\n const size_t N = A->size1;\n\n if ((N != A->size2) || (N != B->size1) || (N != B->size2))\n {\n GSL_ERROR (\"Hessenberg-triangular reduction requires square matrices\",\n GSL_ENOTSQR);\n }\n else if (N != work->size)\n {\n GSL_ERROR (\"length of workspace must match matrix dimension\",\n GSL_EBADLEN);\n }\n else\n {\n double cs, sn; /* rotation parameters */\n size_t i, j; /* looping */\n gsl_vector_view xv, yv; /* temporary views */\n\n /* B -> Q^T B = R (upper triangular) */\n gsl_linalg_QR_decomp(B, work);\n\n /* A -> Q^T A */\n gsl_linalg_QR_QTmat(B, work, A);\n\n /* initialize U and V if desired */\n\n if (U)\n {\n gsl_linalg_QR_unpack(B, work, U, B);\n }\n else\n {\n /* zero out lower triangle of B */\n for (j = 0; j < N - 1; ++j)\n {\n for (i = j + 1; i < N; ++i)\n gsl_matrix_set(B, i, j, 0.0);\n }\n }\n\n if (V)\n gsl_matrix_set_identity(V);\n\n if (N < 3)\n return GSL_SUCCESS; /* nothing more to do */\n\n /* reduce A and B */\n for (j = 0; j < N - 2; ++j)\n {\n for (i = N - 1; i >= (j + 2); --i)\n {\n /* step 1: rotate rows i - 1, i to kill A(i,j) */\n\n /*\n * compute G = [ CS SN ] so that G^t [ A(i-1,j) ] = [ * ]\n * [-SN CS ] [ A(i, j) ] [ 0 ]\n */\n create_givens(gsl_matrix_get(A, i - 1, j),\n gsl_matrix_get(A, i, j),\n &cs,\n &sn);\n /* invert so drot() works correctly (G -> G^t) */\n sn = -sn;\n\n /* compute G^t A(i-1:i, j:n) */\n xv = gsl_matrix_subrow(A, i - 1, j, N - j);\n yv = gsl_matrix_subrow(A, i, j, N - j);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n\n /* compute G^t B(i-1:i, i-1:n) */\n xv = gsl_matrix_subrow(B, i - 1, i - 1, N - i + 1);\n yv = gsl_matrix_subrow(B, i, i - 1, N - i + 1);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n\n if (U)\n {\n /* accumulate U: U -> U G */\n xv = gsl_matrix_column(U, i - 1);\n yv = gsl_matrix_column(U, i);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n }\n\n /* step 2: rotate columns i, i - 1 to kill B(i, i - 1) */\n\n create_givens(-gsl_matrix_get(B, i, i),\n gsl_matrix_get(B, i, i - 1),\n &cs,\n &sn);\n /* invert so drot() works correctly (G -> G^t) */\n sn = -sn;\n\n /* compute B(1:i, i-1:i) G */\n xv = gsl_matrix_subcolumn(B, i - 1, 0, i + 1);\n yv = gsl_matrix_subcolumn(B, i, 0, i + 1);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n\n /* apply to A(1:n, i-1:i) */\n xv = gsl_matrix_column(A, i - 1);\n yv = gsl_matrix_column(A, i);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n\n if (V)\n {\n /* accumulate V: V -> V G */\n xv = gsl_matrix_column(V, i - 1);\n yv = gsl_matrix_column(V, i);\n gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n} /* gsl_linalg_hesstri_decomp() */\n", "meta": {"hexsha": "59f78c9207a7b907a56da22fa37676fcde0b120f", "size": 5530, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/linalg/hesstri.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/hesstri.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/hesstri.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": 31.7816091954, "max_line_length": 81, "alphanum_fraction": 0.5014466546, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6058994268636307}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nint main() {\n\tint ret;\n\tint i, j;\n\tgsl_vector* tau;\n\tgsl_matrix *A;\n\tgsl_matrix *Q, *R, *RTR;\n\tgsl_matrix_view Rtop;\n\tint M = 4;\n\tint N = 3;\n\n\t/*\n\t gsl_matrix A;\n\t double data[9];\n\t memset(&A, 0, sizeof(gsl_matrix));\n\t A.size1 = 3;\n\t A.size2 = 3;\n\t A.tda = 3;\n\t A.data = data;\n\t gsl_matrix_set(&A, 0, 0, 34.0);\n\t gsl_matrix_set(&A, 0, 1, 4.0);\n\t gsl_matrix_set(&A, 0, 2, 14.0);\n\t gsl_matrix_set(&A, 1, 0, 1.0);\n\t gsl_matrix_set(&A, 1, 1, 8.0);\n\t gsl_matrix_set(&A, 1, 2, 3.0);\n\t gsl_matrix_set(&A, 2, 0, 7.0);\n\t gsl_matrix_set(&A, 2, 1, 1.0);\n\t gsl_matrix_set(&A, 2, 2, 8.0);\n\t*/\n\n\tA = gsl_matrix_alloc(M, N);\n\n\tfor (i=0; isize1; i++) {\n\t\tprintf((i==0) ? \"A = (\" : \" (\");\n\t\tfor (j=0; jsize2; j++) {\n\t\t\tprintf(\" %12.5g \", gsl_matrix_get(A, i, j));\n\t\t}\n\t\tprintf(\")\\n\");\n\t}\n\tprintf(\"\\n\");\n\n\ttau = gsl_vector_alloc(N);\n\n\tret = gsl_linalg_QR_decomp(A, tau);\n\n\tQ = gsl_matrix_alloc(M, M);\n\tR = gsl_matrix_alloc(M, N);\n\n\tret = gsl_linalg_QR_unpack(A, tau, Q, R);\n\n\tfor (i=0; isize1; i++) {\n\t\tprintf((i==0) ? \"Q = (\" : \" (\");\n\t\tfor (j=0; jsize2; j++) {\n\t\t\tprintf(\" %12.5g \", gsl_matrix_get(Q, i, j));\n\t\t}\n\t\tprintf(\")\\n\");\n\t}\n\tprintf(\"\\n\");\n\n\tfor (i=0; isize1; i++) {\n\t\tprintf((i==0) ? \"R = (\" : \" (\");\n\t\tfor (j=0; jsize2; j++) {\n\t\t\tprintf(\" %12.5g \", gsl_matrix_get(R, i, j));\n\t\t}\n\t\tprintf(\")\\n\");\n\t}\n\tprintf(\"\\n\");\n\n\n\tRtop = gsl_matrix_submatrix(R, 0, 0, N, N);\n\tRTR = gsl_matrix_alloc(N, N);\n\tgsl_matrix_memcpy(RTR, &(Rtop.matrix));\n\tret = gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit,\n\t\t\t\t\t\t 1.0, RTR, RTR);\n\t//(Rtop.matrix), &(Rtop.matrix));\n\n\tfor (i=0; isize1; i++) {\n\t\tprintf((i==0) ? \"RTR = (\" : \" (\");\n\t\tfor (j=0; jsize2; j++) {\n\t\t\tprintf(\" %12.5g \", gsl_matrix_get(RTR, i, j));\n\t\t}\n\t\tprintf(\")\\n\");\n\t}\n\tprintf(\"\\n\");\n\n\tgsl_matrix_free(RTR);\n\n\n\tgsl_matrix_free(Q);\n\tgsl_matrix_free(R);\n\tgsl_vector_free(tau);\n\n\tgsl_matrix_free(A);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "5b292a542ff5d487b10ffd22e948440723544a59", "size": 2275, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/qr-demo.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/qr-demo.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/qr-demo.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": 20.4954954955, "max_line_length": 70, "alphanum_fraction": 0.5586813187, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6056171991244171}} {"text": "// Copyright (c) 2021 Stig Rune Sellevag\n//\n// This file is distributed under the MIT License. See the accompanying file\n// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms\n// and conditions.\n\n#ifndef SCILIB_LINALG_EIGENVALUE_H\n#define SCILIB_LINALG_EIGENVALUE_H\n\n#ifdef USE_MKL\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Sci {\nnamespace Linalg {\n\n// Compute eigenvalues and eigenvectors of a real symmetric matrix.\ntemplate \ninline void eigs(Sci::Matrix_view a,\n Sci::Vector_view w,\n double abstol = -1.0 /* use default value */)\n{\n static_assert(a.is_contiguous());\n static_assert(w.is_contiguous());\n\n assert(a.extent(0) == a.extent(1));\n assert(w.extent(0) == a.extent(0));\n\n const BLAS_INT n = static_cast(a.extent(0));\n const BLAS_INT nselect = n;\n const BLAS_INT lda = n;\n const BLAS_INT ldz = nselect;\n\n BLAS_INT il = 1;\n BLAS_INT iu = n;\n BLAS_INT m;\n BLAS_INT info;\n\n double vl = 0.0;\n double vu = 0.0;\n\n Sci::Vector isuppz(2 * n);\n Sci::Matrix z(ldz, n);\n\n auto matrix_layout = LAPACK_ROW_MAJOR;\n if constexpr (std::is_same_v) {\n matrix_layout = LAPACK_COL_MAJOR;\n }\n\n info = LAPACKE_dsyevr(matrix_layout, 'V', 'A', 'U', n, a.data(), lda, vl,\n vu, il, iu, abstol, &m, w.data(), z.data(), ldz,\n isuppz.data());\n if (info != 0) {\n throw std::runtime_error(\"dsyevr failed\");\n }\n Sci::copy(z.view(), a);\n}\n\ntemplate \ninline void eigs(Sci::Matrix& a,\n Sci::Vector& w,\n double abstol = -1.0 /* use default value */)\n{\n eigs(a.view(), w.view(), abstol);\n}\n\n// Compute eigenvalues and eigenvectors of a real non-symmetric matrix.\ntemplate \nvoid eig(Sci::Matrix_view a,\n Sci::Matrix_view, Layout> evec,\n Sci::Vector_view, Layout> eval)\n{\n using namespace Sci;\n\n static_assert(a.is_contiguous());\n static_assert(evec.is_contiguous());\n static_assert(eval.is_contiguous());\n\n assert(a.extent(0) == a.extent(1));\n assert(a.extent(0) == eval.extent(0));\n assert(a.extent(0) == evec.extent(0));\n assert(a.extent(1) == evec.extent(1));\n\n const BLAS_INT n = static_cast(a.extent(1));\n\n Sci::Vector wr(n);\n Sci::Vector wi(n);\n Sci::Matrix vr(n, n);\n Sci::Matrix vl(n, n);\n\n auto matrix_layout = LAPACK_ROW_MAJOR;\n if constexpr (std::is_same_v) {\n matrix_layout = LAPACK_COL_MAJOR;\n }\n BLAS_INT info =\n LAPACKE_dgeev(matrix_layout, 'N', 'V', n, a.data(), n, wr.data(),\n wi.data(), vl.data(), n, vr.data(), n);\n if (info != 0) {\n throw std::runtime_error(\"dgeev failed\");\n }\n for (BLAS_INT i = 0; i < n; ++i) {\n std::complex wii(wr(i), wi(i));\n eval(i) = wii;\n BLAS_INT j = 0;\n while (j < n) {\n if (wi(j) == 0.0) {\n evec(i, j) = std::complex{vr(i, j), 0.0};\n ++j;\n }\n else {\n evec(i, j) = std::complex{vr(i, j), vr(i, j + 1)};\n evec(i, j + 1) = std::complex{vr(i, j), -vr(i, j + 1)};\n j += 2;\n }\n }\n }\n}\n\ntemplate \nvoid eig(Sci::Matrix& a,\n Sci::Matrix, Layout, Allocator_evec>& evec,\n Sci::Vector, Layout, Allocator_eval>& eval)\n{\n eig(a.view(), evec.view(), eval.view());\n}\n\n} // namespace Linalg\n} // namespace Sci\n\n#endif // SCILIB_LINALG_EIGENVALUE_H\n", "meta": {"hexsha": "95ed9a084f6c71093c78bf07e61303046a43f8ae", "size": 4231, "ext": "h", "lang": "C", "max_stars_repo_path": "include/scilib/linalg_impl/eigenvalue.h", "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/scilib/linalg_impl/eigenvalue.h", "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/scilib/linalg_impl/eigenvalue.h", "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5874125874, "max_line_length": 79, "alphanum_fraction": 0.5972583314, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6054225850334723}} {"text": "/* randist/dirichlet.c\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#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\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 for (i = 0; i < K; i++)\n {\n theta[i] /= norm;\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": "ad136e1821815d89f51a883c883495465d94293c", "size": 2760, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/dirichlet.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/dirichlet.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/dirichlet.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.5384615385, "max_line_length": 81, "alphanum_fraction": 0.6333333333, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6053998754174318}} {"text": "/* \n** gsl routines for float data type\n**\n** G.Lohmann, July 2004\n*/\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"gsl_utils.h\" \n\n\n/*\n** y = Ax\n*/\ngsl_vector_float *fmat_x_vector(gsl_matrix_float *A, gsl_vector_float *x, gsl_vector_float *y)\n{\n if (y == NULL) {\n y = gsl_vector_float_alloc (A->size1);\n }\n\n gsl_blas_sgemv(CblasNoTrans, 1.0, A, x, 0.0, y);\n\n return y;\n}\n\n\n/*\n** C = A x B^T\n*/\ngsl_matrix_float *fmat_x_matT(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)\n{\n if (C == NULL) {\n C = gsl_matrix_float_alloc( A->size1, B->size1 );\n }\n\n gsl_blas_sgemm( CblasNoTrans, CblasTrans, 1.0, A, B, 0.0, C );\n\n return C;\n}\n\n\n/*\n** C = A^T x B\n*/\ngsl_matrix_float *fmatT_x_mat(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)\n{\n if (C == NULL) {\n C = gsl_matrix_float_alloc( A->size2, B->size2 );\n }\n\n gsl_blas_sgemm( CblasTrans, CblasNoTrans, 1.0, A, B, 0.0, C );\n\n return C;\n}\n\n\n/*\n** C = A x B\n*/\ngsl_matrix_float *fmat_x_mat(gsl_matrix_float *A,gsl_matrix_float *B,gsl_matrix_float *C)\n{\n if (C == NULL) {\n C = gsl_matrix_float_alloc( A->size1, B->size2 );\n }\n\n gsl_blas_sgemm( CblasNoTrans, CblasNoTrans, 1.0, A, B, 0.0, C );\n\n return C;\n}\n\n\n/*\n** y = Ax, A double, x float\n*/\ngsl_vector_float *dmat_x_fvector(gsl_matrix *A, gsl_vector_float *x, gsl_vector_float *y)\n{\n int i,j,nrows,ncols;\n float *ptr2,*ptr3,sum;\n double *ptr1;\n\n nrows = A->size1;\n ncols = A->size2;\n\n if (y == NULL) {\n y = gsl_vector_float_alloc (nrows);\n }\n\n if (x->size != ncols || y->size != nrows) {\n fprintf(stderr,\" fmat_x_vect: incongruent dimensions\\n\");\n exit(0);\n }\n\n ptr1 = A->data;\n ptr3 = y->data;\n\n for (i=0; idata;\n for (j=0; jsize;\n if (y->size != n) {\n fprintf(stderr,\" fskalarproduct: incongruent vector sizes: %d %ld\",n,y->size);\n exit(0);\n }\n\n ptr1 = x->data;\n ptr2 = y->data;\n sum = 0;\n for (i=0; isize1; i++) {\n for (j=0; jsize2; j++) {\n fprintf(fp,format,fmget(A,i,j));\n }\n fprintf(fp,\"\\n\");\n }\n fprintf(fp,\"\\n\");\n\n}\n\n/*\n** B = A^T\n*/\ngsl_matrix_float *ftranspose(gsl_matrix_float *A,gsl_matrix_float *B)\n{\n int i,j,n,m;\n\n n = A->size1;\n m = A->size2;\n \n if (B == NULL) {\n B = gsl_matrix_float_alloc(m,n);\n }\n else if (B->size1 != m || B->size2 != n) {\n gsl_matrix_float_free(B);\n B = gsl_matrix_float_alloc(m,n);\n }\n\n for (i=0; isize1;\n n = A->size2;\n\n if (B == NULL) {\n B = gsl_matrix_float_alloc (n,m);\n }\n else if (B->size1 != n || B->size2 != m) {\n gsl_matrix_float_free(B);\n B = gsl_matrix_float_alloc (n, m);\n }\n\n gsl_matrix *U = gsl_matrix_alloc (m, n);\n gsl_matrix *V = gsl_matrix_alloc (n, n);\n gsl_matrix *X = gsl_matrix_alloc (n, n);\n gsl_vector *w = gsl_vector_alloc (n);\n gsl_vector *work = gsl_vector_alloc (n);\n\n /* singular value decomposition */\n flt_pp = A->data;\n dbl_pp = U->data;\n for (i=0; isize1 * A->size2; i++) \n *dbl_pp++ = *flt_pp++;\n\n /* gsl_linalg_SV_decomp_jacobi(U,V,w); */\n gsl_linalg_SV_decomp_mod (U,X,V,w,work);\n\n\n /* check if singular */\n k=0;\n for (j=0; jdata[j]) > 1.0e-6) k++;\n }\n if (k < 2) VError(\" Design matrix is singular\");\n\n\n /* exception from Gaby */\n int j0 = 0;\n double xmin, xmax, tiny=10.0e-6;\n xmax = gsl_vector_get(w,0);\n xmin = tiny;\n for (j=n-1; j >= 0; j--) {\n u = gsl_vector_get(w,j);\n if (u > 0 && u/xmax > tiny) {\n j0 = j;\n goto skip;\n }\n }\n skip: ;\n if (j0 < n-1) {\n fprintf(stderr,\" Warning: Matrix almost singular\\n\");\n xmin = gsl_vector_get(w,j0) - tiny;\n if (xmin < 0) xmin = 0;\n }\n\n\n /* Fill the result matrix */\n gsl_matrix_float_set_zero(B);\n for (k=0; k xmin) {\n x = gsl_matrix_float_get(B,k,l);\n\t x += gsl_matrix_get(V,k,j)*gsl_matrix_get(U,l,j)/u;\n gsl_matrix_float_set(B,k,l,x);\n }\n }\n }\n }\n gsl_matrix_free(U);\n gsl_matrix_free(V);\n gsl_matrix_free(X);\n gsl_vector_free(w);\n gsl_vector_free(work);\n return B;\n}\n\n\n/*\n** returns the trace of a matrix M \n*/\nfloat trace(gsl_matrix_float *M)\n{\n gsl_vector_float_view diag = gsl_matrix_float_diagonal(M);\n float sum = 0;\n int i = 0;\n for(i = 0; isize1;\n int n = mat->size2;\n int i;\n \n /* Create matrix buffer from source matrix. This prevents the overwriting of\n * matrix mat by gsl_linalg_SV_decomp().*/\n gsl_matrix* U = gsl_matrix_alloc(m,n);\n double* dpU = U->data;\n float* fpMat = mat->data;\n for(i=0;isize1* mat->size2;i++) {\n *dpU++ = *fpMat++;\n }\n \n /* create additional matrix buffers */\n gsl_matrix *V;\n gsl_matrix *X;\n gsl_vector *S;\n gsl_vector *work;\n S = gsl_vector_alloc(n);\n V = gsl_matrix_alloc(n,n);\n X = gsl_matrix_alloc (n, n);\n work = gsl_vector_alloc (n);\n \n /* SVD */\n /* gsl_linalg_SV_decomp_jacobi(U,V,S); */\n gsl_linalg_SV_decomp_mod (U,X,V,S,work);\n\n int rank = 0;\n /* counting the nonzero singular values with a tolerance of EPSILON*/\n for(i=0;isize;i++){\n if(S->data[i] > EPSILON) {\n rank++;\n }\n }\n \n gsl_matrix_free(U);\n gsl_matrix_free(V);\n gsl_matrix_free(X);\n gsl_vector_free(S);\n gsl_vector_free(work);\n \n return rank;\n}\n\n\n/*\n** fsum\n*/\ngsl_vector_float *fsum(gsl_matrix_float *matrix, int dim,gsl_vector_float *v) \n{\n \n int row,col;\n float sum=0;\n \n /* build sum over all columns */\n if (dim == 1) {\n \n if (v == NULL) {\n v = gsl_vector_float_alloc(matrix->size2);\n }\n if(v->size != matrix->size2) {\n fprintf(stderr, \"Warning in fsum: vector size doesn't match related matrix dimension. Resizing ..\");\n gsl_vector_float_free(v);\n v = gsl_vector_float_alloc(matrix->size2);\n } \n \n for (col=0;colsize2;col++){ \n sum=0;\n for(row=0;rowsize1;row++) {\n\tsum+=matrix->data[col+row*matrix->size2];\n }\n v->data[col] = sum;\n }\n }\n\n /* build sum over all rows */\n else {\n\n if (v == NULL) {\n v = gsl_vector_float_alloc(matrix->size1);\n }\n \n if (v->size != matrix->size1) {\n fprintf(stderr, \"Warning in fsum: vector size doesn't match related matrix dimension. Resizing ..\");\n gsl_vector_float_free(v);\n v = gsl_vector_float_alloc(matrix->size1);\n }\n\n for (row = 0;rowsize1;row++) {\n sum = 0;\n for(col=0;colsize2;col++) {\n\tsum += matrix->data[col+row*matrix->size2];\n }\n v->data[row] = sum;\n } \n }\n return v;\n}\n\n\n/*\n** funique\n*/\ngsl_vector_float *funique(gsl_vector_float* V) \n{\n \n /* working copy */\n gsl_vector_float* v = gsl_vector_float_alloc(V->size);\n /* pointer to result */\n gsl_vector_float* res; \n /* holds value of last saved element */\n float max=0;\n /* counter */\n int i;\n \n gsl_vector_float_memcpy(v,V);\n \n /* sort elements from V. */\n gsl_sort_vector_float(v);\n\n /* count number of different elements */\n int nelements = 0;\n \n /* first run: count different values */\n float* p = v->data;\n for(i=0;isize;i++) {\n /* the first element in the list is special */\n if(i==0) {\n max = *p;\n nelements++; \n }\n else {\n if(*p > max) {\n\tmax = *p;\n\tnelements++;\n } \n }\n p++;\n }\n \n /* second run: allocate mem & copy every value exactly once. */\n res = gsl_vector_float_alloc(nelements);\n p = v->data;\n float *s = res->data;\n for(i=0;isize;i++) {\n if(i==0) {\n max = *p;\n *s++ = *p;\n }\n else {\n if(*p > max) {\n\tmax = *p;\n\t*s++ = *p;\n }\n }\n p++;\n }\n\n gsl_vector_float_free(v);\n \n return res;\n}\n\n/*\n** subcols\n*/\ngsl_matrix_float *fmat_subcols(gsl_matrix_float* mat,gsl_vector_float* cols) \n{\n \n /* some tests */ \n \n if((cols->size < 0) || (cols->size > mat->size2)) {\n fprintf(stderr,\"column vector: invalid dimensions\");\n exit(-1);\n }\n \n float min, max;\n gsl_vector_float_minmax(cols, &min, &max);\n \n if((min < 0) || (max > mat->size2)) { \n fprintf(stderr,\"column vector values exceed matrix dimensions!\");\n exit(-1);\n }\n \n /* TODO reduce column vector to unique values with funique. We will omit \n * this due to performance reasons. */\n \n /* the return value */\n gsl_matrix_float* ret = gsl_matrix_float_alloc(mat->size1, cols->size);\n /* the copy buffer */\n gsl_vector_float* buff = gsl_vector_float_alloc(mat->size1); \n /* counter */\n int i;\n \n /* copy columns from matrix to return buffer */\n for (i = 0; i < cols->size; ++i) {\n gsl_matrix_float_get_col(buff, mat, (int)cols->data[i]);\n gsl_matrix_float_set_col(ret, i, buff);\n }\n \n gsl_vector_float_free(buff);\n \n return ret;\n}\n\n/*\n** toeplitz\n*/\ngsl_matrix_float *fmat_toeplitz(gsl_vector_float* v, gsl_matrix_float* A)\n{\n int i,j;\n\n if(A == NULL)\n A = gsl_matrix_float_alloc(v->size, v->size);\n else {\n if((A->size1 != v->size) || (A->size2 != v->size)) {\n fprintf(stderr, \"Warning fmat_toeplitz: incongruent matrix dimensions. Trying to\\\n correct it.\");\n gsl_matrix_float_free(A);\n A = gsl_matrix_float_alloc(v->size, v->size);\n }\n }\n\n for(i=0;isize1;i++){\n for(j=0;jsize2;j++) {\n gsl_matrix_float_set(A,i,j,gsl_vector_float_get(v, fabs(i-j)));\n }\n }\n \n return A;\n}\n\n/*\n** A^-1\n*/\ngsl_matrix_float *fInv(gsl_matrix_float *M, gsl_matrix_float *result) \n{\n int s; /*permutation signum for LU-Decomposition*/\n int i;\n\n int m = M->size1;\n int n = M->size2;\n\n if(m != n) {\n fprintf(stderr, \"dInv: not a square matrix\\n\");\n exit(0);\n }\n\n if(result == NULL) { \n result = gsl_matrix_float_alloc(m,m);\n }\n if((result->size1 != m) || (result->size2 != n)) {\n fprintf(stderr,\"dInv: incongruent matrix dimensions.\\n\");\n exit(0);\n }\n \n gsl_matrix *ludecomp = gsl_matrix_alloc(m,m);\n gsl_permutation *perm = gsl_permutation_alloc(m); \n gsl_matrix *res = gsl_matrix_alloc(m,m);\n\n /* convert from float to double */\n double *d_ptr = ludecomp->data;\n float *f_ptr = M->data;\n for(i=0;isize1*M->size2;i++) {\n *d_ptr = (double)*f_ptr;\n d_ptr++;f_ptr++;\n }\n\n /* LU decomposition */\n gsl_linalg_LU_decomp(ludecomp,perm,&s);\n\n /* inverting matrix */\n gsl_linalg_LU_invert(ludecomp,perm,res);\n \n /* convert from double to float */\n d_ptr = res->data;\n f_ptr = result->data;\n for(i=0;isize1*res->size2;i++) {\n *f_ptr = (float)*d_ptr;\n d_ptr++;f_ptr++;\n } \n\n\n gsl_matrix_free(ludecomp);\n gsl_matrix_free(res);\n gsl_permutation_free(perm);\n return result;\n}\n", "meta": {"hexsha": "c5d5ca023b08f041ffb10c6cbf048a3d2728b350", "size": 11747, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_prewhitening/gsl_futils.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 20.2534482759, "max_line_length": 106, "alphanum_fraction": 0.5812547885, "num_tokens": 3847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6052536215960624}} {"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#include \"ccl_params.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.mnu, cosmo->params.T_CMB,\n cosmo->data.accelerator, status) / (cosmo->params.h) / (cosmo->params.h);\n ccl_check_status(cosmo, status);\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_n_rel) a^-4 +\n Om_mass_nu\n */\n return sqrt(\n (cosmo->params.Omega_m +\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_n_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.mnu,\n\t\t cosmo->params.T_CMB, cosmo->data.accelerator, status);\n ccl_check_status(cosmo, 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_m / (a*a*a) / 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_n_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 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// 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 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[0]=y[1]/(a*a*a*hnorm);\n dydt[1]=1.5*hnorm*a*om*y[0];\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(aODE_GROWTH_EPSREL);\n\n y[0]=EPS_SCALEFAC_GROWTH;\n y[1]=EPS_SCALEFAC_GROWTH*EPS_SCALEFAC_GROWTH*EPS_SCALEFAC_GROWTH*\n h_over_h0(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 NAN;\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}\n\n\n/* --------- ROUTINE: compute_chi ---------\nINPUT: scale factor, cosmology\nOUTPUT: chi -> radial comoving distance\nTASK: compute radial comoving distance at a\n*/\nstatic void 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 = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n gsl_function F;\n F.function = &chi_integrand;\n F.params = &p;\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, ccl_gsl->INTEGRATION_DISTANCE_EPSREL, workspace, &result, NULL, NULL);\n *chi=result/cosmo->params.h;\n gsl_integration_cquad_workspace_free(workspace);\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\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, ccl_gsl->ROOT_EPSREL);\n } while(gslstatus==GSL_CONTINUE && iter <= ccl_gsl->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 \n //Do nothing if everything is computed already\n if(cosmo->computed_distances)\n return;\n \n if(ccl_splines->A_SPLINE_MAX>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;\n }\n\n // Create logarithmically and then linearly-spaced values of the scale factor \n int na = ccl_splines->A_SPLINE_NA+ccl_splines->A_SPLINE_NLOG-1; \n double * a = ccl_linlog_spacing(ccl_splines->A_SPLINE_MINLOG, ccl_splines->A_SPLINE_MIN,\n\t\t\t\t ccl_splines->A_SPLINE_MAX, ccl_splines->A_SPLINE_NLOG,\n\t\t\t\t ccl_splines->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(A_SPLINE_TYPE, na);\n gsl_spline * chi = gsl_spline_alloc(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){\n *status=CCL_ERROR_MEMORY; \n\n ccl_cosmology_set_status_message(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]-ccl_splines->A_SPLINE_MINLOG)>1e-5) || \n\t(fabs(a[na-1]-ccl_splines->A_SPLINE_MAX)>1e-5) || \n\t(a[na-1]>1.0)) {\n *status = CCL_ERROR_LINSPACE; \n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): Error 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; i1e-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(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.accelerator==NULL)\n cosmo->data.accelerator=gsl_interp_accel_alloc();\n cosmo->data.E = E;\n cosmo->data.chi = chi;\n cosmo->data.achi = achi;\n cosmo->computed_distances = true;\n}\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*/\n\nvoid ccl_cosmology_compute_growth(ccl_cosmology * cosmo, int * status)\n{\n\n // This is not valid for massive neutrinos; if we have massive neutrinos, exit.\n if (cosmo->params.N_nu_mass>0){\n\t *status = CCL_ERROR_NOT_IMPLEMENTED;\n\t ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Support for the growth rate in cosmologies with massive neutrinos is not yet implemented.\\n\");\n\t return;\n }\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 = ccl_splines->A_SPLINE_NA+ccl_splines->A_SPLINE_NLOG-1;\n double * a = ccl_linlog_spacing(ccl_splines->A_SPLINE_MINLOG, ccl_splines->A_SPLINE_MIN, ccl_splines->A_SPLINE_MAX, ccl_splines->A_SPLINE_NLOG, ccl_splines->A_SPLINE_NA);\n if (a==NULL ||\n (fabs(a[0]-ccl_splines->A_SPLINE_MINLOG)>1e-5) ||\n (fabs(a[na-1]-ccl_splines->A_SPLINE_MAX)>1e-5) ||\n (a[na-1]>1.0)\n ) {\n free(a);\n *status = CCL_ERROR_LINSPACE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating logarithmically and then linear spacing in a\\n\");\n return;\n }\n\n gsl_integration_cquad_workspace * workspace=NULL;\n gsl_function F;\n gsl_spline *df_a_spline=NULL;\n if(cosmo->params.has_mgrowth) {\n double *df_arr=malloc(na*sizeof(double));\n if(df_arr==NULL) {\n free(a);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\\n\");\n return;\n }\n //Generate spline for Delta f(z) that we will then interpolate into an array of a\n gsl_spline *df_z_spline=gsl_spline_alloc(A_SPLINE_TYPE,cosmo->params.nz_mgrowth);\n chistatus=gsl_spline_init(df_z_spline,cosmo->params.z_mgrowth,cosmo->params.df_mgrowth,\n\t\t\t cosmo->params.nz_mgrowth);\n\n if(chistatus) {\n free(a);\n free(df_arr);\n gsl_spline_free(df_z_spline);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(z) spline\\n\");\n return;\n }\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\t chistatus |= gsl_spline_eval_e(df_z_spline,z,NULL,&df_arr[i]);\n } else {\n\t df_arr[i]=0;\n }\n }\n if(chistatus) {\n free(a);\n free(df_arr);\n gsl_spline_free(df_z_spline);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error evaluating Delta f(z) spline\\n\");\n return;\n }\n gsl_spline_free(df_z_spline);\n\n //Generate Delta(f) spline\n df_a_spline=gsl_spline_alloc(A_SPLINE_TYPE,na);\n chistatus=gsl_spline_init(df_a_spline,a,df_arr,na);\n free(df_arr);\n if (chistatus) {\n free(a);\n gsl_spline_free(df_a_spline);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating Delta f(a) spline\\n\");\n return;\n }\n\n workspace=gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);\n F.function=&df_integrand;\n F.params=df_a_spline;\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 int status_mg=0, gslstatus;\n double growth0,fgrowth0;\n double *y = malloc(sizeof(double)*na);\n if(y==NULL) {\n free(a);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\\n\");\n return;\n }\n double *y2 = malloc(sizeof(double)*na);\n if(y2==NULL) {\n free(a);\n free(y);\n *status=CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_distances(): ran out of memory\\n\");\n return;\n }\n\n chistatus|=growth_factor_and_growth_rate(1.,&growth0,&fgrowth0,cosmo, status);\n for(int i=0; iparams.has_mgrowth) {\n if(a[i]>0) {\n\tdouble df,integ;\n\t//Add modification to f\n\tgslstatus = 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\ty2[i]+=df;\n\t//Multiply D by exp(-int(df))\n\tgslstatus = gsl_integration_cquad(&F,a[i],1.0,0.0,ccl_gsl->INTEGRATION_DISTANCE_EPSREL,workspace,&integ,NULL,NULL);\n\tif(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 y[i]/=growth0;\n }\n if(chistatus || status_mg || *status) {\n free(a);\n free(y);\n free(y2);\n if(df_a_spline!=NULL)\n gsl_spline_free(df_a_spline);\n if(workspace!=NULL)\n gsl_integration_cquad_workspace_free(workspace);\n if (chistatus) {\n *status = CCL_ERROR_INTEG;\n ccl_cosmology_set_status_message(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(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): integral for MG growth factor didn't converge\\n\");\n }\n return;\n }\n\n if(cosmo->params.has_mgrowth) {\n gsl_spline_free(df_a_spline);\n gsl_integration_cquad_workspace_free(workspace);\n }\n\n gsl_spline * growth = gsl_spline_alloc(A_SPLINE_TYPE, na);\n chistatus = gsl_spline_init(growth, a, y, na);\n if(chistatus) {\n free(a);\n free(y);\n free(y2);\n gsl_spline_free(growth);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating D(a) spline\\n\");\n return;\n }\n\n gsl_spline * fgrowth = gsl_spline_alloc(A_SPLINE_TYPE, na);\n chistatus = gsl_spline_init(fgrowth, a, y2, na);\n if(chistatus) {\n free(a);\n free(y);\n free(y2);\n gsl_spline_free(growth);\n gsl_spline_free(fgrowth);\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Error creating f(a) spline\\n\");\n return;\n }\n\n // Initialize the accelerator which speeds the splines and\n // assign all the splines we've just made to the structure.\n if(cosmo->data.accelerator==NULL)\n cosmo->data.accelerator=gsl_interp_accel_alloc();\n cosmo->data.growth = growth;\n cosmo->data.fgrowth = fgrowth;\n cosmo->data.growth0 = growth0;\n cosmo->computed_growth = true;\n\n free(a);\n free(y);\n free(y2);\n\n return;\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 ccl_cosmology_compute_distances(cosmo,status);\n ccl_check_status(cosmo, status);\n }\n\n double h_over_h0;\n int gslstatus = gsl_spline_eval_e(cosmo->data.E, a, cosmo->data.accelerator,&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 ccl_check_status(cosmo,status);\n return NAN;\n }\n else {\n if(!cosmo->computed_distances) {\n ccl_cosmology_compute_distances(cosmo, status);\n ccl_check_status(cosmo,status);\n }\n\n double crd;\n int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a, cosmo->data.accelerator, &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(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\t 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 ccl_check_status(cosmo,status);\n return NAN;\n }\n else {\n if (!cosmo->computed_distances) {\n ccl_cosmology_compute_distances(cosmo, status);\n ccl_check_status(cosmo, status);\n }\n\n double chi;\n int gslstatus = gsl_spline_eval_e(cosmo->data.chi, a,\n cosmo->data.accelerator,&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\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 ccl_check_status(cosmo,status);\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 ccl_check_status(cosmo,status);\n return NAN;\n } else {\n if (!cosmo->computed_distances) {\n ccl_cosmology_compute_distances(cosmo, status);\n ccl_check_status(cosmo, status);\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 ccl_check_status(cosmo,status);\n return NAN;\n }\n else {\n if (!cosmo->computed_distances) {\n ccl_cosmology_compute_distances(cosmo,status);\n ccl_check_status(cosmo,status);\n }\n double a;\n int gslstatus = gsl_spline_eval_e(cosmo->data.achi, chi,cosmo->data.accelerator_achi, &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\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(cosmo, \"ccl_background.c: scale factor cannot be larger than 1.\\n\");\n ccl_check_status(cosmo,status);\n return NAN;\n }\n else {\n if (!cosmo->computed_growth) {\n ccl_cosmology_compute_growth(cosmo, status);\n ccl_check_status(cosmo, status);\n }\n if (*status!= CCL_ERROR_NOT_IMPLEMENTED) {\n double D;\n int gslstatus = gsl_spline_eval_e(cosmo->data.growth, a, cosmo->data.accelerator,&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(cosmo, \"ccl_background.c: ccl_growth_factor(): Scale factor outside interpolation range.\\n\");\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 ccl_cosmology_compute_growth(cosmo, status);\n ccl_check_status(cosmo, status);\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 ccl_check_status(cosmo,status);\n return NAN;\n } else {\n if (!cosmo->computed_growth) {\n ccl_cosmology_compute_growth(cosmo, status);\n ccl_check_status(cosmo, status);\n }\n if(*status != CCL_ERROR_NOT_IMPLEMENTED) {\n double g;\n int gslstatus = gsl_spline_eval_e(cosmo->data.fgrowth, a, cosmo->data.accelerator,&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\t return NAN;\n\t }\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\n/* ----- IFU and GSL includes -----*/\n#include \n#include \n#include \"IFU_io.h\"\n// #include \"IFU_math.h\"\n/* ----- Specific IFU includes ----- */\n#include \"data_io.h\"\n#ifdef FITS\n#include \n#endif\n\n/* Removing MIDAS by hand - not really clean, but should allow to compile with an IFU with --disable-midas enabled*/\n#undef MIDAS\n\n#ifdef MIDAS\n#include \"midas_defs.h\"\n#include \"tbldef.h\"\n#include \"fctext.h\"\n#include \"ldbext.h\"\n#include \"proto_st.h\"\n\n#endif\nextern IO_Format InputIO, OutputIO;\n\n/* ----- local includes ----- */\n#include \"utils.h\"\n\n\n/* ----- static functions ---------------------------------------- */\nstatic int ascending(const void *a, const void*b) {\n if (*(double*)a==*(double*)b) return 0; \n return (*(double*)a > *(double*)b ) ? 1 : -1;\n}\n\n/* ----- ut_median ---------------------------------------- */\nvoid ut_sort_ascending(double* values, int n)\n /* median of unsorted values */\n{\n qsort(values,n,sizeof(double),&ascending);\n}\n\n/* ----- ut_median ---------------------------------------- */\ndouble ut_median(double* values, int n)\n /* median of unsorted values */\n{\n qsort(values,n,sizeof(double),&ascending);\n /* alternatively, I could have used gsl_stats_median_from_sorted_data \n but it is fucking the flies ! */\n /* i saw also something usable in mathlib : the names might conflict !*/\n if (n%2) \n return values[n/2]; \n else \n return (values[n/2-1]+values[n/2])/2;\n\n \n}\n\n/* ----- ut_min ---------------------------------------- */\ndouble ut_min(double* values, int n)\n /* min of array */\n{\n double min = values[0];\n int i;\n \n for (i=1;i slow if\n the sigcut is too low !\n \n values : pointer to array of values - modified\n nitems : number of values -> modified\n sigcut : if <0, does nothing\n\n Beware : the number of remaining items might be 0 !\n\n */\n int ok=0;\n\n if (sigcut<0) \n return;\n \n qsort(*values,*nitems,sizeof(double),ascending);\n\n while (!ok && *nitems>1) {\n \n double mean=ut_mean(*values,*nitems);\n double valinf = (mean-(*values)[0])/sigma;\n double valsup = ((*values)[*nitems-1]-mean)/sigma;\n if (valsup>sigcut && valsup>=valinf) {\n double bound = MAX(sigcut,valinf);\n /* remove more than one for efficiency */\n while(valsup>=bound && *nitems>1) {\n (*nitems)--;\n valsup = ((*values)[*nitems-1]-mean)/sigma;\n }\n } else if (valinf>sigcut && valinf>=valsup) {\n double bound = MAX(sigcut,valinf);\n while(valinf>=bound && *nitems>1 ){\n (*nitems)--;\n (*values)++;\n valinf = (mean-(*values)[0])/sigma;\n }\n } else {\n ok=1;\n }\n }\n}\n\n\n/* ------------------------------- ut_trunc_sigma_unknown ------------------ */\nvoid ut_trunc_sigma_unknown(double** values, int * nitems, double sigcut){\n /* trunc the data set, removing any value outside +/- sigcut sigma\n if sigcut<0, does noting .\n it works iteratively by removing too far away values. => slow if\n the sigcut is too low !\n Beware : sigma is computed from the distribution itself.\n Points far away will push the sigma towards greater values.\n \n values : pointer to array of values - modified\n nitems : number of values -> modified\n sigcut : if <0, does nothing\n\n Beware : the number of remaining items might be 0 !\n\n */\n int ok=0;\n\n if (sigcut<0) \n return;\n \n qsort(*values,*nitems,sizeof(double),ascending);\n\n while (!ok && *nitems>1) {\n double mean,sigma,valinf,valsup;\n\n mean = ut_mean((*values),*nitems);\n sigma = gsl_stats_sd_m(*values,1,*nitems,mean);\n valinf = (mean-(*values)[0])/sigma;\n valsup = ((*values)[*nitems-1]-mean)/sigma;\n if (valsup>sigcut && valsup>=valinf) {\n (*nitems)--;\n } else if (valinf>sigcut && valinf>=valsup) {\n (*nitems)--;\n (*values)++;\n } else {\n ok=1;\n }\n }\n}\n\n/* ------------------------------- ut_trunc_sigma_unknown ------------------ */\nvoid ut_trunc_sigma_unknown_fast_sorted(double** values, int * nitems, double sigcut){\n /* trunc the data set, removing any value outside +/- sigcut sigma\n if sigcut<0, does noting .\n it works grossly, removing each time all what is outside the window, \n which is not accurate\n\n Beware : sigma is computed from the distribution itself.\n Points far away will push the sigma towards greater values.\n \n values : pointer to array of values - modified\n nitems : number of values -> modified\n sigcut : if <0, does nothing\n\n Beware : the number of remaining items might be 0 !\n\n */\n int ok=0;\n\n if (sigcut<0) \n return;\n \n /* qsort(*values,*nitems,sizeof(double),ascending); */\n\n while (!ok && *nitems>1) {\n\n double mean,sigma,valinf,valsup;\n int nitems_old = *nitems;\n\n mean = ut_mean((*values),*nitems);\n sigma = gsl_stats_sd_m(*values,1,*nitems,mean);\n valinf = mean-sigma*sigcut;\n valsup = mean + sigma*sigcut;\n while ((*values)[0] < valinf && *nitems>1) {\n (*nitems)--;\n (*values)++;\n }\n while ((*values)[*nitems-1] > valsup && *nitems>1) {\n (*nitems)--;\n }\n if (nitems_old == (*nitems))\n ok=1;\n }\n}\n\n/*-------------------- ut_fraction_sigcut ----------------------*/\ndouble ut_fraction_sigcut(double fraction) {\n /* given a distribution with fraction outliers, at infinite \n distance with respect to normal values, \n returns the standard deviation of the outliers, when the\n RMS is computed with it included.*/\n\n /* the computation is performed with fraction values at 1 and \n 1-fraction at 0 */\n double sigcut,rms;\n /* mean = fraction */\n rms = sqrt(fraction*fraction*(1-fraction) + (1-fraction)*(1-fraction)*fraction);\n \n sigcut = (1-fraction)/rms;\n return sigcut;\n}\n\n/*-------------------- ut_mean ----------------------*/\ndouble ut_mean(double* val,int n){\n\n int i;\n double sum = 0;\n for (i=0;i fabs (med - val[index[nmax-1]]) )\n nmin =(nmin + nmax - 1 )/2;\n else if ( fabs(med - val[index[nmin]]) < fabs (med - val[index[nmax-1]]) )\n /* rounding in the good direction in order to include the median place */\n nmax = ( nmin + nmax)/2 + 1;\n else /* stop in case of equality */\n nmax = nmin;\n } while (nmax-nmin > 2);\n \n return med;\n}\n\n/*-------------------- ut_mean ----------------------*/\ndouble ut_mode2(double* val,int n){\n /* This function returns the highest probability density a set of\n datas. This only works reliabely if there is only 1 maximum, \n and in the limit where the data is sufficiently sampled. \n No error computation is performed ...*/\n /* The search is dyadic and iterative, each step looking for the part\n which contains most of the data with respect to the highest value. \n The time is O(NlnN) (+ the time to run indexx)*/ \n /* This is a fast and inaccurate algorithm. For a general algorithm, see the\n Parzenwindow method - the drawback is that it depends on a window size\n a priori*/ \n\n\n size_t * index;\n double half;\n int nmin=0;\n int nmax=n; /* out of the table */\n\n index = malloc(n*sizeof(size_t));\n \n /* test */\n\n gsl_sort_index(index,val,1,n);\n\n \n do { \n int i;\n /* half window computation */\n half=(val[index[nmin]]+val[index[nmax-1]])/2;\n for (i=nmin;ihalf) \n break;\n }\n if (i==nmax)\n return half;\n else if (inmin+(nmax-nmin)/2 || ((nmax-nmin)%2) )\n nmax=i;\n else {\n nmin++;\n nmax--;\n }\n } while (nmax-nmin>2);\n return half;\n}\n\n/*-------------------- ut_autocovariance ----------------------*/\nvoid ut_autocovariance(double* data, double* autocorr, int n) {\n/* data is of dim n, autocorr of dim n */\n int decal,i;\n double mean;\n /* double var; */\n double *mdata = malloc(sizeof(double)*n);\n\n /* compute the mean */\n mean = ut_mean(data,n);\n\n /* substract it (n computations) */\n for (i=0;iident,' ',lg_ident);\n frame->ident[lg_ident] = '\\0';\n memset(frame->cunit,' ',lg_unit);\n frame->cunit[lg_unit] = '\\0';\n memset(frame->history,' ',lg_hist);\n frame->history[lg_hist] = '\\0';\n frame->external_info = NULL;\n frame->file_type = T_IMA2D;\n frame->data_format = InputIO.basic_io;\n\n strcpy(filename,name);\n first_blk(filename); \n strcpy(frame->name,filename);\n append_ima_extension(frame->name,InputIO.basic_io);\n\n strcpy(filename,frame->name);\n\n if (!exist(filename)) { /* check if fil exists */\n status = ERR_OPEN;\n sprintf(errtext,\"open_frame: frame %s\",filename);\n Handle_Error(errtext,status);\n return(status);\n }\n\n switch(mode[0]) {\n case 'I' : \n if (mode[1] == 'O')\n frame->iomode = (int)IO_MODE;\n else\n frame->iomode = (int)I_MODE;\n break;\n case 'O' : frame->iomode = (int)O_MODE;\n break;\n default : frame->iomode = (int)I_MODE;\n break;\n }\n\t\n iomode = get_iomode_code(InputIO.basic_io,frame->iomode);\n\n switch (InputIO.basic_io) {\n\n#ifdef MIDAS\n case MIDAS_FORMAT :\n status = SCFINF(filename,2,info); \n if (status == 0) {\n status = SCIGET(filename, info[1], iomode, F_IMA_TYPE, 2, \n &nbaxes, &(frame->nx), &(frame->startx), &(frame->stepx),\n frame->ident, frame->cunit, (char **)(&(frame->data)), \n &(frame->imno));\n frame->data_type = info[1];\n frame->data_type = decode_datatype(InputIO.basic_io,frame->data_type);\n\n if (nbaxes!=2) /* We open a spectrum like an image, and that's not good */\n status = ERR_OPEN; \n\n }\n break;\n#endif\n#ifdef IRAF\n case IRAF_FORMAT :\n case STSDAS_FORMAT :\n len = strlen(filename);\n uimopn(filename,&iomode,&(frame->imno),&status,len);\n if (status != 0) \n break;\n uimgid(&(frame->imno),&int_datatype,&two_dim,&(frame->nx),&status);\n frame->data_type = decode_datatype(InputIO.basic_io,(short)(int_datatype));\n if (status != 0)\n break;\n alloc_frame_mem(frame, datatype);\n switch(frame->data_type) {\n case SHORT :\n uigs2s(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.s_data,&status);\n break;\n case INT :\n case LONG :\n uigs2l(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.l_data,&status);\n break;\n case FLOAT :\n uigs2r(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.f_data,&status);\n break;\n case DOUBLE :\n uigs2d(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.d_data,&status);\n break;\n }\n disable_user_warnings();\n RD_desc(frame,\"IDENT\",CHAR,lg_ident,frame->ident);\n restore_user_warnings();\n break;\n#endif\n#ifdef FITS\n case FITS_A_FORMAT :\n case FITS_B_FORMAT :\n status =0;\n if (fits_open_file(&fptr,filename,iomode,&status)) {\n status = ERR_ACCESS; break;\n }\n frame->external_info = (void *)fptr;\n if (fits_read_key(fptr, TINT,\"NAXIS\", &nbaxes,NULL, &status)) {\n status = ERR_READ; break;\n }\n if (nbaxes != 2) {\n status = ERR_IMA_HEAD; break;\n }\n if (fits_read_key(fptr, TINT, \"NAXIS1\",\n &(frame->nx), NULL, &status)) {\n status = ERR_READ; break;\n }\n if (fits_read_key(fptr, TINT, \"NAXIS2\",\n &(frame->ny), NULL, &status)) {\n status = ERR_READ; break;\n }\n if (status == 0) {\n pixref = 1.0;\n fits_read_key(fptr, TDOUBLE, \"CRPIX1\", &pixref, NULL, &status);\n if (status) { status = 0; pixref = 1; }\n fits_read_key(fptr, TDOUBLE, \"CRVAL1\", &(frame->startx), NULL, &status);\n if (status) { status = 0; frame->startx = (double)1; }\n fits_read_key(fptr, TDOUBLE, \"CDELT1\", &(frame->stepx), NULL, &status);\n if (status) { status = 0; frame->stepx = (double)1; }\n frame->startx -= (pixref-1)*frame->stepx;\n pixref = 1.0;\n fits_read_key(fptr, TDOUBLE, \"CRPIX2\", &pixref, NULL, &status);\n if (status) { status = 0; pixref = 1; }\n fits_read_key(fptr, TDOUBLE, \"CRVAL2\", &(frame->starty), NULL, &status);\n if (status) { status = 0; frame->starty = (double)1; }\n fits_read_key(fptr, TDOUBLE, \"CDELT2\", &(frame->stepy), NULL, &status);\n if (status) { status = 0; frame->stepy = (double)1; }\n frame->starty -= (pixref-1)*frame->stepy;\n }\n else\n break;\n\n int_datatype = (fptr->Fptr->tableptr)->tdatatype;\n frame->data_type = decode_datatype(InputIO.basic_io,(short)int_datatype);\n if (frame->data_type == SHORT) {\n if (fptr->Fptr->tableptr[1].tscale == 1 && fptr->Fptr->tableptr[1].tzero == 32768)\n /* unsigned short !!! */\n frame->data_type = LONG;\n }\n\n if (alloc_frame_mem(frame, frame->data_type) < 0) {\n fits_close_file(fptr,&status);\n status = ERR_ALLOC;\n break;\n }\n\n npix = frame->nx*frame->ny;\n switch (frame->data_type) {\n case SHORT :\n if (fits_read_img_sht(fptr,group,1L,npix,(short)0,\n frame->data.s_data,&nbread,&status)) {\n status = ERR_READ; break;\n }\n break;\n case LONG :\n case INT :\n if (fits_read_img_lng(fptr,group,1L,npix,(int)0,\n frame->data.l_data,&nbread,&status)) {\n status = ERR_READ; break;\n }\n break;\n case FLOAT :\n if (fits_read_img_flt(fptr,group,1L,npix,(float)0,\n frame->data.f_data,&nbread,&status)) {\n status = ERR_READ; break;\n }\n break;\n case DOUBLE :\n if (fits_read_img_dbl(fptr,group,1L,npix,(double)0,\n frame->data.d_data,&nbread,&status)) {\n status = ERR_READ; break;\n }\n break;\n }\n break;\n#endif\n }\n\n if (status) {\n sprintf(errtext,\"open_frame: frame %s\",filename);\n status = get_tiger_errcode(frame->data_format,status);\n Handle_Error(errtext,status);\n }\n else {\n disable_user_warnings();\n status = RD_desc(frame,\"LHCUTS\",FLOAT,4,cuts);\n RD_desc(frame,\"HISTORY\",CHAR,lg_hist,frame->history);\n restore_user_warnings();\n\n frame->endx = frame->startx + (frame->nx -1)*frame->stepx;\n frame->endy = frame->starty + (frame->ny -1)*frame->stepy;\n if (status <= 0) {\n /* image_minmax is a really slow routine, and most of the time useless */\n frame->min = -ut_big_value;\n frame->max = +ut_big_value;\n /*\t\t\timage_minmax(frame); */\n }\n else {\n frame->min = cuts[2];\n frame->max = cuts[3];\n }\n status = 0;\n /* parse wcs if contained in file */\n status = parse_wcs(frame);\n }\n return(status);\n}\n\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n!\n!.func close_frame_fast()\n!\n!.purp closes a currently active 2D frame \n!.desc\n! close_frame(frame)\t\n!\n! IMAGE2D *frame; image structure\n!.ed\n-------------------------------------------------------------------- */\nint \nclose_frame_fast(IMAGE2D *frame)\t\t\t/* close active frame */\n{\n char errtext[132], filename[lg_name+1];\n int stat, int_datatype;\n float cuts[4];\n#ifdef IRAF\n int one=1;\n#endif\n#ifdef FITS\n fitsfile *fptr;\n int npix;\n#endif\n\n strcpy(filename,frame->name);\n\n if (frame->iomode == (int)I_MODE) {\n switch (frame->data_format) {\n#ifdef MIDAS\n case MIDAS_FORMAT :\n stat = SCFCLO(frame->imno);\n break;\n#endif\n#ifdef IRAF\n case IRAF_FORMAT :\n case STSDAS_FORMAT :\n uimclo(&(frame->imno),&stat);\n break;\n#endif\n#ifdef FITS\n case FITS_A_FORMAT :\n case FITS_B_FORMAT :\n stat =0;\n fptr = (fitsfile *)frame->external_info;\n fits_close_file(fptr,&stat);\n free_frame_mem(frame);\n frame->external_info = NULL;\n break;\n#endif\n }\n if (stat) {\n sprintf(errtext,\"close_frame: frame %s\",filename);\n stat = get_tiger_errcode(frame->data_format,stat);\n Handle_Error(errtext,stat);\n }\n return(stat);\n }\n\n /*\n if (frame->data.d_data != NULL) {\n image_minmax(frame);\n\n cuts[0]=(float)frame->min; cuts[2]=(float)frame->min;\n cuts[1]=(float)frame->max; cuts[3]=(float)frame->max;\n stat = WR_desc(frame,\"LHCUTS\",FLOAT,4,cuts);\n }\n */\n\n WR_history(frame, (Anyfile *)0);\n\n switch (frame->data_format) {\n#ifdef MIDAS\n case MIDAS_FORMAT :\n stat = SCFCLO(frame->imno);\n break;\n#endif\n#ifdef IRAF\n case IRAF_FORMAT :\n case STSDAS_FORMAT :\n switch(frame->data_type) {\n case SHORT :\n uips2s(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.s_data,&stat);\n break;\n case INT :\n case LONG :\n uips2l(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.l_data,&stat);\n break;\n case FLOAT :\n uips2r(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.f_data,&stat);\n break;\n case DOUBLE :\n uips2d(&(frame->imno),&one,&(frame->nx),&one,&(frame->ny),\n frame->data.d_data,&stat);\n break;\n }\n if (stat == 0) \n uimclo(&(frame->imno),&stat);\n free_frame_mem(frame);\n break;\n#endif\n#ifdef FITS\n case FITS_A_FORMAT :\n case FITS_B_FORMAT :\n stat = 0;\n fptr = (fitsfile *)frame->external_info;\n if (frame->iomode != (int)I_MODE) {\n if (frame->data.d_data != NULL) {\n int_datatype = get_datatype_code(OutputIO.basic_io,frame->data_type);\n npix = frame->nx*frame->ny;\n if (fits_write_img(fptr,int_datatype,1L,npix,\n frame->data.s_data,&stat)) {\n stat = ERR_WRIT;\n }\n }\n }\n if (! stat) {\n fits_close_file(fptr,&stat);\n stat = wcs_free(frame);\n }\n free_frame_mem(frame);\n frame->external_info = NULL;\n break;\n#endif\n }\n if (stat) {\n sprintf(errtext,\"close_frame: frame %s\",filename);\n stat = get_tiger_errcode(frame->data_format,stat);\n Handle_Error(errtext,stat);\n } else {\n if (TK && (frame->iomode == O_MODE || frame->iomode == IO_MODE))\n {\n printf(\"@ N {%s}\\n\",filename);\n }\n }\n\n return(stat);\n}\n\n\n/* ----- juldat --------------------------------------------------------- */\n/*C\nC FUNCTION JULDAT RETURNS THE JULIAN DATE AS A DOUBLE\nC PRECISION NUMBER.\nC ALGORITHM FROM \"ALAMANAC FOR COMPUTERS\" p.B2\nC*/\ndouble juldat( int year, int month, int day, double ut)\n /* year, month, day, ut are the UTC ones\n ut is the fractional hour */\n{\n double tmp;\n tmp = 367.0*year + 0.5 + ut/24.0;\n tmp = tmp - ((7*(year+((month+9)/12)))/4) + ((275*month)/9) + day + 1721013;\n return tmp;\n}\n\n/* ===== string utilities ===== */\n\nint ut_parse_line(char* line, char** tokens) {\n /* the token strings will contain the line elements separated by spaces */\n /* the original line will be modified (some '/0' char added)*/\n char* pt_line = line;\n int itoken=0;\n\n while (pt_line && pt_line[0]!='\\0') {\n tokens[itoken++] = pt_line;\n pt_line = strchr(pt_line,' ');\n if (pt_line)\n while((pt_line)[0]==' ') {\n pt_line[0]='\\0';\n pt_line++;\n }\n }\n return itoken;\n}\n", "meta": {"hexsha": "07424d7e61c0864035aff0f123869ffd87b6f3fb", "size": 25152, "ext": "c", "lang": "C", "max_stars_repo_path": "libsrc/utils.c", "max_stars_repo_name": "snfactory/preprocess", "max_stars_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "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": "libsrc/utils.c", "max_issues_repo_name": "snfactory/preprocess", "max_issues_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "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": "libsrc/utils.c", "max_forks_repo_name": "snfactory/preprocess", "max_forks_repo_head_hexsha": "9be356dcf64e411d74a080629ffa2ca67974d530", "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.5789473684, "max_line_length": 116, "alphanum_fraction": 0.5723202926, "num_tokens": 7100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6047299122127631}} {"text": "#include \n#include \n#include \n#include \n#include \n\ntypedef struct {\n double l, g;\n} Params;\n\nint func (double t, const double y[], double f[], void *params) {\n Params *p = (Params *) params;\n double l = p->l;\n double g = p->g;\n f[0] = y[1];\n f[1] = -(g/l)*y[0];\n return GSL_SUCCESS;\n}\n\nint jac (double t, const double y[], double *dfdy, double dfdt[],\n void *params) {\n Params *p = (Params *) params;\n double l = p->l;\n double g = p->g;\n gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);\n gsl_matrix * m = &(dfdy_mat.matrix); \n gsl_matrix_set (m, 0, 0, 0.0);\n gsl_matrix_set (m, 0, 1, 1.0);\n gsl_matrix_set (m, 1, 0, -(g/l));\n gsl_matrix_set (m, 1, 1, 0.0);\n dfdt[0] = 0.0;\n dfdt[1] = 0.0;\n return GSL_SUCCESS;\n}\n\nint main (void) {\n Params params;\n params.l = 1.0;\n params.g = 9.81;\n gsl_odeiv2_system sys = {func, jac, 2, ¶ms};\n\n gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (\n &sys, gsl_odeiv2_step_rk8pd, 1e-6, 1e-6, 0.0\n );\n int i;\n double t = 0.0, t1 = 100.0;\n double y[2] = { 0.1, 0.0 };\n\n for (i = 1; i <= 1000; i++) {\n double ti = i*t1/1000.0;\n int status = gsl_odeiv2_driver_apply (d, &t, ti, y);\n\n if (status != GSL_SUCCESS) {\n fprintf(stderr, \"error, return value=%d\\n\", status);\n break;\n }\n\n printf (\"%.5le %.5le %.5le\\n\", t, y[0], y[1]);\n }\n\n gsl_odeiv2_driver_free (d);\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c27a268c8b3af7a1b6b16a16f86e96af5fe2622d", "size": 1578, "ext": "c", "lang": "C", "max_stars_repo_path": "Math/GSL/ODEs/pendulum.c", "max_stars_repo_name": "Gjacquenot/training-material", "max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "Math/GSL/ODEs/pendulum.c", "max_issues_repo_name": "Gjacquenot/training-material", "max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "Math/GSL/ODEs/pendulum.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": 24.65625, "max_line_length": 66, "alphanum_fraction": 0.5513307985, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6047299099567033}} {"text": "/* interpolation/cspline.c\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#include \n#include \n#include \n#include \n#include \n#include \"integ_eval.h\"\n#include \n\ntypedef struct\n{\n double * c;\n double * g;\n double * diag;\n double * offdiag;\n} cspline_state_t;\n\n\n/* common initialization */\nstatic void *\ncspline_alloc (size_t size)\n{\n cspline_state_t * state = (cspline_state_t *) malloc (sizeof (cspline_state_t));\n\n if (state == NULL)\n {\n GSL_ERROR_NULL(\"failed to allocate space for state\", GSL_ENOMEM);\n }\n \n state->c = (double *) malloc (size * sizeof (double));\n \n if (state->c == NULL)\n {\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for c\", GSL_ENOMEM);\n }\n\n state->g = (double *) malloc (size * sizeof (double));\n \n if (state->g == NULL)\n {\n free (state->c);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for g\", GSL_ENOMEM);\n }\n\n state->diag = (double *) malloc (size * sizeof (double));\n \n if (state->diag == NULL)\n {\n free (state->g);\n free (state->c);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for diag\", GSL_ENOMEM);\n }\n\n state->offdiag = (double *) malloc (size * sizeof (double));\n \n if (state->offdiag == NULL)\n {\n free (state->diag);\n free (state->g);\n free (state->c);\n free (state);\n GSL_ERROR_NULL(\"failed to allocate space for offdiag\", GSL_ENOMEM);\n }\n\n return state;\n}\n\n\n/* natural spline calculation\n * see [Engeln-Mullges + Uhlig, p. 254]\n */\nstatic int\ncspline_init (void * vstate, const double xa[], const double ya[],\n size_t size)\n{\n cspline_state_t *state = (cspline_state_t *) vstate;\n\n size_t i;\n size_t num_points = size;\n size_t max_index = num_points - 1; /* Engeln-Mullges + Uhlig \"n\" */\n size_t sys_size = max_index - 1; /* linear system is sys_size x sys_size */\n\n state->c[0] = 0.0;\n state->c[max_index] = 0.0;\n\n for (i = 0; i < sys_size; i++)\n {\n const double h_i = xa[i + 1] - xa[i];\n const double h_ip1 = xa[i + 2] - xa[i + 1];\n const double ydiff_i = ya[i + 1] - ya[i];\n const double ydiff_ip1 = ya[i + 2] - ya[i + 1];\n const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;\n const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;\n state->offdiag[i] = h_ip1;\n state->diag[i] = 2.0 * (h_ip1 + h_i);\n state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);\n }\n\n if (sys_size == 1)\n {\n state->c[1] = state->g[0] / state->diag[0];\n return GSL_SUCCESS;\n }\n else\n {\n gsl_vector_view g_vec = gsl_vector_view_array(state->g, sys_size);\n gsl_vector_view diag_vec = gsl_vector_view_array(state->diag, sys_size);\n gsl_vector_view offdiag_vec = gsl_vector_view_array(state->offdiag, sys_size - 1);\n gsl_vector_view solution_vec = gsl_vector_view_array ((state->c) + 1, sys_size);\n \n int status = gsl_linalg_solve_symm_tridiag(&diag_vec.vector, \n &offdiag_vec.vector, \n &g_vec.vector, \n &solution_vec.vector);\n return status;\n }\n}\n\n\n/* periodic spline calculation\n * see [Engeln-Mullges + Uhlig, p. 256]\n */\nstatic int\ncspline_init_periodic (void * vstate, const double xa[], const double ya[],\n size_t size)\n{\n cspline_state_t *state = (cspline_state_t *) vstate;\n\n size_t i;\n size_t num_points = size;\n size_t max_index = num_points - 1; /* Engeln-Mullges + Uhlig \"n\" */\n size_t sys_size = max_index; /* linear system is sys_size x sys_size */\n\n if (sys_size == 2) {\n /* solve 2x2 system */\n \n const double h0 = xa[1] - xa[0];\n const double h1 = xa[2] - xa[1];\n\n const double A = 2.0*(h0 + h1);\n const double B = h0 + h1;\n double g[2];\n double det;\n \n g[0] = 3.0 * ((ya[2] - ya[1]) / h1 - (ya[1] - ya[0]) / h0);\n g[1] = 3.0 * ((ya[1] - ya[2]) / h0 - (ya[2] - ya[1]) / h1);\n \n det = 3.0 * (h0 + h1) * (h0 + h1);\n state->c[1] = ( A * g[0] - B * g[1])/det;\n state->c[2] = (-B * g[0] + A * g[1])/det;\n state->c[0] = state->c[2];\n \n return GSL_SUCCESS;\n } else {\n \n for (i = 0; i < sys_size-1; i++) {\n const double h_i = xa[i + 1] - xa[i];\n const double h_ip1 = xa[i + 2] - xa[i + 1];\n const double ydiff_i = ya[i + 1] - ya[i];\n const double ydiff_ip1 = ya[i + 2] - ya[i + 1];\n const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;\n const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;\n state->offdiag[i] = h_ip1;\n state->diag[i] = 2.0 * (h_ip1 + h_i);\n state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);\n }\n\n i = sys_size - 1;\n\n {\n const double h_i = xa[i + 1] - xa[i];\n const double h_ip1 = xa[1] - xa[0];\n const double ydiff_i = ya[i + 1] - ya[i];\n const double ydiff_ip1 = ya[1] - ya[0];\n const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;\n const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;\n state->offdiag[i] = h_ip1;\n state->diag[i] = 2.0 * (h_ip1 + h_i);\n state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);\n }\n \n {\n gsl_vector_view g_vec = gsl_vector_view_array(state->g, sys_size);\n gsl_vector_view diag_vec = gsl_vector_view_array(state->diag, sys_size);\n gsl_vector_view offdiag_vec = gsl_vector_view_array(state->offdiag, sys_size);\n gsl_vector_view solution_vec = gsl_vector_view_array ((state->c) + 1, sys_size);\n \n int status = gsl_linalg_solve_symm_cyc_tridiag(&diag_vec.vector, \n &offdiag_vec.vector, \n &g_vec.vector, \n &solution_vec.vector);\n state->c[0] = state->c[max_index];\n \n return status;\n }\n }\n}\n\n\nstatic\nvoid\ncspline_free (void * vstate)\n{\n cspline_state_t *state = (cspline_state_t *) vstate;\n \n free (state->c);\n free (state->g);\n free (state->diag);\n free (state->offdiag);\n free (state);\n}\n\n/* function for common coefficient determination\n */\nstatic inline void\ncoeff_calc (const double c_array[], double dy, double dx, size_t index, \n double * b, double * c, double * d)\n{\n const double c_i = c_array[index];\n const double c_ip1 = c_array[index + 1];\n *b = (dy / dx) - dx * (c_ip1 + 2.0 * c_i) / 3.0;\n *c = c_i;\n *d = (c_ip1 - c_i) / (3.0 * dx);\n}\n\n\nstatic\nint\ncspline_eval (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double *y)\n{\n const cspline_state_t *state = (const cspline_state_t *) vstate;\n\n double x_lo, x_hi;\n double dx;\n size_t index;\n \n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n x_hi = x_array[index + 1];\n x_lo = x_array[index];\n dx = x_hi - x_lo;\n if (dx > 0.0)\n {\n const double y_lo = y_array[index];\n const double y_hi = y_array[index + 1];\n const double dy = y_hi - y_lo;\n double delx = x - x_lo;\n double b_i, c_i, d_i; \n coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);\n *y = y_lo + delx * (b_i + delx * (c_i + delx * d_i));\n return GSL_SUCCESS;\n }\n else\n {\n *y = 0.0;\n return GSL_EINVAL;\n }\n}\n\n\nstatic\nint\ncspline_eval_deriv (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double *dydx)\n{\n const cspline_state_t *state = (const cspline_state_t *) vstate;\n\n double x_lo, x_hi;\n double dx;\n size_t index;\n \n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n x_hi = x_array[index + 1];\n x_lo = x_array[index];\n dx = x_hi - x_lo;\n if (dx > 0.0)\n {\n const double y_lo = y_array[index];\n const double y_hi = y_array[index + 1];\n const double dy = y_hi - y_lo;\n double delx = x - x_lo;\n double b_i, c_i, d_i; \n coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);\n *dydx = b_i + delx * (2.0 * c_i + 3.0 * d_i * delx);\n return GSL_SUCCESS;\n }\n else\n {\n *dydx = 0.0;\n return GSL_EINVAL;\n }\n}\n\n\nstatic\nint\ncspline_eval_deriv2 (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n double x,\n gsl_interp_accel * a,\n double * y_pp)\n{\n const cspline_state_t *state = (const cspline_state_t *) vstate;\n\n double x_lo, x_hi;\n double dx;\n size_t index;\n \n if (a != 0)\n {\n index = gsl_interp_accel_find (a, x_array, size, x);\n }\n else\n {\n index = gsl_interp_bsearch (x_array, x, 0, size - 1);\n }\n \n /* evaluate */\n x_hi = x_array[index + 1];\n x_lo = x_array[index];\n dx = x_hi - x_lo;\n if (dx > 0.0)\n {\n const double y_lo = y_array[index];\n const double y_hi = y_array[index + 1];\n const double dy = y_hi - y_lo;\n double delx = x - x_lo;\n double b_i, c_i, d_i;\n coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);\n *y_pp = 2.0 * c_i + 6.0 * d_i * delx;\n return GSL_SUCCESS;\n }\n else\n {\n *y_pp = 0.0;\n return GSL_EINVAL;\n }\n}\n\n\nstatic\nint\ncspline_eval_integ (const void * vstate,\n const double x_array[], const double y_array[], size_t size,\n gsl_interp_accel * acc,\n double a, double b,\n double * result)\n{\n const cspline_state_t *state = (const cspline_state_t *) vstate;\n\n size_t i, index_a, index_b;\n \n if (acc != 0)\n {\n index_a = gsl_interp_accel_find (acc, x_array, size, a);\n index_b = gsl_interp_accel_find (acc, x_array, size, b);\n }\n else\n {\n index_a = gsl_interp_bsearch (x_array, a, 0, size - 1);\n index_b = gsl_interp_bsearch (x_array, b, 0, size - 1);\n }\n\n *result = 0.0;\n \n /* interior intervals */\n for(i=index_a; i<=index_b; i++) {\n const double x_hi = x_array[i + 1];\n const double x_lo = x_array[i];\n const double y_lo = y_array[i];\n const double y_hi = y_array[i + 1];\n const double dx = x_hi - x_lo;\n const double dy = y_hi - y_lo;\n if(dx != 0.0) {\n double b_i, c_i, d_i; \n coeff_calc(state->c, dy, dx, i, &b_i, &c_i, &d_i);\n \n if (i == index_a || i == index_b)\n {\n double x1 = (i == index_a) ? a : x_lo;\n double x2 = (i == index_b) ? b : x_hi;\n *result += integ_eval(y_lo, b_i, c_i, d_i, x_lo, x1, x2);\n }\n else\n {\n *result += dx * (y_lo + dx*(0.5*b_i + dx*(c_i/3.0 + 0.25*d_i*dx)));\n }\n }\n else {\n *result = 0.0;\n return GSL_EINVAL;\n }\n }\n \n return GSL_SUCCESS;\n}\n\nstatic const gsl_interp_type cspline_type = \n{\n \"cspline\", \n 3,\n &cspline_alloc,\n &cspline_init,\n &cspline_eval,\n &cspline_eval_deriv,\n &cspline_eval_deriv2,\n &cspline_eval_integ,\n &cspline_free\n};\n\nconst gsl_interp_type * gsl_interp_cspline = &cspline_type;\n\nstatic const gsl_interp_type cspline_periodic_type = \n{\n \"cspline-periodic\", \n 2,\n &cspline_alloc,\n &cspline_init_periodic,\n &cspline_eval,\n &cspline_eval_deriv,\n &cspline_eval_deriv2,\n &cspline_eval_integ,\n &cspline_free\n};\n\nconst gsl_interp_type * gsl_interp_cspline_periodic = &cspline_periodic_type;\n\n\n", "meta": {"hexsha": "37c73d4ae1b218eca9cea206f64bcc741cb794bf", "size": 12596, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/interpolation/cspline.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/interpolation/cspline.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/interpolation/cspline.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.4621848739, "max_line_length": 88, "alphanum_fraction": 0.5645442998, "num_tokens": 3968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6046672286863092}} {"text": "// my_gsl.h is included in bayesMLR.c\n// Contains wrapper funtions \n// References: \n// https://www.gnu.org/software/gsl/manual/html_node/Matrices.html\n// https://github.com/Blei-Lab/diln/blob/master/gsl_wrapper.c\n#include // standard input/output\n#include // malloc\n#include // fabs, sqrt, etc.\n#include // time / set seed\n#include // GNU Scientific Library\n#include // GNU Scientific Library\n#include // GNU Scientific Library\n#include // GNU Scientific Library\n#include // GNU Scientific Library\n#include // GNU Scientific Library\n#include // GSL Basic Linear Algebra\n#define pi 3.14159265358979323846\n\n// Reading Matrices ////////////////////////////////////////////////\nint countFileRows(char* filename) {\n // Count number of rows in file \"filename\"\n FILE *fp;\n int count = 0; // Line counter (result)\n char c; // To store a character read from file\n\n fp = fopen(filename, \"r\");\n // Extract characters from file and store in character c\n if (fp) { // check file existence\n for (c = getc(fp); c != EOF; c = getc(fp))\n if (c == '\\n') // Increment count if this character is newline\n count = count + 1;\n }\n fclose(fp);\n\n return count;\n}\n\nint countFileCols(char* filename, char delim) {\n // Count number of columns in file \"filename\" (with delimiter delim)\n FILE *fp = fopen(filename, \"r\");\n char c;\n int count = 0;\n\n while( c=fgetc(fp) ) {\n if(c == EOF) {\n break; /* break if end of file */\n } else if (c == delim) {\n count += 1; /* otherwise add one to the count */\n } else if (c == '\\n') {\n count += 1;\n break;\n }\n }\n fclose(fp);\n\n return count;\n}\n\nvoid read_csv(char* filename, gsl_matrix* m) {\n // Read a csv into matrix m\n FILE* f = fopen(filename, \"r\");\n gsl_matrix_fscanf(f, m);\n fclose(f);\n}\n\n// Printing Matrix Info ////////////////////////////\nvoid print_vector(gsl_matrix* v, char* filename) {\n FILE* f;\n if (filename == \"\") {\n f = stdout;\n printf(\"\\n\");\n } else {\n f = fopen(filename, \"w\");\n }\n\n gsl_vector_fprintf(f,v,\"%g\");\n}\n\nvoid print_matrix(gsl_matrix* m, char* filename) {\n // print matrix to filename or stdout if filename == \"\"\n FILE* f;\n if (filename == \"\") {\n f = stdout;\n printf(\"\\n\");\n } else {\n f = fopen(filename, \"w\");\n }\n int n = m->size1;\n int k = m->size2;\n \n for (int i = 0; i < n; i++) {\n for (int j = 0; j < k; j++) {\n fprintf (f, \"%g\\t\", gsl_matrix_get (m, i, j));\n }\n fprintf (f, \"\\n\");\n }\n\n if (filename == \"\") {\n printf(\"\\n\");\n } else {\n fclose(f);\n }\n}\n\nvoid print_matrix_dims(gsl_matrix* m) {\n // print dimensions of matrix m\n printf(\"%d%s%d\\n\",m->size1,\"x\",m->size2);\n}\n\n// Access Matrix Elements: //////////////////////////////////\nvoid mat_sub(gsl_matrix* X, size_t r1, size_t r2, size_t c1, size_t c2, gsl_matrix* X_new) {\n gsl_matrix_view x = gsl_matrix_submatrix(X,r1,c1,r2-r1+1,c2-c1+1);\n gsl_matrix_memcpy(X_new,&x.matrix);\n}\n\n// Random Number Functions: /////////////////////////////////\ndouble runif() {\n // Returns a random number b/w 0 & 1\n return (double) rand() / (double) RAND_MAX;\n}\n\nvoid mvrnorm(gsl_vector* m, gsl_matrix* cholS, gsl_rng* r, gsl_vector* out) {\n // vector addition, vector prod\n // m + cholS * e\n\n int n = m->size;\n double tmp;\n gsl_vector* e = gsl_vector_alloc(n);\n\n for (int i=0; isize != y->size)\n error(\"Error in vv_add(): input vectors must have the same dimensionality\");\n else if (x->size != out->size || y->size != out->size)\n error(\"Error in vv_add(): output vector has incorrect dimensions\");\n\n double tmp;\n int n = x->size;\n\n for (int i=0; isize != y->size)\n error(\"Error in vv_prod(): input vectors must have the same dimensionality\");\n\n double out = 0;\n int n = x->size;\n\n for (int i=0; isize1,X->size2);\n gsl_permutation * p = gsl_permutation_calloc(X->size1);\n gsl_matrix_memcpy(LU,X);\n\n gsl_linalg_LU_decomp (LU,p,&signum);\n gsl_linalg_LU_invert(LU,p,invX);\n\n gsl_matrix_free(LU);\n gsl_permutation_free(p);\n}\n\nvoid xxi_m(gsl_matrix* X, gsl_matrix* xxi) {\n int n = X->size1;\n int k = X->size2;\n double dot;\n gsl_matrix* xx = gsl_matrix_alloc(k,k);\n\n for (int i=0; isize1;\n const size_t N = A->size2;\n\n if (M != N)\n {\n GSL_ERROR(\"cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else\n {\n size_t i,j,k;\n int status = 0;\n\n /* Do the first 2 rows explicitly. It is simple, and faster. And\n * one can return if the matrix has only 1 or 2 rows. \n */\n\n double A_00 = gsl_matrix_get (A, 0, 0);\n \n double L_00 = sqrt(A_00);\n \n if (A_00 <= 0)\n {\n status = GSL_EDOM ;\n }\n\n gsl_matrix_set (A, 0, 0, L_00);\n \n if (M > 1)\n {\n double A_10 = gsl_matrix_get (A, 1, 0);\n double A_11 = gsl_matrix_get (A, 1, 1);\n \n double L_10 = A_10 / L_00;\n double diag = A_11 - L_10 * L_10;\n double L_11 = sqrt(diag);\n \n if (diag <= 0)\n {\n status = GSL_EDOM;\n }\n\n gsl_matrix_set (A, 1, 0, L_10); \n gsl_matrix_set (A, 1, 1, L_11);\n }\n \n for (k = 2; k < M; k++)\n {\n double A_kk = gsl_matrix_get (A, k, k);\n \n for (i = 0; i < k; i++)\n {\n double sum = 0;\n\n double A_ki = gsl_matrix_get (A, k, i);\n double A_ii = gsl_matrix_get (A, i, i);\n\n gsl_vector_view ci = gsl_matrix_row (A, i);\n gsl_vector_view ck = gsl_matrix_row (A, k);\n\n if (i > 0) {\n gsl_vector_view di = gsl_vector_subvector(&ci.vector, 0, i);\n gsl_vector_view dk = gsl_vector_subvector(&ck.vector, 0, i);\n \n gsl_blas_ddot (&di.vector, &dk.vector, &sum);\n }\n\n A_ki = (A_ki - sum) / A_ii;\n gsl_matrix_set (A, k, i, A_ki);\n } \n\n {\n gsl_vector_view ck = gsl_matrix_row (A, k);\n gsl_vector_view dk = gsl_vector_subvector (&ck.vector, 0, k);\n \n double sum = gsl_blas_dnrm2 (&dk.vector);\n double diag = A_kk - sum * sum;\n\n double L_kk = sqrt(diag);\n \n if (diag <= 0)\n {\n status = GSL_EDOM;\n }\n \n gsl_matrix_set (A, k, k, L_kk);\n }\n }\n\n /* Now copy the transposed lower triangle to the upper triangle,\n * the diagonal is common. \n */\n \n //for (i = 1; i < M; i++)\n // {\n // for (j = 0; j < i; j++)\n // {\n // double A_ij = 0;//gsl_matrix_get (A, i, j);\n // gsl_matrix_set (A, j, i, A_ij);\n // }\n // } \n \n if (status == GSL_EDOM)\n {\n GSL_ERROR (\"matrix must be positive definite\", GSL_EDOM);\n }\n \n return GSL_SUCCESS;\n }\n}\n\nvoid chol(gsl_matrix* X, gsl_matrix* cholS) {\n int n = X->size1;\n gsl_matrix_memcpy(cholS,X);\n my_gsl_linalg_cholesky_decomp(cholS);\n\n // lower tri stored in cholS.\n // So: mvrnorm <- function(M,S,n=nrow(S)) M + chol(S) %*% rnorm(n)\n}\n", "meta": {"hexsha": "69cb15d0c3d542882fe844cfd07ff035bc91f0e1", "size": 8982, "ext": "h", "lang": "C", "max_stars_repo_path": "_posts/langcompare/code/raw.h", "max_stars_repo_name": "luiarthur/padawan", "max_stars_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "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": "_posts/langcompare/code/raw.h", "max_issues_repo_name": "luiarthur/padawan", "max_issues_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-05-17T22:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T01:19:59.000Z", "max_forks_repo_path": "_posts/langcompare/code/raw.h", "max_forks_repo_name": "luiarthur/padawan", "max_forks_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8847262248, "max_line_length": 92, "alphanum_fraction": 0.5472055222, "num_tokens": 2690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6045465171571998}} {"text": "/* randist/logarithmic.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\n/* Logarithmic distribution \n\n prob(n) = p^n / (n log(1/(1-p)) for n = 1, 2, 3, ...\n\n We use Kemp's second accelerated generator, from Luc Devroye's book\n on \"Non-Uniform Random Variate Generation\", Springer */\n\nunsigned int\ngsl_ran_logarithmic (const gsl_rng * r, const double p)\n{\n double c = log (1-p) ;\n\n double v = gsl_rng_uniform_pos (r);\n \n if (v >= p)\n {\n return 1 ;\n }\n else\n {\n double u = gsl_rng_uniform_pos (r); \n double q = 1 - exp (c * u);\n\n if (v <= q*q)\n\t{\n\t double x = 1 + log(v)/log(q) ;\n\t return x ;\n\t}\n else if (v <= q)\n\t{\n\t return 2;\n\t}\n else\n\t{\n\t return 1 ;\n\t}\n }\n}\n\ndouble\ngsl_ran_logarithmic_pdf (const unsigned int k, const double p)\n{\n if (k == 0)\n {\n return 0 ;\n }\n else \n {\n double P = pow(p, (double)k) / (double) k / log(1/(1-p)) ;\n return P;\n }\n}\n", "meta": {"hexsha": "37dffbdab209fd7a97497361a3188e18fd5bc7e2", "size": 1774, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/randist/logarithmic.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/logarithmic.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/logarithmic.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.038961039, "max_line_length": 72, "alphanum_fraction": 0.630777903, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6043910632996436}} {"text": "/* integration/qcheb.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n\n\n/* This function computes the 12-th order and 24-th order Chebyshev\n approximations to f(x) on [a,b] */\n\nvoid\ngsl_integration_qcheb (gsl_function * f, double a, double b, double *cheb12, double *cheb24)\n{\n size_t i;\n double fval[25], v[12];\n\n /* These are the values of cos(pi*k/24) for k=1..11 needed for the\n Chebyshev expansion of f(x) */\n \n const double x[11] = { 0.9914448613738104, \n 0.9659258262890683,\n 0.9238795325112868, \n 0.8660254037844386,\n 0.7933533402912352, \n 0.7071067811865475,\n 0.6087614290087206, \n 0.5000000000000000,\n 0.3826834323650898, \n 0.2588190451025208,\n 0.1305261922200516 };\n \n const double center = 0.5 * (b + a);\n const double half_length = 0.5 * (b - a);\n \n fval[0] = 0.5 * GSL_FN_EVAL (f, b);\n fval[12] = GSL_FN_EVAL (f, center);\n fval[24] = 0.5 * GSL_FN_EVAL (f, a);\n\n for (i = 1; i < 12; i++)\n {\n const size_t j = 24 - i;\n const double u = half_length * x[i-1];\n fval[i] = GSL_FN_EVAL(f, center + u);\n fval[j] = GSL_FN_EVAL(f, center - u);\n }\n\n for (i = 0; i < 12; i++)\n {\n const size_t j = 24 - i;\n v[i] = fval[i] - fval[j];\n fval[i] = fval[i] + fval[j];\n }\n\n {\n const double alam1 = v[0] - v[8];\n const double alam2 = x[5] * (v[2] - v[6] - v[10]);\n\n cheb12[3] = alam1 + alam2;\n cheb12[9] = alam1 - alam2;\n }\n\n {\n const double alam1 = v[1] - v[7] - v[9];\n const double alam2 = v[3] - v[5] - v[11];\n {\n const double alam = x[2] * alam1 + x[8] * alam2;\n\n cheb24[3] = cheb12[3] + alam;\n cheb24[21] = cheb12[3] - alam;\n }\n\n {\n const double alam = x[8] * alam1 - x[2] * alam2;\n cheb24[9] = cheb12[9] + alam;\n cheb24[15] = cheb12[9] - alam;\n }\n }\n\n {\n const double part1 = x[3] * v[4];\n const double part2 = x[7] * v[8];\n const double part3 = x[5] * v[6];\n \n {\n const double alam1 = v[0] + part1 + part2;\n const double alam2 = x[1] * v[2] + part3 + x[9] * v[10];\n \n cheb12[1] = alam1 + alam2;\n cheb12[11] = alam1 - alam2;\n }\n \n {\n const double alam1 = v[0] - part1 + part2;\n const double alam2 = x[9] * v[2] - part3 + x[1] * v[10];\n cheb12[5] = alam1 + alam2;\n cheb12[7] = alam1 - alam2;\n }\n }\n\n {\n const double alam = (x[0] * v[1] + x[2] * v[3] + x[4] * v[5]\n + x[6] * v[7] + x[8] * v[9] + x[10] * v[11]);\n cheb24[1] = cheb12[1] + alam;\n cheb24[23] = cheb12[1] - alam;\n }\n\n {\n const double alam = (x[10] * v[1] - x[8] * v[3] + x[6] * v[5] \n - x[4] * v[7] + x[2] * v[9] - x[0] * v[11]);\n cheb24[11] = cheb12[11] + alam;\n cheb24[13] = cheb12[11] - alam;\n }\n\n {\n const double alam = (x[4] * v[1] - x[8] * v[3] - x[0] * v[5] \n - x[10] * v[7] + x[2] * v[9] + x[6] * v[11]);\n cheb24[5] = cheb12[5] + alam;\n cheb24[19] = cheb12[5] - alam;\n }\n\n {\n const double alam = (x[6] * v[1] - x[2] * v[3] - x[10] * v[5] \n + x[0] * v[7] - x[8] * v[9] - x[4] * v[11]);\n cheb24[7] = cheb12[7] + alam;\n cheb24[17] = cheb12[7] - alam;\n }\n\n for (i = 0; i < 6; i++)\n {\n const size_t j = 12 - i;\n v[i] = fval[i] - fval[j];\n fval[i] = fval[i] + fval[j];\n }\n\n {\n const double alam1 = v[0] + x[7] * v[4];\n const double alam2 = x[3] * v[2];\n\n cheb12[2] = alam1 + alam2;\n cheb12[10] = alam1 - alam2;\n }\n\n cheb12[6] = v[0] - v[4];\n\n {\n const double alam = x[1] * v[1] + x[5] * v[3] + x[9] * v[5];\n cheb24[2] = cheb12[2] + alam;\n cheb24[22] = cheb12[2] - alam;\n }\n\n {\n const double alam = x[5] * (v[1] - v[3] - v[5]);\n cheb24[6] = cheb12[6] + alam;\n cheb24[18] = cheb12[6] - alam;\n }\n\n {\n const double alam = x[9] * v[1] - x[5] * v[3] + x[1] * v[5];\n cheb24[10] = cheb12[10] + alam;\n cheb24[14] = cheb12[10] - alam;\n }\n\n for (i = 0; i < 3; i++)\n {\n const size_t j = 6 - i;\n v[i] = fval[i] - fval[j];\n fval[i] = fval[i] + fval[j];\n }\n\n cheb12[4] = v[0] + x[7] * v[2];\n cheb12[8] = fval[0] - x[7] * fval[2];\n\n {\n const double alam = x[3] * v[1];\n cheb24[4] = cheb12[4] + alam;\n cheb24[20] = cheb12[4] - alam;\n }\n\n {\n const double alam = x[7] * fval[1] - fval[3];\n cheb24[8] = cheb12[8] + alam;\n cheb24[16] = cheb12[8] - alam;\n }\n\n cheb12[0] = fval[0] + fval[2];\n\n {\n const double alam = fval[1] + fval[3];\n cheb24[0] = cheb12[0] + alam;\n cheb24[24] = cheb12[0] - alam;\n }\n\n cheb12[12] = v[0] - v[2];\n cheb24[12] = cheb12[12];\n\n for (i = 1; i < 12; i++)\n {\n cheb12[i] *= 1.0 / 6.0;\n }\n\n cheb12[0] *= 1.0 / 12.0;\n cheb12[12] *= 1.0 / 12.0;\n\n for (i = 1; i < 24; i++)\n {\n cheb24[i] *= 1.0 / 12.0;\n }\n\n cheb24[0] *= 1.0 / 24.0;\n cheb24[24] *= 1.0 / 24.0;\n}\n", "meta": {"hexsha": "a6564f7640f9a8e1ebde49e831c3c4c5f2abdbbc", "size": 5893, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/integration/qcheb.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/integration/qcheb.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/integration/qcheb.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.6217391304, "max_line_length": 92, "alphanum_fraction": 0.4955031393, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6043747380234015}} {"text": "/*\n * ParticleFilter.h\n *\n * Created on: Mar 21, 2012\n * Author: nair\n */\n\n#ifndef PARTICLEFILTER_H_\n#define PARTICLEFILTER_H_\n\n#include \n#include \n#include \n\n\nnamespace tracking1\n{\n\nclass ParticleFilterParams\n{\npublic:\n ParticleFilterParams();\n ~ParticleFilterParams();\n\n void parse(std::string filename);\n\npublic:\n\n int NUMBER_OF_PARTICLES;\n\n /* standard deviations for gaussian sampling in transition model */\n float TRANS_X_STD;\n float TRANS_Y_STD;\n float TRANS_SCALE_STD;\n\n /* autoregressive dynamics parameters for transition model */\n float DYNAMICS_A1;\n float DYNAMICS_A2;\n float DYNAMICS_B0;\n\n double LAMBDA;\n\n bool DYNAMIC_MODEL_CV;\n};\n\nstruct Particle\n{\n float x; /**< current x coordinate */\n float y; /**< current y coordinate */\n float s; /**< current z coordinate */\n float xp; /**< previous x coordinate */\n float yp; /**< previous y coordinate */\n float sp; /**< previous z coordinate */\n float x0; /**< original x coordinate */\n float y0; /**< original y coordinate */\n float s0;\t\t\t/**< original z coordinate */\n float x_velocity; /**< current x_velocity coordinate */\n float y_velocity; /**< current y_velocity coordinate */\n float s_velocity; /**< current z_velocity coordinate */\n\n float w; /**< weight */\n};\n\nclass ParticleFilter\n{\npublic:\n\n ParticleFilter();\n ~ParticleFilter();\n\n void initialize(const cv::Vec3d& initPose);\n\n void predict();\n\n void predict_with_simple_model();\n\n void predict_with_cv_model();\n\n void correct();\n\n void resizeParticleSet(int n);\n void setParticleWeight(int id, float w);\n\n double getMaxLikelihood()\n {\n double max=0.0;\n for(int i=0;iw > _p2->w )\n return -1;\n if( _p1->w < _p2->w )\n return 1;\n return 0;\n }\n\n void getParticlePose(int id, cv::Vec3d& pose);\n\n void getOutputPose(cv::Vec3d& pose);\n\n void getOutputAvgPose(cv::Vec3d& pose);\n\n void getOutputVelocity(cv::Vec3d& vel);\n\n double getLambda()\n {\n return mParams.LAMBDA;\n }\n\nprivate:\n\n void normalize();\n\n void resample();\n\nprivate:\n\n\n ParticleFilterParams mParams;\n\n Particle* mParticles;\n cv::Vec3d mOutputPose;\n\n Eigen::MatrixXd A_Matrix;\n Eigen::MatrixXd G_Matrix;\n Eigen::MatrixXd W_Matrix;\n\n Eigen::MatrixXd State_Matrix;\n Eigen::MatrixXd State_Prev_Matrix;\n\n gsl_rng* rng;\n\n};\n\n\n}\n#endif /* PARTICLEFILTER_H_ */\n", "meta": {"hexsha": "8adcc57d84f0c7494340360d7573addf0b15389f", "size": 3237, "ext": "h", "lang": "C", "max_stars_repo_path": "2d-object-tracking/client/src/tracker/ParticleFilter.h", "max_stars_repo_name": "cognitivesystems/smartcamera", "max_stars_repo_head_hexsha": "5374193260e6385becfe8086a70d21d650314beb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-27T16:14:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-27T16:14:59.000Z", "max_issues_repo_path": "2d-object-tracking/client/src/tracker/ParticleFilter.h", "max_issues_repo_name": "cognitivesystems/smartcamera", "max_issues_repo_head_hexsha": "5374193260e6385becfe8086a70d21d650314beb", "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": "2d-object-tracking/client/src/tracker/ParticleFilter.h", "max_forks_repo_name": "cognitivesystems/smartcamera", "max_forks_repo_head_hexsha": "5374193260e6385becfe8086a70d21d650314beb", "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": 19.5, "max_line_length": 71, "alphanum_fraction": 0.5990114303, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6042243999127692}} {"text": "/*\n * Assignment 4, Question 5 matvec implementation in C using MPI.\n *\n * Copyright (C) 2015, Jonathan Gillett (100437638)\n * All rights reserved.\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n// Minimum of two values\n#define min(a, b) (((a) < (b)) ? (a) : (b))\n// Define process 0 as MASTER\n#define MASTER 0\n// Message tags\n#define REQUEST 1\n#define REPLY 2\n\n\n// Master process, divides up the matrix into rows for computation by slaves\nvoid master(int n_proc, int n_rows, int n_cols) {\n // 0. Allocate space for arrays as needed to compute y = A*x\n double *x = (double *) malloc(n_cols*sizeof(double));\n double *y = (double *) malloc(n_rows*sizeof(double));\n double *z = (double *) malloc(n_rows*sizeof(double));\n double *A = (double *) malloc(n_rows*n_cols*sizeof(double));\n double *sub = (double *) malloc(n_cols*sizeof(double));\n double ans = 0.0;\n int n_sent = 0, row = 0, sender = 0;\n MPI_Status status;\n\n // 1. Define data A (n_rows x n_cols matrix) and x (n_cols x 1 vector)\n for (int i = 0; i < n_cols; ++i) {\n x[i] = i+1;\n } \n for (int i = 0; i < n_rows; ++i) {\n for (int j = 0; j < n_cols; ++j) {\n A[(i*n_cols)+j] = i+1;\n }\n }\n \n // 2. Broadcast vector x to all processes\n MPI_Bcast(x, n_cols, MPI_DOUBLE, MASTER, MPI_COMM_WORLD);\n\n // 3. Send first rows to other processes\n for (int i = 1; i < min(n_rows+1, n_proc); ++i) {\n \tmemcpy((void *) sub, (void *) &A[n_sent*n_cols], n_cols * sizeof(double));\n MPI_Send(sub, n_cols, MPI_DOUBLE, i, n_sent, MPI_COMM_WORLD);\n n_sent++;\n }\n\n // Now loop over remaining rows, receiving dot products computed\n for (int i = 0; i < n_rows; ++i) {\n // Receive a computed inner product from one of the processes\n MPI_Recv(&ans, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG,\n MPI_COMM_WORLD, &status);\n sender = status.MPI_SOURCE;\n row = status.MPI_TAG;\n y[row] = ans;\n\n // Either send another row back to sender or send final y=Ax\n // along with a tag to signal completion.\n if (n_sent < n_rows) {\n \tmemcpy((void *) sub, (void *) &A[n_sent*n_cols], n_cols * sizeof(double));\n MPI_Send(sub, n_cols, MPI_DOUBLE, sender, n_sent, MPI_COMM_WORLD);\n n_sent++;\n }\n // Inform sender that there is no more work\n else {\n MPI_Send(y, n_rows, MPI_DOUBLE, sender, n_rows+1, MPI_COMM_WORLD);\n }\n }\n\n printf(\"Finished!\\n\");\n // Calculate the norm to verify ||y-Ax|| is correct\n cblas_dgemv(CblasRowMajor, CblasNoTrans, n_rows, n_cols, 1.0, A, n_cols,\n\t \t\tx, 1, 0.0, z, 1);\n for (int i = 0; i < n_rows; ++i) {\n \ty[i] -= z[i];\n }\n printf(\"Check: ||y-Ax|| = %f\\n\", cblas_dnrm2(n_rows, y, 1));\n\n free(x);\n free(y);\n free(z);\n free(A);\n free(sub);\n}\n\n\n// Slave process computes inner product and returns result to master process\nvoid slave(int proc_id, int n_rows, int n_cols) {\n // Allocate arrays for receiving and sending rows & dot products\n double *x = (double *) malloc(n_cols*sizeof(double));\n double *my_row = (double *) malloc(n_cols*sizeof(double));\n double ans = 0.0;\n int row = 0;\n MPI_Status status;\n\n // 1. Receive vector x from master process\n MPI_Bcast(x, n_cols, MPI_DOUBLE, MASTER, MPI_COMM_WORLD);\n\n // Receive row to calculate from master process\n MPI_Recv(my_row, n_cols, MPI_DOUBLE, MASTER, MPI_ANY_TAG, \n MPI_COMM_WORLD, &status);\n row = status.MPI_TAG;\n\n while (row < n_rows) {\n // Compute inner product and return result to master process\n ans = cblas_ddot(n_cols, my_row, 1, x, 1);\n MPI_Send(&ans, 1, MPI_DOUBLE, MASTER, row, MPI_COMM_WORLD);\n // Receive new row from master\n MPI_Recv(my_row, n_cols, MPI_DOUBLE, MASTER, MPI_ANY_TAG, \n MPI_COMM_WORLD, &status);\n row = status.MPI_TAG;\n }\n}\n\n\nint main(int argc, char *argv[]) {\n int proc_id; // Process ID number\n int n_proc; // Number of processes\n int n_rows = 1000; // Number of rows\n int n_cols = 1000; // Number of columns\n\n // Initialize MPI\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &n_proc);\n MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);\n\n if (n_proc == 1) {\n puts(\"Error: requires two or more processes (no work will be done).\");\n MPI_Finalize();\n exit(1);\n }\n\n if (proc_id == MASTER) {\n master(n_proc, n_rows, n_cols);\n }\n else {\n slave(proc_id, n_rows, n_cols);\n }\n\n MPI_Finalize();\n return 0;\n}\n", "meta": {"hexsha": "83ed710e839fc1d7bca56cfd184de326fa73e92d", "size": 4706, "ext": "c", "lang": "C", "max_stars_repo_path": "Assignment-04/Question-05/matvec.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-04/Question-05/matvec.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-04/Question-05/matvec.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": 31.3733333333, "max_line_length": 83, "alphanum_fraction": 0.5990225244, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6040929332544549}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include // memcpy\n#include \n\n#include \"cgraph.h\"\n#include \"cg_operation.h\"\n#include \"cg_types.h\"\n#include \"cg_variables.h\"\n#include \"cg_errors.h\"\n#include \"cg_constants.h\"\n#include \"cg_enums.h\"\n#include \"cg_factory.h\"\n#include \"cg_math.h\"\n\n\n\n\n#if cg_float == float\n#define cblas_dcopy cblas_scopy\n#define cblas_dscal cblas_sscal\n#define cblas_dgemm cblas_sgemm\n#define cblas_ddot cblas_sdot\n#define cblas_dgemv cblas_sgemv\n#endif\n\nint selectContext() {\n return 0;\n}\n\n\nvoid copyDataToHost(CGResultNode* res){}\n\n/*\n * *********************\n * Multiplication\n * *********************\n */\n\n/*\n * d.d\n */\nCGResultNode* mulDD(CGDouble* M, CGDouble* V, CGraph* graph, CGNode* parentNode){\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = M->value * V->value;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * d.V == V.d\n */\nCGResultNode* mulDV(CGDouble* a, CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = V->len;\n Y->data = y;\n\n if(a->value != 0){\n cblas_dcopy(V->len, V->data, 1, y, 1);\n cblas_dscal(V->len, a->value, y, 1);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * d.M == M.d\n */\nCGResultNode* mulDM(CGDouble* a, CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->cols*M->rows;\n cg_float value = a->value;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = y;\n\n if(a->value != 0){\n cblas_dcopy(size, M->data, 1, y, 1);\n cblas_dscal(size, a->value, y, 1);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M*v\n * broadcasting\n */\nCGResultNode* mulMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n if(M->cols != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Add M(%\"PRIu64\", %\"PRIu64\") by V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M->cols*M->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] * V->data[(i)%V->len];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * Mv\n */\n/*\nCGResultNode* mulMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n\tif(M->cols != V->len){\n\t\tchar msg[MAX_ERR_FMT_LEN];\n\t\tsnprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Add M(%\"PRIu64\", %\"PRIu64\") by V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n\t\treturn returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n\t}\n\n\tuint64_t size = M->cols*M->rows;\n\tcg_float* res = calloc(size, sizeof(cg_float));\n\n\tCGMatrix* Y = calloc(1, sizeof(CGMatrix));\n\tY->rows = M->rows;\n\tY->cols = M->cols;\n\tY->data = res;\n\n\tuint64_t i = 0;\n\n\tfor(;idata[i] * V->data[(i)%V->len];\n\t}\n\n\tCGResultNode* result = calloc(1, sizeof(CGResultNode));\n\tresult->type = CGVT_MATRIX;\n\tresult->value = Y;\n\n\treturn result;\n}\n*/\n\n/*\n * M*N\n * broadcasting\n */\nCGResultNode* mulMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){\n if((M1->rows != M2->rows) && (M1->cols != M2->cols)){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot multiply M(%\"PRIu64\", %\"PRIu64\") by N(%\"PRIu64\", %\"PRIu64\")\", M1->rows, M1->cols, M2->rows, M2->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M1->cols*M1->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M1->rows;\n Y->cols = M1->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n\n for(;idata[i] * M2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M.v\n */\nCGResultNode* dotMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n if(M->cols != 1){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot calculate M(%\"PRIu64\", %\"PRIu64\") DOT V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n cg_float* y = calloc(M->rows*V->len, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows= M->rows;\n Y->cols = V->len;\n Y->data = y;\n\n /*\n cblas_dgemv(CblasRowMajor,\n CblasNoTrans, M->rows, M->cols, 1.0, M->data,\n M->cols, V->data, 1, 0.0, Y->data, 1);\n */\n\n\n cblas_dgemm(CblasRowMajor,\n CblasNoTrans, CblasNoTrans, M->rows, V->len, M->cols,\n 1.0, M->data, M->cols, V->data, V->len, 0, y, Y->cols);\n\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * v.M\n */\nCGResultNode* dotVM(CGVector* V, CGMatrix* M, CGraph* graph, CGNode* parentNode){\n if(M->rows != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot calculate V(%\"PRIu64\") DOT M(%\"PRIu64\", %\"PRIu64\")\", V->len, M->rows, M->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n cg_float* y = calloc(M->cols, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = M->cols;\n Y->data = y;\n\n int m = 1;\n int n = M->cols;\n int k = V->len;\n\n cblas_dgemm(CblasRowMajor,\n CblasNoTrans, CblasNoTrans, m, n, k, 1, V->data, k, M->data, n, 0, Y->data, n);\n\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M.N\n */\nCGResultNode* dotMM(CGMatrix* M, CGMatrix* N, CGraph* graph, CGNode* parentNode){\n if(M->cols != N->rows){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot DOT M(%\"PRIu64\", %\"PRIu64\") by N(%\"PRIu64\", %\"PRIu64\")\", M->rows, M->cols, N->rows, N->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n cg_float* z = calloc(M->rows*N->cols, sizeof(cg_float));\n\n CGMatrix* Z = calloc(1, sizeof(CGMatrix));\n Z->rows = M->rows;\n Z->cols = N->cols;\n\n cblas_dgemm(CblasRowMajor,\n CblasNoTrans, CblasNoTrans, M->rows, N->cols, M->cols,\n 1.0, M->data, M->cols, N->data, N->cols, 0, z, Z->cols);\n\n Z->data = z;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Z;\n\n return result;\n}\n\n\n/*\n * V.V\n */\nCGResultNode* crossVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){\n if(V1->len != V2->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot compute Cross Product of V(%\"PRIu64\") by V(%\"PRIu64\")\", V1->len, V2->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = V1->len;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = V1->len;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] * V2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * Dot Product\n * *********************\n */\n\n/*\n * V.V\n */\nCGResultNode* dotVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){\n if(V1->len != V2->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot compute Dot Product of V(%\"PRIu64\") by V(%\"PRIu64\")\", V1->len, V2->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = V1->len;\n cg_float res = 0;\n\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = cblas_ddot(V1->len, V1->data, 1, V2->data, 1);\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * Division\n * *********************\n */\n\n/*\n * d/d\n */\nCGResultNode* divDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){\n if(D2->value == 0.0){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Diving by zero D/(D=0)\");\n return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg);\n }\n\n cg_float res = D1->value / D2->value;\n\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = res;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V/d\n */\nCGResultNode* divVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){\n if(D->value == 0.0){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Diving by zero V/(D=0)\");\n return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg);\n }\n\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n cblas_dcopy(V->len, V->data, 1, res, 1);\n cblas_dscal(V->len, 1.0/D->value, res, 1);\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V/V\n */\nCGResultNode* divVV(CGVector* V, CGVector* D, CGraph* graph, CGNode* parentNode){\n if(V->len != D->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot calculate V(%\"PRIu64\") DIV V(%\"PRIu64\")\", V->len, D->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n cg_float* res = calloc(V->len, sizeof(cg_float));\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n for(;ilen;i++){\n res[i] = V->data[i]/D->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * d/V element-wise\n */\nCGResultNode* divDV(CGDouble* D, CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n res[i] = value / V->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M/d\n */\nCGResultNode* divMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){\n if(D->value == 0.0){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Diving by zero M/(D=0)\");\n return returnResultError(graph, CGET_DIVIDE_BY_ZERO, parentNode, msg);\n }\n\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n cblas_dcopy(size, M->data, 1, res, 1);\n cblas_dscal(size, 1.0/D->value, res, 1);\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M/v\n */\nCGResultNode* divMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n if(M->rows != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot calculate M(%\"PRIu64\", %\"PRIu64\") DIV V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(; i < size;i++)\n {\n res[i] = M->data[i] / V->data[i/M->cols];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * d/M element-wise\n */\nCGResultNode* divDM(CGDouble* D, CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * Addition\n * *********************\n */\n\n/*\n * d+d\n */\nCGResultNode* addDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){\n cg_float res = D1->value + D2->value;\n\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = res;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V+d\n */\nCGResultNode* addVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n res[i] = V->data[i] + value;\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M+d\n */\nCGResultNode* addMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] + value;\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V+V\n */\nCGResultNode* addVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){\n if(V1->len != V2->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Add V(%\"PRIu64\") by V(%\"PRIu64\")\", V1->len, V2->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = V1->len;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = V1->len;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] + V2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n\n\n/*\n * M+V\n */\nCGResultNode* addMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n if(M->cols != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Add M(%\"PRIu64\", %\"PRIu64\") by V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M->cols*M->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] + V->data[(i)%V->len];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M+M\n */\nCGResultNode* addMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){\n if((M1->rows != M2->rows) && (M1->cols != M2->cols)){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot add M(%\"PRIu64\", %\"PRIu64\") by N(%\"PRIu64\", %\"PRIu64\")\", M1->rows, M1->cols, M2->rows, M2->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M1->cols*M1->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M1->rows;\n Y->cols = M1->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] + M2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * Substraction\n * *********************\n */\n\n/*\n * d-d\n */\nCGResultNode* subDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){\n cg_float res = D1->value - D2->value;\n\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = res;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V-d\n */\nCGResultNode* subVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n res[i] = V->data[i] - value;\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * d-V\n */\nCGResultNode* subDV(CGDouble* D, CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n res[i] = value - V->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * M-d\n */\nCGResultNode* subMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] - value;\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * D-M\n */\nCGResultNode* subDM(CGDouble* D, CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * V-V\n */\nCGResultNode* subVV(CGVector* V1, CGVector* V2, CGraph* graph, CGNode* parentNode){\n if(V1->len != V2->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Substract V(%\"PRIu64\") by V(%\"PRIu64\")\", V1->len, V2->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = V1->len;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = V1->len;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] - V2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M-M\n */\nCGResultNode* subMM(CGMatrix* M1, CGMatrix* M2, CGraph* graph, CGNode* parentNode){\n if((M1->rows != M2->rows) && (M1->cols != M2->cols)){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Substract M(%\"PRIu64\", %\"PRIu64\") by N(%\"PRIu64\", %\"PRIu64\")\", M1->rows, M1->cols, M2->rows, M2->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M1->cols*M1->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M1->rows;\n Y->cols = M1->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] - M2->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M-V\n */\nCGResultNode* subMV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n if(M->rows != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Substract M(%\"PRIu64\", %\"PRIu64\") by V(%\"PRIu64\")\", M->rows, M->cols, V->len);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M->cols*M->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i] - V->data[(i)/M->cols];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V-M\n */\nCGResultNode* subVM(CGVector* V, CGMatrix* M, CGraph* graph, CGNode* parentNode){\n\n if(M->rows != V->len){\n char msg[MAX_ERR_FMT_LEN];\n snprintf(msg, MAX_ERR_FMT_LEN, \"Cannot Substract V(%\"PRIu64\") by M(%\"PRIu64\", %\"PRIu64\")\", V->len, M->rows, M->cols);\n return returnResultError(graph, CGET_INCOMPATIBLE_DIMENTIONS_EXCEPTION, parentNode, msg);\n }\n\n uint64_t size = M->cols*M->rows;\n cg_float* res = calloc(size, sizeof(cg_float));\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[(i)/M->cols] - M->data[i];\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * Power\n * *********************\n */\n\n/*\n * d^d\n */\nCGResultNode* powDD(CGDouble* D1, CGDouble* D2, CGraph* graph, CGNode* parentNode){\n cg_float res = pow(D1->value, D2->value);\n\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = res;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * V^d\n */\nCGResultNode* powVD(CGVector* V, CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float* res = calloc(V->len, sizeof(cg_float));\n cg_float value = D->value;\n\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = res;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n res[i] = pow(V->data[i], value);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * M^d\n */\nCGResultNode* powMD(CGMatrix* M, CGDouble* D, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n cg_float* res = calloc(size, sizeof(cg_float));\n cg_float value = D->value;\n\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->rows = M->rows;\n Y->cols = M->cols;\n Y->data = res;\n\n uint64_t i = 0;\n\n for(;idata[i], value);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * Transpose Multiplication\n * *********************\n */\n/*\n * M^T.v\n */\nCGResultNode* mulMtV(CGMatrix* M, CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->len = V->len;\n Y->data = y;\n\n cblas_dgemv(CblasRowMajor,\n CblasTrans, M->rows, M->cols, 1.0, M->data,\n V->len, V->data, 1, 0.0, Y->data, 1);\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * exp(d)\n */\nCGResultNode* expD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = exp(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * exp(v)\n */\nCGResultNode* expV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = exp(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * exp(M)\n */\nCGResultNode* expM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * log(d)\n */\nCGResultNode* logD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = log(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * log(V)\n */\nCGResultNode* logV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = log(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * exp(M)\n */\nCGResultNode* logM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * Sin\n * *********************\n */\n\n/*\n * sin(d)\n */\nCGResultNode* sinD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = sin(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * sin(V)\n */\nCGResultNode* sinV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = sin(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * sin(M)\n */\nCGResultNode* sinM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * cos\n * *********************\n */\n\n/*\n * cos(d)\n */\nCGResultNode* cosD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = cos(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * cos(V)\n */\nCGResultNode* cosV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = cos(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * cos(M)\n */\nCGResultNode* cosM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * tan\n * *********************\n */\n\n/*\n * tan(d)\n */\nCGResultNode* tanD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = tan(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * tan(V)\n */\nCGResultNode* tanV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = tan(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * tan(M)\n */\nCGResultNode* tanM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * tanh\n * *********************\n */\n\n/*\n * tanh(d)\n */\nCGResultNode* tanhD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = tanh(D->value);\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * tanh(V)\n */\nCGResultNode* tanhV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n CGVector* Y = calloc(1, sizeof(CGVector));\n Y->data = y;\n Y->len = V->len;\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y[i] = tanh(V->data[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = Y;\n\n return result;\n}\n\n/*\n * tanh(M)\n */\nCGResultNode* tanhM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->rows;\n Y->cols = M->cols;\n\n uint64_t i = 0;\n\n for(;idata[i]);\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n/*\n * *********************\n * Invert\n * *********************\n */\n\n// TODO\n\n/*\n * *********************\n * Transpose\n * *********************\n */\n\n/*\n * D^t\n */\nCGResultNode* transposeD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n CGDouble* R = calloc(1, sizeof(CGDouble));\n R->value = D->value;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = R;\n\n return result;\n}\n\n\n/*\n * V^t\n */\nCGResultNode* transposeV(CGVector* V, CGraph* graph, CGNode* parentNode){\n uint64_t size = V->len;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = V->len;\n Y->cols = 1;\n Y->data = y;\n\n uint64_t i = 0;\n uint64_t j = 0;\n\n memcpy(Y->data, V->data, V->len*sizeof(cg_float));\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * M^t\n */\nCGResultNode* transposeM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t size = M->rows*M->cols;\n\n cg_float* y = calloc(size, sizeof(cg_float));\n CGMatrix* Y = calloc(1, sizeof(CGMatrix));\n Y->data = y;\n Y->rows = M->cols;\n Y->cols = M->rows;\n Y->data = y;\n\n uint64_t i = 0;\n uint64_t j = 0;\n\n for(;irows;i++){\n for(j = 0;jcols;j++){\n y[j*Y->cols+i] = M->data[i*M->cols +j];\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_MATRIX;\n result->value = Y;\n\n return result;\n}\n\n\n/*\n * *********************\n * SUM\n * *********************\n */\n\n/*\n * sum(D)\n */\nCGResultNode* sumD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float y = D->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n Y->value = y;\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * sum(V)\n */\nCGResultNode* sumV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 0;\n\n for(;ilen;i++){\n y += V->data[i];\n }\n\n Y->value = y;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n}\n\n/*\n * TODO:\n * sum(M, axis=axis)\n */\n\nCGResultNode* sumM(CGMatrix* M, CGraph* graph, CGNode* parentNode, uint8_t axis){\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows*M->cols;i++){\n y[i%len] += M->data[i];\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows*M->cols;i++){\n y[i/M->cols] += M->data[i];\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n}\n\n\nCGResultNode* max(CGNode* X, CGraph* graph){\n CGResultNode* res = computeCGNode(graph, X->axop->uhs);\n\n switch(res->type){\n case CGVT_DOUBLE:\n {\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = ((CGDouble*)res->value)->value;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_VECTOR:\n {\n CGVector* v = (CGVector*)res->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 1;\n cg_float m = v->data[0];\n\n for (;i < v->len; i++){\n if(v->data[i] > m)\n m = v->data[i];\n }\n\n Y->value = m;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_MATRIX: {\n CGMatrix* M = (CGMatrix*)res->value;\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(X->axop->axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;icols;i++){\n y[i] = M->data[i];\n }\n\n for(i=0;irows*M->cols;i++){\n if(y[i%len] < M->data[i])\n y[i%len] = M->data[i];\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows;i++){\n y[i] = M->data[i*M->cols];\n }\n\n for(i=0;irows*M->cols;i++){\n if(y[i/M->cols] < M->data[i])\n y[i/M->cols] = M->data[i];\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n\n }\n }\n}\n\n\nCGResultNode* min(CGNode* X, CGraph* graph){\n CGResultNode* res = computeCGNode(graph, X->axop->uhs);\n\n switch(res->type){\n case CGVT_DOUBLE:\n {\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = ((CGDouble*)res->value)->value;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_VECTOR:\n {\n CGVector* v = (CGVector*)res->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 1;\n cg_float m = v->data[0];\n\n for (;i < v->len; i++){\n if(v->data[i] > m)\n m = v->data[i];\n }\n\n Y->value = m;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_MATRIX: {\n CGMatrix* M = (CGMatrix*)res->value;\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(X->axop->axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;icols;i++){\n y[i] = M->data[i];\n }\n\n for(i=0;irows*M->cols;i++){\n if(y[i%len] > M->data[i])\n y[i%len] = M->data[i];\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows;i++){\n y[i] = M->data[i*M->cols];\n }\n\n for(i=0;irows*M->cols;i++){\n if(y[i/M->cols] > M->data[i])\n y[i/M->cols] = M->data[i];\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n\n }\n }\n}\n\n\nCGResultNode* argmax(CGNode* X, CGraph* graph){\n CGResultNode* res = computeCGNode(graph, X->axop->uhs);\n\n switch(res->type){\n case CGVT_DOUBLE:\n {\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = ((CGDouble*)res->value)->value;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_VECTOR:\n {\n CGVector* v = (CGVector*)res->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 1;\n uint64_t maxIdx = 0;\n\n for (;i < v->len; i++){\n if(v->data[i] > v->data[maxIdx])\n maxIdx = i;\n }\n\n Y->value = maxIdx;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_MATRIX: {\n CGMatrix* M = (CGMatrix*)res->value;\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(X->axop->axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;icols;i++){\n y[i] = i;\n }\n\n for(i=0;irows*M->cols;i++){\n if(M->data[(uint64_t)y[i%len]] < M->data[i])\n y[i%len] = i;\n }\n\n // transform vector representation into matrix\n for(i=0;icols;i++){\n y[i] = ((int)y[i])/M->cols;\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows;i++){\n y[i] = i*M->cols;\n }\n\n for(i=0;irows*M->cols;i++){\n if(M->data[(uint64_t)y[i/M->cols]] < M->data[i])\n y[i/M->cols] = i;\n }\n\n // transform vector representation into matrix\n for(i=0;irows;i++){\n y[i] = ((int)y[i])%M->cols;\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n\n }\n }\n}\n\n\nCGResultNode* argmin(CGNode* X, CGraph* graph){\n CGResultNode* res = computeCGNode(graph, X->axop->uhs);\n\n switch(res->type){\n case CGVT_DOUBLE:\n {\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = 0;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_VECTOR:\n {\n CGVector* v = (CGVector*)res->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 1;\n uint64_t minIdx = 0;\n\n for (;i < v->len; i++){\n if(v->data[i] > v->data[minIdx])\n minIdx = (cg_float)i;\n }\n\n Y->value = minIdx;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_MATRIX: {\n CGMatrix* M = (CGMatrix*)res->value;\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(X->axop->axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;icols;i++){\n y[i] = i;\n }\n\n for(i=0;irows*M->cols;i++){\n if(M->data[(uint64_t)y[i%len]] > M->data[i])\n y[i%len] = (cg_float)i;\n }\n\n // transform vector representation into matrix\n for(i=0;icols;i++){\n y[i] = ((int)y[i])/M->cols;\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows;i++){\n y[i] = i*M->cols;\n }\n\n for(i=0;irows*M->cols;i++){\n if(M->data[(uint64_t)y[i/M->cols]] > M->data[i])\n y[i/M->cols] = (cg_float)i;\n }\n\n\n // transform vector representation into matrix\n for(i=0;irows;i++){\n y[i] = ((int)y[i])%M->cols;\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n\n }\n }\n}\n\nCGResultNode* mean(CGNode* X, CGraph* graph){\n CGResultNode* res = computeCGNode(graph, X->axop->uhs);\n\n switch(res->type){\n case CGVT_DOUBLE:\n {\n cg_float y = 0;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n Y->value = ((CGDouble*)res->value)->value;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_VECTOR:\n {\n CGVector* v = (CGVector*)res->value;\n CGDouble* Y = calloc(1, sizeof(CGDouble));\n\n uint64_t i = 0;\n cg_float m = v->data[0];\n\n for (;i < v->len; i++){\n m += v->data[i];\n }\n\n m /= v->len;\n\n Y->value = m;\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_DOUBLE;\n result->value = Y;\n\n return result;\n }\n\n case CGVT_MATRIX: {\n CGMatrix* M = (CGMatrix*)res->value;\n CGVector* V = calloc(1, sizeof(CGVector));\n\n if(X->axop->axis == 0){\n uint64_t len = M->cols;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows*M->cols;i++){\n y[i%len] += M->data[i];\n }\n\n\n for(i=0;icols;i++){\n y[i] /= M->rows;\n }\n }\n else {\n uint64_t len = M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n\n V->data = y;\n V->len = len;\n\n uint64_t i = 0;\n\n for(;irows*M->cols;i++){\n y[i/M->cols] += M->data[i];\n }\n\n for(i=0;irows;i++){\n y[i] /= M->cols;\n }\n }\n\n CGResultNode* result = calloc(1, sizeof(CGResultNode));\n result->type = CGVT_VECTOR;\n result->value = V;\n\n return result;\n\n }\n }\n}\n\n\n/*\n * relu(d)\n */\nCGResultNode* reluD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float val = D->value;\n return makeDoubleResultNode(__cg_relu(val));\n}\n\n\n/*\n * relu(V)\n */\nCGResultNode* reluV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n __cg_map_array(V->data, y, V->len, __cg_relu);\n return makeVectorResultNode(V->len, y);\n}\n\n/*\n * relu(M)\n */\nCGResultNode* reluM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t len = M->cols*M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n __cg_map_array(M->data, y, len, __cg_relu);\n return makeMatrixResultNode(M->rows, M->cols, y);\n}\n\n/*\n * softplus(d)\n */\nCGResultNode* softplusD(CGDouble* D, CGraph* graph, CGNode* parentNode){\n cg_float val = D->value;\n return makeDoubleResultNode(__cg_softplus(val));\n}\n\n\n/*\n * softplus(V)\n */\nCGResultNode* softplusV(CGVector* V, CGraph* graph, CGNode* parentNode){\n cg_float* y = calloc(V->len, sizeof(cg_float));\n __cg_map_array(V->data, y, V->len, __cg_softplus);\n return makeVectorResultNode(V->len, y);\n}\n\n/*\n * softplus(M)\n */\nCGResultNode* softplusM(CGMatrix* M, CGraph* graph, CGNode* parentNode){\n uint64_t len = M->cols*M->rows;\n cg_float* y = calloc(len, sizeof(cg_float));\n __cg_map_array(M->data, y, len, __cg_softplus);\n return makeMatrixResultNode(M->rows, M->cols, y);\n}\n\n\n#if cg_float == float\n#undef cblas_dcopy\n#undef cblas_dscal\n#undef cblas_dgemm\n#undef cblas_ddot\n#undef cblas_dgemv\n#endif", "meta": {"hexsha": "39b3836c824be52c708e72889f3292e103a89dfc", "size": 50472, "ext": "c", "lang": "C", "max_stars_repo_path": "source/libcgraph/source/cg_cpuops.c", "max_stars_repo_name": "Enehcruon/cgraph", "max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z", "max_issues_repo_path": "source/libcgraph/source/cg_cpuops.c", "max_issues_repo_name": "Enehcruon/cgraph", "max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z", "max_forks_repo_path": "source/libcgraph/source/cg_cpuops.c", "max_forks_repo_name": "praisethemoon/ccgraph", "max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z", "avg_line_length": 23.2589861751, "max_line_length": 150, "alphanum_fraction": 0.537466318, "num_tokens": 14937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6040469230981796}} {"text": "#include \n#include \n#include \n#include \n\n\n#define NCols 5\n#define Nrows 4\n\nfloat A[] = { 8, 4, 7, 3, 5, 1, 1, 3, 2, 1, 2, 3, 2, 0, 1, 1 , 2, 3, 4, 1};\n\nfloat x[] = { -1, 2, -1, 1, 2 };\n\nfloat y[Nrows];\nfloat alpha = 1.0, beta = 0.0;\nchar tbuf[1024];\nint main() {\n int i, j;\n\n // Print original matrix\n\n // y = Ax\n cblas_sgemv(CblasRowMajor, CblasNoTrans, Nrows, NCols, alpha, A, NCols, x, 1, beta, y, 1);\n // Print resulting vector\n for (j = 0; j < Nrows; j++) {\n printf(\" %f\\n\", y[j]);\n }\n\n cblas_sgemv(CblasColMajor, CblasNoTrans, Nrows, NCols, alpha, A, Nrows, x, 1, beta, y, 1);\n // Print resulting vector\n for (j = 0; j < Nrows; j++) {\n printf(\" %f\\n\", y[j]);\n }\n\n return 0;\n}\n\n", "meta": {"hexsha": "7a4c7dd38c5c4351502fb315a9e1c0b831b03141", "size": 769, "ext": "c", "lang": "C", "max_stars_repo_path": "3test.c", "max_stars_repo_name": "ramcn/flappie-x-cpp", "max_stars_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-16T17:15:21.000Z", "max_issues_repo_path": "3test.c", "max_issues_repo_name": "ramcn/flappie-x-cpp", "max_issues_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3test.c", "max_forks_repo_name": "ramcn/flappie-x-cpp", "max_forks_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2368421053, "max_line_length": 94, "alphanum_fraction": 0.5318595579, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.6037351294886236}} {"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*/\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"string_f.h\"\n\n#include \n\n/* Numerical threshold for oct_bessel_k0 and oct_bessel_k1 */\n#define BESSEL_K_THRES 1.0e2\n\n/* ---------------------- Interface to GSL functions ------------------------ */\n\n\n/* Special Functions */\ndouble FC_FUNC_(oct_gamma, OCT_GAMMA)\n (const double *x)\n{\n return gsl_sf_gamma(*x);\n}\n\ndouble FC_FUNC_(oct_incomplete_gamma, OCT_INCOMPLETE_GAMMA)\n (const double *a, const double *x)\n{\n return gsl_sf_gamma_inc_Q(*a, *x);\n}\n\ndouble FC_FUNC_(oct_sph_bessel, OCT_SPH_BESSEL)\n (const fint *l, const double*x)\n{\n return gsl_sf_bessel_jl(*l, *x);\n}\n\ndouble FC_FUNC_(oct_bessel, OCT_BESSEL)\n (const fint *n, const double *x)\n{\n return gsl_sf_bessel_Jn(*n, *x);\n}\n\ndouble FC_FUNC_(oct_bessel_in, OCT_BESSEL_IN)\n (const fint *n, const double *x)\n{\n return gsl_sf_bessel_In(*n, *x);\n}\n\ndouble FC_FUNC_(oct_bessel_j0, OCT_BESSEL_J0)\n (const double *x)\n{\n return gsl_sf_bessel_J0(*x);\n}\n\ndouble FC_FUNC_(oct_bessel_j1, OCT_BESSEL_J1)\n (const double *x)\n{\n return gsl_sf_bessel_J1(*x);\n}\n\ndouble FC_FUNC_(oct_bessel_k0, OCT_BESSEL_K0)\n (const double *x)\n{\n if( *x > BESSEL_K_THRES )\n {\n return 0.0e0; \n } else {\n return gsl_sf_bessel_K0(*x);\n } \n}\n\ndouble FC_FUNC_(oct_bessel_k1, OCT_BESSEL_K1)\n (const double *x)\n{\n if( *x > BESSEL_K_THRES )\n {\n return 0.0e0; \n } else {\n return gsl_sf_bessel_K1(*x);\n } \n}\n\n/* the GSL headers specify double x, not const double x */\ndouble FC_FUNC_(oct_erfc, OCT_ERFC)\n (const double *x)\n{\n /* avoid floating invalids in the asymptotic limit */\n if(*x > 20.0) return 0.0;\n if(*x < -20.0) return 2.0;\n /* otherwise call gsl */\n return gsl_sf_erfc(*x);\n}\n\n/* the GSL headers specify double x, not const double x */\ndouble FC_FUNC_(oct_erf, OCT_ERF)\n (const double *x)\n{\n /* avoid floating invalids in the asymptotic limit */\n if(*x > 20.0) return 1.0;\n if(*x < -20.0) return -1.0;\n /* otherwise call gsl */\n return gsl_sf_erf(*x);\n}\n\ndouble FC_FUNC_(oct_legendre_sphplm, OCT_LEGENDRE_SPHPLM)\n (const fint *l, const int *m, const double *x)\n{\n return gsl_sf_legendre_sphPlm(*l, *m, *x);\n}\n\n/* generalized Laguerre polynomials */\ndouble FC_FUNC_(oct_sf_laguerre_n, OCT_SF_LAGUERRE_N)\n (const int *n, const double *a, const double *x)\n{\n return gsl_sf_laguerre_n(*n, *a, *x);\n}\n\n\n/* Combinations */\n\nvoid FC_FUNC_(oct_combination_init, OCT_COMBINATION_INIT)\n (gsl_combination **c, const fint *n, const fint *k)\n{\n *c = gsl_combination_calloc (*n, *k);\n}\n\nvoid FC_FUNC_(oct_combination_next, OCT_COMBINATION_NEXT)\n (gsl_combination **c, fint *next)\n{\n *next = gsl_combination_next (((gsl_combination *)(*c)));\n}\n\nvoid FC_FUNC_(oct_get_combination, OCT_GET_COMBINATION)\n (gsl_combination **c, fint *comb)\n{\n int i;\n for (i=0;i< ((gsl_combination *)(*c))->k; i++) {\n comb[i]=(fint)((gsl_combination *)(*c))->data[i]; \n }\n}\n\nvoid FC_FUNC_(oct_combination_end, OCT_COMBINATION_END)\n (gsl_combination **c)\n{\n gsl_combination_free (((gsl_combination *)(*c)));\n}\n\n\n/* Random Number Generation */\nvoid FC_FUNC_(oct_ran_init, OCT_RAN_INIT)\n (gsl_rng **r)\n{\n gsl_rng_env_setup();\n *r = gsl_rng_alloc(gsl_rng_default);\n}\n\nvoid FC_FUNC_(oct_ran_end, OCT_RAN_END)\n (gsl_rng **r)\n{\n gsl_rng_free(*r);\n}\n\n\n/* Random Number Distributions */ \ndouble FC_FUNC_(oct_ran_gaussian, OCT_RAN_GAUSSIAN)\n (const gsl_rng **r, const double *sigma)\n{\n return gsl_ran_gaussian(*r, *sigma);\n}\n\n\ndouble FC_FUNC_(oct_ran_flat, OCT_RAN_FLAT)\n (const gsl_rng **r, const double *a, const double *b)\n{\n return gsl_ran_flat(*r, *a, *b);\n}\n\nvoid FC_FUNC_(oct_strerror, OCT_STRERROR)\n (const fint *err, STR_F_TYPE res STR_ARG1)\n{\n const char *c;\n\n c = gsl_strerror(*err);\n TO_F_STR1(c, res);\n}\n", "meta": {"hexsha": "936c5b04ac972e40f7cb87bf8d86f3e81384c7a3", "size": 4746, "ext": "c", "lang": "C", "max_stars_repo_path": "src/math/oct_gsl_f.c", "max_stars_repo_name": "shunsuke-sato/octopus", "max_stars_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T09:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-17T06:31:08.000Z", "max_issues_repo_path": "src/math/oct_gsl_f.c", "max_issues_repo_name": "shunsuke-sato/octopus", "max_issues_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-11T19:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-11T19:14:06.000Z", "max_forks_repo_path": "src/math/oct_gsl_f.c", "max_forks_repo_name": "shunsuke-sato/octopus", "max_forks_repo_head_hexsha": "dcf68a185cdb13708395546b1557ca46aed969f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-11-22T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-29T23:24:51.000Z", "avg_line_length": 22.6, "max_line_length": 80, "alphanum_fraction": 0.6843657817, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.603730400874519}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define maxnd 10000\n#define H 0.5\n\n/*\n PROGRAM: simSFS\n AUTHOR: Athanasios Kousathanas\n VERSION: 1.0\n\n Generate allele frequency vectors (AFVs) using Wright-Fisher transition matrix methods and sample\n to obtain site frequency spectra (SFS). Code implements methods described by Keightley and Eyre-Walker(2007).\n\n Features:\n Demography: 1-epoch or 2-epoch population changes\n Selection: only single s\n\n Compilation:\n use makefile or compile as\n gcc -O2 -o simSFS simSFS.v1.0.c -lm -lgsl -lgslcblas -w\n*/\n\n\n////////////////////////////////////////\n//calculate allele frequency change, delta(q)\n////////////////////////////////////////\ndouble selfn(double q, double s, double h)\n{\n double num, denom;\n num = s*q*(1-q)*(q + h*(1-2*q));\n denom = 1 + 2.0*h*s*q*(1-q) + s*q*q;\n if (denom== 0) denom = .00000000000001;\n return( q + (num/denom));\n}\n////////////////////////////////////////\n//initialise rows of matrix (used by setupmatrix)\n////////////////////////////////////////\nsetuprow(double **a, double p, int row, int n){\n double z; /*probability of zero failures*/\n double x, y, temp1, temp2;\n int j;\n\n temp1 = 1.0 - p;\n if (temp1 == 0.0) temp1 = .000000000001; /*prevent zero divide*/\n temp1 = p/temp1; /*First prevent negative log*/\n if (temp1 <=0) temp1 = .000000000001;\n x = log(temp1); /*used for later multiplication of series*/\n temp2 = 1.0-p;\n if (temp2<=0) temp2 = .000000000001;\n z = (double)n*log(temp2);\n if (z > 150) z = 150;\n a[row][0] = exp(z);\n y = a[row][0]; /*add up for later*/\n for (j = 1;j<=n; j++)\n {\n\n z = z + log(((double)n + 1.0 - (double)j)/(double)j) + x;\n /* cumulative binomial coeff.*/\n a[row][j] = exp(z);\n y = y + a[row][j]; /*add up*/\n }\n if (y == 0.0) y = .0000000000001;\n for (j=0; j<=n; j++) a[row][j] = a[row][j]/y;\n}\n////////////////////////////////////////\n//initialise transition matrix\n////////////////////////////////////////\nsetupmatrix(double **a, int n1, int n2, double s, double h){\n int i;\n double p;\n\n\n for (i = 1; i<=n1 - 1; i++) /*do variable rows*/\n {\n p = (double)i/(double)n1;\n p = selfn(p, s,h);\n setuprow(a, p, i, n2);\n }\n for (i = 0; i<=n2; i++)\n { /*do constant edges*/\n a[0][i] = 0;\n a[n1][i] = 0;\n }\n a[0][0] = 1.0; /*do absorbing corners*/\n a[n1][n2] = 1.0;\n\n}\n////////////////////////////////////////\n//Perform matrix inversion\n////////////////////////////////////////\nmatrixinvert(int N, double **a,double *inverter){\n\n int i, j, lotkin_signum;\n\n gsl_matrix *lotkin_a,*lotkin_inv;\n gsl_vector *x, *lotkin_b, *lotkin_x;\n\n gsl_permutation *lotkin_perm;\n\n /* allocate a, x, b */\n lotkin_a = gsl_matrix_alloc(N-1, N-1);\n lotkin_inv = gsl_matrix_alloc(N-1, N-1);\n x = gsl_vector_alloc(N-1);\n lotkin_b = gsl_vector_alloc(N-1);\n\n lotkin_x = gsl_vector_alloc(N-1);\n\n gsl_matrix *identity=gsl_matrix_alloc(N-1, N-1);\n\n\n for (i = 0; i<=N-2; i++)\n {\n\n for (j = 0; j<=N-2; j++)\n\t{\n gsl_matrix_set( identity, i, i,1);\n\t}\n\n }\n\n for (i = 0; i<=N-2; i++)\n {\n for (j = 0; j<=N-2; j++)\n\t{\n\t gsl_matrix_set(lotkin_a,i,j,gsl_matrix_get(identity,i,j)-a[i+1][j+1]);\n\t}\n\n }\n\n\n /* LU decomposition and forward&backward substition */\n\n //gsl_blas_dgemv(CblasNoTrans, 1.0, lotkin_a, x, 0.0, lotkin_b);\n\n lotkin_perm = gsl_permutation_alloc(N-1);\n gsl_linalg_LU_decomp(lotkin_a, lotkin_perm, &lotkin_signum);\n gsl_linalg_LU_solve(lotkin_a, lotkin_perm, lotkin_b, lotkin_x);\n gsl_linalg_LU_invert (lotkin_a,lotkin_perm, lotkin_inv);\n\n /*apparently the inversion adds +1 to the first element of the vector\n so I substract it*/\n\n gsl_matrix_set(lotkin_inv,0,0,gsl_matrix_get(lotkin_inv,0,0)-1);\n\n\n\n for (i=0;i<=N-2;i++){\n\n inverter[i+1]=gsl_matrix_get(lotkin_inv,0,i);\n\n }\n\n\n gsl_matrix_free(lotkin_a);\n gsl_matrix_free(lotkin_inv);\n gsl_vector_free(x);\n gsl_vector_free(lotkin_b);\n gsl_vector_free(lotkin_x);\n gsl_matrix_free(identity);\n gsl_permutation_free(lotkin_perm);\n\n}\n////////////////////////////////////////\n//perform TM iteration for t generations\n////////////////////////////////////////\ntmiterate(double **a,double *mut1,\n\t int t, int n1, int n2,int decay,double *sumf){\n\n int k, i, j = 0;\n double z;\n\n double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double));\n double * mut2 = (double*) calloc (maxnd+1, sizeof(double));\n\n for (i=0; i<=n1; i++) steadystatefreq[i] = 0;\n for (k = 1; k<=t; k++)\n { /*t iterations*/\n\n /* Increment steadystatefreq. distribution*/\n for (i = 0; i<=n1; i++)\n\t{\n\t steadystatefreq[i] = steadystatefreq[i] + mut1[i];\n\t}\n\n /* Perform matrix multiplication*/\n for (i = 0; i<=n2; i++)\n\t{\n\t z = 0;\n\t for (j = 0; j<=n1; j++)\n\t {\n\t z = z + a[j][i]*mut1[j];\n\t }\n\t mut2[i] = z;\n\t}\n\n /* Copy result of multiplication*/\n for (i=0; i<=n2; i++) {mut1[i] = mut2[i];\n\n\tif (decay==0){\n\t sumf[i]+=mut1[i];}\n\tif(decay==1){sumf[i]=mut1[i];}\n }\n\n\n }\n\n free(steadystatefreq);\n free(mut2);\n}\n\neqf_using_matrix_inversion(int n1,double s,double **a,double *egf_out){\n\n\n setupmatrix(a, n1, n1, s, H);\n matrixinvert(n1,a,egf_out);\n\n\n}\n////////////////////////////////////////\n//scale AFV for mutations eliminated by selection/not mutated\n////////////////////////////////////////\n\negf_scaling_s(int n1,double *v_s_in, double *v_s_out,double f0){\n int n1d=2*n1;\n double sumx,sumy;\n int i;\n sumx=0;\n sumy=0;\n\n for (i=1;iN2\n setupmatrix(egf_0,n1d,n2d,s,H);\n tmiterate(egf_0,FVW,1, n1d, n2d,1,FVW);\n setupmatrix(egf_0,n2d,n2d,s,H);\n tmiterate(egf_0,FVW,t-1, n2d, n2d,1,FVW);\n\n //dumpvector(FVW,0,n2,\"FVW\");\n /*\n Contributions of mutations to AFV after the change in population size.\n */\n setupmatrix(egf_0,n2d,n2d,s,H);\n startingfreq[1]=1.0;\n tmiterate(egf_0,startingfreq, t-1, n2d, n2d,0,FVX);\n FVX[1]+=1.0;//cumulative vector includes 1st mutant\n //dumpvector(FVX,0,n2,\"FVX\");\n\n /*\n averaging of vectors FVW (N1) and FVX(N2)\n */\n vector_average(n1,n2,FVW,FVX,FV);\n\n\n for(i = 0; i < maxnd+1; i++){\n free(egf_0[i]);\n }\n\n free(egf_0);\n free(FVX);\n free(FVW);\n free(startingfreq);\n}\n////////////////////////////////////////\n//print given matrix\n////////////////////////////////////////\n\ndumpmatrix(double **m, int s1,\n\t int rows, int s2, int cols, char *s){\n int i, j;\n printf(\"\\n%s\\n\", s);\n for (i = s1; i<=rows; i++)\n {\n for (j = s2; j<=cols; j++)\n\t{\n\t printf(\" %2.3f\", m[i][j]);\n\t}\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n////////////////////////////////////////\n//print given vector\n////////////////////////////////////////\ndumpvector(double *v, int min, int max, char *s){\n int i, control = 0;\n // printf(\"\\n\");\n printf(\"%s\", s); printf(\"\\n\");\n for (i = min; i<=max; i++)\n {\n printf(\"%3d %lf \", i, v[i]);\n control++;\n if (control==5)\n\t{\n\t control = 0;\n\t printf(\"\\n\");\n\t}\n }\n printf(\"\\n\");\n}\n\n\n\n\n/*\n////////////////////////////////////////\nMAIN START\n////////////////////////////////////////\n*/\n\nint main(int argc, char **argv)\n{\n\n //initialise input variables and use default values\n int N1=100,n=10,sampleS=1000,sampleN=1000;\n int N2=N1;\n int t=N1;\n double f0=0.9,S=0;\n char outfile[maxnd+1]=\"sfs.out\";\n long seed=time (NULL) * getpid();\n\n //other variables\n int option_index = 0;\n int c=0;\n static int verbose_flag;\n\n const gsl_rng_type * T;\n T = gsl_rng_taus;\n gsl_rng *rgen =gsl_rng_alloc(T);\n gsl_rng_set(rgen,seed);\n\n int * discrete0 = (int*) calloc (maxnd+1, sizeof(int));\n int * discrete1 = (int*) calloc (maxnd+1, sizeof(int));\n\n double * FV0 = (double*) calloc (maxnd+1, sizeof(double));\n double * FVS = (double*) calloc (maxnd+1, sizeof(double));\n\n\n //parse input\n while (1)\n {\n\n static struct option long_options[] =\n\t{\n\t {\"h\",no_argument, &verbose_flag, 1},\n\t {\"N1\", required_argument,0, 'a'},\n\t {\"N2\", required_argument,0, 'b'},\n\t {\"n\", required_argument, 0, 'c'},\n\t {\"f0\", required_argument, 0, 'd'},\n\t {\"s\", required_argument, 0, 'e'},\n\t {\"LS\", required_argument, 0, 'f'},\n\t {\"LN\", required_argument, 0, 'g'},\n\t {\"t\", required_argument, 0, 'h'},\n\t {\"o\", required_argument, 0, 'i'},\n\t {\"seed\", required_argument, 0, 'j'},\n\t {NULL, 0, 0, 0}\n\t};\n /* getopt_long stores the option index here. */\n c = getopt_long_only (argc, argv, \"\",\n\t\t\t long_options, &option_index);\n\n /* Detect the end of the options. */\n if (c == -1)\n\tbreak;\n\n switch (c)\n\t{\n\tcase 0:\n\t /* If this option set a flag, do nothing else now. */\n\t if (long_options[option_index].flag != 0)\n\t {\n\t printf(\"\\\noption\\tdefault_value\\tdescription\\n\\\nN1\\t100\\tsize N1\\n\\\nN2\\t100\\tsize N2\\n\\\nt\\t100\\ttime since size change\\n\\\nn\\t10\\tallele sample size\\n\\\nf0\\t0.9\\t1-f0 is proportional to mutation rate\\n\\\ns\\t0\\tselection coeffient\\n\\\nLS\\t1000\\tno. neutral sites\\n\\\nLN\\t1000\\tno. selected sites\\n\\\no\\tsfs.out\\toutput file\\n\\\nseed\\ttime*pid\\tset seed for random generator\\n\\\n\");\n\t }\n\t break;\n\t printf (\"option %s\", long_options[option_index].name);\n\t if (optarg)\n\t printf (\" with arg %s\", optarg);\n\t printf (\"\\n\");\n\t break;\n\n\tcase 'a':\n\t N1=atoi(optarg);\n\t break;\n\tcase 'b':\n\t N2=atoi(optarg);\n\t break;\n\tcase 'c':\n\t n=atoi(optarg);\n\t break;\n\tcase 'd':\n\t f0=atof(optarg);\n\t break;\n\tcase 'e':\n\t S=atof(optarg);\n\t break;\n\tcase 'f':\n\t sampleS=atoi(optarg);\n\t break;\n\tcase 'g':\n\t sampleN=atoi(optarg);\n\t break;\n\tcase 'h':\n\t t=atoi(optarg);\n\t break;\n\tcase 'i':\n\t strncpy(outfile,optarg,maxnd+1);\n\t break;\n\tcase 'j':\n\t seed=atoi(optarg);\n\t gsl_rng_set(rgen,seed);\n\t break;\n\tcase '?':\n\t abort();\n\t break;\n\tdefault:\n\t abort ();\n\t}\n }\n\n if (optind < argc)\n {\n printf (\"non-option ARGV-elements: \");\n while (optind < argc)\n\tprintf (\"%s \", argv[optind++]);\n putchar ('\\n');\n }\n\n if (N1>1000||N2>1000){printf (\"Use N1,N2 <1000\\n\"); abort();}\n /*\n calculate allele frequency vectors for neutral (FV0)\n and selected sites (FVS)\n */\n if (N1==N2){\n calculate_FV_one_epoch(N1,0.0,FV0);\n calculate_FV_one_epoch(N1,S,FVS);\n }else{\n calculate_FV_two_epoch(N1,N2,t,0.0,FV0);\n calculate_FV_two_epoch(N1,N2,t,S,FVS);\n }\n\n /*\n scale FVS to include the frequency of sites at which mutations\n have been eliminated by selection or have not experienced a mutation\n */\n egf_scaling_s(N2,FV0,FVS, f0);\n egf_scaling_f0(N2,FVS,f0);\n\n /*\n scale FV0 to account for sites that have never experienced a mutation.\n */\n egf_scaling_s(N2,FV0, FV0,f0);\n egf_scaling_f0(N2,FV0,f0);\n\n\n /*sampling\n sample sampleN neutral sites from FV0\n sample sampleS selected sites from FVS\n */\n\n binomial_sampling(N2,n,sampleN,FV0,discrete0,rgen);\n binomial_sampling(N2,n,sampleS, FVS,discrete1,rgen);\n\n output_sfs_to_file(n,discrete0,discrete1,outfile,seed);\n\n //free vectors\n free(FV0);\n free(FVS);\n\n free(discrete0);\n free(discrete1);\n\n gsl_rng_free (rgen);\n\n return 0;\n}\n\n/*\n////////////////////////////////////////\nEND OF MAIN\n////////////////////////////////////////\n*/\n", "meta": {"hexsha": "417fe26be1b90db3601377d5e42f011089afe9be", "size": 14491, "ext": "c", "lang": "C", "max_stars_repo_path": "simSFS.v1.0.c", "max_stars_repo_name": "kousathanas/simsfs", "max_stars_repo_head_hexsha": "8454615aaa863c84b4bb2300aa80ff053acae27d", "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": "simSFS.v1.0.c", "max_issues_repo_name": "kousathanas/simsfs", "max_issues_repo_head_hexsha": "8454615aaa863c84b4bb2300aa80ff053acae27d", "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": "simSFS.v1.0.c", "max_forks_repo_name": "kousathanas/simsfs", "max_forks_repo_head_hexsha": "8454615aaa863c84b4bb2300aa80ff053acae27d", "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.1116427432, "max_line_length": 111, "alphanum_fraction": 0.5578635015, "num_tokens": 4729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.6036260394758352}} {"text": "/* cheb/eval.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#include \n#include \n#include \n#include \n#include \n\n/* For efficiency there are separate implementations of each of these\n functions */\n\ndouble\ngsl_cheb_eval (const gsl_cheb_series * cs, const double x)\n{\n size_t i;\n double d1 = 0.0;\n double d2 = 0.0;\n\n double y = (2.0 * x - cs->a - cs->b) / (cs->b - cs->a);\n double y2 = 2.0 * y;\n\n for (i = cs->order; i >= 1; i--)\n {\n double temp = d1;\n d1 = y2 * d1 - d2 + cs->c[i];\n d2 = temp;\n }\n\n return y * d1 - d2 + 0.5 * cs->c[0];\n}\n\ndouble\ngsl_cheb_eval_n (const gsl_cheb_series * cs, const size_t n, const double x)\n{\n size_t i;\n double d1 = 0.0;\n double d2 = 0.0;\n\n size_t eval_order = GSL_MIN (n, cs->order);\n\n double y = (2.0 * x - cs->a - cs->b) / (cs->b - cs->a);\n double y2 = 2.0 * y;\n\n for (i = eval_order; i >= 1; i--)\n {\n double temp = d1;\n d1 = y2 * d1 - d2 + cs->c[i];\n d2 = temp;\n }\n\n return y * d1 - d2 + 0.5 * cs->c[0];\n}\n\n\nint\ngsl_cheb_eval_err (const gsl_cheb_series * cs, const double x,\n double *result, double *abserr)\n{\n size_t i;\n double d1 = 0.0;\n double d2 = 0.0;\n\n double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a);\n double y2 = 2.0 * y;\n\n double absc = 0.0;\n\n for (i = cs->order; i >= 1; i--)\n {\n double temp = d1;\n d1 = y2 * d1 - d2 + cs->c[i];\n d2 = temp;\n }\n\n *result = y * d1 - d2 + 0.5 * cs->c[0];\n\n /* Estimate cumulative numerical error */\n\n for (i = 0; i <= cs->order; i++)\n {\n absc += fabs(cs->c[i]);\n }\n\n /* Combine truncation error and numerical error */\n\n *abserr = fabs (cs->c[cs->order]) + absc * GSL_DBL_EPSILON;\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_cheb_eval_n_err (const gsl_cheb_series * cs,\n const size_t n, const double x,\n double *result, double *abserr)\n{\n size_t i;\n double d1 = 0.0;\n double d2 = 0.0;\n\n double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a);\n double y2 = 2.0 * y;\n\n double absc = 0.0;\n\n size_t eval_order = GSL_MIN (n, cs->order);\n\n for (i = eval_order; i >= 1; i--)\n {\n double temp = d1;\n d1 = y2 * d1 - d2 + cs->c[i];\n d2 = temp;\n }\n\n *result = y * d1 - d2 + 0.5 * cs->c[0];\n\n /* Estimate cumulative numerical error */\n\n for (i = 0; i <= eval_order; i++)\n {\n absc += fabs(cs->c[i]);\n }\n\n /* Combine truncation error and numerical error */\n\n *abserr = fabs (cs->c[eval_order]) + absc * GSL_DBL_EPSILON;\n\n return GSL_SUCCESS;\n}\n\nint\ngsl_cheb_eval_mode_e (const gsl_cheb_series * cs,\n const double x, gsl_mode_t mode,\n double *result, double *abserr)\n{\n size_t i;\n double d1 = 0.0;\n double d2 = 0.0;\n\n double y = (2. * x - cs->a - cs->b) / (cs->b - cs->a);\n double y2 = 2.0 * y;\n\n double absc = 0.0;\n\n size_t eval_order;\n\n if (GSL_MODE_PREC (mode) == GSL_PREC_DOUBLE)\n eval_order = cs->order;\n else\n eval_order = cs->order_sp;\n\n for (i = eval_order; i >= 1; i--)\n {\n double temp = d1;\n d1 = y2 * d1 - d2 + cs->c[i];\n d2 = temp;\n }\n\n *result = y * d1 - d2 + 0.5 * cs->c[0];\n\n /* Estimate cumulative numerical error */\n\n for (i = 0; i <= eval_order; i++)\n {\n absc += fabs(cs->c[i]);\n }\n\n /* Combine truncation error and numerical error */\n\n *abserr = fabs (cs->c[eval_order]) + absc * GSL_DBL_EPSILON;\n\n return GSL_SUCCESS;\n}\n\ndouble\ngsl_cheb_eval_mode (const gsl_cheb_series * cs,\n const double x, gsl_mode_t mode)\n{\n double result, abserr;\n int status = gsl_cheb_eval_mode_e (cs, x, mode, &result, &abserr);\n\n if (status != GSL_SUCCESS) \n {\n GSL_ERROR_VAL(\"gsl_cheb_eval_mode\", status, result);\n };\n\n return result;\n}\n\n\n", "meta": {"hexsha": "9d5acda57961ecf493a59c2c0a7811d86c91f970", "size": 4549, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/cheb/eval.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/cheb/eval.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/cheb/eval.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": 21.9758454106, "max_line_length": 81, "alphanum_fraction": 0.5759507584, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.603557059620379}} {"text": "#define _XOPEN_SOURCE 600\n\n#include \n#include \n#include \n#include \n\nvoid \nsetupInitialSeed(\n\t\t int id, \n\t\t gsl_rng *rgen) \n{\n\n struct timespec spec;\n \n clock_gettime( CLOCK_REALTIME, &spec );\n \n gsl_rng_set( rgen, (unsigned long int) ( round( spec.tv_nsec / 1.0e6 ) + 20 * id ) );\n\n}\n\nvoid createInitialSample( \n\t\t\t double *x, \n\t\t\t long N, \n\t\t\t gsl_rng *rgen, \n\t\t\t int state_dim ) \n{\n \n for ( long i = 0; i < N; i++)\n for ( int d = 0; d < state_dim; d++ ) \n x[ state_dim * i + d ] = gsl_ran_gaussian_ziggurat( rgen, 1.0 );\n \n}\n\n\n", "meta": {"hexsha": "c84073fbc63e0ecd3c94f6db8b002880430c111f", "size": 595, "ext": "c", "lang": "C", "max_stars_repo_path": "src/randomisation.c", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "src/randomisation.c", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/randomisation.c", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5277777778, "max_line_length": 87, "alphanum_fraction": 0.6, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6034281197169147}} {"text": "/*This program evaluates the differential equations for a photon's geodesic in a perturbed spacetime in SPHERICAL coordinates and restricted to RADIAL MOTION with a Runge-Kutta-Fehlberg 45 method.*/\n\n/*This program solves the particular case for flat FRW perturbed spacetime with metric: $g_{ab} = {[g]}_{ab} + h_{ab}$. Where ${[g]}_{ab}$ corresponds to the flat FRW metric and $h_{ab}$ corresponds to the perturbation in the conformal Newtonian gauge. A Plummer potential with adequate parameters have been used to simulate the perturbation.\nThe equations are written in the form $\\frac{d(x or p)^{\\alpha}}{d\\lambda}=f(x^{\\alpha},p^{\\beta})$ and the indices $\\alpha$ and $\\beta$ run from 0 to 1 since the motion is only radial.\nWhere $p^{\\alpha}={\\dot{x}}^{\\alpha}$.\nThe coordinates for the photon's geodesics are then: (ct,r) = (x0,x1).*/\n\n#include \n#include \n#include \n#include //GSL error management module\n#include //GSL interpolation module\n\n/* PHYSICAL CONSTANTS AND PARAMETERS */\n#define A 10.0 //Distance parameter of the perturbations\n#define G 43007.01 //Gravitational constant\n#define M 0.0 //Mass of the perturbation\n#define C 299792.458 //Speed of light\n\n/* PROGRAM PARAMETERS (ONLY USING NLINES FRW) */\n#define NLINES 100000 //Number of lines in geodesic_solution.dat file\n#define NSTEPS 75000000 //Number of steps for solving geodesics\n#define NLINESFRW 10000 //Number of lines in frw.dat file\n#define DLAMBDA 0.01 //Geodesics parameter step\n\n//We define mydbl as a generic variable type which can be changed when needed to: float, double, long double\ntypedef long double mydbl;\n\n/* RUNGE-KUTTA-FEHLBERG METHOD CONSTANTS */\nconst mydbl c2 = 0.25, c3 = 3.0/8.0, c4 = 12.0/13.0, c5 = 1.0, c6 = 0.5; //Multiplying increment in t\nconst mydbl a21 = 0.25, a31 = 3.0/32.0, a32 = 9.0/32.0, a41 = 1932.0/2197.0, a42 = -7200.0/2197.0, a43 = 7296.0/2197.0, a51 = 439.0/216.0, a52 = -8.0, a53 = 3680.0/513.0, a54 = -845.0/4104.0, a61 = -8.0/27.0, a62 = 2.0, a63 = -3544.0/2565.0, a64 = 1859.0/4104.0, a65 = -11.0/40.0; //This adds to the approximated solution in step i. First script means K value and second which K is multiplying\nconst mydbl r1 = 1.0/360.0, r3 = -128.0/4275.0, r4 = -2197.0/75240.0, r5 = 1.0/50.0, r6 = 2.0/55.0; //Coefficients to calculate R\nconst mydbl b1 = 25.0/216.0, b3 = 1408.0/2565.0, b4 = 2197.0/4104.0, b5 = -1.0/5.0;\n\n/* FUNCTIONS OF THE PROGRAM */\n\n/*Find and return the maximum value for objects in a vector*/\nmydbl maxValue(mydbl arr[], size_t size)\n{\n size_t i;\n mydbl maxValue = arr[0];\n \n for(i = 1; i < size; i++)\n {\n if(arr[i] > maxValue)\n\t{\n\t maxValue = arr[i];\n\t}\n }\n return maxValue;\n}\n\n/*Interpolation of function inside *spline object evaluated at an abscisa 'x'.\nArgument *spline is a pointer to a spline object which stores the type of interpolation to be made. x is the independent variable where the function is evaluated. *acc is a pointer to a lookup object for interpolations.*/\ndouble interpolator(gsl_spline *spline, double x, gsl_interp_accel *acc)\n{\n double a = gsl_spline_eval(spline, x, acc); //Interpolates data to abcisa x using method in spline and acceleration object acc\n\n return a; //Return value of interpolated function at x\n}\n\n/*Function for the gravitational potential to be used. Potential for Plummer model.*/\nmydbl potential(mydbl r)\n{\n return -G*M/(sqrtl(A*A + r*r));\n}\n\n/*Derivative of potential respecto to radial coordinate.*/\nmydbl der_potential(mydbl r)\n{\n return G*M*r/(powl(A*A+r*r, 1.5));\n}\n\n/*Function of the 0th momentum component differential equation for the geodesics.\n${p0}^{dot} = f0(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_0(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = -2.0*der_potential(r)*p0*pr/(C*C + 2.0*potential(r)) - (1.0 - 2.0*potential(r)/(C*C))*(a*adot)*(pr*pr)/(C + 2.0*potential(r)/C);\n return f;\n}\n\n/*Function of the 1th (radial) momentum component differential equation for the geodesics.\n${p1}^{dot} = f1(x^{\\alpha},p^{\\alpha})$.*/\nmydbl geodesic_equation_r(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl p0, mydbl pr, mydbl x0, mydbl r)\n{\n double t = (double)(1.0*x0/C);\n mydbl a = (mydbl) 1.0*interpolator(spline1, t, acc1);\n mydbl adot = (mydbl) 1.0*interpolator(spline2, t, acc2);\n mydbl f = - (der_potential(r)*p0*p0)/(a*a*(C*C - 2.0*potential(r))) - (2.0*adot*p0*pr)/(C*a) + der_potential(r)*(pr*pr)/(C*C - 2.0*potential(r));\n return f;\n}\n\n/*To set the initial value of pr, it must hold $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.\nThis factor multiplies p0 to guarantee that p1 fulfill the null geodesic condition.*/\nmydbl condition_factor(mydbl r, double a)\n{\n return (mydbl)(1.0/a)*sqrtl((1.0+2.0*potential(r)/(C*C))/(1.0 - 2.0*potential(r)/(C*C)));\n}\n\n/*$cp^{0}$ multiplied by this factor allows to obtain the energy for a local inertial observer in this spacetime.*/\nmydbl energy_factor(mydbl r)\n{\n mydbl g = sqrtl(1.0 + 2.0*potential(r)/(C*C));\n return g;\n}\n\n/*Violation of null geodesics condition $g_{\\mu\\nu}p^{\\mu}p^{\\nu} = 0$.*/\nmydbl violation(mydbl r, mydbl p0, mydbl pr, double a)\n{\n mydbl f = -(1.0+2.0*potential(r)/(C*C))*p0*p0 + (mydbl)(1.0*a*a)*(1.0-2.0*potential(r)/(C*C))*pr*pr;\n return f;\n}\n\n/*Function for solving the geodesic's differential equations using a Runge-Kutta-Fehlber method with adaptative stepsize.\nArguments are pointer so variables in that memory addresses are changed every time this function is called. There is no need to define auxiliary variables to store the results of computations.*/\nvoid runge_kutta_fehlberg(gsl_spline *spline1, gsl_interp_accel *acc1, gsl_spline *spline2, gsl_interp_accel *acc2, mydbl *x0, mydbl *x1, mydbl *p0, mydbl *p1, mydbl *lambda, mydbl *dlambda, mydbl lambda_endpoint, mydbl tol, mydbl dlambda_max, mydbl dlambda_min, FILE *fp, double aem, mydbl energy1)\n{\n /*Define the k quantities for all the variables*/\n mydbl k1x0, k1x1, k1p0, k1p1;\n mydbl k2x0, k2x1, k2p0, k2p1;\n mydbl k3x0, k3x1, k3p0, k3p1;\n mydbl k4x0, k4x1, k4p0, k4p1;\n mydbl k5x0, k5x1, k5p0, k5p1;\n mydbl k6x0, k6x1, k6p0, k6p1;\n \n /*Define a vector that carries the errors for each differential equation and a variable for storing the biggest error*/\n mydbl r[4], rmax;\n\n /*Define the increments for the values to be solved in the differential equations*/\n mydbl dp0, dp1, dx0, dx1;\n\n /*Define some relevant quantities to be printed in a file*/\n mydbl energy, difft, t, v, difference;\n double aobs, difftfrw;\n\n /*Relevant quantity to determine the new stepsize*/\n mydbl delta;\n\n while(*lambda < lambda_endpoint)\n {\n /*Check if the independent variable plus the actual stepsize is still in the desired interval*/\n if((*lambda + *dlambda) > lambda_endpoint)\n\t{\n\t *dlambda = lambda_endpoint - *lambda;\n\t}\n\n /*Calculate the k quantities for all the variables*/\n /*This section calculates the k1 quantities*/\n k1x0 = (*dlambda)*(*p0); k1x1 = (*dlambda)*(*p1);\n k1p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1);\n k1p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0, *p1, *x0, *x1);\n \n /*This section calculates the k2 quantities*/\n k2x0 = *dlambda*(*p0 + a21*k1p0); k2x1 = *dlambda*(*p1 + a21*k1p1);\n k2p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a21*k1p0, *p1 + a21*k1p1, *x0 + a21*k1x0, *x1 + a21*k1x1);\n k2p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a21*k1p0, *p1 + a21*k1p1, *x0 + a21*k1x0, *x1 + a21*k1x1);\n \n /*This section calculates the k3 quantities*/\n k3x0 = *dlambda*(*p0 + a31*k1p0 + a32*k2p0); k3x1 = *dlambda*(*p1 + a31*k1p1 + a32*k2p1);\n k3p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a31*k1p0 + a32*k2p0, *p1 + a31*k1p1 + a32*k2p1, *x0 + a31*k1x0 + a32*k2x0, *x1 + a31*k1x1 + a32*k2x1);\n k3p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a31*k1p0 + a32*k2p0, *p1 + a31*k1p1 + a32*k2p1, *x0 + a31*k1x0 + a32*k2x0, *x1 + a31*k1x1 + a32*k2x1);\n \n /*This section calculates the k4 quantities*/\n k4x0 = *dlambda*(*p0 + a41*k1p0 + a42*k2p0 + a43*k3p0); k4x1 = *dlambda*(*p1 + a41*k1p1 + a42*k2p1 + a43*k3p1);\n k4p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a41*k1p0 + a42*k2p0 + a43*k3p0, *p1 + a41*k1p1 + a42*k2p1 + a43*k3p1, *x0 + a41*k1x0 + a42*k2x0 + a43*k3x0, *x1 + a41*k1x1 + a42*k2x1 + a43*k3x1);\n k4p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a41*k1p0 + a42*k2p0 + a43*k3p0, *p1 + a41*k1p1 + a42*k2p1 + a43*k3p1, *x0 + a41*k1x0 + a42*k2x0 + a43*k3x0, *x1 + a41*k1x1 + a42*k2x1 + a43*k3x1);\n\n /*This section calculates the k5 quantities*/\n k5x0 = *dlambda*(*p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0); k5x1 = *dlambda*(*p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1);\n k5p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0, *p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1, *x0 + a51*k1x0 + a52*k2x0 + a53*k3x0 + a54*k4x0, *x1 + a51*k1x1 + a52*k2x1 + a53*k3x1 + a54*k4x1);\n k5p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a51*k1p0 + a52*k2p0 + a53*k3p0 + a54*k4p0, *p1 + a51*k1p1 + a52*k2p1 + a53*k3p1 + a54*k4p1, *x0 + a51*k1x0 + a52*k2x0 + a53*k3x0 + a54*k4x0, *x1 + a51*k1x1 + a52*k2x1 + a53*k3x1 + a54*k4x1);\n\n /*This section calculates the k6 quantities*/\n k6x0 = *dlambda*(*p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0); k6x1 = *dlambda*(*p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1);\n k6p0 = *dlambda*geodesic_equation_0(spline1, acc1, spline2, acc2, *p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0, *p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1, *x0 + a61*k1x0 + a62*k2x0 + a63*k3x0 + a64*k4x0 + a65*k5x0, *x1 + a61*k1x1 + a62*k2x1 + a63*k3x1 + a64*k4x1 + a65*k5x1);\n k6p1 = *dlambda*geodesic_equation_r(spline1, acc1, spline2, acc2, *p0 + a61*k1p0 + a62*k2p0 + a63*k3p0 + a64*k4p0 + a65*k5p0, *p1 + a61*k1p1 + a62*k2p1 + a63*k3p1 + a64*k4p1 + a65*k5p1, *x0 + a61*k1x0 + a62*k2x0 + a63*k3x0 + a64*k4x0 + a65*k5x0, *x1 + a61*k1x1 + a62*k2x1 + a63*k3x1 + a64*k4x1 + a65*k5x1);\n\n /*Determination of the biggest error between the errors for each differential equation*/\n r[0] = fabsl(r1*k1p0 + r3*k3p0 + r4*k4p0 + r5*k5p0 + r6*k6p0)/(*dlambda);\n r[1] = fabsl(r1*k1p1 + r3*k3p1 + r4*k4p1 + r5*k5p1 + r6*k6p1)/(*dlambda);\n r[2] = fabsl(r1*k1x0 + r3*k3x0 + r4*k4x0 + r5*k5x0 + r6*k6x0)/(*dlambda);\n r[3] = fabsl(r1*k1x1 + r3*k3x1 + r4*k4x1 + r5*k5x1 + r6*k6x1)/(*dlambda);\n rmax = maxValue(r, 4);\n\n /*Check whether the worst approximation is less than the introduced tolerance*/\n if(rmax <= tol)\n\t{\n\t *lambda = *lambda + *dlambda;\n\t \n\t dp0 = b1*k1p0 + b3*k3p0 + b4*k4p0 + b5*k5p0;\n\t dp1 = b1*k1p1 + b3*k3p1 + b4*k4p1 + b5*k5p1;\n\t dx0 = b1*k1x0 + b3*k3x0 + b4*k4x0 + b5*k5x0;\n\t dx1 = b1*k1x1 + b3*k3x1 + b4*k4x1 + b5*k5x1;\n\t *p0 = *p0 + dp0; *p1 = *p1 + dp1; *x0 = *x0 + dx0; *x1 = *x1 + dx1;\n\t \n\t /*Relevant quantities to save in the .dat file. These only are calculated if the approximation is accepted*/\n\t energy = C*energy_factor(*x1)*(*p0);\n \t difft = (energy - energy1)/energy1;\n \t t = *x0/C;\n \t aobs = interpolator(spline1, (double)(1.0*t), acc1);\n \t v = violation(*x1, *p0, *p1, aobs);\n \t difftfrw = (aem/aobs) - 1.0;\n \t difference = difft - (mydbl)(1.0*difftfrw);\n \t fprintf(fp, \"%16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8Le %16.8e %16.8Le %16.8Le\\n\", *lambda, *dlambda, *x0, *x1, *p0, *p1, energy, v, difft, difftfrw, difference, rmax);\n\t}\n\n /*Calculate a new stepsize*/\n delta = 0.84*powl(tol/rmax, 0.25);\n\n if(delta <= 0.1)\n\t{\n\t *dlambda = *dlambda*0.1;\n\t}\n else if(delta >= 4.0)\n\t{\n\t *dlambda = *dlambda*4.0;\n\t}\n else\n\t{\n\t *dlambda = *dlambda*delta;\n\t}\n\n /*Check whether the stepsize is too big or too small*/\n if(*dlambda > dlambda_max)\n\t{\n\t *dlambda = dlambda_max;\n\t}\n else if(*dlambda < dlambda_min)\n\t{\n\t printf(\"Minimum value for stepsize dlambda exceeded.\\n\");\n\t break;\n\t}\n }\n}\n\nint main(void)\n{\n /***READ SCALE FACTOR DATA AND PREPARE OBJECTS FOR INTERPOLATION ***/\n int i; //For array manipulation\n \n /*Pointer to scale_factor.data file*/\n FILE *frw; \n frw = fopen(\"../scale_factor.dat\",\"r\");\n\n /*Variables and arrays to read the data*/\n double cosmictime[NLINESFRW], conftime, scale_factor[NLINESFRW], der_scale_factor[NLINESFRW];\n\n /*Reading the data*/\n for(i=0; i\n#include \n#include \n\nint\ndofit(const gsl_multifit_robust_type *T,\n const gsl_matrix *X, const gsl_vector *y,\n gsl_vector *c, gsl_matrix *cov)\n{\n int s;\n gsl_multifit_robust_workspace * work \n = gsl_multifit_robust_alloc (T, X->size1, X->size2);\n\n s = gsl_multifit_robust (X, y, c, cov, work);\n gsl_multifit_robust_free (work);\n\n return s;\n}\n\nint\nmain (int argc, char **argv)\n{\n int i;\n size_t n;\n const size_t p = 2; /* linear fit */\n gsl_matrix *X, *cov;\n gsl_vector *x, *y, *c, *c_ols;\n const double a = 1.45; /* slope */\n const double b = 3.88; /* intercept */\n gsl_rng *r;\n\n if (argc != 2)\n {\n fprintf (stderr,\"usage: robfit n\\n\");\n exit (-1);\n }\n\n n = atoi (argv[1]);\n\n X = gsl_matrix_alloc (n, p);\n x = gsl_vector_alloc (n);\n y = gsl_vector_alloc (n);\n\n c = gsl_vector_alloc (p);\n c_ols = gsl_vector_alloc (p);\n cov = gsl_matrix_alloc (p, p);\n\n r = gsl_rng_alloc(gsl_rng_default);\n\n /* generate linear dataset */\n for (i = 0; i < n - 3; i++)\n {\n double dx = 10.0 / (n - 1.0);\n double ei = gsl_rng_uniform(r);\n double xi = -5.0 + i * dx;\n double yi = a * xi + b;\n\n gsl_vector_set (x, i, xi);\n gsl_vector_set (y, i, yi + ei);\n }\n\n /* add a few outliers */\n gsl_vector_set(x, n - 3, 4.7);\n gsl_vector_set(y, n - 3, -8.3);\n\n gsl_vector_set(x, n - 2, 3.5);\n gsl_vector_set(y, n - 2, -6.7);\n\n gsl_vector_set(x, n - 1, 4.1);\n gsl_vector_set(y, n - 1, -6.0);\n\n /* construct design matrix X for linear fit */\n for (i = 0; i < n; ++i)\n {\n double xi = gsl_vector_get(x, i);\n\n gsl_matrix_set (X, i, 0, 1.0);\n gsl_matrix_set (X, i, 1, xi);\n }\n\n /* perform robust and OLS fit */\n dofit(gsl_multifit_robust_ols, X, y, c_ols, cov);\n dofit(gsl_multifit_robust_bisquare, X, y, c, cov);\n\n /* output data and model */\n for (i = 0; i < n; ++i)\n {\n double xi = gsl_vector_get(x, i);\n double yi = gsl_vector_get(y, i);\n gsl_vector_view v = gsl_matrix_row(X, i);\n double y_ols, y_rob, y_err;\n\n gsl_multifit_robust_est(&v.vector, c, cov, &y_rob, &y_err);\n gsl_multifit_robust_est(&v.vector, c_ols, cov, &y_ols, &y_err);\n\n printf(\"%g %g %g %g\\n\", xi, yi, y_rob, y_ols);\n }\n\n#define C(i) (gsl_vector_get(c,(i)))\n#define COV(i,j) (gsl_matrix_get(cov,(i),(j)))\n\n {\n printf (\"# best fit: Y = %g + %g X\\n\", \n C(0), C(1));\n\n printf (\"# covariance matrix:\\n\");\n printf (\"# [ %+.5e, %+.5e\\n\",\n COV(0,0), COV(0,1));\n printf (\"# %+.5e, %+.5e\\n\", \n COV(1,0), COV(1,1));\n }\n\n gsl_matrix_free (X);\n gsl_vector_free (x);\n gsl_vector_free (y);\n gsl_vector_free (c);\n gsl_vector_free (c_ols);\n gsl_matrix_free (cov);\n gsl_rng_free(r);\n\n return 0;\n}\n", "meta": {"hexsha": "ce9a3859805f54e91b36e8c17a8ec8ac3458a0d2", "size": 2799, "ext": "c", "lang": "C", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/robfit.c", "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/robfit.c", "max_issues_repo_name": "ruslankuzmin/julia", "max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/doc/examples/robfit.c", "max_forks_repo_name": "ruslankuzmin/julia", "max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 22.756097561, "max_line_length": 69, "alphanum_fraction": 0.5694891033, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6029304684805589}} {"text": "//\n// her2k.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 1/6/12.\n// Copyright (c) 2012 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _her2k_h\n#define _her2k_h\n\n/// @file her2k.h Performs multiplication of two complex matrices resulting in a Hermitian matrix.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Performs multiplcation of complex matrices resulting in a Hermitian matrix.\n ///\n /// For complex matrices A and B, complex Hermitian matrix C, and complex scalar alpha and real\n /// scalar beta\n ///\n /// C := alpha*A*B'+conj(alpha)*B*A'+beta*C\n /// or\n ///\n /// C := alpha*A'*B+conj(alpha)*B'*A+beta*C\n /// is computed.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param uplo Specifies whether the upper or lower triangular part of the Hermitian matrix C\n /// is to be referenced:\n ///\n /// if uplo = 'U' or 'u' then C is upper triangular,\n /// if uplo = 'L' or 'l' then C is lower triangular.\n /// @param trans Specifies the operation to be perfomed as follows:\n ///\n /// if trans = 'N' or 'n' then C := alpha*A*B'+conj(alpha)*B*A'+beta*C\n /// if trans = 'C' or 'c' then C := alpha*A'*B+conj(alpha)*B'*A+beta*C\n /// @param n Specifies the order of the complex Hermitian matrix C. n>=0\n /// @param k Specifies the other dimension of the complex matrices A and B.\n ///\n /// if trans = 'N' or 'n' then A and B are n-by-k\n /// if trans = 'C' or 'c' then A and B are k-by-n\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex matrix.\n /// @param ldA Column length of the matrix A. If trans = 'N' or 'n' ldA>=n, otherwise ldA>=k.\n /// @param B Pointer to complex matrix.\n /// @param ldB Column length of the matrix B. If trans = 'N' or 'n' ldB>=n, otherwise ldB>=k.\n /// @param beta Real scalar.\n /// @param C Pointer to complex Hermitian n-by-n matrix C.\n /// Only the upper or lower triangular part of C is referenced, depending on the value of uplo above.\n /// @param ldC Column length of the matrix C. ldC>=n\n /// @ingroup BLAS\n\n template \n int HER2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, real_t beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n using std::real;\n using std::conj;\n const complex zero(0.0,0.0);\n const complex one(1.0,0.0);\n int_t i,j,l;\n complex *a,*b,*c,*at,*bt;\n complex s,t;\n\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldCj)\n c[i]=alpha*t+conj(alpha)*s+beta*c[i];\n else\n c[j]=real(alpha*t+conj(alpha)*s)+beta*real(c[j]);\n a+=ldA;\n b+=ldB;\n }\n at+=ldA;\n bt+=ldB;\n c+=ldC;\n }\n }\n }\n return 0;\n }\n\n#ifdef __latl_cblas\n#include \n\n template <> int HER2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, float beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC int HER2K(char uplo, char trans, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, double beta, complex *C, int_t ldC)\n {\n using std::toupper;\n uplo=toupper(uplo);\n trans=toupper(trans);\n if((uplo!='U')&&(uplo!='L'))\n return -1;\n else if((trans!='N')&&(trans!='C'))\n return -2;\n else if(n<0)\n return -3;\n else if(k<0)\n return -4;\n else if(ldA<((trans=='N')?n:k))\n return -7;\n else if(ldB<((trans=='N')?n:k))\n return -9;\n else if(ldC\n#include \"snpFile.h\"\n#include \"popGenTools.h\"\n#include \"numerical.h\"\n#include \"assert.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* function for sfs generation -- stationary solution for snp frequency density*/\ndouble my_f(double q, void * p){\n struct my_f_params * params = (struct my_f_params *) p;\n double beta = params->beta;\n int i = params->i;\n int n = params->n;\n\t\n return ((1.0 - exp(-2.0 * beta * (1.0 - q))) / (1.0 - exp(-2.0 * beta))) * (2.0 / (q * (1.0 - q))) * gsl_ran_binomial_pdf(i, q, n);\n}\n\n\n\n/* integral of f over allele freq */\ndouble my_F(double beta, void * p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_f_params fParams;\n gsl_function f;\n //gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);\n double result,error;\n size_t size= 1000;\n \n if (beta == 0){\n //gsl_integration_workspace_free(w);\n return 1.0 / params->i;\n }\n else{\n fParams.beta = beta;\n fParams.i = params->i;\n fParams.n = params->n;\n f.function = &(my_f);\n f.params = &fParams;\n //adaptive integration-- slow and steady\n//\tgsl_integration_qags(&f,0.0,1.0,1e-5,1e-5, 100000,w, &result,&error);\n\t//non-adaptive version is rougher and faster\n\tgsl_integration_qng(&f, 0.0, 1.0, 1e-2,1e-2,&result,&error,&size);\n// gsl_integration_workspace_free(w);\n return result;\n }\n}\n\n\n/* integral of f over allele freq using numerical recipes integration */\ndouble my_F2(double beta, void * p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_f_params fParams;\n double result;\n \n if (beta == 0){\n return 1.0 / params->i;\n }\n else{\n fParams.beta = beta;\n fParams.i = params->i;\n fParams.n = params->n;\n result = d_qromb2(&my_f, 0.0, 1.0, &fParams);\n return result;\n }\n}\n\n/* integral of f over allele freq-- using adaptive integration */\ndouble my_FAdapt(double beta, void * p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_f_params fParams;\n gsl_function f;\n double result,error;\n size_t size= 100;\n \n if (beta == 0){\n return 1.0 / params->i;\n }\n else{\n fParams.beta = beta;\n fParams.i = params->i;\n fParams.n = params->n;\n f.function = &(my_f);\n f.params = &fParams;\n //adaptive integration-- slow and steady\n\tgsl_integration_qags(&f,0.0,1.0,1e-3,1e-3,size,params->w, &result,&error);\n return result;\n }\n}\n\n\n/* this returns the prob of SNP freq i given n and beta */\ndouble snpProb(double beta, void * p){\t\t\t\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_F_params tempParams;\n long double tot;\n int i;\n gsl_function F;\n \n /* add up total prob space */\n tot = 0.0;\n tempParams.n = params->n;\n\n for(i = 1; i < params->n ; i++){\n tempParams.i = i;\n tempParams.w = params->w;\n F.function = &my_F;\n F.params = &tempParams;\n tot += GSL_FN_EVAL(&F, beta);\n }\n \n /* reset parameters */\t\n F.function = &my_FAdapt;\n F.params = params;\n \n return GSL_FN_EVAL(&F, beta) / tot ;\n}\t\t\n\n/* trying to speedup the snpProb routine with a lookup of the denominators (in snpProb_params) */\ndouble snpProbDenomLookup(double beta, void * p){\t\t\t\n\tstruct my_snpProb_params * params = (struct my_snpProb_params *) p;\n\tstruct my_F_params tempParams;\n\tgsl_function F;\n\n/* set parameters */\t\n\ttempParams.n = params->n;\n\ttempParams.i = params->i;\n\ttempParams.w = params->w;\n\tF.function = &my_FAdapt;\n\tF.params = &tempParams;\n\n\treturn GSL_FN_EVAL(&F, beta) / params->denom ;\n}\t\n\n/* sampleSize vector - returns a vector of 1s or 0s depending on sample sizes in the data */\ngsl_vector *sampleSizeVector(struct snp data[], int snpNumber, int maxSampleSize){\n gsl_vector *bools;\n int i;\n\n //alloc and initialize bools vector\n bools = gsl_vector_alloc(maxSampleSize + 1);\n gsl_vector_set_zero(bools);\n\n //go through data, set each sampleSize value to 1\n for(i = 0; i < snpNumber; i++){\n gsl_vector_set(bools,data[i].n, 1);\n }\n return(bools);\n}\n\n\n/* sampleSize vector - returns a vector of 1s or 0s depending on sample sizes in the data */\nvoid sampleSizeVectorFill(struct snp data[], int snpNumber, int maxSampleSize, gsl_vector *bools){\n int i;\n\n //initialize bools vector\n gsl_vector_set_zero(bools);\n\n //go through data, set each sampleSize value to 1\n for(i = 0; i < snpNumber; i++){\n gsl_vector_set(bools,data[i].n, 1);\n }\n}\n/* returns a vector of snpProbDenominators from i = 2 to n, 1 indexed */\ngsl_vector *makeSnpProbDenomVector(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){\n\tgsl_vector *probs;\n\tint i, j, test;\n\tdouble tot;\n\tstruct my_F_params tempParams;\n\tgsl_function F;\n\tgsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n\tprobs = gsl_vector_alloc(maxSampleSize + 1);\n\n\ttempParams.w = w;\n/* go from n = 2 to maxSampleSize, calc total prob space for each, put in vector probs */\n\tfor(j = 2; j < maxSampleSize + 1; j++){\n\t//check if sampleSize is included\n\t\ttest = gsl_vector_get(sampleSizeVector,j);\n\t\tif (test){\n\t\t\ttot = 0.0;\n\t\t\ttempParams.n = j;\n\t\t\tfor(i = 1; i < j ; i++){\n\t\t\t\ttempParams.i = i;\n\t\t\t\tF.function = &my_FAdapt;\n\t\t\t\tF.params = &tempParams;\n\t\t\t\ttot += GSL_FN_EVAL(&F, beta);\n\t\t\t}\n\t\t\tgsl_vector_set(probs, j, tot);\n\t\t}\n\t}\n\tgsl_integration_workspace_free(w);\n\treturn probs;\n}\n \n/* snpProbDenom - returns denom for snpProb */\ndouble snpProbDenom(double beta, int sampleSize){\n int i;\n double tot;\n struct my_F_params tempParams;\n gsl_function F;\n\n tot = 0.0;\n tempParams.n = sampleSize;\n for(i = 1; i < sampleSize ; i++){\n\ttempParams.i = i;\n\tF.function = &my_F;\n\tF.params = &tempParams;\n\ttot += GSL_FN_EVAL(&F, beta);\n }\n return(tot);\n}\n\n\n/* snpProbMatrix- returns a matrix of log snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\n variable sampleSizes (2 to max), columns represent freqs (1 to max -1) */\ngsl_matrix *snpProbMatrix(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){\n gsl_vector *denoms;\n gsl_matrix *probs;\n struct my_snpProb_params FParams;\n gsl_function f;\n int i, j;\n \n //alloc probs\n probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n gsl_matrix_set_zero(probs);\n //get denoms\n denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);\n FParams.w = gsl_integration_workspace_alloc(1000);\n //go through sampleSizes\n for(i = 2; i <= maxSampleSize; i++){\n //have sample size i?\n if (gsl_vector_get(sampleSizeVector, i)){\n //go through freqs\n for(j = 1; j < maxSampleSize; j++){\n\t//have freq j?\n\tif(gsl_matrix_get(sfsBools, i, j)){\n\t //calc prob\n\t FParams.i = j;\n\t FParams.n = i;\n\t FParams.denom = gsl_vector_get(denoms,i);\n\t f.function = &snpProbDenomLookup;\n\t f.params = &FParams;\n\t gsl_matrix_set(probs, i, j, log(GSL_FN_EVAL(&f, beta)));\n\t}\n }\n }\n }\n gsl_vector_free(denoms);\n gsl_integration_workspace_free(FParams.w);\n return(probs);\n}\n/* snpProbMatrix- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\nvariable sampleSizes (2 to max), columns represent freqs (1 to max -1) */\ngsl_matrix *snpProbMatrixNotLog(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){\n\tgsl_vector *denoms;\n\tgsl_matrix *probs;\n\tstruct my_snpProb_params FParams;\n\tgsl_function f;\n\tgsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);\n\tint i, j;\n\n\tFParams.w = w;\n//alloc probs\n\tprobs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n\tgsl_matrix_set_zero(probs); \n//get denoms\n\tdenoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);\n\n//go through sampleSizes\n\tfor(i = 2; i <= maxSampleSize; i++){\n\t//have sample size i?\n\t\tif (gsl_vector_get(sampleSizeVector, i)){\n\t//go through freqs\n\t\t\tfor(j = 1; j < maxSampleSize; j++){\n\t//have freq j?\n\t\t\t\tif(gsl_matrix_get(sfsBools, i, j)){\n\t//calc prob\n\t\t\t\t\tFParams.i = j;\n\t\t\t\t\tFParams.n = i;\n\t\t\t\t\tFParams.denom = gsl_vector_get(denoms,i);\n\t\t\t\t\tf.function = &snpProbDenomLookup;\n\t\t\t\t\tf.params = &FParams;\n\t\t\t\t\tgsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tgsl_vector_free(denoms);\n\treturn(probs);\n}\n/* snpProbMatrixNotLogFull- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\n variable sampleSizes (2 to max), columns represent freqs (1 to max -1). All freqs/samplesizes included */\ngsl_matrix *snpProbMatrixNotLogFull(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){\n gsl_vector *denoms;\n gsl_matrix *probs;\n struct my_snpProb_params FParams;\n gsl_function f;\n int i, j;\n \n //alloc probs\n probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n gsl_matrix_set_zero(probs); \n\n //get denoms\n\n denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);\n\n //go through sampleSizes\n for(i = 2; i <= maxSampleSize; i++){\n //check for sampleSize\n if (gsl_vector_get(sampleSizeVector,i)){\n //go through freqs\n for(j = 1; j < maxSampleSize; j++){\n\t//calc prob\n\tFParams.i = j;\n\tFParams.n = i;\n\tFParams.denom = gsl_vector_get(denoms,i);\n\tf.function = &snpProbDenomLookup;\n\tf.params = &FParams;\n\tgsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));\n }\n }\n }\n gsl_vector_free(denoms);\n return(probs);\n}\n\n\n/* snpProbVectorNotLog- returns a vector of log snpProbs at specified sampleSize columns represent freqs (1 to max -1) */\ngsl_vector *snpProbVectorNotLog(double beta, int sampleSize){\n double denom;\n gsl_vector *probs;\n struct my_snpProb_params FParams;\n gsl_function f;\n int i;\n \n //alloc probs\n probs = gsl_vector_alloc(sampleSize);\n gsl_vector_set_zero(probs);\n //get denoms\n denom = snpProbDenom(beta, sampleSize);\n\n //go through freqs\n for(i = 1; i < sampleSize; i++){\n FParams.i = i;\n FParams.n = sampleSize;\n FParams.denom = denom;\n f.function = &snpProbDenomLookup;\n f.params = &FParams;\n gsl_vector_set(probs, i, GSL_FN_EVAL(&f, beta));\n }\n return(probs);\n}\n\ngsl_vector *snpProbVectorNotLogPre(double beta, int sampleSize, gsl_vector *probs){\n double denom;\n struct my_snpProb_params FParams;\n gsl_function f;\n int i;\n \n gsl_vector_set_zero(probs);\n //get denoms\n denom = snpProbDenom(beta, sampleSize);\n\n //go through freqs\n for(i = 1; i < sampleSize; i++){\n FParams.i = i;\n FParams.n = sampleSize;\n FParams.denom = denom;\n f.function = &snpProbDenomLookup;\n f.params = &FParams;\n gsl_vector_set(probs, i, GSL_FN_EVAL(&f, beta));\n }\n return(probs);\n}\n\n/* likelihood function for SFS given the data; p here contains the data and the weights */\ndouble my_lik(double beta, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tstruct my_F_params FParams;\n\tgsl_function f;\n\tdouble lik;\n\tint i;\n\t\n\tlik = 0;\n\tfor(i = 0; i < params->snpNumber; i++){\n\t\tFParams.i = params->data[i].i;\n\t\tFParams.n = params->data[i].n;\n\t\tf.function = &snpProb;\n\t\tf.params = &FParams;\n\t\tlik += log(GSL_FN_EVAL(&f, beta));\n\t\t}\n\treturn -lik;\n}\n\n/* likelihood function for SFS where each SNP has independent selection coeff */\ndouble sfsLikBetaVector(gsl_vector *betas, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tstruct my_F_params FParams;\n\tgsl_function f;\n\tdouble lik;\n\tint i;\n\t\n\tlik = 0;\n\tfor(i = 0; i < params->snpNumber; i++){\n\t\tFParams.i = params->data[i].i;\n\t\tFParams.n = params->data[i].n;\n\t\tFParams.w = params->w;\n\t\tf.function = &snpProb;\n\t\tf.params = &FParams;\n\t\t//\tprintf(\"here lik:%f beta:%f i: %d n: %d\\n\",lik,gsl_vector_get(betas, i),FParams.i,FParams.n);\n\t\t\n\t\tlik += log(GSL_FN_EVAL(&f, gsl_vector_get(betas, i)));\n\t\t}\n\treturn -lik;\n}\n\n/*likelihood from Bustamante et al. 2001 */\ndouble bustaLik(double beta, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tstruct my_F_params FParams;\n\tgsl_function f;\n\tdouble lik;\n\tint i;\n\n\tlik = 0;\n\tfor(i = 0; i < params->snpNumber; i++){\n\t\tFParams.i = params->data[i].i;\n\t\tFParams.n = params->data[i].n;\n\t\tf.function = &snpProb;\n\t\tf.params = &FParams;\n\t\tlik += log(GSL_FN_EVAL(&f, beta));\n\t\t}\n\treturn -lik;\n}\n\n/* weighted likelihood function for SFS given the data; here contains the data and the weights */\ndouble weightedLik(double beta, void * p){\n struct my_lik_params * params = (struct my_lik_params *) p;\n struct my_F_params FParams;\n gsl_function f;\n double lik;\n int i;\n\t\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n FParams.i = params->data[i].i;\n FParams.n = params->data[i].n;\n f.function = &snpProb;\n f.params = &FParams;\n lik += gsl_vector_get(params->weights, i) * log(GSL_FN_EVAL(&f, beta)); \n }\n return -lik;\n}\n\n/* weighted likelihood function for SFS given the data; here contains the data and the weights and uses the snpProbLookup routine */\ndouble weightedLikLook(double beta, void * p){\n struct my_lik_params * params = (struct my_lik_params *) p;\n double lik;\n int i;\n gsl_matrix *probs;\n \n //make prob matrix (note this is in logs)\n probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);\n //now go and tally likelihood\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);\n }\n gsl_matrix_free(probs);\n return -lik;\n}\n \n/* Folded SFS version of above; weighted likelihood function for SFS given the data; here contains the data and the weights and uses the snpProbLookup routine */\ndouble weightedLikLookFolded(double beta, void * p){\n struct my_lik_params * params = (struct my_lik_params *) p;\n double lik;\n int i;\n gsl_matrix *probs;\n \n //make prob matrix (note this is in logs)\n probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);\n //now go and tally likelihood\n lik = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);\n\tlik += gsl_matrix_get(probs,params->data[i].n, params->data[i].n - params->data[i].i) * gsl_vector_get(params->weights,i);\n }\n gsl_matrix_free(probs);\n return -lik;\n}\n\n/* PRF log Likelihood */\ndouble prfLik(double beta, void * p){\n\t struct prfLik_params * params = (struct prfLik_params *) p;\n\tdouble lik;\n\tdouble term1, term2,theta;\n \tint i;\t\n\tstruct my_F_params tempParams;\n\tgsl_function F;\n\tdouble fTerm = 0.;\n\t\n\ttheta = gsl_vector_get(params->betas,1);\n\tterm1 = term2 = 0;\n\tfor(i = 1; i < params->maxSampleSize;i++){\n\t\ttempParams.i = i;\n\t\ttempParams.n = params->maxSampleSize;\n\t\tF.function = &my_F;\n\t\tF.params = &tempParams;\n\t\tfTerm = GSL_FN_EVAL(&F,beta);\n\t\tterm1 += gsl_matrix_get(params->sfsCounts,params->maxSampleSize,i) * log( theta* fTerm) ;\n\t\tterm2 += fTerm;\n\t}\n\treturn((term1 - (theta * term2)) * -1);\n}\t\n \n\n\n\ndouble weightedLikLookCI(double beta, void * p){\n struct my_likCI_params *params = (struct my_likCI_params *) p;\n struct my_lik_params likParams;\n gsl_function l;\n double result;\n\n likParams.data = params->data;\n likParams.snpNumber = params->snpNumber;\n likParams.sampleSizeVector = params->sampleSizeVector;\n likParams.maxSampleSize = params->maxSampleSize;\n likParams.weights = params->weights;\n likParams.sfsBools = params->sfsBools;\n l.function = &weightedLikLook;\n l.params = &likParams;\n result = GSL_FN_EVAL(&l, beta) - (params->lMax) - (params->logUnits) ;\n // printf(\"%f\\t%f\\t%f\\n\",params->lMax,GSL_FN_EVAL(&l, beta),result);\n return result;\n}\n\n\ndouble weightedLikLookCIFolded(double beta, void * p){\n struct my_likCI_params *params = (struct my_likCI_params *) p;\n struct my_lik_params likParams;\n gsl_function l;\n double result;\n\n likParams.data = params->data;\n likParams.snpNumber = params->snpNumber;\n likParams.sampleSizeVector = params->sampleSizeVector;\n likParams.maxSampleSize = params->maxSampleSize;\n likParams.weights = params->weights;\n likParams.sfsBools = params->sfsBools;\n l.function = &weightedLikLookFolded;\n l.params = &likParams;\n result = GSL_FN_EVAL(&l, beta) - (params->lMax) - (params->logUnits) ;\n // printf(\"%f\\t%f\\t%f\\n\",params->lMax,GSL_FN_EVAL(&l, beta),result);\n return result;\n}\n\n\n/* wrapper for my_lik for use in mnbrak */\ndouble likWrap(double beta){\n\tgsl_function f;\n\t\n\tf.function = &my_lik;\n\tf.params = NULL;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\n/* wrapper for my_lik for use in mnbrak */\ndouble wlikWrap(double beta, void * p){\n\tgsl_function f;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\t\n\tf.function = &weightedLik;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\n/* wrapper for my_lik for use in mnbrak */\ndouble wlikWrapLook(double beta, void * p){\n\tgsl_function f;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\t\n\tf.function = &weightedLikLook;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\ndouble wlikWrapLookFolded(double beta, void * p){\n\tgsl_function f;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\t\n\tf.function = &weightedLikLookFolded;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\ndouble wlikCIWrapLook(double beta, void * p){\n\tgsl_function f;\n\tstruct my_likCI_params * params = (struct my_likCI_params *) p;\n\t\n\tf.function = &weightedLikLookCI;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n \n\n/* wrapper for prfLik for use in mnbrak */\ndouble prfLikWrap(double beta, void * p){\n\tgsl_function f;\n\tstruct prfLik_params * params = (struct prfLik_params *) p;\n\t\n\tf.function = &prfLik;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n} \n\n/*error checking function for likelihood function */\nvoid printProfile(double min, double max, void * p){\n gsl_function f;\n struct my_lik_params *params = (struct my_lik_params *) p;\n int i;\n\n f.function = &weightedLikLook;\n f.params = params;\n for(i = min; i < max; i++){\n printf(\"%d\\t%f\\n\",i, GSL_FN_EVAL(&f, i));\n }\n \n}\n \n/* get ML estimate of beta using likelihood function; BRENT method for gsl */\ndouble ml_est(double * lik_beta_hat){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc;\n\tgsl_function L;\n\t\n\t\n\t\n\t/* get minimum bracket */\n\tax = -10.0;\n\tbx = 0.0;\n\tcx = 10.0;\n\t\n\tmnbrak(&ax, &bx, &cx, &fa, &fb, &fc, &my_lik);\n\t\n\t/* check if there is a minimum, if not return inf */\n\tif (fa == fb || fc == fb || ax > cx){\n\t\t*lik_beta_hat = fa;\n\t\treturn 666.0;\n\t\t}\n\telse{\n\t\t\n\t\t/* do mimization */\n\t\t\n\t\tL.function = &my_lik;\n\t\t//should have param line here but no params....\n\t\t\n\t\tT = gsl_min_fminimizer_brent;\n\t\ts = gsl_min_fminimizer_alloc(T);\n\t\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\t\t\n\t\tdo{\n\t\t\titer++;\n\t\t\tstatus = gsl_min_fminimizer_iterate(s);\n\t\t\t m = gsl_min_fminimizer_x_minimum (s);\n\t\t\t a = gsl_min_fminimizer_x_lower (s);\n\t\t\t b = gsl_min_fminimizer_x_upper (s);\n\t\t\n\t\t\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t\t\n\t\t}\n\t while (status == GSL_CONTINUE && iter < max_iter);\n\t gsl_min_fminimizer_free(s);\n\t \n\t return m;\n\t}\n}\n\n/* get weighted ML estimate of beta using likelihood function; BRENT method for gsl */\ndouble weighted_ml_est(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, min;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -10.0;\n\tbx = 1.0;\n\tcx = 10;\n\tL.function = &weightedLik;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrap, bx, params);\n\n\t//check if there is a minimum, if not return 666\n\tif (fa == fb || fc == fb || ax > cx){\n\t min = fa;\n\t if(fb < min){\n\t min = fb;\n\t }\n\t if(fc < min){\n\t min = fc;\n\t }\n\t *lik_beta_hat = min;\n \t\n\t return 666.0;\n\t}\n\telse{\n\t // do mimization \n\t\t\n\t //initialize lik function\n\t L.function = &weightedLik;\n\t L.params = params;\n\t \n\t //min routine\n\t T = gsl_min_fminimizer_brent;\n\t s = gsl_min_fminimizer_alloc(T);\n\t gsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\t do{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t }\n\t while (status == GSL_CONTINUE && iter < max_iter);\n\t *lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\t gsl_min_fminimizer_free(s);\n\t return m;\n\t}\n}\n\ndouble weighted_ml_est_lookup(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 1000;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t// get minimum bracket \n\tax = -20.0;\n\tbx = -1.0;\n\tcx = 20000;\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\n\tif (fb == fc){\n\t\treturn HUGE_VAL;\n\t}\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_min_fminimizer_brent;\n\ts = gsl_min_fminimizer_alloc(T);\n\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.01, 0.01);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\tgsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* same as above but outputs 666 on minimization error */\ndouble weighted_ml_est_lookup_errReport(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -20.0;\n\tbx = -1.0;\n\tcx = 20;\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\t//check for error\n\tif (fb >= fc || fb >= fa){\n\t return(666.0);\n\t}\n\t\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\t \n\t//min routine\n\ts = params->min;\n\tgsl_set_error_handler_off ();\n\tstatus = gsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tif (status == GSL_EINVAL){\n\t return(666);\n\t}\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.01, 0.01);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\t//gsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* get weighted ML lower CI beta using weightedLikLookCI method; BRENT method for gsl */\ndouble weighted_ml_CILower_lookup(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\tdouble m, a, b, ax, cx;\n\tgsl_function L;\n\tstruct my_likCI_params * params = (struct my_likCI_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -50.0;\n\tcx = params->beta_hat;\n\t \n\t// do root finding \t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookCI;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &L, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_root_fsolver_iterate(s);\n\t m = gsl_root_fsolver_root(s);\n\t a = gsl_root_fsolver_x_lower(s);\n\t b = gsl_root_fsolver_x_upper(s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\tgsl_root_fsolver_free(s);\n\treturn m;\n}\n\n/* get weighted ML upper CI beta using weightedLikLookCI method; BRENT method for gsl */\ndouble weighted_ml_CIUpper_lookup(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\tdouble m, a, b, ax, cx;\n\tgsl_function L;\n\tstruct my_likCI_params * params = (struct my_likCI_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tcx = 100.0;\n\tax = params->beta_hat;\n\t \n\t// do root finding \t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookCI;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &L, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_root_fsolver_iterate(s);\n\t m = gsl_root_fsolver_root(s);\n\t a = gsl_root_fsolver_x_lower(s);\n\t b = gsl_root_fsolver_x_upper(s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\tgsl_root_fsolver_free(s);\n\treturn m;\n}\n\n//Folded Version\ndouble weighted_ml_est_lookup_folded(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 1000;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t// get minimum bracket \n\tax = -20.0;\n\tbx = -1.0;\n\tcx = 20000;\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookFolded, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\n\tif (fb == fc){\n\t\treturn HUGE_VAL;\n\t}\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &weightedLikLook;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_min_fminimizer_brent;\n\ts = gsl_min_fminimizer_alloc(T);\n\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.01, 0.01);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\tgsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* get weighted ML lower CI beta using weightedLikLookCI method; BRENT method for gsl */\ndouble weighted_ml_CILower_lookupFolded(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\tdouble m, a, b, ax, cx;\n\tgsl_function L;\n\tstruct my_likCI_params * params = (struct my_likCI_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -50.0;\n\tcx = params->beta_hat;\n\t \n\t// do root finding \t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookCIFolded;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &L, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_root_fsolver_iterate(s);\n\t m = gsl_root_fsolver_root(s);\n\t a = gsl_root_fsolver_x_lower(s);\n\t b = gsl_root_fsolver_x_upper(s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\tgsl_root_fsolver_free(s);\n\treturn m;\n}\n\n/* get weighted ML upper CI beta using weightedLikLookCI method; BRENT method for gsl */\ndouble weighted_ml_CIUpper_lookupFolded(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\tdouble m, a, b, ax, cx;\n\tgsl_function L;\n\tstruct my_likCI_params * params = (struct my_likCI_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tcx = 100.0;\n\tax = params->beta_hat;\n\t \n\t// do root finding \t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookCIFolded;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &L, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_root_fsolver_iterate(s);\n\t m = gsl_root_fsolver_root(s);\n\t a = gsl_root_fsolver_x_lower(s);\n\t b = gsl_root_fsolver_x_upper(s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\tgsl_root_fsolver_free(s);\n\treturn m;\n}\n\n//ML estimation using PRF likelihood model\ndouble ml_prf(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct prfLik_params * params = (struct prfLik_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -10.0;\n\tbx = 0.0;\n\tcx = 10;\n\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &prfLikWrap, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\n\tif (fb == fc){\n\t\treturn HUGE_VAL;\n\t}\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &prfLik;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_min_fminimizer_brent;\n\ts = gsl_min_fminimizer_alloc(T);\n\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\tgsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* summarizeSFS- returns a matrix of counts which summarize the SFS conditional\n upon sampleSize. rows = sampleSize, column = freqs */\n\ngsl_matrix *summarizeSFS(int maxSampleSize, struct snp data[], int snpNumber){\n gsl_matrix *counts;\n int i;\n\n //alloc matrix of size maxSampleSize by maxSampleSize\n counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);\n gsl_matrix_set_zero(counts);\n assert(counts != NULL);\n \n //gsl_matrix_set_zero(counts);\n \n //go through data, fill up matrix\n for(i = 0; i < snpNumber; i++){\n gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);\n }\n return(counts);\n\n}\n\n/* summarizeSFSFill- fills a matrix of counts which summarize the SFS conditional\n upon sampleSize. rows = sampleSize, column = freqs */\n\nvoid summarizeSFSFill(gsl_matrix *counts, struct snp data[], int snpNumber){\n int i;\n\n //fill matrix of size maxSampleSize by maxSampleSize\n gsl_matrix_set_zero(counts);\n assert(counts != NULL);\n gsl_matrix_set_zero(counts);\n \n //go through data, fill up matrix\n for(i = 0; i < snpNumber; i++){\n gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);\n }\n}\n\n/* summarizeSFSFill- fills a matrix of counts which summarize the SFS conditional\n upon sampleSize. rows = sampleSize, column = freqs */\n\nint summarizeSFSFillFromTo(gsl_matrix *counts, struct snp data[], int snpNumber, int from, int to, int startPos){\n int i;\n\n //fill matrix of size maxSampleSize by maxSampleSize\n gsl_matrix_set_zero(counts);\n assert(counts != NULL);\n gsl_matrix_set_zero(counts);\n \n //go through data, fill up matrix\n\ti = startPos;\n\twhile(data[i].pos < to){\n\t\tif(data[i].pos >= from)\n \t\tgsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);\n\t\ti++;\n \t}\n\treturn(i);\n}\n\n\n\n/* summarizeSFS- returns a matrix of booleans which summarize the SFS conditional\n upon sampleSize. rows = sampleSize, column = freqs */\n\ngsl_matrix *summarizeSFSBool(int maxSampleSize, struct snp data[], int snpNumber){\n gsl_matrix *counts;\n int i;\n\n //alloc matrix of size maxSampleSize by maxSampleSize\n counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);\n gsl_matrix_set_zero(counts);\n assert(counts != NULL);\n \n gsl_matrix_set_zero(counts);\n \n //go through data, fill up matrix\n for(i = 0; i < snpNumber; i++){\n gsl_matrix_set(counts, data[i].n, data[i].i, 1);\n }\n return(counts);\n\n}\n\n/* summarizeSFSBoolFill- fills a matrix of booleans which summarize the SFS conditional\n upon sampleSize. rows = sampleSize, column = freqs */\n\nvoid summarizeSFSBoolFill(gsl_matrix *counts, struct snp data[], int snpNumber){\n int i;\n\n //fill matrix of size maxSampleSize by maxSampleSize\n //counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);\n gsl_matrix_set_zero(counts);\n assert(counts != NULL);\n \n gsl_matrix_set_zero(counts);\n \n //go through data, fill up matrix\n for(i = 0; i < snpNumber; i++){\n gsl_matrix_set(counts, data[i].n, data[i].i, 1);\n }\n}\n\n\n/* simulateSiteFreq- returns an int representing the frequency of\n of a site (unfolded), i, in sampleSize n, conditional on sel. \n coeff. beta , also needs a pointer to a gsl random number generator */\n\nint simulateSiteFreq(int sampleSize, double alpha, void *r){\n int i;\n double sum, probs[sampleSize - 1], rand;\n gsl_function p;\n struct my_F_params simParams;\n gsl_rng * rn = (gsl_rng *) r;\n \n simParams.n = sampleSize;\n /* put probs in vector */\n for(i = 0; i < sampleSize - 1; i++){\n simParams.i = i + 1;\n p.function = &snpProb;\n p.params = &simParams;\n probs[i] = GSL_FN_EVAL(&p, alpha); \n }\n\n /* choose frequency */\n rand = gsl_rng_uniform(rn);\n sum = 0;\n for(i = 0; i < sampleSize - 1; i++){\n sum += probs[i];\n if (rand <= sum){\n return(i+1);\n }\n }\n return(666);\n}\n\n/* ascertainment stuff -- following Nielsen et al. 2004 */\n\n/* simpleAscertain-- Nielsen et al. 2004 eqn 2 *, returns the prob of ascertainment \ngiven a sample freq */\ndouble simpleAscertain(double sampleFreq, void * p){\n struct my_F_params * params = (struct my_F_params *) p;\n double sampleSize, ascSize,tmpSampleFreq;\n double num1 = 0.0;\n double num2 = 0.0;\n \n sampleSize = params->n;\n ascSize = params->ascSize;\n tmpSampleFreq = (int) sampleFreq;\n\n //test for weirdness\n \n if (sampleFreq < ascSize){\n num1 = 0;\n }\n else{\n num1 = gsl_sf_choose(sampleFreq, ascSize);\n }\n\n if ((sampleSize -sampleFreq) < ascSize){\n num2 = 0;\n }\n else{\n num2 = gsl_sf_choose(sampleSize - sampleFreq, ascSize);\n }\n\n return(1.0 - ((num1 + num2) / gsl_sf_choose(sampleSize, ascSize)));\n}\n\n/* outgroupAscertain-- equivalent to Nielsen et al. 2004 eqn 2,\n returns the prob of ascertainment given a sample freq, but\nis for use when ascertainment was based on single outgroup comparisons\n(e.g. divergence between reference genomes). specifically this\ncalculates the prob of sampling only ancestral alleles.\nIMPORTANT- sampleFreq here is derived allele freq */\ndouble outgroupAscertain(double sampleFreq, void * p){\n\tstruct my_F_params * params = (struct my_F_params *) p;\n\tint sampleSize, ascSize, derived;\n\tdouble num = 0.0;\n\n\tsampleSize = params->n;\n\tascSize = params->ascSize;\n\tderived = params->derivedFlag;\n\tif(derived){\t \n\t num = xchoosey( sampleFreq, ascSize);\n\t }\n\t else{\n\t num = xchoosey((sampleSize - sampleFreq), ascSize);\n\t }\n\t return(num /xchoosey(sampleSize, ascSize));\n}\n\n/*same as above for case where ascSamp is not subset of sample */\ndouble outgroupAscertain2(double sampleFreq, void * p){\n\tstruct my_F_params * params = (struct my_F_params *) p;\n\tint sampleSize, ascSize,ascFreq, derived, N, j;\n\tdouble num = 0.0, denom = 0.0;\n\n\tsampleSize = params->n;\n\tascSize = params->ascSize;\n\tascFreq = params->ascFreq;\n\tderived = params->derivedFlag;\n\t\n\tN = sampleSize + ascSize;\n\tj = sampleFreq + ascFreq;\n \t//was ascertainment for derived?\n \tif(derived == 1){\n\t\tnum = xchoosey(j,sampleFreq) * xchoosey((N-j), sampleSize - sampleFreq);\n \t}\n \telse{\n\t\tnum = xchoosey((N-j), (sampleSize - sampleFreq)) * xchoosey(j, sampleFreq); \n \t}\n//\tprintf(\"num: %f\\n\", num );\n//\tprintf(\"N: %d j: %d sampleSize: %d ascSize: %d derivedFlag: %d\\n\",N,j, sampleSize,ascSize,derived);\n\tdenom = xchoosey(N, sampleSize);\n\tif (denom == 0 || num == 0){\n\t\treturn(0);\n\t}\n//\tprintf(\"oaVal: %f\\n\",num)/denom;\n \treturn(num / denom);\n}\n\n/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8\n returns the prob of ascertainment given the model */\ndouble probAscertainmentGivenModel(double beta, void *p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_F_params tempParams;\n \n long double tot, tmpres, tmpres2;\n int i=1;\n gsl_function F, G;\n \n /* add up total prob space */\n tot = 0.0;\n tempParams.n = params->n;\n tempParams.ascSize = params->ascSize;\n \n for(i = 1; i < params->n ; i++){\n tempParams.i = i;\n \n F.function = &(snpProb);\n F.params = &tempParams;\n tmpres = 0.0;\n tmpres = GSL_FN_EVAL(&F, beta);\n G.function = &simpleAscertain;\n G.params = &tempParams;\n tmpres2 = GSL_FN_EVAL(&G, i) ;\n tot += tmpres * tmpres2;\n \n }\n \n \n return(tot) ;\n}\n\n/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8\n returns the prob of ascertainment given the model */\ndouble probOutgroupAscertainmentGivenModel(double beta, void *p){\n struct my_F_params * params = (struct my_F_params *) p;\n struct my_F_params tempParams;\n \n long double tot, tmpres, tmpres2;\n int i=1;\n gsl_function F, G;\n \n /* add up total prob space */\n tot = 0.0;\n tempParams.n = params->n;\n tempParams.ascSize = params->ascSize;\n \n for(i = 1; i < params->n ; i++){\n tempParams.i = i;\n \n F.function = &(snpProb);\n F.params = &tempParams;\n tmpres = 0.0;\n tmpres = GSL_FN_EVAL(&F, beta);\n G.function = &outgroupAscertain;\n G.params = &tempParams;\n tmpres2 = GSL_FN_EVAL(&G, i) ;\n tot += tmpres * tmpres2;\n \n }\n \n \n return(tot) ;\n}\n\n/* probAscertainmentGivenModelLookup-- Nielsen et al. 2005 eqn 8\n returns the prob of ascertainment given the model, lookup version\n requires snpProb matrix and ascProb matrix */\ndouble probAscertainmentGivenModelLookup(double beta, int sampSize, gsl_matrix *snpProbs, gsl_matrix *ascProbs){\n \n long double tot;\n int i=1;\n \n /* add up total prob space */\n tot = 0.0;\n \n for(i = 1; i < sampSize ; i++){\n tot += gsl_matrix_get(snpProbs, sampSize, i) * gsl_matrix_get(ascProbs, sampSize, i);\n }\n return(tot) ;\n}\n\n/* probAscertainmentGivenModelHemiLookup-- same\n as above but expects vector not matrix of snpProbs */\ndouble probAscertainmentGivenModelHemiLookup(double beta, int sampSize, gsl_vector *snpProbs, gsl_matrix *ascProbs){\n \n long double tot;\n int i=1;\n \n /* add up total prob space */\n tot = 0.0;\n \n for(i = 1; i < sampSize ; i++){\n tot += gsl_vector_get(snpProbs, i) * gsl_matrix_get(ascProbs, sampSize, i);\n }\n return(tot) ;\n}\n\n\n/* ascSize vector - returns a vector of 1s or 0s depending on ascertainment sample sizes in the data */\ngsl_vector *ascSizeVector(struct snp data[], int snpNumber, int maxSampleSize){\n gsl_vector *bools;\n int i;\n\n //alloc and initialize bools vector\n bools = gsl_vector_alloc(maxSampleSize + 1);\n gsl_vector_set_zero(bools);\n\n //go through data, set each sampleSize value to 1\n for(i = 0; i < snpNumber; i++){\n gsl_vector_set(bools,data[i].ascSize, 1);\n }\n return(bools);\n}\n\n/* snpAscMatrix- returns a matrix of simpleAscertainment probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\n variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */\ngsl_matrix *snpAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \\\n\t\t int ascSize){\n gsl_matrix *probs;\n struct my_F_params FParams;\n gsl_function f;\n int i, j;\n \n //alloc probs\n probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n gsl_matrix_set_zero(probs);\n //go through sampleSizes\n for(i = 2; i <= maxSampleSize; i++){\n //have sample size i?\n if (gsl_vector_get(sampleSizeVector, i)){\n //go through freqs\n for(j = 1; j < maxSampleSize; j++){\n\t//have freq j?\n\tif(gsl_matrix_get(sfsBools, i, j)){\n\t //calc prob\n\t FParams.i = j;\n\t FParams.n = i;\n\t FParams.ascSize = ascSize;\n\t f.function = &simpleAscertain;\n\t f.params = &FParams;\n\t gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));\n\t}\n }\n }\n }\n return(probs);\n}\n\n/* snpOutgroupAscMatrix- returns a matrix of outgroupAscertainment probs. \nmatrix is maxSampleSize+1 by maxSampleSize. rows represent\n variable sampleSizes (2 to max), columns represent freqs (1 to max -1). \nCurrently this only supports a single ascertainment size. Also has inelegance\nof calculating derived or anscertral matrix */\ngsl_matrix *snpOutgroupAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize, int derived, \\\nint runMode){\n\tgsl_matrix *probs;\n\tstruct my_F_params FParams;\n\tgsl_function f;\n\tint i, j;\n\n//alloc probs\n\tprobs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n\tgsl_matrix_set_zero(probs);\n//go through sampleSizes\n\tfor(i = 2; i <= maxSampleSize; i++){\n\t//have sample size i?\n\t\tif (gsl_vector_get(sampleSizeVector, i)){\n\t//go through freqs\n\t\t\tfor(j = 1; j < i; j++){\n\t//calc prob\n\t\t\t\tFParams.i = j;\n\t\t\t\tFParams.n = i;\n\t\t\t\tFParams.ascSize = ascSize;\n\t\t\t\tFParams.ascFreq = derived;\n\t\t\t\tFParams.derivedFlag = derived;\n\t\t\t\tif(runMode == 0){\n\t\t\t\t\tf.function = &outgroupAscertain;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tf.function = &outgroupAscertain2;\n\t\t\t\t}\n\t\t\t\tf.params = &FParams;\n\t\t\t\tgsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));\n\t\t\t}\n\t\t}\n\t}\n\treturn(probs);\n}\n\ngsl_matrix *snpOutgroupAscMatrixPre(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize, int derived, \\\nint runMode, gsl_matrix *probs){\n\tstruct my_F_params FParams;\n\tgsl_function f;\n\tint i, j;\n\n\tgsl_matrix_set_zero(probs);\n//go through sampleSizes\n\tfor(i = 2; i <= maxSampleSize; i++){\n\t//have sample size i?\n\t\tif (gsl_vector_get(sampleSizeVector, i)){\n\t//go through freqs\n\t\t\tfor(j = 1; j < i; j++){\n\t//calc prob\n\t\t\t\tFParams.i = j;\n\t\t\t\tFParams.n = i;\n\t\t\t\tFParams.ascSize = ascSize;\n\t\t\t\tFParams.ascFreq = derived;\n\t\t\t\tFParams.derivedFlag = derived;\n\t\t\t\tif(runMode == 0){\n\t\t\t\t\tf.function = &outgroupAscertain;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tf.function = &outgroupAscertain2;\n\t\t\t\t}\n\t\t\t\tf.params = &FParams;\n\t\t\t\tgsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));\n\t\t\t}\n\t\t}\n\t}\n\treturn(probs);\n}\n\n\n/*estimateAscSFS-- ML estimates of SFS, given ascertainment. returns \n a matrix of probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent\nvariable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */\n\ngsl_matrix *estimateAscSFS(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \\\n\t\t\t int ascSize, gsl_matrix *sfsSummary){\n gsl_matrix *probs, *ascProbs;\n int i, j;\n double ssTmp, p_hat; \n double xij;\n\n //alloc probs\n probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);\n gsl_matrix_set_zero(probs);\n //calculate ascProbs\n ascProbs = snpAscMatrix(maxSampleSize, sampleSizeVector, sfsBools, \\\n\t\t\t ascSize);\n \n\n //go through sampleSizes \n for(i = 2; i <= maxSampleSize; i++){\n //have sample size i?\n if (gsl_vector_get(sampleSizeVector, i)){\n //go through freqs to tally up denom at sampleSize\n ssTmp = 0.0;\n for(j = 1; j < maxSampleSize; j++){\n\txij = gsl_matrix_get(sfsSummary, i, j);\n\tif (xij > 0){\n\t ssTmp += xij / gsl_matrix_get(ascProbs, i, j);\n\t}\n }\n //go back through freqs to assign p_hats at sampleSize\n for(j = 1; j < maxSampleSize; j++){\n\txij = gsl_matrix_get(sfsSummary, i, j);\n\tp_hat = (double) xij / gsl_matrix_get(ascProbs, i, j);\n\tgsl_matrix_set(probs, i, j, p_hat / ssTmp);\n }\n }\n }\n return(probs);\n}\n\n/* weighted likelihood function for SFS given the data and ascertainment; here contains the data and the weights and uses the snpProbLookup routine */\ndouble weightedLikLookAsc(double beta, void * p){\n struct my_lik_params * params = (struct my_lik_params *) p;\n double lik, num;\n int i;\n gsl_matrix *probs, *ascProbs;\n gsl_vector *ascDenoms;\n\n \n //make prob matrix (note this is in logs)\n probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);\n //make ascProb matrix (NOT in logs!)\n ascProbs = snpAscMatrix(params->maxSampleSize, params->sampleSizeVector, params->sfsBools, params->ascSize);\n\n //make vector of denoms\n ascDenoms = gsl_vector_alloc(params->maxSampleSize + 1);\n gsl_vector_set_zero(ascDenoms);\n for(i = params->ascSize; i <= params->maxSampleSize; i++){\n gsl_vector_set(ascDenoms,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbs));\n }\n\n //now go and tally likelihood\n lik = 0;\n num = 0;\n for(i = 0; i < params->snpNumber; i++){\n lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i)\t\\\n + log(gsl_matrix_get(ascProbs,params->data[i].n,params->data[i].i)) \\\n - log(gsl_vector_get(ascDenoms, params->data[i].n));\n }\n gsl_matrix_free(probs);\n gsl_matrix_free(ascProbs);\n gsl_vector_free(ascDenoms);\n \n return -lik;\n}\n \n\n/* weighted likelihood function for SFS given the data and outgroup ascertainment; here contains the data and the weights and uses the snpProbLookup routine */\ndouble weightedLikLookOutgroupAsc(double beta, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tdouble lik, num;\n\tint i;\n\tgsl_matrix *probs, *ascProbsDerived, *ascProbsAncestral;\n\tgsl_vector *ascDenomsDerived, *ascDenomsAncestral;\n\n\t//make prob matrix \n\tprobs = snpProbMatrixNotLogFull(beta, params->maxSampleSize, params->sampleSizeVector);\n\t//make ascProb matrices, one for derived one for ancestral\n\tascProbsAncestral = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 0, params->runMode);\n\n\tascProbsDerived = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 1, params->runMode);\n\t\n\t//make vectors of denoms- derived, ancestral\n\tascDenomsDerived = gsl_vector_alloc(params->maxSampleSize + 1);\n\tascDenomsAncestral = gsl_vector_alloc(params->maxSampleSize + 1);\n\tgsl_vector_set_zero(ascDenomsDerived);\n\tgsl_vector_set_zero(ascDenomsAncestral);\n\tfor(i = params->ascSize; i <= params->maxSampleSize; i++){\n\t\tgsl_vector_set(ascDenomsDerived,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbsDerived));\n\t\tgsl_vector_set(ascDenomsAncestral,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbsAncestral));\n\t}\n\n//now go and tally likelihood\n\tlik = 0;\n\tnum = 0;\n\tfor(i = 0; i < params->snpNumber; i++){\n\t\tif(params->data[i].derivedFlag == 1){\n\t\t\tnum = (gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(ascProbsDerived,params->data[i].n,params->data[i].i)) \\\n\t\t\t\t/ gsl_vector_get(ascDenomsDerived, params->data[i].n); \n\t\t\t}\n\t\telse{\n\t\t\tnum = (gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(ascProbsAncestral,params->data[i].n,params->data[i].i)) \\\n\t\t\t\t/ gsl_vector_get(ascDenomsAncestral, params->data[i].n);\n\t\t}\t\n\t\tlik += log(num);\n\t}\n\n\tgsl_matrix_free(probs);\n\tgsl_matrix_free(ascProbsDerived);\n\tgsl_matrix_free(ascProbsAncestral);\n\tgsl_vector_free(ascDenomsDerived);\n\tgsl_vector_free(ascDenomsAncestral);\n\treturn -lik;\n}\n\n\n/* wrapper for my_lik for use in mnbrak */\ndouble wlikWrapLookAsc(double beta, void * p){\n\tgsl_function f;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\t\n\tf.function = &weightedLikLookAsc;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\n/* wrapper for my_lik for use in mnbrak */\ndouble wlikWrapLookOutgroupAsc(double beta, void * p){\n\tgsl_function f;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\t\n\tf.function = &weightedLikLookOutgroupAsc;\n\tf.params = params;\n\treturn GSL_FN_EVAL(&f, beta);\n}\n\n/* get weighted ML estimate of beta using likelihood function (lookup) conditional on ascertainment\n; BRENT method for gsl */\ndouble weighted_ml_est_lookup_asc(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -20.0;\n\tbx = -1.0;\n\tcx = 20;\n\tL.function = &weightedLikLookAsc;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookAsc, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookAsc;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_min_fminimizer_brent;\n\ts = gsl_min_fminimizer_alloc(T);\n\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\tgsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* get weighted ML estimate of beta using likelihood function (lookup) conditional on outgroup ascertainment\n; BRENT method for gsl */\ndouble weighted_ml_est_lookup_outgroup_asc(double * lik_beta_hat, void * p){\n\tint status;\n\tint iter = 0;\n\tint max_iter = 100;\n\tconst gsl_min_fminimizer_type *T;\n\tgsl_min_fminimizer *s;\n\tdouble m, a, b, ax, bx, cx, fa, fb, fc, dummy;\n\tgsl_function L;\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\t\n\t\n\t\n\t// get minimum bracket \n\tax = -20.0;\n\tbx = -1.0;\n\tcx = 20;\n\tL.function = &weightedLikLookOutgroupAsc;\n\tL.params = params;\n\tmnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookOutgroupAsc, bx, params);\n\t//swap bounds if needed\n\tif (cx < ax){\n\t dummy = cx;\n\t cx = ax;\n\t ax = dummy;\n\t}\n\t// do mimization \n\t\t\n\t//initialize lik function\n\tL.function = &weightedLikLookOutgroupAsc;\n\tL.params = params;\n\t \n\t//min routine\n\tT = gsl_min_fminimizer_brent;\n\ts = gsl_min_fminimizer_alloc(T);\n\tgsl_min_fminimizer_set(s, &L, bx, ax, cx);\n\tdo{\n\t iter++;\n\t status = gsl_min_fminimizer_iterate(s);\n\t m = gsl_min_fminimizer_x_minimum (s);\n\t a = gsl_min_fminimizer_x_lower (s);\n\t b = gsl_min_fminimizer_x_upper (s);\n\t status = gsl_min_test_interval (a, b, 0.001, 0.0);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);\n\tgsl_min_fminimizer_free(s);\n\treturn m;\n}\n\n/* likelihood function for SFS where each SNP has\n independent selection coeff and outgroup ascertainment */\ndouble sfsLikBetaVectorOutgroupAsc(gsl_vector *betas, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tdouble pSNP, pAsc, pAscModel,lik, tmp;\n\tint i;\n\tgsl_matrix *ascProbsDerived, *ascProbsAncestral;\n\tgsl_vector *snpProbs;\n\n\tlik = 0;\n//make ascProb matrix \n\tascProbsAncestral = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 0, params->runMode);\n\n\tascProbsDerived = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 1, params->runMode);\n//go through snps\n\tfor(i = 0; i < params->snpNumber; i++){\n\t//create vector of snpProbs, find pSNP_i\n\t\tsnpProbs = snpProbVectorNotLog(gsl_vector_get(betas, i), params->data[i].n);\n\t\tpSNP = gsl_vector_get(snpProbs, params->data[i].i);\n\n\t//lookup pAsc_i\n\t\tif(params->data[i].derivedFlag){\n\t\t\tpAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsDerived);\n\t\t}\n\t\telse{\n\t\t\tpAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsAncestral);\n\t\t}\n\t\ttmp = pSNP * pAsc / pAscModel;\n\t\tlik += log(tmp);\n\t\tgsl_vector_free(snpProbs);\n\t}\n\tgsl_matrix_free(ascProbsAncestral);\n\tgsl_matrix_free(ascProbsDerived);\n\treturn -lik;\n}\n\ndouble sfsLikBetaVectorOutgroupAscPre(gsl_vector *betas, gsl_matrix *ascProbsAncestral,gsl_matrix *ascProbsDerived, gsl_vector *snpProbs, void * p){\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tdouble pSNP, pAsc, pAscModel,lik, tmp;\n\tint i;\n\n\tlik = 0.0;\n//make ascProb matrix \n\tascProbsAncestral = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 0, params->runMode,ascProbsAncestral);\n\n\tascProbsDerived = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 1, params->runMode,ascProbsDerived);\n//go through snps\n\tfor(i = 0; i < params->snpNumber; i++){\n\t//create vector of snpProbs, find pSNP_i\n\t\tsnpProbs = snpProbVectorNotLogPre(gsl_vector_get(betas, i), params->data[i].n,snpProbs);\n\t\tpSNP = gsl_vector_get(snpProbs, params->data[i].i);\n\n\t//lookup pAsc_i\n\t\tif(params->data[i].derivedFlag){\n\t\t\tpAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsDerived);\n\t\t}\n\t\telse{\n\t\t\tpAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsAncestral);\n\t\t}\n\t\ttmp = pSNP * pAsc / pAscModel;\n\t\tlik += log(tmp);\n//\t\tprintf(\"%f\\n\",lik);\n\t}\n\treturn(-lik);\n}\n//classical summary stats\n\n//tajimas theta_pi\ndouble theta_pi(struct snp *data, int sites){\n\tint i;\n\tdouble n,p, sum;\n\t\n\tsum = 0.0;\n\tfor(i=0;isnpNumber;\n\tint i, start, end, window;\n\t\n\t//initialize; where am i?\n\tlik = 0.;\n\twindow = ceil((float)snpNumber / mprocs);\n\tstart = myrank * window;\n\tend = start + window;\n\tFParams.w = params->w;\n\tf.function = &snpProb;\n\tfor(i = start; i < end && i < snpNumber; i++){\n\t\tFParams.i = params->data[i].i;\n\t\tFParams.n = params->data[i].n;\n\n\t\tf.params = &FParams;\n\t//\tprintf(\"here lik:%f beta:%f i: %d n: %d\\n\",lik,gsl_vector_get(betas, i),FParams.i,FParams.n);\n\t\t\n\t\tlik += log(GSL_FN_EVAL(&f, gsl_vector_get(betas, i)));\n\t\t}\n\tMPI_Reduce(&lik,&final,1, MPI_DOUBLE,MPI_SUM,0,comm);\n\treturn -final;\n}\n\ndouble sfsLikBetaVectorOutgroupAscPreMPI(gsl_vector *betas, gsl_matrix *ascProbsAncestral,gsl_matrix *ascProbsDerived, \\\n\tgsl_vector *snpProbs, void * p,int myrank, int mprocs, MPI_Comm comm){\n\t\t\n\tstruct my_lik_params * params = (struct my_lik_params *) p;\n\tdouble pSNP, pAsc, pAscModel,lik, tmp, final;\n\tint i,start, end, window,snpNumber;\n\t\n\t//initialization; window for proc to process\n\tlik = 0;\n\tsnpNumber = params->snpNumber;\n\twindow = ceil((float)snpNumber / mprocs);\n\tstart = myrank * window;\n\tend = start + window;\n\t\n\t//currently every process calculates the matrices below-- could be faster\n\t//make ascProb matrix \n\tascProbsAncestral = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 0, params->runMode,ascProbsAncestral);\n\n\tascProbsDerived = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \\\n\t\tparams->ascSize, 1, params->runMode,ascProbsDerived);\n\t\t\n\t//go through snps\n\tfor(i = start; i < end && i < snpNumber; i++){\n\t//create vector of snpProbs, find pSNP_i\n\t\tsnpProbs = snpProbVectorNotLogPre(gsl_vector_get(betas, i), params->data[i].n,snpProbs);\n\t\tpSNP = gsl_vector_get(snpProbs, params->data[i].i);\n\n\t//lookup pAsc_i\n\t\tif(params->data[i].derivedFlag){\n\t\t\tpAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsDerived);\n\t\t}\n\t\telse{\n\t\t\tpAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);\n\t\t\t//get pAscModel\n\t\t\tpAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \\\n\t\t\t\t\tsnpProbs, ascProbsAncestral);\n\t\t}\n\t\ttmp = pSNP * pAsc / pAscModel;\n\t\tlik += log(tmp);\n\t}\n\tMPI_Reduce(&lik,&final,1, MPI_DOUBLE,MPI_SUM,0,comm);\n\treturn -final;\n}\n\n\n", "meta": {"hexsha": "0c801aba44d08ecc4cccf4ca72a818022bb06e98", "size": 57971, "ext": "c", "lang": "C", "max_stars_repo_path": "popGenTools.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": "popGenTools.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": "popGenTools.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": 27.6447305675, "max_line_length": 161, "alphanum_fraction": 0.6834106709, "num_tokens": 18103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6023220877428426}} {"text": "#include \n#include \n\nint\nmain (int argc, char **argv)\n{\n int i, n;\n double xi, yi, ei, chisq;\n gsl_matrix *X, *cov;\n gsl_vector *y, *w, *c;\n\n if (argc != 2)\n {\n fprintf (stderr,\"usage: fit n < data\\n\");\n exit (-1);\n }\n\n n = atoi (argv[1]);\n\n X = gsl_matrix_alloc (n, 3);\n y = gsl_vector_alloc (n);\n w = gsl_vector_alloc (n);\n\n c = gsl_vector_alloc (3);\n cov = gsl_matrix_alloc (3, 3);\n\n for (i = 0; i < n; i++)\n {\n int count = fscanf (stdin, \"%lg %lg %lg\",\n &xi, &yi, &ei);\n\n if (count != 3)\n {\n fprintf (stderr, \"error reading file\\n\");\n exit (-1);\n }\n\n printf (\"%g %g +/- %g\\n\", xi, yi, ei);\n \n gsl_matrix_set (X, i, 0, 1.0);\n gsl_matrix_set (X, i, 1, xi);\n gsl_matrix_set (X, i, 2, xi*xi);\n \n gsl_vector_set (y, i, yi);\n gsl_vector_set (w, i, 1.0/(ei*ei));\n }\n\n {\n gsl_multifit_linear_workspace * work \n = gsl_multifit_linear_alloc (n, 3);\n gsl_multifit_wlinear (X, w, y, c, cov,\n &chisq, work);\n gsl_multifit_linear_free (work);\n }\n\n#define C(i) (gsl_vector_get(c,(i)))\n#define COV(i,j) (gsl_matrix_get(cov,(i),(j)))\n\n {\n printf (\"# best fit: Y = %g + %g X + %g X^2\\n\", \n C(0), C(1), C(2));\n\n printf (\"# covariance matrix:\\n\");\n printf (\"[ %+.5e, %+.5e, %+.5e \\n\",\n COV(0,0), COV(0,1), COV(0,2));\n printf (\" %+.5e, %+.5e, %+.5e \\n\", \n COV(1,0), COV(1,1), COV(1,2));\n printf (\" %+.5e, %+.5e, %+.5e ]\\n\", \n COV(2,0), COV(2,1), COV(2,2));\n printf (\"# chisq = %g\\n\", chisq);\n }\n\n gsl_matrix_free (X);\n gsl_vector_free (y);\n gsl_vector_free (w);\n gsl_vector_free (c);\n gsl_matrix_free (cov);\n\n return 0;\n}\n", "meta": {"hexsha": "43f8c06706a43996e9d73dcacd08e7ae50dbea43", "size": 1799, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/fitting2.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/fitting2.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/fitting2.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.2098765432, "max_line_length": 52, "alphanum_fraction": 0.4813785436, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6023220079932596}} {"text": "/* randist/geometric.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/* Geometric distribution (bernoulli trial with probability p) \n\n prob(k) = p (1 - p)^(k-1) for n = 1, 2, 3, ...\n\n It gives the distribution of \"waiting times\" for an event that\n occurs with probability p. */\n\nunsigned int\ngsl_ran_geometric (const gsl_rng * r, const double p)\n{\n double u = gsl_rng_uniform_pos (r);\n\n unsigned int k;\n\n if (p == 1)\n {\n k = 1;\n }\n else\n {\n k = log (u) / log (1 - p) + 1;\n }\n\n return k;\n}\n\ndouble\ngsl_ran_geometric_pdf (const unsigned int k, const double p)\n{\n if (k == 0)\n {\n return 0 ;\n }\n else if (k == 1)\n {\n return p ;\n }\n else\n {\n double P = p * pow (1 - p, k - 1.0);\n return P;\n }\n}\n", "meta": {"hexsha": "afce6b27b252de26c394dc7aa17adcadb2cc653c", "size": 1624, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/randist/geometric.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/geometric.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/geometric.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 23.8823529412, "max_line_length": 81, "alphanum_fraction": 0.6471674877, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6023219919686535}} {"text": "static char help[] =\n\"ODE system solver example using TS. Solves a 2D system\\n\"\n\" dy/dt = G(t,y)\\n\"\n\"with y(t0) = y0 to compute y(tf). Sets problem type to NONLINEAR and\\n\"\n\"TS type to Runge-Kutta. No Jacobian is supplied; compare odejac.c.\\n\"\n\"Exact solution is known.\\n\\n\";\n\n#include \n\nextern PetscErrorCode ExactSolution(PetscReal, Vec);\nextern PetscErrorCode FormRHSFunction(TS, PetscReal, Vec, Vec, void*);\n\n//STARTMAIN\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 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 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(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//ENDCALLBACKS\n\n", "meta": {"hexsha": "3d18b802d2e7e8948818c8d7c061d38887deb3e0", "size": 2727, "ext": "c", "lang": "C", "max_stars_repo_path": "c/ch5/ode.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/ode.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/ode.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": 32.4642857143, "max_line_length": 76, "alphanum_fraction": 0.6508984232, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6020324526615664}} {"text": "/*\ncopied from http://www.gnu.org/software/gsl/manual/html_node/Basis-Splines.html\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid geterf_(double *xanderfx) {\n xanderfx[1] = gsl_sf_erf(xanderfx[0]);\n}\n\n//spline locations held fixed in Mpc^-1; CMB basically fixed P(k) in these units\nvoid dopksmoothbspline_(double *kvals, double *lnpklinear, double *lnpksmooth, int *npts) {\n\n\tdouble kmaxsuppress = 0.01*0.7;\n\tsize_t n, ncoeffs, nbreak;\n\tgsl_bspline_workspace *bw;\n\tgsl_vector *B;\n\tgsl_vector *c, *w, *x, *y;\n\tgsl_matrix *X, *cov;\n\tgsl_multifit_linear_workspace *mw;\n\tdouble deltak,lastk;\n\tint i,j,countkeep;\n\n\tnbreak = 9;\n\tgsl_vector *mybreaks = gsl_vector_alloc(nbreak);\n\tgsl_vector_set(mybreaks,0,(0.001*0.7));\n\tgsl_vector_set(mybreaks,1,(0.025*0.7));\n\tgsl_vector_set(mybreaks,2,(0.075*0.7));\n\tgsl_vector_set(mybreaks,3,(0.125*0.7));\n\tgsl_vector_set(mybreaks,4,(0.175*0.7));\n\tgsl_vector_set(mybreaks,5,(0.225*0.7));\n\tgsl_vector_set(mybreaks,6,(0.275*0.7));\n\tgsl_vector_set(mybreaks,7,(0.325*0.7));\n\tgsl_vector_set(mybreaks,8,(0.375*0.7));\n\n\tcountkeep = 0;\n\tfor(i=0;i<(*npts);i++) {\n\t\tif((kvals[i]) >= gsl_vector_get(mybreaks,0) && (kvals[i]) <= gsl_vector_get(mybreaks,nbreak-1)) {\n\t\t\tcountkeep += 1;\n\t\t\t}\n\t\t}\n\tn = countkeep;\n\tncoeffs = nbreak + 2;\n\n\t/* allocate a cubic bspline workspace (k = 4) */\n\tbw = gsl_bspline_alloc(4, nbreak);\n\tB = gsl_vector_alloc(ncoeffs); \n\tx = gsl_vector_alloc(n);\n\ty = gsl_vector_alloc(n);\n\tX = gsl_matrix_alloc(n, ncoeffs);\n\tc = gsl_vector_alloc(ncoeffs);\n\tw = gsl_vector_alloc(n);\n\tcov = gsl_matrix_alloc(ncoeffs, ncoeffs);\n\tmw = gsl_multifit_linear_alloc(n, ncoeffs);\n\ti=0;\n\tfor(j=0;j<(*npts);j++) {\n\t\tif((kvals[j]) >= gsl_vector_get(mybreaks,0) && (kvals[j]) <= gsl_vector_get(mybreaks,nbreak-1)) {\n\t\t\tgsl_vector_set(x,i,(kvals[j]));\n\t\t\tgsl_vector_set(y,i,exp(lnpklinear[j])*pow(kvals[j],1.5));\n\t\t\tif(j>0) {\n\t\t\t\tdeltak = kvals[j] - kvals[j-1];\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tdeltak = kvals[0];\n\t\t\t\tif(kvals[1] - kvals[0] < deltak) {\n\t\t\t\t\tdeltak = kvals[1]-kvals[0];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tgsl_vector_set(w,i,deltak);\n\t\t\ti+=1;\n\t\t\t}\n\t\t}\n\tgsl_bspline_knots(mybreaks,bw);\n\tfor(i=0;i= gsl_vector_get(mybreaks,0) && (kvals[j]) <= gsl_vector_get(mybreaks,nbreak-1)) {\n\t\t\tgsl_bspline_eval(gsl_vector_get(x,i),B,bw);\n\t\t\tgsl_multifit_linear_est(B,c,cov,&yi,&yierr);\n\t\t\tlnpksmooth[j] = log(yi*pow(kvals[j],-1.5));\n\t\t\ti += 1;\n\t\t\t}\n\t\telse {\n\t\t\tlnpksmooth[j] = lnpklinear[j];\n\t\t\t}\n\t\t//spline is wacky at small k -- suppress difference at k < 0.01\n\t\tif(kvals[j] < kmaxsuppress) {\n\t\t\tlnpksmooth[j] = lnpklinear[j];\n\t\t\t}\n\t\t}\n\tassert(i==n);\n\tgsl_bspline_free(bw);\n\tgsl_vector_free(B);\n\tgsl_vector_free(x);\n\tgsl_vector_free(y);\n\tgsl_vector_free(mybreaks);\n\tgsl_matrix_free(X);\n\tgsl_vector_free(c);\n\tgsl_vector_free(w);\n\tgsl_matrix_free(cov);\n\tgsl_multifit_linear_free(mw);\n\t}\n/*\n\nFILE *open_file_read(char *filename) {\n\tFILE *ifp;\n\n\tif(!(ifp=fopen(filename,\"r\"))) {\n\t\tfprintf(stderr,\"Can't open %s\\n\",filename);\n\t\treturn NULL;\n\t\t}\n\telse {\n\t\treturn ifp;\n\t\t}\n\t}\t\n\nint get_file_length(FILE *ifp, int *headercount, int *linecount) {\n\tint i;\n\tchar line[256];\n\t\n\t*headercount = 0;\n\t*linecount = 0;\n\t\t\t\n while(fgets(line,256,ifp)) {\n if(!feof(ifp)) {\n (*linecount)++;\n }\n\t\telse {\n\t\t\tbreak;\n\t\t\t}\n\t\tif(strstr(line,\"#\")) {\n\t\t\t(*headercount)++;\n\t\t\t}\n }\n\t(void) rewind(ifp);\n\t}\n\n\n\nint main() {\n\tdouble *lnpksmooth, *lnpklinear, *kvals;\n\tFILE *ifp;\n\tint headercount, linecount,i,j;\n\tdouble kval,pnw,plin;\n\tifp = open_file_read(\"/Users/breid/cosmomcmnu/test1.cut\");\n\tget_file_length(ifp,&headercount,&linecount);\n\tlnpksmooth = (double *) malloc(sizeof(double)*linecount);\n\tlnpklinear = (double *) malloc(sizeof(double)*linecount);\n\tkvals = (double *) malloc(sizeof(double)*linecount);\n\tfor(i=0;i\n#include \n\nint\nprint_gsl_sf_bessel_J0 (double x)\n{\n double y = gsl_sf_bessel_J0 (x);\n printf (\"J0(%g) = %.18e\\n\", x, y);\n return 0;\n}\n", "meta": {"hexsha": "6f2cda51f7e8302ab68c674f165db37779007c4f", "size": 198, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/simplecases/externaldeps/sources/gsl_dependent/example.c", "max_stars_repo_name": "Dwoosh/cBinder", "max_stars_repo_head_hexsha": "940e8c78eb9cf2eda1bc69427a6279b8b832bfe1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-22T20:05:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T21:18:47.000Z", "max_issues_repo_path": "tests/simplecases/externaldeps/sources/gsl_dependent/example.c", "max_issues_repo_name": "Tetrite/cBinder", "max_issues_repo_head_hexsha": "940e8c78eb9cf2eda1bc69427a6279b8b832bfe1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-24T09:09:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-18T11:12:46.000Z", "max_forks_repo_path": "tests/simplecases/externaldeps/sources/gsl_dependent/example.c", "max_forks_repo_name": "Dwoosh/cBinder", "max_forks_repo_head_hexsha": "940e8c78eb9cf2eda1bc69427a6279b8b832bfe1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5, "max_line_length": 36, "alphanum_fraction": 0.6565656566, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6015020438388089}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the instrumental noise for LISA-type detectors.\n *\n * Formulas taken from Królak&al gr-qc/0401108 (c.f. section III).\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"LISAnoise.h\"\n\n\n/* static double tflight_SI = L_SI/C_SI; */\n/* static double twopitflight_SI = 2.*PI*L_SI/C_SI; */\n\n/* Proof mass and optic noises - f in Hz */\n/* Taken from (4) in McWilliams&al_0911 */\nstatic double SpmLISA2010(const double f) {\n double invf2 = 1./(f*f);\n //return 2.5e-48 * invf2 * sqrt(1. + 1e-8*invf2);\n //const double Daccel=3.0e-15; //acceleration noise in m/s^2/sqrt(Hz)\n const double Daccel=3.0e-15; //scaled off L3LISA-v1 to for equal-SNR PE experiment\n const double SaccelFF=Daccel*Daccel/4.0/PI/PI/C_SI/C_SI; //f^-2 coeff for fractional-freq noise PSD from accel noise; yields 2.54e-48 from 3e-15;\n double invf8=invf2*invf2*invf2*invf2;\n //Here we add an eyeball approximation based on 4yrs integration with L3LISAReferenceMission looking at a private comm from Neil Cornish 2016.11.12\n double WDWDnoise=5000.0/sqrt(1e-21*invf8 + invf2 + 3e28/invf8)*SaccelFF*invf2;\n return SaccelFF * invf2 * sqrt(1. + 1e-8*invf2) + WDWDnoise;\n}\nstatic double SopLISA2010(const double f) {\n const double Dop=2.0e-11; //Optical path noise in m/rtHz (Standard LISA)\n const double SopFF=Dop*Dop*4.0*PI*PI/C_SI/C_SI; //f^2 coeff for OP frac-freq noise PSD. Yields 1.76e-37 for Dop=2e-11.\n return SopFF * f * f;\n}\n\n/* Proof mass and optical noises - f in Hz */\n/* L3 Reference Mission, from Petiteau LISA-CST-TN-0001 */\nstatic double SpmLISA2017(const double f) {\n double invf2 = 1./(f*f);\n //double invf4=invf2*invf2;\n //double invf8=invf4*invf4;\n //double invf10=invf8*invf2;\n const double twopi2=4.0*PI*PI;\n double ddtsq=twopi2/invf2; //time derivative factor\n const double C2=1.0*C_SI*C_SI; //veloc to doppler\n const double Daccel_white=3.0e-15; //acceleration noise in m/s^2/sqrt(Hz)\n const double Daccel_white2=Daccel_white*Daccel_white;\n const double Dloc=1.7e-12; //local IFO noise in m/sqrt(Hz)\n const double Dloc2=Dloc*Dloc;\n double Saccel_white=Daccel_white2/ddtsq; //PM vel noise PSD (white accel part)\n //double Saccel_red=Saccel_white*(1.0 + 2.12576e-44*invf10 + 3.6e-7*invf2); //reddening factor from Petiteau Eq 1\n double Saccel_red=Saccel_white*(1.0 + 36.0*(pow(3e-5/f,10) + 1e-8*invf2)); //reddening factor from Petiteau Eq 1\n //Saccel_red*=4.0;//Hack to decrease low-freq sens by fac of 2.\n double Sloc=Dloc2*ddtsq/4.0;//Factor of 1/4.0 is in Petiteau eq 2\n double S4yrWDWD=5.16e-27*exp(-pow(f,1.2)*2.9e3)*pow(f,(-7./3.))*0.5*(1.0 + tanh(-(f-2.0e-3)*1.9e3))*ddtsq;//Stas' fit for 4yr noise (converted from Sens curve to position noise by multipyling by 3*L^2/80) which looks comparable to my fit), then converted to velocity noise\n double Spm_vel = ( Saccel_red + Sloc + S4yrWDWD );\n return Spm_vel / C2;//finally convert from velocity noise to fractional-frequency doppler noise.\n}\nstatic double SopLISA2017(const double f) {\n //double invf2 = 1./(f*f);\n const double twopi2=4.0*PI*PI;\n double ddtsq=twopi2*f*f; //time derivative factor\n const double C2=C_SI*C_SI; //veloc to doppler\n const double Dloc=1.7e-12; //local IFO noise in m/sqrt(Hz)\n const double Dsci=8.9e-12; //science IFO noise in m/sqrt(Hz)\n const double Dmisc=2.0e-12; //misc. optical path noise in m/sqrt(Hz)\n const double Dop2=Dsci*Dsci+Dloc*Dloc+Dmisc*Dmisc;\n double Sop=Dop2*ddtsq/C2; //f^2 coeff for OP frac-freq noise PSD. Yields 1.76e-37 for Dop=2e-11.\n return Sop;\n}\n\n/* Proof mass and optical noises - f in Hz */\n/* LISA Proposal, copied from the LISA Data Challenge pipeline */\nstatic double SpmLISAProposal(const double f) {\n /* Acceleration noise */\n double noise_Sa_a = 9.e-30; /* m^2/sec^4 /Hz */\n /* In acceleration */\n double Sa_a = noise_Sa_a * (1.0 + pow(0.4e-3/f, 2)) * (1.0 + pow((f/8e-3), 4));\n /* In displacement */\n double Sa_d = Sa_a * pow(2.*PI*f, -4);\n /* In relative frequency unit */\n double Sa_nu = Sa_d * pow(2.*PI*f/C_SI, 2);\n double Spm = Sa_nu;\n return Spm;\n}\nstatic double SopLISAProposal(const double f) {\n /* Optical Metrology System noise */\n double noise_Soms_d = pow((10e-12), 2); /* m^2/Hz */\n /* In displacement */\n double Soms_d = noise_Soms_d * (1. + pow(2.e-3/f, 4));\n /* In relative frequency unit */\n double Soms_nu = Soms_d * pow(2.*PI*f/C_SI, 2);\n double Sop = Soms_nu;\n return Sop;\n}\n\n/* Compute proof mass and optical noises, for a given choice of noise - f in Hz */\nstatic void ComputeLISASpmSop(double* Spm, double* Sop, const double f, LISANoiseType noise) {\n if(noise==LISAProposalnoise) {\n *Spm = SpmLISAProposal(f);\n *Sop = SopLISAProposal(f);\n }\n else if(noise==LISA2017noise) {\n *Spm = SpmLISA2017(f);\n *Sop = SopLISA2017(f);\n }\n else if(noise==LISA2010noise) {\n *Spm = SpmLISA2010(f);\n *Sop = SopLISA2010(f);\n }\n else {\n printf(\"Error in ComputeLISASpmSop: LISANoiseType not recognized.\\n\");\n exit(1);\n }\n}\n\n/* Noise Sn for TDI observables - factors have been scaled out both in the response and the noise */\n/* Rescaled by 4*sin2pifL^2 */\ndouble SnXYZ(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 4*( 2*(1. + c2*c2)*Spm + Sop );\n}\n/* No rescaling */\ndouble Snalphabetagamma(const LISAconstellation *variant, double f) {\n double pifL = PI*variant->ConstL/C_SI*f;\n double s1 = sin(pifL);\n double s3 = sin(3*pifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*( (4*s3*s3 + 8*s1*s1)*Spm + 3*Sop );\n}\n/* Rescaled by 2*sin2pifL^2 */\ndouble SnAXYZ(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop;\n}\n/* Rescaled by 2*sin2pifL^2 */\ndouble SnEXYZ(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop;\n}\n/* Rescaled by 8*sin2pifL^2*sinpifL^2 */\ndouble SnTXYZ(const LISAconstellation *variant, double f) {\n double pifL = PI*variant->ConstL/C_SI*f;\n double s1 = sin(pifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 4*s1*s1*Spm + Sop;\n}\n/* Rescaled by 8*sin2pifL^2 */\ndouble SnAalphabetagamma(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop;\n}\n/* Rescaled by 8*sin2pifL^2 */\ndouble SnEalphabetagamma(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop;\n}\n/* Rescaled by sin3pifL^2/sinpifL^2 */\ndouble SnTalphabetagamma(const LISAconstellation *variant, double f) {\n double pifL = PI*variant->ConstL/C_SI*f;\n double s1 = sin(pifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 8*s1*s1*Spm + 2*Sop;\n}\n\n/* Noise functions for AET(XYZ) without rescaling */\n/* Scaling by 2*sin2pifL^2 put back */\ndouble SnAXYZNoRescaling(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double s2 = sin(twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*s2*s2 * (2*(3. + 2*c2 + c4)*SpmLISA2017(f) + (2 + c2)*SopLISA2017(f));\n}\n/* Scaling by 2*sin2pifL^2 put back */\ndouble SnEXYZNoRescaling(const LISAconstellation *variant, double f) {\n double twopifL = 2.*PI*variant->ConstL/C_SI*f;\n double c2 = cos(twopifL);\n double c4 = cos(2*twopifL);\n double s2 = sin(twopifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 2*s2*s2 * (2*(3. + 2*c2 + c4)*Spm + (2 + c2)*Sop);\n}\n/* Scaling by 8*sin2pifL^2*sinpifL^2 put back*/\ndouble SnTXYZNoRescaling(const LISAconstellation *variant, double f) {\n double pifL = PI*variant->ConstL/C_SI*f;\n double s1 = sin(pifL);\n double s2 = sin(2*pifL);\n double Spm = 0., Sop = 0.;\n ComputeLISASpmSop(&Spm, &Sop, f, variant->noise);\n return 8*s1*s1*s2*s2 * (4*s1*s1*Spm + Sop);\n}\n\n/* The noise functions themselves\n/* Note - we factored out and cancelled the factors of the type sin(n pi f L) */\n/* double NoiseSnA(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double cos1 = cos(twopifL); */\n/* double cos2 = cos(2*twopifL); */\n/* return 32*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */\n/* } */\n/* double NoiseSnE(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double cos1 = cos(twopifL); */\n/* double cos2 = cos(2*twopifL); */\n/* return 32*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */\n/* } */\n/* double NoiseSnT(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double sinhalf = sin(0.5*twopifL); */\n/* double cos1 = cos(twopifL); */\n/* return 8*( 4*sinhalf*sinhalf*Spm(f) + Sop(f) ); */\n/* } */\n\n/* Function returning the relevant noise function, given a set of TDI observables and a channel */\nObjectFunction NoiseFunction(const LISAconstellation *variant, const TDItag tditag, const int nchan)\n{\n ObjectFunction fn;\n switch(tditag) {\n case TDIXYZ:\n case TDIX: {\n switch(nchan) {\n case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break;\n case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break;\n case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnXYZ}; break;\n }\n break;\n }\n case TDIalphabetagamma:\n case TDIalpha: {\n switch(nchan) {\n case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break;\n case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break;\n case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)Snalphabetagamma}; break;\n }\n break;\n }\n case TDIAETXYZ:\n case TDIAXYZ:\n case TDIEXYZ:\n case TDITXYZ: {\n switch(nchan) {\n case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnAXYZ}; break;\n case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnEXYZ}; break;\n case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnTXYZ}; break;\n }\n break;\n }\n case TDIAETalphabetagamma:\n case TDIAalphabetagamma:\n case TDIEalphabetagamma:\n case TDITalphabetagamma: {\n switch(nchan) {\n case 1: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnAalphabetagamma}; break;\n case 2: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnEalphabetagamma}; break;\n case 3: fn = (ObjectFunction){variant,(RealObjectFunctionPtr)SnTalphabetagamma}; break;\n }\n break;\n }\n }\n if(fn.object==NULL) {\n printf(\"Error in NoiseFunction: incorrect argument.\\n\");\n exit(1);\n }\n return fn;\n}\n\n//Previous version - we had put a noise floor to mitigate cancellation lines\n/* double NoiseSnA(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double sinhalf = sin(0.5*twopifL); */\n/* double sin3half = sin(1.5*twopifL); */\n/* double cos1 = cos(twopifL); */\n/* double cos2 = cos(2*twopifL); */\n/* double res = 32*sinhalf*sinhalf*sin3half*sin3half*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */\n/* return fmax(res, 1e-46); */\n/* } */\n/* double NoiseSnE(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double sinhalf = sin(0.5*twopifL); */\n/* double sin3half = sin(1.5*twopifL); */\n/* double cos1 = cos(twopifL); */\n/* double cos2 = cos(2*twopifL); */\n/* double res = 32*sinhalf*sinhalf*sin3half*sin3half*( (6 + 4*cos1 + 2*cos2)*Spm(f) + (2 + cos1)*Sop(f) ); */\n/* return fmax(res, 1e-46); */\n/* } */\n/* double NoiseSnT(const double f) { */\n/* double twopifL = 2.*PI*L_SI/C_SI*f; */\n/* double sinhalf = sin(0.5*twopifL); */\n/* double sin3half = sin(1.5*twopifL); */\n/* double cos1 = cos(twopifL); */\n/* double res = 8*(1+2*cos1)*(1+2*cos1)*sin3half*sin3half*( 4*sinhalf*sinhalf*Spm(f) + Sop(f) ); */\n/* return fmax(res, 1e-46); */\n/* } */\n", "meta": {"hexsha": "bc07363d54781f152ebcc8bbe147522423de7f15", "size": 13143, "ext": "c", "lang": "C", "max_stars_repo_path": "LISAsim/LISAnoise.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "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": "LISAsim/LISAnoise.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAsim/LISAnoise.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "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": 37.9855491329, "max_line_length": 274, "alphanum_fraction": 0.6677318725, "num_tokens": 4839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6015020302864345}} {"text": "/* dwt_undec.c\n * Paul Demorest, 2007/10\n *\n * Undecimated wavelet transform and inverse. These\n * do the usual wavelet filter tree, but don't decimate\n * by 2 after each step. This makes the transform \n * translation-invariant (to translations which are \n * integer numbers of samples anyways).\n *\n * Ends up with n*log2(n) sized array, from size n input.\n *\n * Wavelet coeffs g and h need to be externally supplied.\n */\n#include \n#include \n#include \n#include \n\n/* Do one UDWT step on input data, out-of-place (original \n * data array is unaltered).\n * Vars:\n * in pointer to input data (n doubles)\n * outl pointer to low-pass output data (n doubles)\n * outh pointer to high-pass output data (n doubles)\n * n size of in/out\n * h Wavelet coeffs, low-pass (nc doubles)\n * g Wavelet coeffs, high-pass (nc doubles)\n * nc size of h/g\n * s scale (filters expand by 2^s)\n */\nvoid udwt_forward_step(double *in, double *outl, double *outh, size_t n, \n const double h[], const double g[], size_t nc, int s) {\n\n int i,j,idx;\n\n /* Zero output array */\n for (i=0; i>rv)>1) { rv++; }\n return(rv);\n}\n\n/* Do a undec wavelet transform on input data n.\n * Vars:\n * in pointer to input data (n doubles)\n * out pointer to output data (n*log2(n) doubles)\n * n size of in\n * h Wavelet coeffs, high-pass (nc doubles)\n * g Wavelet coeffs, low-pass (nc doubles)\n * nc size of h/g\n *\n * This can be called using a GSL wavelet definition struct like:\n * gsl_wavelet *w;\n * (etc, init wavelet...)\n * dwt_undec_transform(in, &out, n, w->h1, w->g1, w->nc);\n */\nint _dwt_undec_transform(double *in, double *out, size_t n, \n const double h[], const double g[], size_t nc) {\n\n /* Determine number of levels of decomp */\n int nl=0;\n nl = log2i(n);\n\n /* maybe do some value checks on n, nl .. */\n\n /* Temporary low-pass outputs */\n double *tmp1 = (double *)malloc(sizeof(double)*n);\n double *tmp2 = (double *)malloc(sizeof(double)*n);\n\n /* Loop to do dwts */\n int i;\n double *curi, *curol, *curoh, *swp;\n curi = in;\n curol = tmp1;\n curoh = out;\n for (i=0; ih2, w->g2, w->nc);\n */\nint _dwt_undec_inverse(double *in, double *out, size_t n, \n const double h[], const double g[], size_t nc) {\n\n /* Determine number of levels of decomp */\n int nl=0;\n nl = log2i(n);\n\n /* maybe do some value checks on n, nl .. */\n\n /* Temporary low-pass outputs */\n int i;\n double *tmp1 = (double *)malloc(sizeof(double)*n);\n double *tmp2 = (double *)malloc(sizeof(double)*n);\n for (i=0; i=0; i--) {\n udwt_inverse_step(curil, curih, curo, n, h, g, nc, i);\n swp = curil;\n curil = curo;\n curo = swp;\n curih = &in[(i-1)*n];\n }\n\n /* We end up with final output in curil */\n for (i=0; ih1, w->g1, w->nc);\n}\nint dwt_undec_inverse(double *in, double *out, size_t n, const gsl_wavelet *w) {\n return _dwt_undec_inverse(in, out, n, w->h2, w->g2, w->nc);\n}\n\n", "meta": {"hexsha": "39601933d7f8a82cbe845f79879c52e03d38a6ce", "size": 4943, "ext": "c", "lang": "C", "max_stars_repo_path": "Util/genutil/dwt_undec.c", "max_stars_repo_name": "xuanyuanstar/psrchive_CDFT", "max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_stars_repo_licenses": ["AFL-2.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Util/genutil/dwt_undec.c", "max_issues_repo_name": "xuanyuanstar/psrchive_CDFT", "max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_issues_repo_licenses": ["AFL-2.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Util/genutil/dwt_undec.c", "max_forks_repo_name": "xuanyuanstar/psrchive_CDFT", "max_forks_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35", "max_forks_repo_licenses": ["AFL-2.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4611111111, "max_line_length": 82, "alphanum_fraction": 0.5688852923, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6012611500703035}} {"text": "#include \n#include \n#include \n#include \n#include \n#ifdef ENABLE_GSL\n#include \n#include \n#include \n\n#endif\n\n#ifndef PI\n#define PI 3.141593\n#endif\n\n#ifndef Grav\n#define Grav 4.7788e-20 // Newton's over c^2 in Mpc / Msun\n#endif\n\n#ifndef lightspeed\n#define lightspeed 2.99792458e5 // km / s\n#endif\n\n#ifndef error_message\n#define error_message\n#define ERROR_MESSAGE() std::cerr << \"ERROR: file: \" << __FILE__ << \" line: \" << __LINE__ << std::endl;\n#endif\n\n#define CRITD 2.49783e18 /* critical density / Ho^2 solar/Mpc */\n#define CRITD2 2.7752543e11 /* critical density / h^2 M_sun/Mpc^3 */\n\n#ifndef cosmo_declare\n\nenum CosmoParamSet {WMAP5yr,Millennium,Planck1yr,Planck15,Planck18,BigMultiDark,none};\n\nstd::ostream &operator<<(std::ostream &os, CosmoParamSet p);\n\n/**\n *\n * \\brief The cosmology and all the functions required to calculated quantities based on the cosmology.\n *\n * This class is used to store the cosmological parameters, calculate cosmological distances, calculate\n * the power spectrum of density fluctuations and the mass function of halos.\n *\n * As set now, there are no baryon acoustic oscillations in the power spectrum, but this can be changed\n * at the expense of not including neutrinos.\n */\nclass COSMOLOGY{\npublic:\n \n COSMOLOGY(CosmoParamSet cosmo_p = WMAP5yr);\n /// if justdistances== true\n COSMOLOGY(double omegam,double omegal,double h, double w = -1,double wa = 0\n ,bool justdistances=false /// if true the internals needed calculate structure formation will not be calculated making constructuion faster\n );\n COSMOLOGY(const COSMOLOGY &cosmo);\n ~COSMOLOGY();\n \n COSMOLOGY& operator=(const COSMOLOGY &cosmo);\n \n // returns the parameter set if any\n CosmoParamSet ParamSet(){return cosmo_set;}\n \n void PrintCosmology(short physical = 0) const;\n std::string print(short physical= 0) const;\n \n // Lengths\n double rcurve() const;\n //double emptyDist(double zo,double z);\n double coorDist(double zo,double z) const;\n double coorDist(double z) const {return coorDist(0,z);}\n double radDist(double zo,double z) const;\n double radDist(double z) const {return radDist(0,z);}\n double angDist(double zo,double z) const;\n double angDist(double z) const {return angDist(0,z);}\n double lumDist(double zo,double z) const;\n double lumDist(double z) const {return lumDist(0,z);}\n \n /// derivative of coordinate distance with respect to Omo in flat cosmology. Useful for Fisher matrix calculations\n double d_coorDist_dOmo(double zo,double z) const;\n /// derivative of coordinate distance with respect to w. Useful for Fisher matrix calculations\n double d_coorDist_dw(double zo,double z) const;\n /// derivative of coordinate distance with respect to w1. Useful for Fisher matrix calculations\n double d_coorDist_dw1(double zo,double z) const;\n \n double DRradius(double zo,double z,double pfrac);\n double DRradius2(double zo,double z);\n \n double invCoorDist(double d) const;\n double invRadDist(double d) const;\n double invComovingDist(double d) const;\n \n double scalefactor(double rad) const;\n double Omegam(double z) const;\n double rho_crit_comoving(double z) const;\n //double drdz_empty(double x);\n double drdz(double x) const;\n //double adrdz(double x) const;\n double drdz_dark(double x) const;\n inline double dark_factor(double x) const;\n //double adrdz_dark(double x) const;\n \n /// the critical over density\n double delta_c() const;\n \n double DeltaVir(double z,int caseunit=0) const;\n double Deltao(double m) const;\n double time(double z) const;\n double nonlinMass(double z) const;\n\n // Stuff having to do with the power spectrum\n double power_normalize(double sigma8);\n /**\n * \\brief Linear power spectrum P(k,z)/a^2\n */\n double power_linear(double k,double z);\n double Dgrowth(double z) const;\n \n /** \n * \\brief powerCDM.c calculates the nonlinear P(k,z)/a(r)^2\n *\n * The method of Peacock & Dodds 1996 is used to convert the linear\n * power spectrum into the nonlinear one.\n * This could be updated to a more recent nonlinear power spectrum\n */\n double powerCDMz(double k,double z);\n double psdfdm(double z,double m,int caseunit=0);\n double halo_bias (double m, double z, int t=0);\n double stdfdm(double z,double m,int caseunit=0);\n double powerlawdfdm(double z,double m,double alpha,int caseunit=0);\n double haloNumberDensity(double m,double z,double a, int t,double alpha = 0.0);\n \n /** \\brief Dark matter correlation function \n *\n * This integrates powerCDMz() to get the correlation function as a function of comoving radius.\n * Care should be taken that the right range of k is integrated over if the radius is very small or large.\n */\n double CorrelationFunction(double radius,double redshift\n ,double k_max = 100,double k_min = 1.0e-3);\n\n struct CorrFunctorType{\n CorrFunctorType(COSMOLOGY *cosmo,double radius,double redshift)\n : cosmology(cosmo),z(redshift),r(radius)\n {\n norm = 0.5/PI/PI/(1+z)/(1+z);\n };\n \n COSMOLOGY *cosmology;\n double z;\n double r;\n \n double norm;\n \n double operator () (double k) {\n \n double rk = r*k;\n double jo = sin(rk)/rk;\n if(rk < 1.0e-3) jo = 1.0;\n \n return norm*jo*k*k*cosmology->powerCDMz(k,z);\n }\n };\n\n \n double haloNumberDensityOnSky (double m,double z1,double z2,int t,double alpha = 0.0);\n double haloNumberInBufferedCone (double mass ,double z1,double z2,double fov,double buffer ,int type ,double alpha=0.0);\n double haloMassInBufferedCone (double mass ,double z1,double z2,double fov,double buffer ,int type ,double alpha=0.0);\n \n double TopHatVariance(double m) const;\n double TopHatVarianceR(double R,double z);\n double TopHatVarianceM(double M,double z);\n //double gradius(double R,double rd);\n \n double getTimefromDeltaC(double dc);\n double getZfromDeltaC(double dc);\n \n /// accesser functions:\n \n /// Hubble paremters in units of 100 km/s/Mpc, renormalizes P(k) to keep sig8 fixed\n void sethubble(double ht){ h = ht; TFmdm_set_cosm();\n power_normalize(sig8); \tcalc_interp_dist(); cosmo_set = none;}\n double gethubble() const {return h;}\n /// Hubble parameter in 1/Mpc units\n double getHubble() const {return 100*h/lightspeed;}\n \n /// Primordial spectral index, renormalizes P(k) to keep sig8 fixed\n void setindex(double nn){ n = nn; power_normalize(sig8); cosmo_set = none;}\n double getindex() const { return n;}\n \n /// Omega matter, renormalizes P(k) to keep sig8 fixed\n void setOmega_matter(double Omega_matter,bool FLAT = false){Omo = Omega_matter; if(FLAT) Oml = 1-Omo ; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;}\n double getOmega_matter() const {return Omo;}\n \n /// Omega lambda, renormalizes P(k) to keep sig8 fixed\n void setOmega_lambda(double Omega_lambda,bool FLAT = false){Oml = Omega_lambda; if(FLAT) Oml = 1-Omo ; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;}\n double getOmega_lambda() const {return Oml;}\n \n /// Omega baryon, renormalizes P(k) to keep sig8 fixed\n void setOmega_baryon(double Omega_baryon){Omb = Omega_baryon; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;\n }\n double getOmega_baryon() const {return Omb;}\n \n /// Omega neutrino, renormalizes P(k) to keep sig8 fixed\n void setOmega_neutrino(double Omega_neutrino){Omnu = Omega_neutrino; TFmdm_set_cosm(); power_normalize(sig8); \tcalc_interp_dist(); cosmo_set = none;\n }\n double getOmega_neutrino() const {return Omnu;}\n \n /// Number of neutrino species, renormalizes P(k) to keep sig8 fixed\n void setNneutrino(double Nneutrino){Nnu = Nneutrino; TFmdm_set_cosm(); power_normalize(sig8); cosmo_set = none;}\n double getNneutrino() const {return Nnu;}\n \n /// Dark energy equation of state parameter p/rho = w + w_1 (1+z)\n void setW(double w){ww = w; \tcalc_interp_dist(); cosmo_set = none;}\n double getW() const {return ww;}\n void setW1(double w){ww1 = w; \tcalc_interp_dist(); cosmo_set = none;}\n double getW1() const {return ww1;}\n \n /// Running of primordial spectral index, P(k)_primordial \\propto pow(k/h,n+dndlnk*log(k)), renormalizes P(k) to keep sig8 fixed\n void setdndlnk(double w){dndlnk = w; power_normalize(sig8); cosmo_set = none;}\n double getdndlnk() const {return dndlnk;}\n \n /// Alternative to w for dark energy/ alt. grav. structure evolution\n void setgamma(double gamm){gamma = gamm; cosmo_set = none;}\n double getgamma() const {return gamma;}\n // If physical = 1 all Omega are Omega*h^2 otherwise they have the usual definitions.\n // 2 gamma parameterization is used for dark energy\n void setDEtype(short tt){darkenergy = tt; cosmo_set = none;}\n short getDEtype() const {return darkenergy;}\n \n void setSigma8(double my_sig8){power_normalize(my_sig8); cosmo_set = none;}\n double getSigma8() const {return sig8;}\n \n \n void dzdangDist(double D,double z[],double dzdD[]);\n \n double totalMassDensityinHalos(int t,double alpha,double m_min,double z,double z1,double z2);\n \n /// set interpolation range and number of points\n void setInterpolation(double z_interp, std::size_t n_interp);\n \n /// The lensing critical density in Msun / Mpc^2\n double SigmaCrit(double zlens,double zsource) const;\n \nprotected:\n void SetConcordenceCosmology(CosmoParamSet cosmo_p);\n \n CosmoParamSet cosmo_set;\n \n // structure rappers to make integration thread safe\n struct drdz_struct{\n drdz_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.drdz(x);}\n COSMOLOGY const &cos;\n };\n struct drdzdark_struct{\n drdzdark_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.drdz_dark(x);}\n COSMOLOGY const &cos;\n };\n struct adrdz_struct{\n adrdz_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.drdz(x)/x;}\n COSMOLOGY const &cos;\n };\n struct adrdzdark_struct{\n adrdzdark_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.drdz_dark(x)/x;}\n COSMOLOGY const &cos;\n };\n\n struct normL_struct{\n normL_struct(COSMOLOGY &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.normL(x);}\n COSMOLOGY &cos;\n };\n\n double ddrdzdOmo(double x) const;\n double ddrdzdw(double x) const;\n double ddrdzdw1(double x) const;\n \n struct ddrdzdOmo_struct{\n ddrdzdOmo_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.ddrdzdOmo(x);}\n COSMOLOGY const &cos;\n };\n struct ddrdzdw_struct{\n ddrdzdw_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.ddrdzdw(x);}\n COSMOLOGY const &cos;\n };\n struct ddrdzdw1_struct{\n ddrdzdw1_struct(COSMOLOGY const &cosmo):cos(cosmo){};\n double operator()(double x) const {return cos.ddrdzdw1(x);}\n COSMOLOGY const &cos;\n };\n\n bool init_structure_functions;\n \n /// Hubble paremters in units of 100 km/s/Mpc\n double h;\n /// Primordial spectral index\n double n;\n /// Omega matter, dark matter + baryons\n double Omo;\n /// Omega lambda\n double Oml;\n /// Omega baryon\n double Omb;\n /// Omega neutrino\n double Omnu;\n /// Number of neutrino species\n double Nnu;\n /// Dark energy equation of state parameter p/rho = ww + ww_1 (1+z)\n double ww;\n /// Dark energy equation of state parameter p/rho = ww + ww_1 (1+z)\n double ww1;\n /// Running of primordial spectral index, P(k)_primordial \\propto pow(k/h,n+dndlnk*log(k))\n double dndlnk;\n \n /// Alternative to w for dark energy/ alt. grav. structure evolution\n double gamma;\n // If physical = 1 all Omega are Omega*h^2 otherwise they have the usual definitions.\n //short physical;\n // 2 gamma parameterization is used for dark energy\n short darkenergy;\n \n /* table for growth parameter */\n //std::auto_ptr *aa;\n //std::auto_ptr *growth;\n //int Ntable;\n \n double A;\n double sig8; /* do not access these normalization outside */\n \n double Rtophat;\n double ztmp;\n \n double powerEH(double k,double z);\n double powerEHv2(double k);\n double powerloc(double k,double z);\n double npow(double k);\n double normL(double lgk);\n double gradius(double R,double rd) const;\n \n int nbin; // number of points when binning to interpolate\n std:: vector vDeltaCz,vlz,vt;\n double DpropDz(double z);\n double dsigdM(double m);\n double timeEarly(double a) const;\n double dNdz(double z);\n \n typedef double (COSMOLOGY::*pt2MemFunc)(double) const;\n typedef double (COSMOLOGY::*pt2MemFuncNonConst)(double);\n \n double nintegrateDcos(pt2MemFunc func,double a,double b,double tols) const;\n double trapzdDcoslocal(pt2MemFunc func, double a, double b, int n, double *s2) const;\n void polintD(double xa[], double ya[], int n, double x, double *y, double *dy) const;\n double nintegrateDcos(pt2MemFuncNonConst func,double a,double b,double tols);\n double trapzdDcoslocal(pt2MemFuncNonConst func, double a, double b, int n, double *s2);\n double dfridrDcos(pt2MemFunc func, double x, double h, double *err);\n double f4(double u) const;\n \n int ni;\n std::vector xf, wf;\n \n // The parameters used in Eisenstein & Hu power spectrum\n /* in powerEH.c */\n short TFmdm_set_cosm_change_z(double redshift);\n short TFmdm_set_cosm();\n double TFmdm_onek_mpc(double kk);\n double TFmdm_onek_hmpc(double kk);\n \n double f_baryon;\t// Baryon fraction\n double f_bnu;\t\t// Baryon + Massive Neutrino fraction\n double f_cb;\t\t// Baryon + CDM fraction\n double f_cdm;\t\t// CDM fraction\n double f_hdm;\t\t// Massive Neutrino fraction\n \n double alpha_gamma;\t // sqrt(alpha_nu)\n double alpha_nu;\t // The small-scale suppression\n double beta_c;\t\t // The correction to the log in the small-scale\n double num_degen_hdm;\t // Number of degenerate massive neutrino species\n double growth_k0;\t // D_1(z) -- the growth function as k->0\n double growth_to_z0;\t // D_1(z)/D_1(0) -- the growth relative to z=0\n double k_equality;\t // The comoving wave number of the horizon at equality\n double obhh;\t\t // Omega_baryon * hubble^2\n double omega_curv;\t // = 1 - omega_matter - omega_lambda\n double omega_lambda_z; // Omega_lambda at the given redshift\n double omega_matter_z; // Omega_matter at the given redshift\n double omhh;\t\t // Omega_matter * hubble^2\n double onhh;\t\t // Omega_hdm * hubble^2\n double p_c;\t\t // The correction to the exponent before drag epoch\n double p_cb;\t\t // The correction to the exponent after drag epoch\n double sound_horizon_fit; // The sound horizon at the drag epoch\n double theta_cmb;\t // The temperature of the CMB, in units of 2.7 K\n double y_drag;\t\t // Ratio of z_equality to z_drag\n double z_drag;\t\t // Redshift of the drag epoch\n double z_equality;\t // Redshift of matter-radiation equality\n \n void setinternals();\n // in powerEHv2.c\n void TFset_parameters(double omega0hh, double f_baryon, double Tcmb);\n double TFfit_onek(double k, double *tf_baryon, double *tf_cdm);\n \n double R_drag;\t\t// Photon-baryon ratio at drag epoch\n double R_equality;\t// Photon-baryon ratio at equality epoch\n double sound_horizon;\t// Sound horizon at drag epoch, in Mpc\n double k_silk;\t\t// Silk damping scale, in Mpc^-1\n double alpha_c;\t // CDM suppression\n double alpha_b;\t // Baryon suppression\n double beta_b;\t\t// Baryon envelope shift\n double beta_node;\t// Sound horizon shift\n double k_peak;\t\t// Fit to wavenumber of first peak, in Mpc^-1\n \n // temporary variables for doing interations\n int tmp_type;\n double tmp_alpha;\n double tmp_mass;\n double tmp_a;\n \n // interpolation of functions\n double z_interp;\n std::size_t n_interp;\n void calc_interp_dist();\n double interp(const std::vector& table, double z) const;\n double invert(const std::vector& table, double f_z) const;\n std::vector redshift_interp;\n std::vector coorDist_interp;\n std::vector radDist_interp;\n};\n\ntypedef COSMOLOGY *CosmoHndl;\n/**\n * \\brief Class for calculating properties of NFW halo profile.\n *\n * This class does not take into affect the cosmological correlation between concentration and mass.\n * For this see the HALOCalculator class.\n */\nclass NFW_Utility {\npublic:\n NFW_Utility(){return;}\n ~NFW_Utility(){};\n \n // methods for NFW profile\n double NFW_V200(double M200,double R200);\n double NFW_Vmax(double cons,double M200,double R200);\n double NFW_Vr(double x,double cons,double M200,double R200);\n double NFW_M(double x,double cons,double M200);\n double NFW_deltac(double cons);\n double NFW_Concentration(double Vmax,double M200,double R200);\n double NFW_rho(double cons,double x);\n \n void match_nfw(float Vmax,float R_half,float mass,float *cons,float *Rsize);\n float Rsize(float cons,float Vmax,float mass);\n float g_func(float x);\n \nprivate:\n float Vmax,R_half,mass; /// Mass (solar masses)\n \n typedef float (NFW_Utility::*MemFunc)(float);\n float zbrentD(MemFunc func, float a,float b,float tols);\n float nfwfunc(float cons);\n float funcforconcentration(float cons);\n};\n\n\n/// wrapper functions for gsl integration / differentiation\ndouble drdz_wrapper(double x, void *params);\ndouble drdz_dark_wrapper(double x, void *params);\ndouble Deltao_wrapper(double m, void *params);\n\n#define cosmo_declare\n#endif\n\n/*** in cosmo.c ***/\nint cosmo_compare(CosmoHndl cos1,CosmoHndl cos2);\nvoid cosmo_copy(CosmoHndl cos1,CosmoHndl cos2);\nvoid ders(double z,double Da[],double dDdz[]);\nvoid dir(double r,double a[],double dadr[]);\ndouble arctanh(double x);\ndouble fmini(double a,double b);\ndouble fmaxi(double a,double b);\ndouble **dmatrixcos(long nrl, long nrh, long ncl, long nch);\nvoid free_dmatrixcos(double **m, long nrl, long nrh, long ncl, long nch);\n\n/* in nfw.c */\n\n/* in powerEHv2.c */\nvoid TFset_parameters(double omega0hh, double f_baryon, double Tcmb);\ndouble TFfit_onek(double k, double *tf_baryon, double *tf_cdm);\n", "meta": {"hexsha": "ae5b28e83eda546bd526c2e368bb8d7edcc02157", "size": 18020, "ext": "h", "lang": "C", "max_stars_repo_path": "include/cosmo.h", "max_stars_repo_name": "glenco/CosmoLib", "max_stars_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "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/cosmo.h", "max_issues_repo_name": "glenco/CosmoLib", "max_issues_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-29T10:22:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-29T10:27:21.000Z", "max_forks_repo_path": "include/cosmo.h", "max_forks_repo_name": "glenco/CosmoLib", "max_forks_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6260162602, "max_line_length": 185, "alphanum_fraction": 0.7162042175, "num_tokens": 5140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.600545362617123}} {"text": "#include \n#include \n#include \"mf.h\"\n#include \n\n//****************************the functions are listed below**********\ndouble func1 (double y, double T) //The self-consistent equation f(y)=0\n{\n\tdouble res = tanh(3*y/T)-y;\n\treturn res;\n}\ndouble func2 (double y, double T) //The free energy per site\n{\n\tdouble res = 0.5*3*y*y-T*log(2*cosh(3*y)/T);\n\treturn res;\n}\n//*****************************************************************************\nint main()\n{\n\tFILE *fp;\n\tint anyi;\n\tif((fp=fopen(filename,\"w\"))==NULL)\n\t{\n\t\tprintf(\"cannot open the file: %s\\n\",filename);\n\t\tprintf(\"Please input an integer to end the program:\");\n\t\tscanf(\"%d\",&anyi);\n\t\treturn 0;\n\t}\n\n\tFILE *ffp;\n\tif((ffp=fopen(filename2,\"w\"))==NULL)\n\t{\n\t\tprintf(\"cannot open the file: %s\\n\",filename2);\n\t\tprintf(\"Please input an integer to end the program:\");\n\t\tscanf(\"%d\",&anyi);\n\t\treturn 0;\n\t}\n\n\tdouble tem0; //judge indicator\t\n\tdouble T_step; //the step of Temperature\n\tT_step = (T_high-T_low)/(N_T-1); //note N_T is the tatal points of T\n//\tprintf(\"The temperature step is %lf\\n\",T_step);\n\n\n\tdouble y_1;\n\tdouble y_2;\n\n\tdouble tem_1;\n\tdouble tem_2;\n\n\tdouble T = T_low;\n\n\tint i,j; //loop indicator\n\tfor(i=0;i0)\n\t\tif(tem_1*tem_2>0)\n\t\t{\n\t\t\tprintf(\"The two points in the boundary isn't good! Give up them now. Do it, baby!\\n\");\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t//******************************************\n\t\t\n\t\tfor(j=10;j>1;j++)\n\t\t{\n\t\t\ttem_1 = func1(y_1, T);\n\t\t\ttem_2 = func1(y_2, T);\n\t\t\ttem0 = func1((y_1+y_2)/2.,T);\n\t\t//\tprintf(\"tem_1:%lf\\ttem_2:%lf\\n\",tem_1,tem_2);\n\t\t\tif((tem_1=0)||(tem_1>-precision&&tem_1<=0))\n\t\t\t{\n\t\t\t\tfprintf(fp,\"%lf\\t%lf\\n\",T,y_1);\n\t\t\t\tfprintf(ffp,\"%lf\\t%lf\\t%lf\\n\",T,func2(y_1,T),func2(-y_1,T));\n\t\t\t\tj=0;\n\t\t\t}\n\t\t\tif((tem_2=0)||(tem_2>-precision&&tem_2<=0))\n\t\t\t{\n\t\t\t\tfprintf(fp,\"%lf\\t%lf\\n\",T,y_2);\n\t\t\t\tfprintf(ffp,\"%lf\\t%lf\\t%lf\\n\",T,func2(y_2,T),func2(-y_2,T));\n\t\t\t\tj=0;\n\t\t\t}\n\t\t\tif(tem_1*tem0>0)\n\t\t\t{\n\t\t\t\ty_1 = (y_1+y_2)/2;\n\t\t\t}\n\t\t\tif(tem_2*tem0>0)\n\t\t\t{\n\t\t\t\ty_2 = (y_1+y_2)/2;\n\t\t\t}\n\t\t\tprintf(\"%lf\\n\",(y_1+y_2)/2); //the mediate point value\n\n\t\t}\n\t}\n\treturn 1;\n}\n", "meta": {"hexsha": "7d96771b9a332defd4200e442c4daa3d75ff192a", "size": 2274, "ext": "c", "lang": "C", "max_stars_repo_path": "q1/1_mean-field/m-eq/mf.c", "max_stars_repo_name": "PostQuantum/Buckyball-Ising-Model", "max_stars_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T01:23:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T03:00:21.000Z", "max_issues_repo_path": "q1/1_mean-field/m-eq/mf.c", "max_issues_repo_name": "PostQuantum/Buckyball-Ising-Model", "max_issues_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635", "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": "q1/1_mean-field/m-eq/mf.c", "max_forks_repo_name": "PostQuantum/Buckyball-Ising-Model", "max_forks_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T23:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T13:02:13.000Z", "avg_line_length": 22.0776699029, "max_line_length": 89, "alphanum_fraction": 0.5466138962, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6004206473212267}} {"text": "//\n// gemm.h\n// Linear Algebra Template Library\n//\n// Created by Rodney James on 1/30/12.\n// Copyright (c) 2012 University of Colorado Denver. All rights reserved.\n//\n\n#ifndef _gemm_h\n#define _gemm_h\n\n/// @file gemm.h Computes general matrix-matrix products.\n\n#include \n#include \"latl.h\"\n\nnamespace LATL\n{\n /// @brief Computes products of real matrices.\n ///\n /// For real matrices A,B,C and real scalars alpha, beta\n ///\n /// C := alpha * op(A) * op(B) + beta * C\n ///\n /// is calculated, where op(X) = X or X'.\n /// @return 0 if success.\n /// @return -i if the ith argument is invalid.\n /// @tparam real_t Floating point type.\n /// @param transA Specifies whether op(A)=A or A' as follows:\n ///\n /// if transA = 'N' or 'n' then op(A)=A\n /// if transA = 'T' or 't' then op(A)=A'\n /// if transA = 'C' or 'c' then op(A)=A'\n ///\n /// @param transB Specifies whether op(B)=B or B' as follows:\n ///\n /// if transB = 'N' or 'n' then op(B)=B\n /// if transB = 'T' or 't' then op(B)=B'\n /// if transB = 'C' or 'c' then op(B)=B'\n ///\n /// @param m The number of rows of the matrices C and op(A). m>=0\n /// @param n The number of columns of the matrices C and op(B). n>=0\n /// @param k The number of columns of the matrix op(A), and the number of rows of the matrix op(B). k>=0\n /// @param alpha Real scalar.\n /// @param A Pointer to real matrix A, where op(A) is m-by-k.\n /// @param ldA Column length of the matrix A. If transA='N' or 'n', ldA>=m; otherwise, ldA>=k.\n /// @param B Pointer to real matrix B, where op(B) is k-by-n.\n /// @param ldB Column length of the matrix B. If transB='N' or 'n', ldB>=k; otherwise, ldA>=n.\n /// @param beta Real scalar.\n /// @param C Pointer to real matrix C, where C is m-by-n.\n /// @param ldC Column length of the matrix C. ldC>=m.\n /// @ingroup BLAS\n \n template\n int GEMM(char transA, char transB, int_t m, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC)\n {\n using std::toupper;\n const real_t zero(0.0);\n const real_t one(1.0);\n int_t i,j,l;\n real_t s,t;\n real_t *a,*b,*c;\n \n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC=0\n /// @param n The number of columns of the matrices C and op(B). n>=0\n /// @param k The number of columns of the matrix op(A), and the number of rows of the matrix op(B). k>=0\n /// @param alpha Complex scalar.\n /// @param A Pointer to complex matrix A, where op(A) is m-by-k.\n /// @param ldA Column length of the matrix A. If transA='N' or 'n', ldA>=m; otherwise, ldA>=k.\n /// @param B Pointer to complex matrix B, where op(B) is k-by-n.\n /// @param ldB Column length of the matrix B. If transB='N' or 'n', ldB>=k; otherwise, ldA>=n.\n /// @param beta Complex scalar.\n /// @param C Pointer to complex matrix C, where C is m-by-n.\n /// @param ldC Column length of the matrix C. ldC>=m.\n /// @ingroup BLAS\n \n template\n int GEMM(char transA, char transB, int_t m, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n using std::conj;\n using std::toupper;\n const complex zero(0.0,0.0);\n const complex one(1.0,0.0);\n int_t i,j,l;\n complex *a,*b,*c;\n complex s,t;\n \n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC\n \n template<> int GEMM(char transA, char transB, int_t m, int_t n, int_t k, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC)\n {\n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC int GEMM(char transA, char transB, int_t m, int_t n, int_t k, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC)\n {\n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC int GEMM(char transA, char transB, int_t m, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC int GEMM(char transA, char transB, int_t m, int_t n, int_t k, complex alpha, complex *A, int_t ldA, complex *B, int_t ldB, complex beta, complex *C, int_t ldC)\n {\n transA=toupper(transA);\n transB=toupper(transB);\n \n if((transA!='N')&&(transA!='T')&&(transA!='C'))\n return -1;\n else if((transB!='N')&&(transB!='T')&&(transB!='C'))\n return -2;\n else if(m<0)\n return -3;\n else if(n<0)\n return -4;\n else if(k<0)\n return -5;\n else if(ldA<((transA!='N')?k:m))\n return -8;\n else if(ldB<((transB!='N')?n:k))\n return -10;\n else if(ldC