File size: 12,996 Bytes
803451e
 
1
2
3
{"text": "#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n\n#include \"design.h\"\n\n/*This function computes the p-distance between 2 points in D dimensions:\nthe exponent p is tunable*/\n\ndouble distance(double *x,double *y,int D,double p){\n\n\tdouble dist = 0.0;\n\tint i;\n\n\tfor(i=0;i<D;i++){\n\t\tdist += pow(fabs(x[i]-y[i]),p);\n\t}\n\n\treturn pow(dist,1.0/p);\n\n}\n\n/*This is the cost function of the problem: it is a sum of all the reciprocal of \nthe pairs distances, with some tunable exponent lambda; note that the final\n1/lambda exponentiation is not performed here!*/\n\ndouble cost(gsl_matrix *data,int Npoints,int D,double p,double lambda){\n\n\tdouble sum = 0.0;\n\tint i,j;\n\n\tfor(i=0;i<Npoints;i++){\n\t\tfor(j=i+1;j<Npoints;j++){\n\n\t\t\t//Add the contribution of pair (i,j) to the cost function\n\t\t\tsum += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,j,0),D,p),lambda); \n\n\t\t}\n\t}\n\n\treturn (2.0/(Npoints*(Npoints-1)))*sum;\n\n}\n\n/*This computes the cost function in the particular case in which all the points are \nequally spaced on the diagonal of the hypercube*/\n\ndouble diagonalCost(int Npoints,double lambda){\n\n\tdouble sum = 0.0;\n\tint i,j;\n\n\tfor(i=0;i<Npoints;i++){\n\t\tfor(j=i+1;j<Npoints;j++){\n\n\t\t\t//Add the contribution of pair (i,j) to the cost function\n\t\t\tsum += pow((Npoints-1)*1.0/(j-i),lambda); \n\n\t\t}\n\t}\n\n\treturn (2.0/(Npoints*(Npoints-1)))*sum;\n\n}\n\n/*This function computes the variation of the cost when a pair of coordinates is exchanged;\nthis function also performs an in-place swap of the coordinates. More specifically:\nthis function swaps coordinate d of points i1 and i2 and returns the variation of the cost\nfunction due to this swap*/\n\n/**/\n\ndouble swap(gsl_matrix *data,int Npoints,int D,double p,double lambda,int i1,int i2, int d){\n\n\tdouble costBefore,costAfter,temp;\n\tint i;\n\n\t//initialize to 0\n\tcostBefore = costAfter = 0.0;\n\n\t/*compute the contribution of points i1 and i2 to the cost function, before swapping;\n\tsum over all the particles except i1 and i2*/\n\tfor(i=0;i<Npoints;i++){\n\t\t\n\t\tif(i!=i1 && i!=i2){\n\t\t\tcostBefore += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i1,0),D,p),lambda) + pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i2,0),D,p),lambda);\n\t\t}\n\t\n\t}\n\n\t//perform the coordinate swap\n\ttemp = gsl_matrix_get(data,i1,d);\n\tgsl_matrix_set(data,i1,d,gsl_matrix_get(data,i2,d));\n\tgsl_matrix_set(data,i2,d,temp);\n\n\t/*compute the contribution of points i1 and i2 to the cost function, after swapping;\n\tsum over all the particles except i1 and i2*/\n\tfor(i=0;i<Npoints;i++){\n\t\t\n\t\tif(i!=i1 && i!=i2){\n\t\t\tcostAfter += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i1,0),D,p),lambda) + pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i2,0),D,p),lambda);\n\t\t}\n\t\n\t}\n\n\t//return the cost difference\n\treturn (2.0/(Npoints*(Npoints-1)))*(costAfter - costBefore);\n\n}\n\n/*This function swaps the particle pair back: needed if the original swap didn't improve the cost function*/\n\nvoid swapBack(gsl_matrix *data,int i1,int i2,int d){\n\n\tdouble temp;\n\n\t//perform the coordinate swap\n\ttemp = gsl_matrix_get(data,i1,d);\n\tgsl_matrix_set(data,i1,d,gsl_matrix_get(data,i2,d));\n\tgsl_matrix_set(data,i2,d,temp);\n\n}\n\n/*Main design sampler*/\n\ndouble sample(int Npoints,int D,double p,double lambda,int seed,int maxIterations,gsl_matrix *data,double *costValues){\n\n\tint i,d,i1,i2,iterCount;\n\t\n\tconst gsl_rng_type *T;\n\tgsl_rng *r;\n\tgsl_permutation *perm = gsl_permutation_alloc(Npoints);\n\n\tdouble currentCost,deltaCost,deltaPerc;\n\n\t//Initialize random number generator\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\n\t//Initialize permutation\n\tgsl_permutation_init(perm);\n\n\t//Initialize random number generator with provided seed\n\tgsl_rng_set(r,seed);\n\n\t//Initialize the point coordinates in data with random permutations of (1..Npoints) to enforce latin hypercube structure\n\tfor(d=0;d<D;d++){\n\n\t\t//Shuffle the numbers\n\t\tgsl_ran_shuffle(r,perm->data,Npoints,sizeof(size_t));\n\n\t\t//Permute coordinates\n\t\tfor(i=0;i<Npoints;i++){\n\t\t\tgsl_matrix_set(data,i,d,(double)perm->data[i]/(Npoints-1));\n\t\t}\n\n\t}\n\n\t/*The loop does the following: it swaps a random coordinate of a random pair,\n\tchecks if the cost is lower. If so, it keeps the configuration, otherwise it\n\treverses it and tries a new one.*/\n\n\titerCount = 0;\n\tcurrentCost = cost(data,Npoints,D,p,lambda);\n\tdeltaPerc = 0.0;\n\n\twhile(1){\n\n\t\t//Decide which coordinate to swap of which pair\n\n\t\ti1 = gsl_rng_uniform_int(r,Npoints);\n\t\twhile((i2=gsl_rng_uniform_int(r,Npoints))==i1);\n\t\td = gsl_rng_uniform_int(r,D);\n\n\t\t//Compute the change in the cost function\n\t\tdeltaCost = swap(data,Npoints,D,p,lambda,i1,i2,d);\n\n\n\t\t/*Check if gain in cost is positive or negative: if positive, revert the swap, if negative keep it;\n\t\tanyway, log the result*/\n\t\tif(deltaCost>=0){\n\t\t\tswapBack(data,i1,i2,d);\n\t\t} else{\n\t\t\tcurrentCost += deltaCost;\n\t\t\tdeltaPerc = deltaCost/currentCost;\n\t\t}\n\n\t\t//Save the current cost to array\n\t\tcostValues[iterCount] = currentCost;\n\n\t\t//Criterion to break the loop\n\t\tif(++iterCount == maxIterations) break;\n\t\n\t}\n\n\t//Release resources for random number generator and permutations\n\tgsl_rng_free(r);\n\tgsl_permutation_free(perm);\n\n\t//Return the relative cost change due to the last iteration\n\treturn deltaPerc;\n\n}", "meta": {"hexsha": "f99fec28cf49bce2c454c7f2beae670453f83130", "size": 5389, "ext": "c", "lang": "C", "max_stars_repo_path": "lenstools/extern/design.c", "max_stars_repo_name": "asabyr/LensTools", "max_stars_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T02:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:03:11.000Z", "max_issues_repo_path": "lenstools/extern/design.c", "max_issues_repo_name": "asabyr/LensTools", "max_issues_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "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": "lenstools/extern/design.c", "max_forks_repo_name": "asabyr/LensTools", "max_forks_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "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.9086538462, "max_line_length": 199, "alphanum_fraction": 0.7133048803, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741295151718, "lm_q2_score": 0.863391602943619, "lm_q1q2_score": 0.8224445046047268}}
{"text": "#include <stdio.h>\n#include <glib.h>\n#include <gsl/gsl_matrix.h>\n\n#define MATRIX_SIZE 3\n\nstatic double d_matrix[MATRIX_SIZE][MATRIX_SIZE] = {\n  {1., 4., 2.},\n  {-1., -2., 1.},\n  {3., 20., 19.},\n};\nstatic double d_vector[] = {8., 3., 71.};\n\nint main(void) {\n  printf(\"Gauss.\\n\\n\");\n\n  // Alloc matrix`s\n  gsl_matrix *matrix = gsl_matrix_alloc(MATRIX_SIZE, MATRIX_SIZE);\n  // gsl_matrix *orig_matrix = gsl_matrix_alloc(MATRIX_SIZE, MATRIX_SIZE);\n\n  gsl_vector *vector = gsl_vector_alloc(MATRIX_SIZE);\n  // gsl_vector *orig_vector = gsl_vector_alloc(MATRIX_SIZE);\n\n  gsl_vector *result = gsl_vector_alloc(MATRIX_SIZE);\n\n  // Init matrix\n  for (size_t i = 0; i < MATRIX_SIZE; i++) {\n    for (size_t j = 0; j < MATRIX_SIZE; j++) {\n      gsl_matrix_set(matrix, i, j, d_matrix[i][j]);\n      // gsl_matrix_set(orig_matrix, i, j, d_matrix[i][j]);\n    }\n  }\n\n  // Init vector\n  for (size_t j = 0; j < MATRIX_SIZE; j++) {\n    gsl_vector_set(vector, j, d_vector[j]);\n    // gsl_vector_set(orig_vector, j, d_vector[j]);\n  }\n\n  printf(\"First matrix row:\\n\");\n\n  for (size_t j = 0; j < MATRIX_SIZE; j++) {\n    double el = gsl_matrix_get(matrix, 0, j);\n    printf(\"%zu - %f\\n\", j, el);\n  }\n  printf(\"\\n\");\n\n\n  // Gauss\n\n  // Forward\n\n  // Steps by equations\n  size_t swap_counter = 0;\n  for (size_t step = 0; step < MATRIX_SIZE - 1; step++) {\n\n\n    // Walk by matrix rows\n    for (size_t eq_idx = step + 1; eq_idx < MATRIX_SIZE; eq_idx++) {\n      // Multiplier\n\n      {\n        // Get vector column from submatrix\n        size_t subcol_size = MATRIX_SIZE - eq_idx;\n        gsl_vector_view subcol = gsl_matrix_subcolumn(matrix, eq_idx, eq_idx, subcol_size);\n\n        // Find max idx\n        gsl_vector *subcol_copy = gsl_vector_alloc(subcol_size);\n        gsl_vector_memcpy(subcol_copy, &subcol.vector);\n        for (size_t i = 0; i < subcol_size; i++) {\n          gsl_vector_set(subcol_copy, i, abs(gsl_vector_get(&subcol.vector, i)));\n        }\n        size_t eq_max_idx = gsl_vector_max_index(&subcol.vector) + eq_idx;\n\n        // swap rows\n        double cell = gsl_matrix_get(matrix, eq_max_idx, eq_idx);\n        if (cell == 0) {\n          goto err;\n        }\n        else if (eq_idx != eq_max_idx) {\n          gsl_matrix_swap_rows(matrix, eq_idx, eq_max_idx);\n          gsl_vector_swap_elements(vector, eq_idx, eq_max_idx);\n\n          // gsl_matrix_swap_rows(orig_matrix, eq_idx, eq_max_idx);\n          // gsl_vector_swap_elements(orig_vector, eq_idx, eq_max_idx);\n\n          swap_counter++;\n        }\n      }\n\n      double multiplier = gsl_matrix_get(matrix, eq_idx, step) / gsl_matrix_get(matrix, step, step);\n\n      gsl_matrix_set(matrix, eq_idx, step, 0);\n\n      // Update vector value\n      double vector_val = gsl_vector_get(vector, eq_idx) - multiplier * gsl_vector_get(vector, step);\n      gsl_vector_set(vector, eq_idx, vector_val);\n\n      // Walk by eq cells\n      for (size_t col = step + 1; col < MATRIX_SIZE; col++) {\n        double cell_val = gsl_matrix_get(matrix, eq_idx, col) - multiplier * gsl_matrix_get(matrix, step, col);\n\n        gsl_matrix_set(matrix, eq_idx, col, cell_val);\n      }\n    }\n  }\n\n  // /Forward\n\n  // det\n\n  double det = 1;\n  for (size_t i = 0; i < MATRIX_SIZE; i++) {\n    det *= gsl_matrix_get(matrix, i, i);\n  }\n  if (swap_counter % 2 != 0) {\n    det *= -1;\n  }\n\n\n  printf(\"det = %f\\n\\n\", det);\n\n  // /det\n\n  // Back\n\n  for (ssize_t eq_idx = MATRIX_SIZE - 1; eq_idx >= 0; eq_idx--) { //1\n    double sum = 0;\n\n    for (size_t col = eq_idx + 1; col <= MATRIX_SIZE - 1; col++) { // 2\n      sum += gsl_matrix_get(matrix, eq_idx, col) * gsl_vector_get(result, col);\n    }\n\n    gsl_vector_set(result, eq_idx, (gsl_vector_get(vector, eq_idx) - sum) / gsl_matrix_get(matrix, eq_idx, eq_idx));\n  }\n\n  // /Back\n\n  // /Gauss\n\n\n  printf(\"Result:\\n\");\n\n  for (size_t i = 0; i < MATRIX_SIZE; i++) {\n    printf(\"%zu - %f\\n\", i, gsl_vector_get(result, i));\n  }\n\n  printf(\"\\nCheck:\\n\");\n\n  for (size_t row = 0; row < MATRIX_SIZE; row++) {\n    double sum = 0;\n\n    for (size_t col = 0; col < MATRIX_SIZE; col++) {\n      sum += d_matrix[row][col] * gsl_vector_get(result, col);\n    }\n\n    printf(\"%f = %f\\n\", sum, d_vector[row]);\n  }\n\n  exit(EXIT_SUCCESS);\n\n  err:\n    fprintf(stderr, \"No decision.\\n\");\n    exit(EXIT_FAILURE);\n}\n", "meta": {"hexsha": "1405dfa17bce22819eff719bef72dddb013ebec2", "size": 4239, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gauss.c", "max_stars_repo_name": "unixs/numerical-la-gauss", "max_stars_repo_head_hexsha": "1b9e14a4a4774b317b96cb99fb5354f45938a870", "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/gauss.c", "max_issues_repo_name": "unixs/numerical-la-gauss", "max_issues_repo_head_hexsha": "1b9e14a4a4774b317b96cb99fb5354f45938a870", "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/gauss.c", "max_forks_repo_name": "unixs/numerical-la-gauss", "max_forks_repo_head_hexsha": "1b9e14a4a4774b317b96cb99fb5354f45938a870", "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.5361445783, "max_line_length": 116, "alphanum_fraction": 0.6065109696, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9441768651485394, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.8043941222678459}}