Search is not available for this dataset
text
string
meta
dict
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <nlopt.h> typedef struct { int N; double *x, *y; /* length N; */ } lorentzdata; static double sqr(double x) { return x * x; } static int count = 0; static double lorentzerr(int n, const double *p, double *grad, void *data) { lorentzdata *d = (lorentzdata *) data; int N = d->N; const double *xs = d->x; const double *ys = d->y; double val = 0; int i, j; for (i = 0; i < N; ++i) { double x = xs[i], y = ys[i]; double lorsum = 0; for (j = 0; j < n; j += 3) { double A = p[j + 0]; double w = p[j + 1]; double G = p[j + 2]; double lor = A / (sqr(x - w) + G*G); lorsum += lor; } val += sqr(y - lorsum); if (grad) for (j = 0; j < n; j += 3) { double A = p[j + 0]; double w = p[j + 1]; double G = p[j + 2]; double deninv = 1.0 / (sqr(x - w) + G*G); grad[j + 0] += -2 * (y - lorsum) * deninv; grad[j + 1] += 4*A * (w - x) * (y - lorsum) * sqr(deninv); grad[j + 2] += 4*A * G * (y - lorsum) * sqr(deninv); } } ++count; // printf("%d: f(%g,%g,%g) = %g\n", count, p[0],p[1],p[2], val); return val; } extern double nlopt_urand(double a, double b); int main(void) { lorentzdata d; int i; double A = 1, w = 0, G = 1, noise=0.01; double lb[3] = {-HUGE_VAL,-HUGE_VAL,0}; double ub[3] = {HUGE_VAL,HUGE_VAL,HUGE_VAL}; double p[3] = {0,1,2}, minf; nlopt_srand_time(); d.N = 200; d.x = (double *) malloc(sizeof(double) * d.N * 2); d.y = d.x + d.N; for (i = 0; i < d.N; ++i) { d.x[i] = nlopt_urand(-0.5, 0.5) * 8*G + w; d.y[i] = 2*noise*nlopt_urand(-0.5,0.5) + A / (sqr(d.x[i]-w) + G*G); } nlopt_minimize(NLOPT_LN_NEWUOA_BOUND, 3, lorentzerr, &d, lb, ub, p, &minf, -HUGE_VAL, 0,0, 1e-6,NULL, 0,0); printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]); count = 0; nlopt_minimize(NLOPT_LN_COBYLA, 3, lorentzerr, &d, lb, ub, p, &minf, -HUGE_VAL, 0,0, 1e-6,NULL, 0,0); printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]); count = 0; nlopt_minimize(NLOPT_LN_NELDERMEAD, 3, lorentzerr, &d, lb, ub, p, &minf, -HUGE_VAL, 0,0, 1e-6,NULL, 0,0); printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]); count = 0; nlopt_minimize(NLOPT_LN_SBPLX, 3, lorentzerr, &d, lb, ub, p, &minf, -HUGE_VAL, 0,0, 1e-6,NULL, 0,0); printf("%d minf=%g at A=%g, w=%g, G=%g\n", count, minf, p[0],p[1],p[2]); return 0; }
{ "alphanum_fraction": 0.4828741623, "avg_line_length": 25.1028037383, "ext": "c", "hexsha": "afa957aa8424ace7a6990a4404dfb2b3f7c2eec3", "lang": "C", "max_forks_count": 35, "max_forks_repo_forks_event_max_datetime": "2019-09-13T07:06:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-01T17:26:50.000Z", "max_forks_repo_head_hexsha": "a9880be9bd86955afd6b8f7352822bc18673eda3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "daemonslayer/Notebook", "max_forks_repo_path": "collection/cp/optimization/nlopt-master/test/lorentzfit.c", "max_issues_count": 29, "max_issues_repo_head_hexsha": "a9880be9bd86955afd6b8f7352822bc18673eda3", "max_issues_repo_issues_event_max_datetime": "2017-08-07T08:18:23.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-01T22:35:17.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "daemonslayer/Notebook", "max_issues_repo_path": "collection/cp/optimization/nlopt-master/test/lorentzfit.c", "max_line_length": 77, "max_stars_count": 65, "max_stars_repo_head_hexsha": "a9880be9bd86955afd6b8f7352822bc18673eda3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "daemonslayer/Notebook", "max_stars_repo_path": "collection/cp/optimization/nlopt-master/test/lorentzfit.c", "max_stars_repo_stars_event_max_datetime": "2021-06-27T14:40:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-20T20:46:26.000Z", "num_tokens": 1128, "size": 2686 }
// Test program for comparison with brighten_float_image. #include <assert.h> #include <stdlib.h> #include <glib.h> #include <gsl/gsl_blas.h> #include <asf_meta.h> int main (int argc, char **argv) { assert (argc == 3); // Image to be brightened. GString *input_image_basename = g_string_new (argv[1]); // Basename to use for brightened version of image. GString *output_image_basename = g_string_new (argv[2]); // Form names for the input image data and metadata. GString *input_metadata_file = g_string_new (input_image_basename->str); g_string_append (input_metadata_file, ".meta"); GString *input_data_file = g_string_new (input_image_basename->str); g_string_append (input_data_file, ".img"); // Form names for the output image data and metadata. GString *output_metadata_file = g_string_new (output_image_basename->str); g_string_append (output_metadata_file, ".meta"); GString *output_data_file = g_string_new (output_image_basename->str); g_string_append (output_data_file, ".img"); // Read the metadata for the input image. meta_parameters *imd = meta_read (input_image_basename->str); // Shorthand for the dimension of the input image. size_t ixs = imd->general->sample_count; size_t iys = imd->general->line_count; // Set up gsl matrix for the input image. gsl_matrix_float *id = gsl_matrix_float_alloc (iys, ixs); // Set up gsl matrix for the output image. gsl_matrix_float *od = gsl_matrix_float_alloc (iys, ixs); // Do the brightening. size_t ii; // For each line. for ( ii = 0 ; ii < iys ; ii++ ) { size_t jj; // For each pixel of line. for ( jj = 0 ; jj < ixs ; jj++ ) { // Brighten pixel by factor of two and store in output image. float pixel_value = gsl_matrix_float_get (id, ii, jj); gsl_matrix_float_set (od, ii, jj, pixel_value * 2); } } // Store the output image data. FILE *od_stream = fopen (output_data_file->str, "wb"); g_assert (od_stream != NULL); int return_code = gsl_matrix_float_fwrite (od_stream, od); g_assert (return_code == GSL_SUCCESS); return_code = fclose (od_stream); g_assert (return_code == 0); // Copy the input metadata to the output metadata. GString *system_command = g_string_new ("cp "); g_string_append_printf (system_command, "%s %s", input_metadata_file->str, output_metadata_file->str); return_code = system (system_command->str); g_assert (return_code == 0); exit (EXIT_SUCCESS); }
{ "alphanum_fraction": 0.7070707071, "avg_line_length": 32.1428571429, "ext": "c", "hexsha": "7371001d90c583e831ba24227698aa4af2811607", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_raster/brighten_in_memory.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_raster/brighten_in_memory.c", "max_line_length": 76, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_raster/brighten_in_memory.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 661, "size": 2475 }
/* matrices.c */ // 8.4.13 Example programs for matrices of gsl-ref.pdf // GNU GSL GNU Scientific Library reference book #include <stdio.h> #include <gsl/gsl_matrix.h> int main (void) { int i, j; gsl_matrix * m = gsl_matrix_alloc (10, 3); for (i = 0; i < 10; i++) for (j = 0; j < 3; j++) gsl_matrix_set (m, i, j, 0.23 + 100*i + j); for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */ for (j = 0; j < 3; j++) printf("m(%d,%d) = %g\n", i, j, gsl_matrix_get (m, i, j)); gsl_matrix_free(m); return 0; }
{ "alphanum_fraction": 0.5449541284, "avg_line_length": 19.4642857143, "ext": "c", "hexsha": "86a2ce1ad52507c38322fdd46118a909d4318b3b", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z", "max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z", "max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ernestyalumni/CompPhys", "max_forks_repo_path": "gslExamples/matrices.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ernestyalumni/CompPhys", "max_issues_repo_path": "gslExamples/matrices.c", "max_line_length": 54, "max_stars_count": 70, "max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ernestyalumni/CompPhys", "max_stars_repo_path": "gslExamples/matrices.c", "max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z", "num_tokens": 199, "size": 545 }
#include <stdio.h> #include <gsl/gsl_poly.h> int main (void) { int i; /* coefficients of P(x) = -1 + x^5 */ double a[6] = { -1, 0, 0, 0, 0, 1 }; double z[10]; gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc (6); gsl_poly_complex_solve (a, 6, w, z); gsl_poly_complex_workspace_free (w); for (i = 0; i < 5; i++) { printf ("z%d = %+.18f %+.18f\n", i, z[2*i], z[2*i+1]); } return 0; }
{ "alphanum_fraction": 0.5268817204, "avg_line_length": 17.2222222222, "ext": "c", "hexsha": "6debbd54b63a37bfdeb04ea0b0de0c8369fda1e6", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/polyroots.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/polyroots.c", "max_line_length": 45, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/polyroots.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 175, "size": 465 }
/* movstat/mvacc.c * * Moving window mean/variance accumulator - based on a modification * to Welford's algorithm, discussed here: * * https://stackoverflow.com/a/6664212 * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_movstat.h> typedef double ringbuf_type_t; #include "ringbuf.c" typedef struct { size_t n; /* window size */ size_t k; /* number of samples currently in window */ double mean; /* current window mean */ double M2; /* current window M2 */ ringbuf *rbuf; /* ring buffer storing current window */ } mvacc_state_t; static size_t mvacc_size(const size_t n) { size_t size = 0; size += sizeof(mvacc_state_t); size += ringbuf_size(n); return size; } static int mvacc_init(const size_t n, void * vstate) { mvacc_state_t * state = (mvacc_state_t *) vstate; state->n = n; state->k = 0; state->mean = 0.0; state->M2 = 0.0; state->rbuf = (ringbuf *) ((unsigned char *) vstate + sizeof(mvacc_state_t)); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int mvacc_insert(const double x, void * vstate) { mvacc_state_t * state = (mvacc_state_t *) vstate; if (ringbuf_is_full(state->rbuf)) { /* remove oldest window element and add new one */ double old = ringbuf_peek_back(state->rbuf); double prev_mean = state->mean; state->mean += (x - old) / (double) state->n; state->M2 += ((old - prev_mean) + (x - state->mean)) * (x - old); } else { double delta = x - state->mean; /* * Welford algorithm: * * mu_new = mu_old + (x - mu_old) / n * M2_new = M2_old + (x - mu_old) * (x - mu_new) */ ++(state->k); state->mean += delta / (double) state->k; state->M2 += delta * (x - state->mean); } /* add new element to ring buffer */ ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int mvacc_delete(void * vstate) { mvacc_state_t * state = (mvacc_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) { if (state->k > 1) { /* * mu_new = mu_old + (mu_old - x_old) / (n - 1) * M2_new = M2_old - (mu_old - x_old) * (mu_new - x_old) */ double old = ringbuf_peek_back(state->rbuf); double prev_mean = state->mean; double delta = prev_mean - old; state->mean += delta / (state->k - 1.0); state->M2 -= delta * (state->mean - old); } else if (state->k == 1) { state->mean = 0.0; state->M2 = 0.0; } ringbuf_pop_back(state->rbuf); --(state->k); } return GSL_SUCCESS; } static int mvacc_mean(void * params, double * result, const void * vstate) { const mvacc_state_t * state = (const mvacc_state_t *) vstate; (void) params; *result = state->mean; return GSL_SUCCESS; } static int mvacc_variance(void * params, double * result, const void * vstate) { const mvacc_state_t * state = (const mvacc_state_t *) vstate; (void) params; if (state->k < 2) *result = 0.0; else *result = state->M2 / (state->k - 1.0); return GSL_SUCCESS; } static int mvacc_sd(void * params, double * result, const void * vstate) { double variance; int status = mvacc_variance(params, &variance, vstate); *result = sqrt(variance); return status; } static const gsl_movstat_accum mean_accum_type = { mvacc_size, mvacc_init, mvacc_insert, mvacc_delete, mvacc_mean }; const gsl_movstat_accum *gsl_movstat_accum_mean = &mean_accum_type; static const gsl_movstat_accum variance_accum_type = { mvacc_size, mvacc_init, mvacc_insert, mvacc_delete, mvacc_variance }; const gsl_movstat_accum *gsl_movstat_accum_variance = &variance_accum_type; static const gsl_movstat_accum sd_accum_type = { mvacc_size, mvacc_init, mvacc_insert, mvacc_delete, mvacc_sd }; const gsl_movstat_accum *gsl_movstat_accum_sd = &sd_accum_type;
{ "alphanum_fraction": 0.6452624974, "avg_line_length": 23.2087378641, "ext": "c", "hexsha": "14f08944d25c57806824825dff45e0bf0c44c6f1", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/mvacc.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/movstat/mvacc.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/movstat/mvacc.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1371, "size": 4781 }
#include <stdio.h> #include <gsl/gsl_statistics.h> #include <assert.h> extern "C" { #include <quadmath.h> } #ifndef N #define N 64 #endif #define K N/2 #ifndef FB #define FB 64 #endif #if(FB==64) #define FT double #elif(FB==80) #define FT long double #endif int main(int argc, char *argv[]) { assert(argc == 3); int i; char *inname = argv[1]; char *outname = argv[2]; FILE *infile = fopen(inname, "r"); FILE *outfile = fopen(outname, "w"); FT data[K], w[K]; FT wsd; for (i = 0 ; i < K ; i++) { __float128 in_data; fread(&in_data, sizeof(__float128), 1, infile); data[i] = (float) in_data; } for (i = 0 ; i < K ; i++) { __float128 in_data; fread(&in_data, sizeof(__float128), 1, infile); w[i] = (float) in_data; } fclose(infile); // library call double wmean; #if(FB==64) wmean = gsl_stats_wmean(w, 1, data, 1, K); wsd = gsl_stats_wsd_with_fixed_mean(w, 1, data, 1, K, wmean); #elif(FB==80) wmean = gsl_stats_long_double_wmean(w, 1, data, 1, K); wsd = gsl_stats_long_double_wsd_with_fixed_mean(w, 1, data, 1, K, wmean); #else exit(-1); #endif //printf ("The sample wsd is %g\n", wsd); __float128 out_data; out_data = (__float128) wsd; fwrite(&out_data, sizeof(__float128), 1, outfile); fclose(outfile); return 0; }
{ "alphanum_fraction": 0.6082397004, "avg_line_length": 18.0405405405, "ext": "c", "hexsha": "82f1c95ab4ab0c16a78d18b9c4281aa24b141edc", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_path": "benchmarks/gsl/wsd-w/wsd-w-INOUT.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_path": "benchmarks/gsl/wsd-w/wsd-w-INOUT.c", "max_line_length": 81, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_path": "benchmarks/gsl/wsd-w/wsd-w-INOUT.c", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "num_tokens": 464, "size": 1335 }
/* Copyright [2020] [IBM Corporation] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef _MCAS_COMMON_BYTE_SPAN_ #define _MCAS_COMMON_BYTE_SPAN_ #include <common/pointer_cast.h> #include <cstddef> #include <gsl/gsl_byte> #include <gsl/span> #include <sys/uio.h> #ifndef MCAS_SPAN_USES_GSL /* For minimal difference with older code; implement span as iovec (not gsl::span) */ #define MCAS_SPAN_USES_GSL 0 #endif #ifndef MCAS_BYTE_USES_STD /* For compilcation with C++14, use gsl::byte, not C++17 std::byte */ #define MCAS_BYTE_USES_STD 0 #endif namespace common { #if MCAS_BYTE_USES_STD using byte = std::byte; #else using byte = gsl::byte; /* can be std::byte in C++17 */ #endif template <typename T> using span = gsl::span<T>; /* can be std::span in C++20 */ /* span of a const area. No equivalent in ::iovec, so always use span */ using const_byte_span = span<const byte>; inline const_byte_span make_const_byte_span(const void *base, std::size_t len) { return const_byte_span(static_cast<const_byte_span::pointer>(base), len); } } namespace { /* Accessors: Non-member in order to match ::iovec accessors */ /* Start of area as a void *, for use with %p format and for conversion to an arbitrary type */ inline const void *base(const common::const_byte_span &r) { return r.data(); } /* Length of area in bytes, for use in byte-based address calculations and comparisons */ inline std::size_t size(const common::const_byte_span &r) { return r.size(); } /* Start of area as byte *, for use in byte-based address calculations and comparisons */ inline const common::byte *data(const common::const_byte_span &r) { return r.data(); } /* End of area as byte *, for use in byte-based address calculations and comparisons */ inline const common::byte *data_end(const common::const_byte_span &r) { return r.data() + r.size(); } /* End of are as a void *, for use with %p format */ inline const void *end(const common::const_byte_span &r) { return ::data_end(r); } } namespace { /* Same accessors as above, for ::iovec */ inline void *base(const ::iovec &r) { return r.iov_base; } inline std::size_t size(const ::iovec &r) { return r.iov_len; } inline common::byte *data(const ::iovec &r) { return static_cast<common::byte *>(::base(r)); } inline common::byte *data_end(const ::iovec &r) { return ::data(r) + ::size(r); } inline void *end(const ::iovec &r) { return ::data_end(r); } } namespace common { inline constexpr ::iovec make_iovec(void *base, std::size_t len) { return ::iovec{base, len}; } } #if MCAS_SPAN_USES_GSL #include <common/pointer_cast.h> namespace common { using byte_span = span<byte>; } namespace { /* Same accessors as above, for non-const byte span */ inline void *base(const common::byte_span &r) { return r.data(); } inline std::size_t size(const common::byte_span &r) { return r.size(); } inline common::byte *data(const common::byte_span &r) { return r.data(); } inline common::byte *data_end(const common::byte_span &r) { return ::data(r) + ::size(r); } inline void *end(const common::byte_span &r) { return ::data_end(r); } } namespace common { /* Construct a byte_span in syntax compatible with iovec (function, not constructor) */ inline byte_span make_byte_span(void *base, std::size_t len) { return byte_span(common::pointer_cast<byte_span::value_type>(base), len); } } #else /* ! MCAS_SPAN_USES_GSL */ namespace common { using byte_span = ::iovec; /* Construct an iovec in syntax compatible with span (no braces) */ inline byte_span make_byte_span(void *base, std::size_t len) { return byte_span{base, len}; } } #endif namespace common { /* Converion from span of non-const to span of const */ inline const_byte_span make_const_byte_span(const byte_span s) { return const_byte_span(::data(s), ::size(s)); } } #endif
{ "alphanum_fraction": 0.7147154095, "avg_line_length": 37.2586206897, "ext": "h", "hexsha": "6fee0c69438faed6159cf16c4969591b51c4fc9f", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2022-01-26T01:56:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-02T06:30:36.000Z", "max_forks_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "moshik1/mcas", "max_forks_repo_path": "src/lib/common/include/common/byte_span.h", "max_issues_count": 66, "max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:34:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-03T23:40:48.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "moshik1/mcas", "max_issues_repo_path": "src/lib/common/include/common/byte_span.h", "max_line_length": 139, "max_stars_count": 60, "max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "moshik1/mcas", "max_stars_repo_path": "src/lib/common/include/common/byte_span.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T10:35:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-28T08:15:07.000Z", "num_tokens": 1125, "size": 4322 }
#ifndef ARRUS_CORE_DEVICES_TXRXPARAMETERS_H #define ARRUS_CORE_DEVICES_TXRXPARAMETERS_H #include <gsl/gsl> #include <utility> #include <ostream> #include "arrus/core/api/common/Interval.h" #include "arrus/core/api/common/Tuple.h" #include "arrus/core/api/common/types.h" #include "arrus/common/format.h" #include "arrus/core/common/collections.h" #include "arrus/core/api/ops/us4r/Pulse.h" namespace arrus::devices { class TxRxParameters { public: static const TxRxParameters US4OEM_NOP; static TxRxParameters createRxNOPCopy(const TxRxParameters& op) { return TxRxParameters( op.txAperture, op.txDelays, op.txPulse, BitMask(op.rxAperture.size(), false), op.rxSampleRange, op.rxDecimationFactor, op.pri, op.rxPadding ); } /** * * ** tx aperture, tx delays and rx aperture should have the same size * (tx delays is NOT limited to the tx aperture active elements - * the whole array must be provided).** * * @param txAperture * @param txDelays * @param txPulse * @param rxAperture * @param rxSampleRange [start, end) range of samples to acquire, starts from 0 * @param rxDecimationFactor * @param pri * @param rxPadding how many 0-channels padd from the left and right */ TxRxParameters(std::vector<bool> txAperture, std::vector<float> txDelays, const ops::us4r::Pulse &txPulse, std::vector<bool> rxAperture, Interval<uint32> rxSampleRange, uint32 rxDecimationFactor, float pri, Tuple<ChannelIdx> rxPadding = {0, 0}) : txAperture(std::move(txAperture)), txDelays(std::move(txDelays)), txPulse(txPulse), rxAperture(std::move(rxAperture)), rxSampleRange(std::move(rxSampleRange)), rxDecimationFactor(rxDecimationFactor), pri(pri), rxPadding(std::move(rxPadding)){} [[nodiscard]] const std::vector<bool> &getTxAperture() const { return txAperture; } [[nodiscard]] const std::vector<float> &getTxDelays() const { return txDelays; } [[nodiscard]] const ops::us4r::Pulse &getTxPulse() const { return txPulse; } [[nodiscard]] const std::vector<bool> &getRxAperture() const { return rxAperture; } [[nodiscard]] const Interval<uint32> &getRxSampleRange() const { return rxSampleRange; } [[nodiscard]] uint32 getNumberOfSamples() const { return rxSampleRange.end() - rxSampleRange.start(); } [[nodiscard]] int32 getRxDecimationFactor() const { return rxDecimationFactor; } [[nodiscard]] float getPri() const { return pri; } [[nodiscard]] const Tuple<ChannelIdx> &getRxPadding() const { return rxPadding; } [[nodiscard]] bool isNOP() const { auto atLeastOneTxActive = ::arrus::reduce( std::begin(txAperture), std::end(txAperture), false, [](auto a, auto b) {return a | b;}); auto atLeastOneRxActive = ::arrus::reduce( std::begin(rxAperture), std::end(rxAperture), false, [](auto a, auto b) {return a | b;}); return !atLeastOneTxActive && !atLeastOneRxActive; } [[nodiscard]] bool isRxNOP() const { auto atLeastOneRxActive = ::arrus::reduce( std::begin(rxAperture), std::end(rxAperture), false, [](auto a, auto b) {return a | b;}); return !atLeastOneRxActive; } friend std::ostream & operator<<(std::ostream &os, const TxRxParameters &parameters) { os << "Tx/Rx: "; os << "TX: "; os << "aperture: " << ::arrus::toString(parameters.getTxAperture()) << ", delays: " << ::arrus::toString(parameters.getTxDelays()) << ", center frequency: " << parameters.getTxPulse().getCenterFrequency() << ", n. periods: " << parameters.getTxPulse().getNPeriods() << ", inverse: " << parameters.getTxPulse().isInverse(); os << "; RX: "; os << "aperture: " << ::arrus::toString(parameters.getRxAperture()); os << "sample range: " << parameters.getRxSampleRange().start() << ", " << parameters.getRxSampleRange().end(); os << ", fs divider: " << parameters.getRxDecimationFactor(); os << std::endl; return os; } bool operator==(const TxRxParameters &rhs) const { return txAperture == rhs.txAperture && txDelays == rhs.txDelays && txPulse == rhs.txPulse && rxAperture == rhs.rxAperture && rxSampleRange == rhs.rxSampleRange && rxDecimationFactor == rhs.rxDecimationFactor && pri == rhs.pri; } bool operator!=(const TxRxParameters &rhs) const { return !(rhs == *this); } private: ::std::vector<bool> txAperture; ::std::vector<float> txDelays; ::arrus::ops::us4r::Pulse txPulse; ::std::vector<bool> rxAperture; // TODO change to a simple pair Interval<uint32> rxSampleRange; int32 rxDecimationFactor; float pri; Tuple<ChannelIdx> rxPadding; }; using TxRxParamsSequence = std::vector<TxRxParameters>; /** * Returns the number of actual ops, that is, a the number of ops excluding RxNOPs. */ uint16 getNumberOfNoRxNOPs(const TxRxParamsSequence &seq); } #endif //ARRUS_CORE_DEVICES_TXRXPARAMETERS_H
{ "alphanum_fraction": 0.6011519078, "avg_line_length": 32.3023255814, "ext": "h", "hexsha": "fb53f16aee4c6e9aa0e8ea05b202f1cf6e54075c", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": [ "BSL-1.0", "MIT" ], "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_path": "arrus/core/devices/TxRxParameters.h", "max_issues_count": 60, "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_licenses": [ "BSL-1.0", "MIT" ], "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_path": "arrus/core/devices/TxRxParameters.h", "max_line_length": 85, "max_stars_count": 11, "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": [ "BSL-1.0", "MIT" ], "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_path": "arrus/core/devices/TxRxParameters.h", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "num_tokens": 1405, "size": 5556 }
/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ Copyright (c) 1999-2014 and onwards, Imperial College London All rights reserved. See LICENSE for details =========================================================================*/ #ifndef _IRTKVECTOR_H #define _IRTKVECTOR_H #ifdef USE_VXL // VXL header file was loaded in irtkMatrix.h #include <vnl/vnl_diag_matrix.h> #else #include <gsl/gsl_vector.h> #endif #include <iostream> #include <cmath> #include <irtkObject.h> /** Vector class. */ class irtkVector : public irtkObject { protected: /// Number of rows int _rows; /// Data double *_vector; public: /// Default constructor irtkVector(); /// Constructor for given row dimensions irtkVector(int); /// Copy constructor irtkVector(const irtkVector &); /// Destructor ~irtkVector(); /// Intialize matrix with number of rows void Initialize(int); // // Vector access functions // /// Returns number of rows int Rows() const; /// Puts vector value void Put(int, double); /// Gets vector value double Get(int) const; // // Operators for vector access // /// Puts vector value double &operator()(int); /// Gets vector value double operator()(int) const; // // Vector operators for doubles // /// Subtraction of a double irtkVector& operator-=(double); /// Addition of a double irtkVector& operator+=(double); /// Multiplication with a double irtkVector& operator*=(double); /// Division by a double irtkVector& operator/=(double); /// Return result of subtraction of a double irtkVector operator- (double); /// Return result of addition of a double irtkVector operator+ (double); /// Return result of multiplication with a double irtkVector operator* (double); /// Return result of division by a double irtkVector operator/ (double); // // Vector operators for vectors // /// Vector copy operator irtkVector& operator =(const irtkVector&); /// Vector subtraction operator irtkVector& operator-=(const irtkVector&); /// Vector addition operator irtkVector& operator+=(const irtkVector&); /// Vector componentwise multiplication operator (no scalar nor cross product) irtkVector& operator*=(const irtkVector&); /// Vector componentwise division operator irtkVector& operator/=(const irtkVector&); /// Return result for vector subtraction irtkVector operator- (const irtkVector&); /// Return result for vector addition irtkVector operator+ (const irtkVector&); /// Return result for componentwise vector multiplication (no scalar nor cross product) irtkVector operator* (const irtkVector&); /// Return result for componentwise vector division irtkVector operator/ (const irtkVector&); /// Comparison operator == bool operator==(const irtkVector &); #ifndef USE_STL /// Comparison operator != (if USE_STL is defined, negate == operator) bool operator!=(const irtkVector &); #endif /// Comparison operator < bool operator<(const irtkVector &); /// Scalar/dot product double ScalarProduct(const irtkVector&); /// Vector/cross product irtkVector CrossProduct(const irtkVector&); /// Returns norm of a vector double Norm(void) const; /// Vector normalization void Normalize(void); // // Vector in- and output // /// Interface to output stream friend std::ostream& operator<< (std::ostream&, const irtkVector&); /// Interface to input stream friend std::istream& operator>> (std::istream&, irtkVector&); /// Print vector void Print(); /// Read vector from file void Read (char *); /// Write vector to file void Write(char *); #ifdef USE_VXL template <class T> void Vector2Vnl(vnl_diag_matrix<T>*) const; template <class T> void Vnl2Vector(vnl_diag_matrix<T>*); #else /// Conversion to GSL vector (memory must be allocated) void Vector2GSL(gsl_vector *) const; /// Conversion from GSL vector void GSL2Vector(gsl_vector *); #endif }; // // Access operators // inline int irtkVector::Rows() const { return _rows; } inline void irtkVector::Put(int rows, double vector) { _vector[rows] = vector; } inline double irtkVector::Get(int rows) const { return _vector[rows]; } inline double& irtkVector::operator()(int rows) { return _vector[rows]; } inline double irtkVector::operator()(int rows) const { return _vector[rows]; } // // Vector operators for doubles // inline irtkVector& irtkVector::operator-=(double x) { int i; for (i = 0; i < _rows; i++) { _vector[i] -= x; } return *this; } inline irtkVector& irtkVector::operator+=(double x) { int i; for (i = 0; i < _rows; i++) { _vector[i] += x; } return *this; } inline irtkVector& irtkVector::operator*=(double x) { int i; for (i = 0; i < _rows; i++) { _vector[i] *= x; } return *this; } inline irtkVector& irtkVector::operator/=(double x) { int i; for (i = 0; i < _rows; i++) { _vector[i] /= x; } return *this; } inline irtkVector irtkVector::operator- (double x) { int i; irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] - x; } return m; } inline irtkVector irtkVector::operator+ (double x) { int i; irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] + x; } return m; } inline irtkVector irtkVector::operator* (double x) { int i; irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] * x; } return m; } inline irtkVector irtkVector::operator/ (double x) { int i; irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] / x; } return m; } // // Vector operators for vectors // inline irtkVector& irtkVector::operator =(const irtkVector& v) { int i; // Copy size this->Initialize(v._rows); // Copy vector for (i = 0; i < _rows; i++) { _vector[i] = v._vector[i]; } return *this; } inline irtkVector& irtkVector::operator-=(const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator-=: Size mismatch" << std::endl; exit(1); } for (i = 0; i < _rows; i++) { _vector[i] -= v._vector[i]; } return *this; } inline irtkVector& irtkVector::operator+=(const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator+=: Size mismatch" << std::endl; exit(1); } for (i = 0; i < _rows; i++) { _vector[i] += v._vector[i]; } return *this; } inline irtkVector& irtkVector::operator*=(const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator*=: Size mismatch" << std::endl; exit(1); } for (i = 0; i < _rows; i++) { _vector[i] *= v._vector[i]; } return *this; } inline irtkVector& irtkVector::operator/=(const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator/=: Size mismatch" << std::endl; exit(1); } for (i = 0; i < _rows; i++) { _vector[i] /= v._vector[i]; } return *this; } inline irtkVector irtkVector::operator- (const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator-: Size mismatch" << std::endl; exit(1); } irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] - v._vector[i]; } return m; } inline irtkVector irtkVector::operator+ (const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator+: Size mismatch" << std::endl; exit(1); } irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] + v._vector[i]; } return m; } inline irtkVector irtkVector::operator* (const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator*: Size mismatch" << std::endl; exit(1); } irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] * v._vector[i]; } return m; } inline irtkVector irtkVector::operator/ (const irtkVector& v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::operator/: Size mismatch" << std::endl; exit(1); } irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = _vector[i] / v._vector[i]; } return m; } // // Comparison // inline bool irtkVector::operator==(const irtkVector &v) { if (_rows != v._rows) { return false; } for (int i = 0; i < _rows; i++) { if (_vector[i] != v._vector[i]) return false; } return true; } #ifndef USE_STL inline bool irtkVector::operator!=(const irtkVector &v) { if (_rows != v._rows) { return true; } for (int i = 0; i < _rows; i++) { if (_vector[i] != v._vector[i]) return true; } return false; } #endif inline bool irtkVector::operator<(const irtkVector &v) { if (_rows > v._rows) { return false; } for (int i = 0; i < _rows; i++) { if (_vector[i] >= v._vector[i]) return false; } return true; } // // Vector products // inline double irtkVector::ScalarProduct(const irtkVector &v) { int i; double scalar_product=0; if (_rows != v._rows) { std::cerr << "irtkVector::ScalarProduct: Size mismatch" << std::endl; exit(1); } for (i = 0; i < _rows; i++) { scalar_product += _vector[i]*v._vector[i]; } return scalar_product; } inline irtkVector irtkVector::CrossProduct(const irtkVector &v) { int i; if (_rows != v._rows) { std::cerr << "irtkVector::CrossProduct: Size mismatch" << std::endl; exit(1); } irtkVector m(_rows); for (i = 0; i < _rows; i++) { m._vector[i] = (_vector[(i+1)%_rows]*v._vector[(i+2)%_rows]- _vector[(i+2)%_rows]*v._vector[(i+1)%_rows]); } return m; } // // Functions // inline double irtkVector::Norm(void) const { double norm = 0; for (int i = 0; i < _rows; i++) { norm += _vector[i]*_vector[i]; } return std::sqrt(norm); } inline void irtkVector::Normalize(void) { double norm = Norm(); if (norm != 0) { *this /= norm; } } #ifdef USE_VXL template <class T> inline void irtkVector::Vector2Vnl(vnl_diag_matrix<T>* m) const { unsigned i; for (i = 0; i < (unsigned) _rows; i++) { (*m)(i) = (T) _vector[i]; } } template <class T> inline void irtkVector::Vnl2Vector(vnl_diag_matrix<T>* m) { unsigned i; for (i = 0; i < (unsigned) _rows; i++) { _vector[i] = (float) (*m)(i); } } #endif #endif
{ "alphanum_fraction": 0.6132313147, "avg_line_length": 18.0117647059, "ext": "h", "hexsha": "1b58babdd7e7219c1a17763b3ebffa27ac462357", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_forks_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_forks_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_forks_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_issues_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_issues_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "6a1e4a15bdf92e86439791d836d1b20ede793293", "max_stars_repo_licenses": [ "Zlib", "Unlicense", "Intel", "MIT" ], "max_stars_repo_name": "gordon-n-stevenson/fetalReconstruction", "max_stars_repo_path": "source/IRTKSimple2/geometry++/include/irtkVector.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3347, "size": 10717 }
// // lu2lib.c // // J. Makino // Time-stamp: <2019-05-06 22:08:30 makino> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <timerlib.h> #ifndef NOBLAS #ifdef MKL #include <mkl_cblas.h> #else #include <cblas.h> #endif #endif #ifdef USEGDR #include "gdrdgemm.h" #endif #define FTYPE double #include <emmintrin.h> typedef double v2df __attribute__((vector_size(16))); typedef union {v2df v; double s[2];}v2u; #ifndef USEGDR void gdrsetboardid(int boardid) {} #endif void matmul2_host(int n, FTYPE a[n][n], FTYPE b[n][n], FTYPE c[n][n]) { int i, j, k; for(i=0;i<n;i++){ for(j=0;j<n;j++){ c[i][j]=0.0e0; for(k=0;k<n;k++) c[i][j]+= a[i][k]*b[k][j]; } } } // simplest version void matmul_for_small_nk_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { // simplest version int i,j,k; for(j=0;j<n;j++) for(i=0;i<m;i++) for(k=0;k<kk;k++) c[i][j] -= a[i][k]*b[k][j]; } // make copy of B void matmul_for_small_nk_1(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; double bcopy[n][kk]; for(k=0;k<kk;k++) for(j=0;j<n;j++) bcopy[j][k] = b[k][j]; for(i=0;i<m;i++){ for(j=0;j<n;j++){ register double tmp=0.0; for(k=0;k<kk;k++){ tmp += a[i][k]*bcopy[j][k]; } c[i][j] -= tmp; } } } // hand-unroll innermost loop void matmul_for_small_nk_2(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; double bcopy[n][kk]; for(j=0;j<n;j++) for(k=0;k<kk;k++) bcopy[j][k] = b[k][j]; for(i=0;i<m;i++){ double *ap=a[i]; for(j=0;j<n;j++){ double *bp = bcopy[j]; double tmp=0.0; for(k=0;k<kk;k+=8) tmp += ap[k]*bp[k] + ap[k+1]*bp[k+1] + ap[k+2]*bp[k+2] + ap[k+3]*bp[k+3] + ap[k+4]*bp[k+4] + ap[k+5]*bp[k+5] + ap[k+6]*bp[k+6] + ap[k+7]*bp[k+7]; c[i][j]-=tmp; } } } // hand-unroll mid-loop void matmul_for_small_nk_3(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; double bcopy[n][kk]; for(j=0;j<n;j++) for(k=0;k<kk;k++) bcopy[j][k] = b[k][j]; for(i=0;i<m;i++){ double *ap=a[i]; for(j=0;j<n;j+=4){ double *bp = bcopy[j]; double *bpp = bcopy[j+1]; double *bp2 = bcopy[j+2]; double *bp3 = bcopy[j+3]; double tmp=0.0; double tmp1=0.0; double tmp2=0.0; double tmp3=0.0; for(k=0;k<kk;k+=8){ tmp += ap[k]*bp[k] + ap[k+1]*bp[k+1] + ap[k+2]*bp[k+2] + ap[k+3]*bp[k+3] + ap[k+4]*bp[k+4] + ap[k+5]*bp[k+5] + ap[k+6]*bp[k+6] + ap[k+7]*bp[k+7]; tmp1 += ap[k]*bpp[k] + ap[k+1]*bpp[k+1] + ap[k+2]*bpp[k+2] + ap[k+3]*bpp[k+3] + ap[k+4]*bpp[k+4] + ap[k+5]*bpp[k+5] + ap[k+6]*bpp[k+6] + ap[k+7]*bpp[k+7]; tmp2 += ap[k]*bp2[k] + ap[k+1]*bp2[k+1] + ap[k+2]*bp2[k+2] + ap[k+3]*bp2[k+3] + ap[k+4]*bp2[k+4] + ap[k+5]*bp2[k+5] + ap[k+6]*bp2[k+6] + ap[k+7]*bp2[k+7]; tmp3 += ap[k]*bp3[k] + ap[k+1]*bp3[k+1] + ap[k+2]*bp3[k+2] + ap[k+3]*bp3[k+3] + ap[k+4]*bp3[k+4] + ap[k+5]*bp3[k+5] + ap[k+6]*bp3[k+6] + ap[k+7]*bp3[k+7]; } c[i][j]-=tmp; c[i][j+1]-=tmp1; c[i][j+2]-=tmp2; c[i][j+3]-=tmp3; } } } // hand-unroll mid-loop by 2 void matmul_for_small_nk_4(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; double bcopy[n][kk]; for(j=0;j<n;j++) for(k=0;k<kk;k++) bcopy[j][k] = b[k][j]; for(i=0;i<m;i++){ double *ap=a[i]; for(j=0;j<n;j+=2){ double *bp = bcopy[j]; double *bpp = bcopy[j+1]; double tmp=0.0; double tmp1=0.0; for(k=0;k<kk;k+=8){ tmp += ap[k]*bp[k] + ap[k+1]*bp[k+1] + ap[k+2]*bp[k+2] + ap[k+3]*bp[k+3] + ap[k+4]*bp[k+4] + ap[k+5]*bp[k+5] + ap[k+6]*bp[k+6] + ap[k+7]*bp[k+7]; tmp1 += ap[k]*bpp[k] + ap[k+1]*bpp[k+1] + ap[k+2]*bpp[k+2] + ap[k+3]*bpp[k+3] + ap[k+4]*bpp[k+4] + ap[k+5]*bpp[k+5] + ap[k+6]*bpp[k+6] + ap[k+7]*bpp[k+7]; } c[i][j]-=tmp; c[i][j+1]-=tmp1; } } } // use sse2 for dot product void matmul_for_small_nk_5(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; int nh = n/2; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; double acopyd[kk]; for(j=0;j<nh;j++) for(k=0;k<kk;k++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ double *ap=a[i]; double *acp = (double*) acopy; register v2df tmp= (v2df){0.0,0.0}; v2df * cp = (v2df*) (&(c[i][0])); for(k=0;k<kk;k+=4){ __builtin_prefetch((double*)a[i+4]+k,0); } for(j=0;j<n;j+=4){ __builtin_prefetch(c[i+4]+j,0); } for(k=0;k<kk;k+=2){ // v2df aa = *((v2df*)(ap+k)); // acopy[k]=__builtin_ia32_shufpd(aa,aa,0x0); // acopy[k+1]= __builtin_ia32_shufpd(aa,aa,0x5); acp[k*2]=acp[k*2+1]=ap[k]; acp[k*2+2]=acp[k*2+3]=ap[k+1]; } for(j=0;j<nh;j++){ tmp = (v2df){0.0,0.0}; v2df * bp = bcopy2[j]; for(k=0;k<kk;k+=2){ tmp += acopy[k]*bp[k] +acopy[k+1]*bp[k+1] #if 0 +acopy[k+2]*bp[k+2] +acopy[k+3]*bp[k+3] +acopy[k+4]*bp[k+4] +acopy[k+5]*bp[k+5] +acopy[k+6]*bp[k+6] +acopy[k+7]*bp[k+7] #endif ; } cp[j] -= tmp; } } } // use sse2 for dot product void matmul_for_small_nk_6(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j,k; int nh = n/2; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; v2df acopy3[kk]; v2df acopy4[kk]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; double *acp3 = (double*) acopy3; double *acp4 = (double*) acopy4; for(j=0;j<nh;j++) for(k=0;k<kk;k++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i+=4){ double *ap=a[i]; double *ap2=a[i+1]; double *ap3=a[i+2]; double *ap4=a[i+3]; register v2df tmp, tmp2, tmp3, tmp4; v2df * cp = (v2df*) (&(c[i][0])); v2df * cp2 = (v2df*) (&(c[i+1][0])); v2df * cp3 = (v2df*) (&(c[i+2][0])); v2df * cp4 = (v2df*) (&(c[i+3][0])); for(k=0;k<kk;k+=4){ __builtin_prefetch((double*)a[i+4]+k,0); __builtin_prefetch((double*)a[i+5]+k,0); __builtin_prefetch((double*)a[i+6]+k,0); __builtin_prefetch((double*)a[i+7]+k,0); __builtin_prefetch(c[i+4]+j,0); __builtin_prefetch(c[i+5]+j,0); __builtin_prefetch(c[i+6]+j,0); __builtin_prefetch(c[i+7]+j,0); } for(k=0;k<kk;k+=2){ v2df * aa = (v2df*)(ap+k); acopy [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa = (v2df*)(ap2+k); acopy2 [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); // acp[k*2]=acp[k*2+1]=ap[k]; // acp[k*2+2]=acp[k*2+3]=ap[k+1]; // acp2[k*2]=acp2[k*2+1]=ap2[k]; // acp2[k*2+2]=acp2[k*2+3]=ap2[k+1]; } for(k=0;k<kk;k+=2){ acp3[k*2]=acp3[k*2+1]=ap3[k]; acp3[k*2+2]=acp3[k*2+3]=ap3[k+1]; acp4[k*2]=acp4[k*2+1]=ap4[k]; acp4[k*2+2]=acp4[k*2+3]=ap4[k+1]; } for(j=0;j<nh;j++){ tmp = tmp2= tmp3= tmp4= (v2df){0.0,0.0}; v2df * bp = bcopy2[j]; #if 0 for(k=0;k<kk;k+=4){ tmp += acopy[k]*bp[k] +acopy[k+1]*bp[k+1] +acopy[k+2]*bp[k+2] +acopy[k+3]*bp[k+3]; tmp2 += acopy2[k]*bp[k] +acopy2[k+1]*bp[k+1] +acopy2[k+2]*bp[k+2] +acopy2[k+3]*bp[k+3]; tmp3 += acopy3[k]*bp[k] +acopy3[k+1]*bp[k+1] +acopy3[k+2]*bp[k+2] +acopy3[k+3]*bp[k+3]; tmp4 += acopy4[k]*bp[k] +acopy4[k+1]*bp[k+1] +acopy4[k+2]*bp[k+2] +acopy4[k+3]*bp[k+3]; } #endif for(k=0;k<kk;k+=2){ tmp += acopy[k]*bp[k] +acopy[k+1]*bp[k+1]; tmp2 += acopy2[k]*bp[k] +acopy2[k+1]*bp[k+1]; tmp3 += acopy3[k]*bp[k] +acopy3[k+1]*bp[k+1]; tmp4 += acopy4[k]*bp[k] +acopy4[k+1]*bp[k+1]; } cp[j] -= tmp; cp2[j] -= tmp2; cp3[j] -= tmp3; cp4[j] -= tmp4; } } } void matmul_for_small_nk7(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; // BEGIN_TSC; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); // END_TSC(bpcount); for(i=0;i<m;i+=2){ // BEGIN_TSC; double *ap=a[i]; double *ap2=a[i+1]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * cp2 = (v2df*) (&(c[i+1][0])); for(k=0;k<kk;k+=2){ v2df * aa = (v2df*)(ap+k); __builtin_prefetch((double*)a[i+4]+k,0); __builtin_prefetch((double*)a[i+5]+k,0); acopy [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa = (v2df*)(ap2+k); acopy2 [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); // acp[k*2]=acp[k*2+1]=ap[k]; // acp[k*2+2]=acp[k*2+3]=ap[k+1]; // acp2[k*2]=acp2[k*2+1]=ap2[k]; // acp2[k*2+2]=acp2[k*2+3]=ap2[k+1]; } // END_TSC(apcount); // BEGIN_TSC; for(j=0;j<nh;j++){ tmp = tmp2= (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df ctmp2 = cp2[j] ; v2df * bp = bcopy2[j]; __builtin_prefetch(c[i+4]+j,0); __builtin_prefetch(c[i+5]+j,0); for(k=0;k<kk;k+=8){ int k2 = k+4; v2df *avp = acopy+k; v2df *avp2 = acopy2+k; v2df *bvp = bp+k; tmp += avp[0]*bvp[0]; tmp2 += avp2[0]*bvp[0]; tmp +=avp[1]*bvp[1]; tmp2+=avp2[1]*bvp[1]; tmp +=avp[2]*bvp[2]; tmp2+=avp2[2]*bvp[2]; tmp +=avp[3]*bvp[3]; tmp2+=avp2[3]*bvp[3]; tmp += avp[4]*bvp[4]; tmp2 += avp2[4]*bvp[4]; tmp +=avp[5]*bvp[5]; tmp2+=avp2[5]*bvp[5]; tmp +=avp[6]*bvp[6]; tmp2+=avp2[6]*bvp[6]; tmp +=avp[7]*bvp[7]; tmp2+=avp2[7]*bvp[7]; } #if 0 for(k=0;k<kk;k+=8){ int k2 = k+4; tmp += acopy[k]*bp[k]; tmp2 += acopy2[k]*bp[k]; tmp +=acopy[k+1]*bp[k+1]; tmp2+=acopy2[k+1]*bp[k+1]; tmp +=acopy[k+2]*bp[k+2]; tmp2+=acopy2[k+2]*bp[k+2]; tmp +=acopy[k+3]*bp[k+3]; tmp2+=acopy2[k+3]*bp[k+3]; tmp += acopy[k2]*bp[k2]; tmp2 += acopy2[k2]*bp[k2]; tmp +=acopy[k2+1]*bp[k2+1]; tmp2+=acopy2[k2+1]*bp[k2+1]; tmp +=acopy[k2+2]*bp[k2+2]; tmp2+=acopy2[k2+2]*bp[k2+2]; tmp +=acopy[k2+3]*bp[k2+3]; tmp2+=acopy2[k2+3]*bp[k2+3]; } #endif #if 0 for(k=0;k<kk;k+=2){ tmp += acopy[k]*bp[k]; tmp __builtin_prefetch(c[i+4+(j&1)]+j,0); +=acopy[k+1]*bp[k+1]; tmp2 += acopy2[k]*bp[k]; tmp2+=acopy2[k+1]*bp[k+1]; } #endif cp[j] = ctmp -tmp; cp2[j] = ctmp2 -tmp2; } // END_TSC(dotcount); } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } // XMM registers #define X0 "%xmm0" #define X1 "%xmm1" #define X2 "%xmm2" #define X3 "%xmm3" #define X4 "%xmm4" #define X5 "%xmm5" #define X6 "%xmm6" #define X7 "%xmm7" #define X8 "%xmm8" #define X9 "%xmm9" #define X10 "%xmm10" #define X11 "%xmm11" #define X12 "%xmm12" #define X13 "%xmm13" #define X14 "%xmm14" #define X15 "%xmm15" #define LOADPD(mem, reg) asm("movapd %0, %"reg::"m"(mem)); #define STORPD(reg, mem) asm("movapd %"reg " , %0"::"m"(mem)); #define MOVNTPD(reg, mem) asm("movntpd %"reg " , %0"::"m"(mem)); #define MOVAPD(src, dst) asm("movapd " src "," dst); #define MOVQ(src, dst) asm("movq " src "," dst); #define BCAST0(reg) asm("shufpd $0x00, " reg "," reg); #define BCAST1(reg) asm("shufpd $0xff, " reg "," reg); #define MULPD(src, dst) asm("mulpd " src "," dst); #define ADDPD(src, dst) asm("addpd " src "," dst); #define SUBPD(src, dst) asm("subpd " src "," dst); void matmul_for_nk8_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 8; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; #define PREFETCHL 32 for(i=0;i<PREFETCHL;i++){ __builtin_prefetch((double*)a[i],0,0); __builtin_prefetch(c[i+8],1,0); } for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; // v2df acopy[8]; v2df *ap = (v2df*) a[i]; v2df * cp = (v2df*) (&(c[i][0])); __builtin_prefetch((double*)a[i+PREFETCHL],0,0); int k; for(j=0;j<nh;j+=4){ __builtin_prefetch(c[i+PREFETCHL]+j,1,3); v2df * bvp0 = bcopy2[j]; v2df * bvp1 = bcopy2[j+1]; v2df * bvp2 = bcopy2[j+2]; v2df * bvp3 = bcopy2[j+3]; LOADPD(cp[j],X12); LOADPD(cp[j+1],X13); LOADPD(cp[j+2],X14); LOADPD(cp[j+3],X15); LOADPD(ap[0],X0); LOADPD(bvp0[0],X4); LOADPD(bvp1[0],X5); LOADPD(bvp2[0],X6); LOADPD(bvp3[0],X7); LOADPD(bvp0[1],X8); LOADPD(bvp1[1],X9); LOADPD(bvp2[1],X10); LOADPD(bvp3[1],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[1],X0); LOADPD(bvp0[2],X4); LOADPD(bvp1[2],X5); LOADPD(bvp2[2],X6); LOADPD(bvp3[2],X7); LOADPD(bvp0[3],X8); LOADPD(bvp1[3],X9); LOADPD(bvp2[3],X10); LOADPD(bvp3[3],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[2],X0); LOADPD(bvp0[4],X4); LOADPD(bvp1[4],X5); LOADPD(bvp2[4],X6); LOADPD(bvp3[4],X7); LOADPD(bvp0[5],X8); LOADPD(bvp1[5],X9); LOADPD(bvp2[5],X10); LOADPD(bvp3[5],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[3],X0); LOADPD(bvp0[6],X4); LOADPD(bvp1[6],X5); LOADPD(bvp2[6],X6); LOADPD(bvp3[6],X7); LOADPD(bvp0[7],X8); LOADPD(bvp1[7],X9); LOADPD(bvp2[7],X10); LOADPD(bvp3[7],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); STORPD(X12,cp[j+0]); STORPD(X13,cp[j+1]); STORPD(X14,cp[j+2]); STORPD(X15,cp[j+3]); } } } void matmul_for_nk16_0a(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 16; int nh = n/2; register int k; v2df bcopy2[nh][kk]; #ifdef PREFETCHL #undef PREFETCHL #endif #define PREFETCHL 32 for(i=0;i<PREFETCHL;i++){ __builtin_prefetch((double*)a[i],0,0); __builtin_prefetch((double*)a[i]+8,0,0); __builtin_prefetch(c[i+8],1,0); __builtin_prefetch(c[i+8]+8,1,0); } for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i+=2){ // BEGIN_TSC; v2df *ap = (v2df*) a[i]; v2df * cp = (v2df*) (&(c[i][0])); v2df *app = (v2df*) a[i+1]; v2df * cpp = (v2df*) (&(c[i+1][0])); __builtin_prefetch((double*)a[i+PREFETCHL],0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0); __builtin_prefetch((double*)a[i+PREFETCHL+1],0,0); __builtin_prefetch((double*)a[i+PREFETCHL+1]+8,0,0); int k; for(j=0;j<nh;j+=2){ __builtin_prefetch(c[i+PREFETCHL]+j,1,0); v2df * bvp0 = bcopy2[j]; v2df * bvp1 = bcopy2[j+1]; LOADPD(cp[j],X12); LOADPD(cp[j+1],X13); LOADPD(cpp[j],X14); LOADPD(cpp[j+1],X15); for(k=0;k<8;k++){ LOADPD(ap[k],X0); LOADPD(app[k],X2); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MOVAPD(X2,X3); BCAST0(X2); BCAST1(X3); LOADPD(bvp0[k*2],X4); MOVAPD(X4,X6); MULPD(X0,X4); SUBPD(X4,X12); LOADPD(bvp1[k*2],X5); MOVAPD(X5,X7); MULPD(X0,X5); SUBPD(X5,X13); LOADPD(bvp0[k*2+1],X8); MOVAPD(X8,X10); MULPD(X1,X8); SUBPD(X8,X12); LOADPD(bvp1[k*2+1],X9); MOVAPD(X9,X11); MULPD(X1,X9); SUBPD(X9,X13); MULPD(X2,X6); SUBPD(X6,X14); MULPD(X2,X7); SUBPD(X7,X15); MULPD(X3,X10); SUBPD(X10,X14); MULPD(X3,X11); SUBPD(X11,X15); } STORPD(X12,cp[j+0]); STORPD(X13,cp[j+1]); STORPD(X14,cpp[j+0]); STORPD(X15,cpp[j+1]); } } } void matmul_for_nk16_0c(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 16; int nh = n/2; register int k; v2df bcopy2[nh][kk]; #ifdef PREFETCHL #undef PREFETCHL #endif #define PREFETCHL 16 for(i=0;i<PREFETCHL;i++){ __builtin_prefetch((double*)a[i],0,0); __builtin_prefetch((double*)a[i]+8,0,0); __builtin_prefetch(c[i+8],1,0); __builtin_prefetch(c[i+8]+8,1,0); } for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; v2df *ap = (v2df*) a[i]; v2df * cp = (v2df*) (&(c[i][0])); __builtin_prefetch((double*)a[i+PREFETCHL],0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0); int k; for(j=0;j<nh;j+=4){ __builtin_prefetch(c[i+PREFETCHL]+j,1,0); v2df * bvp0 = bcopy2[j]; v2df * bvp1 = bcopy2[j+1]; v2df * bvp2 = bcopy2[j+2]; v2df * bvp3 = bcopy2[j+3]; LOADPD(cp[j],X12); LOADPD(cp[j+1],X13); LOADPD(cp[j+2],X14); LOADPD(cp[j+3],X15); for(k=0;k<8;k++){ LOADPD(ap[k],X0); LOADPD(bvp0[k*2],X4); LOADPD(bvp1[k*2],X5); LOADPD(bvp2[k*2],X6); LOADPD(bvp3[k*2],X7); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); LOADPD(bvp0[k*2+1],X8); LOADPD(bvp1[k*2+1],X9); LOADPD(bvp2[k*2+1],X10); LOADPD(bvp3[k*2+1],X11); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); } STORPD(X12,cp[j+0]); STORPD(X13,cp[j+1]); STORPD(X14,cp[j+2]); STORPD(X15,cp[j+3]); } } } void matmul_for_nk32_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 32; int nh = n/2; register int k; v2df bcopy2[nh][kk]; #ifdef PREFETCHL #undef PREFETCHL #endif #define PREFETCHL 8 for(i=0;i<PREFETCHL;i++){ __builtin_prefetch((double*)a[i],0,0); __builtin_prefetch((double*)a[i]+8,0,0); __builtin_prefetch((double*)a[i]+16,0,0); __builtin_prefetch((double*)a[i]+24,0,0); __builtin_prefetch(c[i+8],1,0); __builtin_prefetch(c[i+8]+8,1,0); __builtin_prefetch(c[i+8]+16,1,0); __builtin_prefetch(c[i+8]+24,1,0); } for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; v2df *ap = (v2df*) a[i]; v2df * cp = (v2df*) (&(c[i][0])); __builtin_prefetch((double*)a[i+PREFETCHL],0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+16,0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+24,0,0); int k; for(j=0;j<nh;j+=4){ __builtin_prefetch(c[i+PREFETCHL]+j,1,0); v2df * bvp0 = bcopy2[j]; v2df * bvp1 = bcopy2[j+1]; v2df * bvp2 = bcopy2[j+2]; v2df * bvp3 = bcopy2[j+3]; LOADPD(cp[j],X12); LOADPD(cp[j+1],X13); LOADPD(cp[j+2],X14); LOADPD(cp[j+3],X15); for(k=0;k<16;k++){ LOADPD(ap[k],X0); LOADPD(bvp0[k*2],X4); LOADPD(bvp1[k*2],X5); LOADPD(bvp2[k*2],X6); LOADPD(bvp3[k*2],X7); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); LOADPD(bvp0[k*2+1],X8); LOADPD(bvp1[k*2+1],X9); LOADPD(bvp2[k*2+1],X10); LOADPD(bvp3[k*2+1],X11); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); } STORPD(X12,cp[j+0]); STORPD(X13,cp[j+1]); STORPD(X14,cp[j+2]); STORPD(X15,cp[j+3]); } } } void matmul_for_nk16_0b(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 16; int nh = n/2; register int k; v2df bcopy2[nh][kk]; #ifdef PREFETCHL #undef PREFETCHL #endif #define PREFETCHL 16 for(i=0;i<PREFETCHL;i++){ __builtin_prefetch((double*)a[i],0,0); __builtin_prefetch((double*)a[i]+8,0,0); __builtin_prefetch(c[i+8],1,0); __builtin_prefetch(c[i+8]+8,1,0); } for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; v2df *ap = (v2df*) a[i]; v2df * cp = (v2df*) (&(c[i][0])); __builtin_prefetch((double*)a[i+PREFETCHL],0,0); __builtin_prefetch((double*)a[i+PREFETCHL]+8,0,0); int k; for(j=0;j<nh;j+=4){ __builtin_prefetch(c[i+PREFETCHL]+j,1,0); v2df * bvp0 = bcopy2[j]; v2df * bvp1 = bcopy2[j+1]; v2df * bvp2 = bcopy2[j+2]; v2df * bvp3 = bcopy2[j+3]; LOADPD(cp[j],X12); LOADPD(cp[j+1],X13); LOADPD(cp[j+2],X14); LOADPD(cp[j+3],X15); LOADPD(ap[0],X0); LOADPD(bvp0[0],X4); LOADPD(bvp1[0],X5); LOADPD(bvp2[0],X6); LOADPD(bvp3[0],X7); LOADPD(bvp0[1],X8); LOADPD(bvp1[1],X9); LOADPD(bvp2[1],X10); LOADPD(bvp3[1],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[1],X0); LOADPD(bvp0[2],X4); LOADPD(bvp1[2],X5); LOADPD(bvp2[2],X6); LOADPD(bvp3[2],X7); LOADPD(bvp0[3],X8); LOADPD(bvp1[3],X9); LOADPD(bvp2[3],X10); LOADPD(bvp3[3],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[2],X0); LOADPD(bvp0[4],X4); LOADPD(bvp1[4],X5); LOADPD(bvp2[4],X6); LOADPD(bvp3[4],X7); LOADPD(bvp0[5],X8); LOADPD(bvp1[5],X9); LOADPD(bvp2[5],X10); LOADPD(bvp3[5],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[3],X0); LOADPD(bvp0[6],X4); LOADPD(bvp1[6],X5); LOADPD(bvp2[6],X6); LOADPD(bvp3[6],X7); LOADPD(bvp0[7],X8); LOADPD(bvp1[7],X9); LOADPD(bvp2[7],X10); LOADPD(bvp3[7],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[4],X0); LOADPD(bvp0[8],X4); LOADPD(bvp1[8],X5); LOADPD(bvp2[8],X6); LOADPD(bvp3[8],X7); LOADPD(bvp0[9],X8); LOADPD(bvp1[9],X9); LOADPD(bvp2[9],X10); LOADPD(bvp3[9],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[5],X0); LOADPD(bvp0[10],X4); LOADPD(bvp1[10],X5); LOADPD(bvp2[10],X6); LOADPD(bvp3[10],X7); LOADPD(bvp0[11],X8); LOADPD(bvp1[11],X9); LOADPD(bvp2[11],X10); LOADPD(bvp3[11],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[6],X0); LOADPD(bvp0[12],X4); LOADPD(bvp1[12],X5); LOADPD(bvp2[12],X6); LOADPD(bvp3[12],X7); LOADPD(bvp0[13],X8); LOADPD(bvp1[13],X9); LOADPD(bvp2[13],X10); LOADPD(bvp3[13],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); LOADPD(ap[7],X0); LOADPD(bvp0[14],X4); LOADPD(bvp1[14],X5); LOADPD(bvp2[14],X6); LOADPD(bvp3[14],X7); LOADPD(bvp0[15],X8); LOADPD(bvp1[15],X9); LOADPD(bvp2[15],X10); LOADPD(bvp3[15],X11); MOVAPD(X0,X1); BCAST0(X0); BCAST1(X1); MULPD(X0,X4); MULPD(X0,X5); MULPD(X0,X6); MULPD(X0,X7); MULPD(X1,X8); MULPD(X1,X9); MULPD(X1,X10); MULPD(X1,X11); SUBPD(X4,X12); SUBPD(X5,X13); SUBPD(X6,X14); SUBPD(X7,X15); SUBPD(X8,X12); SUBPD(X9,X13); SUBPD(X10,X14); SUBPD(X11,X15); STORPD(X12,cp[j+0]); STORPD(X13,cp[j+1]); STORPD(X14,cp[j+2]); STORPD(X15,cp[j+3]); } } } void matmul_for_nk8_0d(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 8; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; v2df awork[4]; v2df awork2[4]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; double *ap=a[i]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * aa = (v2df*)(ap); __builtin_prefetch((double*)a[i+8],0,0); v2df acopy0=(v2df){a[i][0], a[i][0]}; v2df acopy1=(v2df){a[i][1], a[i][1]}; v2df acopy2=(v2df){a[i][2], a[i][2]}; v2df acopy3=(v2df){a[i][3], a[i][3]}; v2df acopy4=(v2df){a[i][4], a[i][4]}; v2df acopy5=(v2df){a[i][5], a[i][5]}; v2df acopy6=(v2df){a[i][6], a[i][6]}; v2df acopy7=(v2df){a[i][7], a[i][7]}; v2df zero=(v2df){0.0, 0.0}; LOADPD(acopy0,X0); LOADPD(acopy1,X1); LOADPD(acopy2,X2); LOADPD(acopy3,X3); LOADPD(acopy4,X4); LOADPD(acopy5,X5); LOADPD(acopy6,X6); LOADPD(acopy7,X7); for(j=0;j<nh;j++){ __builtin_prefetch(c[i+8]+j,1,0); v2df * bvp = bcopy2[j]; LOADPD(cp[j],X14); LOADPD(bvp[0],X8); LOADPD(bvp[1],X9); MULPD(X0,X8); MULPD(X1,X9); LOADPD(bvp[2],X10); LOADPD(bvp[3],X11); ADDPD(X9,X8); MULPD(X2,X10); MULPD(X3,X11); ADDPD(X11,X10); LOADPD(bvp[4],X9); LOADPD(bvp[5],X11); LOADPD(bvp[6],X12); LOADPD(bvp[7],X13); MULPD(X4,X9); MULPD(X5,X11); ADDPD(X10,X8); ADDPD(X11,X9); MULPD(X6,X12); MULPD(X7,X13); ADDPD(X13,X12); ADDPD(X9,X8); ADDPD(X12,X8); SUBPD(X8,X14); STORPD(X14,cp[j]); } } } void matmul_for_nk8_0c(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 8; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; v2df awork[4]; v2df awork2[4]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; double *ap=a[i]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * aa = (v2df*)(ap); __builtin_prefetch((double*)a[i+8],0,0); register v2df acopy0=(v2df){a[i][0], a[i][0]}; register v2df acopy1=(v2df){a[i][1], a[i][1]}; register v2df acopy2=(v2df){a[i][2], a[i][2]}; register v2df acopy3=(v2df){a[i][3], a[i][3]}; register v2df acopy4=(v2df){a[i][4], a[i][4]}; register v2df acopy5=(v2df){a[i][5], a[i][5]}; register v2df acopy6=(v2df){a[i][6], a[i][6]}; register v2df acopy7=(v2df){a[i][7], a[i][7]}; for(j=0;j<nh;j++){ tmp = (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df * bp = bcopy2[j]; __builtin_prefetch(c[i+4]+j,1,0); v2df *bvp = bp; tmp += acopy0*bvp[0]; tmp +=acopy1*bvp[1]; tmp +=acopy2*bvp[2]; tmp +=acopy3*bvp[3]; tmp +=acopy4*bvp[4]; tmp +=acopy5*bvp[5]; tmp +=acopy6*bvp[6]; tmp +=acopy7*bvp[7]; cp[j] = ctmp -tmp; } } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } void matmul_for_nk8_0b(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 8; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; v2df awork[4]; v2df awork2[4]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i++){ // BEGIN_TSC; double *ap=a[i]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * aa = (v2df*)(ap); __builtin_prefetch((double*)a[i+8],0,0); acopy[0]=(v2df){a[i][0], a[i][0]}; acopy[1]=(v2df){a[i][1], a[i][1]}; acopy[2]=(v2df){a[i][2], a[i][2]}; acopy[3]=(v2df){a[i][3], a[i][3]}; acopy[4]=(v2df){a[i][4], a[i][4]}; acopy[5]=(v2df){a[i][5], a[i][5]}; acopy[6]=(v2df){a[i][6], a[i][6]}; acopy[7]=(v2df){a[i][7], a[i][7]}; for(j=0;j<nh;j++){ tmp = tmp2= (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df * bp = bcopy2[j]; __builtin_prefetch(c[i+4]+j,1,0); v2df *avp = acopy; v2df *bvp = bp; tmp += avp[0]*bvp[0]; tmp +=avp[1]*bvp[1]; tmp +=avp[2]*bvp[2]; tmp +=avp[3]*bvp[3]; tmp += avp[4]*bvp[4]; tmp +=avp[5]*bvp[5]; tmp +=avp[6]*bvp[6]; tmp +=avp[7]*bvp[7]; cp[j] = ctmp -tmp; } } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } void matmul_for_nk8_0a(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j; int kk = 8; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; v2df awork[4]; v2df awork2[4]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); for(i=0;i<m;i+=2){ // BEGIN_TSC; double *ap=a[i]; double *ap2=a[i+1]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * cp2 = (v2df*) (&(c[i+1][0])); v2df * aa = (v2df*)(ap); __builtin_prefetch((double*)a[i+8],0,0); __builtin_prefetch((double*)a[i+9],0,0); acopy[0]=(v2df){a[i][0], a[i][0]}; acopy[1]=(v2df){a[i][1], a[i][1]}; acopy[2]=(v2df){a[i][2], a[i][2]}; acopy[3]=(v2df){a[i][3], a[i][3]}; acopy[4]=(v2df){a[i][4], a[i][4]}; acopy[5]=(v2df){a[i][5], a[i][5]}; acopy[6]=(v2df){a[i][6], a[i][6]}; acopy[7]=(v2df){a[i][7], a[i][7]}; aa = (v2df*)(ap2); acopy2[0]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa++; acopy2[2]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[3]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa++; acopy2[4]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[5]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa++; acopy2[6]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[7]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa++; for(j=0;j<nh;j++){ tmp = tmp2= (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df ctmp2 = cp2[j] ; v2df * bp = bcopy2[j]; __builtin_prefetch(c[i+4]+j,1,0); __builtin_prefetch(c[i+5]+j,1,0); v2df *avp = acopy; v2df *avp2 = acopy2; v2df *bvp = bp; tmp += avp[0]*bvp[0]; tmp2 += avp2[0]*bvp[0]; tmp +=avp[1]*bvp[1]; tmp2+=avp2[1]*bvp[1]; tmp +=avp[2]*bvp[2]; tmp2+=avp2[2]*bvp[2]; tmp +=avp[3]*bvp[3]; tmp2+=avp2[3]*bvp[3]; tmp += avp[4]*bvp[4]; tmp2 += avp2[4]*bvp[4]; tmp +=avp[5]*bvp[5]; tmp2+=avp2[5]*bvp[5]; tmp +=avp[6]*bvp[6]; tmp2+=avp2[6]*bvp[6]; tmp +=avp[7]*bvp[7]; tmp2+=avp2[7]*bvp[7]; cp[j] = ctmp -tmp; cp2[j] = ctmp2 -tmp2; } } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } void matmul_for_nk8_1(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j,k; const int kk = 8; const int kh = kk/2; int nh = n/2; v2df bcopy[n][kh]; v2df acopy[kk][kh]; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(j=0;j<n;j++) for(k=0;k<kh;k++) bcopy[j][k] = (v2df){b[k*2][j],b[k*2+1][j]}; // printf("copy b end\n"); for(i=0;i<m;i+=kk){ for(k=0;k<kk;k++){ v2df *ak = (v2df*)(a[i+k]); v2df * awp =acopy+k; awp[0]=ak[0]; awp[1]=ak[1]; awp[2]=ak[2]; awp[3]=ak[3]; } // printf("copy a end\n"); for(k=0;k<kk;k++){ v2u tmp, tmp1; v2df * ap = acopy[k]; for(j=0;j<n;j+=2){ tmp.v = ap[0]*bcopy[j][0] + ap[1]*bcopy[j][1] + ap[2]*bcopy[j][2] + ap[3]*bcopy[j][3]; tmp1.v = ap[0]*bcopy[j+1][0] + ap[1]*bcopy[j+1][1] + ap[2]*bcopy[j+1][2] + ap[3]*bcopy[j+1][3]; c[k+i][j] -= tmp.s[0]+tmp.s[1]; c[k+i][j+1] -= tmp1.s[0]+tmp1.s[1]; } } // printf("calc c end\n"); } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } void matmul_for_nk8_2(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j,k; const int kk = 8; const int kh = kk/2; int nh = n/2; v2df bcopy[nh][kk]; v2df acopy[kk][kh]; v2df ccopy[kk][kh]; v2df acopy2[kk][kk]; unsigned long bpcount, apcount, dotcount; bpcount= apcount= dotcount=0; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy[j][k] = *((v2df*)(b[k]+j+j)); // printf("copy b end\n"); for(i=0;i<m;i+=kk){ for(k=0;k<kk;k++){ __builtin_prefetch(a+i+k+8,0,0); __builtin_prefetch(c+i+k+8,1,0); v2df *ak = (v2df*)(a[i+k]); v2df * awp = (v2df*)(acopy+k); v2df *ck = (v2df*)(c[i+k]); v2df * cwp = (v2df*)(ccopy+k); awp[0]=ak[0]; awp[1]=ak[1]; awp[2]=ak[2]; awp[3]=ak[3]; cwp[0]=ck[0]; cwp[1]=ck[1]; cwp[2]=ck[2]; cwp[3]=ck[3]; } for (j=0;j<n;j++){ double * ap = (double*)( acopy+j); for (k=0;k<kk;k++){ acopy2[j][k]=(v2df){ap[k],ap[k]}; } } // printf("copy a end\n"); for(k=0;k<kk;k++){ v2df * cp = (v2df*) ccopy[k]; v2df * ap = acopy2[k]; for(j=0;j<nh;j++){ v2df * bp = bcopy[j]; cp[j] -= ap[0]*bp[0] + ap[1]*bp[1] + ap[2]*bp[2] + ap[3]*bp[3] + ap[4]*bp[4] + ap[5]*bp[5] + ap[6]*bp[6] + ap[7]*bp[7]; } } for(k=0;k<kk;k++){ v2df *ck = (v2df*)(c[i+k]); v2df * cwp = (v2df*)(ccopy+k); #if 0 ck[0] = cwp[0]; ck[1] = cwp[1]; ck[2] = cwp[2]; ck[3] = cwp[3]; #endif __builtin_ia32_movntpd((double*)(ck),cwp[0]); __builtin_ia32_movntpd((double*)(ck+1),cwp[1]); __builtin_ia32_movntpd((double*)(ck+2),cwp[2]); __builtin_ia32_movntpd((double*)(ck+3),cwp[3]); } // printf("calc c end\n"); } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); } void matmul_for_nk8(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i,j,k; const int kk = 8; const int kh = kk/2; int nh = n/2; v2df bcopy[nh][kk]; v2df acopy2[kk][kk]; // unsigned long bpcount, apcount, dotcount; // bpcount= apcount= dotcount=0; BEGIN_TSC; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy[j][k] = *((v2df*)(b[k]+j+j)); // END_TSC(bpcount); // printf("copy b end\n"); #pragma omp parallel for private(i,j,k,acopy2) schedule(static) for(i=0;i<m;i+=kk){ // BEGIN_TSC; for(k=0;k<kk;k++){ __builtin_prefetch(a+i+k+16,0,0); __builtin_prefetch(c+i+k+16,1,0); } for (j=0;j<n;j++){ double * ap = (double*)( a[i+j]); for (k=0;k<kk;k++){ acopy2[j][k]=(v2df){ap[k],ap[k]}; } } // END_TSC(apcount); // printf("copy a end\n"); // BEGIN_TSC; for(k=0;k<kk;k++){ v2df * cp = (v2df*) (c[i+k]); v2df * ap = acopy2[k]; for(j=0;j<nh;j++){ v2df * bp = bcopy[j]; cp[j] -= ap[0]*bp[0] + ap[1]*bp[1] + ap[2]*bp[2] + ap[3]*bp[3] + ap[4]*bp[4] + ap[5]*bp[5] + ap[6]*bp[6] + ap[7]*bp[7]; } } // printf("calc c end\n"); // END_TSC(dotcount); } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); END_TSC(t,10); } void matmul_for_nk8_3(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int ii; int dm = (m+31)/32; dm*= 8; #pragma omp parallel for private(ii) schedule(static) for(ii=0;ii<4;ii++){ int ifirst, iend; ifirst = ii*dm; iend = ifirst+dm; if (iend > m) iend = m; // fprintf(stderr, "m, i, ifirst, iend = %d %d %d %d\n", m, ii, ifirst, iend); if (ifirst < m){ matmul_for_nk8_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n); } } } void matmul_for_nk16_0(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int i; int mm=64; for(i=0;i<m;i+=mm){ if (i+mm >m) mm=m-i; matmul_for_nk8_0(n1, (double(*)[]) (a[i]), n2, b, n3, (double(*)[]) (c[i]), mm, 16); matmul_for_nk8_0(n1, (double(*)[]) (&a[i][8]), n2,(double(*)[])(b[8]), n3, (double(*)[]) (c[i]), mm, 16); } } void matmul_for_nk16(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { if (m < 64){ matmul_for_nk16_0c(n1, a, n2, b, n3, c, m, n); return; } int ii; int dm = (m+63)/64; dm*= 16; #pragma omp parallel for private(ii) schedule(static) for(ii=0;ii<4;ii++){ int ifirst, iend; ifirst = ii*dm; iend = ifirst+dm; if (iend > m) iend = m; // fprintf(stderr, "m, i, ifirst, iend = %d %d %d %d\n", m, ii, ifirst, iend); if (ifirst < m){ matmul_for_nk16_0c(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n); } } } void matmul_for_nk32(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int n) { int ii; int dm = (m+127)/128; dm*= 32; #pragma omp parallel for private(ii) schedule(static) for(ii=0;ii<4;ii++){ int ifirst, iend; ifirst = ii*dm; iend = ifirst+dm; if (iend > m) iend = m; // fprintf(stderr, "m, i, ifirst, iend = %d %d %d %d\n", m, ii, ifirst, iend); if (ifirst < m){ matmul_for_nk32_0(n1, a[ifirst], n2, b, n3, c[ifirst], iend-ifirst, n); } } } void matmul_for_small_nk_7(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,j; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; unsigned long bpcount, apcount, dotcount; if (kk == 8){ matmul_for_nk8(n1, a, n2, b, n3, c, m, n); return; } BEGIN_TSC; bpcount= apcount= dotcount=0; // BEGIN_TSC; for(k=0;k<kk;k++) for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); // END_TSC(bpcount); for(i=0;i<m;i+=2){ // BEGIN_TSC; double *ap=a[i]; double *ap2=a[i+1]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * cp2 = (v2df*) (&(c[i+1][0])); for(k=0;k<kk;k+=2){ v2df * aa = (v2df*)(ap+k); __builtin_prefetch((double*)a[i+4]+k,0); __builtin_prefetch((double*)a[i+5]+k,0); acopy [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa = (v2df*)(ap2+k); acopy2 [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); // acp[k*2]=acp[k*2+1]=ap[k]; // acp[k*2+2]=acp[k*2+3]=ap[k+1]; // acp2[k*2]=acp2[k*2+1]=ap2[k]; // acp2[k*2+2]=acp2[k*2+3]=ap2[k+1]; } // END_TSC(apcount); // BEGIN_TSC; for(j=0;j<nh;j++){ tmp = tmp2= (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df ctmp2 = cp2[j] ; v2df * bp = bcopy2[j]; __builtin_prefetch(c[i+4]+j,0); __builtin_prefetch(c[i+5]+j,0); for(k=0;k<kk;k+=8){ int k2 = k+4; v2df *avp = acopy+k; v2df *avp2 = acopy2+k; v2df *bvp = bp+k; tmp += avp[0]*bvp[0]; tmp2 += avp2[0]*bvp[0]; tmp +=avp[1]*bvp[1]; tmp2+=avp2[1]*bvp[1]; tmp +=avp[2]*bvp[2]; tmp2+=avp2[2]*bvp[2]; tmp +=avp[3]*bvp[3]; tmp2+=avp2[3]*bvp[3]; tmp += avp[4]*bvp[4]; tmp2 += avp2[4]*bvp[4]; tmp +=avp[5]*bvp[5]; tmp2+=avp2[5]*bvp[5]; tmp +=avp[6]*bvp[6]; tmp2+=avp2[6]*bvp[6]; tmp +=avp[7]*bvp[7]; tmp2+=avp2[7]*bvp[7]; } cp[j] = ctmp -tmp; cp2[j] = ctmp2 -tmp2; } // END_TSC(dotcount); } // printf("m, kk, n = %d %d %d counts = %g %g %g\n", m,kk,n, // (double)bpcount, (double)apcount, (double)dotcount); END_TSC(t,11); } void matmul_for_small_nk(int n1, double a[][n1], int n2, double b[][n2], int n3, double c[][n3], int m, int kk, int n) { int i,ii; int nh = n/2; register int k; double bcopy[n][kk]; v2df bcopy2[nh][kk]; v2df acopy[kk]; v2df acopy2[kk]; double *acp = (double*) acopy; double *acp2 = (double*) acopy2; if (kk == 8){ matmul_for_nk8_3(n1, a, n2, b, n3, c, m, n); return; } if (kk == 16){ matmul_for_nk16(n1, a, n2, b, n3, c, m, n); return; } if (kk == 32){ matmul_for_nk32(n1, a, n2, b, n3, c, m, n); return; } BEGIN_TSC; for(k=0;k<kk;k++){ int j; for(j=0;j<nh;j++) bcopy2[j][k] = *((v2df*)(b[k]+j+j)); } #pragma omp parallel for private(i,k,acopy,acopy2) schedule(static) for(i=0;i<m;i+=2){ int j; double *ap=a[i]; double *ap2=a[i+1]; register v2df tmp, tmp2; v2df * cp = (v2df*) (&(c[i][0])); v2df * cp2 = (v2df*) (&(c[i+1][0])); for(k=0;k<kk;k+=2){ v2df * aa = (v2df*)(ap+k); acopy [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); aa = (v2df*)(ap2+k); acopy2 [k]= (v2df) __builtin_ia32_shufpd(*aa,*aa,0x0); acopy2[k+1]=(v2df) __builtin_ia32_shufpd(*aa,*aa,0xff); } __builtin_prefetch(a[i+4],0,3); __builtin_prefetch(c[i+4],1); __builtin_prefetch(a[i+5],0,3); __builtin_prefetch(c[i+5],1); __builtin_prefetch(a[i+20],0,3); __builtin_prefetch(c[i+20],1); __builtin_prefetch(a[i+21],0,3); __builtin_prefetch(c[i+21],1); for(j=0;j<nh;j++){ tmp = tmp2= (v2df){0.0,0.0}; v2df ctmp= cp[j]; v2df ctmp2 = cp2[j] ; v2df * bp = bcopy2[j]; for(k=0;k<kk;k+=8){ int k2 = k+4; v2df *avp = acopy+k; v2df *avp2 = acopy2+k; v2df *bvp = bp+k; tmp += avp[0]*bvp[0]; tmp2 += avp2[0]*bvp[0]; tmp +=avp[1]*bvp[1]; tmp2+=avp2[1]*bvp[1]; tmp +=avp[2]*bvp[2]; tmp2+=avp2[2]*bvp[2]; tmp +=avp[3]*bvp[3]; tmp2+=avp2[3]*bvp[3]; tmp += avp[4]*bvp[4]; tmp2 += avp2[4]*bvp[4]; tmp +=avp[5]*bvp[5]; tmp2+=avp2[5]*bvp[5]; tmp +=avp[6]*bvp[6]; tmp2+=avp2[6]*bvp[6]; tmp +=avp[7]*bvp[7]; tmp2+=avp2[7]*bvp[7]; } cp[j] = ctmp -tmp; cp2[j] = ctmp2 -tmp2; } } END_TSC(t,11); } void mydgemm(int m, int n, int k, double alpha, double * a, int na, double * b, int nb, double beta, double * c, int nc) { double t0, t1, t2; // printf("mydgemm called %d %d %d\n", m, n, k); if (k>= 512){ get_cputime(&t0,&t1); } BEGIN_TSC; BEGIN_TIMER(timer); #ifdef USEGDR if ((k>512) || ((k==512) && ((n>=1024)||(m>=1024)))){ // if (k>=2048){ mygdrdgemm(m, n, k, alpha, a, na, b, nb, beta, c, nc); }else{ if ((k<=16) && (alpha == -1.0) && (beta == 1.0)){ matmul_for_small_nk(na, a, nb, b, nc, c, m, n, k); }else{ cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, m,n, k, alpha, a, na, b, nb, beta, c, nc); } } #else #ifdef GEMMTEST mytestdgemm(m, n, k, na, nb, nc,alpha, a, b, beta, c); #else cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, m,n, k, alpha, a, na, b, nb, beta, c, nc); #endif #endif // cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, // m,n, k, alpha, a, na, b, nb, beta, c, nc); if (k==2048){ END_TIMER(timer,31,((double)(m))*n*k*2); END_TSC(t,14); }else if (k==1024){ END_TIMER(timer,32,((double)(m))*n*k*2); END_TSC(t,15); }else if (k==512){ END_TIMER(timer,33,((double)(m))*n*k*2); END_TSC(t,17); }else{ END_TIMER(timer,34,((double)(m))*n*k*2); END_TSC(t,18); } if (k>= 512){ get_cputime(&t0,&t1); dprintf(10,"dgemm M=%d N=%d K=%d time=%10.4g %g Gflops\n", m,n,k,t0, ((double)m)*n*k*2/t0/1e9); } } void reset_gdr(int m, double a[][m], int nb, double awork[][nb], int n) { #ifdef USEGDR double aw2[nb][nb]; if (nb < 2048){ fprintf(stderr,"reset_gdr nb = %d <2048 not supported\n", nb); exit(-1); } gdr_check_and_restart(a, awork, aw2); int i,j; dprintf(9,"reset_gdr clear awork\n"); for (i=0;i<nb;i++){ for (j=0;j<n;j++){ awork[j][i]=0; } } dprintf(9,"reset_gdr clear aw2\n"); for (i=0;i<nb;i++){ for (j=0;j<nb;j++){ aw2[j][i]=0; } } dprintf(9,"reset_gdr try_dgemm\n"); gdrsetforceswapab(); cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, n,nb, nb, 1.0, awork, nb, aw2, nb, 0.0, a, m); mydgemm(n,nb,nb,1.0,awork,nb,aw2,nb,0.0,a,m); #endif } #ifndef USEGDR void gdrsetforceswapab(){} void gdrresetforceswapab(){} void gdrsetskipsendjmat(){}; void gdrresetskipsendjmat(){} void gdrsetnboards(){} void set_matmul_msg_level(int level){} void gdrdgemm_set_stress_factor(int x){} #endif
{ "alphanum_fraction": 0.5161925646, "avg_line_length": 22.5508241758, "ext": "c", "hexsha": "8d95c01f221f72d5381dd5da5966d5b93f03def2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jmakino/lu2", "max_forks_repo_path": "lu2lib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jmakino/lu2", "max_issues_repo_path": "lu2lib.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jmakino/lu2", "max_stars_repo_path": "lu2lib.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 21719, "size": 49251 }
/* # # Copyright (c) 2006-2012 University of Houston. All rights reserved. # $COPYRIGHT$ # # Additional copyrights may follow # # $HEADER$ # */ #ifndef __SL_INTERNAL__ #define __SL_INTERNAL__ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> //#include <gsl/gsl_fit.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <math.h> #include <errno.h> //#include <papi.h> #ifdef MINGW #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <sys/wait.h> #include <sys/resource.h> #include <pwd.h> #include <sys/utsname.h> #endif #include "SL_array.h" extern fd_set SL_send_fdset; extern fd_set SL_recv_fdset; extern int SL_this_procid; extern int SL_this_procport; extern int SL_this_listensock; extern int SL_numprocs; extern int SL_init_numprocs; extern int SL_proxy_numprocs; /* Message header send before any message */ struct SL_msg_header { int cmd; /* what type of message is this */ int from; /* id of the src process */ int to; /* id of the dest. process */ int tag; /* tag of the message */ int context; /* context id */ int len; /* Message length in bytes */ int id; /* Id of the last fragment */ int loglength; int temp; }; typedef struct SL_msg_header SL_msg_header; /* Process structure containing all relevant contact information, communication status etc. */ struct SL_proc; typedef int SL_msg_comm_fnct ( struct SL_proc *dproc, int fd ); struct SL_proc { int id; char *hostname; int port; int sock; int state; int connect_attempts; /* number of connect attempts */ double connect_start_tstamp; /* time stamp when we started to accept or connect for this proc */ double timeout; /* max time a process should wait before disconnecting */ struct SL_msgq_head *squeue; /* Send queue */ struct SL_msgq_head *rqueue; /* Recv queue */ struct SL_msgq_head *urqueue; /* Unexpected msgs queue */ struct SL_msgq_head *scqueue; /* Send complete queue */ struct SL_msgq_head *rcqueue; /* Recv complete queue */ struct SL_qitem *currecvelem; struct SL_qitem *cursendelem; SL_msg_comm_fnct *recvfunc; SL_msg_comm_fnct *sendfunc; struct SL_msg_perf *msgperf; /*to keep track of time and msglenth for each communication */ struct SL_msg_perf *insertpt; struct SL_network_perf *netperf; }; struct SL_msg_perf { struct SL_msg_perf *fwd; struct SL_msg_perf *back; int msglen; double time; int pos; int msgtype; /*send type(0) or recieve type(1)*/ int elemid; struct SL_proc *proc; }; typedef struct SL_msg_perf SL_msg_perf; struct SL_network_perf { struct SL_network_perf *fwd; struct SL_network_perf *back; double latency; double bandwidth; int pos; }; typedef struct SL_network_perf SL_network_perf; typedef struct SL_proc SL_proc; #ifdef MINGW struct iovec { char *iov_base; /* Base address. */ size_t iov_len; /* Length. */ }; #define TCP_MAXSEG 0x02 /* set maximum segment size */ #define F_GETFL 3 /* get file->f_flags */ #define F_SETFL 4 /* set file->f_flags */ #define O_NONBLOCK 00004 #endif /* A message queue item containing the operation it decsribes */ struct SL_msgq_head; struct SL_qitem { int id; int iovpos; int lenpos; int error; struct iovec iov[2]; struct SL_msgq_head *move_to; struct SL_msgq_head *head; struct SL_qitem *next; struct SL_qitem *prev; double starttime; double endtime; }; typedef struct SL_qitem SL_qitem; /* A message queue */ struct SL_msgq_head { int count; char *name; struct SL_qitem *first; struct SL_qitem *last; }; typedef struct SL_msgq_head SL_msgq_head; /* Request object identifying an ongoing communication */ struct SL_msg_request { struct SL_proc *proc; int type; /* Send or Recv */ int id; struct SL_qitem *elem; struct SL_msgq_head *cqueue; /* completion queue to look for */ }; typedef struct SL_msg_request SL_msg_request; struct SL_msgq_head *SL_event_sendq; struct SL_msgq_head *SL_event_recvq; struct SL_msgq_head *SL_event_sendcq; /* MACROS */ /*#ifdef PRINTF #undef PRINTF #define PRINTF(A) printf A #else #define PRINTF(A) #endif*/ #define FALSE 0 #define TRUE 1 #define SEND 0 #define RECV 1 #define SL_RECONN_MAX 20 #define SL_ACCEPT_MAX_TIME 10 #define SL_READ_MAX_TIME 5 #define SL_ACCEPT_INFINITE_TIME -1 #define SL_BIND_PORTSHIFT 200 #define SL_SLEEP_TIME 1 #define SL_TCP_BUFFER_SIZE 262142 #define SL_MAX_EVENT_HANDLE 1 #define SL_CONSTANT_ID -32 #define SL_EVENT_MANAGER -1 #define SL_PROXY_SERVER -2 #define PERFBUFSIZE 20 #define MTU (1024L*4L) #define SL_PROC_ID -64 int SL_socket ( void ); int SL_bind_static ( int handle, int port ); int SL_bind_dynamic ( int handle, int port ); int SL_socket_close ( int handle ); int SL_open_socket_conn ( int *handle, const char *as_host, int port ); int SL_open_socket_bind ( int *handle, int port ); int SL_open_socket_listen ( int sock ); int SL_open_socket_listen_nb ( int *handle, int port ); int SL_open_socket_conn_nb ( int *handle, const char *as_host, int port ); int SL_socket_read ( int hdl, char *buf, int num, double timeout ); int SL_socket_write ( int hdl, char *buf, int num, double timeout ); int SL_socket_write_nb ( int hdl, char *buf, int num, int *numwritten ); int SL_socket_read_nb ( int hdl, char *buf, int num, int* numread ); void SL_print_socket_options ( int fd ); void SL_configure_socket ( int sd ); void SL_configure_socket_nb ( int sd ); int SL_init_internal(); double SL_papi_time(); /* status object t.b.d */ #endif /* __SL_INTERNALL__ */
{ "alphanum_fraction": 0.6594225888, "avg_line_length": 26.9401709402, "ext": "h", "hexsha": "674a20c2298a53c6b933b0eb97265cc39b14291b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "edgargabriel/VolpexMPI", "max_forks_repo_path": "include/SL_internal.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "edgargabriel/VolpexMPI", "max_issues_repo_path": "include/SL_internal.h", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "3289231c0feb6e48fbcff13af8795640d1ce1fb8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "edgargabriel/VolpexMPI", "max_stars_repo_path": "include/SL_internal.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1610, "size": 6304 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef delaunay_3673850c_175d_4077_bef2_fc69e19e5cf8_h #define delaunay_3673850c_175d_4077_bef2_fc69e19e5cf8_h #include <gslib/std.h> #include <gslib/math.h> #include <ariel/config.h> /* * A implementation of the Delaunay Triangulation and the Constrained Delaunay Triangulation. * The original implementation was: * https://code.google.com/archive/p/cgprojects09/ * further more, modifications were done to achieve the constrained version, visit: * http://www.geom.uiuc.edu/~samuelp/del_project.html */ __ariel_begin__ class ariel_export dt_joint { protected: vec2 _point; void* _binding; public: dt_joint() { _binding = nullptr; } dt_joint(const vec2& p, void* b) { _point = p, _binding = b; } void set_point(const vec2& p) { _point = p; } const vec2& get_point() const { return _point; } void set_binding(void* b) { _binding = b; } void* get_binding() const { return _binding; } }; class ariel_export dt_edge { protected: dt_joint* _org; dt_edge* _prev; dt_edge* _next; dt_edge* _symmetric; bool _constraint; bool _checked; public: dt_edge(); void set_org(dt_joint* j) { _org = j; } dt_joint* get_org() const { return _org; } void set_dest(dt_joint* j) { _symmetric->set_org(j); } dt_joint* get_dest() const { return _symmetric->get_org(); } void set_prev_edge(dt_edge* e) { _prev = e; } dt_edge* get_prev_edge() const { return _prev; } void set_next_edge(dt_edge* e) { _next = e; } dt_edge* get_next_edge() const { return _next; } void set_symmetric(dt_edge* e) { _symmetric = e; } dt_edge* get_symmetric() const { return _symmetric; } const vec2& get_org_point() const { return _org->get_point(); } const vec2& get_dest_point() const { return get_dest()->get_point(); } void* get_org_binding() const { return _org->get_binding(); } void* get_dest_binding() const { return get_dest()->get_binding(); } dt_edge* get_org_next() const { return _prev->get_symmetric(); } dt_edge* get_org_prev() const { return _symmetric->get_next_edge(); } dt_edge* get_dest_next() const { return _symmetric->get_prev_edge(); } dt_edge* get_dest_prev() const { return _next->get_symmetric(); } dt_edge* get_left_next() const { return _next; } dt_edge* get_left_prev() const { return _prev; } dt_edge* get_right_next() const { return _symmetric->get_next_edge()->get_symmetric(); } dt_edge* get_right_prev() const { return _symmetric->get_prev_edge()->get_symmetric(); } void set_constraint(bool b) { _constraint = b; } bool is_constraint() const { return _constraint; } void set_checked(bool c) { _checked = c; } bool is_checked() const { return _checked; } bool is_outside_boundary() const; bool is_boundary() const; }; struct ariel_export dt_edge_range { dt_edge* left; dt_edge* right; dt_edge_range() { left = right = nullptr; } }; typedef list<dt_joint> dt_input_joints; typedef list<dt_joint*> dt_joint_ptrs; typedef vector<dt_joint*> dt_joints; typedef unordered_set<dt_edge*> dt_edges; typedef vector<dt_edge*> dt_edge_list; class ariel_export delaunay_triangulation { public: delaunay_triangulation() {} ~delaunay_triangulation() { clear(); } void initialize(dt_input_joints& inputs); void run(); void clear(); dt_edge* add_constraint(const vec2& p1, const vec2& p2); void trim(dt_edge_list& edges); void set_range_left(dt_edge* e) { _edge_range.left = e; } void tracing() const; void trace_heuristically() const; void trace_mel() const; protected: dt_joints _sorted_joints; dt_edge_range _edge_range; dt_edges _edge_holdings; protected: bool is_in_range(int begin, int end, dt_joint* joint); dt_edge_range delaunay(int begin, int end); dt_edge* create_edge_pair(); dt_edge* connect_edges(dt_edge* e1, dt_edge* e2); void destroy_edge_pair(dt_edge* e); void shrink_triangulate(dt_edge* cut); void shrink_recursively(dt_edge_list& strips, dt_edge_list& temps); void collect_trim_edges(dt_edge_list& edges, dt_edge* e); template<class _visit> static void traverse_triangles_recursively(dt_edge* e, _visit visit) { assert(e); if(e->is_checked()) return; auto do_visit = [&visit](dt_edge* e) { assert(e); auto* e1 = e->get_prev_edge(); auto* e2 = e->get_next_edge(); assert(e1 && e2 && !e1->is_checked() && !e2->is_checked()); void* b1 = e->get_org_binding(); void* b2 = e->get_dest_binding(); void* b3 = e1->get_org_binding(); void* b4 = e2->get_dest_binding(); if(b3 != b4) /* invalid triangle */ return; auto& p1 = e->get_org_point(); auto& p2 = e->get_dest_point(); auto& p3 = e1->get_org_point(); if(!is_concave_angle(p1, p2, p3)) /* ccw! */ return; bool b[3]; b[0] = e->is_boundary(); b[1] = e1->is_boundary(); b[2] = e2->is_boundary(); visit(b1, b2, b3, b); e->set_checked(true); e1->set_checked(true); e2->set_checked(true); }; do_visit(e); traverse_triangles_recursively(e->get_symmetric(), visit); traverse_triangles_recursively(e->get_prev_edge()->get_symmetric(), visit); traverse_triangles_recursively(e->get_next_edge()->get_symmetric(), visit); } template<class _visit> static void traverse_triangles_flatly(dt_edge* e, _visit visit) { vector<dt_edge*> edges; edges.push_back(e); while(!edges.empty()) { e = edges.back(); edges.pop_back(); if(e->is_checked()) continue; auto do_visit = [&visit](dt_edge* e) { assert(e); auto* e1 = e->get_prev_edge(); auto* e2 = e->get_next_edge(); assert(e1 && e2 && !e1->is_checked() && !e2->is_checked()); void* b1 = e->get_org_binding(); void* b2 = e->get_dest_binding(); void* b3 = e1->get_org_binding(); void* b4 = e2->get_dest_binding(); if(b3 != b4) /* invalid triangle */ return; auto& p1 = e->get_org_point(); auto& p2 = e->get_dest_point(); auto& p3 = e1->get_org_point(); if(!is_concave_angle(p1, p2, p3)) /* ccw! */ return; bool b[3]; b[0] = e->is_boundary(); b[1] = e1->is_boundary(); b[2] = e2->is_boundary(); visit(b1, b2, b3, b); e->set_checked(true); e1->set_checked(true); e2->set_checked(true); }; do_visit(e); edges.push_back(e->get_symmetric()); edges.push_back(e->get_prev_edge()->get_symmetric()); edges.push_back(e->get_next_edge()->get_symmetric()); } } public: template<class _visit> void traverse_triangles(_visit visit) { traverse_triangles_flatly(_edge_range.left, visit); } void reset_traverse(); }; __ariel_end__ #endif
{ "alphanum_fraction": 0.6054932735, "avg_line_length": 37.7966101695, "ext": "h", "hexsha": "f8000809ea63ded0658b0586108200b5131a2745", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/delaunay.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/delaunay.h", "max_line_length": 94, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/delaunay.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 2237, "size": 8920 }
/* specfunc/beta_inc.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* Modified for cdfs by Brian Gough, June 2003 */ #include <gsl/gsl_sf_gamma.h> static double beta_cont_frac (const double a, const double b, const double x, const double epsabs) { const unsigned int max_iter = 512; /* control iterations */ const double cutoff = 2.0 * GSL_DBL_MIN; /* control the zero cutoff */ unsigned int iter_count = 0; double cf; /* standard initialization for continued fraction */ double num_term = 1.0; double den_term = 1.0 - (a + b) * x / (a + 1.0); if (fabs (den_term) < cutoff) den_term = GSL_NAN; den_term = 1.0 / den_term; cf = den_term; while (iter_count < max_iter) { const int k = iter_count + 1; double coeff = k * (b - k) * x / (((a - 1.0) + 2 * k) * (a + 2 * k)); double delta_frac; /* first step */ den_term = 1.0 + coeff * den_term; num_term = 1.0 + coeff / num_term; if (fabs (den_term) < cutoff) den_term = GSL_NAN; if (fabs (num_term) < cutoff) num_term = GSL_NAN; den_term = 1.0 / den_term; delta_frac = den_term * num_term; cf *= delta_frac; coeff = -(a + k) * (a + b + k) * x / ((a + 2 * k) * (a + 2 * k + 1.0)); /* second step */ den_term = 1.0 + coeff * den_term; num_term = 1.0 + coeff / num_term; if (fabs (den_term) < cutoff) den_term = GSL_NAN; if (fabs (num_term) < cutoff) num_term = GSL_NAN; den_term = 1.0 / den_term; delta_frac = den_term * num_term; cf *= delta_frac; if (fabs (delta_frac - 1.0) < 2.0 * GSL_DBL_EPSILON) break; if (cf * fabs (delta_frac - 1.0) < epsabs) break; ++iter_count; } if (iter_count >= max_iter) return GSL_NAN; return cf; } /* The function beta_inc_AXPY(A,Y,a,b,x) computes A * beta_inc(a,b,x) + Y taking account of possible cancellations when using the hypergeometric transformation beta_inc(a,b,x)=1-beta_inc(b,a,1-x). It also adjusts the accuracy of beta_inc() to fit the overall absolute error when A*beta_inc is added to Y. (e.g. if Y >> A*beta_inc then the accuracy of beta_inc can be reduced) */ static double beta_inc_AXPY (const double A, const double Y, const double a, const double b, const double x) { if (x == 0.0) { return A * 0 + Y; } else if (x == 1.0) { return A * 1 + Y; } else if (a > 1e5 && b < 10 && x > a / (a + b)) { /* Handle asymptotic regime, large a, small b, x > peak [AS 26.5.17] */ double N = a + (b - 1.0) / 2.0; return A * gsl_sf_gamma_inc_Q (b, -N * log (x)) + Y; } else if (b > 1e5 && a < 10 && x < b / (a + b)) { /* Handle asymptotic regime, small a, large b, x < peak [AS 26.5.17] */ double N = b + (a - 1.0) / 2.0; return A * gsl_sf_gamma_inc_P (a, -N * log1p (-x)) + Y; } else { double ln_beta = gsl_sf_lnbeta (a, b); double ln_pre = -ln_beta + a * log (x) + b * log1p (-x); double prefactor = exp (ln_pre); if (x < (a + 1.0) / (a + b + 2.0)) { /* Apply continued fraction directly. */ double epsabs = fabs (Y / (A * prefactor / a)) * GSL_DBL_EPSILON; double cf = beta_cont_frac (a, b, x, epsabs); return A * (prefactor * cf / a) + Y; } else { /* Apply continued fraction after hypergeometric transformation. */ double epsabs = fabs ((A + Y) / (A * prefactor / b)) * GSL_DBL_EPSILON; double cf = beta_cont_frac (b, a, 1.0 - x, epsabs); double term = prefactor * cf / b; if (A == -Y) { return -A * term; } else { return A * (1 - term) + Y; } } } } /* Direct series evaluation for testing purposes only */ #if 0 static double beta_series (const double a, const double b, const double x, const double epsabs) { double f = x / (1 - x); double c = (b - 1) / (a + 1) * f; double s = 1; double n = 0; s += c; do { n++; c *= -f * (2 + n - b) / (2 + n + a); s += c; } while (n < 512 && fabs (c) > GSL_DBL_EPSILON * fabs (s) + epsabs); s /= (1 - x); return s; } #endif
{ "alphanum_fraction": 0.5568490493, "avg_line_length": 26.5670103093, "ext": "c", "hexsha": "ac1d34032f31d23ee5580362a7ced8ec1a6a38d2", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cdf/beta_inc.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/cdf/beta_inc.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/cdf/beta_inc.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1592, "size": 5154 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_interp.h> typedef double (*eval_func)(const gsl_interp*,const double *x,const double *y, double,gsl_interp_accel*); static const double EPSILON = 0.00000001; static const double EPS = 0.0001; static const int PTS = 801; static const double x_values[] = { 0, 1, 2, 3, 4, 5 }; static const double y_values[] = { 5, 0, 5, 2, 0, 5 }; static double x_range; static const int N = sizeof(x_values)/sizeof(double); static double* interpolate(const gsl_interp_type *type, const size_t order); static void check_discont(gsl_interp *interp, const eval_func func, const char *dsym, const double x, gsl_interp_accel *accel); static inline double scale_x(const int i) { return x_values[0] + (double)i/(PTS-1)*x_range; } int main(int argc, char *argv[]) { int i; double *cspline, *cspline_d, *cspline_dd; double *akima, *akima_d, *akima_dd; x_range = x_values[N-1] - x_values[0]; akima = interpolate(gsl_interp_akima_periodic, 0); akima_d = interpolate(gsl_interp_akima_periodic, 1); akima_dd = interpolate(gsl_interp_akima_periodic, 2); cspline = interpolate(gsl_interp_cspline_periodic, 0); cspline_d = interpolate(gsl_interp_cspline_periodic, 1); cspline_dd = interpolate(gsl_interp_cspline_periodic, 2); puts("# x akima cspline akima' cspline' akima'' cspline''"); for (i = -PTS/2; i < PTS/2; i++) printf("%0.5f %0.5f %0.5f %0.5f %0.5f %0.5f %0.5f\n", scale_x(i), akima[(i + PTS)%PTS], cspline[(i + PTS)%PTS], akima_d[(i + PTS)%PTS], cspline_d[(i + PTS)%PTS], akima_dd[(i + PTS)%PTS], cspline_dd[(i + PTS)%PTS]); free(akima); free(akima_d); free(akima_dd); free(cspline); free(cspline_d); free(cspline_dd); return 0; } static double* interpolate(const gsl_interp_type *type, const size_t order) { static const eval_func DERIV_ORDERS[] = { gsl_interp_eval, gsl_interp_eval_deriv, gsl_interp_eval_deriv2 }; static const char *DERIV_SYMS[] = { "", "'", "''" }; gsl_interp *interp = gsl_interp_alloc(type, N); gsl_interp_accel *accel = gsl_interp_accel_alloc(); double *plotpts = (double*)malloc(PTS*sizeof(double)); int i; assert(order < sizeof(DERIV_ORDERS)); gsl_interp_init(interp, x_values, y_values, N); for (i = 0; i < PTS; i++) plotpts[i] = DERIV_ORDERS[order](interp, x_values, y_values, scale_x(i), accel); for (i = 0; i < N-1; i++) check_discont(interp, DERIV_ORDERS[order], DERIV_SYMS[order], x_values[i], accel); gsl_interp_free(interp); gsl_interp_accel_free(accel); return plotpts; } static void check_discont(gsl_interp *interp, const eval_func func, const char *dsym, const double x, gsl_interp_accel *accel) { double xm, xp; double ym, yp; xm = fmod(x - EPSILON + x_range, x_range); xp = fmod(x + EPSILON, x_range); ym = func(interp, x_values, y_values, xm, accel); yp = func(interp, x_values, y_values, xp, accel); if (fabs(yp - ym) > EPS) { fprintf(stderr, "discontinuity in %s%s at %f:\n" "\t left value: %f\n" "\tright value: %f\n" "\t difference: %f\n\n", gsl_interp_name(interp), dsym, x, ym, yp, yp-ym); } }
{ "alphanum_fraction": 0.6245714286, "avg_line_length": 28.6885245902, "ext": "c", "hexsha": "f41b5983a3f701e063435a627f9683da0db2e07a", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/test_disc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/test_disc.c", "max_line_length": 78, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/interpolation/test_disc.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1047, "size": 3500 }
// // Created by Harold on 2020/9/16. // #ifndef M_MATH_M_INTERP_H #define M_MATH_M_INTERP_H #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include <vector> #include <algorithm> namespace M_MATH { class Interpolation1D { public: enum InterpType { LINEAR, POLYNOMIAL, CSPLINE, CSPLINE_PERIODIC, AKIMA, AKIMA_PERIODIC, STEFFEN }; static bool interpolate(double const* x, double const* y, size_t length, InterpType type, double const* n_x, size_t n_length, double* n_y); // this will create tmp var inside, better to use former one if possible template<typename IT_X, typename IT_Y, typename IT_NX, typename IT_NY> static bool interpolate(IT_X x_begin, IT_X x_end, IT_Y y_begin, IT_Y y_end, InterpType type, IT_NX nx_begin, IT_NX nx_end, IT_NY ny_begin); private: static const gsl_interp_type* InterpType2GSL(InterpType type); }; class Interpolation2D { public: enum InterpType { BI_LINEAR, BI_CUBIC }; static bool interpolate(double const* x, double const* y, double const* z, size_t x_length, size_t y_length, InterpType type, double const* n_x, double const* n_y, size_t n_x_length, size_t n_y_length, double* n_z); // this will create tmp var inside, better to use former one if possible template<typename IT_X, typename IT_Y, typename IT_Z, typename IT_NX, typename IT_NY, typename IT_NZ> static bool interpolate(IT_X x_begin, IT_X x_end, IT_Y y_begin, IT_Y y_end, IT_Z z_begin, IT_Z z_end, InterpType type, IT_NX nx_begin, IT_NX nx_end, IT_NY ny_begin, IT_NY ny_end, IT_NZ nz_begin); private: static const gsl_interp2d_type* InterpType2GSL(InterpType type); }; const gsl_interp_type *Interpolation1D::InterpType2GSL(Interpolation1D::InterpType type) { switch (type) { case LINEAR: return gsl_interp_linear; case POLYNOMIAL: return gsl_interp_polynomial; case CSPLINE: return gsl_interp_cspline; case CSPLINE_PERIODIC: return gsl_interp_cspline_periodic; case AKIMA: return gsl_interp_akima; case AKIMA_PERIODIC: return gsl_interp_akima_periodic; case STEFFEN: return gsl_interp_steffen; } return nullptr; } bool Interpolation1D::interpolate(const double *x, const double *y, size_t length, Interpolation1D::InterpType type, const double *n_x, size_t n_length, double* n_y) { gsl_spline* spl = gsl_spline_alloc(InterpType2GSL(type), length); if (spl == nullptr) return false; gsl_interp_accel* acc = gsl_interp_accel_alloc(); if (acc == nullptr) { return false; } gsl_spline_init(spl, x, y, length); for (auto i = 0; i < n_length; ++i) n_y[i] = gsl_spline_eval(spl, n_x[i], acc); gsl_spline_free(spl); gsl_interp_accel_free(acc); return true; } template<typename IT_X, typename IT_Y, typename IT_NX, typename IT_NY> bool Interpolation1D::interpolate(const IT_X x_begin, const IT_X x_end, const IT_Y y_begin, const IT_Y y_end, Interpolation1D::InterpType type, const IT_NX nx_begin, const IT_NX nx_end, IT_NY ny_begin) { auto len = std::min(std::distance(x_begin, x_end), std::distance(y_begin, y_end)); auto n_len = std::distance(nx_begin, nx_end); std::vector<double> x_tmp(len), y_tmp(len); std::copy(x_begin, x_begin+len, x_tmp.begin()); std::copy(y_begin, y_begin+len, y_tmp.begin()); gsl_spline* spl = gsl_spline_alloc(InterpType2GSL(type), len); if (spl == nullptr) return false; gsl_interp_accel* acc = gsl_interp_accel_alloc(); if (acc == nullptr) { return false; } gsl_spline_init(spl, x_tmp.data(), y_tmp.data(), len); for (auto i = 0; i < n_len; ++i) *(ny_begin+i) = gsl_spline_eval(spl, *(nx_begin+i), acc); gsl_spline_free(spl); gsl_interp_accel_free(acc); return true; } const gsl_interp2d_type *Interpolation2D::InterpType2GSL(Interpolation2D::InterpType type) { switch (type) { case BI_LINEAR: return gsl_interp2d_bilinear; case BI_CUBIC: return gsl_interp2d_bicubic; } return nullptr; } bool Interpolation2D::interpolate(const double *x, const double *y, const double *z, size_t x_length, size_t y_length, Interpolation2D::InterpType type, const double *n_x, const double *n_y, size_t n_x_length, size_t n_y_length, double *n_z) { gsl_spline2d* spl = gsl_spline2d_alloc(InterpType2GSL(type), x_length, y_length); if (spl == nullptr) return false; gsl_interp_accel *x_acc = gsl_interp_accel_alloc(); if (x_acc == nullptr) return false; gsl_interp_accel *y_acc = gsl_interp_accel_alloc(); if (y_acc == nullptr) return false; // zij = z[j * x_length + i] gsl_spline2d_init(spl, x, y, z, x_length, y_length); for (auto i = 0; i < n_x_length; ++i) for (auto j = 0; j < n_y_length; ++j) n_z[j * n_x_length + i] = gsl_spline2d_eval(spl, n_x[i], n_y[j], x_acc, y_acc); gsl_spline2d_free(spl); gsl_interp_accel_free(x_acc); gsl_interp_accel_free(y_acc); return true; } template<typename IT_X, typename IT_Y, typename IT_Z, typename IT_NX, typename IT_NY, typename IT_NZ> bool Interpolation2D::interpolate(const IT_X x_begin, const IT_X x_end, const IT_Y y_begin, const IT_Y y_end, const IT_Z z_begin, const IT_Z z_end, Interpolation2D::InterpType type, const IT_NX nx_begin, const IT_NX nx_end, const IT_NY ny_begin, const IT_NY ny_end, const IT_NZ nz_begin) { auto x_length = std::distance(x_begin, x_end); auto y_length = std::distance(y_begin, y_end); auto z_length = std::distance(z_begin, z_end); auto n_x_length = std::distance(nx_begin, nx_end); auto n_y_length = std::distance(ny_begin, ny_end); std::vector<double> x_tmp(x_length), y_tmp(y_length), z_tmp(z_length); std::copy(x_begin, x_end, x_tmp.begin()); std::copy(y_begin, y_end, y_tmp.begin()); std::copy(z_begin, z_end, z_tmp.begin()); gsl_spline2d* spl = gsl_spline2d_alloc(InterpType2GSL(type), x_length, y_length); if (spl == nullptr) return false; gsl_interp_accel *x_acc = gsl_interp_accel_alloc(); if (x_acc == nullptr) return false; gsl_interp_accel *y_acc = gsl_interp_accel_alloc(); if (y_acc == nullptr) return false; // zij = z[j * x_length + i] gsl_spline2d_init(spl, x_tmp.data(), y_tmp.data(), z_tmp.data(), x_length, y_length); for (auto i = 0; i < n_x_length; ++i) for (auto j = 0; j < n_y_length; ++j) *(nz_begin + j * n_x_length + i) = gsl_spline2d_eval(spl, *(nx_begin + i), *(ny_begin + j), x_acc, y_acc); gsl_spline2d_free(spl); gsl_interp_accel_free(x_acc); gsl_interp_accel_free(y_acc); return true; } } #endif //M_MATH_M_INTERP_H
{ "alphanum_fraction": 0.5091143041, "avg_line_length": 40.3722943723, "ext": "h", "hexsha": "50e75a5bc14d2dd71a8e7a7b627669389d13c648", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_path": "include/m_interp.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_path": "include/m_interp.h", "max_line_length": 122, "max_stars_count": 2, "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_path": "include/m_interp.h", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "num_tokens": 2078, "size": 9326 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/file.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include "allvars.h" #include "proto.h" #include "domain.h" static FILE *fd; static void in(int *x, int modus); static void byten(void *x, int n, int modus); /* This function reads or writes the restart files. * Each processor writes its own restart file, with the * I/O being done in parallel. To avoid congestion of the disks * you can tell the program to restrict the number of files * that are simultaneously written to NumFilesWrittenInParallel. * * If modus>0 the restart()-routine reads, * if modus==0 it writes a restart file. */ void restart(int modus) { char buf[200], buf_bak[200], buf_mv[500]; double save_PartAllocFactor; int i, nprocgroup, masterTask, groupTask, old_MaxPart, old_MaxNodes; struct global_data_all_processes all_task0; #if defined(SFR) || defined(BLACK_HOLES) #ifdef NO_TREEDATA_IN_RESTART if(modus == 0) { rearrange_particle_sequence(); All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TreeDomainUpdateFrequency * All.TotNumPart); /* ensures that new tree will be constructed */ } #endif #endif if(ThisTask == 0 && modus == 0) { sprintf(buf, "%s/restartfiles", All.OutputDir); mkdir(buf, 02755); } MPI_Barrier(MPI_COMM_WORLD); sprintf(buf, "%s/restartfiles/%s.%d", All.OutputDir, All.RestartFile, ThisTask); sprintf(buf_bak, "%s/restartfiles/%s.%d.bak", All.OutputDir, All.RestartFile, ThisTask); sprintf(buf_mv, "mv %s %s", buf, buf_bak); if((NTask < All.NumFilesWrittenInParallel)) { printf ("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n"); endrun(2131); } nprocgroup = NTask / All.NumFilesWrittenInParallel; if((NTask % All.NumFilesWrittenInParallel)) { nprocgroup++; } masterTask = (ThisTask / nprocgroup) * nprocgroup; for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if(ThisTask == (masterTask + groupTask)) { if(!modus) { #ifndef NOCALLSOFSYSTEM int ret; ret = system(buf_mv); /* move old restart files to .bak files */ #endif } } } for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */ { if(modus) { if(!(fd = fopen(buf, "r"))) { printf("Restart file '%s' not found.\n", buf); endrun(7870); } } else { if(!(fd = fopen(buf, "w"))) { printf("Restart file '%s' cannot be opened.\n", buf); endrun(7878); } } save_PartAllocFactor = All.PartAllocFactor; /* common data */ byten(&All, sizeof(struct global_data_all_processes), modus); if(ThisTask == 0 && modus > 0) all_task0 = All; if(modus > 0 && groupTask == 0) /* read */ { MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD); } old_MaxPart = All.MaxPart; old_MaxNodes = (int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes; if(modus) /* read */ { if(All.PartAllocFactor != save_PartAllocFactor) { All.PartAllocFactor = save_PartAllocFactor; All.MaxPart = (int) (All.PartAllocFactor * (All.TotNumPart / NTask)); All.MaxPartSph = (int) (All.PartAllocFactor * (All.TotN_gas / NTask)); #ifdef INHOMOG_GASDISTR_HINT All.MaxPartSph = All.MaxPart; #endif save_PartAllocFactor = -1; } if(all_task0.Time != All.Time) { printf("The restart file on task=%d is not consistent with the one on task=0\n", ThisTask); fflush(stdout); endrun(16); } allocate_memory(); } in(&NumPart, modus); if(NumPart > All.MaxPart) { printf ("it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n", NumPart / (((double) All.TotNumPart) / NTask)); printf("fatal error\n"); endrun(22); } /* Particle data */ byten(&P[0], NumPart * sizeof(struct particle_data), modus); in(&N_gas, modus); if(N_gas > 0) { if(N_gas > All.MaxPartSph) { printf ("SPH: it seems you have reduced(!) 'PartAllocFactor' below the value of %g needed to load the restart file.\n", N_gas / (((double) All.TotN_gas) / NTask)); printf("fatal error\n"); endrun(222); } /* Sph-Particle data */ byten(&SphP[0], N_gas * sizeof(struct sph_particle_data), modus); } /* write state of random number generator */ byten(gsl_rng_state(random_generator), gsl_rng_size(random_generator), modus); /* now store relevant data for tree */ #ifdef SFR in(&Stars_converted, modus); #endif #ifndef NO_TREEDATA_IN_RESTART /* now store relevant data for tree */ int nmulti = MULTIPLEDOMAINS; in(&nmulti, modus); if(modus != 0 && nmulti != MULTIPLEDOMAINS) { if(ThisTask == 0) printf ("Looks like you changed MULTIPLEDOMAINS from %d to %d.\nWill discard tree stored in restart files and construct a new one.\n", nmulti, (int) MULTIPLEDOMAINS); All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TreeDomainUpdateFrequency * All.TotNumPart); /* ensures that new tree will be constructed */ } else { in(&NTopleaves, modus); in(&NTopnodes, modus); if(modus) /* read */ { domain_allocate(); force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart); } in(&Numnodestree, modus); if(Numnodestree > MaxNodes) { printf ("Tree storage: it seems you have reduced(!) 'PartAllocFactor' below the value needed to load the restart file (task=%d). " "Numnodestree=%d MaxNodes=%d\n", ThisTask, Numnodestree, MaxNodes); endrun(221); } byten(Nodes_base, Numnodestree * sizeof(struct NODE), modus); byten(Extnodes_base, Numnodestree * sizeof(struct extNODE), modus); byten(Father, NumPart * sizeof(int), modus); byten(Nextnode, NumPart * sizeof(int), modus); byten(Nextnode + All.MaxPart, NTopnodes * sizeof(int), modus); byten(DomainStartList, NTask * MULTIPLEDOMAINS * sizeof(int), modus); byten(DomainEndList, NTask * MULTIPLEDOMAINS * sizeof(int), modus); byten(DomainTask, NTopnodes * sizeof(int), modus); byten(DomainNodeIndex, NTopleaves * sizeof(int), modus); byten(DomainCorner, 3 * sizeof(double), modus); byten(DomainCenter, 3 * sizeof(double), modus); byten(&DomainLen, sizeof(double), modus); byten(&DomainFac, sizeof(double), modus); if(modus) /* read */ if(All.PartAllocFactor != save_PartAllocFactor) { for(i = 0; i < NumPart; i++) Father[i] += (All.MaxPart - old_MaxPart); for(i = 0; i < NumPart; i++) if(Nextnode[i] >= old_MaxPart) { if(Nextnode[i] >= old_MaxPart + old_MaxNodes) Nextnode[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxPart); else Nextnode[i] += (All.MaxPart - old_MaxPart); } for(i = 0; i < Numnodestree; i++) { if(Nodes_base[i].u.d.sibling >= old_MaxPart) { if(Nodes_base[i].u.d.sibling >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.sibling += (All.MaxPart - old_MaxPart); } if(Nodes_base[i].u.d.father >= old_MaxPart) { if(Nodes_base[i].u.d.father >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.father += (All.MaxPart - old_MaxPart); } if(Nodes_base[i].u.d.nextnode >= old_MaxPart) { if(Nodes_base[i].u.d.nextnode >= old_MaxPart + old_MaxNodes) Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nodes_base[i].u.d.nextnode += (All.MaxPart - old_MaxPart); } } for(i = 0; i < NTopnodes; i++) if(Nextnode[i + All.MaxPart] >= old_MaxPart) { if(Nextnode[i + All.MaxPart] >= old_MaxPart + old_MaxNodes) Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else Nextnode[i + All.MaxPart] += (All.MaxPart - old_MaxPart); } for(i = 0; i < NTopnodes; i++) if(DomainNodeIndex[i] >= old_MaxPart) { if(DomainNodeIndex[i] >= old_MaxPart + old_MaxNodes) DomainNodeIndex[i] += (All.MaxPart - old_MaxPart) + (MaxNodes - old_MaxNodes); else DomainNodeIndex[i] += (All.MaxPart - old_MaxPart); } } } #endif fclose(fd); } else /* wait inside the group */ { if(modus > 0 && groupTask == 0) /* read */ { MPI_Bcast(&all_task0, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD); } } MPI_Barrier(MPI_COMM_WORLD); } #ifdef HEALPIX //this should be readed in the parameterfile All.Nside=8; // if(ThisTask==0) printf(" Restart calculation of Healpix %i with %i \n",All.Nside,NSIDE2NPIX(All.Nside)); // initialize the healpix array (just in case) All.healpixmap=(float *) malloc(NSIDE2NPIX(All.Nside) * sizeof(float)); for(i=0;i<NSIDE2NPIX(All.Nside);i++)All.healpixmap[i]=0; healpix_halo(All.healpixmap); #endif } /* reads/writes n bytes */ void byten(void *x, int n, int modus) { if(modus) my_fread(x, n, 1, fd); else my_fwrite(x, n, 1, fd); } /* reads/writes one int */ void in(int *x, int modus) { if(modus) my_fread(x, 1, sizeof(int), fd); else my_fwrite(x, 1, sizeof(int), fd); }
{ "alphanum_fraction": 0.6282818044, "avg_line_length": 27.5558659218, "ext": "c", "hexsha": "e0922ae597bbec67280ea5d18d564bbdfdfcb66a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "egpbos/egp", "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "egpbos/egp", "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_line_length": 157, "max_stars_count": null, "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "egpbos/egp", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/restart.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2950, "size": 9865 }
#include <gsl/gsl_poly.h> #include <stdio.h> int main(int argc, char *argv[]) { /* 0 + 2x - 3x^2 + 1x^3 */ double p[] = {0, 2, -3, 1}; double z[6]; gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(4); gsl_poly_complex_solve(p, 4, w, z); gsl_poly_complex_workspace_free(w); for(int i = 0; i < 3; ++i) printf("%.12f\n", z[2 * i]); return 0; }
{ "alphanum_fraction": 0.5775, "avg_line_length": 22.2222222222, "ext": "c", "hexsha": "3bc63c8f43cb4f93d5542105ad7abf4e7b8f5c5d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_path": "lang/C/roots-of-a-function-2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_path": "lang/C/roots-of-a-function-2.c", "max_line_length": 72, "max_stars_count": 2, "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_path": "lang/C/roots-of-a-function-2.c", "max_stars_repo_stars_event_max_datetime": "2017-06-26T18:52:29.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-10T14:21:53.000Z", "num_tokens": 141, "size": 400 }
#include "../include/paralleltt.h" #include <stdio.h> #include <stdlib.h> #include <cblas.h> #include <lapacke.h> #include <time.h> flattening_info* flattening_info_init(const MPI_tensor* ten, int flattening, int iscol, int t_v_block) { // Tensor info flattening_info* fi = (flattening_info*) malloc(sizeof(flattening_info)); int t_d = ten->d; int* t_nps = (int*) malloc(t_d*sizeof(int)); int t_Nblocks = 1; for (int ii = 0; ii < t_d; ++ii){ t_nps[ii] = ten->nps[ii]; t_Nblocks = t_Nblocks * t_nps[ii]; } int* t_t_block = (int*) malloc(t_d*sizeof(int)); to_tensor_ind(t_t_block, t_v_block, t_nps, t_d); long t_N = 1; int* t_t_sizes = (int*) malloc(t_d*sizeof(int)); int* t_t_index = (int*) malloc(t_d*sizeof(int)); for (int ii = 0; ii < t_d; ++ii){ int* partition_ii = ten->partitions[ii]; t_t_index[ii] = partition_ii[t_t_block[ii]]; t_t_sizes[ii] = partition_ii[t_t_block[ii]+1] - t_t_index[ii]; t_N = t_N * t_t_sizes[ii]; } // Flattening info int f_d = (iscol) ? flattening : t_d-flattening; int offset = (iscol) ? 0 : flattening; long f_N = 1; int f_Nblocks = 1; int* f_nps = (int*) malloc(f_d * sizeof(int)); int* f_t_block = (int*) malloc(f_d * sizeof(int)); int* f_t_index = (int*) malloc(f_d * sizeof(int)); int* f_t_sizes = (int*) malloc(f_d * sizeof(int)); for (int ii = 0; ii < f_d; ++ii){ f_nps[ii] = t_nps[ii+offset]; f_t_block[ii] = t_t_block[ii+offset]; f_t_index[ii] = t_t_index[ii+offset]; f_t_sizes[ii] = t_t_sizes[ii+offset]; f_N = f_N * f_t_sizes[ii]; f_Nblocks = f_Nblocks * f_nps[ii]; } int f_v_block = to_vec_ind(f_t_block, f_nps, f_d); // Sketching dimensions info int s_d = t_d - f_d; long s_N = 1; offset = (iscol) ? flattening : 0; int* s_nps = (int*) malloc(s_d * sizeof(int)); int* s_t_index = (int*) malloc(s_d * sizeof(int)); int* s_t_sizes = (int*) malloc(s_d * sizeof(int)); for (int ii = 0; ii < s_d; ++ii){ s_nps[ii] = t_nps[ii+offset]; s_t_index[ii] = t_t_index[ii+offset]; s_t_sizes[ii] = t_t_sizes[ii+offset]; s_N = s_N * s_t_sizes[ii]; } // Assigning fi->t_d = t_d; fi->t_N = t_N; fi->t_Nblocks = t_Nblocks; fi->t_nps = t_nps; fi->t_v_block = t_v_block; fi->t_t_block = t_t_block; fi->t_t_index = t_t_index; fi->t_t_sizes = t_t_sizes; fi->flattening = flattening; fi->iscol = iscol; fi->f_d = f_d; fi->f_N = f_N; fi->f_Nblocks = f_Nblocks; fi->f_nps = f_nps; fi->f_v_block = f_v_block; fi->f_t_block = f_t_block; fi->f_t_index = f_t_index; fi->f_t_sizes = f_t_sizes; fi->s_d = s_d; fi->s_N = s_N; fi->s_nps = s_nps; fi->s_t_index = s_t_index; fi->s_t_sizes = s_t_sizes; return fi; } void flattening_info_free(flattening_info* fi) { free(fi->t_nps); fi->t_nps = NULL; free(fi->t_t_block); fi->t_t_block = NULL; free(fi->t_t_index); fi->t_t_index = NULL; free(fi->t_t_sizes); fi->t_t_sizes = NULL; free(fi->f_nps); fi->f_nps = NULL; free(fi->f_t_block); fi->f_t_block = NULL; free(fi->f_t_index); fi->f_t_index = NULL; free(fi->f_t_sizes); fi->f_t_sizes = NULL; free(fi->s_nps); fi->s_nps = NULL; free(fi->s_t_index); fi->s_t_index = NULL; free(fi->s_t_sizes); fi->s_t_sizes = NULL; free(fi); } void flattening_info_update(flattening_info* fi, const MPI_tensor* ten, int t_v_block) { // Tensor info int t_d = ten->d; int* t_nps = fi->t_nps; int* t_t_block = fi->t_t_block; to_tensor_ind(t_t_block, t_v_block, t_nps, t_d); long t_N = 1; int* t_t_sizes = fi->t_t_sizes; int* t_t_index = fi->t_t_index; for (int ii = 0; ii < t_d; ++ii){ int* partition_ii = ten->partitions[ii]; t_t_index[ii] = partition_ii[t_t_block[ii]]; t_t_sizes[ii] = partition_ii[t_t_block[ii]+1] - t_t_index[ii]; t_N = t_N * t_t_sizes[ii]; } // Flattening info int flattening = fi->flattening; int iscol = fi->iscol; int f_d = fi->f_d; int offset = (iscol) ? 0 : flattening; long f_N = 1; int* f_nps = fi->f_nps; int* f_t_block = fi->f_t_block; int* f_t_index = fi->f_t_index; int* f_t_sizes = fi->f_t_sizes; for (int ii = 0; ii < f_d; ++ii){ f_nps[ii] = t_nps[ii+offset]; f_t_block[ii] = t_t_block[ii+offset]; f_t_index[ii] = t_t_index[ii+offset]; f_t_sizes[ii] = t_t_sizes[ii+offset]; f_N = f_N * f_t_sizes[ii]; } int f_v_block = to_vec_ind(f_t_block, f_nps, f_d); // Sketching dimensions info int s_d = fi->s_d; long s_N = 1; offset = (iscol) ? flattening : 0; int* s_nps = fi->s_nps; int* s_t_index = fi->s_t_index; int* s_t_sizes = fi->s_t_sizes; for (int ii = 0; ii < s_d; ++ii){ s_nps[ii] = t_nps[ii+offset]; s_t_index[ii] = t_t_index[ii+offset]; s_t_sizes[ii] = t_t_sizes[ii+offset]; s_N = s_N * s_t_sizes[ii]; } // Assigning fi->t_d = t_d; fi->t_N = t_N; fi->t_nps = t_nps; fi->t_v_block = t_v_block; fi->t_t_block = t_t_block; fi->t_t_index = t_t_index; fi->t_t_sizes = t_t_sizes; fi->flattening = flattening; fi->iscol = iscol; fi->f_d = f_d; fi->f_N = f_N; fi->f_nps = f_nps; fi->f_v_block = f_v_block; fi->f_t_block = f_t_block; fi->f_t_index = f_t_index; fi->f_t_sizes = f_t_sizes; fi->s_d = s_d; fi->s_N = s_N; fi->s_nps = s_nps; fi->s_t_index = s_t_index; fi->s_t_sizes = s_t_sizes; } void flattening_info_f_update(flattening_info* fi, const MPI_tensor* ten, int f_v_block) { // tensor info int t_d = fi->t_d; long t_N = -1; int t_v_block = -1; int* t_t_block = fi->t_t_block; int* t_t_index = fi->t_t_index; int* t_t_sizes = fi->t_t_sizes; for (int ii = 0; ii < t_d; ++ii){ t_t_block[ii] = -1; t_t_index[ii] = 0; t_t_sizes[ii] = 0; } fi->t_N = t_N; fi->t_v_block = t_v_block; // flattening info int flattening = fi->flattening; int iscol = fi->iscol; int f_d = fi->f_d; int f_Nblocks = fi->f_Nblocks; int* f_nps = fi->f_nps; int* f_t_block = fi->f_t_block; to_tensor_ind(f_t_block, (long) f_v_block, f_nps, f_d); long f_N = 1; int* f_t_index = fi->f_t_index; int* f_t_sizes = fi->f_t_sizes; int offset = (iscol) ? 0 : flattening; for (int ii = 0; ii < f_d; ++ii){ int* partition_ii = ten->partitions[ii + offset]; f_t_index[ii] = partition_ii[f_t_block[ii]]; f_t_sizes[ii] = partition_ii[f_t_block[ii]+1] - f_t_index[ii]; f_N = f_N * f_t_sizes[ii]; } fi->f_N = f_N; fi->f_v_block = f_v_block; // Sketching dimensions info int s_d = fi->s_d; long s_N = 0; int* s_t_index = fi->s_t_index; int* s_t_sizes = fi->s_t_sizes; for (int ii = 0; ii < s_d; ++ii){ s_t_index[ii] = 0; s_t_sizes[ii] = 0; } fi->s_N = s_N; } void flattening_info_print(flattening_info* fi) { printf("\n~~~~~~~~~~~~~~~ Flattening Info ~~~~~~~~~~~~~~~\n"); int t_d = fi->t_d; printf("t_d = %d\n", t_d); printf("t_N = %ld\n", fi->t_N); printf("t_Nblocks = %d\n", fi->t_Nblocks); if (t_d>0){ printf("t_nps = [%d", fi->t_nps[0]); for (int ii = 1; ii < t_d; ++ii){printf(", %d", fi->t_nps[ii]); } printf("]\n"); } else{ printf("t_nps = []\n"); } printf("t_v_block = %d\n", fi->t_v_block); if (t_d>0){ printf("t_t_block = [%d", fi->t_t_block[0]); for (int ii = 1; ii < t_d; ++ii){printf(", %d", fi->t_t_block[ii]);} printf("]\n"); } else{ printf("t_t_block = []\n"); } if (t_d>0){ printf("t_t_index = [%d", fi->t_t_index[0]); for (int ii = 1; ii < t_d; ++ii){printf(", %d", fi->t_t_index[ii]);} printf("]\n"); } else{ printf("t_t_index = []\n"); } if (t_d>0){ printf("t_t_sizes = [%d", fi->t_t_sizes[0]); for (int ii = 1; ii < t_d; ++ii){printf(", %d", fi->t_t_sizes[ii]);} printf("]\n"); } else{ printf("t_t_sizes = []\n"); } printf("flattening = %d\n", fi->flattening); printf("iscol = %d\n", fi->iscol); int f_d = fi->f_d; printf("f_d = %d\n", f_d); printf("f_N = %ld\n", fi->f_N); printf("f_Nblocks = %d\n", fi->f_Nblocks); if (f_d>0){ printf("f_nps = [%d", fi->f_nps[0]); for (int ii = 1; ii < f_d; ++ii){printf(", %d", fi->f_nps[ii]);} printf("]\n"); } else{ printf("f_nps = []\n"); } printf("f_v_block = %d\n", fi->f_v_block); if (f_d>0){ printf("f_t_block = [%d", fi->f_t_block[0]); for (int ii = 1; ii < f_d; ++ii){printf(", %d", fi->f_t_block[ii]);} printf("]\n"); } else{ printf("f_t_block = []\n"); } if (f_d>0){ printf("f_t_index = [%d", fi->f_t_index[0]); for (int ii = 1; ii < f_d; ++ii){printf(", %d", fi->f_t_index[ii]);} printf("]\n"); } else{ printf("f_t_index = []\n"); } if (f_d>0){ printf("f_t_sizes = [%d", fi->f_t_sizes[0]); for (int ii = 1; ii < f_d; ++ii){printf(", %d", fi->f_t_sizes[ii]);} printf("]\n"); } else{ printf("f_t_sizes = []\n"); } int s_d = fi->s_d; printf("s_d = %d\n", s_d); printf("s_N = %ld\n", fi->s_N); if (s_d>0){ printf("s_nps = [%d", fi->s_nps[0]); for (int ii = 1; ii < s_d; ++ii){printf(", %d", fi->s_nps[ii]);} printf("]\n"); } else{ printf("s_nps = []\n"); } if (s_d>0){ printf("s_t_index = [%d", fi->s_t_index[0]); for (int ii = 1; ii < s_d; ++ii){printf(", %d", fi->s_t_index[ii]);} printf("]\n"); } else{ printf("s_t_index = []\n"); } if (s_d>0){ printf("s_t_sizes = [%d", fi->s_t_sizes[0]); for (int ii = 1; ii < s_d; ++ii){printf(", %d", fi->s_t_sizes[ii]);} printf("]\n"); } else{ printf("s_t_sizes = []\n"); } printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"); } int* get_sketch_owners(MPI_tensor* ten, int flattening, int iscol) { int np_flattening = 1; int* nps = ten->nps; int ii0 = (iscol) ? 0 : flattening; int ii1 = (iscol) ? flattening : ten->d; for (int ii = ii0; ii < ii1; ++ii){ np_flattening = np_flattening * nps[ii]; } int* owners = get_partition(ten->comm_size, np_flattening); return owners; } void get_sketch_height(MPI_tensor* ten, int* owners, int flattening, int iscol, long* X_height_ptr, long* buf_height_ptr) { *X_height_ptr = 0; *buf_height_ptr = 0; flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0); for (int rank = 0; rank < ten->comm_size; ++rank){ long X_height_tmp = 0; for (int jj = owners[rank]; jj < owners[rank + 1]; ++jj){ flattening_info_f_update(fi, ten, jj); X_height_tmp = X_height_tmp + fi->f_N; *buf_height_ptr = (fi->f_N > *buf_height_ptr) ? fi->f_N : *buf_height_ptr; } *X_height_ptr = (X_height_tmp > *X_height_ptr) ? X_height_tmp : *X_height_ptr; } flattening_info_free(fi); } matrix_tt** get_sketch_Omega(const MPI_tensor* ten, int flattening, int r, int buf, int iscol) { // Seed random numbers double t = (double) time(NULL); MPI_Bcast(&t, 1, MPI_DOUBLE, 0, ten->comm); srand((unsigned long) t); int ii0 = iscol ? flattening : 0; int n_Omega = iscol ? (ten->d) - flattening : flattening; matrix_tt** Omegas = (matrix_tt**) malloc(n_Omega * sizeof(matrix_tt*)); for (int ii = 0; ii < n_Omega; ++ii){ Omegas[ii] = matrix_tt_init(ten->n[ii+ii0], r+buf); matrix_tt_dlarnv(Omegas[ii]); } return Omegas; } void get_KR_info(int *d_KR, int *stride_KR, matrix_tt** KRs, MPI_tensor* ten, int flattening, int r, int buf, int iscol) { int max_m = 1000; int assigned = 0; *d_KR = 0; int N_KR = 1; int ii0 = iscol ? flattening : 0; int n_Omega = iscol ? (ten->d) - flattening : flattening; KRs[2] = matrix_tt_init(1, r+buf); for (int ii = 0; ii < n_Omega; ++ii){ if (assigned == 0){ int* partition_ii = ten->partitions[ii + ii0]; int sz_ii = 0; for (int jj = 0; jj < ten->nps[ii+ii0]; ++jj){ int candidate_n = partition_ii[jj+1] - partition_ii[jj]; sz_ii = (sz_ii > candidate_n) ? sz_ii : candidate_n; } if (N_KR * sz_ii < max_m){ *d_KR = ii+1; N_KR = N_KR * sz_ii; } else{ *stride_KR = max_m / N_KR; KRs[0] = matrix_tt_init(N_KR, r+buf); KRs[1] = matrix_tt_init(*stride_KR, r+buf); N_KR = N_KR * (*stride_KR); KRs[3] = matrix_tt_init(N_KR, r+buf); assigned = 1; } } } if (assigned == 0){ *stride_KR = 0; KRs[0] = matrix_tt_init(N_KR, r+buf); KRs[1] = matrix_tt_init(1, r+buf); KRs[3] = matrix_tt_init(N_KR, r+buf); } } sketch* sketch_init(MPI_tensor* ten, int flattening, int r, int buf, int iscol) { sketch* s = (sketch*) malloc(sizeof(sketch)); s->ten = ten; s->flattening = flattening; s->r = r; s->buf = buf; s->iscol = iscol; s->owner_partition = get_sketch_owners(ten, flattening, iscol); long recv_buf_height = 0; get_sketch_height(ten, s->owner_partition, flattening, iscol, &(s->lda), &recv_buf_height); s->Omegas = get_sketch_Omega(ten, flattening, r, buf, iscol); s->X_size = (s->lda)*(r+buf); s->X = (double*) calloc(s->X_size, sizeof(double)); s->scratch = (double*) calloc(s->X_size, sizeof(double)); s->recv_buf = (double*) calloc(recv_buf_height * (r+buf), sizeof(double)); s->fi = flattening_info_init(ten, flattening, iscol, 0); s->KRs = (matrix_tt**) calloc(4, sizeof(matrix_tt*)); get_KR_info(&(s->d_KR), &(s->stride_KR), s->KRs, ten, flattening, r, buf, iscol); return s; } matrix_tt** copy_sketch_Omega(matrix_tt** Omegas, MPI_tensor* ten, int flattening, int r, int buf, int iscol) { int ii0 = iscol ? flattening : 0; int n_Omega = iscol ? (ten->d) - flattening : flattening; matrix_tt** Omegas_cp = (matrix_tt**) malloc(n_Omega * sizeof(matrix_tt*)); for (int ii = 0; ii < n_Omega; ++ii){ submatrix_update(Omegas[ii], 0, ten->n[ii+ii0], 0, r+buf); Omegas_cp[ii] = matrix_tt_copy(Omegas[ii]); } return Omegas_cp; } sketch* sketch_init_with_Omega(MPI_tensor* ten, int flattening, int r, int buf, int iscol, matrix_tt** Omegas) { sketch* s = (sketch*) malloc(sizeof(sketch)); s->ten = ten; s->flattening = flattening; s->r = r; s->buf = buf; s->iscol = iscol; s->owner_partition = get_sketch_owners(ten, flattening, iscol); long recv_buf_height; get_sketch_height(ten, s->owner_partition, flattening, iscol, &(s->lda), &recv_buf_height); s->Omegas = copy_sketch_Omega(Omegas, ten, flattening, r, buf, iscol); s->X_size = (s->lda)*(r+buf); s->X = (double*) calloc(s->X_size, sizeof(double)); s->scratch = (double*) calloc(s->X_size, sizeof(double)); s->recv_buf = (double*) calloc(recv_buf_height * (r+buf), sizeof(double)); s->fi = flattening_info_init(ten, flattening, iscol, 0); s->KRs = (matrix_tt**) calloc(4, sizeof(matrix_tt*)); get_KR_info(&(s->d_KR), &(s->stride_KR), s->KRs, ten, flattening, r, buf, iscol); return s; } // NOTE: does not free the MPI_tensor. We assume this is shared, and should not be freed this way. void sketch_free(sketch* s) { MPI_tensor* ten = s->ten; s->ten = NULL; int d = ten->d; int n_Omega = s->iscol ? d - s->flattening : s->flattening; for (int ii = 0; ii < n_Omega; ++ii){ matrix_tt_free(s->Omegas[ii]); s->Omegas[ii] = NULL; } for (int ii = 0; ii < 4; ++ii){ matrix_tt_free(s->KRs[ii]); s->KRs[ii] = NULL; } free(s->KRs); s->KRs = NULL; free(s->owner_partition); s->owner_partition = NULL; free(s->X); s->X = NULL; free(s->scratch); s->scratch = NULL; free(s->Omegas); s->Omegas = NULL; free(s->recv_buf); s->recv_buf = NULL; flattening_info_free(s->fi); s->fi = NULL; free(s); } void sketch_print(sketch* s) { printf("Printing sketch at %p\n", s); printf("\nten address: %p\n", s->ten); printf("flattening = %d\n",s->flattening); printf("r = %d\n", s->r); printf("buf = %d\n", s->buf); printf("iscol = %d\n", s->iscol); int* op = s->owner_partition; MPI_tensor* ten = s->ten; printf("owner_partition = [%d", op[0]); for (int ii = 1; ii < (ten->comm_size) + 1; ++ii){ printf(", %d", op[ii]); } printf("]\n"); printf("lda = %ld\n", s->lda); printf("X_size = %ld\n", s->X_size); printf("\nX = \n"); int r = s->r; int buf = s->buf; long X_size = s->X_size; long lda = s->lda; matrix_tt* X_mat = matrix_tt_wrap(lda, r+buf, s->X); matrix_tt_print(X_mat, 1); free(X_mat); X_mat = NULL; printf("\nscratch = \n"); matrix_tt* scratch_mat = matrix_tt_wrap(lda, r+buf, s->scratch); matrix_tt_print(scratch_mat, 1); free(scratch_mat); scratch_mat = NULL; int n_Omega = s->iscol ? (s->ten)->d-s->flattening : s->flattening; for (int ii = 0; ii < n_Omega; ++ii){ printf("\nOmegas[%d] = \n", ii); matrix_tt_print(s->Omegas[ii], 1); } } // Performs C[ii + n_ii * jj,kk] = A[ii, kk] * B[jj, kk] void submatrix_khatri_rao_outer_product(matrix_tt* A, matrix_tt* B, matrix_tt* C) { for (int kk = 0; kk < A->n; ++kk){ int A_offset = A->offset + kk*(A->lda); int B_offset = B->offset + kk*(B->lda); int C_offset = C->offset + kk*(C->lda); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, A->m, B->m, 1, 1.0, A->X + A_offset, A->m, B->X + B_offset, 1, 0.0, C->X + C_offset, A->m); } } // General idea of the algorithm: // Split the Omegas into 3 parts: ii < d_KR, ii == d_KR, ii > d_KR // For ii < d_KR, we will pre-multiply the sketch matrices Omega[ii] (Call this KR_1) // For ii == d_KR, we will loop through blocks of Omega[d_KR] // For ii > d_KR, we will loop and multiply to get a row vector (Call this KR_3) // Then, at each point in the loop, we will perform // KR_2 = Omegas[ii] * KR_3 and // KR_4 = KR_1 * KR_2, // where * is the Khatri-Rao product. Finally, we multiply X_mat by KR_4 to update the sketch, and repeat. void subtensor_khatri_rao(sketch* s, matrix_tt* C, flattening_info* fi, double beta, matrix_tt* X_mat) { int r = s->r + s->buf; matrix_tt** Omegas = s->Omegas; MPI_tensor* ten = s->ten; int d_KR = s->d_KR; matrix_tt* KR_1; matrix_tt* KR_4; if ((d_KR == 0) || (d_KR%2 == 1)){ KR_1 = s->KRs[0]; KR_4 = s->KRs[3]; } else{ KR_1 = s->KRs[3]; KR_4 = s->KRs[0]; } int s_d = fi->s_d; int N_kk = 1; int h = 0; int Omega_offset_KR; // printf("Starting loop to get KR_1\n"); for (int ii = 0; ii < s_d; ++ii){ int ii0 = fi->s_t_index[ii]; int ii1 = ii0 + fi->s_t_sizes[ii]; submatrix_update(Omegas[ii], ii0, ii1, 0, r); if (ii > d_KR){ N_kk = N_kk * fi->s_t_sizes[ii]; // Number of elements in outer loop } else if (ii == d_KR){ Omega_offset_KR = ii0; } if ((ii == 0) && (d_KR > 0)){ matrix_tt_reshape(ii1-ii0, r, KR_1); matrix_tt_copy_data(KR_1, Omegas[0]); h = ii1 - ii0; } else if (ii < d_KR){ // Multiply inner matrices matrix_tt* tmp = KR_1; KR_1 = KR_4; KR_4 = tmp; h = h*(ii1-ii0); matrix_tt_reshape(h, r, KR_1); submatrix_khatri_rao_outer_product(KR_4, Omegas[ii], KR_1); } } // printf("Finished loop to get KR_1\n"); if (fi->iscol){ matrix_tt_wrap_update(X_mat, fi->f_N, fi->s_N, get_X(ten)); } else{ matrix_tt_wrap_update(X_mat, fi->s_N, fi->f_N, get_X(ten)); } X_mat->transpose = (fi->iscol ? 0 : 1); if (d_KR == s_d){ // If we have done everything, just multiply (the sketch is relatively small) matrix_tt_dgemm(X_mat, KR_1, C, 1.0, beta); return; } int stride_KR = s->stride_KR; matrix_tt* KR_2 = s->KRs[1]; matrix_tt* KR_3 = s->KRs[2]; int* t_kk = ten->t_kk; int size_KR = fi->s_t_sizes[d_KR]; int N_ll = 1 + (size_KR - 1) / stride_KR; int tensor_offset = 0; for (int kk = 0; kk < N_kk; ++kk) { to_tensor_ind(t_kk, (long) kk, fi->s_t_sizes + d_KR + 1, s_d - 1 - d_KR); for (int ii = d_KR + 1; ii < s_d; ++ii){ if (ii == d_KR + 1){ for (int jj = 0; jj < r; ++jj){ KR_3->X[jj] = matrix_tt_element(Omegas[ii], t_kk[ii-d_KR-1], jj); } } else{ for (int jj = 0; jj < r; ++jj){ KR_3->X[jj] *= matrix_tt_element(Omegas[ii], t_kk[ii-d_KR-1], jj); } } } for (int ll = 0; ll < N_ll; ++ll){ double bb = ((kk==0) && (ll==0)) ? beta : 1.0; int ii0 = Omega_offset_KR + ll * stride_KR; int ii1 = ((ll+1)*stride_KR > size_KR) ? size_KR + Omega_offset_KR: (ll+1)*stride_KR + Omega_offset_KR; submatrix_update(Omegas[d_KR], ii0, ii1, 0, r); if (d_KR + 1 == s_d){ // If we only need KR_1 and Omegas[ii] matrix_tt_reshape((KR_1->m) * (ii1-ii0), r, KR_4); submatrix_khatri_rao_outer_product(KR_1, Omegas[d_KR], KR_4); } else if (d_KR == 0){ // If we only need Omegas[ii] and KR_3 matrix_tt_reshape(Omegas[d_KR]->m, r, KR_4); submatrix_khatri_rao_outer_product(Omegas[d_KR], KR_3, KR_4); } else{ // We need everything... matrix_tt_reshape(ii1-ii0, r, KR_2); submatrix_khatri_rao_outer_product(Omegas[d_KR], KR_3, KR_2); matrix_tt_reshape((ii1-ii0) * (KR_1->m), r, KR_4); submatrix_khatri_rao_outer_product(KR_1, KR_2, KR_4); } if (fi->iscol) { submatrix_update(X_mat, 0, fi->f_N, tensor_offset, tensor_offset + KR_4->m); } else { submatrix_update(X_mat, tensor_offset, tensor_offset + KR_4->m, 0, fi->f_N); } matrix_tt_dgemm(X_mat, KR_4, C, 1.0, bb); tensor_offset = tensor_offset + KR_4->m; } } } int get_owner(int block, int* owner_partition, int comm_size) { int color = -1; for (int ii = 0; ii < comm_size; ++ii){ if ((block >= owner_partition[ii]) && (block < owner_partition[ii+1])){ color = ii; } } return color; } int s_get_owner(sketch* s, int f_v_block){ int* op = s->owner_partition; MPI_tensor* ten = s->ten; int size = ten->comm_size; // Binary search (basically wikipedia) int a = 0; int b = size-1; int c; while (a <= b){ c = (a+b)/2; if (f_v_block < op[c]){ b = c-1; } else if(f_v_block >= op[c+1]){ a = c+1; } else{ return c; } } return -1; } void own_submatrix_update(matrix_tt* mat, sketch* s, int f_v_block, int with_buf){ if (f_v_block == -1){ return; } int sketch_offset = 0; int sketch_lda = s->lda; MPI_tensor* ten = s->ten; int world_rank = ten->rank; int* owner_partition = s->owner_partition; flattening_info* fi = s->fi; if ((f_v_block < owner_partition[world_rank]) || (f_v_block >= owner_partition[world_rank+1])){ printf("r%d own_submatrix: This core does not own f_v_block = %d\n", world_rank, f_v_block); } for (int block = s->owner_partition[world_rank]; block < f_v_block; ++block){ flattening_info_f_update(fi, ten, block); sketch_offset = sketch_offset + fi->f_N; } flattening_info_f_update(fi, ten, f_v_block); matrix_tt_wrap_update(mat, sketch_lda, s->r + s->buf, s->X); int r = (with_buf) ? s->r + s->buf : s->r; submatrix_update(mat, sketch_offset, sketch_offset + fi->f_N, 0, r); } matrix_tt* own_submatrix(sketch* s, int f_v_block, int with_buf){ matrix_tt* mat = (matrix_tt*) malloc(sizeof(matrix_tt)); own_submatrix_update(mat, s, f_v_block, with_buf); return mat; } void subtensor_sketch_multiply(sketch* s, flattening_info* fi, matrix_tt** holders) { MPI_tensor* ten = s->ten; int* owner_partition = s->owner_partition; int world_size = ten->comm_size; int world_rank = ten->rank; // Actually sketch the thing matrix_tt* sketch_mat = holders[0]; double beta = 0.0; if (ten->current_part != -1){ int current_color = get_owner(fi->f_v_block, owner_partition, world_size); if (current_color == world_rank){ own_submatrix_update(sketch_mat, s, fi->f_v_block, 1); beta = 1.0; } else{ matrix_tt_wrap_update(sketch_mat, fi->f_N, s->r + s->buf, s->scratch); beta = 0.0; } subtensor_khatri_rao(s, sketch_mat, fi, beta, holders[1]); } } void subtensor_sketch_communicate(sketch* s, int stream_step, flattening_info* fi, matrix_tt** holders) { MPI_tensor* ten = s->ten; int* owner_partition = s->owner_partition; int world_size = ten->comm_size; int world_rank = ten->rank; int* group_ranks = ten->group_ranks; flattening_info* fi_tmp = s->fi; matrix_tt* sketch_mat = holders[0]; // For each flattening block for (int ii = 0; ii < fi->f_Nblocks; ++ii){ int kk = 0; int owner_ii = get_owner(ii, owner_partition, world_size); int group_owner; // For each rank in the world for (int jj = 0; jj < world_size; ++jj){ // If the rank owns the block if (owner_ii == jj){ // Add it to the group group_ranks[kk] = jj; kk = kk+1; group_owner = jj; } else{ int* schedule_jj = ten->schedule[jj]; int stream_jj = schedule_jj[stream_step]; if (stream_jj != -1){ flattening_info_update(fi_tmp, ten, schedule_jj[stream_step]); // Else, if the rank just calculated something that adds to the block if (ii == fi_tmp->f_v_block){ // Add it to the group group_ranks[kk] = jj; kk = kk+1; } } } } if (world_rank == owner_ii){ matrix_tt* comm_matrix = holders[1]; own_submatrix_update(comm_matrix, s, ii, 1); matrix_tt* buf_mat = holders[2]; matrix_tt_wrap_update(buf_mat, comm_matrix->m, comm_matrix->n, s->recv_buf); matrix_tt_group_reduce(ten->comm, world_rank, comm_matrix, buf_mat, owner_ii, group_ranks, kk); } else if (sketch_mat->X){ matrix_tt* buf_mat = holders[2]; matrix_tt_wrap_update(buf_mat, sketch_mat->m, sketch_mat->n, s->recv_buf); matrix_tt_group_reduce(ten->comm, world_rank,sketch_mat, buf_mat, owner_ii, group_ranks, kk); } } } void multi_perform_sketch(sketch** sketches, int n_sketch) { int n_holders = 3; matrix_tt** holders = (matrix_tt**) malloc(n_holders*n_sketch*sizeof(matrix_tt*)); for (int ii = 0; ii < n_holders*n_sketch; ++ii){ holders[ii] = (matrix_tt*) calloc(1, sizeof(matrix_tt)); } MPI_tensor* ten = sketches[0]->ten; // Tensor int rank = ten->rank; int* schedule_rank = ten->schedule[rank]; flattening_info** fis = (flattening_info**) calloc(n_sketch, sizeof(flattening_info*)); for (int ii = 0; ii < n_sketch; ++ii){ fis[ii] = flattening_info_init(ten, sketches[ii]->flattening, sketches[ii]->iscol, 0); } for (int ii = 0; ii < ten->n_schedule; ++ii){ stream(ten, schedule_rank[ii]); for (int jj = 0; jj < n_sketch; ++jj){ matrix_tt** holders_jj = holders + jj*n_holders; flattening_info_update(fis[jj], ten, ten->current_part); holders_jj[0]->X = NULL; subtensor_sketch_multiply(sketches[jj], fis[jj], holders_jj); } for (int jj = 0; jj < n_sketch; ++jj){ matrix_tt** holders_jj = holders + jj*n_holders; subtensor_sketch_communicate(sketches[jj], ii, fis[jj], holders_jj); } } for (int ii = 0; ii < n_holders*n_sketch; ++ii){ free(holders[ii]); holders[ii] = NULL; } for (int ii = 0; ii < n_sketch; ++ii){ flattening_info_free(fis[ii]); fis[ii] = NULL; } free(fis); fis = NULL; free(holders); holders = NULL; } void sketch_qr(sketch* sketch) { MPI_tensor* ten = sketch->ten; int* owner_partition = sketch->owner_partition; int flattening = sketch->flattening; int iscol = sketch->iscol; int r = sketch->r; int buf = sketch->buf; MPI_Comm comm = ten->comm; int size = ten->comm_size; int rank = ten->rank; // A little pre-processing int head = 0; flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0); int* Ns = (int*) calloc(size, sizeof(int)); for (int ii = 0; ii < size; ++ii){ for (int jj = owner_partition[ii]; jj < owner_partition[ii+1]; ++jj){ flattening_info_f_update(fi, ten, jj); Ns[ii] = Ns[ii] + fi->f_N; } } int N_rank = Ns[rank]; int lda = sketch->lda; matrix_tt* Q_big = matrix_tt_wrap(lda, r+buf, sketch->X); matrix_tt* Q = submatrix(Q_big, 0, N_rank, 0, r+buf); matrix_tt* Q_head = NULL; matrix_tt* R = NULL; if (rank == head){ Q_head = matrix_tt_init(size * (r+buf), r+buf); R = submatrix(Q_head, 0, r+buf, 0, r+buf); } else{ R = matrix_tt_init(r+buf, r+buf); } matrix_tt_truncated_qr(Q, R, r+buf); // Gather the Rs for (int jj = 0; jj < r+buf; ++jj){ // printf("r%d jj%d\n", rank, jj); if (rank == head){ double* col = Q_head->X + jj*(Q_head->lda); MPI_Gather(col, r+buf, MPI_DOUBLE, col, r+buf, MPI_DOUBLE, head, comm); } else{ MPI_Gather(R->X + jj*(R->lda), r+buf, MPI_DOUBLE, NULL, r+buf, MPI_DOUBLE, head, comm); } } // Take the QR of the Rs if (rank == head){ matrix_tt_truncated_qr(Q_head, NULL, r+buf); } // Scatter the Q of the preceding step for (int jj = 0; jj < r+buf; ++jj){ if (rank == head){ double* col = Q_head->X + jj*(Q_head->lda); MPI_Scatter(col, r+buf, MPI_DOUBLE, col, r+buf, MPI_DOUBLE, head, comm); } else{ MPI_Scatter(NULL, r+buf, MPI_DOUBLE, R->X + jj*(R->lda), r+buf, MPI_DOUBLE, head, comm); } } // Multiply to get the final Q matrix_tt* X_big = matrix_tt_wrap(lda, r, sketch->scratch); matrix_tt* new_X = submatrix(X_big, 0, N_rank, 0, r); matrix_tt* Q_head_sub = submatrix(R, 0, r+buf, 0, r); matrix_tt_dgemm(Q, Q_head_sub, new_X, 1.0, 0.0); // Switch so the QR lives in X double* tmp = sketch->scratch; sketch->scratch = sketch->X; sketch->X = tmp; free(X_big); X_big = NULL; free(new_X); new_X = NULL; free(Q_head_sub); Q_head_sub = NULL; flattening_info_free(fi); fi = NULL; free(Ns); Ns = NULL; free(Q_big); Q_big = NULL; free(Q); Q = NULL; if (rank == head){ matrix_tt_free(Q_head); Q_head = NULL; free(R); R = NULL; } else{ matrix_tt_free(R); R = NULL; } } void perform_sketch(sketch* s) { multi_perform_sketch(&s, 1); } // Gets the sketch block from the correct owner (stored in fi->f_v_block). Returns a matrix with the correct dimensions void sendrecv_sketch_block(matrix_tt* mat, sketch* s, flattening_info* fi, int recv_rank, int with_buf) { int f_v_block = fi->f_v_block; MPI_tensor* ten = s->ten; int rank = ten->rank; MPI_Comm comm = ten->comm; int owner = s_get_owner(s, f_v_block); int r = (with_buf) ? s->r + s->buf : s->r; if (rank == recv_rank){ if (rank == owner){ own_submatrix_update(mat, s, f_v_block, with_buf); } else{ matrix_tt_wrap_update(mat, fi->f_N, r, s->scratch); matrix_tt_recv(comm, mat, owner); } } else{ if(rank == owner){ own_submatrix_update(mat, s, f_v_block, with_buf); matrix_tt_send(comm, mat, recv_rank); } mat->X = NULL; } } // Eats s, so be careful! MPI_tensor* sketch_to_tensor(sketch** s_ptr) { sketch* s = *s_ptr; MPI_tensor* sten = (MPI_tensor*) malloc(sizeof(MPI_tensor)); MPI_tensor* ten = s->ten; int rank = ten->rank; int size = ten->comm_size; flattening_info* fi = flattening_info_init(ten, s->flattening, s->iscol, 0); // Get the schedule from the owner_partition int n_schedule = 0; int* owners = s->owner_partition; for (int ii = 0; ii < size; ++ii){ int sz = owners[ii+1] - owners[ii]; n_schedule = (n_schedule > sz) ? n_schedule : sz; } int** schedule = (int**) malloc(size * sizeof(int*)); int* inverse_schedule = (int*) malloc(fi->f_Nblocks * sizeof(int)); for (int ii = 0; ii < size; ++ii){ schedule[ii] = (int*) malloc(n_schedule * sizeof(int)); int* schedule_ii = schedule[ii]; int jj0 = owners[ii]; int sz = owners[ii+1] - jj0; for (int jj = 0; jj < n_schedule; ++jj){ if (jj < sz){ schedule_ii[jj] = jj+jj0; inverse_schedule[jj+jj0] = ii*n_schedule + jj; } else{ schedule_ii[jj] = -1; } } } int d = fi->f_d + 1; int soffset = (s->iscol) ? 0 : 1; int offset = (s->iscol) ? 0 : s->flattening; int end_ind = (s->iscol) ? d-1 : 0; // Inherit the properties of ten int* n = (int*) malloc(d * sizeof(int)); int* nps = (int*) malloc(d * sizeof(int)); int** partitions = (int**) malloc(d * sizeof(int*)); for (int ii = 0; ii < d-1; ++ii){ n[ii + soffset] = ten->n[ii + offset]; nps[ii + soffset] = ten->nps[ii + offset]; partitions[ii + soffset] = (int*) malloc( (nps[ii+soffset] + 1) * sizeof(int)); int* spartition_ii = partitions[ii+soffset]; int* partition_ii = ten->partitions[ii+offset]; for (int jj = 0; jj < nps[ii+soffset] + 1; ++jj){ spartition_ii[jj] = partition_ii[jj]; } } // Set the special sketched dimension properties n[end_ind] = s->r; nps[end_ind] = 1; partitions[end_ind] = (int*) malloc( (nps[end_ind] + 1) * sizeof(int)); int* spartition_end = partitions[end_ind]; spartition_end[0] = 0; spartition_end[1] = n[end_ind]; // Get the parameters giving the subtensor locations double** subtensors = (double**) malloc(n_schedule * sizeof(double*)); int* schedule_rank = schedule[rank]; int with_buf = 0; long scratch_offset = 0; for (int ii = 0; ii < n_schedule; ++ii){ if (schedule_rank[ii] != -1){ matrix_tt* X_submat = own_submatrix(s, schedule_rank[ii], with_buf); subtensors[ii] = s->scratch + scratch_offset; matrix_tt* scratch_submat = matrix_tt_wrap(X_submat->m, X_submat->n, subtensors[ii]); matrix_tt_copy_data(scratch_submat, X_submat); scratch_offset = scratch_offset + X_submat->n * X_submat->m; free(X_submat); free(scratch_submat); } } void* parameters = p_static_init(subtensors); // Assigning fields sten->d = d; sten->n = n; sten->comm = ten->comm; sten->rank = ten->rank; sten->comm_size = ten->comm_size; sten->schedule = schedule; sten->n_schedule = n_schedule; sten->inverse_schedule = inverse_schedule; sten->partitions = partitions; sten->nps = nps; sten->current_part = -1; sten->f_ten = NULL; sten->parameters = parameters; sten->X_size = s->X_size; sten->X = s->scratch; sten->ind1 = (int*) malloc(d * sizeof(int)); sten->ind2 = (int*) malloc(d * sizeof(int)); sten->tensor_part = (int*) malloc(d * sizeof(int)); sten->group_ranks = (int*) malloc(ten->comm_size * sizeof(int)); sten->t_kk = (int*) malloc(d * sizeof(int)); // Freeing sketch things int n_Omega = s->iscol ? ten->d - s->flattening : s->flattening; for (int ii = 0; ii < n_Omega; ++ii){ matrix_tt_free(s->Omegas[ii]); s->Omegas[ii] = NULL; } for (int ii = 0; ii < 4; ++ii){ matrix_tt_free(s->KRs[ii]); s->KRs[ii] = NULL; } free(s->KRs); s->KRs = NULL; s->ten = NULL; free(s->owner_partition); s->owner_partition = NULL; free(s->X); s->X = NULL; free(s->Omegas); s->Omegas = NULL; free(s->recv_buf); s->recv_buf = NULL; flattening_info_free(s->fi); s->fi = NULL; free(s); *s_ptr = NULL; flattening_info_free(fi); return sten; }
{ "alphanum_fraction": 0.554265097, "avg_line_length": 31.1493027071, "ext": "c", "hexsha": "f839fadf2b29677c37488abe76ddcb5c097db805", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_path": "src/sketch.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_path": "src/sketch.c", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_path": "src/sketch.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 12193, "size": 37971 }
#include <gsl/gsl_errno.h> #include <gsl/matrix/gsl_matrix.h> #define BASE_DOUBLE #include <gsl/templates_on.h> #include <gsl/matrix/matrix_source.c> #include <gsl/templates_off.h> #undef BASE_DOUBLE
{ "alphanum_fraction": 0.7772277228, "avg_line_length": 20.2, "ext": "c", "hexsha": "1b965a5eaa1520e0a4057b71f20027175511f7c8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_line_length": 37, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/matrix.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 55, "size": 202 }
/** * Copyright 2016 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es> * * This file is part of Matrix Market Suite. * * Matrix Market Suite is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Matrix Market Suite is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>. */ #include <lapacke.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include "LUDecomposition.h" void usageLUDecomposition(){ fprintf(stderr, "\n"); fprintf(stderr, "Usage: MM-Suite LUDecomposition [options] <input-matrix>\n"); fprintf(stderr, "\nInput/output options:\n\n"); fprintf(stderr, " -o STR Output file name. Default: stdout\n"); fprintf(stderr, " -r Input format is row per line. Default: False\n"); fprintf(stderr, "\n"); } int LUDecomposition(int argc, char *argv[]) { int ret_code = 1; int option; unsigned long *II; unsigned long *J; double *values; unsigned long M; unsigned long N; unsigned long long nz; int _M; int _N; char *outputFileName = NULL; char *inputMatrixFile = NULL; int inputFormatRow = 0; while ((option = getopt(argc, argv,"ro:")) >= 0) { switch (option) { case 'o' : //free(outputFileName); outputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1); strcpy(outputFileName,optarg); break; case 'r': inputFormatRow = 1; break; default: break; } } if ((optind + 1 > argc) || (optind + 2 <= argc)) { usageLUDecomposition(); return 0; } if(outputFileName == NULL) { outputFileName = (char *) malloc(sizeof(char)*7); sprintf(outputFileName,"stdout"); } inputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1); strcpy(inputMatrixFile,argv[optind]); //Read matrix if(inputFormatRow){ if(!readDenseCoordinateMatrixRowLine(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } } else { if(!readDenseCoordinateMatrix(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){ fprintf(stderr, "[%s] Can not read Matrix\n",__func__); return 0; } } _M = (int) M; _N = (int) N; int ipiv[_M]; /* lapack_int LAPACKE_dgetrf( int matrix_layout, lapack_int m, lapack_int n, double* a, lapack_int lda, lapack_int* ipiv ); */ ret_code = LAPACKE_dgetrf(LAPACK_ROW_MAJOR,_M,_N, values,_N, ipiv); if(inputFormatRow){ writeLUCoordinateMatrixRowLine(outputFileName, values,M,N,nz, ipiv); } else{ writeLUCoordinateMatrix(outputFileName, values,M,N,nz, ipiv); } //writeDenseCoordinateMatrix("stdout",values,M,N,nz); if(!ret_code) return 1; else return 0; }
{ "alphanum_fraction": 0.6557326793, "avg_line_length": 22.8111888112, "ext": "c", "hexsha": "b5ce4d4327e97835f94d0f300fcbe0171bc0f2f2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "vkeller/math-454", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/LUDecomposition.c", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "num_tokens": 922, "size": 3262 }
#pragma once #include <Hypo/Config.h> #include <Hypo/System/Exports.h> #include <gsl/span> #include <Hypo/System/Streams/MemoryStream.h> #include <Hypo/System/Buffer/Buffer.h> namespace Hypo { class HYPO_SYSTEM_API BinaryReader { public: BinaryReader(std::istream& stream); BinaryReader& operator >>(uInt8& value); BinaryReader& operator >>(uInt16& value); BinaryReader& operator >>(uInt32& value); BinaryReader& operator >>(uInt64& value); BinaryReader& operator >>(Int8& value ); BinaryReader& operator >>(Int16& value); BinaryReader& operator >>(Int32& value); BinaryReader& operator >>(Int64& value); BinaryReader& operator >>(std::string& value); template<typename T> BinaryReader& operator >>(std::vector<T>& value) { uInt32 size = 0; *this >> size; for (int i = 0; i < size; i++) { T elem; *this >> elem; value.push_back(elem); } return *this; } std::vector<unsigned char> ReadRaw(int size); void ReadRaw(void* buffer, int size); void ReadBOM(); void Read7BitEncoded(uInt32& value); void Read7BitEncoded(uInt64& value); bool Good()const { return m_Stream.good(); } bool Bad()const { return m_Stream.bad(); } bool Fail() const { return m_Stream.fail(); } bool Eof() const { return m_Stream.eof(); } std::istream& GetStream() const { return m_Stream; } private: std::istream& m_Stream; }; template <typename T> class BasicMemoryBinaryReader : public BinaryReader /// A convenient wrapper for using Buffer and MemoryStream with BinaryReader. { public: BasicMemoryBinaryReader(const Buffer<T>& data) : BinaryReader(_istr), _data(data), _istr(data.begin(), data.Capacity()) { } ~BasicMemoryBinaryReader() { } const Buffer<T>& data() const { return _data; } const MemoryInputStream& stream() const { return _istr; } MemoryInputStream& stream() { return _istr; } private: const Buffer<T>& _data; MemoryInputStream _istr; }; typedef BasicMemoryBinaryReader<char> MemoryBinaryReader; }
{ "alphanum_fraction": 0.672815534, "avg_line_length": 19.8076923077, "ext": "h", "hexsha": "7d1c3a8adf687f2550618655d56d05c960174f8c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "TheodorLindberg/Hypo", "max_forks_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "TheodorLindberg/Hypo", "max_issues_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "TheodorLindberg/Hypo", "max_stars_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryReader.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 592, "size": 2060 }
/** * \copyright * Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once /// The LinearSolverLibrarySetup takes care of proper initialization and /// shutting down of an external linear solver library. The concrete /// implementation is chosen by the build system. /// An object of this class must be created at the begining of the scope where /// it is used. When the scope closes (or the object is destroyed explicitly) /// library shutting down functions are automatically called. /// The default implementation is empty providing polymorphic behaviour when /// using this class. #include "NumLib/DOF/GlobalMatrixProviders.h" #if defined(USE_PETSC) #include <petsc.h> #include <mpi.h> namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int argc, char* argv[]) { MPI_Init(&argc, &argv); char help[] = "ogs6 with PETSc \n"; PetscInitialize(&argc, &argv, nullptr, help); } ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); PetscFinalize(); MPI_Finalize(); } }; } // ApplicationsLib #elif defined(USE_LIS) #include <lis.h> namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int argc, char* argv[]) { lis_initialize(&argc, &argv); } ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); lis_finalize(); } }; } // ApplicationsLib #else namespace ApplicationsLib { struct LinearSolverLibrarySetup final { LinearSolverLibrarySetup(int /*argc*/, char* /*argv*/[]) {} ~LinearSolverLibrarySetup() { NumLib::cleanupGlobalMatrixProviders(); } }; } // ApplicationsLib #endif
{ "alphanum_fraction": 0.6849385246, "avg_line_length": 25.6842105263, "ext": "h", "hexsha": "8ae299b6627698d65661538100560a71333ae379", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_forks_repo_licenses": [ "BSD-4-Clause" ], "max_forks_repo_name": "hosseinsotudeh/ogs", "max_forks_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-4-Clause" ], "max_issues_repo_name": "hosseinsotudeh/ogs", "max_issues_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "214afcb00af23e4393168a846c7ee8ce4f13e489", "max_stars_repo_licenses": [ "BSD-4-Clause" ], "max_stars_repo_name": "hosseinsotudeh/ogs", "max_stars_repo_path": "Applications/ApplicationsLib/LinearSolverLibrarySetup.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 438, "size": 1952 }
/* GLIB - Library of useful routines for C programming * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the GLib Team and others 1997-2000. See the AUTHORS * file for a list of people on the GLib Team. See the ChangeLog * files for a list of changes. These files are distributed with * GLib at ftp://ftp.gtk.org/pub/gtk/. */ #ifndef __G_LIB_H__ #define __G_LIB_H__ #include <galloca.h> #include <garray.h> #include <gasyncqueue.h> #include <gbacktrace.h> #include <gcache.h> #include <gcompat.h> #include <gcompletion.h> #include <gconvert.h> #include <gdataset.h> #include <gdate.h> #include <gerror.h> #include <gfileutils.h> #include <ghash.h> #include <ghook.h> #include <giochannel.h> #include <glist.h> #include <gmacros.h> #include <gmain.h> #include <gmarkup.h> #include <gmem.h> #include <gmessages.h> #include <gnode.h> #include <gprimes.h> #include <gqsort.h> #include <gquark.h> #include <gqueue.h> #include <grand.h> #include <grel.h> #include <gscanner.h> #include <gshell.h> #include <gslist.h> #include <gspawn.h> #include <gstrfuncs.h> #include <gstring.h> #include <gthread.h> #include <gthreadpool.h> #include <gtimer.h> #include <gtree.h> #include <gtypes.h> #include <gunicode.h> #include <gutils.h> #ifdef G_OS_WIN32 #include <gwin32.h> #endif #endif /* __G_LIB_H__ */
{ "alphanum_fraction": 0.7277936963, "avg_line_length": 27.5526315789, "ext": "h", "hexsha": "689f2e8699ece5f0e8ce8730ff1f641541dd7049", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_path": "vega-vc9/include/glib/glib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_path": "vega-vc9/include/glib/glib.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_path": "vega-vc9/include/glib/glib.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 563, "size": 2094 }
#include <stdio.h> #include <gsl/gsl_multiset.h> void print_all_multisets ( size_t n, size_t k ); int main (void) { gsl_multiset * c; size_t i; printf("all multisets of {0,1,2,3} by size (lex. order)\n") ; for(i = 0; i <= 4; i++) { c = gsl_multiset_calloc (4, i); do { printf("{"); gsl_multiset_fprintf (stdout, c, " %u"); printf(" }\n"); } while (gsl_multiset_next(c) == GSL_SUCCESS); gsl_multiset_free(c); } printf("all multisets of {1,2,3,4} by size (reverse lex. order)\n") ; for(i = 0; i <= 4; i++) { c = gsl_multiset_alloc (4, i) ; gsl_multiset_init_last(c) ; do { printf("{"); gsl_multiset_fprintf (stdout, c, " %u"); printf(" }\n"); } while (gsl_multiset_prev(c) == GSL_SUCCESS); gsl_multiset_free(c); } printf("\n"); print_all_multisets(5, 3); print_all_multisets(5, 0); print_all_multisets(5, 5); print_all_multisets(1, 1); print_all_multisets(3, 1); return 0; } void print_all_multisets (size_t n, size_t k) { gsl_multiset * c = gsl_multiset_calloc (n, k); printf("multisets %u choose %u (with replacement)\n", n, k); do { gsl_multiset_fprintf (stdout, c, " %u"); printf("\n"); } while (gsl_multiset_next(c) == GSL_SUCCESS); while (gsl_multiset_next(c) == GSL_SUCCESS); do { gsl_multiset_fprintf (stdout, c, " %u"); printf("\n"); } while (gsl_multiset_prev(c) == GSL_SUCCESS); printf("\n"); gsl_multiset_free(c); }
{ "alphanum_fraction": 0.5655478151, "avg_line_length": 21.6301369863, "ext": "c", "hexsha": "3c4749ad945bc3160a4e6d3467045777734f93cf", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multiset/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multiset/demo.c", "max_line_length": 71, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multiset/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 515, "size": 1579 }
#pragma once #include <gsl/span> #include "halley/text/halleystring.h" #include "halley/resources/resource.h" #include "halley/maths/range.h" #include "halley/maths/vector4.h" #include "halley/data_structures/maybe.h" #include <map> #include <vector> #include "halley/utils/type_traits.h" #if defined(DEV_BUILD) #define STORE_CONFIG_NODE_PARENTING #endif namespace Halley { class Serializer; class Deserializer; class ConfigNode; template<typename T> struct HasToConfigNode { private: typedef std::true_type yes; typedef std::false_type no; template<typename U> static auto test(int) -> decltype(std::declval<U>().toConfigNode(), yes()); template<typename> static no test(...); public: static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value; }; template<typename T> struct HasConfigNodeConstructor { private: typedef std::true_type yes; typedef std::false_type no; template<typename U> static auto test(int) -> decltype(U(std::declval<ConfigNode>()), yes()); template<typename> static no test(...); public: static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value; }; enum class ConfigNodeType { Undefined, String, Sequence, Map, Int, Float, Int2, Float2, Bytes, DeltaSequence, // For delta coding DeltaMap, // For delta coding Noop, // For delta coding Idx, // For delta coding Del // For delta coding }; template <> struct EnumNames<ConfigNodeType> { constexpr std::array<const char*, 13> operator()() const { return{{ "undefined", "string", "sequence", "map", "int", "float", "int2", "float2", "bytes", "deltaSequence", "deltaMap", "noop", "idx" "del" }}; } }; class ConfigFile; class ConfigNode { friend class ConfigFile; public: using MapType = std::map<String, ConfigNode, std::less<>>; using SequenceType = std::vector<ConfigNode>; struct NoopType {}; struct DelType {}; struct IdxType { int start; int len; IdxType() = default; IdxType(int start, int len) : start(start), len(len) {} }; ConfigNode(); explicit ConfigNode(const ConfigNode& other); ConfigNode(ConfigNode&& other) noexcept; ConfigNode(MapType entryMap); ConfigNode(SequenceType entryList); explicit ConfigNode(String value); explicit ConfigNode(const std::string_view& value); explicit ConfigNode(bool value); explicit ConfigNode(int value); explicit ConfigNode(float value); explicit ConfigNode(Vector2i value); explicit ConfigNode(Vector2f value); explicit ConfigNode(Bytes value); explicit ConfigNode(NoopType value); explicit ConfigNode(DelType value); explicit ConfigNode(IdxType value); template <typename T> explicit ConfigNode(const std::vector<T>& sequence) { *this = sequence; } template <typename K, typename V> explicit ConfigNode(const std::map<K, V>& values) { *this = values; } ~ConfigNode(); ConfigNode& operator=(const ConfigNode& other); ConfigNode& operator=(ConfigNode&& other) noexcept; ConfigNode& operator=(bool value); ConfigNode& operator=(int value); ConfigNode& operator=(float value); ConfigNode& operator=(Vector2i value); ConfigNode& operator=(Vector2f value); ConfigNode& operator=(MapType entryMap); ConfigNode& operator=(SequenceType entryList); ConfigNode& operator=(String value); ConfigNode& operator=(Bytes value); ConfigNode& operator=(gsl::span<const gsl::byte> bytes); ConfigNode& operator=(const char* value); ConfigNode& operator=(const std::string_view& value); ConfigNode& operator=(NoopType value); ConfigNode& operator=(DelType value); ConfigNode& operator=(IdxType value); template <typename T> ConfigNode& operator=(const std::vector<T>& sequence) { SequenceType seq; seq.reserve(sequence.size()); for (const auto& e: sequence) { if constexpr (HasToConfigNode<T>::value) { seq.push_back(e.toConfigNode()); } else { seq.push_back(ConfigNode(e)); } } return *this = seq; } template <typename K, typename V> ConfigNode& operator=(const std::map<K, V>& values) { MapType map; for (const auto& [k, v]: values) { String key = toString(k); if constexpr (HasToConfigNode<V>::value) { map[std::move(key)] = v.toConfigNode(); } else { map[std::move(key)] = ConfigNode(v); } } return *this = map; } bool operator==(const ConfigNode& other) const; bool operator!=(const ConfigNode& other) const; ConfigNodeType getType() const; void serialize(Serializer& s) const; void deserialize(Deserializer& s); int asInt() const; float asFloat() const; bool asBool() const; Vector2i asVector2i() const; Vector2f asVector2f() const; Vector3i asVector3i() const; Vector3f asVector3f() const; Vector4i asVector4i() const; Vector4f asVector4f() const; Range<float> asFloatRange() const; String asString() const; const Bytes& asBytes() const; int asInt(int defaultValue) const; float asFloat(float defaultValue) const; bool asBool(bool defaultValue) const; String asString(const std::string_view& defaultValue) const; Vector2i asVector2i(Vector2i defaultValue) const; Vector2f asVector2f(Vector2f defaultValue) const; Vector3i asVector3i(Vector3i defaultValue) const; Vector3f asVector3f(Vector3f defaultValue) const; Vector4i asVector4i(Vector4i defaultValue) const; Vector4f asVector4f(Vector4f defaultValue) const; template <typename T> std::vector<T> asVector() const { if (type == ConfigNodeType::Sequence) { std::vector<T> result; result.reserve(asSequence().size()); for (const auto& e : asSequence()) { if constexpr (HasConfigNodeConstructor<T>::value) { result.emplace_back(T(e)); } else { result.emplace_back(e.convertTo(Tag<T>())); } } return result; } else if (type == ConfigNodeType::Undefined) { return {}; } else { throw Exception("Can't convert " + getNodeDebugId() + " from " + toString(getType()) + " to std::vector<T>.", HalleyExceptions::Resources); } } template <typename T> std::vector<T> asVector(const std::vector<T>& defaultValue) const { if (type == ConfigNodeType::Sequence) { return asVector<T>(); } else { return defaultValue; } } template <typename K, typename V> std::map<K, V> asMap() const { if (type == ConfigNodeType::Map) { std::map<K, V> result; for (const auto& [k, v] : asMap()) { const K key = fromString<K>(k); if constexpr (HasConfigNodeConstructor<V>::value) { result[std::move(key)] = V(v); } else { result[std::move(key)] = v.convertTo(Tag<V>()); } } return result; } else if (type == ConfigNodeType::Undefined) { return {}; } else { throw Exception("Can't convert " + getNodeDebugId() + " from " + toString(getType()) + " to std::map<K, V>.", HalleyExceptions::Resources); } } const SequenceType& asSequence() const; const MapType& asMap() const; SequenceType& asSequence(); MapType& asMap(); void ensureType(ConfigNodeType type); bool hasKey(const String& key) const; void removeKey(const String& key); ConfigNode& operator[](const std::string_view& key); ConfigNode& operator[](size_t idx); const ConfigNode& operator[](const std::string_view& key) const; const ConfigNode& operator[](size_t idx) const; SequenceType::iterator begin(); SequenceType::iterator end(); SequenceType::const_iterator begin() const; SequenceType::const_iterator end() const; void reset(); void setOriginalPosition(int line, int column); void setParent(const ConfigNode* parent, int idx); void propagateParentingInformation(const ConfigFile* parentFile); inline void assertValid() const { Expects(intData != 0xCDCDCDCD); Expects(intData != 0xDDDDDDDD); } struct BreadCrumb { const BreadCrumb* prev = nullptr; String key; OptionalLite<int> idx; int depth = 0; BreadCrumb() = default; BreadCrumb(const BreadCrumb& prev, String key) : prev(&prev), key(std::move(key)), depth(prev.depth + 1) {} BreadCrumb(const BreadCrumb& prev, int index) : prev(&prev), idx(index), depth(prev.depth + 1) {} bool hasKeyAt(const String& key, int depth) const; bool hasIndexAt(int idx, int depth) const; }; class IDeltaCodeHints { public: virtual ~IDeltaCodeHints() = default; virtual std::optional<size_t> getSequenceMatch(const SequenceType& seq, const ConfigNode& newValue, size_t curIdx, const BreadCrumb& breadCrumb) const = 0; virtual bool doesSequenceOrderMatter(const BreadCrumb& breadCrumb) const { return true; } virtual bool canDeleteKey(const String& key, const BreadCrumb& breadCrumb) const { return true; } virtual bool canDeleteAnyKey() const { return true; } virtual bool shouldBypass(const BreadCrumb& breadCrumb) const { return false; } virtual bool areNullAndEmptyEquivalent(const BreadCrumb& breadCrumb) const { return false; } }; static ConfigNode createDelta(const ConfigNode& from, const ConfigNode& to, const IDeltaCodeHints* hints = nullptr); static ConfigNode applyDelta(const ConfigNode& from, const ConfigNode& delta); void applyDelta(const ConfigNode& delta); void decayDeltaArtifacts(); private: template <typename T> class Tag {}; union { String* strData; MapType* mapData; SequenceType* sequenceData; Bytes* bytesData; void* rawPtrData; int intData; float floatData; Vector2i vec2iData; Vector2f vec2fData; }; ConfigNodeType type = ConfigNodeType::Undefined; int auxData = 0; // Used by delta coding #if defined(STORE_CONFIG_NODE_PARENTING) struct ParentingInfo { int line = 0; int column = 0; int idx = 0; const ConfigNode* node = nullptr; const ConfigFile* file = nullptr; }; std::unique_ptr<ParentingInfo> parent; #endif static ConfigNode undefinedConfigNode; static String undefinedConfigNodeName; template <typename T> void deserializeContents(Deserializer& s) { T v; s >> v; *this = std::move(v); } String getNodeDebugId() const; String backTrackFullNodeName() const; int convertTo(Tag<int> tag) const; float convertTo(Tag<float> tag) const; bool convertTo(Tag<bool> tag) const; Vector2i convertTo(Tag<Vector2i> tag) const; Vector2f convertTo(Tag<Vector2f> tag) const; Vector3i convertTo(Tag<Vector3i> tag) const; Vector3f convertTo(Tag<Vector3f> tag) const; Vector4i convertTo(Tag<Vector4i> tag) const; Vector4f convertTo(Tag<Vector4f> tag) const; Range<float> convertTo(Tag<Range<float>> tag) const; String convertTo(Tag<String> tag) const; const Bytes& convertTo(Tag<Bytes&> tag) const; bool isNullOrEmpty() const; static ConfigNode doCreateDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints); static ConfigNode createMapDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints); static ConfigNode createSequenceDelta(const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints); void applyMapDelta(const ConfigNode& delta); void applySequenceDelta(const ConfigNode& delta); bool isEquivalent(const ConfigNode& other) const; bool isEquivalentStrictOrder(const ConfigNode& other) const; }; }
{ "alphanum_fraction": 0.6981875493, "avg_line_length": 27.9926470588, "ext": "h", "hexsha": "a5404eed9d2202f30bf77cd81d40312816c7fc62", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "moonantonio/halley", "max_forks_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "moonantonio/halley", "max_issues_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_line_length": 158, "max_stars_count": null, "max_stars_repo_head_hexsha": "c4dfc476ab58539ebb503a5fcdb929413674254d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "moonantonio/halley", "max_stars_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3106, "size": 11421 }
/* * Copyright (c) 2015, Aleksas Mazeliauskas and Derek Teaney * All rights reserved. * * rnavier is distributed under MIT license; * see the LICENSE file that should be present in the root * of the source distribution, or alternately available at: * https://github.com/rnavier/rnavier/ */ #ifndef RN_TEOSLats95p_h #define RN_TEOSLats95p_h #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include "TEOS.h" #include "numeric.h" // Lattice EoS s95p_v0 by Huovinen and Petreczky. Data files are stored in /s95p, correspondingly // in *par*.dat (T, \mu_1, \mu_2) and *dens*.dat (e, P, s, n_B, plasma ratio), with natural units, // e.g., T-GeV, \mu-GeV, e-GeV/fm^3. Each file is // particularly available in its range. // file1: T~[0.0159,0.1801], e~[0.001,1.001] // file2: T~[0.1801,0.2810], e~[1.001,11.00] // file3: T~[0.2810,0.4243], e~[11.00,61.00] // file4: T~[0.2423,0.6335], e~[61.00,311.0] // There are also files avaiable for T<180MeV, with 28 non-zero chemical potential for baryon, // strangeness, etc. For the time being, and for simplicity we ignore these files. So basically // we have \mu = 0 and n_B = 0. class TEOSs95p : public virtual TEOS { private: //minimum table values double fEmin; double fSmin; double fTmin; double fPmin; gsl_interp_accel *acc_eVSp; gsl_spline *eVSp; gsl_interp_accel *acc_tVSx; gsl_spline *tVSx; gsl_interp_accel *acc_eVSt; gsl_spline *eVSt; gsl_interp_accel *acc_eVSs; gsl_spline *eVSs; gsl_interp_accel *acc_sVSe; gsl_spline *sVSe; void eos(const double &e, double &p, double &cs) ; void st(const double &e, double &s, double &t) ; double fEtaOverS ; //!< The Shear viscosity/entropy double fEtaOverSHad ; //!< The Shear viscosity/entropy double fSigmaOverS ; //!< The Shear viscosity/entropy double fKappaTOverS ; //!< The Conductivity/entropy double fTPi_EtaST ; //!< tau_pi / (eta/sT) double fL1_EtaTPi ; //!< lambda_1 /(eta*tau_pi) double fL2_EtaTPi ; //!< lambda_2 /(eta*tau_pi) public: TEOSs95p (); ~TEOSs95p (); virtual void read(std::istream &in) ; virtual void write(std::ostream &out) ; virtual void eos(const double &e, const double &n, double &p, double &cs) ; virtual double eofs(const double &s, const double &n) ; virtual void stmu(const double &e, const double &n, double &s, double &t, double &mu) ; virtual void viscosity(const double &e, const double &n, double &sigma_overs, double &kappaT_overs, double &eta_overs) ; virtual void getBRSSSParams(const double &e, const double &n, double &tpi_etast, double &l1_ntpi, double &l2_ntpi) { tpi_etast = fTPi_EtaST ; l1_ntpi = fL1_EtaTPi ; l2_ntpi = fL2_EtaTPi ; } void tmux(const double &e, const double &n, double &t, double &mub, double &mus, double &x) ; } ; std::unique_ptr<TEOS> make_eos_eoss95p(TRNavier3DBj *rn, const std::string &icname) ; #endif
{ "alphanum_fraction": 0.6460746461, "avg_line_length": 31.3939393939, "ext": "h", "hexsha": "83e48a33971897b4721d58643f27a0aceea30642", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rnavier/rnavier", "max_forks_repo_path": "src/eoss95p/TEOSs95p.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rnavier/rnavier", "max_issues_repo_path": "src/eoss95p/TEOSs95p.h", "max_line_length": 121, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rnavier/rnavier", "max_stars_repo_path": "src/eoss95p/TEOSs95p.h", "max_stars_repo_stars_event_max_datetime": "2021-05-05T15:03:33.000Z", "max_stars_repo_stars_event_min_datetime": "2015-08-04T14:02:15.000Z", "num_tokens": 1019, "size": 3108 }
/* * * Copyright (c) Kresimir Fresl 2002 * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Author acknowledges the support of the Faculty of Civil Engineering, * University of Zagreb, Croatia. * */ #ifndef BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H #define BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_H #ifdef HAS_OpenBLAS #define OPENBLAS_CONST_FLOAT_CAST(x) reinterpret_cast<const float*>(x) #define OPENBLAS_CONST_DOUBLE_CAST(x) reinterpret_cast<const double*>(x) #define OPENBLAS_FLOAT_CAST(x) reinterpret_cast<float*>(x) #define OPENBLAS_DOUBLE_CAST(x) reinterpret_cast<double*>(x) #define OPENBLAS_OPENBLAS_COMPLEX_FLOAT_CAST(x) reinterpret_cast<openblas_complex_float*>(x) #define OPENBLAS_OPENBLAS_COMPLEX_DOUBLE_CAST(x) reinterpret_cast<openblas_complex_double*>(x) #else #define OPENBLAS_CONST_FLOAT_CAST(x) x #define OPENBLAS_CONST_DOUBLE_CAST(x) x #define OPENBLAS_FLOAT_CAST(x) x #define OPENBLAS_DOUBLE_CAST(x) x #define OPENBLAS_OPENBLAS_COMPLEX_FLOAT_CAST(x) x #define OPENBLAS_OPENBLAS_COMPLEX_DOUBLE_CAST(x) x #endif // // MKL-specific CBLAS include // #if defined BOOST_NUMERIC_BINDINGS_BLAS_MKL extern "C" { #include <mkl_cblas.h> //#include <mkl_service.h> // // mkl_types.h defines P4 macro which breaks MPL, undefine it here. // #undef P4 } // // Default CBLAS include // #else extern "C" { #include <cblas.h> } #endif #endif
{ "alphanum_fraction": 0.7858108108, "avg_line_length": 24.262295082, "ext": "h", "hexsha": "f0538233207fbadbdfa168e0651699e909b1b533", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-07T19:35:16.000Z", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/blas/detail/cblas.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 389, "size": 1480 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #else #include "FakeGSL.h" #endif #include <fstream> #include <iostream> #include <vector> #include <map> #include <math.h> #include "FloatSupport.h" #include "BooleanDAG.h" #include "Interface.h" #include "ConflictGenerator.h" #include "ActualEvaluators.h" #include "CommandLineArgs.h" #include "SmoothEvaluators.h" #include "NumDebugger.h" using namespace std; class NumericalSolver { protected: BooleanDAG* dag; Interface* interf; int ncontrols; map<string, int>& ctrls; SmoothEvaluators* smoothEval; ActualEvaluators* actualEval; OptimizationWrapper* opt; SimpleEvaluator* seval; set<int> assertConstraints; int minimizeNode; const vector<vector<int>>& dependentInputs; const vector<vector<int>>& dependentCtrls; gsl_vector* result; LocalState* localState; NumDebugger* debugger; public: NumericalSolver(BooleanDAG* _dag, map<string, int>& _ctrls, Interface* _interface, SmoothEvaluators* _smoothEval, ActualEvaluators* _actualEval, OptimizationWrapper* _opt, const vector<vector<int>>& _dependentInputs, const vector<vector<int>>& _dependentCtrls, NumDebugger* _debugger); ~NumericalSolver(void); // Called by the NumericalSolver bool checkSAT(int level, gsl_vector* initState = NULL); bool checkFullSAT(gsl_vector* state); gsl_vector* getResult(); LocalState* getLocalState(); };
{ "alphanum_fraction": 0.7232447171, "avg_line_length": 22.5692307692, "ext": "h", "hexsha": "0864ecdf7fc87eea1e8a9e91f19a449cf5fbf0e3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Solvers/NumericalSolver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Solvers/NumericalSolver.h", "max_line_length": 289, "max_stars_count": null, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Solvers/NumericalSolver.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 359, "size": 1467 }
// MIT License // Copyright (c) [2017] [Vinay Yuvashankar] // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /** \file "Wavelet.cc" \brief This file contains all of the functions that support the ERSP and CWT functions */ #include "wavelet.h" #include <omp.h> #include <assert.h> #include <gsl/gsl_statistics.h> #define TEST 0.00001 #define SETTLING_PERCENTAGE 0.02 #define NORMALIZATION_FACTOR 0.375402913609157562 int Wavelet(double* raw_data, double* scales, double sampling_frequency, int n, int J, double* result) { //Variable Declarations int i, j; fftw_complex *data_in, *fft_data; fftw_plan plan_forward; //Calculate Padding Required // const int PADDED_SIZE = CalculatePaddingSize(n, 1); const int PADDED_SIZE = n; const double dw = (2 * M_PI * sampling_frequency)/(PADDED_SIZE); //NOT IN RAD/SAMPLE in RAD/SEC data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE ); fft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE ); //populate the FFTW data vector for (i = 0; i < n; ++i) { data_in[i][0] = raw_data[i]; // data_in[i + n][0] = raw_data[i]; // data_in[i + n][1] = 0.0; data_in[i ][1] = 0.0; } // //Force the rest of the data vector to zero just in case // for (int i = n; i < PADDED_SIZE; ++i) // { // data_in[i][0] = 0.0; // data_in[i][1] = 0.0; // } double *temp = (double*) malloc(n * sizeof(double)); FILE* debug_file = fopen("debug.log", "w"); //Calculate the FFT of the data and store it in fft_data plan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan_forward); // #pragma omp parallel num_threads(1) private(i, j) shared (result, sampling_frequency, J, n, scales, fft_data) default(none) // { double value; fftw_plan plan_backward; fftw_complex *filter_convolution, *fftw_result; filter_convolution = (fftw_complex *) fftw_malloc( sizeof( fftw_complex )* PADDED_SIZE ); fftw_result = (fftw_complex *) fftw_malloc( sizeof( fftw_complex )* PADDED_SIZE ); // #pragma omp critical (make_plan) // { //Preapre for the plan backwards plan_backward = fftw_plan_dft_1d(PADDED_SIZE, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_ESTIMATE); // } // #pragma omp for for (i = 0; i < J; ++i) { //Force the arrays to zero memset(filter_convolution, 0.0, sizeof( fftw_complex ) * PADDED_SIZE); memset(fftw_result, 0.0, sizeof( fftw_complex ) * PADDED_SIZE); //Compute the Fourier Morlet at 0 and N/2 double norm = sqrt(scales[i]); value = CompleteFourierMorlet(0.0, scales[i], norm); filter_convolution[0][0] = ( fft_data[0][0] / PADDED_SIZE ) * value; filter_convolution[0][1] = ( fft_data[0][1] / PADDED_SIZE ) * value; filter_convolution[PADDED_SIZE/2][0] = 0.0; filter_convolution[PADDED_SIZE/2][1] = 0.0; //Compute the Fourier Morlet Convolution in between for (j = 1; j < PADDED_SIZE/2 - 1; ++j) { value = CompleteFourierMorlet( j * dw , scales[i], norm); filter_convolution[j][0] = ( fft_data[j][0] / PADDED_SIZE ) * value; filter_convolution[j][1] = ( fft_data[j][1] / PADDED_SIZE ) * value; filter_convolution[PADDED_SIZE- j][0] = 0.0; filter_convolution[PADDED_SIZE- j][1] = 0.0; } //Take the inverse FFT. fftw_execute(plan_backward); //Calculate the power and store it in result for (j = 0; j < n; ++j) { result[i * n + j] = MAGNITUDE(fftw_result[j][0], fftw_result[j][1]) / ( NORMALIZATION_FACTOR * sqrt(scales[i]) ); temp[j] = result[i * n + j]; } double total = 0; for (int j = 0; j < n; ++j) { total += temp[j]; } double variance = gsl_stats_variance(temp, 1, n); fprintf(debug_file, "%.16f\t%.16f\t%.16f\n", SCALE_TO_FREQ(scales[i]), variance, total); } free(temp); fclose(debug_file); //FFTW sanitation engineering. fftw_destroy_plan(plan_backward); fftw_free(fftw_result); fftw_free(filter_convolution); // } //Sanitation Engineering fftw_destroy_plan(plan_forward); fftw_free(fft_data); fftw_free(data_in); return(0); } /*Wavelet */ double* ShortTimeFourierTransform(double * raw_data, double sampling_frequency, int n, int window_size) { //Variable Declarations int i, j; fftw_complex *data_in, *fft_data; fftw_plan plan_forward; double* result; // FILE * STFT_FILE = fopen("STFT_Result.log", "w"); int num_windows = ceil((double) n / window_size); assert(num_windows > 0); // const int PADDED_SIZE = CalculatePaddingSize(window_size, 1); const int PADDED_SIZE = window_size; result = (double*) malloc(num_windows * PADDED_SIZE * sizeof(double)); data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE ); fft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE ); //Calculate the FFT of the data and store it in fft_data plan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_ESTIMATE); for (i = 0; i < num_windows; ++i) { memset(data_in, 0.0, sizeof( fftw_complex ) * PADDED_SIZE); memset(fft_data, 0.0, sizeof( fftw_complex ) * PADDED_SIZE); //Fill Data into FFT Array for (j = 0; j < window_size; ++j) { if (i * window_size + j < n) { data_in[j][0] = raw_data[i * window_size + j]; data_in[j][1] = 0.0; } else { data_in[j][0] = 0.0; data_in[j][1] = 0.0; } } fftw_execute(plan_forward); for (j = 0; j < window_size / 2; ++j) { result[j * num_windows + i] = MAGNITUDE(fft_data[j][0], fft_data[j][1]); // fprintf(STFT_FILE, "%d\t%f\t%d\n", j, result[j * num_windows + i], j * num_windows + i); } } // fclose(STFT_FILE); fftw_destroy_plan(plan_forward); fftw_free(data_in); fftw_free(fft_data); return(result); } int Find_Peaks(double* array, double* frequency, int n, int J) { FILE* maximum_file = fopen("maximum.log", "w"); ARRAY_DATA *maximum_array = (ARRAY_DATA*) malloc (J * sizeof(ARRAY_DATA)); int local_maximum_location[J]; double* temp = (double*) malloc(n * sizeof(double)); //Find the local maximum at every frequency for (int i = 0; i < J; ++i) { ARRAY_DATA max; max.value = array[i * n]; max.index = i * n; for (int j = 0; j < n; ++j) { if (array[i * n + j] > max.value) { max.value = array[i * n + j]; max.index = i * n + j; } } maximum_array[i] = max; fprintf(maximum_file, "%f\t%f\n", frequency[i], maximum_array[i].value); } //Calculate the deravitive of the signal and isolate the peaks double sign = (maximum_array[1].value - maximum_array[0].value) / (frequency[1] - frequency[0]); int max_count = 0; for (int i = 0; i < J - 1; ++i) { double slope = (maximum_array[i + 1].value - maximum_array[i].value) / (frequency[i + 1] - frequency[i]); if (signbit(slope) != signbit(sign) && sign < 0) { local_maximum_location[max_count] = i; max_count++; } sign = slope; } for (int i = 0; i < max_count; ++i) { int arr_index = local_maximum_location[i]; //Copy data into memory block for (int j = 0; j < n; ++j) { temp[j] = array[arr_index * n + j]; // if (i == 1) // fprintf(maximum_file, "%f\t%.16f\n", (double) j/FS, array[arr_index * n + j]); } ARRAY_DATA impact_site = Max(temp, n); int system_setteled = 0; int setteled_index = 0; for (int j = impact_site.index; j < n; ++j) { if (temp[j] < SETTLING_PERCENTAGE * impact_site.value && system_setteled == 0) { setteled_index = j; double setteled_time = (double) (setteled_index - impact_site.index)/FS; printf("Frequency[%d]: %f, Settled Time = %f\n", i, frequency[arr_index], setteled_time); system_setteled = 1; } } } fclose(maximum_file); free(maximum_array); free(temp); return(0); } int CalculatePaddingSize(const int array_size, const int pad_flag) { const int pad = ceil(log2(array_size)); int out = array_size; switch(pad_flag) { case 0: //No Padding what so ever. out = array_size; break; case 1: //Zero - Padding and preforming a Radix-2 Operation out = (int) pow(2, pad + 1); break; case 2: //Duplicate array and ramp up and ramp down output out = 2 * array_size; break; case 3: //Repeat the array once. out = 2 * array_size; break; default: //Else return the array size out = array_size; break; } return(out); } void GenerateScalesAndFrequency(const int min_i, const int max_i, const double s_0, double* scales, double* frequency) { int count = ( max_i - min_i ) + 1; //Populate the scales array for (int i = 0; i < count; ++i) { int counterVariable = min_i + i; scales[i] = s_0 * pow(2, counterVariable * D_J); } IdentifyFrequencies(scales, count, frequency); } void IdentifyFrequencies(double* scales, int count, double* frequency) { // double * frequency = (double*) malloc( count * sizeof(double) ); for (int i = 0; i < count; ++i) { frequency[i] = (W_0)/(scales[i] * 2 * M_PI); } } double CompleteFourierMorlet(double w, const double scale, double norm) { // double norm = 1.0/sqrt(scale); // double norm = sqrt(scale); w = w * scale; double out = exp( -0.5 * ( W_0 - w ) * (W_0 - w) ) - K_SIGMA * (exp ( -0.5 * w * w)); out = norm * C_SIGMA * QUAD_ROOT_PI * out; return(out); } void TestCases(double *data, const int flag, double freq, double sampling_frequency, int data_size) { // Fit a freq signal at two points // double DT = 1./sampling_frequency; double fsig = freq/sampling_frequency; double dw = 2 * M_PI * fsig; double w0 = 0.001; // A SMALL PHASE SHIFT SO ITS NOT ALL INTERGER ALIGNED int one_peri = (int)1./fsig; double frequency_increment = (MAX_FREQUENCY - MIN_FREQUENCY)/ 3.0; //3.0 seconds. int t = 2 * sampling_frequency; //At 2 seconds. switch(flag) { //Impulse at T = 2 seconds case 1: for (int i = 0; i < data_size; ++i) { data[i] = 0.0; } data[t] = 1.0; break; //Multiple Sines at t = 1500 case 2: for (int i = data_size/2; i < data_size/2 + 2*one_peri; ++i) { data[i] = sin((i - data_size/2)* dw + w0) + sin((i - data_size/2)* 2* dw + w0); } break; //Multiple Sines at all times case 3: for (int i = 0; i < data_size; ++i) { data[i] = sin(i*dw + w0) + sin(i*2*dw + w0); } break; //Single sine at t = 1.0s; case 4: for (int i = data_size/3; i < data_size/3 + 2 * one_peri; ++i) { data[i] = sin( (i - data_size/2) * dw + w0 ); } break; case 5: for (int i = 0; i < data_size; ++i) { data[i] = cos( i * dw + w0 ); if (i >= data_size/2 && i <= 2 * (data_size)/3) { data[i] = 2 * cos(i * dw + w0); } } break; case 6: for (int i = 0; i < data_size; ++i) { data[i] = cos(i * dw + w0 ); if (i >= data_size/3 && i <= data_size/2) { data[i] = cos(i * (dw - 0.005) + w0); } } break; //Frequency Sweep case 7: for (int i = 0; i < data_size; ++i) { // fsig = frequency/sampling_frequency; // dw = 2*M_PI*fsig; data[i] = sin(w0 + 2 * M_PI * (MIN_FREQUENCY + (frequency_increment/2) * pow(i/sampling_frequency, 2)) ); // frequency += frequency_increment; } break; //Single sine all the way through. case 8: for (int i = 0; i < data_size; ++i) { data[i] = cos(i*dw + w0); } break; } } int WriteDebug(const double *data, const int length, const int sampling_frequency, const char* filename) { FILE* out_file=fopen(filename,"w"); if (out_file == NULL) return -1; double t = 0.0; double dt = 1.0/sampling_frequency; for (int i = 0; i < length; ++i) { // double value = (double) i/length; fprintf(out_file, "%f\t%.16e\n", t, data[i]); t += dt; } fclose(out_file); return 0; } void FillData(double * data) { // Fit a FREQ signal at two points // double DT = 1./FS; double fsig = FREQ/FS; double dw = 2*M_PI*fsig; double w0 = 0.01; // A SMALL PHASE SHIFT SO ITS NOT ALL INTERGER ALIGNED int one_peri = (int)1./fsig; // printf("FS %.2d Pitch %.f Discrete Period = %d \n",FS,FREQ,one_peri); for (int i = 0; i < DATA_SIZE; ++i) { data[i] = 0.0; } // //Impulse Sample // data[2000] = 1.0; int i; // double t=0; for(i=0;i<DATA_SIZE;i++){ // data[i] = sin(i*dw) + sin(i*dw*4); data[i]=0.; // if((i>200)&(i<400))data[i]=sin( (i-200)*dw+w0); if((i>0.25*DATA_SIZE)&(i<0.25*DATA_SIZE+one_peri)) data[i]=sin( (i-200)*dw+w0); if((i>0.5*DATA_SIZE)&(i<0.5*DATA_SIZE+2*one_peri))data[i]=sin( (i-1000)*dw+w0); if((i>0.75*DATA_SIZE)&(i<0.75*DATA_SIZE+3*one_peri))data[i]=sin( (i-2000)*dw+w0); } } int GetFileSize(char filename[]) { FILE* signalFile = fopen(filename, "r"); assert(signalFile != NULL); // obtain file size: fseek (signalFile , 0 , SEEK_END); long lSize = ftell (signalFile); rewind (signalFile); char * buffer = (char*) malloc(sizeof(char)*lSize); assert(buffer != NULL); int result = fread (buffer, 1, lSize, signalFile); assert(result == lSize); char * token = strtok(buffer, "\n"); //Get input from text. int counterVariable = 0; while (token !=NULL) { // data[counterVariable] = atof(token); counterVariable++; token = strtok (NULL, "\n"); } fclose(signalFile); return (counterVariable); } int ReadFile(double data[], char filename[]) { FILE* signalFile = fopen(filename, "r"); assert(signalFile != NULL); // obtain file size: fseek (signalFile , 0 , SEEK_END); long lSize = ftell (signalFile); rewind (signalFile); char * buffer = (char*) malloc(sizeof(char)*lSize); assert(buffer != NULL); int result = fread (buffer, 1, lSize, signalFile); assert(result == lSize); // puts(buffer); char * token = strtok(buffer, "\n"); //Get input from text. int counterVariable = 0; while (token !=NULL) { data[counterVariable] = atof(token); counterVariable++; token = strtok (NULL, "\n"); } fclose(signalFile); return (counterVariable); } double CWT_Cosine_Real(double time, double scale) { double norm = sqrt(scale); double w_o = FREQ * 2 * M_PI; w_o *= scale; double mor = exp( - 0.5 * (W_0 - w_o) * (W_0 - w_o) ) + K_SIGMA * exp( -0.5 * w_o * w_o ); double cosine = cos(w_o * time); double out = 0.5 * C_SIGMA * QUAD_ROOT_PI * norm * mor * cosine; return(out); } double CWT_Cosine_Complex(double time, double scale) { double norm = sqrt(scale); double w_o = FREQ * 2 * M_PI; w_o *= scale; double mor = exp( - 0.5 * (W_0 - w_o) * (W_0 - w_o) ) + K_SIGMA * exp( -0.5 * w_o * w_o ); double sine = sin(w_o * time); double out = 0.5 * C_SIGMA * QUAD_ROOT_PI * norm * mor * sine; return(out); } double CWT_Dirac_Real(double time, double scale) { double impulse = 2.0; time = (impulse - time )/scale; double norm = 1.0/sqrt(scale); double out = exp( - 0.5 * time * time ) * ( cos( W_0 * time ) - K_SIGMA ); out = norm * C_SIGMA * QUAD_ROOT_PI * out; return(out); } double CWT_Dirac_Complex(double time, double scale) { double impulse = 2.0; time = (impulse - time )/scale; double norm = 1.0/sqrt(scale); double out = exp( - 0.5 * time * time ) * ( sin( W_0 * time ) - K_SIGMA ); out = norm * C_SIGMA * QUAD_ROOT_PI * out; return(out); } ARRAY_DATA Max(double * array, int size) { double max = array[0]; int array_index = 0; ARRAY_DATA out; for (int i = 0; i < size; ++i) { if (array[i] > max) { max = array[i]; // if (max != max) // { // printf("Naan Alert!\n"); // } array_index = i; } } out.value = max; out.index = array_index; // printf("Max: Array[%d] = %.17f\n", array_index, array[array_index]); return(out); } /** \fn int OpenFile(const char* fileName, struct edf_hdr_struct *header) \brief Openes a .BDF file and allocates it to an edf_hdr_struct. \param fileName The name and location of the file to be opened \param header The pointer to the edf header structure \return 0 if file is opened successfully \return -1 if there is an error */ int OpenFile(const char* fileName, struct edf_hdr_struct *header) { if(edfopen_file_readonly(fileName, header, EDFLIB_READ_ALL_ANNOTATIONS)) { switch(header->filetype) { case EDFLIB_MALLOC_ERROR : printf("\nmalloc error\n\n"); break; case EDFLIB_NO_SUCH_FILE_OR_DIRECTORY : printf("\ncan not open file, no such file or directory\n\n"); break; case EDFLIB_FILE_CONTAINS_FORMAT_ERRORS : printf("\nthe file is not EDF(+) or BDF(+) compliant\n" "(it contains format errors)\n\n"); break; case EDFLIB_MAXFILES_REACHED : printf("\nto many files opened\n\n"); break; case EDFLIB_FILE_READ_ERROR : printf("\na read error occurred\n\n"); break; case EDFLIB_FILE_ALREADY_OPENED : printf("\nfile has already been opened\n\n"); break; default : printf("\nunknown error\n\n"); break; } return(-1); } return(0); } /** \fn int64_t FindTriggers(const int * statusInput, const int64_t numberOfRecords, int64_t * outputBuffer) \brief This function should take an array input and return the rising and falling edges of the triggers. \param statusInput: The Status Channel Input from the BDF or EDF flie. use the edfread_digital_samples \param numberOfRecords: The size of statusInput \param outputBuffer: a 1 x 2 * MAXIMUM_TRIGGERS int64_t array with the odd entries being the rising edge and the even entries being the falling edges. \return counterVariable The number of triggers that were found. */ int FindTriggers(const int * statusInput, const int64_t numberOfRecords, int64_t * outputBuffer) { int64_t counterVariable = 0; int counterVariable_int = 0; //int i needs to be int64_t because we are recording it into a int64_t arrray. int edge = 0; for (int64_t i = 0; i < numberOfRecords; ++i) { //Bit and the lower 16 bits to see if any of the triggers have been triggered to on. if ( ((statusInput[i] & 0x0000FFFF) > 0) && (edge == 0) && (statusInput[i-1] != statusInput[i]) ) //Rising Edge Detected. { outputBuffer[counterVariable] = i; // printf("outputBuffer[%" PRId64 "] = %" PRId64"\n", counterVariable, outputBuffer[counterVariable]); counterVariable++; counterVariable_int++; edge = 1; } if (statusInput[i-1] != statusInput[i] && edge == 1) //Falling Edge Detected. { edge = 0; } if (counterVariable > MAXIMUM_TRIGGERS) return -1; } return(counterVariable_int); } /** \fn int FilterTriggers(const int code, const int button, const int numberOfRecords, const int64_t * triggerList, const int * readBuffer, int * outputBuffer) \brief Filteres the triggers coming in, and finds the specified events \param code The code of the trigger list that is needed Possible Inputs: 1, or 2 \param button The code of the button that is needed Possible Inputs 1, or 2 \param triggerList The list of all of the possible triggers \param readBuffer The Status Channel input from the file \param outputBuffer The buffer that FilterTriggers will populate with the location of the location of the triggers that we're looking for \return counterVariable The number of triggers found. */ int FilterTriggers(const int code, const int button, const int numberOfRecords, const int64_t * triggerList, const int * readBuffer, int * outputBuffer) { int readCode; int buttonCode; int counterVariable = 0; for (int i = 0; i < numberOfRecords; ++i) { readCode = readBuffer[i] & 255; buttonCode = (readBuffer[i] >> 8) & 3; if ( (readCode == code) && (buttonCode == button) ) { outputBuffer[counterVariable] = triggerList[i]; counterVariable++; } } return counterVariable; } void CleanData(double * data, double n) { double mean = gsl_stats_mean(data, 1, n); double sDeviation = gsl_stats_sd_m(data, 1, n, mean); // printf("Mean: %f, SD: %f\n", mean, sDeviation); //Compute the Z-Score or Standard Score for (int i = 0; i < n; ++i) { data[i] = (data[i] - mean)/sDeviation; } } int WriteFile(const double *data, const double *frequency, const int x, const int y, int sampling_frequency, const char filename[]) { FILE* out_file=fopen(filename,"w"); if (out_file == NULL) return -1; //Xticks fprintf(out_file, "%d\t", x); for (int i = 0; i < y; ++i) { fprintf(out_file, "%f\t", (double) i/sampling_frequency); } fprintf(out_file, "\n"); // double small_eps = 0.00001; //Add a small eps so that logs of zero don't happen. for (int i = 0; i < x; ++i) { //Feed Frequency fprintf(out_file, "%f\t", frequency[i]); //Feed Data for (int j = 0; j < y; ++j) { // value = Magnitude(result[i*n + j], result[i*n + j]); fprintf(out_file, "%.16e\t", data[i*y + j]); } //Ready for the next line. fprintf(out_file, "\n"); } fclose(out_file); return(0); } int WriteGnuplotScript(const char graph_title[], const char filename[]) { FILE* gnuplot_file = fopen("script.gplot", "w"); if (gnuplot_file == NULL) return -1; // fprintf(gnuplot_file, "set term x11\n"); // fprintf(gnuplot_file, "set logscale z 10\n"); fprintf(gnuplot_file, "set term pngcairo enhanced font 'arial,12'\n"); fprintf(gnuplot_file, "%s%s%s","set output '", graph_title, ".png' \n"); fprintf(gnuplot_file, "set pm3d map\n"); fprintf(gnuplot_file, "set logscale y 2\n"); fprintf(gnuplot_file, "set ticslevel 0\n"); fprintf(gnuplot_file, "set xlabel \"time (s)\"\n"); fprintf(gnuplot_file, "set ylabel \"Frequency (Hz)\"\n"); //Input Graph Title fprintf(gnuplot_file, "%s%s%s\n", "set title \"", graph_title, "\""); //Plot filename // plot "DATA.log" matrix nonuniform with pm3d t '' fprintf(gnuplot_file, "%s%s%s\n", "splot \"", filename, "\" matrix nonuniform with pm3d t ''"); // fprintf(gnuplot_file, "pause -1 \"Hit Return to continue\""); return(0); }
{ "alphanum_fraction": 0.6082074147, "avg_line_length": 28.0997679814, "ext": "c", "hexsha": "3a15538b5fbee523ab89dab74697303ab28bb470", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "yuvashankar/Research", "max_forks_repo_path": "src/wavelet.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "yuvashankar/Research", "max_issues_repo_path": "src/wavelet.c", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "yuvashankar/Research", "max_stars_repo_path": "src/wavelet.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7264, "size": 24222 }
#include <errno.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <clapack.h> #include <cblas.h> #include <omp.h> #define DIM 16 #define NB 256 //#define DIM 96 //#define NB 128 extern void spotrf_(char *, int *, float *, int *, int *); /*#pragma css task input(NB) inout(A[NB][NB]) highpriority */ void smpSs_spotrf_tile(float *A) { unsigned char LO='L'; int INFO; int nn=NB; spotrf_(&LO, &nn, A,&nn, &INFO); } /*#pragma css task input(A[NB][NB], B[NB][NB], NB) inout(C[NB][NB])*/ void smpSs_sgemm_tile(float *A, float *B, float *C) { unsigned char TR='T', NT='N'; float DONE=1.0, DMONE=-1.0; cblas_sgemm( CblasColMajor, CblasNoTrans, CblasTrans, NB, NB, NB, -1.0, A, NB, B, NB, 1.0, C, NB); } /*#pragma css task input(T[NB][NB], NB) inout(B[NB][NB])*/ void smpSs_strsm_tile(float *T, float *B) { unsigned char LO='L', TR='T', NU='N', RI='R'; float DONE=1.0; cblas_strsm( CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, NB, NB, 1.0, T, NB, B, NB); } /*#pragma css task input(A[NB][NB], NB) inout(C[NB][NB])*/ void smpSs_ssyrk_tile( float *A, float *C) { unsigned char LO='L', NT='N'; float DONE=1.0, DMONE=-1.0; cblas_ssyrk( CblasColMajor, CblasLower,CblasNoTrans, NB, NB, -1.0, A, NB, 1.0, C, NB); } void compute(struct timeval *start, struct timeval *stop, float *A[DIM][DIM]) { #pragma omp parallel num_threads(48) #pragma omp single { gettimeofday(start,NULL); double t1 = omp_get_wtime(); long j,k,i; for (j = 0; j < DIM; j++) { for (k= 0; k< j; k++) { for (i = j+1; i < DIM; i++) { #pragma omp task shared(A) firstprivate(i,k,j) depend(in : A[i][k], A[j][k]) depend(inout:A[i][j]) smpSs_sgemm_tile( A[i][k], A[j][k], A[i][j]); } } for (i = 0; i < j; i++) { #pragma omp task shared(A) firstprivate(i,j) depend (in : A[j][i]) depend(inout : A[j][j]) smpSs_ssyrk_tile( A[j][i], A[j][j]); } #pragma omp task shared(A) firstprivate(j) depend(inout : A[j][j]) smpSs_spotrf_tile( A[j][j]); for (i = j+1; i < DIM; i++) { #pragma omp task shared(A) firstprivate(i,j) depend(in : A[j][j]) depend (inout : A[i][j]) smpSs_strsm_tile( A[j][j], A[i][j]); } } #pragma omp taskwait double t2 = omp_get_wtime(); fprintf(stderr,"Time: %f\n",t2-t1); } gettimeofday(stop,NULL); exit(0); } static void init(int argc, char **argv, long *N_p); float **A; float * Alin; long N; int main(int argc, char *argv[]) { unsigned char LO='L'; int INFO; struct timeval start; struct timeval stop; unsigned long elapsed; init(argc, argv, &N); fprintf(stderr,"Computing cholesky...\n"); compute(&start, &stop, (void *)A); int nn=N; elapsed = 1000000 * (stop.tv_sec - start.tv_sec); elapsed += stop.tv_usec - start.tv_usec; printf ("%lu;\t", elapsed); printf("%d\n", (int)((0.33*N*N*N+0.5*N*N+0.17*N)/elapsed)); printf("par_sec_time_us:%lu\n",elapsed); return 0; } static void convert_to_blocks(long N, float *Alin, float *A[DIM][DIM]) { long i,j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { A[j/NB][i/NB][(i%NB)*NB+j%NB] = Alin[i*N+j]; } } } void fill_random(float *Alin, int NN) { int i; for (i = 0; i < NN; i++) { Alin[i]=((float)rand())/((float)RAND_MAX); } } static void init(int argc, char **argv, long *N_p) { long ISEED[4] = {0,0,0,1}; long IONE=1; long N = NB*DIM; long NN = N * N; *N_p = N; Alin = (float *) malloc(NN * sizeof(float)); fill_random(Alin,NN); long i; for(i=0; i<N; i++) { Alin[i*N + i] += N; } A = (float **) malloc(DIM*DIM*sizeof(float *)); for ( i = 0; i < DIM*DIM; i++) { // #pragma omp memory A[i] = (float *) malloc(NB*NB*sizeof(float)); int z; for (z=0;z<DIM*DIM;z++) { float *zz = (float *) A[i]; zz[z] = Alin[(DIM*DIM)*i + z]; } } convert_to_blocks(N, Alin, (void *)A); }
{ "alphanum_fraction": 0.5486873508, "avg_line_length": 18.5398230088, "ext": "c", "hexsha": "d1a12d0e051f6ec942c511ad321b67a80106ff15", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "podobas/BLYSK", "max_forks_repo_path": "Benchmarks/cholesky/cholesky.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "podobas/BLYSK", "max_issues_repo_path": "Benchmarks/cholesky/cholesky.c", "max_line_length": 106, "max_stars_count": 2, "max_stars_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "podobas/BLYSK", "max_stars_repo_path": "Benchmarks/cholesky/cholesky.c", "max_stars_repo_stars_event_max_datetime": "2018-10-21T18:10:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-18T11:08:45.000Z", "num_tokens": 1477, "size": 4190 }
#ifndef MATH_FNS_H #define MATH_FNS_H #ifdef USE_OPENBLAS extern "C" { #include <cblas.h> } #endif struct QuantizationParams { float scale; uint8_t zero_point; }; template<typename Dtype> void cpu_gemm(bool transA, bool transB, uint64_t M, uint64_t N, uint64_t K, Dtype alpha, Dtype* A, Dtype* B, Dtype beta, Dtype* C); template<typename Dtype> void cpu_axpy(uint64_t N, Dtype alpha, Dtype* X, Dtype* Y, Dtype* C); // c = alpha * x + y template<typename Dtype> void cpu_axpby(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype beta, Dtype* Y_ptr, Dtype* C_ptr); // c = alpha * x + beta * y template<typename Dtype> void cpu_mul(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c = a * b template<typename Dtype> void cpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr, Dtype beta, Dtype* C_ptr); // c = beta * c + alpha * a * b template<typename Dtype> void cpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha * a template<typename Dtype> void cpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a template<typename Dtype> void cpu_div(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c += a / b template<typename Dtype> void cpu_div(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr, Dtype beta, Dtype* C_ptr); // c = (beta * c) + (alpha * a / b) template<typename Dtype> void cpu_div_back(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr, Dtype* D_ptr); // special function for processing div_backward during backpropagation (calculates d += a * (-b) / (c * c)) template<typename Dtype> void cpu_sig(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = sig(a) template<typename Dtype> void cpu_tanh(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = tanh(a) template<typename Dtype> void cpu_powx(uint64_t N, const Dtype* A_ptr, Dtype x, Dtype* B_ptr); // b = pow(a,x) template<typename Dtype> void cpu_copy(uint64_t N, Dtype* A_ptr, Dtype* B_ptr); // b = a template<typename Dtype> void cpu_max(const Dtype* src, Dtype* dst, uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_max_backward(Dtype* dst, const Dtype* src, const uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_sum(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_sum_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_mean(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_mean_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_var(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_var_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void cpu_std(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true); template<typename Dtype> void cpu_std_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const Dtype* std, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true); template<typename Dtype> void cpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len); template<typename Dtype> void cpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels); template<typename Dtype> void cpu_tanh_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels); void cpu_transpose(float* src, float* dst, int dim_1, int dim_2, int stride_src_dim_1, int stride_src_dim_1_minus_1, int stride_src_dim_2, int stride_src_dim_2_minus_1, int stride_trn_dim_1, int stride_trn_dim_1_minus_1, int stride_trn_dim_2, int stride_trn_dim_2_minus_1, uint64_t numels); void quantized_matmul(bool traspose_A, bool traspose_B, uint64_t M, uint64_t N, uint64_t K, uint8_t alpha, uint8_t* A, uint8_t* B, uint8_t beta, uint8_t* C, QuantizationParams* qparms, int* bias, int* workspace); // workspace must be at least (M + N) * sizeof(int) bytes //-------------------------------------CUDA functions---------------------------------------------------------------- template<typename Dtype> void gpu_sum(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B); template<typename Dtype> void gpu_sub(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B); // C = A * B template<typename Dtype> void gpu_mul(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // C = beta * C + A * B // supports broadcast semantics // use this when C dims >= both A and B dims (avoid atomics) template<typename Dtype> void gpu_mul(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, Dtype beta); // C = C + A * B // supports broadcast semantics // use this when C dims < either A or B dims (uses atomics, but no support for uint8_t) void gpu_mul(float* A, float* B, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C); template<typename Dtype> void gpu_mul(uint64_t N, Dtype alpha, Dtype* A, Dtype* B, Dtype beta, Dtype* C); // c = beta * c + alpha * a * b template<typename Dtype> void gpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha * a // C = A / B // supports broadcast semantics // use this when C dims >= both A and B dims (avoid atomics) template<typename Dtype> void gpu_div(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B); // C = C + A / B // use this when C numels == A numels == B numels (no broadcast therefore fastest) template<typename Dtype> void gpu_div(uint64_t N, Dtype* A, Dtype* B, Dtype* C); // C = A / B // use this when C numels == A numels == B numels (no broadcast therefore fastest) //template<typename Dtype> //void gpu_div2(uint64_t N, Dtype* A, Dtype* B, Dtype* C); // C = C + A / B // supports broadcast semantics // use this when C dims < either A or B dims (uses atomics, but no support for uint8_t) void gpu_div(float* A, float* B, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C); // special function for processing div_backward during backpropagation (calculates d += a * (-b) / (c * c)) // supports broadcast semantics // use this when D dims < A or B or C dims (uses atomics, but no support for uint8_t) //template<typename Dtype> void gpu_div_back(float* A, float* B, float* C, float* D, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C, uint64_t height_D, uint64_t width_D); template<typename Dtype> void gpu_sum(Dtype* data, Dtype* sum, uint64_t len); template<typename Dtype> void gpu_nll(Dtype* input, Dtype* target, Dtype* loss, uint64_t len, uint64_t batches); template<typename Dtype> void gpu_scalar_mul(Dtype* A, Dtype* B, Dtype scalar, uint64_t len); // B = scaler * A // C += alpha * A // supports broadcast semantics // use this when C dims < A dims (uses atomics, but no support for uint8_t) void gpu_scalar_mul(float alpha, float* A, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_C, uint64_t width_C); template<typename Dtype> void gpu_fill(Dtype* memory, uint64_t size, Dtype value); template<typename Dtype> void gpu_fill(Dtype* memory, uint64_t len, Dtype* value); void gpu_sgd_step(float* weight_ptr, float* weight_grad_ptr, float* velocity_ptr, int64_t numels, float mo, float wd, float lr); template<typename Dtype> void gpu_max(const Dtype* src, Dtype* dst, uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_max_backward(Dtype* dst, const Dtype* src, const uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_powx(uint64_t N, const Dtype* A, Dtype x, Dtype* B); // b = pow(a,x) template<typename Dtype> void gpu_exp(Dtype* dst, const Dtype* src, const uint64_t numels); template<typename Dtype> void gpu_log(Dtype* dst, const Dtype* src, const uint64_t numels); template<typename Dtype> void gpu_sig(Dtype* dst, const Dtype* src, const uint64_t numels); template<typename Dtype> void gpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels); template<typename Dtype> void gpu_tanh(Dtype* dst, const Dtype* src, const uint64_t numels); template<typename Dtype> void gpu_tanh_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels); template<typename Dtype> void gpu_sum(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_sum_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a template<typename Dtype> void gpu_axpy(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype* Y_ptr, Dtype* C_ptr); template<typename Dtype> void gpu_axpby(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype beta, Dtype* Y_ptr, Dtype* C_ptr); // c = alpha * x + beta * y template<typename Dtype> void gpu_relu(Dtype* dst, Dtype* src, uint64_t len); template<typename Dtype> void gpu_relu_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t len); template<typename Dtype> void gpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len); template<typename Dtype> void gpu_transpose(Dtype* src, Dtype* dst, int dim_1, int dim_2, int stride_src_dim_1, int stride_src_dim_1_minus_1, int stride_src_dim_2, int stride_src_dim_2_minus_1, int stride_trn_dim_1, int stride_trn_dim_1_minus_1, int stride_trn_dim_2, int stride_trn_dim_2_minus_1, uint64_t numels); template<typename Dtype> void gpu_cat(Dtype* dest, Dtype* op1, Dtype* op2, uint64_t dest_stride_1, uint64_t dest_stride_2, uint64_t op1_stride, uint64_t op2_stride_1, uint64_t op2_stride_2, uint64_t dim_offset, uint64_t op1_numels, uint64_t op2_numels); template<typename Dtype> void gpu_cat_backward(Dtype* dest, Dtype* src, uint64_t dest_stride, uint64_t src_stride, uint64_t dest_numels); template<typename Dtype> void gpu_cat_backward(Dtype* dest, Dtype* src, uint64_t dest_stride_1, uint64_t dest_stride_2, uint64_t src_stride_1, uint64_t src_stride_2, uint64_t dim_offset, uint64_t op1_numels, uint64_t dest_numels); template<typename Dtype> void gpu_embedding(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim); template<typename Dtype> void gpu_embedding_backward(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim); template<typename Dtype> void gpu_sqrt(Dtype* dst, const Dtype* src, const uint64_t numels); template<typename Dtype> void gpu_sqrt_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels); template<typename Dtype> void gpu_mean(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_mean_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_var(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_var_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride); template<typename Dtype> void gpu_std(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true); template<typename Dtype> void gpu_std_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const Dtype* std, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true); #endif // MATH_FNS_H
{ "alphanum_fraction": 0.7582543565, "avg_line_length": 45.7482517483, "ext": "h", "hexsha": "36ef3008f89d4c7161ee97929d043a66e0b4535c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "adeobootpin/light-tensor", "max_forks_repo_path": "l-ten/math_fns.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "adeobootpin/light-tensor", "max_issues_repo_path": "l-ten/math_fns.h", "max_line_length": 270, "max_stars_count": null, "max_stars_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "adeobootpin/light-tensor", "max_stars_repo_path": "l-ten/math_fns.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3651, "size": 13084 }
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include "core_allvars.h" #include "core_proto.h" #include "UVmag/UVmag.h" // Local Proto-Types // int32_t init_delayedSN(void); int32_t init_nionlookup(void); int32_t init_metalcooling(void); void read_snap_list(void); void set_units(void); int32_t init_fesc(void); int32_t determine_fescMH_constants(void); // External Functions // void sage_init(void) { int32_t i, status; count_gal = 0; random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(random_generator, 42); // start-up seed set_units(); srand((unsigned) time(NULL)); read_snap_list(); for(i = 0; i < MAXSNAPS; i++) { ZZ[i] = 1 / AA[i] - 1; Age[i] = time_to_present(ZZ[i]); } a0 = 1.0 / (1.0 + Reionization_z0); ar = 1.0 / (1.0 + Reionization_zr); read_cooling_functions(); status = init_fesc(); if (status != EXIT_SUCCESS) { ABORT(0); } count_onehalo = 0; zeromass_count = 0; suppression_count = 0; previous_tree = 0; smallest_mass = 100000; lowmass_halo = 0; outside_box = 0; inside_box = 0; count_Mvir = 0; count_Len = 0; if (IMF == 0) { // Salpeter IMF // IMF_norm =0.1706; IMF_slope = -2.35; Eta_SNII = 7.432e-3; //Number fraction of stars that will end their lives as type II supernovae. m_SNII = 0.144; // Mass fraction of stars that will end their lives as type II supernovae. } else if (IMF == 1) { // Chabrier IMF // IMF_norm = 0.23638; IMF_slope = -2.3; Eta_SNII = 1.1893e-2; //Number fraction of stars that will end their lives as type II supernovae. m_SNII = 0.23638; // Mass fraction of stars that will end their lives as type II supernovae. } // Tiamat Parameters // V_energy = 70.0; alpha_energy = 0.5; beta_energy = 10.0; V_mass = 70.0; alpha_mass = 6.0; beta_mass = 10.0; epsilon_mass_max = 30.0; if (IRA == 0) { status = init_delayedSN(); if (status != EXIT_SUCCESS) { ABORT(EXIT_FAILURE); } } if (PhotonPrescription == 1) { status = init_nionlookup(); if (status != EXIT_SUCCESS) { ABORT(EXIT_FAILURE); } } if (calcUVmag == 1) { status = init_UVlookup(); if (status != EXIT_SUCCESS) { ABORT(EXIT_FAILURE); } } if ((PhotonPrescription == 1) || (calcUVmag == 1)) { StellarTracking_Len = STELLAR_TRACKING_TIME / TimeResolutionStellar; } mergedgal_mallocs = 0; gal_mallocs = 0 ; mergedgal_frees = 0; gal_frees = 0; Ngamma_HI_Total = 0.0; } // Local Functions // int32_t init_delayedSN(void) { // We keep the past 50 Myrs of star formation stored for each galaxy. // Based on the TimeResolution specified need to find out how many elements this corresponds to. if(TimeResolutionSN > 50) { fprintf(stderr, "The selected time resolution for SN feedback (TimeResolutionSN) is set too high (%d Myr). Using TimeResolutionSN > 50Myr is the same as using the instantaneous recycling approximation; set 'IRA' to 1 instead!\n", TimeResolutionSN); ABORT(EXIT_FAILURE); } else if(TimeResolutionSN > 35) { fprintf(stderr, "Your selected time resolution for SN feedback (TimeResolutionSN) is quite high (%d Myr). Beyond 50Myr the instantaneous recycling approximation is valid hence with your value it would likely be correct to set 'IRA' to 1.\n", TimeResolutionSN); } else { Time_SFH = 0; SN_Array_Len = 0; while(Time_SFH < 50) { Time_SFH += TimeResolutionSN; ++SN_Array_Len; } } // For the delayed SN scheme the number of SN for each time step depends on the IMF. // As we will need to calculate this for every substep we create look-up tables for efficiency. // First we need to know given a timestep, what is the minimum mass star that will go supernova? double a = 0.7473; // Fits from Portinari et al. (1998). double b = -2.6979; double c = -4.7659; double d = 0.5934; coreburning_tbins_low = 2; // Any time below 2Myr will result in stars > 120Myr to explode. This is beyond the limits of the IMF. coreburning_tbins_high = 45; // Any time above 45Myr will result in stars > 8Myr to explode. Can just return 8.0 in this case. coreburning_tbins_delta = 0.00001; N_tbins = (coreburning_tbins_high - coreburning_tbins_low) / (coreburning_tbins_delta); int32_t bin_idx; coreburning_times = malloc(sizeof(*(coreburning_times)) * N_tbins); if (coreburning_times == NULL) { fprintf(stderr, "Could not allocate memory for the grid to contains the coreburning times.\n"); return EXIT_FAILURE; } for (bin_idx = 0; bin_idx < N_tbins; ++bin_idx) { double t = coreburning_tbins_low + ((double)bin_idx * coreburning_tbins_delta); coreburning_times[bin_idx] = exp10(a/log10(t) + b * exp(c/log10(t)) + d); } // Now need to know given a mass range (defined by the timestep) what is the number and mass fraction of SN that go supernova. m_IMFbins_low = 8.0; // The IMF range is from 8.0 to 120.0 Msun. m_IMFbins_high = 120.0; m_IMFbins_delta = 0.00001; N_massbins = (m_IMFbins_high - m_IMFbins_low) / (m_IMFbins_delta); IMF_massgrid_eta = malloc(sizeof(*(IMF_massgrid_eta)) * N_massbins); if (IMF_massgrid_eta == NULL) { fprintf(stderr, "Could not allocate memory for the grid to contain the IMF eta masses for delayed supernova.\n"); return EXIT_FAILURE; } IMF_massgrid_m = malloc(sizeof(*(IMF_massgrid_m)) * N_massbins); if (IMF_massgrid_m == NULL) { fprintf(stderr, "Could not allocate memory for the grid to contain the IMF m masses for delayed supernova.\n"); return EXIT_FAILURE; } for (bin_idx = 0; bin_idx < N_massbins; ++bin_idx) { IMF_massgrid_eta[bin_idx] = pow(m_IMFbins_low + ((double)bin_idx * m_IMFbins_delta), IMF_slope + 1.0); IMF_massgrid_m[bin_idx] = pow(m_IMFbins_low + ((double)bin_idx * m_IMFbins_delta), IMF_slope + 2.0); } return EXIT_SUCCESS; } int32_t init_nionlookup(void) { // For PhotonPrescription == 1 we wish to explicitly track the stellar ages of a galaxy. // Then we determine the number of ionizing photons using the age of the stellar population. // Using STARBURST99 it was determined that the number of ionizing photons emitted from an instantaneous starburst depends on the // mass of stars formed and the time since the starburst. Furthermore, the number of ionizing photons scales linearly with the mass of stars formed. // That is, a starburst that forms 7.0e10Msun worth of stars will emit 10x as many photons as a starburst that forms 6.0e10Msun worth of stars. // So if we read in a table that contains the number of ionizing photons emitted from a starburst for a 6.0e10Msun episode, then we can scale our values to this lookup table // using log10 Ngamma(Msun, t) = (log10 M* - 6.0) + log10 Ngamma(6.0, t). #define MAXBINS 10000 char buf[MAX_STRING_LEN], fname[MAX_STRING_LEN]; FILE *niontable; int32_t i = 0, num_lines = 0; float t, HI, HI_L, HeI, HeI_L, HeII, HeII_L, L; snprintf(fname, MAX_STRING_LEN - 1, ROOT_DIR "/extra/nion_table.txt"); niontable = fopen(fname, "r"); if (niontable == NULL) { fprintf(stderr, "Could not open file %s\n", fname); return EXIT_FAILURE; } stars_tbins = calloc(MAXBINS, sizeof(*(stars_tbins))); if (stars_tbins == NULL) { fprintf(stderr, "Could not allocate memory for the time bins for the tracking of stellar populations.\n"); return EXIT_FAILURE; } stars_Ngamma = calloc(MAXBINS, sizeof(*(stars_Ngamma))); if (stars_Ngamma == NULL) { fprintf(stderr, "Could not allocate memory for the Ngamma HI bins for the tracking of stellar populations.\n"); return EXIT_FAILURE; } // The first 8 lines are all header information. So move past them. while (i < 8) { fgets(buf, MAX_STRING_LEN, niontable); ++i; } while (fscanf(niontable, "%f %f %f %f %f %f %f %f", &t, &HI, &HI_L, &HeI, &HeI_L, &HeII, &HeII_L, &L) == 8) { stars_tbins[num_lines] = t; stars_Ngamma[num_lines] = HI; ++num_lines; if (num_lines == MAXBINS - 1) { fprintf(stderr, "Exceeding the maximum bins for the tracking of stellar populations.\n"); return EXIT_FAILURE; } } fclose(niontable); // Check that the Nion lookup table had enough datapoints to cover the time we're tracking the ages for. if (stars_tbins[num_lines - 1] / 1.0e6 < STELLAR_TRACKING_TIME) { fprintf(stderr, "The final time specified in the Nion lookup table is %.4f Myr. However we specified to track stellar ages over %d Myr.\n", stars_tbins[num_lines - 1] / 1.0e6, STELLAR_TRACKING_TIME); fprintf(stderr, "Either update the Nion lookup table or reduce the value of STELLAR_TRACKING_TIME in `core_allvars.h`.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; #undef MAXBINS } void set_units(void) { UnitTime_in_s = UnitLength_in_cm / UnitVelocity_in_cm_per_s; UnitTime_in_Megayears = UnitTime_in_s / SEC_PER_MEGAYEAR; UnitDensity_in_cgs = UnitMass_in_g / pow(UnitLength_in_cm, 3); UnitPressure_in_cgs = UnitMass_in_g / UnitLength_in_cm / pow(UnitTime_in_s, 2); UnitCoolingRate_in_cgs = UnitPressure_in_cgs / UnitTime_in_s; UnitEnergy_in_cgs = UnitMass_in_g * pow(UnitLength_in_cm, 2) / pow(UnitTime_in_s, 2); EnergySNcode = EnergySN / UnitEnergy_in_cgs * Hubble_h; sage_G = GRAVITY / pow(UnitLength_in_cm, 3) * UnitMass_in_g * pow(UnitTime_in_s, 2); // convert some physical input parameters to internal units sage_Hubble = HUBBLE * UnitTime_in_s; // compute a few quantitites RhoCrit = 3 * sage_Hubble * sage_Hubble / (8 * M_PI * sage_G); } void read_snap_list(void) { FILE *fd; char fname[1000]; sprintf(fname, "%s", FileWithSnapList); if(!(fd = fopen(fname, "r"))) { printf("can't read output list in file '%s'\n", fname); ABORT(0); } Snaplistlen = 0; do { if(fscanf(fd, " %lg ", &AA[Snaplistlen]) == 1) Snaplistlen++; else break; } while(Snaplistlen < MAXSNAPS); fclose(fd); } double time_to_present(double z) { #define WORKSIZE 1000 gsl_function F; gsl_integration_workspace *workspace; double time, result, abserr; workspace = gsl_integration_workspace_alloc(WORKSIZE); F.function = &integrand_time_to_present; gsl_integration_qag(&F, 1.0 / (z + 1), 1.0, 1.0 / sage_Hubble, 1.0e-8, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr); time = 1 / sage_Hubble * result; gsl_integration_workspace_free(workspace); // return time to present as a function of redshift return time; } double integrand_time_to_present(double a, void *param) { (void)(param); // Avoids triggering unused-parameter warning. return 1 / sqrt(Omega / a + (1 - Omega - OmegaLambda) + OmegaLambda * a * a); } int32_t init_fesc(void) { switch(fescPrescription) { case 0: if (ThisTask == 0) { printf("\n\nUsing a constant escape fraction of %.4f\n", beta); } break; case 1: if (ThisTask == 0) { printf("\n\nUsing an fesc prescription that scales with the fraction of ejected mass in the galaxy.\nThis takes the form A*fej + B with A = %.4e and B = %.4e\n", alpha, beta); } break; case 2: if (ThisTask == 0) { printf("\n\nUsing an fesc prescription that depends upon quasar activity.\n"); printf("\nFor a galaxy that had a quasar event within %.2f dynamical times go the escape fraction will be %.2f. Otherwise it will have a constant value of %.2f\n", N_dyntime, quasar_boosted, quasar_baseline); } break; case 3: if (ThisTask == 0) { printf("\n\nUsing Anne's functional form for an escape fraction that increases for descreasing halo mass.\n"); printf("MH_low = %.4e\tMH_high = %.4e\tfesc_low = %.4f\tfesc_high = %.4f.\n", MH_low, MH_high, fesc_low, fesc_high); } XASSERT(fesc_low > fesc_high, "Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 3), we require fesc_low > fesc_high\n", fesc_low, fesc_high); break; case 4: if (ThisTask == 0) { printf("\n\nUsing Anne's functional form for an escape fraction that increases for increasing halo mass.\n"); printf("MH_low = %.4e\tMH_high = %.4e\tfesc_low = %.4f\tfesc_high = %.4f.\n", MH_low, MH_high, fesc_low, fesc_high); } XASSERT(fesc_low < fesc_high, "Input file contain fesc_low = %.2f and fesc_high = %.2f. For this prescription (fescPrescription == 4), we require fesc_low < fesc_high\n", fesc_low, fesc_high); break; case 5: if (ThisTask == 0) { printf("\n\nUsing an fesc prescription that depends upon the SFR of the galaxy.\n"); printf("This takes the function form of a logistic function, fesc = delta / (1.0 + exp(-alpha*(log10(SFR)-beta))), with range [0.0, delta]. `alpha` controls the steepness of the curve and beta defines the value of log10(SFR) gives fesc = delta/2.\n"); printf("alpha = %.4f\tbeta = %.4f\tdelta = %.4f\n", alpha, beta, delta); } break; default: printf("\n\nOnly escape fraction prescriptions 0, 1, 2, 3, 4 or 5 are permitted.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* For some escape fraction prescriptions, the functional form is a power law with the constants calculated using two fixed points. This function determines these constants based on the fixed points specified. Refer to the .ini file or `determine_fesc()` function for full details on each `fescPrescription`. Parameters ---------- None. All variables used/adjusted are global. Returns ---------- None. All variables adjusted are global . Pointer Updates ---------- None. Units ---------- The Halo Masses used to specify the fixed points (MH_low and MH_high) are in Msun. */ int32_t determine_fescMH_constants(void) { double A, B, log_A; switch(fescPrescription) { case 3: log_A = (log10(fesc_high) - (log10(fesc_low)*log10(MH_high)/log10(MH_low))) * pow(1 - (log10(MH_high) / log10(MH_low)), -1); B = (log10(fesc_low) - log_A) / log10(MH_low); A = pow(10, log_A); fescMH_alpha = A; fescMH_beta = B; printf("Fixing the points (%.4e, %.2f) and (%.4e, %.2f)\n", MH_low, fesc_low, MH_high, fesc_high); printf("This gives a power law with constants A = %.4e, B = %.4e\n", fescMH_alpha, fescMH_beta); break; } return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6740514905, "avg_line_length": 29.7580645161, "ext": "c", "hexsha": "9c9428dc3ed01889d230e5ab816c187df1725f63", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jacobseiler/rsage", "max_forks_repo_path": "src/sage/core_init.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jacobseiler/rsage", "max_issues_repo_path": "src/sage/core_init.c", "max_line_length": 265, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jacobseiler/rsage", "max_stars_repo_path": "src/sage/core_init.c", "max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z", "num_tokens": 4430, "size": 14760 }
/* specfunc/hyperg.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* Miscellaneous implementations of use * for evaluation of hypergeometric functions. */ #ifndef _HYPERG_H_ #define _HYPERG_H_ #include <gsl/gsl_sf_result.h> /* Direct implementation of 1F1 series. */ int gsl_sf_hyperg_1F1_series_e(const double a, const double b, const double x, gsl_sf_result * result); /* Implementation of the 1F1 related to the * incomplete gamma function: 1F1(1,b,x), b >= 1. */ int gsl_sf_hyperg_1F1_1_e(double b, double x, gsl_sf_result * result); /* 1F1(1,b,x) for integer b >= 1 */ int gsl_sf_hyperg_1F1_1_int_e(int b, double x, gsl_sf_result * result); /* Implementation of large b asymptotic. * [Bateman v. I, 6.13.3 (18)] * [Luke, The Special Functions and Their Approximations v. I, p. 129, 4.8 (4)] * * a^2 << b, |x|/|b| < 1 - delta */ int gsl_sf_hyperg_1F1_large_b_e(const double a, const double b, const double x, gsl_sf_result * result); /* Implementation of large b asymptotic. * * Assumes a > 0 is small, x > 0, and |x|<|b|. */ int gsl_sf_hyperg_U_large_b_e(const double a, const double b, const double x, gsl_sf_result * result, double * ln_multiplier ); /* Implementation of 2F0 asymptotic series. */ int gsl_sf_hyperg_2F0_series_e(const double a, const double b, const double x, int n_trunc, gsl_sf_result * result); #endif /* !_HYPERG_H_ */
{ "alphanum_fraction": 0.6841409692, "avg_line_length": 28.7341772152, "ext": "h", "hexsha": "37d11b046509880969de3b6bd8b807cf1c37f310", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/hyperg.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/hyperg.h", "max_line_length": 100, "max_stars_count": 14, "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vinej/sml", "max_stars_repo_path": "include/gsl/hyperg.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 633, "size": 2270 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_qrng.h> #include <gsl/gsl_errno.h> /* Setup */ gsl_qrng *mgsl_qrng_alloc(int type, unsigned int d) { const gsl_qrng_type *types[] = { gsl_qrng_niederreiter_2, gsl_qrng_sobol, gsl_qrng_halton, gsl_qrng_reversehalton }; const gsl_qrng_type *T; gsl_qrng *q; T = types[type]; q = gsl_qrng_alloc(T, d); return q; }
{ "alphanum_fraction": 0.7157894737, "avg_line_length": 23.75, "ext": "c", "hexsha": "b71c27378a5278f795b47def22bc7eebf26a6a46", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "595e2fb9055cbcb13277937c7a8d06461c48851c", "max_forks_repo_licenses": [ "Artistic-2.0" ], "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-QuasiRandom", "max_forks_repo_path": "src/quasirandom.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "595e2fb9055cbcb13277937c7a8d06461c48851c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Artistic-2.0" ], "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-QuasiRandom", "max_issues_repo_path": "src/quasirandom.c", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "595e2fb9055cbcb13277937c7a8d06461c48851c", "max_stars_repo_licenses": [ "Artistic-2.0" ], "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-QuasiRandom", "max_stars_repo_path": "src/quasirandom.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 129, "size": 380 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for example generation of waveforms with the EOBNRv2HM reduced order model, * processing through the Fourier-domain LISA response and SNR calculation. * */ #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "EOBNRv2HMROMstruct.h" #include "EOBNRv2HMROM.h" #include "wip.h" #include "LISAgeometry.h" #include "LISAFDresponse.h" /* Parameters for the generation of a ROM waveform (in the form of a list of modes) */ /* All parameters are to be given in SI units! */ typedef struct tagROMParams { int nbmode; /* Number of modes to generate (starting with the 22) - defaults to 1 (22 mode only) */ double tRef; /* shift in time with respect to the 22-fit-removed waveform */ double phiRef; /* phase at fRef */ double fRef; /* reference frequency */ double m1; /* mass of companion 1 */ double m2; /* mass of companion 2 */ double distance; /* distance of source */ char outname[256]; /* file to which output should be written */ } ROMParams; /* Parameters for the generation of a ROM waveform (in the form of a list of modes) */ /* All parameters are in SI units in the internals */ /* Angle definitions are taken from the Krolak&al paper gr-qc/0401108 */ typedef struct tagLISAParams { int nbmode; /* Number of modes to generate (starting with the 22) - defaults to 1 (22 mode only) */ double tRef; /* shift in time with respect to the 22-fit-removed waveform */ double phiRef; /* phase at fRef */ double fRef; /* reference frequency */ double m1; /* mass of companion 1 */ double m2; /* mass of companion 2 */ double distance; /* distance of source */ double inclination; /* inclination of L relative to line of sight */ double lambda; /* First angle for the position in the sky of the source */ double beta; /* Second angle for the position in the sky of the source */ double psi; /* Polarization angle */ char outname[256]; /* file to which output should be written */ } LISAParams; /* Parse command line and return a newly allocated ROMParams object * Masses are input in solar masses and distances in Mpc - converted in SI for the internals */ static ROMParams* parse_args_ROM(ssize_t argc, char **argv) { ssize_t i; ROMParams* params; params = (ROMParams*) malloc(sizeof(ROMParams)); memset(params, 0, sizeof(ROMParams)); /* Set default values to the arguments */ params->nbmode = 1; params->tRef = 0.; params->phiRef = 0.; params->fRef = 0.; params->m1 = 1. * 1e6 * MSUN_SI; params->m2 = 1. * 1e6 * MSUN_SI; params->distance = 1. * 1e9 * PC_SI; /* consume command line */ for (i = 1; i < argc; ++i) { if (strcmp(argv[i], "--nbmode") == 0) { params->nbmode = atof(argv[++i]); } else if (strcmp(argv[i], "--tRef") == 0) { params->tRef = atof(argv[++i]); } else if (strcmp(argv[i], "--phiRef") == 0) { params->phiRef = atof(argv[++i]); } else if (strcmp(argv[i], "--fRef") == 0) { params->fRef = atof(argv[++i]); } else if (strcmp(argv[i], "--m1") == 0) { params->m1 = atof(argv[++i]) * MSUN_SI; } else if (strcmp(argv[i], "--m2") == 0) { params->m2 = atof(argv[++i]) * MSUN_SI; } else if (strcmp(argv[i], "--distance") == 0) { params->distance = atof(argv[++i]) * 1e6 * PC_SI; } else if (strcmp(argv[i], "--outname") == 0) { strncpy(params->outname, argv[++i], 256); } else { printf("Error: invalid option: %s\n", argv[i]); goto fail; } } return params; fail: free(params); exit(1); } /* Parse command line and return a newly allocated LISAParams object * Masses are input in solar masses and distances in Mpc - converted in SI for the internals */ static LISAParams* parse_args_LISA(ssize_t argc, char **argv) { ssize_t i; LISAParams* params; params = (LISAParams*) malloc(sizeof(LISAParams)); memset(params, 0, sizeof(LISAParams)); /* Set default values to the arguments */ params->nbmode = 1; params->tRef = 0.; params->phiRef = 0.; params->fRef = 0.; params->m1 = 1. * 1e6 * MSUN_SI; params->m2 = 1. * 1e6 * MSUN_SI; params->distance = 1. * 1e9 * PC_SI; params->inclination = 0.; params->lambda = 0.; params->beta = 0.; params->psi = 0.; sprintf(params->outname, ""); /* consume command line */ for (i = 1; i < argc; ++i) { if (strcmp(argv[i], "--nbmode") == 0) { params->nbmode = atof(argv[++i]); } else if (strcmp(argv[i], "--tRef") == 0) { params->tRef = atof(argv[++i]); } else if (strcmp(argv[i], "--phiRef") == 0) { params->phiRef = atof(argv[++i]); } else if (strcmp(argv[i], "--fRef") == 0) { params->fRef = atof(argv[++i]); } else if (strcmp(argv[i], "--m1") == 0) { params->m1 = atof(argv[++i]) * MSUN_SI; } else if (strcmp(argv[i], "--m2") == 0) { params->m2 = atof(argv[++i]) * MSUN_SI; } else if (strcmp(argv[i], "--distance") == 0) { params->distance = atof(argv[++i]) * 1e6 * PC_SI; } else if (strcmp(argv[i], "--inclination") == 0) { params->inclination = atof(argv[++i]); } else if (strcmp(argv[i], "--lambda") == 0) { params->lambda = atof(argv[++i]); } else if (strcmp(argv[i], "--beta") == 0) { params->beta = atof(argv[++i]); } else if (strcmp(argv[i], "--psi") == 0) { params->psi = atof(argv[++i]); } else if (strcmp(argv[i], "--outname") == 0) { strncpy(params->outname, argv[++i], 256); } else { printf("Error: invalid option: %s\n", argv[i]); goto fail; } } return params; fail: free(params); exit(1); } /* Function to output to a file an AmpPhaseFrequencySeries; each mode will be output to a separate file using this function */ static int Write_CAmpPhaseFrequencySeries(FILE* f, CAmpPhaseFrequencySeries* freqseries) { gsl_vector* freq = freqseries->freq; gsl_vector* amp_real = freqseries->amp_real; gsl_vector* amp_imag = freqseries->amp_imag; gsl_vector* phase = freqseries->phase; int len = (int) freq->size; /*Here, we could add a check on the length of the gsl_vectors*/ fprintf(f, "# f amp_re amp_im phase\n"); for (int i=0; i<len; i++) { fprintf(f, "%.16e %.16e %.16e %.16e\n", gsl_vector_get(freq, i), gsl_vector_get(amp_real, i), gsl_vector_get(amp_imag, i), gsl_vector_get(phase, i)); } return 0; } /* * Swhitenoise * a simple noise function */ double Swhitenoise(double x){ return 1; }; /* * main */ int main (int argc , char **argv) { FILE* f; ListmodesCAmpPhaseFrequencySeries* listROM = NULL; ListmodesCAmpPhaseFrequencySeries* listA = NULL; ListmodesCAmpPhaseFrequencySeries* listE = NULL; ListmodesCAmpPhaseFrequencySeries* listT = NULL; //ROMParams* params; LISAParams* params; /* parse commandline */ //params = parse_args_ROM(argc, argv); params = parse_args_LISA(argc, argv); /* Generate the waveform with the ROM */ SimEOBNRv2HMROM(&listROM, params->nbmode, params->tRef, params->phiRef, params->fRef, params->m1, params->m2, params->distance); /* Process the waveform through the LISA response */ LISASimFDResponseTDI(&listROM, &listA, &listE, &listT, params->inclination, params->lambda, params->beta, params->psi); ListmodesCAmpPhaseFrequencySeries* listelementA; ListmodesCAmpPhaseFrequencySeries* listelementE; ListmodesCAmpPhaseFrequencySeries* listelementT; int l,m; int status = 0; /* Loop over the modes */ for(int i=0; i<params->nbmode; i++){ l = listmode[i][0]; m = listmode[i][1]; listelementA = ListmodesCAmpPhaseFrequencySeries_GetMode(listA, l, m); listelementE = ListmodesCAmpPhaseFrequencySeries_GetMode(listE, l, m); listelementT = ListmodesCAmpPhaseFrequencySeries_GetMode(listT, l, m); /* Write files - suffix _A,E,T_lm.dat imposed to each file name, attached to the string given by outname */ /* If outname is still the default empty string, we do not output and skip this stage */ if(!(strcmp(params->outname, "") == 0)){ char *filenameA = malloc(strlen(params->outname)+64); char *filenameE = malloc(strlen(params->outname)+64); char *filenameT = malloc(strlen(params->outname)+64); sprintf(filenameA, "%s%s%d%d%s", params->outname, "_A_", l, m, ".dat"); sprintf(filenameE, "%s%s%d%d%s", params->outname, "_E_", l, m, ".dat"); sprintf(filenameT, "%s%s%d%d%s", params->outname, "_T_", l, m, ".dat"); f = fopen(filenameA, "w"); status |= Write_CAmpPhaseFrequencySeries(f, listelementA->freqseries); fclose(f); f = fopen(filenameE, "w"); status |= Write_CAmpPhaseFrequencySeries(f, listelementE->freqseries); fclose(f); f = fopen(filenameT, "w"); status |= Write_CAmpPhaseFrequencySeries(f, listelementT->freqseries); fclose(f); if (status) goto fail; } /* Example SNR calculation, taking the A observable */ double *f1=listelementA->freqseries->freq->data; int n1=listelementA->freqseries->freq->size; double *s1Ar=listelementA->freqseries->amp_real->data; double *s1Ai=listelementA->freqseries->amp_imag->data; double *s1p=listelementA->freqseries->phase->data; double *f2=listelementA->freqseries->freq->data; int n2=listelementA->freqseries->freq->size; double *s2Ar=listelementA->freqseries->amp_real->data; double *s2Ai=listelementA->freqseries->amp_imag->data; double *s2p=listelementA->freqseries->phase->data; printf("n1: %d\n", n1); printf("s1Ar[299]: %g\n", s1Ar[299]); double start=((double)clock())/CLOCKS_PER_SEC; //JGB: Set these somehwere else where it makes sense. f_min or f_max <= 0 means use intersection of signal domains. double f_min=-1.0; double f_max=-1.0; double rho2= wip_phase (f1, n1, f2, n2, s1Ar, s1Ai, s1p, s2Ar, s2Ai, s2p, Swhitenoise, 1.0, f_min, f_max); double end=((double)clock())/CLOCKS_PER_SEC; printf( "SNR2 = %g, SNR time = %g\n", rho2, end-start); printf( "SNR = %g, SNR time = %g\n",sqrt(rho2), end-start); } /* clean up */ free(params); ListmodesCAmpPhaseFrequencySeries_Destroy(listROM); ListmodesCAmpPhaseFrequencySeries_Destroy(listA); ListmodesCAmpPhaseFrequencySeries_Destroy(listE); ListmodesCAmpPhaseFrequencySeries_Destroy(listT); return 0; fail: free(params); ListmodesCAmpPhaseFrequencySeries_Destroy(listROM); ListmodesCAmpPhaseFrequencySeries_Destroy(listA); ListmodesCAmpPhaseFrequencySeries_Destroy(listE); ListmodesCAmpPhaseFrequencySeries_Destroy(listT); return 1; }
{ "alphanum_fraction": 0.6024803084, "avg_line_length": 39, "ext": "c", "hexsha": "30fb12cfe7504993998ceefed58acaa900e92c19", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_line_length": 156, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 3259, "size": 11934 }
/* * Partition.h * Provides class prototype that simplifies partition vectors. * Copyright 2017 Dariusz Kuchta Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <vector> #include <gsl.h> namespace spectre::unsupervised { /// <summary> /// Class storing simplified representation of partition vectors. /// </summary> class Partition { public: /// <summary> /// Default constructor. Deleted so no dataless instance can be created. /// </summary> Partition() = delete; /// <summary> /// Constructor taking partition data and computing its simplified version. /// </summary> /// <param name="partition">Input partition data.</param> explicit Partition(gsl::span<unsigned int> partition); /// <summary> /// Getter for simplified partition data. /// </summary> /// <returns>Stored simplified partition.</returns> const std::vector<unsigned int>& Get() const; /// <summary> /// Method for comparing specified partitions. /// </summary> /// <param name="lhs">The first partition.</param> /// <param name="rhs">The second partition.</param> /// <param name="tolerance">The tolerance rate of mismatch.</param> static bool Compare(const Partition &lhs, const Partition &rhs, double tolerance = 0); /// <summary> /// Equality operator. Compares with tolerance = 0. /// </summary> /// <param name="other">The second partition.</param> bool operator==(const Partition &other) const; /// <summary> /// Inequality operator. Compares with tolerance = 0. /// </summary> /// <param name="other">The second partition.</param> bool operator!=(const Partition &other) const; private: std::vector<unsigned int> m_Partition; }; }
{ "alphanum_fraction": 0.6779289162, "avg_line_length": 30.3866666667, "ext": "h", "hexsha": "4598561dd7c51e3f905a4a252652fa066602f804", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "spectre-team/native-algorithms", "max_forks_repo_path": "src/Spectre.libClustering/Partition.h", "max_issues_count": 36, "max_issues_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_issues_repo_issues_event_max_datetime": "2018-08-03T21:18:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-12-31T16:44:51.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "spectre-team/native-algorithms", "max_issues_repo_path": "src/Spectre.libClustering/Partition.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "spectre-team/native-algorithms", "max_stars_repo_path": "src/Spectre.libClustering/Partition.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 506, "size": 2279 }
/* min/golden.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* goldensection.c -- goldensection minimum finding algorithm */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_min.h> #include "min.h" typedef struct { double dummy; } goldensection_state_t; static 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); static 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); static 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) { goldensection_state_t * state = (goldensection_state_t *) vstate; /* no initialization required, prevent warnings about unused variables */ state = 0; f = 0; x_minimum = 0; f_minimum = 0; x_lower = 0; f_lower = 0; x_upper = 0; f_upper = 0; return GSL_SUCCESS; } static 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) { goldensection_state_t * state = (goldensection_state_t *) vstate; const double x_center = *x_minimum ; const double x_left = *x_lower ; const double x_right = *x_upper ; const double f_min = *f_minimum; const double golden = 0.3819660; /* golden = (3 - sqrt(5))/2 */ const double w_lower = (x_center - x_left); const double w_upper = (x_right - x_center); double x_new, f_new; state = 0 ; /* avoid warning about unused parameters */ x_new = x_center + golden * ((w_upper > w_lower) ? w_upper : -w_lower) ; SAFE_FUNC_CALL (f, x_new, &f_new); if (f_new < f_min) { *x_minimum = x_new ; *f_minimum = f_new ; return GSL_SUCCESS; } else if (x_new < x_center && f_new > f_min) { *x_lower = x_new ; *f_lower = f_new ; return GSL_SUCCESS; } else if (x_new > x_center && f_new > f_min) { *x_upper = x_new ; *f_upper = f_new ; return GSL_SUCCESS; } else { return GSL_FAILURE; } } static const gsl_min_fminimizer_type goldensection_type = {"goldensection", /* name */ sizeof (goldensection_state_t), &goldensection_init, &goldensection_iterate}; const gsl_min_fminimizer_type * gsl_min_fminimizer_goldensection = &goldensection_type;
{ "alphanum_fraction": 0.6922180122, "avg_line_length": 28.3553719008, "ext": "c", "hexsha": "49dfddb36cc7aacb1de17bbdb60f3d6c6204ae83", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/min/golden.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/min/golden.c", "max_line_length": 179, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/min/golden.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 936, "size": 3431 }
#ifndef DIRICHLETSAMPLE_H #define DIRICHLETSAMPLE_H #include <stdio.h> #include <iostream> #include <vector> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <sys/time.h> using namespace std; std::vector<double> DirSample(std::vector<double> alpha, int k, int N); #endif
{ "alphanum_fraction": 0.7474048443, "avg_line_length": 18.0625, "ext": "h", "hexsha": "bb95e20964554d4002557f9d0d8d8424717e0be8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "KathrynLaing/CPNLearning", "max_forks_repo_path": "10_DirichletSample.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "KathrynLaing/CPNLearning", "max_issues_repo_path": "10_DirichletSample.h", "max_line_length": 71, "max_stars_count": null, "max_stars_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "KathrynLaing/CPNLearning", "max_stars_repo_path": "10_DirichletSample.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 80, "size": 289 }
/** @file matrix.h * @author T J Atherton * * @brief Veneer class over the objectmatrix type that interfaces with blas and lapack */ #ifndef matrix_h #define matrix_h #include <stdio.h> #include "veneer.h" /** Use Apple's Accelerate library for LAPACK and BLAS */ #ifdef __APPLE__ #ifdef MORPHO_LINALG_USE_ACCELERATE #include <Accelerate/Accelerate.h> #define MATRIX_LAPACK_PRESENT #endif #endif /** Otherwise, use LAPACKE */ #ifndef MATRIX_LAPACK_PRESENT #include <cblas.h> #include <lapacke.h> #define MORPHO_LINALG_USE_LAPACKE #define MATRIX_LAPACK_PRESENT #endif /* ------------------------------------------------------- * Matrix objects * ------------------------------------------------------- */ extern objecttype objectmatrixtype; #define OBJECT_MATRIX objectmatrixtype /** Matrices are a purely numerical collection type oriented toward linear algebra. Elements are stored in column-major format, i.e. [ 1 2 ] [ 3 4 ] is stored ( 1, 3, 2, 4 ) in memory. This is for compatibility with standard linear algebra packages */ typedef struct { object obj; unsigned int nrows; unsigned int ncols; double *elements; double matrixdata[]; } objectmatrix; /** Tests whether an object is a matrix */ #define MORPHO_ISMATRIX(val) object_istype(val, OBJECT_MATRIX) /** Gets the object as an matrix */ #define MORPHO_GETMATRIX(val) ((objectmatrix *) MORPHO_GETOBJECT(val)) /** Creates a matrix object */ objectmatrix *object_newmatrix(unsigned int nrows, unsigned int ncols, bool zero); /** Creates a new matrix from an array */ objectmatrix *object_matrixfromarray(objectarray *array); /** Creates a new matrix from an existing matrix */ objectmatrix *object_clonematrix(objectmatrix *array); /** @brief Use to create static matrices on the C stack @details Intended for small matrices; Caller needs to supply a double array of size nr*nc. */ #define MORPHO_STATICMATRIX(darray, nr, nc) { .obj.type=OBJECT_MATRIX, .obj.status=OBJECT_ISUNMANAGED, .obj.next=NULL, .elements=darray, .nrows=nr, .ncols=nc } /** Macro to decide if a matrix is 'small' or 'large' and hence static or dynamic allocation should be used. */ #define MATRIX_ISSMALL(m) (m->nrows*m->ncols<MORPHO_MAXIMUMSTACKALLOC) /* ------------------------------------------------------- * Matrix class * ------------------------------------------------------- */ #define MATRIX_CLASSNAME "Matrix" #define MATRIX_TRANSPOSE_METHOD "transpose" #define MATRIX_TRACE_METHOD "trace" #define MATRIX_INNER_METHOD "inner" #define MATRIX_DET_METHOD "det" #define MATRIX_EIGENVALUES_METHOD "eigenvalues" #define MATRIX_EIGENSYSTEM_METHOD "eigensystem" #define MATRIX_NORM_METHOD "norm" #define MATRIX_GETCOLUMN_METHOD "column" #define MATRIX_SETCOLUMN_METHOD "setcolumn" #define MATRIX_DIMENSIONS_METHOD "dimensions" #define MATRIX_INDICESOUTSIDEBOUNDS "MtrxBnds" #define MATRIX_INDICESOUTSIDEBOUNDS_MSG "Matrix index out of bounds." #define MATRIX_INVLDINDICES "MtrxInvldIndx" #define MATRIX_INVLDINDICES_MSG "Matrix indices must be integers." #define MATRIX_INVLDNUMINDICES "MtrxInvldNumIndx" #define MATRIX_INVLDNUMINDICES_MSG "Matrix expects two arguments for indexing." #define MATRIX_CONSTRUCTOR "MtrxCns" #define MATRIX_CONSTRUCTOR_MSG "Matrix() constructor should be called either with dimensions or an array, list or matrix initializer." #define MATRIX_INVLDARRAYINIT "MtrxInvldInit" #define MATRIX_INVLDARRAYINIT_MSG "Invalid initializer passed to Matrix()." #define MATRIX_ARITHARGS "MtrxInvldArg" #define MATRIX_ARITHARGS_MSG "Matrix arithmetic methods expect a matrix or number as their argument." #define MATRIX_INCOMPATIBLEMATRICES "MtrxIncmptbl" #define MATRIX_INCOMPATIBLEMATRICES_MSG "Matrices have incompatible shape." #define MATRIX_SINGULAR "MtrxSnglr" #define MATRIX_SINGULAR_MSG "Matrix is singular." #define MATRIX_NOTSQ "MtrxNtSq" #define MATRIX_NOTSQ_MSG "Matrix is not square." #define MATRIX_SETCOLARGS "MtrxStClArgs" #define MATRIX_SETCOLARGS_MSG "Method setcolumn expects an integer column index and a column matrix as arguments." /* ------------------------------------------------------- * Matrix errors * ------------------------------------------------------- */ typedef enum { MATRIX_OK, MATRIX_INCMPTBLDIM, MATRIX_SING, MATRIX_INVLD, MATRIX_BNDS, MATRIX_NSQ, MATRIX_ALLOC } objectmatrixerror; /* ------------------------------------------------------- * Matrix interface * ------------------------------------------------------- */ bool matrix_getarraydimensions(objectarray *array, unsigned int dim[], unsigned int maxdim, unsigned int *ndim); value matrix_getarrayelement(objectarray *array, unsigned int ndim, unsigned int *indx); bool matrix_getlistdimensions(objectlist *list, unsigned int dim[], unsigned int maxdim, unsigned int *ndim); bool matrix_getlistelement(objectlist *list, unsigned int ndim, unsigned int *indx, value *val); bool matrix_setelement(objectmatrix *matrix, unsigned int row, unsigned int col, double value); bool matrix_getelement(objectmatrix *matrix, unsigned int row, unsigned int col, double *value); bool matrix_getcolumn(objectmatrix *matrix, unsigned int col, double **v); bool matrix_setcolumn(objectmatrix *matrix, unsigned int col, double *v); bool matrix_addtocolumn(objectmatrix *m, unsigned int col, double alpha, double *v); objectmatrixerror matrix_copy(objectmatrix *a, objectmatrix *out); objectmatrixerror matrix_add(objectmatrix *a, objectmatrix *b, objectmatrix *out); objectmatrixerror matrix_accumulate(objectmatrix *a, double lambda, objectmatrix *b); objectmatrixerror matrix_sub(objectmatrix *a, objectmatrix *b, objectmatrix *out); objectmatrixerror matrix_mul(objectmatrix *a, objectmatrix *b, objectmatrix *out); objectmatrixerror matrix_inner(objectmatrix *a, objectmatrix *b, double *out); objectmatrixerror matrix_divs(objectmatrix *a, objectmatrix *b, objectmatrix *out); objectmatrixerror matrix_divl(objectmatrix *a, objectmatrix *b, objectmatrix *out); objectmatrixerror matrix_inverse(objectmatrix *a, objectmatrix *out); objectmatrixerror matrix_transpose(objectmatrix *a, objectmatrix *out); objectmatrixerror matrix_trace(objectmatrix *a, double *out); objectmatrixerror matrix_scale(objectmatrix *a, double scale); objectmatrixerror matrix_identity(objectmatrix *a); double matrix_sum(objectmatrix *a); //objectmatrixerror matrix_det(objectmatrix *a, double *out); //objectmatrixerror matrix_eigensystem(objectmatrix *a, double *val, objectmatrix *vec); void matrix_print(objectmatrix *m); void matrix_initialize(void); #endif /* matrix_h */
{ "alphanum_fraction": 0.7102489019, "avg_line_length": 41.6463414634, "ext": "h", "hexsha": "04f61b843d779b580956ff079e63deb21f5fd7e3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mattsep/morpho", "max_forks_repo_path": "morpho5/datastructures/matrix.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mattsep/morpho", "max_issues_repo_path": "morpho5/datastructures/matrix.h", "max_line_length": 164, "max_stars_count": null, "max_stars_repo_head_hexsha": "50bb935653c0675b81e9f2d78573cf117971a147", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mattsep/morpho", "max_stars_repo_path": "morpho5/datastructures/matrix.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1507, "size": 6830 }
#pragma once #ifndef _NOGSL #include <gsl/gsl_vector.h> #else #include "CustomSolver.h" #endif #include "ValueGrad.h" #include "BooleanNodes.h" #include "BooleanDAG.h" #include "NodeVisitor.h" #include "VarStore.h" #include <map> #include <set> #include "SymbolicEvaluator.h" #include "Interface.h" #include <iostream> using namespace std; class Path { public: map<int, int> nodeToVal; Path() { } void add(map<int, int>& initMap) { nodeToVal.insert(initMap.begin(), initMap.end()); } void addCond(int nodeid, int val) { Assert(nodeToVal.find(nodeid) == nodeToVal.end(), "Node already has value"); nodeToVal[nodeid] = val; } string toString() { stringstream s; for (auto it = nodeToVal.begin(); it != nodeToVal.end(); it++) { s << "(" << it->first << "," << it->second << ");"; } return s.str(); } int getVal(int nodeid) { if (nodeToVal.find(nodeid) == nodeToVal.end()) { return -1; } else { return nodeToVal[nodeid]; } } void empty() { nodeToVal.clear(); } int length() { return nodeToVal.size(); } int lowestId() { if (nodeToVal.size() == 0) { return -1; } return nodeToVal.begin()->first; } static bool isCompatible(Path* p1, Path* p2) { int size1 = p1->nodeToVal.size(); int size2 = p2->nodeToVal.size(); if (size1 == 0 || size2 == 0) { return true; } Path* pl; Path* ps; if (size1 > size2) { pl = p1; ps = p2; } else { pl = p2; ps = p1; } for (auto it = pl->nodeToVal.begin(); it != pl->nodeToVal.end(); it++) { int nodeid = it->first; int val = it->second; int val1 = ps->getVal(nodeid); if (val1 != -1 && val != val1) { return false; } } return true; } static void combinePaths(Path* p1, Path* p2, Path* p) { // assumes that paths are compatible p->nodeToVal.clear(); p->add(p1->nodeToVal); p->add(p2->nodeToVal); } static void combinePath(Path* p1, Path* p) { p->nodeToVal.clear(); p->add(p1->nodeToVal); } static void combinePaths(vector<Path*>& paths, Path* p2, Path* p) { p->nodeToVal.clear(); p->add(p2->nodeToVal); // TODO: need to add common conditions in paths to p } static Path* pIntersect(Path* p1, Path* p2) { // assumes that the paths are compatible Path* p = new Path(); p->add(p1->nodeToVal); p->add(p2->nodeToVal); return p; } // only one cond should differ static int isConjugate(Path* p1, Path* p2) { //cout << "Conjugate check: " << p1->toString() << " | " << p2->toString() << endl; if (p1->length() != p2->length()) { return -1; } int conjIdx = -1; int ctr = 0; for (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) { if (p2->getVal(it->first) == -1) { return -1; } if (p2->getVal(it->first) != it->second) { if (conjIdx == -1) { conjIdx = ctr; } else { return -1; } } ctr++; } //cout << conjIdx << endl; return conjIdx; } static Path* pUnion(Path* p1, Path* p2) { // assumes that the paths are conjugates Path* p = new Path(); for (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) { if (p2->getVal(it->first) == it->second) { p->addCond(it->first, it->second); } } return p; } static bool isSubset(Path* p1, Path* p2) { if (p1->length() == 0) return true; for (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) { if (p2->getVal(it->first) != it->second) { return false; } } return true; } // no common condition static bool isDisjoint(Path* p1, Path* p2) { if (p1->length() == 0 || p2->length() == 0) return false; for (auto it = p1->nodeToVal.begin(); it != p1->nodeToVal.end(); it++) { if (p2->getVal(it->first) != -1) { return false; } } return true; } }; class MergeNodesList { vector<tuple<int, int, int, int>> nodesToMerge; public: void add(int node1, int idx1, int node2, int idx2) { nodesToMerge.push_back(make_tuple(node1, idx1, node2, idx2)); } string print() { stringstream s; for (int i = 0; i < nodesToMerge.size(); i++) { auto& t = nodesToMerge[i]; s << "(" << get<0>(t) << "," << get<1>(t) << "," << get<2>(t) << "," << get<3>(t) << ") "; } return s.str(); } int size() { return nodesToMerge.size(); } tuple<int, int, int, int>& getTuple(int idx) { return nodesToMerge[idx]; } }; class KLocalityAutoDiff: public NodeVisitor, public SymbolicEvaluator { BooleanDAG& bdag; map<string, int>& floatCtrls; // Maps float ctrl names to indices within grad vector int nctrls; // number of float ctrls gsl_vector* ctrls; // ctrl values vector<vector<ValueGrad*>> values; // Keeps track of values along with gradients for each node vector<vector<DistanceGrad*>> distances; // Keeps track of distance metric for boolean nodes vector<vector<Path*>> paths; vector<int> sizes; Interface* inputValues; set<string> pathStrings; int MAX_REGIONS = 16 + 1; // 0th idx is for final merging vector<vector<MergeNodesList*>> mergeNodes; public: int DEFAULT_INP = -32; KLocalityAutoDiff(BooleanDAG& bdag_p, map<string, int>& floatCtrls_p); ~KLocalityAutoDiff(void); virtual void visit( SRC_node& node ); virtual void visit( DST_node& node ); virtual void visit( CTRL_node& node ); virtual void visit( PLUS_node& node ); virtual void visit( TIMES_node& node ); virtual void visit( ARRACC_node& node ); virtual void visit( DIV_node& node ); virtual void visit( MOD_node& node ); virtual void visit( NEG_node& node ); virtual void visit( CONST_node& node ); virtual void visit( LT_node& node ); virtual void visit( EQ_node& node ); virtual void visit( AND_node& node ); virtual void visit( OR_node& node ); virtual void visit( NOT_node& node ); virtual void visit( ARRASS_node& node ); virtual void visit( UFUN_node& node ); virtual void visit( TUPLE_R_node& node ); virtual void visit( ASSERT_node& node ); virtual void setInputs(Interface* inputValues_p); virtual void run(const gsl_vector* ctrls_p, const set<int>& nodesSubset) { Assert(false, "Not yet supported"); } virtual void run(const gsl_vector* ctrls_p); virtual double getErrorOnConstraint(int nodeid, gsl_vector* grad); double getSqrtError(bool_node* node, gsl_vector* grad); double getAssertError(bool_node* node, gsl_vector* grad); double getBoolCtrlError(bool_node* node, gsl_vector* grad); double getBoolExprError(bool_node* node, gsl_vector* grad); virtual double getErrorOnConstraint(int nodeid); double getSqrtError(bool_node* node); double getAssertError(bool_node* node); double getBoolCtrlError(bool_node* node); double getBoolExprError(bool_node* node); virtual double getErrorForAsserts(const set<int>& assertIds, gsl_vector* grad) { Assert(false, "TODO"); } virtual double getErrorForAssert(int assertId, gsl_vector* grad) { Assert(false, "TODO"); } void setvalue(bool_node& bn, int idx, ValueGrad* v) { values[bn.id][idx] = v; } ValueGrad* v(bool_node& bn, int idx) { ValueGrad* val = values[bn.id][idx]; if (val == NULL) { gsl_vector* g = gsl_vector_alloc(nctrls); GradUtil::default_grad(g); val = new ValueGrad(0, g); setvalue(bn, idx, val); } return val; } ValueGrad* v(bool_node* bn, int idx) { return v(*bn, idx); } void setdistance(bool_node& bn, int idx, DistanceGrad* d) { distances[bn.id][idx] = d; } DistanceGrad* d(bool_node& bn, int idx) { DistanceGrad* dist = distances[bn.id][idx]; if (dist == NULL) { gsl_vector* g = gsl_vector_alloc(nctrls); GradUtil::default_grad(g); dist = new DistanceGrad(0, g); setdistance(bn, idx, dist); } return dist; } DistanceGrad* d(bool_node* bn, int idx) { return d(*bn, idx); } int size(bool_node& bn) { return sizes[bn.id]; } int size(bool_node* bn) { return size(*bn); } void setsize(bool_node& bn, int sz) { sizes[bn.id] = sz; } void setsize(bool_node* n, int sz) { setsize(*n, sz); } void setpath(bool_node& bn, int idx, Path* p) { paths[bn.id][idx] = p; } Path* path(bool_node& bn, int idx) { Path* p = paths[bn.id][idx]; if (p == NULL) { p = new Path(); setpath(bn, idx, p); } return p; } Path* path(bool_node* bn, int idx) { return path(*bn, idx); } virtual double dist(int nid) { ValueGrad* val = v(bdag[nid], 0); return val->getVal(); } virtual double dist(int nid, gsl_vector* grad) { ValueGrad* val = v(bdag[nid], 0); gsl_vector_memcpy(grad, val->getGrad()); return val->getVal(); } virtual void print() { /*for (int i = 0; i < bdag.size(); i++) { if (bdag[i]->type == bool_node::ASSERT) { DistanceGrad* dist = d(bdag[i]->mother); if (dist->set) { double gmag = gsl_blas_dnrm2(dist->grad); if (dist->dist < 0.1) { cout << bdag[i]->mother->lprint() << endl; cout << dist->printFull() << endl; } } } } return;*/ for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << " "; if (bdag[i]->getOtype() == OutType::FLOAT) { if (v(bdag[i], 0)->set) { cout << v(bdag[i], 0)->print() << endl; } else { cout << "UNSET" << endl; } } else { if (d(bdag[i], 0)->set) { cout << d(bdag[i], 0)->print() << endl; } else { cout << "UNSET" << endl; } } } } virtual void printFull() { for (int i = 0; i < bdag.size(); i++) { cout << bdag[i]->lprint() << endl; if (bdag[i]->getOtype() == OutType::FLOAT) { if (v(bdag[i],0)->set) { cout << v(bdag[i],0)->printFull() << endl; } else { cout << "UNSET" <<endl; } } else { if(d(bdag[i],0)->set) { cout << d(bdag[i],0)->printFull() << endl; } else { cout << "UNSET" << endl; } } if (bdag[i]->type == bool_node::PLUS) { cout << v(bdag[i]->mother(),0)->getVal() << " + " << v(bdag[i]->father(), 0)->getVal() << endl; } } } bool isFloat(bool_node& bn) { return (bn.getOtype() == OutType::FLOAT); } bool isFloat(bool_node* bn) { return (bn->getOtype() == OutType::FLOAT); } int getInputValue(bool_node& bn) { if (inputValues->hasValue(bn.id)) { int val = inputValues->getValue(bn.id); return val; } else { return DEFAULT_INP; } } int getInputValue(bool_node* bn) { return getInputValue(*bn); } void doUfun(UFUN_node& node, ValueGrad* mval, ValueGrad* val); void copyNodes(bool_node& node, bool_node* m); double merge(bool_node* n, gsl_vector* grad); void mergePaths(vector<tuple<double, vector<tuple<int, int, int>>, Path*>>& mergedPaths); void getMergeNodesBinop(bool_node* n); void getMergeNodesUnop(bool_node* n, bool_node* m); void getMergeNodesArracc(bool_node* node); void getMergeNodes(); void combineDistance(bool_node& node, int nodeid1, int idx1, int nodeid2, int idx2, double& dist, gsl_vector* dg_grad); void doPair(bool_node& node, int nodeid1, int idx1, int nodeid2, int idx2, double& val, gsl_vector* val_grad); void pairNodes(bool_node& node); void normalize(bool_node* n); };
{ "alphanum_fraction": 0.6181553575, "avg_line_length": 24.1626373626, "ext": "h", "hexsha": "edcd5a2df596100602b2c437d6e33e5c1547361c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": [ "X11" ], "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_licenses": [ "X11" ], "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_line_length": 120, "max_stars_count": 17, "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": [ "X11" ], "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/KLocalityAutoDiff.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "num_tokens": 3492, "size": 10994 }
#include <gsl/gsl_rng.h> struct ising { int Lx; // number of spins in x direction int Ly; // number of spins in y direction int N; // total number of spins int steps; // steps so far int **s; // the spins double J; // ferromagnetic coupling double T; // temperature double H; // magnetic field gsl_rng *r; // random number generator unsigned long seed; // rng seed double w[25][3]; // Boltzmann factors int **cluster; // spin cluster labels double addprobability; // probability to add like spin };
{ "alphanum_fraction": 0.4684210526, "avg_line_length": 36.1904761905, "ext": "h", "hexsha": "cffcd76af545d7e5a0e5bc7eced96e8ea16993aa", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "336a70c3cad51b666b6e11770d8e2252e5515bfd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "matthewignal/Phase-Transition-of-a-Ferromagnet", "max_forks_repo_path": "ising_datastructure.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "336a70c3cad51b666b6e11770d8e2252e5515bfd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "matthewignal/Phase-Transition-of-a-Ferromagnet", "max_issues_repo_path": "ising_datastructure.h", "max_line_length": 66, "max_stars_count": 1, "max_stars_repo_head_hexsha": "336a70c3cad51b666b6e11770d8e2252e5515bfd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "matthewignal/Phase-Transition-of-a-Ferromagnet", "max_stars_repo_path": "ising_datastructure.h", "max_stars_repo_stars_event_max_datetime": "2019-05-19T10:56:51.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-19T10:56:51.000Z", "num_tokens": 163, "size": 760 }
#ifndef _WAVELET_H_ #define _WAVELET_H_ #include "gsl/gsl_wavelet.h" //#include <gsl/gsl_wavelet2d.h> // N-to-M conversion helper functions template <typename T> T *** arrayto3D(T * data, size_t x, size_t y, size_t z); template <typename T> T ** arrayto2D(T * data, size_t x, size_t y); template <typename T> T * arrayto1D(T *** data, size_t x, size_t y, size_t z); template <typename T> T * arrayto1D(T ** data, size_t x, size_t y); // Helper functions to compute size of wavelet hierarchy at a level static int binary_logn (const size_t n); int binary_upto_logn (const size_t n); int binary_upto_value (const size_t n, const int log_n); // Debug output of discrete wavelet signal void gsl_wavelet_print (const gsl_wavelet * w); // Native stepping functions that apply signal to data template <typename T> static void dwt_step (const gsl_wavelet * w, T *a, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); template <typename T> static void dwt_step_proto(const gsl_wavelet * w, T *a, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); // 1D-support template <typename T> int wavelet_transform(const gsl_wavelet * w, T *&data, size_t stride, size_t n, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); // 2D-support template <typename T> int wavelet2d_transform(const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); template <typename T> int wavelet2d_nstransform(const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); // 3D-support versions of (GSL) wavelet transform template <typename T> int gsl_wavelet3d_transform (const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2,size_t size3, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); template <typename T> int gsl_wavelet3d_nstransform (const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2, size_t size3, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); template <typename T> int gsl_wavelet3d_nstransform (const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2, size_t size3, gsl_wavelet_direction dir, gsl_wavelet_workspace * work, int levels); template <typename T> int gsl_wavelet3d_nstransform_proto(const gsl_wavelet * w, T *data, size_t tda, size_t size1, size_t size2, size_t size3, gsl_wavelet_direction dir, gsl_wavelet_workspace * work); // Functions to compute dimensions for each coefficient block (quadrant) in a wavelet hierarchy int *** getCoeffDims (int dimx, int dimy, int dimz); int *** getCoeffDims (int dimx, int dimy); // Set/Extract functions used in conjunction with above to extract coefficient subregions template <typename T> T * getCutout3d(T * in, int * codims, int * dims); template <typename T> T * getCutout2d(T * in, int * codims, int * dims); template <typename T> void setCutout3d(T * in, T * cutout, int * codims, int * dims); template <typename T> void setCutout2d(T * in, T * cutout, int * codims, int * dims); template <typename T> int grow(int val, T *** data, size_t x, size_t y, size_t z); template <typename T> int shrink(int val, T *** data, size_t x, size_t y, size_t z); #endif #include "wavelet.inl"
{ "alphanum_fraction": 0.7596735187, "avg_line_length": 61.2592592593, "ext": "h", "hexsha": "ed243b69d9302818c3d44b3260f33a611f109b63", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-19T07:14:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-22T16:14:52.000Z", "max_forks_repo_head_hexsha": "ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd", "max_forks_repo_licenses": [ "Unlicense", "BSD-3-Clause" ], "max_forks_repo_name": "jpulidojr/VizAly-SNWPAC", "max_forks_repo_path": "include/wavelet.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense", "BSD-3-Clause" ], "max_issues_repo_name": "jpulidojr/VizAly-SNWPAC", "max_issues_repo_path": "include/wavelet.h", "max_line_length": 208, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd", "max_stars_repo_licenses": [ "Unlicense", "BSD-3-Clause" ], "max_stars_repo_name": "jpulidojr/VizAly-SNWPAC", "max_stars_repo_path": "include/wavelet.h", "max_stars_repo_stars_event_max_datetime": "2022-03-11T19:29:33.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-19T07:14:54.000Z", "num_tokens": 963, "size": 3308 }
/* * Monte Carlo */ #include <gsl/gsl_rng.h> double mc_pi(long m, gsl_rng *r); double mc_pi(long m, gsl_rng *r) { unsigned long seed = 1UL; double p[NP], mean, sd; int i; /* allocate random number generator */ r = gsl_rng_alloc (gsl_rng_taus2); /* seed the random number generator */ gsl_rng_set (r, seed); for (i = 0; i < NP; i++) { p[i] = gsl_rng_uniform (r); } gsl_rng_free (r); return 0; // for (n = 0; n < m; n++) { /* generate random coordinates */ // x = gsl_rng_uniform(r); // y = gsl_rng_uniform(r); /* count when the point lands in the circle */ // if ((x*x + y*y) <= 1.0) { // count += 1; // } // } // return(4.0 * ((double)count)/((double)m)); }
{ "alphanum_fraction": 0.5332446809, "avg_line_length": 16, "ext": "c", "hexsha": "03c0475834929ef00a050e7b6e53bba59d4d94c6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "matthewignal/fin2", "max_forks_repo_path": "mc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "matthewignal/fin2", "max_issues_repo_path": "mc.c", "max_line_length": 52, "max_stars_count": null, "max_stars_repo_head_hexsha": "4829666b4a2ec58625b6dc37a5d47501f8fbd059", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "matthewignal/fin2", "max_stars_repo_path": "mc.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 241, "size": 752 }
/* vector/gsl_vector_complex_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__ #define __GSL_VECTOR_COMPLEX_FLOAT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_float.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; float *data; gsl_block_complex_float *block; int owner; } gsl_vector_complex_float; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_view; typedef _gsl_vector_complex_float_view gsl_vector_complex_float_view; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_const_view; typedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view; /* Allocation */ GSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n); GSL_FUN gsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n); GSL_FUN gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_complex_float_free (gsl_vector_complex_float * v); /* Views */ GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_view_array (float *base, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_view_array_with_stride (float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array (const float *base, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array_with_stride (const float *base, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_subvector (gsl_vector_complex_float *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_float_view gsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base, size_t i, size_t n); GSL_FUN _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_float_view gsl_vector_complex_float_real (gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_view gsl_vector_complex_float_imag (gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_const_view gsl_vector_complex_float_const_real (const gsl_vector_complex_float *v); GSL_FUN _gsl_vector_float_const_view gsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v); /* Operations */ GSL_FUN void gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v); GSL_FUN void gsl_vector_complex_float_set_all (gsl_vector_complex_float * v, gsl_complex_float z); GSL_FUN int gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i); GSL_FUN int gsl_vector_complex_float_fread (FILE * stream, gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fwrite (FILE * stream, const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fscanf (FILE * stream, gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_fprintf (FILE * stream, const gsl_vector_complex_float * v, const char *format); GSL_FUN int gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src); GSL_FUN int gsl_vector_complex_float_reverse (gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w); GSL_FUN int gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j); GSL_FUN int gsl_vector_complex_float_equal (const gsl_vector_complex_float * u, const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_isnonneg (const gsl_vector_complex_float * v); GSL_FUN int gsl_vector_complex_float_add (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_sub (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_mul (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_div (gsl_vector_complex_float * a, const gsl_vector_complex_float * b); GSL_FUN int gsl_vector_complex_float_scale (gsl_vector_complex_float * a, const gsl_complex_float x); GSL_FUN int gsl_vector_complex_float_add_constant (gsl_vector_complex_float * a, const gsl_complex_float x); GSL_FUN int gsl_vector_complex_float_axpby (const gsl_complex_float alpha, const gsl_vector_complex_float * x, const gsl_complex_float beta, gsl_vector_complex_float * y); GSL_FUN INLINE_DECL gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z); GSL_FUN INLINE_DECL gsl_complex_float *gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i); GSL_FUN INLINE_DECL const gsl_complex_float *gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { gsl_complex_float zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_FLOAT_AT (v, i); } INLINE_FUN void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_FLOAT_AT (v, i) = z; } INLINE_FUN gsl_complex_float * gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } INLINE_FUN const gsl_complex_float * gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */
{ "alphanum_fraction": 0.6779980178, "avg_line_length": 38.3650190114, "ext": "h", "hexsha": "5341cfbfa551d6793dc49a0d1e41669606000467", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_complex_float.h", "max_line_length": 172, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_complex_float.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 2151, "size": 10090 }
//changes to version glm_popdyn_1.0_test2: //lookuptable for G(x)=exp(-0.5*DT*c*exp(x/deltaV)) instead of lambda and Plam #ifndef GLM #define GLM 0 #endif #ifndef GLM2 #define GLM2 2 #endif #ifndef GLIF #define GLIF 10 #endif #ifndef GLIF1 #define GLIF1 11 #endif #ifndef GLIF2 #define GLIF2 12 #endif #ifndef GLIF4 #define GLIF4 14 #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <complex.h> #include <fftw3.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "util.c" #define maxisi 2. #define PFIRE_MAX 0.99999 #define PFIRE_MIN 0.00001 double extime; unsigned int ntrial; struct PopParametersGLM{ double tref; double taum; double *taus1; //incoming synaptic time constants, decay time of 1st filter double *taus2; //incoming synaptic time constants, decay time of 2nd filter double *taur1; //incoming synaptic time constants, rise time of 1st filter double *taur2; //incoming synaptic time constants, rise time of 2nd filter double *a1; //relative weight of fast synaptic current double *a2; //relative weight of slow synaptic current double mu; double c; double deltaV; double delay; double vth; double u_reset; //reset potential for u in glif mode int N; //number of neurons in population double *J; //incoming synaptic weights double *Iext; //external input (in mV), i.e. Iext is actually R*I double *tau_theta; double *J_theta; //amplitudes of the N_theta exponential kernels in mV int N_theta; //number of exponentials for dynamic threshold //internal constants int K; int end; int indx; double Em; double Em2; double *E_theta; //Jtheta*exp(-t/tau_theta)}; double *E_theta2; //exp(-dt/tau_theta)}; double *gamma_QR; //deltaV*(1-exp(-gamma/deltaV))/N; gamma=sum_k Jtheta_k*exp(-t/tautheta_k) double *w1; // effective weight double *w2; double g; double g2; double dV; // resolution of voltage grid for lookup table of hazard/firing prob double Vmin; //min value of voltage grid double Vmax; //max value of voltage grid (this value is not included, i.e. max is Vmax-dv) double *Gtable; //lookup table for firing prob P=1-exp(-lam*DT) }; struct PopVariablesGLM{ double h; double *u; double *Xsyn1; //incoming synaptic currents (filtered with fast decay time, e.g. AMPA, GABA) double *Xsyn2; //incoming synaptic currents (filtered with slow decay time, e.g. NMDA) double *Isyn1; //total incoming synaptic current (sum of Xsyn1+Xsyn2 filtered with short rise-time) double *Isyn2; //total incoming synaptic current (sum of Xsyn1+Xsyn2 filtered with short rise-time) unsigned int *n; double *m0; double *theta; //threshold kernel double *g; //QR threshold variables double *v; double z; double x; double Gfree; double *G; }; double DT; double DTBIN; //////////////////////////////////////////////////////////////////////////////// double get_mean(double *x,int n); void print_matrix1(int N,int M, double A[][M]); void print_matrix2(double **A,int N,int M); void print_matrix3(int N,int M, double *A[N]); void print_pop_parameters(struct PopParametersGLM p[], int Npop); unsigned long int random_seed(); //////////////////////////////////////////////////////////////////////////////// void init_synaptic_filters(double **Es1, double **Es2, double **Er1, double **Er2, struct PopParametersGLM p[], int Npop) { int i,j; for (i=0;i<Npop;i++) for (j=0;j<Npop;j++) { if (p[i].taur1[j]>0) Er1[i][j]=exp(-DT/p[i].taur1[j]); else Er1[i][j]=0; if (p[i].taus1[j]>0) Es1[i][j]=exp(-DT/p[i].taus1[j]); else Es1[i][j]=0; if (p[i].taur2[j]>0) Er2[i][j]=exp(-DT/p[i].taur2[j]); else Er2[i][j]=0; if (p[i].taus2[j]>0) Es2[i][j]=exp(-DT/p[i].taus2[j]); else Es2[i][j]=0; } } void get_inputs(double *input, int k,double **Es1,double **Es2,double **Er1,double **Er2, struct PopParametersGLM p[], struct PopVariablesGLM pop[],int Npop) { int i,j,ndelay; double A[Npop]; for (j=0;j<Npop;j++) { ndelay=p[j].delay/DT; // A[j]= pop[j].n[(p[j].end-1-ndelay+p[j].K)%p[j].K] / (p[j].N * DT); A[j]= pop[j].n[(p[j].end-ndelay+p[j].K)%p[j].K] / (p[j].N * DT); } for (i=0;i<Npop;i++) { //base line input input[i]=p[i].mu; //external input, assumed to be slow compared to DT if (p[i].Iext != NULL) input[i] += p[i].Iext[k] * (1-p[i].Em); //add external input if provided //synaptic input for (j=0;j<Npop;j++) { if (p[i].taur1[j]>0) { printf("Warning: rise time not correctly implemented\n"); input[i]+=p[i].w1[j]*pop[i].Isyn1[j]; if (p[i].taus1[j] > 0) { pop[i].Isyn1[j] = pop[i].Xsyn1[j] + (pop[i].Isyn1[j] - pop[i].Xsyn1[j]) * Er1[i][j]; pop[i].Xsyn1[j] = A[j] + (pop[i].Xsyn1[j] - A[j]) * Es1[i][j]; } else pop[i].Isyn1[j] = A[j] + (pop[i].Isyn1[j] - A[j]) * Es1[i][j]; } else //zero-rise time if (p[i].taus1[j] > 0) { input[i] += p[i].w1[j] * (A[j] + (p[i].taus1[j] * (pop[i].Xsyn1[j] - A[j]) * Es1[i][j] - (pop[i].Xsyn1[j] * p[i].taus1[j] - A[j] * p[i].taum) * p[i].Em) / (p[i].taus1[j] - p[i].taum)); pop[i].Xsyn1[j] = A[j] + (pop[i].Xsyn1[j] - A[j]) * Es1[i][j]; } else //delta current { input[i]+=p[i].w1[j]*A[j] * (1 - p[i].Em); } //same for 2nd filter if (p[i].taur2[j]>0) { input[i]+=p[i].w2[j]*pop[i].Isyn2[j]; if (p[i].taus2[j] > 0) { pop[i].Isyn2[j] = pop[i].Xsyn2[j] + (pop[i].Isyn2[j] - pop[i].Xsyn2[j]) * Er2[i][j]; pop[i].Xsyn2[j] = A[j] + (pop[i].Xsyn2[j] - A[j]) * Es2[i][j]; } else pop[i].Isyn2[j] = A[j] + (pop[i].Isyn2[j] - A[j]) * Es2[i][j]; } else //zero-rise time if (p[i].taus2[j] > 0) { input[i]+=p[i].w2[j]*pop[i].Xsyn2[j]; pop[i].Xsyn2[j] = A[j] + (pop[i].Xsyn2[j] - A[j]) * Es2[i][j]; } else //delta current input[i]+=p[i].w2[j]*A[j]; } } } double cond_rate(double x,struct PopParametersGLM *p) { if (p->deltaV > 0) return p->c * exp(x / p->deltaV); else //p->D==0, no noise { if (x < 0) return 0; else return 1./DT; } } static double get_Plam(double V, struct PopParametersGLM *p, double *G_old) { if (V<p->Vmax) { if (V>=p->Vmin) { //int x=(int)((V - p->Vmin) / p->dV); double G = p->Gtable[(int)((V - p->Vmin) / p->dV)]; double Plam = 1 - *G_old * G; //printf("V=%g x=%d lam=%g\n",V,x,lam); *G_old = G; return Plam; } else { *G_old=1; return 0.; } } else { *G_old = 0; return 1.; } } void update(struct PopVariablesGLM *pop, double *nmean, double input,gsl_rng *rng,struct PopParametersGLM *p, int mode) { int i,k,r; int kref=(int)(p->tref/DT); double W=0, X=0, Y=0, Z=0, theta=p->vth; int end=p->end, K=p->K; double threshold; // first, determine non-refractory spiking prob. for (r=0;r < p->N_theta; r++) { pop->g[r] = pop->g[r]*p->E_theta2[r] + (1 - p->E_theta2[r]) * pop->n[end]/(p->N * DT); theta += p->E_theta[r] * pop->g[r]; } double Pfree; pop->h = input + (pop->h - p->mu) * p->Em; Pfree=get_Plam(pop->h-theta,p,&(pop->Gfree)); for (k=0; k<K; k++) X += pop->m0[k]; double ztot,Plam,PLAM, mm; theta -= pop->n[end] * p->gamma_QR[0];//substracts effect of n[end] above, added again in 1st loop below, but ensures that threshold theta(t+DT|k=end) is correct switch(mode) { case GLM: for (k=end;k<=end-kref+K;k++) { i=k%K; threshold = pop->theta[k-end] + theta; theta += pop->n[i] * p->gamma_QR[k-end]; Plam=get_Plam(pop->h-threshold,p,pop->G+i); Z += pop->v[i]; mm = Plam * pop->m0[i]; Y += Plam * pop->v[i]; W += mm; pop->v[i] = (1-Plam)*(1-Plam)*pop->v[i] + mm; pop->m0[i] -= mm; } break; case GLIF: { for (k=end;k<=end-kref+K;k++) { i=k%K; threshold = pop->theta[k-end] + theta; theta += pop->n[i] * p->gamma_QR[k-end]; pop->u[i] = input + (pop->u[i] - p->mu) * p->Em;//GLIF Plam=get_Plam(pop->u[i]-threshold,p,pop->G+i); Z += pop->v[i]; mm = Plam * pop->m0[i]; Y += Plam * pop->v[i]; W += mm; pop->v[i] = (1-Plam)*(1-Plam)*pop->v[i] + mm; pop->m0[i] -= mm; } } pop->u[end] = p->u_reset;//GLIF break; } ztot = Z + pop->z; if (ztot>0) PLAM=(Y+Pfree*pop->z)/ztot; else PLAM=0; // printf("W=%g Z=%g z=%g Y=%g y=%g\n",W, Z,pop->z,Y,Pfree*pop->z); *nmean = W + Pfree * pop->x + PLAM * (p->N - X - pop->x); pop->n[end] = gsl_ran_binomial(rng, *nmean/p->N, p->N); pop->z=(1-Pfree)*(1-Pfree)*pop->z+Pfree*pop->x+pop->v[end]; pop->x=(1-Pfree)*pop->x+pop->m0[end]; pop->m0[end] = pop->n[end]; pop->v[end] = 0.; pop->G[end] = 1.; } void simulate(int Nbin,double **A,double **rate,struct PopVariablesGLM pop[],gsl_rng *rng,struct PopParametersGLM p[],int Npop, int mode, int dispprog) { double input[Npop],normfact[Npop], nmean[Npop], nmean_bin[Npop]; int n_bin[Npop]; int L,i; int l=0,k=0; L=(int)(DTBIN/DT+0.5); for (i=0;i<Npop;i++) { n_bin[i]=0; nmean_bin[i]=0; normfact[i]=1./(L*DT*p[i].N); } double **Es1=dmatrix(Npop,Npop); double **Es2=dmatrix(Npop,Npop); double **Er1=dmatrix(Npop,Npop); double **Er2=dmatrix(Npop,Npop); init_synaptic_filters(Es1,Es2,Er1,Er2,p,Npop); int dispcount=(int)(Nbin/100); // clock_t start=clock(); while (k<Nbin) { // printf("Nbin=%d, k=%d l=%d\n",Nbin,k,l); get_inputs(input,k,Es1,Es2,Er1,Er2,p,pop,Npop); for (i=0;i<Npop;i++) { update(pop+i,nmean+i,input[i],rng,p+i,mode); n_bin[i]+=pop[i].n[p[i].end]; nmean_bin[i]+=nmean[i]; } l++; // printf("nmeanbin=%g\n",nmean_bin[0]); // printf("\n"); if (l>=L) { for (i=0;i<Npop;i++) { A[i][k] = n_bin[i] * normfact[i]; rate[i][k] = nmean_bin[i] * normfact[i]; //if (i==0) printf("k=%d rate=%g\n",k,rate[i][k]); // aa[i][k]=a[i]; n_bin[i]=0; nmean_bin[i]=0; } l=0; k++; } for (i=0;i<Npop;i++) p[i].end=(p[i].end + 1) % p[i].K; if (dispprog) if ((k+1)%dispcount==0) { printf("%d%% \r",(int)((k+1) * 100. / Nbin)); fflush(stdout); } } // printf("Execution time of mesoscopic sim: %g seconds, K=%d\n",(double)(clock()-start)/CLOCKS_PER_SEC,p[0].K); free_dmatrix(Es1); free_dmatrix(Es2); free_dmatrix(Er1); free_dmatrix(Er2); } double threshold_kernel(double t, struct PopParametersGLM *p) { double theta=0; int r; for (r=0; r<p->N_theta;r++) if (t>=0) theta += p->J_theta[r] / p->tau_theta[r] * exp(-t / p->tau_theta[r]); return theta; } void init_glm(struct PopParametersGLM p[],struct PopVariablesGLM pop[],int Npop, gsl_rng *rng, int mode) //memory allocation and initialization of variables, { int i,j,k,r, K; for (i=0;i<Npop;i++) { K=p[i].K; // printf("i=%d K=%d\n",i,K); pop[i].n=uivector(K); pop[i].m0=dvector(K); pop[i].v=dvector(K); if (mode>=GLIF) pop[i].u=dvector(K); else pop[i].u=NULL; pop[i].Isyn1=dvector(Npop); pop[i].Isyn2=dvector(Npop); pop[i].Xsyn1=dvector(Npop); pop[i].Xsyn2=dvector(Npop); p[i].Em= exp(-DT / p[i].taum); p[i].Em2= exp(-0.5*DT / p[i].taum); p[i].end = 0; pop[i].theta=dvector(K); p[i].gamma_QR=dvector(K); pop[i].G=dvector(K); for (k=0;k<K;k++) { /* if (k<K-1) */ /* { */ /* pop[i].m0[k]=(double)(p[i].N)/(K-1); //normalization (the K-1 element is set zero below) */ /* pop[i].n[k]=(int)(pop[i].m0[k]+1); //initializing with spike count corresponding to zero hazard */ /* pop[i].n[k]=(int)(100*DT*p[i].N+1); //initializing with spike count corresponding to 100 Hz */ /* pop[i].m0[k]=exp(-(K-k-1)*DT*100)*pop[i].n[k]; */ /* n+=pop[i].m0[k]; */ //if (i==0) printf("m0=%g n=%d\n", pop[i].m0[k], pop[i].n[k]); /* } */ pop[i].m0[k]=0; pop[i].n[k]=0; pop[i].v[k]=0; if (mode>=GLIF) pop[i].u[k]=p[i].vth-20*gsl_rng_uniform(rng); pop[i].theta[k]=threshold_kernel( (K-k-1) * DT, p+i);//shifted by DT to get filter at theta(s+DT) p[i].gamma_QR[k] = p[i].deltaV * (1 - exp(-pop[i].theta[k] / p[i].deltaV)) / p[i].N; // if (i==0) printf("i=%d k=%d gamma_QR=%g\n",i,k,p[i].gamma_QR[k]); pop[i].G[k]=1.; } pop[i].Gfree=1.; pop[i].n[K-1]=p[i].N; pop[i].m0[K-1]=p[i].N; pop[i].z=0.; pop[i].x=0.; //pop[i].x=(p[i].N - n) * DT; /* printf("i=%d n=%g x/dt=%g\n",i,n,pop[i].x/DT); */ for (j=0;j<Npop;j++) pop[i].Isyn1[j]=0; for (j=0;j<Npop;j++) pop[i].Isyn2[j]=0; for (j=0;j<Npop;j++) pop[i].Xsyn1[j]=0; for (j=0;j<Npop;j++) pop[i].Xsyn2[j]=0; pop[i].h=p[i].mu; //pre-calculating constant J_k*exp(-tau_rel/tau_k) pop[i].g=dvector(p[i].N_theta); for (r=0; r < p[i].N_theta; r++) pop[i].g[r] = pop[i].n[0]/(p[i].N * DT)/p[i].tau_theta[r]; p[i].E_theta=dvector(p[i].N_theta); p[i].E_theta2=dvector(p[i].N_theta); // printf("E_theta= "); for (r=0; r < p[i].N_theta; r++) { p[i].E_theta[r] = p[i].J_theta[r] * exp(- K * DT / p[i].tau_theta[r]); p[i].E_theta2[r] = exp(- DT / p[i].tau_theta[r]); // printf("%g tautheta=%g",p[i].E_theta[r],p[i].tau_theta[r]); } // printf("\n"); //pre-computing firing probability as lookup table p[i].dV=p[i].deltaV/100; p[i].Vmin = p[i].deltaV * log(-log(1-PFIRE_MIN)/DT / p[i].c); p[i].Vmax = p[i].deltaV * log(-log(1-PFIRE_MAX)/DT / p[i].c); int L=(p[i].Vmax - p[i].Vmin)/p[i].dV; // printf("Lookup tbl (popul %d): Use L=%d, Vmin=%g Vmax=%g dV=%g\n",i+1,L,p[i].Vmin,p[i].Vmax,p[i].dV); p[i].Gtable=dvector(L); for (k=0;k<L;k++) { double V=p[i].Vmin + k*p[i].dV; p[i].Gtable[k]= exp(-0.5 * p[i].c * exp(V/p[i].deltaV) * DT); } } } void get_history_size(struct PopParametersGLM p[],int Npop) { int i; double tmax=20.;//sec for (i=0;i<Npop;i++) { int k=tmax/DT; int kmin=5*p[i].taum/DT; while ((threshold_kernel(k * DT, p+i) / p[i].deltaV < 0.1) && (k>kmin)) k--; // printf("K=%d\n",k); if (k*DT<=p[i].delay) k=(int)(p[i].delay/DT)+1; // printf("K=%d\n",k); if (k*DT<=p[i].tref) k=(int)(p[i].tref/DT)+1; p[i].K=k; // p[i].K=20000; printf("Use K=%d bins for history of population %d (T=%g sec)\n",p[i].K,i+1,p[i].K*DT); } } void free_pop(struct PopVariablesGLM pop[],struct PopParametersGLM p[],int Npop, int mode) { int i; for (i=0;i<Npop;i++) { free_uivector(pop[i].n); free_dvector(pop[i].m0); free_dvector(pop[i].v); if (mode>=GLIF) free_dvector(pop[i].u); free_dvector(pop[i].Isyn1); free_dvector(pop[i].Isyn2); free_dvector(pop[i].Xsyn1); free_dvector(pop[i].Xsyn2); free_dvector(pop[i].g); free_dvector(pop[i].theta); free_dvector(p[i].E_theta); free_dvector(p[i].E_theta2); free_dvector(p[i].gamma_QR); free_dvector(pop[i].G); free_dvector(p[i].Gtable); } } void get_psd_pop(double **SA,int Nbin,int Ntrials,struct PopParametersGLM neuron[],int Npop, int mode) { gsl_rng *rng=gsl_rng_alloc(gsl_rng_taus2); unsigned long int seed; seed = random_seed(); gsl_rng_set(rng,seed); // gsl_rng_set (rng,(long)time(NULL)); get_history_size(neuron,Npop); int i,j,n; struct PopVariablesGLM pop[Npop]; init_glm(neuron,pop,Npop, rng, mode); double sum=0; for (i=0;i<neuron[0].K;i++) { sum+=pop[0].m0[i]; } double **A, **rate; A=dmatrix(Npop,Nbin); rate=dmatrix(Npop,Nbin); simulate(Nbin,A,rate,pop,rng,neuron,Npop, mode, 0); double complex *AF[Npop]; for (j=0;j<Npop;j++) { AF[j]=(double complex *)malloc(sizeof(double complex)*Nbin); SA[j]=(double *)malloc(sizeof(double)*(Nbin/2));//psd of A for (i=0;i<Nbin/2;i++) SA[j][i]=0; } fftw_plan plan=fftw_plan_dft_r2c_1d(Nbin,A[0],AF[0],FFTW_ESTIMATE); for (n=0;n<Ntrials;n++) { // if (n%10==9) { printf("trial %d ",n+1); for (j=0;j<Npop;j++) printf("%g ",get_mean(A[j],Nbin)); printf("\r"); fflush(stdout); } simulate(Nbin,A,rate,pop,rng,neuron,Npop,mode, 0); for (j=0;j<Npop;j++) { fftw_execute_dft_r2c(plan,A[j],AF[j]); for (i=1;i<Nbin/2+1;i++) SA[j][i-1]+=creal(AF[j][i]*conj(AF[j][i]))*DTBIN/Nbin; } } printf("trial %d ",n); for (j=0;j<Npop;j++) printf("%g ",get_mean(A[j],Nbin)); printf("\n"); for (j=0;j<Npop;j++) for (i=0;i<Nbin/2;i++) SA[j][i]/=Ntrials; gsl_rng_free (rng); free_pop(pop,neuron,Npop, mode); free_dmatrix(A); free_dmatrix(rate); for (j=0;j<Npop;j++) free(AF[j]); fftw_destroy_plan(plan); } void get_trajectory(double **A,double **rate,int Nbin, int Npop,struct PopParametersGLM neuron[],double dt, double dtbin, int mode, int seed) { gsl_rng *rng=gsl_rng_alloc(gsl_rng_taus2); gsl_rng_set (rng,(long)seed); /* printf("seed=%d\n",seed); */ /* printf("rndnr=%g\n",gsl_rng_uniform(rng)); */ DT=dt; DTBIN=dtbin; get_history_size(neuron,Npop); struct PopVariablesGLM pop[Npop]; init_glm(neuron,pop,Npop, rng, mode); clock_t start=clock(); simulate(Nbin,A,rate,pop,rng,neuron,Npop, mode, 1); double sim_t=(double)(clock()-start)/CLOCKS_PER_SEC; printf("Execution time of mesoscopic dynamics: %g seconds, %g s per biosecond\n",sim_t,sim_t/Nbin/DTBIN); int i; //for (i=0;i<20;i++) printf("rate=%g\n",rate[0][i]); for (i=0;i<Npop;i++) printf("mean rate of population %d: %g \n",i+1,get_mean(rate[i],Nbin)); // for (i=0;i<Nbin;i++) printf("%g\n",rate[0][i]); gsl_rng_free (rng); free_pop(pop,neuron,Npop, mode); } void init_population(struct PopParametersGLM p[], int Npop,double tref[], double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double **signal, int N_theta[], double J_ref[], double *J_theta[], double *tau_theta[], double sigma[]) { int k,l; for (k=0;k<Npop;k++) { p[k].indx=k; p[k].tref=tref[k]; p[k].taum=taum[k]; p[k].mu=mu[k]; p[k].c=c[k]; p[k].deltaV=deltaV[k]; p[k].delay=delay[k]; p[k].vth=vth[k]; p[k].u_reset = vreset[k]; p[k].N=N[k]; p[k].g=sqrt(1-exp(-2*DT/p[k].taum)) * sigma[k]; p[k].g2=sqrt(1-exp(-DT/p[k].taum)) * sigma[k]; p[k].Iext=signal[k]; p[k].taus1=taus1[k]; p[k].taus2=taus2[k]; p[k].taur1=taur1[k]; p[k].taur2=taur2[k]; if (J_ref[k]==0) p[k].N_theta=N_theta[k]; else p[k].N_theta=N_theta[k]+1; //putting exponential refractory kernel into threshold (theta kernel) p[k].J_theta=dvector(p[k].N_theta); p[k].tau_theta=dvector(p[k].N_theta); for (l=0;l<N_theta[k];l++) { p[k].J_theta[l]=J_theta[k][l]; p[k].tau_theta[l]=tau_theta[k][l]; // printf("k=%d l=%d J=%g tau=%g\n",k,l,J_theta[k][l],tau_theta[k][l]); } if (J_ref[k]!=0.) { p[k].J_theta[N_theta[k]] = J_ref[k]*taum[k]; p[k].tau_theta[N_theta[k]] = taum[k]; } //effective synaptic weights p[k].w1=dvector(Npop); p[k].w2=dvector(Npop); for (l=0;l<Npop;l++) { p[k].w1[l] = J[k][l] * p_conn[k][l] * N[l] * taum[k] * a1[k][l] / (a1[k][l]+a2[k][l]); p[k].w2[l] = J[k][l] * p_conn[k][l] * N[l] * taum[k] * a2[k][l] / (a1[k][l]+a2[k][l]); //printf("k=%d l=%d a1=%g w1=%g\n",k,l,a1[k][l],p[k].w1[l]); } } } void clean_population(struct PopParametersGLM p[], int Npop) { int k; for (k=0;k<Npop;k++) free_dvector(p[k].w1); for (k=0;k<Npop;k++) free_dvector(p[k].w2); for (k=0;k<Npop;k++) free_dvector(p[k].J_theta); for (k=0;k<Npop;k++) free_dvector(p[k].tau_theta); } void get_psd_with_fullparameterlist(double **SA, int Nbin, int Ntrials, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], int N_theta[], double Jref[], double *J_theta[], double *tau_theta[], double sigma[], double dt,double dtbin, int mode) { double **signal=dmatrix(Npop,1); int i; for (i=0;i<Npop;i++) signal[i]=NULL; DT=dt; DTBIN=dtbin; struct PopParametersGLM p[Npop]; init_population(p, Npop, tref, taum, taus1, taus2, taur1, taur2, a1, a2, mu, c, deltaV, delay, vth, vreset, N, J, p_conn, signal, N_theta, Jref, J_theta, tau_theta, sigma); get_psd_pop(SA, Nbin, Ntrials, p, Npop, mode); free_dmatrix(signal); clean_population(p,Npop); } void get_psd_with_2D_arrays(int Nf, double SA[][Nf], int Ntrials, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], int N_theta[], double Jref[], double J_theta[], double tau_theta[], double sigma[], double dt,double dtbin, int mode) { //convert 2D array to double** double *SA_tmp[Npop], *J_theta_ptr[Npop], *tau_theta_ptr[Npop]; int i,j; int Nbin=2*Nf; int indx=0; for (i=0;i<Npop;i++) { J_theta_ptr[i]=&(J_theta[indx]); tau_theta_ptr[i]=&(tau_theta[indx]); indx+=N_theta[i]; /* if (N_theta[i]>0) */ /* { */ /* J_theta_ptr[i]=&(J_theta[indx]); */ /* tau_theta_ptr[i]=&(tau_theta[indx]); */ /* indx+=N_theta[i]; */ /* } */ /* else */ /* { */ /* J_theta_ptr[i]=NULL; */ /* tau_theta_ptr[i]=NULL; */ /* } */ } get_psd_with_fullparameterlist(SA_tmp, Nbin, Ntrials, Npop, tref, taum, taus1, taus2, taur1, taur2, a1, a2, mu, c, deltaV, delay, vth, vreset, N, J, p_conn, N_theta, Jref, J_theta_ptr, tau_theta_ptr, sigma, dt, dtbin, mode); for (j=0;j<Npop;j++) for (i=0;i<Nf;i++) SA[j][i]=SA_tmp[j][i]; for (j=0;j<Npop;j++) free(SA_tmp[j]); } void get_trajectory_with_fullparameterlist(double **A, double **rate, int Nbin, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double **signal, int N_theta[], double Jref[], double *J_theta[], double *tau_theta[], double sigma[], double dt,double dtbin, int mode, int seed) { DT=dt; DTBIN=dtbin; struct PopParametersGLM p[Npop]; init_population(p, Npop, tref, taum, taus1, taus2, taur1, taur2, a1, a2, mu, c, deltaV, delay, vth, vreset, N, J, p_conn, signal, N_theta, Jref, J_theta, tau_theta, sigma); // print_pop_parameters(p,Npop); get_trajectory(A, rate, Nbin, Npop, p, dt, dtbin, mode, seed); clean_population(p,Npop); } void get_trajectory_with_2D_arrays(int Nbin, double A[][Nbin], double rate[][Nbin], int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double s[][Nbin], int N_theta[], double Jref[], double J_theta[], double tau_theta[], double sigma[], double dt,double dtbin, int mode, int seed) { //convert 2D array to double** double *rate_ptr[Npop],*AA[Npop],*signal[Npop], *J_theta_ptr[Npop], *tau_theta_ptr[Npop]; int i; for (i=0;i<Npop;i++) AA[i]=A[i]; for (i=0;i<Npop;i++) rate_ptr[i]=rate[i]; for (i=0;i<Npop;i++) signal[i]=s[i]; int indx=0; for (i=0;i<Npop;i++) { if (N_theta[i]>0) { J_theta_ptr[i]=&(J_theta[indx]); tau_theta_ptr[i]=&(tau_theta[indx]); indx+=N_theta[i]; } else { J_theta_ptr[i]=NULL; tau_theta_ptr[i]=NULL; } } get_trajectory_with_fullparameterlist(AA, rate_ptr, Nbin, Npop, tref, taum, taus1, taus2, taur1, taur2, a1, a2, mu, c, deltaV, delay, vth, vreset, N, J, p_conn, signal, N_theta, Jref, J_theta_ptr, tau_theta_ptr, sigma, dt, dtbin, mode, seed); } //=================================================================== // SRM Model //=================================================================== void print_pop_parameters(struct PopParametersGLM p[], int Npop) { int k,l; printf("\n"); for (k=0;k<Npop;k++) { printf("POPULATION %d\n",k+1); printf("tref=%g\n",p[k].tref); printf("taum=%g\n",p[k].taum); printf("mu=%g\n",p[k].mu); printf("c=%g\n",p[k].c); printf("DeltaV=%g\n",p[k].deltaV); printf("delay=%g\n",p[k].delay); printf("vth=%g\n",p[k].vth); printf("vreset=%g\n",p[k].u_reset); printf("N=%d\n",p[k].N); printf("Ntheta=%d\n",p[k].N_theta); for (l=0;l<p[k].N_theta;l++) { printf("Jtheta=%g\n",p[k].J_theta[l]); printf("tautheta=%g\n",p[k].tau_theta[l]); } for (l=0;l<Npop;l++) { printf("pop%d to pop%d:\n",l+1,k+1); printf(" w1=%g\n",p[k].w1[l]); printf(" w2=%g\n",p[k].w2[l]); printf(" taus1=%g taur1=%g\n",p[k].taus1[l],p[k].taur1[l]); printf(" taus2=%g taur2=%g\n",p[k].taus2[l],p[k].taur2[l]); } printf("\n"); } printf("DT=%g DTBIN=%g\n",DT,DTBIN); } double get_mean(double *x,int n) { int i; double m=0; if (n>200) //discard initial transient { for (i=200;i<n;i++) m+=x[i]; return m/(n-200); } else { for (i=0;i<n;i++) m+=x[i]; return m/n; } } void print_matrix1(int N,int M, double A[][M]) { int i,j; for (i=0;i<N;i++) { for (j=0;j<M;j++) printf("%g ",A[i][j]); printf("\n"); } } void print_matrix2(double **A,int N,int M) { int i,j; for (i=0;i<N;i++) { for (j=0;j<M;j++) printf("%g ",A[i][j]); printf("\n"); } } void print_matrix3(int N,int M, double *A[N]) { int i,j; for (i=0;i<N;i++) { for (j=0;j<M;j++) printf("%g ",A[i][j]); printf("\n"); } } /* unsigned long int random_seed() */ /* { */ /* unsigned int seed; */ /* FILE *devrandom; */ /* if ((devrandom = fopen("/dev/random","r")) == NULL) { */ /* fprintf(stderr,"Cannot open /dev/random, setting seed to 0\n"); */ /* seed = 0; */ /* } else { */ /* fread(&seed,sizeof(seed),1,devrandom); */ /* if(verbose == D_SEED) printf("Got seed %u from /dev/random\n",seed); */ /* fclose(devrandom); */ /* } */ /* return(seed); */ /* } */ #include <sys/time.h> unsigned long int random_seed() { unsigned int seed; struct timeval tv; FILE *devrandom; if ((devrandom = fopen("/dev/urandom","r")) == NULL) { gettimeofday(&tv,0); seed = tv.tv_sec + tv.tv_usec; } else { fread(&seed,sizeof(seed),1,devrandom); fclose(devrandom); } return(seed); }
{ "alphanum_fraction": 0.5577619945, "avg_line_length": 25.5755329008, "ext": "c", "hexsha": "8fc5e76b51eaef5169ef2a5429282c448a0a25de", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dekamps/miind", "max_forks_repo_path": "libs/EPFLLib/orig.c", "max_issues_count": 41, "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dekamps/miind", "max_issues_repo_path": "libs/EPFLLib/orig.c", "max_line_length": 533, "max_stars_count": 13, "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dekamps/miind", "max_stars_repo_path": "libs/EPFLLib/orig.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "num_tokens": 9926, "size": 27596 }
#pragma once #include "mexObjectiveFunction.h" #include <nlopt.h> #include <mex.h> struct mexConstraintFunction { static double con_fun(unsigned n, const double *x, double *gradient, void *d_); static void vcon_fun(unsigned m, double *result, unsigned n, const double* x, double* grad, void* f_data); bool isvector; nlopt_func fun; // (unsigned n, const double *x, double *fc, void *func_data) nlopt_mfunc mfun; // (unsigned m, double *result, unsigned n, const double *x, double *fc, void *func_data) mxArray *prhs[2]; // feval mexMatlabCall input arguments for objective function evaluation nlopt_opt &opt; mxArray *&lasterror; // mexObjectiveFunction's to store trapped MException bool &stop; // mexObjectiveFunction's to flag if user issued a stop mexConstraintFunction(mxArray * mxFun, mexObjectiveFunction &data); ~mexConstraintFunction(); private: double evalFun(unsigned n, const double *x, double *gradient); void evalVecFun(unsigned m, unsigned n, const double* x, double *c, double* Cgrad); bool call_matlab_feval_with_trap(int nlhs, mxArray *plhs[], const int n, const double *x); };
{ "alphanum_fraction": 0.7162393162, "avg_line_length": 39, "ext": "h", "hexsha": "12772a0aaf5accb415bc75b833471c94e79dbec2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:23:20.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-23T09:52:50.000Z", "max_forks_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hokiedsp/matlab-nlopt", "max_forks_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_issues_repo_issues_event_max_datetime": "2020-09-25T01:13:12.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-22T03:36:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hokiedsp/matlab-nlopt", "max_issues_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_line_length": 109, "max_stars_count": 3, "max_stars_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hokiedsp/matlab-nlopt", "max_stars_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_stars_repo_stars_event_max_datetime": "2021-08-02T05:57:14.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-30T06:35:32.000Z", "num_tokens": 311, "size": 1170 }
#ifndef __INTERPOLATOR_H__ #define __INTERPOLATOR_H__ #include <vector> #include <gsl/gsl_math.h> #include <gsl/gsl_spline.h> namespace RHEHpt{ class Interpolator { public: Interpolator (unsigned choice = 0); virtual ~Interpolator (); double operator()(unsigned order, double xp) const; void set_choice(unsigned choice){ _choice = choice; } private: unsigned _choice; gsl_interp_accel* _gsl_acc; /* matrix of gsl interpolators one row per _choice and one column per order */ std::vector < std::vector < gsl_spline *> > _interpolators; }; } /* close RHEHpt namespace* */ #endif /* __INTERPOLATOR_H__ */
{ "alphanum_fraction": 0.7129485179, "avg_line_length": 18.8529411765, "ext": "h", "hexsha": "29b5e507dd38dcc7662220d3a905309b7d1e08e0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f320d8f4e2ef27af19cf62bded85afce8e0de7a7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gvita/RHEHpt", "max_forks_repo_path": "src/interpolator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f320d8f4e2ef27af19cf62bded85afce8e0de7a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gvita/RHEHpt", "max_issues_repo_path": "src/interpolator.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "f320d8f4e2ef27af19cf62bded85afce8e0de7a7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gvita/RHEHpt", "max_stars_repo_path": "src/interpolator.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 171, "size": 641 }
#include <petsc.h> #include <petscmath.h> #include "compressibleFlow.h" #include "mesh.h" #include "petscdmplex.h" #include "petscts.h" typedef struct { PetscInt dim; PetscReal rc; PetscReal xc; PetscReal yc; PetscReal L; PetscReal Tinf; PetscReal rhoInf; PetscReal Mac; PetscReal MaxInf; PetscReal MayInf; PetscReal Rgas; PetscReal gamma; } Constants; typedef struct { Constants constants; FlowData flowData; } ProblemSetup; static PetscLogStage monitorStage; static PetscErrorCode EulerExact(PetscInt dim, PetscReal time, const PetscReal xyz[], PetscInt Nf, PetscScalar *node, void *ctx) { PetscFunctionBeginUser; Constants *constants = (Constants *)ctx; // define the speed of sound and other variables in the infinity PetscReal aInf = PetscSqrtReal(constants->gamma*constants->Rgas*constants->Tinf); PetscReal pInf = constants->rhoInf*constants->Rgas*constants->Tinf; PetscReal uInf = constants->MaxInf*aInf; PetscReal vInf = constants->MayInf*aInf; // compute the values for the vortex PetscReal Tvort = constants->Tinf/(1.0 + 0.5*(constants->gamma - 1.0)*constants->Mac*constants->Mac); PetscReal aVort = PetscSqrtReal(constants->gamma*constants->Rgas*Tvort); // compute the values at each location based upon the time and the var field velocity PetscReal distTraveledX = time*uInf; PetscReal distTraveledY = time*vInf; // compute the updated center PetscReal xc = constants->xc + distTraveledX; PetscReal yc = constants->yc + distTraveledY; while(xc > constants->L*2){ xc -= constants->L*2; } while(yc > constants->L){ yc -= constants->L; } PetscReal x = xyz[0]; PetscReal y = xyz[1]; PetscReal xStar = (x- xc)/constants->rc; PetscReal yStar = (y - yc)/constants->rc; PetscReal rStar = PetscSqrtReal(PetscSqr((x - xc))+ PetscSqr((y - yc)))/constants->rc; PetscReal u = uInf - constants->Mac*aVort*yStar* PetscExpReal(0.5*(1.0 - PetscSqr(rStar))); PetscReal v = vInf + constants->Mac*aVort*xStar* PetscExpReal(0.5*(1.0 - PetscSqr(rStar))); PetscReal machTerm = 0.5*(constants->gamma-1.0)*PetscSqr(constants->Mac); PetscReal T = constants->Tinf*(1.0 - machTerm/(1+machTerm)*PetscSqr(rStar)*PetscExpReal(1-PetscSqr(rStar)) ); PetscReal p = pInf* PetscPowReal(T/constants->Tinf, constants->gamma/(constants->gamma - 1.0)); PetscReal rho = p/constants->Rgas/T; PetscReal e = p/((constants->gamma - 1.0)*rho); PetscReal eT = e + 0.5*(u*u + v*v); // Store the values node[RHO] = rho; node[RHOE] = rho*eT; node[RHOU + 0] = rho*u; node[RHOU + 1] = rho*v; PetscFunctionReturn(0); } static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) { PetscFunctionBeginUser; PetscErrorCode ierr; PetscLogStagePush(monitorStage); PetscInt interval = 1; if(step % interval == 0) { // Get the DM DM dm; ierr = TSGetDM(ts, &dm); CHKERRQ(ierr); ierr = VecViewFromOptions(u, NULL, "-sol_view"); CHKERRQ(ierr); // Open a vtk viewer // PetscViewer viewer; // char filename[PETSC_MAX_PATH_LEN]; // ierr = PetscSNPrintf(filename,sizeof(filename),"/Users/mcgurn/chrestScratch/results/vortex/flow%.4D.vtu",step);CHKERRQ(ierr); // ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)dm),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); // ierr = VecView(u,viewer);CHKERRQ(ierr); // ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); ierr = PetscPrintf(PetscObjectComm((PetscObject)dm), "TS at %f\n", time); CHKERRQ(ierr); // Compute the error void *exactCtxs[1]; PetscErrorCode (*exactFuncs[1])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx); PetscDS ds; ierr = DMGetDS(dm, &ds); CHKERRQ(ierr); // Get the exact solution ierr = PetscDSGetExactSolution(ds, 0, &exactFuncs[0], &exactCtxs[0]); CHKERRQ(ierr); // Create an vector to hold the exact solution Vec exactVec; ierr = VecDuplicate(u, &exactVec); CHKERRQ(ierr); ierr = DMProjectFunction(dm, time, exactFuncs, exactCtxs, INSERT_ALL_VALUES, exactVec); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)exactVec, "exact"); CHKERRQ(ierr); ierr = VecViewFromOptions(exactVec, NULL, "-exact_view"); CHKERRQ(ierr); // For each component, compute the l2 norms ierr = VecAXPY(exactVec, -1.0, u); CHKERRQ(ierr); PetscReal ferrors[4]; ierr = VecSetBlockSize(exactVec, 4); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "Timestep: %04d time = %-8.4g \t\n", (int)step, (double)time); CHKERRQ(ierr); ierr = VecStrideNormAll(exactVec, NORM_2, ferrors); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_2 Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double)(ferrors[0]), (double)(ferrors[1]), (double)(ferrors[2]), (double)(ferrors[3])); CHKERRQ(ierr); // And the infinity error ierr = VecStrideNormAll(exactVec, NORM_INFINITY, ferrors); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "\tL_Inf Error: [%2.3g, %2.3g, %2.3g, %2.3g]\n", (double)ferrors[0], (double)ferrors[1], (double)ferrors[2], (double)ferrors[3]); CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)exactVec, "error"); CHKERRQ(ierr); ierr = VecViewFromOptions(exactVec, NULL, "-exact_view"); CHKERRQ(ierr); ierr = VecDestroy(&exactVec); CHKERRQ(ierr); } PetscLogStagePop(); PetscFunctionReturn(0); } static PetscErrorCode PhysicsBoundary_Euler(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx) { PetscFunctionBeginUser; Constants *constants = (Constants *)ctx; // Offset the calc assuming the cells are square PetscReal x[3]; for(PetscInt i =0; i < constants->dim; i++){ x[i] = c[i] + n[i]*0.5; } EulerExact(constants->dim, time, x, 0, a_xG, ctx); PetscFunctionReturn(0); } int main(int argc, char **argv) { // Setup the problem Constants constants; // sub sonic constants.dim = 2; constants.L = 1.0; constants.xc = constants.L/2.0; constants.yc = constants.L/2.0; constants.Tinf =298.0; constants.rhoInf = 1.0; constants.Rgas = 287.0; constants.gamma = 1.4; constants.rc = .1*constants.L; constants.gamma = 1.4; constants.Mac = 0.3; constants.MaxInf = 0.3; constants.MayInf = 0.0; PetscErrorCode ierr; // create the mesh // setup the ts DM dm; /* problem definition */ TS ts; /* timestepper */ // initialize petsc and mpi PetscInitialize(&argc, &argv, NULL, "HELP"); // Create a ts ierr = TSCreate(PETSC_COMM_WORLD, &ts);CHKERRQ(ierr); ierr = TSSetProblemType(ts, TS_NONLINEAR);CHKERRQ(ierr); ierr = TSSetType(ts, TSRK);CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);CHKERRQ(ierr); PetscInt lengthFactor = 2; ierr = PetscOptionsGetInt(NULL, NULL, "-lengthFactor", &lengthFactor, NULL);CHKERRQ(ierr); PetscPrintf(PETSC_COMM_WORLD, "LengthFactor %d\n", lengthFactor); // Create a mesh // hard code the problem setup PetscReal start[] = {0.0, 0.0}; PetscReal end[] = {constants.L*lengthFactor, constants.L}; PetscReal nxHeight = 10; PetscInt nx[] = {lengthFactor*nxHeight, nxHeight}; ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, constants.dim, PETSC_FALSE, nx, start, end, NULL, PETSC_TRUE, &dm);CHKERRQ(ierr); // Setup the flow data FlowData flowData; /* store some of the flow data*/ ierr = FlowCreate(&flowData);CHKERRQ(ierr); // Combine the flow data ProblemSetup problemSetup; problemSetup.flowData = flowData; problemSetup.constants = constants; //Setup CompressibleFlow_SetupDiscretization(flowData, &dm); // Add in the flow parameters PetscScalar params[TOTAL_COMPRESSIBLE_FLOW_PARAMETERS]; params[CFL] = 0.5; params[GAMMA] = constants.gamma; // set up the finite volume fluxes CompressibleFlow_StartProblemSetup(flowData, TOTAL_COMPRESSIBLE_FLOW_PARAMETERS, params); DMView(flowData->dm, PETSC_VIEWER_STDOUT_WORLD); // Add in any boundary conditions PetscDS prob; ierr = DMGetDS(flowData->dm, &prob); CHKERRABORT(PETSC_COMM_WORLD, ierr); const PetscInt idsLeft[]= {1, 2, 3, 4}; ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall left", "Face Sets", 0, 0, NULL, (void (*)(void))PhysicsBoundary_Euler, NULL, 4, idsLeft, &constants);CHKERRQ(ierr); // Complete the problem setup ierr = CompressibleFlow_CompleteProblemSetup(flowData, ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Name the flow field ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution"); CHKERRABORT(PETSC_COMM_WORLD, ierr); // Setup the TS ierr = TSSetFromOptions(ts); CHKERRABORT(PETSC_COMM_WORLD, ierr); // ierr = TSMonitorSet(ts, MonitorError, &constants, NULL);CHKERRQ(ierr); CHKERRABORT(PETSC_COMM_WORLD, ierr); // set the initial conditions PetscErrorCode (*func[2]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {EulerExact}; void* ctxs[1] ={&constants}; ierr = DMProjectFunction(flowData->dm,0.0,func,ctxs,INSERT_ALL_VALUES,flowData->flowField);CHKERRQ(ierr); // for the mms, add the exact solution ierr = PetscDSSetExactSolution(prob, 0, EulerExact, &constants);CHKERRQ(ierr); // Output the mesh ierr = DMViewFromOptions(flowData->dm, NULL, "-dm_view");CHKERRQ(ierr); // Compute the end time so it goes around once PetscReal aInf = PetscSqrtReal(constants.gamma*constants.Rgas*constants.Tinf); PetscReal u_x = constants.MaxInf*aInf; PetscReal endTime = constants.L/u_x; TSSetMaxTime(ts, endTime); TSSetMaxSteps(ts, 50); PetscDSView(prob, PETSC_VIEWER_STDOUT_WORLD); PetscLogStage solveStage; PetscLogStageRegister("TSSolve",&solveStage); PetscLogStageRegister("Monitor", &monitorStage); PetscLogStagePush(solveStage); ierr = TSSolve(ts,flowData->flowField);CHKERRQ(ierr); PetscLogStagePop(); PetscPrintf(PETSC_COMM_WORLD, "Done"); FlowDestroy(&flowData); TSDestroy(&ts); return PetscFinalize(); }
{ "alphanum_fraction": 0.6586619323, "avg_line_length": 35.4370860927, "ext": "c", "hexsha": "62f7bcce60b97dc81dfebd579a3a9b4cb3d11780", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mmcgurn/MattFlowCases", "max_forks_repo_path": "eulerIsentropicVortex.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mmcgurn/MattFlowCases", "max_issues_repo_path": "eulerIsentropicVortex.c", "max_line_length": 180, "max_stars_count": null, "max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mmcgurn/MattFlowCases", "max_stars_repo_path": "eulerIsentropicVortex.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3064, "size": 10702 }
#include "imd.h" #include <sys/time.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> // #define USEFLOAT // hauptsächlich in der funktion genexptint. Profiling zeigte, dass // hier die meiste zeit verbraucht wird -> float verdoppelt performance #ifdef USEFLOAT typedef float Real; #define REALTYPE MPI_FLOAT #else typedef double Real; #define REALTYPE MPI_DOUBLE #endif #ifdef USEFLOAT #define EXPR expf //exp zu floaten ist eine ganz mieeese idee #define SQRTR sqrtf #define POWR powf #define LOGR logf #else #define EXPR exp #define SQRTR sqrt #define POWR pow #define LOGR log #endif // ********************************************************* // PHYSICAL CONSTANTS // ********************************************************* // const double eV2J=1.6021766E-19; const Real eV2H=0.03674932; //eV to Hartree const Real colrad_reltol=1e-5; const Real colrad_abstol=10.0; // const Real J2eV=6.2415091E18; const Real planck=6.62607004E-34; // J/s const Real bohr_radius=0.52917721067E-10; // m const Real bohr_radius_sq=2.800285202924816e-21; const Real hbar_cub=1.172812163789953e-102; //hbar^3 const Real double_emass_pow_3_2 = 2.459112949719466e-45; // (2*emass)^3/2 const int MAXLINE = 255; const Real pi=3.141592653589793; const Real pi_sq=9.869604401089358; const Real E_ion_H=13.6; // eV const Real E_ion_H_J=2.178960176000000e-18; // J const Real E_ion_H_sq_J=4.747867448593952e-36; const Real colrad_tequi=1e-12;//TEST// 1e-12; //bei initial equi ohne Temperatur-variation erst einmal //die Saha-besetzungsdichten equilibrieren //const double LIGHTSPEED=2.997925458e8; // m/s Real LASERFREQ; int colrad_ydot(double t, N_Vector u, N_Vector udot, void *user_data); void do_Saha(Real Te,Real totalc,Real ne,N_Vector y); int colrad_GetCoeffs(N_Vector y,Real It, void * user_data); // Die Zwei müssen nach Prototypes.h // void do_colrad(double dt); // void colrad_init(void); void colrad_read_states(void); void colrad_Saha_init(int i,int j,int k); // ****************************************************************************** // * CROSS SECTION INTEGRATION STUFF // ****************************************************************************** gsl_integration_workspace * winteg_inner=NULL; gsl_integration_workspace * winteg_outer=NULL; gsl_integration_workspace * winteg_fermi=NULL; gsl_integration_workspace * winteg_exc=NULL; //excitation gsl_integration_romberg_workspace * winteg_rb_inner=NULL; gsl_integration_romberg_workspace * winteg_rb_outer=NULL; struct my_f_params { Real ne; Real T;Real mu; Real E;Real DeltaE; int allowed;}; // struct my_f_params fparams_inner; //For inner integrand // struct my_f_params fparams_outer; //outer integrand // struct my_f_params fparams_fermi; // struct my_f_params fparams_exc; double inner_integrand_ionization(double x, void *p); // integrate along E' double outer_integrand_ionization(double x,void *p); // integrate along E Real double_integral_ionization(Real ne,Real T, Real mu, Real DeltaE); //evaluates double integral double inner_integrand_recombination(double x, void *p); double outer_integrand_recombination(double x,void *p); Real double_integral_recombination(Real ne,Real T, Real mu, Real DeltaE); double integrand_excitation(double x,void *p); Real eval_excitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed); Real eval_dexcitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed); double integrand_deexcitation(double x,void *p); double fermi_integrand(double x, void *p); Real eval_fermi_integrand(Real ne,Real T, Real mu); double integrand_excitation_debug(double x,void *p); double outer_integrand_ionization2(double x,struct my_f_params* p); Real double_integral_ionization2(Real ne,Real T, Real mu, Real DeltaE); //evaluates double integral double inner_integrand_ionization2(double x, struct my_f_params* p); // ********************************************************************************************** // * PAR INTEGRAL STUFF // ********************************************************************************************** int terminate_gkq; int terminate_gkq_outer; int terminate_gkq_inner; int terminate_serial; int gkq_iter_serial; // nr of iterations const double gkq_alpha=0.816496580927726; const double gkq_beta=0.447213595499958; static const double xgkq[12] = { 0.0, -0.942882415695480, -0.816496580927726, -0.641853342345781, -0.447213595499958, -0.236383199662150, 0.0, 0.236383199662150, 0.447213595499958, 0.641853342345781, 0.816496580927726, 0.942882415695480 }; Real integral_simpson(Real (*f)(Real, void*), Real a, Real b,int n,void* p); int simpson_error; const Real tolmax=1e-20; const Real simpson_itermax=120; #define INITIAL_STACK_SIZE 128 /* initial size of new stacks */ /* the stack structure */ struct stack_s{ int el_count; /* count of elements on stack */ int el_size; /* size of an element */ int mem_reserve; /* allocated memory for stack */ void* elements; /* pointer to begin of stack */ }; typedef struct _work_t{ double a; double b; double tol; double S; double fa; double fb; double fm; double rec; int iter; struct my_f_params * p; //pointer auf params } work_t; typedef struct _work_t_gkq{ double a; double b; double toler; double I_13; double I_prev; double fa; double fb; struct my_f_params * p; //pointer auf params shortint iter; } work_gkq; typedef struct stack_s* stack_t; double integral_simpson_par(double (*f)(double, struct my_f_params*), stack_t stack); double gkq_adapt_OMP(double (*f)(double, struct my_f_params*), stack_t stack); double gkq_OMP(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p,stack_t stack); double gkq_serial(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p); double gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, double fa,double fb, double toler,double I_13, struct my_f_params* p); // void create_stack(stack_t* stack, int element_size); // int empty_stack(stack_t stack); // void push_stack(stack_t stack, void* element); // void pop_stack(stack_t stack, void* element); /****************************************** * create new stack ******************************************/ void create_stack( stack_t* stack, /* stack to create */ int element_size) /* size of a stack element */ { int initial_size = INITIAL_STACK_SIZE; /* allocate memory for new stack struct */ (*stack) = (stack_t) malloc(sizeof(struct stack_s)); if (!(*stack)){ char errstr[255]; sprintf(errstr, "error: could not allocate memory for stack.. Abort.\n"); error(errstr); // exit(1); } /* allocate memory for stack elements */ (*stack)->elements = (void*) malloc(element_size * initial_size); (*stack)->mem_reserve = initial_size; if (!(*stack)->elements){ char errstr[255]; sprintf(errstr, "error: could not allocate memory for stack.. Abort.\n"); error(errstr); } (*stack)->el_size = element_size; (*stack)->el_count = 0; } /***************************************** * check if the stack is empty *****************************************/ int empty_stack(stack_t stack) { return stack->el_count <= 0; } /***************************************** * push a element on stack *****************************************/ void push_stack(stack_t stack, /* target stack */ void* element) /* element to push */ { int i, new_reserve; int log2_count; /* check if we need more memory for stack */ if (stack->el_count >= stack->mem_reserve) { /* calculate new size for the stack it should be a power of two */ for (i = stack->el_count, log2_count = 0; i > 0; i>>1, log2_count++); new_reserve = 1 << log2_count; /* reallocate memory for phase thread tables and nullify new values */ stack->elements = (void *) realloc(stack->elements, stack->el_size * new_reserve); if (!stack->elements){ char errstr [255]; sprintf(errstr, "error: can't reallocate stack.. Aborting\n"); error(errstr); // exit(1); } stack->mem_reserve = new_reserve; } /* now push the element on top of the stack */ memcpy((char*)stack->elements + stack->el_count*stack->el_size, element, stack->el_size); stack->el_count++; } /***************************************** * pop an element from stack *****************************************/ void pop_stack( stack_t stack, /* target stack */ void* element) /* where poped el. should be stored */ { if (stack->el_count <= 0){ char errstr[255]; sprintf(errstr, "error: trying to pop from empty stack.\n"); error(errstr); // exit(2); } stack->el_count--; memcpy(element, (char*)stack->elements + stack->el_count*stack->el_size, stack->el_size); } // *************************************************************************** // * Gauss-kronard quadrature, parallel // *************************************************************************** double gkq_OMP(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p,stack_t stack) { //1st integration double result=0.0; // ********************************************* double m=0.5*(a+b); double h=0.5*(b-a); double y[13]; double fa=y[0]=f(a,p); double fb=y[12]=f(b,p); int i; for(i=1;i<12;i++) y[i]=f(m+xgkq[i]*h,p); double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod 625.0*(y[4]+y[8])+672.0*y[6]); double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+ 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+ 0.242611071901408*y[6]); //13-point Kronrod double Err1=fabs(I_7-I_13); double Err2=fabs(I_4-I_13); double r=(Err2 != 0.0) ? Err1/Err2 : 1.0; double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; if(I_13 == 0) I_13=b-a; I_13=fabs(I_13); //Prepare work and push onto stack work_gkq work; work.a = a; work.b = b; work.toler = toler; work.I_13=I_13; work.fa=fa; work.fb=fb; work.p=p; work.I_prev=I_7; //ANTI-FOLGENDES: //OUT OF TOLERANCE !!!, mll:3.0162e-18, a:3.0162e-18, b:3.0162e-18, mrr:3.0162e-18,I_7-I_4:0.0000e+00, tol:1.6002e-315,I_13:7.0585e-313 if(I_13 < 1e-150) return 0; push_stack(stack, &work); result=gkq_adapt(f,stack); return result; } double gkq_serial(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p) { //1st integration double result=0.0; gkq_iter_serial=0; // ********************************************* double m=0.5*(a+b); double h=0.5*(b-a); double y[13]; double fa=y[0]=f(a,p); double fb=y[12]=f(b,p); int i; for(i=1;i<12;i++) y[i]=f(m+xgkq[i]*h,p); double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod 625.0*(y[4]+y[8])+672.0*y[6]); double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+ 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+ 0.242611071901408*y[6]); //13-point Kronrod double Err1=fabs(I_7-I_13); double Err2=fabs(I_4-I_13); double r=(Err2 != 0.0) ? Err1/Err2 : 1.0; double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; if(I_13 == 0) I_13=b-a; I_13=fabs(I_13); result=gkq_adapt_serial(f,a,b,fa,fb,toler,I_13, p); return result; } // *********************************************** // * RECURSIVE ADAPTION ROUTINE FOR PARALLEL-GK-QUADRATURE // ********************************************** double gkq_adapt_OMP(double (*f)(double, struct my_f_params*), stack_t stack) { work_gkq work; work.iter=0; int ready, idle, busy; double integral_result = 0.0; busy = 0; terminate_gkq=0; #pragma omp parallel default(none) \ shared(stack, integral_result,f,busy,terminate_gkq,myid) \ private(work, idle, ready) { // printf("me:%d, err:%d\n",omp_get_thread_num(),simpson_error); ready = 0; idle = 1; while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT! { #pragma omp critical (stack) { if (!empty_stack(stack)) { /* we have new work */ pop_stack(stack, &work); if (idle) { /* say others i'm busy */ busy += 1; idle = 0; } } else { /* no new work on stack */ if (!idle){ busy -= 1; idle = 1; } /* nobody has anything to do; let us leave the loop */ if (busy == 0) { ready = 1; } } } /* end critical(stack) */ if (idle) continue; //if ready==1 --> leave loop double I_prev=work.I_prev; double a = work.a; double b = work.b; double toler = work.toler; double I_13=work.I_13; double fa=work.fa; double fb=work.fb; int iter=work.iter; // double *y= work.y; // brauch ich nicht! struct my_f_params * p = work.p; double m = (a+b)/2; double h = (b -a)/2; double mll=m-gkq_alpha*h; double ml=m-gkq_beta*h; double mr=m+gkq_beta*h; double mrr=m+gkq_alpha*h; double fmll=f(mll,p); double fml=f(ml,p); double fm=f(m,p); double fmr=f(mr,p); double fmrr=f(mrr,p); double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula. double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm); // if(myid==1) // printf("I_7:%.4e, I_13:%.4e,I_4:%.4e, minus:%.4e, to:%.4e\n",I_7,I_13,I_4,I_7-I_4, toler*I_13); int maxiter=50; //max. subdivisions double abstol=1e-30; work.I_prev=I_7; // für abstolcheck in nächster recursion if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr || iter > maxiter || fabs(I_7-I_prev) < abstol ) { if ((mll <= a || b <= mrr)) //Error { // out_of_tolerance=true; // Interval contains no more machine numbers // printf("OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e,I_7-I_4:%.4e, tol:%.4e,I_13:%.4e\n", // mll,b,b,mrr,I_7-I_4, toler*I_13,I_13); terminate_gkq=1; } #pragma omp critical (integral_result) { integral_result += I_7; //Terminate recursion. } // printf("me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f,ubteg;%.4e\n", omp_get_thread_num(), a,b,toler,I_4,I_7,integral_result); } else //subdivide interval and push new work on stack { #pragma omp critical (stack) { // printf("me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\n", omp_get_thread_num(), a,b,toler,I_4,I_7); work.iter=iter+1; work.a=a; work.b=mll; work.fa=fa; work.fb=fmll; push_stack(stack, &work); work.a=mll; work.b=ml; work.fa=fmll; work.fb=fml; push_stack(stack, &work); work.a=ml; work.b=m; work.fa=fml; work.fb=fm; push_stack(stack, &work); work.a=m; work.b=mr; work.fa=fm; work.fb=fmr; push_stack(stack, &work); work.a=mr; work.b=mrr; work.fa=fmr; work.fb=fmrr; push_stack(stack, &work); work.a=mrr; work.b=b; work.fa=fmrr; work.fb=fb; push_stack(stack, &work); } // pragma critical stack } // else ..non-acceptable error } // while } /* end omp parallel */ return integral_result; } double gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, double fa, double fb, double toler,double I_13, struct my_f_params* p) { double m = (a+b)/2; double h = (b -a)/2; double mll=m-gkq_alpha*h; double ml=m-gkq_beta*h; double mr=m+gkq_beta*h; double mrr=m+gkq_alpha*h; double fmll=f(mll,p); double fml=f(ml,p); double fm=f(m,p); double fmr=f(mr,p); double fmrr=f(mrr,p); double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula. double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm); gkq_iter_serial++; if ( (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) && gkq_iter_serial) { if ((mll <= a || b <= mrr) && !terminate_serial) //Error { // out_of_tolerance=true; // Interval contains no more machine numbers printf("OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\n", mll,b,b,mrr); terminate_serial=1; } // printf("me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\n", omp_get_thread_num(), a,b,toler,I_4,I_7); return I_7; } else { // printf("me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\n", omp_get_thread_num(), a,b,toler,I_4,I_7); return gkq_adapt_serial(f, a,mll,fa,fmll,toler,I_13,p) + gkq_adapt_serial(f, mll,ml,fmll,fml,toler,I_13,p) + gkq_adapt_serial(f, ml,m,fml,fm,toler,I_13,p) + gkq_adapt_serial(f, m,mr,fm,fmr,toler,I_13,p) + gkq_adapt_serial(f, mr,mrr,fmr,fmrr,toler,I_13,p) + gkq_adapt_serial(f, mrr,b,fmrr,fb,toler,I_13,p); } }
{ "alphanum_fraction": 0.5735985138, "avg_line_length": 29.1897926635, "ext": "h", "hexsha": "3b0f212278c8120ec4b14091fbe8454a2202a2a6", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fmqeisfeld/IMD", "max_forks_repo_path": "imd_colrad.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "fmqeisfeld/IMD", "max_issues_repo_path": "imd_colrad.h", "max_line_length": 137, "max_stars_count": 2, "max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fmqeisfeld/IMD", "max_stars_repo_path": "imd_colrad.h", "max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z", "num_tokens": 5658, "size": 18302 }
static char help[] = "Solve a hyperbolic system in one space dimension (1D):\n" " q_t + F(t,x,q)_x = g(t,x,q)\n" "where solution q(t,x), flux F(t,x,q), and source g(t,x,q) are column vectors\n" "of length n. The domain is (t,x) in [0,T] x [a,b]. The initial condition is\n" "q(0,x) = f(x). The flux may be of the form\n" " F(t,x,q) = A(t,x,q) q\n" "but this is not required. Flux boundary conditions are used in all cases,\n" " F = bdryflux_a(t,qright)\n" " F = bdryflux_b(t,qleft)\n" "including nonreflecting, reflecting, outflow, and periodic boundary\n" "conditions.\n\n" "Uses a finite volume discretization so the grid values represent cell\n" "averages. Each case implements a Riemann solver\n" " F = faceflux(t,x,qleft,qright)\n" "at cell faces. (The Riemann solver computes the value of the solution on\n" "the cell face going forward in time.) Implements the following\n" "slope-limiters when computing fluxes:\n" " -limiter none Godunov's method, i.e. first-order upwinding\n" " -limiter fromm formula (6.14) in LeVeque 2002\n" " -limiter mc formula (6.29)\n" " -limiter minmod formula (6.26)\n" "Control the spatial grid by PETSc option\n" " -da_grid_x M [grid of M cells/points]\n\n" "Time stepping is by semi-discretization in space (method of lines) and then\n" "application of PETSc's (generally) adaptive and higher-order TS solvers.\n" "Control time stepping and solution information by these PETSc options, among\n" "others:\n" " -ts_monitor [shows time steps]\n" " -ts_monitor_solution draw [generate simple movie]\n" " -draw_pause 0.1 -draw_size 2000,200 [control the movie]\n" " -ts_type [default is rk]\n" " -ts_rk_type X [default is 3bs]\n" " -ts_dt 0.01 -ts_adapt_type none [turn off adaptive]\n" "Note that TS solver type SSP (-ts_type ssp) is recommended for these\n" "hyperbolic problems.\n\n" "Use option -problem selects the problem case:\n" " -problem acoustic wave equation in system form (n=2) [default]\n" " -problem advection scalar advection equation (n=1)\n" " -problem swater shallow water equations (n=2)\n" " -problem traffic scalar, nonlinear traffic equation (n=1)\n" "To see possible initial conditions for problem X see the corresponding\n" ".h file. Based on the problem-specific possiblities, set\n" " -initial Y\n\n" "See the makefile for test examples, and do 'make test' to test.\n\n" "This program is documented by the slides in the fvolume/ directory at\n" "https://github.com/bueler/slide-teach\n\n"; #include <petsc.h> /* The struct "ProblemCtx" is defined in cases.h. The comments in cases.h show how to add new problems. */ #include "cases.h" // minmod(a,b) as define on LeVeque page 111 static PetscReal minmod(PetscReal a, PetscReal b) { if (a*b > 0) // both signs agree return (PetscAbs(a) < PetscAbs(b)) ? a : b; else return 0.0; } typedef enum {NONE,FROMM,MC,MINMOD} LimiterType; static const char* LimiterTypes[] = {"none","fromm","mc","minmod", "LimiterType", "", NULL}; static LimiterType limiter = NONE; // slope-limiter extern PetscErrorCode FormInitial(DMDALocalInfo*, Vec, PetscReal, ProblemCtx*); extern PetscErrorCode GetMaxSpeed(DMDALocalInfo*, Vec, PetscReal, PetscReal*, ProblemCtx*); extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal, PetscReal*, PetscReal*, void*); int main(int argc,char **argv) { PetscErrorCode ierr; TS ts; // ODE solver for method-of-lines (MOL) DM da; // structured grid Vec q; // the solution DMDALocalInfo info; // structured grid info ProblemType problem = ACOUSTIC; // which problem we are solving ProblemCtx user; // problem-specific information PetscInt swidth, k, steps; PetscBool flg; PetscReal hx, qmin, qmax, t0, tf, dt, c; PetscInitialize(&argc,&argv,(char*)0,help); // get which problem we are solving // (ProblemType, ProblemTypes, InitializerPtrs are defined in cases.h) ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"", "riemann (hyperbolic system solver) options",""); CHKERRQ(ierr); ierr = PetscOptionsEnum("-problem", "problem type", "riemann.c",ProblemTypes,(PetscEnum)(problem),(PetscEnum*)&problem, NULL); CHKERRQ(ierr); ierr = PetscOptionsEnum("-limiter", "limiter type", "riemann.c",LimiterTypes,(PetscEnum)(limiter),(PetscEnum*)&limiter, NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); // call the initializer for the given case // (it allocates list of strings in user->field_names thus PetscFree below) ierr = (*InitializerPtrs[problem])(&user); CHKERRQ(ierr); // create grid swidth = (limiter == NONE) ? 1 : 2; ierr = DMDACreate1d(PETSC_COMM_WORLD, user.periodic_bcs ? DM_BOUNDARY_PERIODIC : DM_BOUNDARY_NONE, 4, // default resolution user.n_dim, // system dimension (d.o.f.) swidth, // stencil (half) width NULL,&da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); hx = (user.b_right - user.a_left) / info.mx; ierr = DMDASetUniformCoordinates(da,user.a_left+hx/2.0,user.b_right-hx/2.0, 0.0,1.0,0.0,1.0); CHKERRQ(ierr); // set field names so that visualization makes sense for (k = 0; k < info.dof; k++) { ierr = DMDASetFieldName(da,k,(user.field_names)[k]); CHKERRQ(ierr); } // create TS: dq/dt = G(t,q) form ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr); ierr = TSSetDM(ts,da); CHKERRQ(ierr); ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES, (DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr); ierr = TSSetType(ts,TSRK); CHKERRQ(ierr); // defaults to -ts_rk_type 3bs // set up time axis ierr = TSSetTime(ts,user.t0_default); CHKERRQ(ierr); ierr = TSSetMaxTime(ts,user.tf_default); CHKERRQ(ierr); dt = user.tf_default - user.t0_default; ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); // usually reset below ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr); ierr = TSSetFromOptions(ts); CHKERRQ(ierr); // get initial values ierr = DMCreateGlobalVector(da,&q); CHKERRQ(ierr); ierr = TSGetTime(ts,&t0); CHKERRQ(ierr); ierr = FormInitial(&info,q,t0,&user); CHKERRQ(ierr); //ierr = VecView(q,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); // use CFL to reset initial time-step dt (unless user sets) ierr = PetscOptionsHasName(NULL,NULL,"-ts_dt",&flg); CHKERRQ(ierr); ierr = GetMaxSpeed(&info,q,t0,&c,&user); CHKERRQ(ierr); if (!flg && c > 0.0) { ierr = TSGetMaxTime(ts,&tf); CHKERRQ(ierr); dt = PetscMin(hx / c, tf-t0); ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr); } else { ierr = TSGetTimeStep(ts,&dt); CHKERRQ(ierr); } // solve ierr = PetscPrintf(PETSC_COMM_WORLD, "solving problem %s, a system of %d equations,\n" " on %d-point grid with dx=%.6f and initial dt=%.6f...\n", ProblemTypes[problem],info.dof,info.mx,hx,dt); CHKERRQ(ierr); ierr = TSSolve(ts,q); CHKERRQ(ierr); // report on solution ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); ierr = TSGetTime(ts,&tf); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, " ... completed %d steps for %.4f <= t <= %.4f\n", steps,t0,tf); CHKERRQ(ierr); for (k = 0; k < info.dof; k++) { ierr = VecStrideMin(q,k,NULL,&qmin); CHKERRQ(ierr); ierr = VecStrideMax(q,k,NULL,&qmax); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, " range of %d component: %8.5f <= %s <= %8.5f\n", k,qmin,(user.field_names)[k],qmax); CHKERRQ(ierr); } // free memory VecDestroy(&q); TSDestroy(&ts); DMDestroy(&da); ierr = PetscFree(user.field_names); CHKERRQ(ierr); return PetscFinalize(); } PetscErrorCode FormInitial(DMDALocalInfo *info, Vec q, PetscReal t0, ProblemCtx *user) { PetscErrorCode ierr; const PetscReal hx = (user->b_right - user->a_left) / info->mx; PetscInt j; PetscReal x, *aq; ierr = DMDAVecGetArray(info->da, q, &aq); CHKERRQ(ierr); for (j=info->xs; j<info->xs+info->xm; j++) { x = user->a_left + (j+0.5) * hx; ierr = user->f_initial(t0,x,&aq[(info->dof)*j]); CHKERRQ(ierr); } ierr = DMDAVecRestoreArray(info->da, q, &aq); CHKERRQ(ierr); return 0; } PetscErrorCode GetMaxSpeed(DMDALocalInfo *info, Vec q, PetscReal t, PetscReal *maxspeed, ProblemCtx *user) { PetscErrorCode ierr; const PetscReal hx = (user->b_right - user->a_left) / info->mx; PetscInt j; PetscReal x, cj, locmax, *aq; MPI_Comm comm; ierr = DMDAVecGetArray(info->da, q, &aq); CHKERRQ(ierr); locmax = 0.0; for (j=info->xs; j<info->xs+info->xm; j++) { x = user->a_left + (j+0.5) * hx; ierr = user->maxspeed(t,x,&aq[(info->dof)*j],&cj); CHKERRQ(ierr); locmax = PetscMax(locmax,cj); } ierr = DMDAVecRestoreArray(info->da, q, &aq); CHKERRQ(ierr); ierr = PetscObjectGetComm((PetscObject)info->da,&comm); CHKERRQ(ierr); ierr = MPI_Allreduce(&locmax,maxspeed,1,MPIU_REAL,MPIU_MAX,comm); CHKERRQ(ierr); return 0; } static inline void ncopy(PetscInt n, PetscReal *src, PetscReal *tgt) { PetscInt k; for (k = 0; k < n; k++) tgt[k] = src[k]; } static inline void slopemodify(PetscInt n, PetscReal C, PetscReal *sig, PetscReal *Q_in, PetscReal *Q_out) { PetscInt k; for (k = 0; k < n; k++) Q_out[k] = Q_in[k] + C * sig[k]; } // Right-hand-side of method-of-lines discretization form of PDE. Implements // Gudonov (i.e. Riemann-solver upwind) method with a slope limiter. PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info, PetscReal t, PetscReal *aq, PetscReal *aG, void *ctx) { PetscErrorCode ierr; ProblemCtx *user = (ProblemCtx*)ctx; const PetscInt n = info->dof; const PetscReal hx = (user->b_right - user->a_left) / info->mx; Vec sig; PetscInt j, k; PetscReal x, *asig, sl, sr, *Ql, *Qr, // slope-limited values of solution at either // side of current face *Fl, *Fr; // face fluxes on either end of current cell // for each owned cell get slope using the slope-limiter ierr = DMCreateLocalVector(info->da,&sig); CHKERRQ(ierr); ierr = VecSet(sig,0.0); CHKERRQ(ierr); // implements limiter == NONE ierr = DMDAVecGetArray(info->da,sig,&asig); CHKERRQ(ierr); if (limiter != NONE) { // following block assumes swidth >= 2 for (j = info->xs-1; j < info->xs + info->xm+1; j++) { // x_j is cell center for (k = 0; k < n; k++) { if ((j < 0 || j > info->mx-1) && user->periodic_bcs == PETSC_FALSE) continue; if (j == 0 && user->periodic_bcs == PETSC_FALSE) asig[n*j+k] = (aq[n*(j+1) + k] - aq[n*j + k]) / hx; else if (j == info->mx-1 && user->periodic_bcs == PETSC_FALSE) asig[n*j+k] = (aq[n*j + k] - aq[n*(j-1) + k]) / hx; else { if (limiter == FROMM) { asig[n*j+k] = (aq[n*(j+1) + k] - aq[n*(j-1) + k]) / (2.0 * hx); } else { sr = (aq[n*(j+1) + k] - aq[n*j + k]) / hx; sl = (aq[n*j + k] - aq[n*(j-1) + k]) / hx; if (limiter == MINMOD) asig[n*j+k] = minmod(sl,sr); else if (limiter == MC) asig[n*j+k] = minmod(0.5*(sl+sr),2.0*minmod(sl,sr)); else { SETERRQ(PETSC_COMM_SELF,1,"how did I get here?\n"); } } } } } } // get left-face flux Fl for first cell owned by process; may be at x=a ierr = PetscMalloc4(n,&Ql,n,&Qr,n,&Fl,n,&Fr); CHKERRQ(ierr); if (info->xs == 0 && user->periodic_bcs == PETSC_FALSE) { // use right slope slopemodify(n,-hx/2.0,&asig[0],&aq[0],Qr); ierr = user->bdryflux_a(t,hx,Qr,Fl); CHKERRQ(ierr); } else { // use left and right (limited) slope [left is owned by other process] x = user->a_left + (info->xs+0.5) * hx; slopemodify(n,hx/2.0,&asig[n*(info->xs-1)],&aq[n*(info->xs-1)],Ql); slopemodify(n,-hx/2.0,&asig[n*(info->xs)],&aq[n*(info->xs)],Qr); ierr = user->faceflux(t,x-hx/2.0,Ql,Qr,Fl); CHKERRQ(ierr); } // for each owned cell, compute RHS G(t,x,q) for (j = info->xs; j < info->xs + info->xm; j++) { // x_j is cell center x = user->a_left + (j+0.5) * hx; // set aG[n j + k] = g(t,x_j,u)_k ierr = user->g_source(t,x,&aq[n*j],&aG[n*j]); CHKERRQ(ierr); // get right-face flux Fr for cell; may be at x=b if (j == info->mx-1 && user->periodic_bcs == PETSC_FALSE) { // user left slope slopemodify(n,hx/2.0,&asig[n*j],&aq[n*j],Ql); ierr = user->bdryflux_b(t,hx,Ql,Fr); CHKERRQ(ierr); } else { // use left and right (limited) slope; see formulas LeVeque page 193 slopemodify(n,hx/2.0,&asig[n*j],&aq[n*j],Ql); slopemodify(n,-hx/2.0,&asig[n*(j+1)],&aq[n*(j+1)],Qr); ierr = user->faceflux(t,x+hx/2.0,Ql,Qr,Fr); CHKERRQ(ierr); } // complete the RHS: // aG[n j + k] = g(t,x_j,u)_k + (F_{j-1/2}_k - F_{j+1/2}_k) / hx for (k = 0; k < n; k++) aG[n*j+k] += (Fl[k] - Fr[k]) / hx; ncopy(n,Fr,Fl); // transfer Fr to Fl, for next loop } // clean up ierr = PetscFree4(Ql,Qr,Fl,Fr); CHKERRQ(ierr); ierr = DMDAVecRestoreArray(info->da,sig,&asig); CHKERRQ(ierr); ierr = VecDestroy(&sig); CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.5749173582, "avg_line_length": 44.9181818182, "ext": "c", "hexsha": "dd7fecb3f6d2acbc7bf50cb3dbf43cb23d30dc7d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bueler/p4pdes-next", "max_forks_repo_path": "c/riemann/riemann.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "bueler/p4pdes-next", "max_issues_repo_path": "c/riemann/riemann.c", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "bueler/p4pdes-next", "max_stars_repo_path": "c/riemann/riemann.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4424, "size": 14823 }
#include <stdio.h> #include <stdlib.h> #include <QuEST.h> #include "QuEST_debug.h" #include "QuEST_tn.h" #include <cblas.h> #define DEBUG 0 #if DEBUG # define DEBUG_PRINT(x) printf x #else # define DEBUG_PRINT(x) do {} while (0) #endif int* getTensorIndexPermutation(int* contractionIndices, int numContractions, int* freeIndices, int numFreeIndices, int tensor){ int *perm = (int*) malloc((numContractions+numFreeIndices)*sizeof(int)); int firstSize, secondSize; int *firstArray, *secondArray; if (tensor==1){ firstSize=numFreeIndices; firstArray=freeIndices; secondSize=numContractions; secondArray=contractionIndices; } else { secondSize=numFreeIndices; secondArray=freeIndices; firstSize=numContractions; firstArray=contractionIndices; } for (int i=0; i<firstSize; i++){ perm[i]=firstArray[i]; } for (int i=0; i<secondSize; i++){ perm[i+firstSize]=secondArray[i]; } return perm; } /* * All indices are of size 2 */ int* getTensorSizes(int numQubits){ int *sizes = (int*) malloc(numQubits*sizeof(int)); for (int i=0; i<numQubits; i++) sizes[i]=2; return sizes; } Tensor createTensor(int numPq, int numVq, QuESTEnv env){ Tensor tensor; //! Probably don't need to store these any more tensor.numPq = numPq; tensor.numVq = numVq; tensor.qureg = createQureg(tensor.numPq + tensor.numVq, env); //! might need to store next available vq return tensor; } /* * Swap corresponding qubit IDs in perm and return new index */ int swapBits(long long int b, int *perm, int nQubits) { long long int out = 0; for(int j=0;j<nQubits; j++) { out += (b >> j & 1) * (1 << perm[j]); } return out; } qreal* permuteArray(Qureg qureg, int *perm) { qreal* outArr = (qreal *) malloc(sizeof(qreal)*2*qureg.numAmpsPerChunk); for (long long int i = 0; i < qureg.numAmpsPerChunk; i++) { long long int newIndex = 2*swapBits(i, perm, qureg.numQubitsRepresented); outArr[newIndex] = qureg.stateVec.real[i]; outArr[newIndex+1] = qureg.stateVec.imag[i]; } return outArr; } /* * Expects tensor1Contractions to be in order from smallest to largest. * Expects tensor2Contractions to be ordered to match indices in tensor1. * Ie if tensor1 and tensor2 each have 3 indices and (tensor1, index 1) is * contracted with (tensor2, index 2) and (tensor1, index 2) is contracted with * (tensor2, index 0), use: * tensor1Contractions = [1, 2] * tensor2Contractions = [2, 0] */ Tensor contractIndices(Tensor tensor1, Tensor tensor2, int *tensor1Contractions, int *tensor2Contractions, int numContractions, int *tensor1FreeIndices, int numTensor1FreeIndices, int *tensor2FreeIndices, int numTensor2FreeIndices, QuESTEnv env){ printf("Begin contracting\n"); int numTensor1Qubits, numTensor2Qubits; numTensor1Qubits = tensor1.qureg.numQubitsRepresented; numTensor2Qubits = tensor2.qureg.numQubitsRepresented; int totalNumQ = numTensor1FreeIndices + numTensor2FreeIndices; printf("Permute indices to transform tensor contraction into the form of a matrix matrix multiply\n"); int *tensor1Perm = getTensorIndexPermutation(tensor1Contractions, numContractions, tensor1FreeIndices, numTensor1FreeIndices, 1); int *tensor2Perm = getTensorIndexPermutation(tensor2Contractions, numContractions, tensor2FreeIndices, numTensor2FreeIndices, 2); qreal* tensor1StateVecPermuted = permuteArray(tensor1.qureg, tensor1Perm); qreal* tensor2StateVecPermuted = permuteArray(tensor2.qureg, tensor2Perm); // Working output array for BLAS routine. This needs to be separate to contractedQureg as // that represents complex numbers as a struct of arrays where BLAS will output an array of complex types qreal* outputQureg = (qreal *) malloc(sizeof(qreal)*(1LL << (totalNumQ+1LL))); // Dimensions of MM multiply int M, N, K; M = 1 << numTensor2FreeIndices; N = 1 << numTensor1FreeIndices; K = 1 << numContractions; qreal alpha[2] = {1.0, 0.0}; qreal beta[2] = {0.0, 0.0}; printf("MM multiply dimensions: M:%d N:%d K:%d\n", M, N, K); printf("Do MM multiply\n"); // tensor2 x tensor1. cblas_zgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, M, N, K, alpha, tensor2StateVecPermuted, K, tensor1StateVecPermuted, N, beta, outputQureg, N); // Copy output into qureg object Qureg contractedQureg = createQureg(totalNumQ, env); for(long long int index = 0; index < contractedQureg.numAmpsPerChunk; index++) { contractedQureg.stateVec.real[index] = outputQureg[2*index]; contractedQureg.stateVec.imag[index] = outputQureg[2*index+1]; } printf("Free memory\n"); free(tensor1StateVecPermuted); free(tensor2StateVecPermuted); free(outputQureg); free(tensor1Perm); free(tensor2Perm); // Free old quregs destroyQureg(tensor1.qureg, env); destroyQureg(tensor2.qureg, env); // Create output tensor Tensor outputTensor; outputTensor.qureg = contractedQureg; //! TODO: We may need to set total number of qubits here //outputTensor.numPq = totalNumPq; //outputTensor.numVq = totalNumVq; outputTensor.qureg = contractedQureg; return outputTensor; } // ----- operations ------------------------------------------------------------ /** Place target virtual qubit in the zero state * @param[in,out] tensor the tensor object */ void initVirtualTarget(Tensor tensor, int virtualTargetIndex){ int vqIndex = virtualTargetIndex + tensor.numPq; printf("vqIndex: %d\n", vqIndex); Qureg qureg = tensor.qureg; long long int stateVecSize; long long int index; // dimension of the state vector // TODO: This won't work in parallel stateVecSize = 1LL << vqIndex; qreal *stateVecReal = qureg.stateVec.real; qreal *stateVecImag = qureg.stateVec.imag; # ifdef _OPENMP # pragma omp parallel \ default (none) \ shared (stateVecSize, stateVecReal, stateVecImag) \ private (index) # endif { # ifdef _OPENMP # pragma omp for schedule (static) # endif for (index=0; index<stateVecSize; index++) { stateVecReal[index+stateVecSize] = 0; stateVecImag[index+stateVecSize] = 0; } } } /** Initialize virtual qubit to |0> + |1> * NOTE: not (1/sqrt(2))(|0> + |1>) * @param[in,out] tensor the tensor object * @param[in] virtual qubit to initialize. Index is local to a tensor but includes all physical qubits in the tensor */ void initVirtualControl(Tensor tensor, int virtualControlIndex){ int vqIndex = virtualControlIndex + tensor.numPq; Qureg qureg = tensor.qureg; long long int stateVecSize; long long int index; // dimension of the state vector // TODO: This won't work in parallel stateVecSize = 1LL << vqIndex; qreal *stateVecReal = qureg.stateVec.real; qreal *stateVecImag = qureg.stateVec.imag; # ifdef _OPENMP # pragma omp parallel \ default (none) \ shared (stateVecSize, stateVecReal, stateVecImag) \ private (index) # endif { # ifdef _OPENMP # pragma omp for schedule (static) # endif for (index=0; index<stateVecSize; index++) { stateVecReal[index+stateVecSize] = stateVecReal[index]; stateVecImag[index+stateVecSize] = stateVecImag[index]; } } }
{ "alphanum_fraction": 0.6773544406, "avg_line_length": 30.6748971193, "ext": "c", "hexsha": "9c04570e25d0df05e260ec31f1e8ec3fe6cca076", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "aniabrown/QuEST-TN", "max_forks_repo_path": "TN/QuEST_tn.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_issues_repo_issues_event_max_datetime": "2021-03-01T14:44:40.000Z", "max_issues_repo_issues_event_min_datetime": "2020-02-06T07:02:40.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "aniabrown/QuEST-TN", "max_issues_repo_path": "TN/QuEST_tn.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "aniabrown/QuEST-TN", "max_stars_repo_path": "TN/QuEST_tn.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2099, "size": 7454 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/block/gsl_block.h> #define BASE_DOUBLE #include <gsl/templates_on.h> #include <gsl/block/fwrite_source.c> #include <gsl/block/fprintf_source.c> #include <gsl/templates_off.h> #undef BASE_DOUBLE
{ "alphanum_fraction": 0.7755905512, "avg_line_length": 25.4, "ext": "c", "hexsha": "38aee3fc0085763ec0a4632e2d1b3a04aa402f26", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_line_length": 37, "max_stars_count": null, "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/block/file.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 67, "size": 254 }
#pragma once #include "file_descriptor.h" #include <filesystem> #include <gsl/span> #include <random> namespace dogbox { inline void create_randomness(gsl::span<std::byte> const into) { file_descriptor const random = open_file_for_reading("/dev/urandom").value(); ptrdiff_t written = 0; while (written < into.size()) { size_t const reading = static_cast<size_t>(into.size() - written); ssize_t const read_result = read(random.handle, into.data() + written, reading); if (read_result < 0) { TO_DO(); } written += reading; } } }
{ "alphanum_fraction": 0.5754857997, "avg_line_length": 25.7307692308, "ext": "h", "hexsha": "390f56cbcd58f53383594df9b05a544a1c68f043", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-29T22:01:48.000Z", "max_forks_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "TyRoXx/dogbox", "max_forks_repo_path": "common/create_randomness.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_issues_repo_issues_event_max_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-02T20:36:02.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "TyRoXx/dogbox", "max_issues_repo_path": "common/create_randomness.h", "max_line_length": 92, "max_stars_count": null, "max_stars_repo_head_hexsha": "af9c7631f6f5a22a73fbd4a497a84ed75183c7d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "TyRoXx/dogbox", "max_stars_repo_path": "common/create_randomness.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 147, "size": 669 }
#include "jobqueue.h" #include "degnome.h" #include "fitfunc.h" #include "flagparse.c" #include <stdio.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include <limits.h> typedef struct JobData JobData; struct JobData { Degnome* child; Degnome* p1; Degnome* p2; }; void usage(void); void help_menu(void); int jobfunc(void* p, void* tdat); const char* usageMsg = "Usage: polygensim [-h] [-c chromosome_length] [-e mutation_effect]\n" "\t\t [-g num_generations] [-m mutation_rate]\n" "\t\t [-o crossover_rate] [-p population_size]\n" "\t\t [-t num_threads] [--seed rngseed]\n" "\t\t [--target hat_height target]\n" "\t\t [--sqrt | --linear | --close | --ceiling | --log]\n"; const char* helpMsg = "OPTIONS\n" "\t -c chromosome_length\n" "\t\t Set chromosome length for the current simulation.\n" "\t\t Default chromosome length is 10.\n\n" "\t -e mutation_effect\n" "\t\t Set how much a mutation will effect a gene on average.\n" "\t\t Default mutation effect is 2.\n\n" "\t -g num_generations\n" "\t\t Set how many generations this simulation will run for.\n" "\t\t Default number of generations is 1000.\n\n" "\t -h\t Display this help menu.\n\n" "\t -m mutation_rate\n" "\t\t Set the mutation rate for the current simulation.\n" "\t\t Default mutation rate is 1.\n\n" "\t -o crossover_rate\n" "\t\t Set the crossover rate for the current simulation.\n" "\t\t Default crossover rate is 2.\n\n" "\t -p population_size\n" "\t\t Set the population size for the current simulation.\n" "\t\t Default population size is 10.\n" "\t -t num_threads\n" "\t\t Select the number of threads to be used in the current run.\n" "\t\t Default is 0 (which will result in 3/4 of cores being used).\n" "\t\t Must be 1 if a seed is used in order to prevent race conditions.\n\n" "\t --seed rngseed\n" "\t\t Select the seed used by the RNG in the current run.\n" "\t\t Default seed is 0 (which will result in a random seed).\n\n" "\t --target hat_height target\n" "\t\t Sets the ideal hat height for the current simulation\n" "\t\t Used for fitness functions that have an \"ideal\" value.\n\n" "\t --sqrt\t\t fitness will be sqrt(hat_height)\n\n" "\t --linear\t fitness will be hat_height\n\n" "\t --close\t fitness will be (target - abs(target - hat_height))\n\n" "\t --ceiling\t fitness will quickly level off after passing target\n\n"; pthread_mutex_t seedLock = PTHREAD_MUTEX_INITIALIZER; unsigned long rngseed = 0; // there is no need for the line 'int chrom_size' as it is declared as a global variable in degnome.h int pop_size; int num_gens; int mutation_rate; int mutation_effect; int crossover_rate; int num_threads = 0; JobQueue* jq; void *ThreadState_new(void *notused); void ThreadState_free(void *rng); void *ThreadState_new(void *notused) { // Lock seed, initialize random number generator, increment seed, // and unlock. gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus); pthread_mutex_lock(&seedLock); gsl_rng_set(rng, rngseed); rngseed = (rngseed == ULONG_MAX ? 0 : rngseed + 1); pthread_mutex_unlock(&seedLock); return rng; } void ThreadState_free(void *rng) { gsl_rng_free((gsl_rng *) rng); } int jobfunc(void* p, void* tdat) { gsl_rng* rng = (gsl_rng*) tdat; JobData* data = (JobData*) p; //get data out Degnome_mate(data->child, data->p1, data->p2, rng, mutation_rate, mutation_effect, crossover_rate); //mate return 0; //exited without error } void usage(void) { fputs(usageMsg, stderr); exit(EXIT_FAILURE); } void help_menu(void) { fputs(helpMsg, stderr); exit(EXIT_FAILURE); } int main(int argc, char **argv) { int * flags = NULL; if (parse_flags(argc, argv, 1, &flags) == -1) { free(flags); usage(); } if (flags[2] == 1) { free(flags); help_menu(); } chrom_size = flags[6]; mutation_effect = flags[7]; num_gens = flags[8]; mutation_rate = flags[9]; crossover_rate = flags[10]; pop_size = flags[11]; num_threads = flags[12]; if(flags[13] == 0){ set_function("linear"); } else if(flags[13] == 1){ set_function("sqrt"); } else if(flags[13] == 2){ set_function("close"); } else if(flags[13] == 3){ set_function("ceiling"); } else if(flags[13] == 4){ set_function("log"); } target_num = flags[14]; if(flags[15] <= 0) { time_t currtime = time(NULL); // time unsigned long pid = (unsigned long) getpid(); // process id rngseed = currtime ^ pid; // random seed } else{ rngseed = flags[15]; } gsl_rng* rng = gsl_rng_alloc(gsl_rng_taus); // rand generator gsl_rng_set(rng, rngseed); free(flags); if (num_threads <= 0) { if (num_threads < 0) { #ifdef DEBUG_MODE fprintf(stderr, "Error invalid number of threads: %u\n", num_threads); #endif } num_threads = (3*getNumCores()/4); } #ifdef DEBUG_MODE fprintf(stderr, "Final number of threads: %u\n", num_threads); #endif Degnome* parents; Degnome* children; Degnome* temp; printf("%u, %u, %u\n", chrom_size, pop_size, num_gens); parents = malloc(pop_size*sizeof(Degnome)); children = malloc(pop_size*sizeof(Degnome)); for (int i = 0; i < pop_size; i++) { parents[i].dna_array = malloc(chrom_size*sizeof(double)); children[i].dna_array = malloc(chrom_size*sizeof(double)); parents[i].hat_size = 0; for (int j = 0; j < chrom_size; j++) { parents[i].dna_array[j] = (i+j); //children isn't initiilized parents[i].hat_size += (i+j); } } printf("Generation 0:\n"); for (int i = 0; i < pop_size; i++) { printf("Degnome %u\n", i); for (int j = 0; j < chrom_size; j++) { printf("%lf\t", parents[i].dna_array[j]); } printf("\nTOTAL HAT SIZE: %lg\n\n", parents[i].hat_size); } jq = JobQueue_new(num_threads, NULL, ThreadState_new, ThreadState_free); JobData* dat = malloc(pop_size*sizeof(JobData)); for (int i = 0; i < num_gens; i++) { double fit = get_fitness(parents[0].hat_size); double total_hat_size = fit; double cum_hat_size[pop_size]; cum_hat_size[0] = fit; for (int j = 1; j < pop_size; j++) { fit = get_fitness(parents[j].hat_size); total_hat_size += fit; cum_hat_size[j] = (cum_hat_size[j-1] + fit); } for (int j = 0; j < pop_size; j++) { int m, d; double win_m = gsl_rng_uniform(rng); win_m *= total_hat_size; double win_d = gsl_rng_uniform(rng); win_d *= total_hat_size; // printf("win_m:%lf, wind:%lf, max: %lf\n", win_m,win_d,total_hat_size); for (m = 0; cum_hat_size[m] < win_m; m++) { continue; } for (d = 0; cum_hat_size[d] < win_d; d++) { continue; } // printf("m:%u, d:%u\n", m,d); dat[j].child = (children + j); dat[j].p1 = (parents + m); dat[j].p2 = (parents + d); JobQueue_addJob(jq, jobfunc, dat + j); } JobQueue_waitOnJobs(jq); temp = children; children = parents; parents = temp; } JobQueue_noMoreJobs(jq); printf("Generation %u:\n", num_gens); for (int i = 0; i < pop_size; i++) { printf("Degnome %u\n", i); for (int j = 0; j < chrom_size; j++) { printf("%lf\t", parents[i].dna_array[j]); } printf("\nTOTAL HAT SIZE: %lg\n\n", parents[i].hat_size); } //free everything JobQueue_free(jq); free(dat); for (int i = 0; i < pop_size; i++) { free(parents[i].dna_array); free(children[i].dna_array); parents[i].hat_size = 0; } free(parents); free(children); gsl_rng_free (rng); }
{ "alphanum_fraction": 0.6262939959, "avg_line_length": 26.2857142857, "ext": "c", "hexsha": "4a78b2c653390f7ff4bc2b39b328cebc08c90666", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-27T23:28:50.000Z", "max_forks_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "masalemi/PopGenSim", "max_forks_repo_path": "src/polygensim.c", "max_issues_count": 27, "max_issues_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:56:03.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-17T20:12:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "masalemi/PopGenSim", "max_issues_repo_path": "src/polygensim.c", "max_line_length": 110, "max_stars_count": 3, "max_stars_repo_head_hexsha": "86bbd44f9ad6b588253b6115c7064e91c2d0d76f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "masalemi/PopGenSim", "max_stars_repo_path": "src/polygensim.c", "max_stars_repo_stars_event_max_datetime": "2019-02-01T18:53:36.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-14T20:45:40.000Z", "num_tokens": 2317, "size": 7728 }
#pragma once #include <memory> #include <gsl/gsl_rng.h> extern std::unique_ptr<gsl_rng, decltype(&gsl_rng_free)> rng;
{ "alphanum_fraction": 0.7438016529, "avg_line_length": 15.125, "ext": "h", "hexsha": "69d0ea2d37efb9e7cf3a0b9f627892f6f82ebd83", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_path": "MathEngine/Utils/Random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_path": "MathEngine/Utils/Random.h", "max_line_length": 61, "max_stars_count": null, "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_path": "MathEngine/Utils/Random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 34, "size": 121 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "arcana/type_traits.h" #include "arcana/utils/serialization/base_stream.h" #include "arcana/utils/serialization/serializable.h" #include <gsl/gsl> #include <memory> #include <type_traits> namespace mira { template<typename LambdaT> class binary_iterator { template<typename T> using is_serializable = std::is_base_of<serializable<std::remove_cv_t<T>>, T>; template<typename L> struct check_custom_iterator { template<typename T, typename = decltype(binary_iterate(instance_of<const T>(), instance_of<binary_iterator<LambdaT>>()))> static std::true_type test(T* = nullptr); static std::false_type test(...); }; template<typename T> using has_custom_iterator = decltype(check_custom_iterator<LambdaT>::test(&instance_of<T>())); template<typename T> using is_valid_pod = std::integral_constant<bool, !has_custom_iterator<T>::value && std::is_pod<std::decay_t<T>>::value && !std::is_pointer<std::decay_t<T>>::value>; public: template<typename... ArgTs> void iterate_all(ArgTs&&... args) { int unused[] = { (iterate(std::forward<ArgTs>(args)), 0)... }; (void)unused; } template<typename T> std::enable_if_t<has_custom_iterator<std::decay_t<T>>::value> iterate(const T& value) { static_assert(!is_valid_pod<T>::value, "we've got some overlap"); binary_iterate(value, *this); } template<typename T> std::enable_if_t<is_valid_pod<std::decay_t<T>>::value> iterate(const T& ptr) { static_assert(!has_custom_iterator<T>::value, "we've got some overlap"); stream{ *this }.write(ptr); } void iterate(const void* data, size_t size) { m_iter(data, size); } template<typename ItrT> void iterate(ItrT beg, ItrT end) { while (beg != end) { iterate(*beg); beg++; } } template<typename A, typename B> void iterate(const std::pair<A, B>& pair) { iterate(pair.first); iterate(pair.second); } template<typename T> void iterate(const std::shared_ptr<T>& ptr) { iterate(ptr.get()); } template<typename T, ptrdiff_t E = -1> void iterate(const gsl::span<T, E>& span) { iterate(span.begin(), span.end()); } template<typename T, typename D> void iterate(const std::unique_ptr<T, D>& ptr) { iterate(ptr.get()); } template<typename T> void iterate(const T* ptr) { if (!ptr) iterate((intptr_t)0); else iterate(*ptr); } template<typename T> void iterate(const serializable<T>& ptr) { stream s{ *this }; ptr.serialize(s); } template<typename ItrT> explicit binary_iterator(ItrT&& i) : m_iter{ std::forward<ItrT>(i) } {} LambdaT& iterator() { return m_iter; } const LambdaT& iterator() const { return m_iter; } private: struct stream : public base_stream { template<typename T> void write(const T& obj) { m_itr.iterate(&obj, sizeof(T)); } template<typename T> void write(const T* obj, size_t N) { m_itr.iterate(obj, N * sizeof(T)); } stream(binary_iterator<LambdaT>& itr) : m_itr{ itr } {} private: binary_iterator<LambdaT>& m_itr; }; LambdaT m_iter; }; template<typename LambdaT> binary_iterator<std::decay_t<LambdaT>> make_binary_iterator(LambdaT&& lambda) { return binary_iterator<std::decay_t<LambdaT>>{ std::forward<LambdaT>(lambda) }; } } namespace std { template<typename Iter> void binary_iterate(const std::string& str, mira::binary_iterator<Iter>& iter) { iter.iterate(str.data(), str.size()); } template<typename T, typename Iter> void binary_iterate(const std::vector<T>& vec, mira::binary_iterator<Iter>& iter) { iter.iterate(vec.size()); iter.iterate(vec.begin(), vec.end()); } template<typename IterT, typename FirstT, typename SecondT> void binary_iterate(const std::pair<FirstT, SecondT>& data, mira::binary_iterator<IterT>& itr) { itr.iterate_all(data.first, data.second); } template<typename Iter, typename T> void binary_iterate(const std::shared_ptr<T>& ptr, mira::binary_iterator<Iter>& iter) { iter.iterate(ptr.get()); } template<typename Iter, typename T> void binary_iterate(const std::unique_ptr<T>& ptr, mira::binary_iterator<Iter>& iter) { iter.iterate(ptr.get()); } } namespace gsl { template<typename Iter, typename T, ptrdiff_t E = -1> void binary_iterate(const gsl::span<T, E>& span, mira::binary_iterator<Iter>& iter) { iter.iterate(span.begin(), span.end()); } }
{ "alphanum_fraction": 0.5417923691, "avg_line_length": 26.961722488, "ext": "h", "hexsha": "8f8b1d129cb15b6cc04258ee8f87db0ca343899a", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_line_length": 107, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/binary_iterator.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 1230, "size": 5635 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #ifdef _WIN32 #include "blas.c" #else #include "blas.c" // #include <cblas.h> #endif #include <moss.h> #include <objects/string.h> #include <objects/list.h> #include <modules/bs.h> #include <modules/la.h> double mf_float(mt_object* x, int* e); extern mt_table* mv_type_array; void mf_array_delete(mt_array* a){ if(a->data->refcount==1){ mf_free(a->data); }else{ a->data->refcount--; } mf_free(a); } void mf_array_dec_refcount(mt_array* a){ if(a->refcount==1){ mf_array_delete(a); }else{ a->refcount--; } } static mt_array* mf_new_array(long size, int type){ mt_array* a = mf_malloc(sizeof(mt_array)); if(type==mv_array_float){ a->data = mf_malloc(sizeof(mt_array_data)+size*sizeof(double)); }else{ abort(); } a->data->refcount = 1; a->data->type = type; a->base = a->data->a; a->refcount = 1; a->size = size; return a; } static mt_array* mf_array_copy(mt_array* a){ mt_array* b; if(a->n==2){ if(a->plain){ goto plain; }else{ unsigned long m=a->shape[0]; unsigned long n=a->shape[1]; long si=a->stride[0]; long sj=a->stride[1]; b = mf_new_array(m*n,mv_array_float); b->n = a->n; b->plain = 1; b->shape[0] = m; b->shape[1] = n; b->stride[0] = 1; b->stride[1] = m; double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj=m*j; sjj=sj*j; for(i=0; i<m; i++){ pb[i+mj]=pa[si*i+sjj]; } } return b; } }else if(a->n==1){ b = mf_new_array(a->shape[0],mv_array_float); b->n = 1; b->shape[0] = a->shape[0]; b->stride[0] = 1; cblas_dcopy(a->shape[0],(double*)a->base,a->stride[0],(double*)b->base,1); return b; }else{ if(a->plain) goto plain; abort(); } plain: b = mf_new_array(a->size,mv_array_float); b->n = a->n; b->plain = 1; unsigned long i; for(i=0; i<a->n; i++){ b->shape[i] = a->shape[i]; b->stride[i] = a->stride[i]; } cblas_dcopy(a->size,(double*)a->base,1,(double*)b->base,1); return b; } void mf_ensure_plain(mt_array* a){ if(a->n==2){ if(a->plain) return; mt_array_data* data = mf_malloc(sizeof(mt_array_data)+a->size*sizeof(double)); data->refcount = 1; data->type = mv_array_float; double* pa = (double*)a->base; double* pb = (double*)data->a; unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; long si = a->stride[0]; long sj = a->stride[1]; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj = m*j; sjj = sj*j; for(i=0; i<m; i++){ pb[i+mj] = pa[si*i+sjj]; } } if(a->data->refcount==1){ mf_free(a->data); }else{ a->data->refcount--; } a->stride[0] = 1; a->stride[1] = m; a->data = data; a->base = data->a; a->plain = 1; }else if(a->n==1){ abort(); }else{ if(a->plain) return; abort(); } } static mt_array* mf_array_map_dd(mt_array* a, double(*f)(double)){ mt_array* b; if(a->n==2){ if(a->plain){ goto plain; }else{ unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; long si = a->stride[0]; long sj = a->stride[1]; b = mf_new_array(m*n,mv_array_float); b->n = a->n; b->plain = 1; b->shape[0] = m; b->shape[1] = n; b->stride[0] = 1; b->stride[1] = m; double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long i,j,mj; long sjj; for(j=0; j<n; j++){ mj = m*j; sjj = sj*j; for(i=0; i<m; i++){ pb[i+mj] = f(pa[si*i+sjj]); } } return b; } }else if(a->n==1){ unsigned long n=a->shape[0]; b = mf_new_array(n,mv_array_float); b->n = 1; b->shape[0] = n; b->stride[0] = 1; long s = a->stride[0]; unsigned long k; double* pa = (double*)a->base; double* pb = (double*)b->base; for(k=0; k<n; k++){ pb[k] = f(pa[k*s]); } return b; }else{ if(a->plain) goto plain; abort(); } plain: b = mf_new_array(a->size,mv_array_float); b->n = a->n; b->plain = 1; unsigned long i; for(i=0; i<a->n; i++){ b->shape[i] = a->shape[i]; b->stride[i] = a->stride[i]; } double* pa = (double*)a->base; double* pb = (double*)b->base; unsigned long size = a->size; unsigned long k; for(k=0; k<size; k++){ pb[k] = f(pa[k]); } return b; } long mf_array_size(mt_array* a){ long p; unsigned long k; switch(a->n){ case 1: return a->shape[0]; case 2: return a->shape[0]*a->shape[1]; default: p=1; for(k=0; k<a->n; k++){ p = p*a->shape[k]; } return p; } } mt_array* mf_array(long size, mt_object* v){ mt_array* a; if(size>0 && v[0].type==mv_list){ long i,j; mt_list* list = (mt_list*)v[0].value.p; long n = list->size; a = mf_new_array(size*n,mv_array_float); a->n = 2; a->shape[0] = size; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = size; a->plain = 1; double* b = (double*)a->base; int e=0; for(i=0; i<size; i++){ if(v[i].type!=mv_list) abort(); list = (mt_list*)v[i].value.p; if(list->size!=n) abort(); for(j=0; j<n; j++){ b[i+size*j] = mf_float(list->a+j,&e); if(e) abort(); } } }else{ a = mf_new_array(size,mv_array_float); a->n = 1; a->shape[0] = size; a->stride[0] = 1; long i; double* b = (double*)a->base; int e=0; for(i=0; i<size; i++){ b[i] = mf_float(v+i,&e); } } return a; } int la_array(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"array"); return 1; } if(v[1].type!=mv_list){ mf_type_error1("in array(a): a (type: %s) is not a list.",v+1); return 1; } mt_list* list = (mt_list*)v[1].value.p; mt_array* a = mf_array(list->size, list->a); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } int la_vector(mt_object* x, int argc, mt_object* v){ mt_array* a = mf_array(argc,v+1); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } int la_matrix(mt_object* x, int argc, mt_object* v){ mt_array* a = mf_array(argc,v+1); if(a==NULL) return 1; if(a->n==1){ a->n = 2; unsigned long size = a->shape[0]; a->shape[0] = size; a->shape[1] = 1; a->stride[0] = 1; a->stride[1] = size; a->plain = 0; } x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static void vector_str(mt_bs* bs, mt_array* T){ char buffer[100]; unsigned long i; double* a = (double*)T->base; unsigned long size = T->shape[0]; long step = T->stride[0]; mf_bs_push_cstr(bs,"["); for(i=0; i<size; i++){ snprintf(buffer,100,i==0?"%.4g":", %.4g",a[step*i]); mf_bs_push_cstr(bs,buffer); } mf_bs_push_cstr(bs,"]"); } static void matrix_str(mt_bs* bs, mt_array* T){ char buffer[100]; unsigned long i,j; double* a = (double*)T->base; unsigned long m,n,is,js; m = T->shape[0]; n = T->shape[1]; is = T->stride[0]; js = T->stride[1]; int max = 0; int size; for(i=0; i<m; i++){ for(j=0; j<n; j++){ size = snprintf(buffer,100,"%.4g",a[i*is+j*js]); if(size>max) max=size; } } mf_bs_push_cstr(bs,"["); for(i=0; i<m; i++){ mf_bs_push_cstr(bs,i==0? "[": ",\n ["); for(j=0; j<n; j++){ snprintf(buffer,100,j==0?"%*.4g":", %*.4g",max,a[i*is+j*js]); mf_bs_push_cstr(bs,buffer); } mf_bs_push_cstr(bs,"]"); } mf_bs_push_cstr(bs,"]"); } static int array_str(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.str"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.str(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* T = (mt_array*)v[0].value.p; mt_bs bs; mf_bs_init(&bs); if(T->n==1){ vector_str(&bs,T); }else if(T->n==2){ matrix_str(&bs,T); }else{ abort(); } x->type = mv_string; x->value.p = (mt_basic*)mf_str_new(bs.size,(const char*)bs.a); mf_free(bs.a); return 0; } static int array_list(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.list"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.list(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* T = (mt_array*)v[0].value.p; mt_list* list = mf_raw_list(T->size); unsigned long i; double* a = (double*)T->base; unsigned long size = T->shape[0]; long step = T->stride[0]; for(i=0; i<size; i++){ list->a[i].type = mv_float; list->a[i].value.f = a[step*i]; } x->type = mv_list; x->value.p = (mt_basic*)list; return 0; } double addc; double add(double x){ return x+addc; } double subc; double sub(double x){ return x-subc; } static int array_add(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.add"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a+b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* c; if(v[1].type!=mv_array){ int e = 0; addc = mf_float(&v[1],&e); if(e){ mf_type_error1("in a+r: cannot convert r (type: %s) to float.",&v[1]); return 1; } c = mf_array_map_dd(a,add); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } mt_array* b = (mt_array*)v[1].value.p; if(a->n!=b->n){ mf_value_error("value error in a+b: a and b have unequal order."); return 1; } if(a->n==1){ unsigned long size=a->shape[0]; if(size!=b->shape[0]){ mf_value_error("Value error in a+b: a and b have unequal shape."); return 1; } c = mf_new_array(size,mv_array_float); c->n = 1; c->stride[0] = 1; c->shape[0] = size; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1); cblas_daxpy(size,1,(double*)b->base,b->stride[0],(double*)c->base,1); }else{ unsigned long i; for(i=0; i<a->n; i++){ if(a->shape[i]!=b->shape[i]) abort(); } c = mf_array_copy(a); mf_ensure_plain(b); cblas_daxpy(c->size,1,(double*)b->base,1,(double*)c->base,1); } x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } static int array_radd(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.radd"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in r*a: a (type: %s) is not an array.",&v[1]); return 1; } int e = 0; addc = mf_float(&v[0],&e); if(e){ mf_type_error1("in r+a: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[1].value.p; mt_array* y = mf_array_map_dd(a,add); if(y==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)y; return 0; } static int array_sub(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.sub"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a-b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* c; if(v[1].type!=mv_array){ int e = 0; subc = mf_float(&v[1],&e); if(e){ mf_type_error1("in a-r: cannot convert r (type: %s) to float.",&v[1]); return 1; } c = mf_array_map_dd(a,sub); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } mt_array* b = (mt_array*)v[1].value.p; if(a->n==1){ unsigned long size = a->shape[0]; if(size!=b->shape[0]){ mf_value_error("Value error in a-b: a and b have unequal shape."); return 1; } c = mf_new_array(size,mv_array_float); c->n = 1; c->shape[0] = size; c->stride[0] = 1; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1); cblas_daxpy(size,-1,(double*)b->base,b->stride[0],(double*)c->base,1); }else{ unsigned long i; for(i=0; i<a->n; i++){ if(a->shape[i]!=b->shape[i]) abort(); } c = mf_array_copy(a); mf_ensure_plain(b); cblas_daxpy(c->size,-1,(double*)b->base,1,(double*)c->base,1); } x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } static mt_array* mf_array_scal(double r, mt_array* a){ mt_array* b; if(a->n==1){ unsigned long size = a->shape[0]; b = mf_new_array(size,mv_array_float); b->n = 1; b->shape[0] = size; b->stride[0] = 1; cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)b->base,1); }else{ b = mf_array_copy(a); } cblas_dscal(b->size,r,(double*)b->base,1); return b; } static mt_array* array_mpy_array(mt_array* a, mt_array* b){ if(b->n==1){ unsigned long m = a->shape[0]; unsigned long n = a->shape[1]; if(n!=b->shape[0]){ mf_value_error("Value error in A*x: shape does not match."); return NULL; } if(a->stride[0]!=1){ mf_ensure_plain(a); } mt_array* c = mf_new_array(m,mv_array_float); c->n = 1; c->shape[0] = m; c->stride[0] = 1; cblas_dgemv(CblasColMajor,CblasNoTrans,m,n,1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[0], 0,(double*)c->base,1 ); return c; }else if(b->n==2){ if(a->n==2){ if(a->shape[1]!=b->shape[0]){ mf_value_error("Value error in A*B: incompatible matrices."); return NULL; } if(a->stride[0]!=1){ mf_ensure_plain(a); } if(b->stride[0]!=1){ mf_ensure_plain(b); } unsigned long m = a->shape[0]; unsigned long k = a->shape[1]; unsigned long n = b->shape[1]; mt_array* c = mf_new_array(m*n,mv_array_float); c->n = 2; c->shape[0] = m; c->shape[1] = n; c->stride[0] = 1; c->stride[1] = m; c->plain = 1; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[1], 0, (double*)c->base, m ); return c; }else{ abort(); } }else{ abort(); } } static mt_array* matrix_identity(unsigned long n){ mt_array* a = mf_new_array(n*n,mv_array_float); a->n = 2; a->plain = 1; a->shape[0] = n; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = n; double* b = (double*)a->base; unsigned long i,j,nj; for(j=0; j<n; j++){ nj = n*j; for(i=0; i<n; i++){ b[i+nj] = i==j? 1: 0; } } return a; } static mt_array* square_matrix_mpy(mt_array* a, mt_array* b){ if(a->stride[0]!=1){ mf_ensure_plain(a); } if(b->stride[0]!=1){ mf_ensure_plain(b); } unsigned long n = a->shape[0]; mt_array* c = mf_new_array(n*n,mv_array_float); c->n = 2; c->shape[0] = n; c->shape[1] = n; c->stride[0] = 1; c->stride[1] = n; c->plain = 1; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1, (double*)a->base, a->stride[1], (double*)b->base, b->stride[1], 0, (double*)c->base, n ); return c; } static mt_array* square_matrix_pow(mt_array* a, unsigned long n){ if(n==0){ return matrix_identity(a->shape[0]); } mt_array *p,*h; p = mf_array_copy(a); a = p; a->refcount++; n--; while(n){ if(n&1){ h = p; p = square_matrix_mpy(p,a); mf_array_dec_refcount(h); } n>>=1; if(n==0) break; h = a; a = square_matrix_mpy(a,a); mf_array_dec_refcount(h); } mf_array_dec_refcount(a); return p; } static int array_mul(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.mul"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a*b: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* b; double r; if(v[1].type==mv_array){ b=(mt_array*)v[1].value.p; if(a->n==2){ if(b->n==2 && a->shape[0]==1 && b->shape[1]==1){ if(a->shape[1]!=b->shape[0]){ mf_value_error("Value error in a*b: incompatible matrices."); return 1; } // todo: strides r = cblas_ddot(a->shape[1], (double*)a->base,a->stride[1], (double*)b->base,b->stride[0] ); x->type = mv_float; x->value.f = r; return 0; } mt_array* c = array_mpy_array(a,b); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } if(a->n!=1){ mf_value_error("Value error in a*b: a and b have incompatible shape."); return 1; } if(b->n==2){ mt_array* c = array_mpy_array(b,a); if(c==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)c; return 0; } if(a->shape[0]!=b->shape[0]){ mf_value_error("Value error in a*b: a and b have unequal shape."); return 1; } r = cblas_ddot(a->shape[0], (double*)a->base,a->stride[0], (double*)b->base,b->stride[0] ); x->type = mv_float; x->value.f = r; return 0; }else{ int e = 0; r = mf_float(&v[1],&e); if(e){ mf_type_error1("in a*r: cannot convert r (type: %s) to float.",&v[1]); return 1; } x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(r,a); return 0; } } static int array_pow(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.pow"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a^n: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; double r; if(a->n!=1){ if(a->n==2 && v[1].type==mv_int){ long n = v[1].value.i; if(a->shape[0]!=a->shape[1]){ mf_value_error("Value error in A^n: A is not a square matrix"); return 1; } x->type = mv_array; x->value.p = (mt_basic*)square_matrix_pow(a,(unsigned long)n); return 0; } mf_value_error("Value error in a^n: a is not a vector."); return 1; } r = cblas_ddot(a->shape[0], (double*)a->base,a->stride[0], (double*)a->base,a->stride[0] ); x->type = mv_float; if(v[1].type==mv_int && v[1].value.i==2){ x->value.f = r; }else{ int e = 0; double n = mf_float(&v[1],&e); if(e){ mf_type_error1("in a^n: cannot convert n (type: %s) to float.",&v[1]); return 1; } x->value.f = pow(r,n); } return 0; } static int array_rmul(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.rmul"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in r*a: a (type: %s) is not an array.",&v[1]); return 1; } int e=0; double r = mf_float(&v[0],&e); if(e){ mf_type_error1("in r*a: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[1].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(r,a);; return 0; } static int array_neg(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"Array.neg"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in -a: a (type: %s) is not an array.",&v[1]); return 1; } mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(-1,a);; return 0; } static int array_div(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"Array.div"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a/r: a (type: %s) is not an array.",&v[1]); return 1; } int e = 0; double r = mf_float(&v[1],&e); if(e){ mf_type_error1("in a/r: cannot convert r (type: %s) to float.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_scal(1/r,a);; return 0; } static int array_T(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"array.type.T"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.T(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; if(a->n==2){ mt_array* b = mf_malloc(sizeof(mt_array)); b->refcount = 1; b->n = 2; a->data->refcount++; b->data = a->data; b->base = a->base; b->size = a->size; b->plain = 0; b->shape[0] = a->shape[1]; b->shape[1] = a->shape[0]; b->stride[0] = a->stride[1]; b->stride[1] = a->stride[0]; x->type = mv_array; x->value.p = (mt_basic*)b; }else{ a->refcount++; x->type = mv_array; x->value.p = (mt_basic*)a; } return 0; } static int array_plain(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array) abort(); mt_array* a = (mt_array*)v[0].value.p; mf_ensure_plain(a); a->refcount++; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static int array_copy(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array) abort(); mt_array* a = (mt_array*)v[0].value.p; x->type = mv_array; x->value.p = (mt_basic*)mf_array_copy(a); return 0; } static mt_array* vector_slice(mt_array* a, mt_range* r){ long i,j; if(r->a.type!=mv_int || r->b.type!=mv_int){ mf_type_error("Type error in a[r]: r is not an integer range."); return NULL; } i = r->a.value.i; j = r->b.value.i; unsigned long n = a->shape[0]; if(i<0 || j<0){ mf_value_error("Value error in a[r]: range with negative values."); return NULL; } if((unsigned long)i>=n || (unsigned long)j>=n){ mf_value_error("Value error in a[r]: range is out of bounds."); return NULL; } mt_array* b = mf_malloc(sizeof(mt_array)); b->refcount = 1; b->size = a->size; a->data->refcount++; b->data = a->data; a->data = b->data; b->n = 1; b->base = (unsigned char*)((double*)a->base+a->stride[0]*i); b->shape[0] = j-i+1; b->stride[0] = a->stride[0]; return b; } static int array_get(mt_object* x, int argc, mt_object* v){ if(v[0].type!=mv_array){ mf_type_error1("in a[i]: a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; if(argc==1){ if(a->n!=1){ mf_value_error("Value error in a[i]: a is not a vector."); return 1; } if(v[1].type!=mv_int){ if(v[1].type==mv_range){ mt_array* b = vector_slice(a,(mt_range*)v[1].value.p); if(b==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)b; return 0; } mf_type_error1("in a[i]: i (type: %s) is not an integer.",&v[1]); return 1; } long index = v[1].value.i; unsigned long n = a->shape[0]; if(index<0 || (unsigned long)index>=n){ mf_value_error("Value error in a[i]: i is out of bounds."); return 1; } double* b = (double*)a->base; double t = b[index*a->stride[0]]; x->type = mv_float; x->value.f = t; return 0; }else{ mf_argc_error(argc,1,1,"Array.get"); return 1; } } static int la_idm(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"idm"); return 1; } if(v[1].type!=mv_int){ mf_type_error1("in idm(n): n (type: %s) is not an integer.",v+1); return 1; } long n = v[1].value.i; x->type = mv_array; x->value.p = (mt_basic*)matrix_identity(n); return 0; } static mt_array* diag(mt_array* v){ if(v->n!=1){ mf_value_error("Value error in diag(v): v is not a vector."); return NULL; } unsigned long n = v->shape[0]; mt_array* a = mf_new_array(n*n,mv_array_float); a->n = 2; a->plain = 1; a->shape[0] = n; a->shape[1] = n; a->stride[0] = 1; a->stride[1] = n; double* b = (double*)a->base; double* vb = (double*)v->base; long vs = v->stride[0]; unsigned long i,j,nj; for(j=0; j<n; j++){ nj = n*j; for(i=0; i<n; i++){ b[i+nj] = i==j? vb[i*vs]: 0; } } return a; } static int la_diag(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"diag"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in diag(a): a is not an array.",v+1); return 1; } mt_array* u = (mt_array*)v[1].value.p; mt_array* a = diag(u); if(a==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)a; return 0; } static mt_array* diag_slice(mt_array* a){ if(a->n!=2 || a->shape[0]!=a->shape[1]){ mf_value_error("Value error in a.diag(): a is not an quadratic matrix."); return NULL; } if(a->stride[1]!=1){ mf_ensure_plain(a); } mt_array* v = mf_malloc(sizeof(mt_array)); v->refcount = 1; v->n = 1; a->data->refcount++; v->data = a->data; v->base = a->base; v->shape[0] = a->shape[0]; v->stride[0] = (a->shape[0]+1)*a->stride[0]; return v; } static int array_diag(mt_object* x, int argc, mt_object* v){ if(argc!=0){ mf_argc_error(argc,0,0,"diag"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.diag(): a (type: %s) is not an array.",&v[0]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_array* u = diag_slice(a); if(u==NULL) return 1; x->type = mv_array; x->value.p = (mt_basic*)u; return 0; } int mf_array_map(mt_array* a, mt_function* f){ mt_object argv[2]; argv[0].type = mv_null; double* ba = (double*)a->base; long size = a->size; long i; mt_object x; int e = 0; for(i=0; i<size; i++){ argv[1].type = mv_float; argv[1].value.f = ba[i]; if(mf_call(f,&x,1,argv)){ mf_traceback("map"); return 1; } ba[i] = mf_float(&x,&e); if(e){ mf_type_error1("in a.map(f): cannot convert f(a[k]) (type: %s) to float.",&x); return 1; } } return 0; } static int array_map(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"map"); return 1; } if(v[0].type!=mv_array){ mf_type_error1("in a.map(f): a (type: %s) is not an array.",&v[0]); return 1; } if(v[1].type!=mv_function){ mf_type_error1("in a.map(f): f (type: %s) is not a function.",&v[1]); return 1; } mt_array* a = (mt_array*)v[0].value.p; mt_function* f = (mt_function*)v[1].value.p; mt_array* b = mf_array_copy(a); if(mf_array_map(b,f)) return 1; x->type = mv_array; x->value.p = (mt_basic*)b; return 0; } static int mf_trace(mt_object* x, mt_array* a){ if(a->n!=2 || a->shape[0]!=a->shape[1]){ mf_value_error("Value error in trace(a): a is not a quadratic matrix."); return 1; } double s = 0; long n = a->shape[0]; double* ba = (double*)a->base; long i,m; m = a->stride[0]+a->stride[1]; for(i=0; i<n; i++){ s+=ba[i*m]; } x->type = mv_float; x->value.f = s; return 0; } static int la_trace(mt_object* x, int argc, mt_object* v){ if(argc!=1){ mf_argc_error(argc,1,1,"trace"); return 1; } if(v[1].type!=mv_array){ mf_type_error1("in la.trace(a): a (type: %s) is not an array.",&v[1]); return 1; } mt_array* a = (mt_array*)v[1].value.p; if(mf_trace(x,a)) return 1; return 0; } mt_table* mf_la_load(){ mt_map* m = mv_type_array->m; mf_insert_function(m,0,0,"str",array_str); mf_insert_function(m,0,0,"list",array_list); mf_insert_function(m,1,1,"add",array_add); mf_insert_function(m,1,1,"radd",array_radd); mf_insert_function(m,1,1,"sub",array_sub); mf_insert_function(m,1,1,"mul",array_mul); mf_insert_function(m,1,1,"rmul",array_rmul); mf_insert_function(m,0,0,"neg",array_neg); mf_insert_function(m,1,1,"div",array_div); mf_insert_function(m,1,1,"pow",array_pow); mf_insert_function(m,1,-1,"get",array_get); mf_insert_function(m,0,0,"T",array_T); mf_insert_function(m,0,0,"plain",array_plain); mf_insert_function(m,0,0,"copy",array_copy); mf_insert_function(m,0,0,"diag",array_diag); mf_insert_function(m,1,1,"map",array_map); mt_table* la = mf_table(NULL); la->name = mf_cstr_to_str("module la"); la->m = mf_empty_map(); m = la->m; mf_insert_function(m,1,1,"array",la_array); mf_insert_function(m,1,1,"vector",la_vector); mf_insert_function(m,1,1,"matrix",la_matrix); mf_insert_function(m,1,1,"idm",la_idm); mf_insert_function(m,1,1,"diag",la_diag); mf_insert_function(m,1,1,"trace",la_trace); m->frozen = 1; return la; }
{ "alphanum_fraction": 0.4949240972, "avg_line_length": 26.4260797342, "ext": "c", "hexsha": "86ff9781726f1319affde781c1b59221b6d4f1e3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "JohnBSmith/moss-c", "max_forks_repo_path": "modules/la/la.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "JohnBSmith/moss-c", "max_issues_repo_path": "modules/la/la.c", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "JohnBSmith/moss-c", "max_stars_repo_path": "modules/la/la.c", "max_stars_repo_stars_event_max_datetime": "2020-06-29T20:07:03.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-29T20:07:03.000Z", "num_tokens": 10255, "size": 31817 }
/** * @file batchg_zgemv.c * * Part of API test for Batched BLAS routines. * * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-06-01 * * @precisions normal z -> c d s * **/ #include <cblas.h> #include "bblas.h" #define COMPLEX void batch_zgemv( const enum BBLAS_TRANS *trans, const int *m, const int *n, const BBLAS_Complex64_t *alpha, const BBLAS_Complex64_t **arrayA, const int *lda, const BBLAS_Complex64_t **arrayx, const int *incx, const BBLAS_Complex64_t *beta, BBLAS_Complex64_t **arrayy, const int *incy, const int batch_count, const enum BBLAS_OPTS batch_opts, int* info) { /* Local variables */ char func_name[15] = "batch_zgemv"; /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if (batch_opts == BBLAS_FIXED) { /* Call fixed size code */ batchf_zgemv(trans[0], m[0], n[0], alpha[0], arrayA, lda[0], arrayx, incx[0], beta[0], arrayy, incy[0], batch_count, info[0]); } else if (batch_opts == BBLAS_VARIABLE) { /* Call variable size code */ batchv_zgemv(trans, m, n, alpha, arrayA, lda, arrayx, incx, beta, arrayy, incy, batch_count, info); } else { xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1); } }
{ "alphanum_fraction": 0.6342899191, "avg_line_length": 19.9852941176, "ext": "c", "hexsha": "87b7ab7355a35a6a4c485b5f4c1849221c5904f0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_path": "src/batch_zgemv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_path": "src/batch_zgemv.c", "max_line_length": 57, "max_stars_count": 3, "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_path": "src/batch_zgemv.c", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "num_tokens": 450, "size": 1359 }
#include <stdio.h> #include "sqlite3.h" #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> // returned row static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %s\t", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } // create test_int table in database void create_int_tables(sqlite3 *db) { int r; char *err = 0; r = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS test_int (id INTEGER PRIMARY KEY, uniform INTEGER, normal5 INTEGER, normal20 INTEGER, t20 INTEGER)", callback, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } } // create test table in database void create_tables(sqlite3 *db) { int r; char *err = 0; r = sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, uniformi INTEGER, normali5 INTEGER, normali20 INTEGER, uniformf FLOAT, normalf5 FLOAT, normalf20 FLOAT)", callback, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } } // insert rows into test with varying random distributions void insert_data(sqlite3 *db, int rows, gsl_rng *ran) { char* err = 0; int i; int r; r = sqlite3_exec(db, "PRAGMA synchronous = 0", NULL, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } fprintf(stderr, "executed pragma\n"); r = sqlite3_exec(db, "BEGIN TRANSACTION", NULL, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } fprintf(stderr, "started transaction\n"); sqlite3_stmt *stmt; sqlite3_prepare_v2(db, "INSERT INTO test (id, uniformi, normali5, normali20, uniformf, normalf5, normalf20) VALUES (?,?,?,?,?,?,?)", 512, &stmt, 0); for(i = 0; i < rows; i++) { sqlite3_bind_int(stmt, 1, i); sqlite3_bind_int(stmt, 2, (int)gsl_ran_flat(ran, -100, 100)); sqlite3_bind_int(stmt, 3, (int)gsl_ran_gaussian(ran, 5)); sqlite3_bind_int(stmt, 4, (int)gsl_ran_gaussian(ran, 20)); sqlite3_bind_int(stmt, 5, (float)gsl_ran_flat(ran, -100, 100)); sqlite3_bind_int(stmt, 6, (float)gsl_ran_gaussian(ran, 5)); sqlite3_bind_int(stmt, 7, (float)gsl_ran_gaussian(ran, 20)); int r = sqlite3_step(stmt); if(r != SQLITE_DONE && r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); sqlite3_free(err); return; } sqlite3_reset(stmt); if(i % 10000 == 0) printf("%i\n", i); } sqlite3_finalize(stmt); r=sqlite3_exec(db, "CREATE TEMPORARY TABLE tmp AS SELECT * FROM test", 0, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } r=sqlite3_exec(db, "UPDATE tmp SET id = NULL;", 0, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } for(int i=0;i<24;i++){ r=sqlite3_exec(db, "INSERT INTO test SELECT * FROM tmp;", 0, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } } r=sqlite3_exec(db, "DROP TABLE tmp;", 0, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } r=sqlite3_exec(db, "COMMIT", 0, 0, &err); if(r != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", err); sqlite3_free(err); } } int main(int argc, char **argv){ sqlite3 *db; char *zErrMsg = 0; int rc; if(argc != 2) { fprintf(stderr, "%s <database name>\n", argv[0]); exit(1); } const gsl_rng_type *type; gsl_rng *ran; type = gsl_rng_ranlxd2; ran = gsl_rng_alloc(type); gsl_rng_set(ran, time(0)); rc = sqlite3_open(argv[1], &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); exit(1); } create_tables(db); fprintf(stderr, "tables created\n"); insert_data(db, 100000, ran); if(rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); gsl_rng_free(ran); return 0; }
{ "alphanum_fraction": 0.6422804013, "avg_line_length": 22.456043956, "ext": "c", "hexsha": "d9fe652049d60d38988983be2b08c27463e394f5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "abbc6e5ca9f083c9062f6ebb9af01dfda593c811", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mehrdadnikbakhtjam/sphyraena-extension", "max_forks_repo_path": "db/gendb-ext.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abbc6e5ca9f083c9062f6ebb9af01dfda593c811", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mehrdadnikbakhtjam/sphyraena-extension", "max_issues_repo_path": "db/gendb-ext.c", "max_line_length": 185, "max_stars_count": null, "max_stars_repo_head_hexsha": "abbc6e5ca9f083c9062f6ebb9af01dfda593c811", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mehrdadnikbakhtjam/sphyraena-extension", "max_stars_repo_path": "db/gendb-ext.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1353, "size": 4087 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <opencv2\core\core.hpp> #include <opencv2\features2d\features2d.hpp> #include <utility> #include <gsl\gsl> #include <vector> namespace mage { class CameraCalibration; struct Projection { cv::Point2f Point; float Distance; }; void ProjectPoints(const gsl::span<const cv::Point3f>& points3D, const cv::Matx34f& cameraPose, const cv::Matx33f& calibrationMatrix, std::vector<Projection>& points2D); Projection ProjectUndistorted(const cv::Matx34f& viewMatrix, const cv::Matx33f& calibration, const cv::Point3f& world); Projection ProjectDistorted(const CameraCalibration& cameraCalibration, const cv::Matx34f& viewMatrix, const cv::Point3f& world); std::vector<cv::Point2f> ProjectDistorted( const mage::CameraCalibration& calibration, const cv::Matx34f& viewMatrix, gsl::span<const cv::Vec3f> points3D); }
{ "alphanum_fraction": 0.7193877551, "avg_line_length": 29.696969697, "ext": "h", "hexsha": "b0982ee3c894ef7b0543c4b2d5b1e30705b7a721", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Tracking/Reprojection.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Tracking/Reprojection.h", "max_line_length": 173, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Tracking/Reprojection.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 259, "size": 980 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_filter.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> int main(void) { const size_t N = 1000; /* length of time series */ const size_t K = 61; /* window size */ const double alpha = 3.0; /* Gaussian kernel has +/- 3 standard deviations */ gsl_vector *x = gsl_vector_alloc(N); /* input vector */ gsl_vector *y = gsl_vector_alloc(N); /* filtered output vector */ gsl_vector *dy = gsl_vector_alloc(N); /* first derivative filtered vector */ gsl_vector *d2y = gsl_vector_alloc(N); /* second derivative filtered vector */ gsl_rng *r = gsl_rng_alloc(gsl_rng_default); gsl_filter_gaussian_workspace *gauss_p = gsl_filter_gaussian_alloc(K); size_t i; /* generate input signal */ for (i = 0; i < N; ++i) { double xi = (i > N / 2) ? 0.5 : 0.0; double ei = gsl_ran_gaussian(r, 0.1); gsl_vector_set(x, i, xi + ei); } /* apply filters */ gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha, 0, x, y, gauss_p); gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha, 1, x, dy, gauss_p); gsl_filter_gaussian(GSL_FILTER_END_PADVALUE, alpha, 2, x, d2y, gauss_p); /* print results */ for (i = 0; i < N; ++i) { double xi = gsl_vector_get(x, i); double yi = gsl_vector_get(y, i); double dyi = gsl_vector_get(dy, i); double d2yi = gsl_vector_get(d2y, i); double dxi; /* compute finite difference of x vector */ if (i == 0) dxi = gsl_vector_get(x, i + 1) - xi; else if (i == N - 1) dxi = gsl_vector_get(x, i) - gsl_vector_get(x, i - 1); else dxi = 0.5 * (gsl_vector_get(x, i + 1) - gsl_vector_get(x, i - 1)); printf("%.12e %.12e %.12e %.12e %.12e\n", xi, yi, dxi, dyi, d2yi); } gsl_vector_free(x); gsl_vector_free(y); gsl_vector_free(dy); gsl_vector_free(d2y); gsl_rng_free(r); gsl_filter_gaussian_free(gauss_p); return 0; }
{ "alphanum_fraction": 0.5876623377, "avg_line_length": 29.9444444444, "ext": "c", "hexsha": "9db707f097fb56b0eb5c8200249dfc051da58bea", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/gaussfilt2.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/doc/examples/gaussfilt2.c", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/gaussfilt2.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 643, "size": 2156 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_parser_TokenView_h_ #define SQ_INCLUDE_GUARD_parser_TokenView_h_ #include "core/Token.h" #include "core/typeutil.h" #include <gsl/gsl> #include <optional> #include <range/v3/view/facade.hpp> #include <string_view> namespace sq::parser { /** * A ranges::view of the input query split into tokens. */ class TokenView : public ranges::view_facade<TokenView> { public: explicit TokenView(std::string_view str) noexcept; TokenView() noexcept = default; TokenView(const TokenView &) noexcept = default; TokenView(TokenView &&) noexcept = default; TokenView &operator=(const TokenView &) noexcept = default; TokenView &operator=(TokenView &&) noexcept = default; ~TokenView() noexcept = default; // required for ranges::view_facade friend ranges::range_access; SQ_ND const Token &read() const; SQ_ND bool equal(ranges::default_sentinel_t other) const noexcept; void next(); private: gsl::index whitespace_length() const; std::string_view str_; gsl::index pos_ = 0; mutable std::optional<Token> cache_ = std::nullopt; }; } // namespace sq::parser #endif // SQ_INCLUDE_GUARD_parser_TokenView_h_
{ "alphanum_fraction": 0.6558206797, "avg_line_length": 27.66, "ext": "h", "hexsha": "a66b73db69abe9a6eb41753520bfafcf92a8a9dc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/parser/include/parser/TokenView.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/parser/include/parser/TokenView.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/parser/include/parser/TokenView.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 314, "size": 1383 }
/* rng/gsl_rng.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_RNG_H__ #define __GSL_RNG_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { const char *name; unsigned long int max; unsigned long int min; size_t size; void (*set) (void *state, unsigned long int seed); unsigned long int (*get) (void *state); double (*get_double) (void *state); } gsl_rng_type; typedef struct { const gsl_rng_type * type; void *state; } gsl_rng; /* These structs also need to appear in default.c so you can select them via the environment variable GSL_RNG_TYPE */ extern const gsl_rng_type *gsl_rng_cmrg; extern const gsl_rng_type *gsl_rng_gfsr4; extern const gsl_rng_type *gsl_rng_minstd; extern const gsl_rng_type *gsl_rng_mrg; extern const gsl_rng_type *gsl_rng_mt19937; extern const gsl_rng_type *gsl_rng_mt19937_1998; extern const gsl_rng_type *gsl_rng_r250; extern const gsl_rng_type *gsl_rng_ran0; extern const gsl_rng_type *gsl_rng_ran1; extern const gsl_rng_type *gsl_rng_ran2; extern const gsl_rng_type *gsl_rng_ran3; extern const gsl_rng_type *gsl_rng_rand48; extern const gsl_rng_type *gsl_rng_rand; extern const gsl_rng_type *gsl_rng_random128_bsd; extern const gsl_rng_type *gsl_rng_random128_glibc2; extern const gsl_rng_type *gsl_rng_random128_libc5; extern const gsl_rng_type *gsl_rng_random256_bsd; extern const gsl_rng_type *gsl_rng_random256_glibc2; extern const gsl_rng_type *gsl_rng_random256_libc5; extern const gsl_rng_type *gsl_rng_random32_bsd; extern const gsl_rng_type *gsl_rng_random32_glibc2; extern const gsl_rng_type *gsl_rng_random32_libc5; extern const gsl_rng_type *gsl_rng_random64_bsd; extern const gsl_rng_type *gsl_rng_random64_glibc2; extern const gsl_rng_type *gsl_rng_random64_libc5; extern const gsl_rng_type *gsl_rng_random8_bsd; extern const gsl_rng_type *gsl_rng_random8_glibc2; extern const gsl_rng_type *gsl_rng_random8_libc5; extern const gsl_rng_type *gsl_rng_random_bsd; extern const gsl_rng_type *gsl_rng_random_glibc2; extern const gsl_rng_type *gsl_rng_random_libc5; extern const gsl_rng_type *gsl_rng_randu; extern const gsl_rng_type *gsl_rng_ranf; extern const gsl_rng_type *gsl_rng_ranlux389; extern const gsl_rng_type *gsl_rng_ranlux; extern const gsl_rng_type *gsl_rng_ranlxd1; extern const gsl_rng_type *gsl_rng_ranlxd2; extern const gsl_rng_type *gsl_rng_ranlxs0; extern const gsl_rng_type *gsl_rng_ranlxs1; extern const gsl_rng_type *gsl_rng_ranlxs2; extern const gsl_rng_type *gsl_rng_ranmar; extern const gsl_rng_type *gsl_rng_slatec; extern const gsl_rng_type *gsl_rng_taus; extern const gsl_rng_type *gsl_rng_transputer; extern const gsl_rng_type *gsl_rng_tt800; extern const gsl_rng_type *gsl_rng_uni32; extern const gsl_rng_type *gsl_rng_uni; extern const gsl_rng_type *gsl_rng_vax; extern const gsl_rng_type *gsl_rng_zuf; const gsl_rng_type ** gsl_rng_types_setup(void); extern const gsl_rng_type *gsl_rng_default; extern unsigned long int gsl_rng_default_seed; gsl_rng *gsl_rng_alloc (const gsl_rng_type * T); int gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src); gsl_rng *gsl_rng_clone (const gsl_rng * r); void gsl_rng_free (gsl_rng * r); void gsl_rng_set (const gsl_rng * r, unsigned long int seed); unsigned long int gsl_rng_max (const gsl_rng * r); unsigned long int gsl_rng_min (const gsl_rng * r); const char *gsl_rng_name (const gsl_rng * r); size_t gsl_rng_size (const gsl_rng * r); void * gsl_rng_state (const gsl_rng * r); void gsl_rng_print_state (const gsl_rng * r); const gsl_rng_type * gsl_rng_env_setup (void); unsigned long int gsl_rng_get (const gsl_rng * r); double gsl_rng_uniform (const gsl_rng * r); double gsl_rng_uniform_pos (const gsl_rng * r); unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n); #ifdef HAVE_INLINE extern inline unsigned long int gsl_rng_get (const gsl_rng * r); extern inline unsigned long int gsl_rng_get (const gsl_rng * r) { return (r->type->get) (r->state); } extern inline double gsl_rng_uniform (const gsl_rng * r); extern inline double gsl_rng_uniform (const gsl_rng * r) { return (r->type->get_double) (r->state); } extern inline double gsl_rng_uniform_pos (const gsl_rng * r); extern inline double gsl_rng_uniform_pos (const gsl_rng * r) { double x ; do { x = (r->type->get_double) (r->state) ; } while (x == 0) ; return x ; } extern inline unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n); extern inline unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n) { unsigned long int offset = r->type->min; unsigned long int range = r->type->max - offset; unsigned long int scale = range / n; unsigned long int k; if (n > range) { GSL_ERROR_VAL ("n exceeds maximum value of generator", GSL_EINVAL, 0) ; } do { k = (((r->type->get) (r->state)) - offset) / scale; } while (k >= n); return k; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_RNG_H__ */
{ "alphanum_fraction": 0.7697841727, "avg_line_length": 30.0351758794, "ext": "h", "hexsha": "6a48bb1a1e2db060fac02a380e2dd9bac0e72d4b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_line_length": 93, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/gsl_rng.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 1672, "size": 5977 }
/** * File: specmodel_utils.h * Header file for specmodel_utils.c * */ #ifndef _SPECMODEL_UTILS_H #define _SPECMODEL_UTILS_H #include <gsl/gsl_interp.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include "fitsio.h" #include "aXe_grism.h" // interpolation type used for the // spectral models #define SMODEL_INTERP_TYPE gsl_interp_linear /* * Struct: energy_distrib */ typedef struct { int npoints; double *wavelength; double *flux; gsl_interp *interp; gsl_interp_accel *accel; } energy_distrib; /* * Struct: spectral_models */ typedef struct { int n_models; energy_distrib **SEDlist; } spectral_models; typedef struct { int dim_x; // the number of pixels in x-direction int dim_y; // the number of pixels in y-direction double xmean; // mean x-coordinate of the object double ymean; // mean y-coordinate of the object gsl_matrix *modimage; // matrix with the direct image } dirim_emission; typedef struct { int n_models; // the number of direct image object dirim_emission **obj_list; // the list of direct image objects } object_models; extern object_models * load_object_models(const char object_models_file[]); extern dirim_emission ** load_diremission_list(const char object_models_file[], const int n_models); extern dirim_emission * load_diremission(const char object_models_file[], const int n_extension); extern void free_object_models(object_models *objmodels); extern void free_dirim_emission(dirim_emission *diremission); extern void print_object_models(const object_models *objmodels); extern void print_dirim_emission(const dirim_emission *diremission); extern dirim_emission * get_dirim_emission(const object_models *objmodels, const int objspec); extern int has_aperture_dirim(const object_models *objmodels, const object *actobject); extern double get_diremission_value(const dirim_emission *diremission, const double xpos, const double ypos); extern double bilin_interp_matrix(const gsl_matrix *modimage, const double x, const double y); extern spectral_models * load_spectral_models(const char spectral_models_file[]); extern void print_spectral_models(const spectral_models *smodels); extern energy_distrib ** load_SED_list(const char spectral_models_file[], const int n_models); extern energy_distrib * load_SED_from_fitsext(const char spectral_models_file[], fitsfile *s_models); extern int get_num_extensions(const char spectral_models_file[]); extern void free_spectral_models(spectral_models *smodels); extern void free_specmodels_SEDs(spectral_models *smodels); extern energy_distrib * get_model_sed(const spectral_models *spec_mod, const int modspec); #endif
{ "alphanum_fraction": 0.7714494341, "avg_line_length": 22.2682926829, "ext": "h", "hexsha": "ce00be86d5b32d93215db527d9046f0011ccf2cc", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/specmodel_utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/specmodel_utils.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/specmodel_utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 649, "size": 2739 }
/* linalg/tridiag.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include "tridiag.h" #include "gsl_linalg.h" /* for description of method see [Engeln-Mullges + Uhlig, p. 92] * * diag[0] offdiag[0] 0 ..... * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... */ static int solve_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status; double *gamma = (double *) malloc (N * sizeof (double)); double *alpha = (double *) malloc (N * sizeof (double)); double *c = (double *) malloc (N * sizeof (double)); double *z = (double *) malloc (N * sizeof (double)); if (gamma == 0 || alpha == 0 || c == 0 || z == 0) { status = GSL_ENOMEM; } else { size_t i, j; /* Cholesky decomposition A = L.D.L^t lower_diag(L) = gamma diag(D) = alpha */ alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; for (i = 1; i < N - 1; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride*(i - 1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; } if (N > 1) { alpha[N - 1] = diag[d_stride * (N - 1)] - offdiag[o_stride*(N - 2)] * gamma[N - 2]; } /* update RHS */ z[0] = b[0]; for (i = 1; i < N; i++) { z[i] = b[b_stride * i] - gamma[i - 1] * z[i - 1]; } for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; if (N >= 2) { for (i = N - 2, j = 0; j <= N - 2; j++, i--) { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)]; } } status = GSL_SUCCESS; } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); return status; } /* for description of method see [Engeln-Mullges + Uhlig, p. 96] * * diag[0] offdiag[0] 0 ..... offdiag[N-1] * offdiag[0] diag[1] offdiag[1] ..... * 0 offdiag[1] diag[2] * 0 0 offdiag[2] ..... * ... ... * offdiag[N-1] ... * */ static int solve_cyc_tridiag( const double diag[], size_t d_stride, const double offdiag[], size_t o_stride, const double b[], size_t b_stride, double x[], size_t x_stride, size_t N) { int status; double * delta = (double *) malloc (N * sizeof (double)); double * gamma = (double *) malloc (N * sizeof (double)); double * alpha = (double *) malloc (N * sizeof (double)); double * c = (double *) malloc (N * sizeof (double)); double * z = (double *) malloc (N * sizeof (double)); if (delta == 0 || gamma == 0 || alpha == 0 || c == 0 || z == 0) { status = GSL_ENOMEM; } else { size_t i, j; double sum = 0.0; /* factor */ alpha[0] = diag[0]; gamma[0] = offdiag[0] / alpha[0]; delta[0] = offdiag[o_stride * (N-1)] / alpha[0]; for (i = 1; i < N - 2; i++) { alpha[i] = diag[d_stride * i] - offdiag[o_stride * (i-1)] * gamma[i - 1]; gamma[i] = offdiag[o_stride * i] / alpha[i]; delta[i] = -delta[i - 1] * offdiag[o_stride * (i-1)] / alpha[i]; } for (i = 0; i < N - 2; i++) { sum += alpha[i] * delta[i] * delta[i]; } alpha[N - 2] = diag[d_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * gamma[N - 3]; gamma[N - 2] = (offdiag[o_stride * (N - 2)] - offdiag[o_stride * (N - 3)] * delta[N - 3]) / alpha[N - 2]; alpha[N - 1] = diag[d_stride * (N - 1)] - sum - offdiag[o_stride * (N - 2)] * gamma[N - 2] * gamma[N - 2]; /* update */ z[0] = b[0]; for (i = 1; i < N - 1; i++) { z[i] = b[b_stride * i] - z[i - 1] * gamma[i - 1]; } sum = 0.0; for (i = 0; i < N - 2; i++) { sum += delta[i] * z[i]; } z[N - 1] = b[b_stride * (N - 1)] - sum - gamma[N - 2] * z[N - 2]; for (i = 0; i < N; i++) { c[i] = z[i] / alpha[i]; } /* backsubstitution */ x[x_stride * (N - 1)] = c[N - 1]; x[x_stride * (N - 2)] = c[N - 2] - gamma[N - 2] * x[x_stride * (N - 1)]; if (N >= 3) { for (i = N - 3, j = 0; j <= N - 3; j++, i--) { x[x_stride * i] = c[i] - gamma[i] * x[x_stride * (i + 1)] - delta[i] * x[x_stride * (N - 1)]; } } status = GSL_SUCCESS; } if (z != 0) free (z); if (c != 0) free (c); if (alpha != 0) free (alpha); if (gamma != 0) free (gamma); if (delta != 0) free (delta); return status; } int gsl_linalg_solve_symm_tridiag( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size || (offdiag->size != rhs->size && offdiag->size != rhs->size-1) || (solution->size != rhs->size) ) { return GSL_EBADLEN; } else { return solve_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } } int gsl_linalg_solve_symm_cyc_tridiag( const gsl_vector * diag, const gsl_vector * offdiag, const gsl_vector * rhs, gsl_vector * solution) { if(diag->size != rhs->size || offdiag->size != rhs->size || solution->size != rhs->size ) { return GSL_EBADLEN; } else { return solve_cyc_tridiag(diag->data, diag->stride, offdiag->data, offdiag->stride, rhs->data, rhs->stride, solution->data, solution->stride, diag->size); } }
{ "alphanum_fraction": 0.5075905606, "avg_line_length": 25.6872586873, "ext": "c", "hexsha": "106f171659336c595aee91cbabb2f2c3d78f0328", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/linalg/tridiag.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/linalg/tridiag.c", "max_line_length": 112, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/linalg/tridiag.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 2231, "size": 6653 }
#include <gsl/gsl_spline.h> typedef struct FastPMFDInterp{ size_t size; gsl_interp * F; gsl_interp * DF; gsl_interp * DDF; gsl_interp_accel * acc; } FastPMFDInterp; void fastpm_fd_interp_init(FastPMFDInterp * FDinterp); double fastpm_do_fd_interp(FastPMFDInterp * FDinterp, int F_id, double y); void fastpm_fd_interp_destroy(FastPMFDInterp * FDinterp);
{ "alphanum_fraction": 0.7559681698, "avg_line_length": 23.5625, "ext": "h", "hexsha": "28cf54b10c5279fcf321495d795dea01ec077489", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_path": "fastpm/api/fastpm/FDinterp.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_path": "fastpm/api/fastpm/FDinterp.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_path": "fastpm/api/fastpm/FDinterp.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 111, "size": 377 }
#ifndef _MASSINTEGRAND__H #define _MASSINTEGRAND__H #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <cstdint> #ifdef HAS_MKL #include <mkl.h> #else #include <cblas.h> #endif #ifdef __SSE4_2__ #include <emmintrin.h> #include <mm_malloc.h> #endif #include "SparseAssemblyNative.h" #include "_det_inv_.h" #include "_matmul_.h" #ifndef LL_TYPES #define LL_TYPES using Real = double; using Integer = std::int64_t; using UInteger = std::uint64_t; #endif /*---------------------------------------------------------------------------------------------*/ #ifndef CUSTOM_ALLOCATION_ #define CUSTOM_ALLOCATION_ template<typename T> FASTOR_INLINE T *allocate(Integer size) { #if defined(__AVX__) T *out = (T*)_mm_malloc(sizeof(T)*size,32); #elif defined(__SSE__) T *out = (T*)_mm_malloc(sizeof(T)*size,16); #else T *out = (T*)malloc(sizeof(T)*size); #endif return out; } template<typename T> FASTOR_INLINE void deallocate(T *a) { #if defined(__SSE__) _mm_free(a); #else free(a); #endif } #endif /*---------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------------*/ #ifndef SPARSE_TRIPLET_FILLER #define SPARSE_TRIPLET_FILLER // IJV Filler FASTOR_INLINE void fill_triplet( const Integer *i, const Integer *j, const Real *coeff, int *I, int *J, Real *V, Integer elem, Integer nvar, Integer nodeperelem, const UInteger *elements, Integer i_shape, Integer j_shape ) { Integer ndof = nvar*nodeperelem; Integer *current_row_column = allocate<Integer>(nvar*nodeperelem); Integer const_elem_retriever; for (Integer counter=0; counter<nodeperelem; ++counter) { const_elem_retriever = nvar*elements[elem*nodeperelem+counter]; for (Integer ncounter=0; ncounter<nvar; ++ncounter) { current_row_column[nvar*counter+ncounter] = const_elem_retriever+ncounter; } } Integer icounter = 0; Integer ncounter = ndof*ndof*elem; Integer const_I_retriever; for (Integer counter=0; counter<ndof; ++counter) { const_I_retriever = current_row_column[counter]; for (Integer iterator=0; iterator<ndof; ++iterator) { I[ncounter] = const_I_retriever; J[ncounter] = current_row_column[iterator]; V[ncounter] = coeff[icounter]; ncounter++; icounter++; } } deallocate(current_row_column); } FASTOR_INLINE void fill_global_data( const Integer *i, const Integer *j, const Real *coeff, int *I, int *J, Real *V, Integer elem, Integer nvar, Integer nodeperelem, const UInteger *elements, Integer i_shape, Integer j_shape, int recompute_sparsity_pattern, int squeeze_sparsity_pattern, const int *data_local_indices, const int *data_global_indices, const UInteger *sorted_elements, const Integer *sorter ) { if (recompute_sparsity_pattern) { fill_triplet(i,j,coeff,I,J,V,elem,nvar,nodeperelem,elements,i_shape,j_shape); } else { if (squeeze_sparsity_pattern) { SparseAssemblyNativeCSR_RecomputeDataIndex_( coeff, J, I, V, elem, nvar, nodeperelem, sorted_elements, sorter); } else { const int ndof = nvar*nodeperelem; const int local_capacity = ndof*ndof; SparseAssemblyNativeCSR_( coeff, data_local_indices, data_global_indices, elem, local_capacity, V ); } } } #endif /*---------------------------------------------------------------------------------------------*/ inline void _MassIntegrand_Filler_(Real *mass, const Real* bases, const Real* detJ, int ngauss, int noderpelem, int ndim, int nvar, Real rho) { int local_size = nvar*noderpelem; Real *N = allocate<Real>(nvar*local_size); Real *rhoNN = allocate<Real>(local_size*local_size); std::fill(N,N+nvar*local_size,0.); for (int igauss = 0; igauss < ngauss; ++igauss) { // Fill mass integrand for (int j=0; j<noderpelem; ++j) { const Real bases_j = bases[j*ngauss+igauss]; for (int ivar=0; ivar<ndim; ++ivar) { N[j*nvar*nvar+ivar*nvar+ivar] = bases_j; } } cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, local_size, local_size, nvar, rho, N, nvar, N, nvar, 0.0, rhoNN, local_size); // Multiply mass with detJ const Real detJ_igauss = detJ[igauss]; for (int i=0; i<local_size*local_size; ++i) { mass[i] += rhoNN[i]*detJ_igauss; } } deallocate(N); deallocate(rhoNN); } inline void _ConstantMassIntegrand_Filler_(Real *mass, const Real* constant_mass_integrand, const Real* detJ, int ngauss, int local_capacity) { for (int igauss = 0; igauss < ngauss; ++igauss) { // Multiply mass with detJ const Real detJ_igauss = detJ[igauss]; for (int i=0; i<local_capacity; ++i) { mass[i] += constant_mass_integrand[igauss*local_capacity+i]*detJ_igauss; } } } inline void _GenericConstantMassIntegrand_( const UInteger* elements, const Real* points, const Real* Jm, const Real* AllGauss, const Real* constant_mass_integrand, Integer nelem, Integer ndim, Integer nvar, Integer ngauss, Integer nodeperelem, Integer local_capacity, Integer mass_type, const Integer* local_rows_mass, const Integer* local_cols_mass, int *I_mass, int *J_mass, Real *V_mass, Real *mass, int recompute_sparsity_pattern, int squeeze_sparsity_pattern, const int *data_local_indices, const int *data_global_indices, const UInteger *sorted_elements, const Integer *sorter ) { Integer ndof = nodeperelem*nvar; Real *LagrangeElemCoords = allocate<Real>(nodeperelem*ndim); Real *MaterialGradient = allocate<Real>(ndim*nodeperelem); // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG int plus1 = ndim == 2 ? 0 : 1; Real *ParentGradientX = allocate<Real>(ndim*ndim+plus1); Real detJ = 0.; Real *massel = allocate<Real>(local_capacity); Real *massel_lumped = allocate<Real>(ndof); // PRE-COMPUTE ISOPARAMETRIC GRADIENTS std::vector<std::vector<Real>> current_Jms(ngauss); for (int g=0; g<ngauss; ++g) { std::vector<Real> current_Jm(ndim*nodeperelem); for (int j=0; j<nodeperelem; ++j) { for (int k=0; k<ndim; ++k) { current_Jm[k*nodeperelem+j] = Jm[k*ngauss*nodeperelem+j*ngauss+g]; } } current_Jms[g] = current_Jm; } // LOOP OVER ELEMETNS for (Integer elem=0; elem < nelem; ++elem) { // GET THE FIELDS AT THE ELEMENT LEVEL for (Integer i=0; i<nodeperelem; ++i) { const Integer inode = elements[elem*nodeperelem+i]; for (Integer j=0; j<ndim; ++j) { LagrangeElemCoords[i*ndim+j] = points[inode*ndim+j]; } } std::fill_n(massel,local_capacity,0.); for (Integer igauss = 0; igauss < ngauss; ++igauss) { { // USING A STL BASED FILLER REMOVES THE ANNOYING BUG std::fill_n(ParentGradientX,ndim*ndim+plus1,0.); _matmul_(ndim,ndim,nodeperelem,current_Jms[igauss].data(),LagrangeElemCoords,ParentGradientX); const Real detX = _det_(ndim, ParentGradientX); detJ = AllGauss[igauss]*std::abs(detX); } // Multiply constant part of mass with detJ #ifdef __AVX__ using V2 = Fastor::SIMDVector<Real>; V2 _va, _vb, _vout; _vb.set(detJ); int Vsize = V2::Size; int ROUND_ = ROUND_DOWN(local_capacity,Vsize); int i=0; for (; i<ROUND_; i+=Vsize) { _va.load(&constant_mass_integrand[igauss*local_capacity+i],false); _vout.load(&massel[i],false); #ifdef __FMA__ _vout = fmadd(_va,_vb,_vout); #else _vout += _va*_vb; #endif _vout.store(&massel[i],false); } for ( ; i<local_capacity; ++i) { massel[i] += constant_mass_integrand[igauss*local_capacity+i]*detJ; } #else for (int i=0; i<local_capacity; ++i) { massel[i] += constant_mass_integrand[igauss*local_capacity+i]*detJ; } #endif } // FOR LUMP MASS MATRIX if (mass_type == 0) { // LUMP MASS for (Integer i=0; i<ndof; ++i) { massel_lumped[i] = std::accumulate(&massel[i*ndof], &massel[(i+1)*ndof],0.); } // ASSEMBLE LUMPED MASS { for (Integer i = 0; i<nodeperelem; ++i) { UInteger T_idx = elements[elem*nodeperelem+i]*nvar; for (Integer iterator = 0; iterator < nvar; ++iterator) { mass[T_idx+iterator] += massel_lumped[i*nvar+iterator]; } } } } else { fill_global_data( local_rows_mass, local_cols_mass, massel, I_mass, J_mass, V_mass, elem, nvar, nodeperelem, elements, local_capacity, local_capacity, recompute_sparsity_pattern, squeeze_sparsity_pattern, data_local_indices, data_global_indices, sorted_elements, sorter); } } deallocate(ParentGradientX); deallocate(MaterialGradient); deallocate(LagrangeElemCoords); deallocate(massel); deallocate(massel_lumped); } inline void _SymmetricConstantMassIntegrand_( const UInteger* elements, const Real* points, const Real* Jm, const Real* AllGauss, const Real* constant_mass_integrand, Integer nelem, Integer ndim, Integer nvar, Integer ngauss, Integer nodeperelem, Integer local_capacity, Integer mass_type, const Integer* local_rows_mass, const Integer* local_cols_mass, int *I_mass, int *J_mass, Real *V_mass, Real *mass, int recompute_sparsity_pattern, int squeeze_sparsity_pattern, const int *data_local_indices, const int *data_global_indices, const UInteger *sorted_elements, const Integer *sorter ) { const Integer ndof = nodeperelem*nvar; const Integer symmetric_local_capacity = ndof*(ndof+1)/2; Real *LagrangeElemCoords = allocate<Real>(nodeperelem*ndim); Real *MaterialGradient = allocate<Real>(ndim*nodeperelem); // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG int plus1 = ndim == 2 ? 0 : 1; Real *ParentGradientX = allocate<Real>(ndim*ndim+plus1); Real detJ = 0.; Real *massel = allocate<Real>(local_capacity); Real *symmetric_massel = allocate<Real>(symmetric_local_capacity); Real *massel_lumped = allocate<Real>(ndof); // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS Real *symmetric_constant_mass_integrand = allocate<Real>(ngauss*symmetric_local_capacity); Integer counter = 0; for (Integer igauss = 0; igauss < ngauss; ++igauss) { for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { const Real value = constant_mass_integrand[igauss*ndof*ndof+i*ndof+j]; symmetric_constant_mass_integrand[counter] = value; counter++; } } } // PRE-COMPUTE ISOPARAMETRIC GRADIENTS std::vector<std::vector<Real>> current_Jms(ngauss); for (int g=0; g<ngauss; ++g) { std::vector<Real> current_Jm(ndim*nodeperelem); for (int j=0; j<nodeperelem; ++j) { for (int k=0; k<ndim; ++k) { current_Jm[k*nodeperelem+j] = Jm[k*ngauss*nodeperelem+j*ngauss+g]; } } current_Jms[g] = current_Jm; } // LOOP OVER ELEMETNS for (Integer elem=0; elem < nelem; ++elem) { // GET THE FIELDS AT THE ELEMENT LEVEL for (Integer i=0; i<nodeperelem; ++i) { const Integer inode = elements[elem*nodeperelem+i]; for (Integer j=0; j<ndim; ++j) { LagrangeElemCoords[i*ndim+j] = points[inode*ndim+j]; } } std::fill_n(massel,local_capacity,0.); std::fill_n(symmetric_massel,symmetric_local_capacity,0.); for (Integer igauss = 0; igauss < ngauss; ++igauss) { { // USING A STL BASED FILLER REMOVES THE ANNOYING BUG std::fill_n(ParentGradientX,ndim*ndim+plus1,0.); _matmul_(ndim,ndim,nodeperelem,current_Jms[igauss].data(),LagrangeElemCoords,ParentGradientX); const Real detX = _det_(ndim, ParentGradientX); detJ = AllGauss[igauss]*std::abs(detX); } // Multiply constant part of mass with detJ #ifdef __AVX__ using V2 = Fastor::SIMDVector<Real>; V2 _va, _vb, _vout; _vb.set(detJ); int Vsize = V2::Size; int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize); int i=0; for (; i<ROUND_; i+=Vsize) { _va.load(&symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i],false); _vout.load(&symmetric_massel[i],false); #ifdef __FMA__ _vout = fmadd(_va,_vb,_vout); #else _vout += _va*_vb; #endif _vout.store(&symmetric_massel[i],false); } for ( ; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #else for (int i=0; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #endif } // BUILD TOTAL LOCAL MASS MATRIX Integer counter = 0; for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { const Real value = symmetric_massel[counter]; massel[i*ndof+j] = value; massel[j*ndof+i] = value; counter++; } } // FOR LUMP MASS MATRIX if (mass_type == 0) { // LUMP MASS for (Integer i=0; i<ndof; ++i) { massel_lumped[i] = std::accumulate(&massel[i*ndof], &massel[(i+1)*ndof],0.); } // ASSEMBLE LUMPED MASS { for (Integer i = 0; i<nodeperelem; ++i) { UInteger T_idx = elements[elem*nodeperelem+i]*nvar; for (Integer iterator = 0; iterator < nvar; ++iterator) { mass[T_idx+iterator] += massel_lumped[i*nvar+iterator]; } } } } else { fill_global_data( local_rows_mass, local_cols_mass, massel, I_mass, J_mass, V_mass, elem, nvar, nodeperelem, elements, local_capacity, local_capacity, recompute_sparsity_pattern, squeeze_sparsity_pattern, data_local_indices, data_global_indices, sorted_elements, sorter); } } deallocate(ParentGradientX); deallocate(MaterialGradient); deallocate(LagrangeElemCoords); deallocate(massel); deallocate(symmetric_constant_mass_integrand); deallocate(symmetric_massel); deallocate(massel_lumped); } inline void _SymmetricNonZeroConstantMassIntegrand_( const UInteger* elements, const Real* points, const Real* Jm, const Real* AllGauss, const Real* constant_mass_integrand, Integer nelem, Integer ndim, Integer nvar, Integer ngauss, Integer nodeperelem, Integer local_capacity, Integer mass_type, const Integer* local_rows_mass, const Integer* local_cols_mass, int *I_mass, int *J_mass, Real *V_mass, Real *mass, int recompute_sparsity_pattern, int squeeze_sparsity_pattern, const int *data_local_indices, const int *data_global_indices, const UInteger *sorted_elements, const Integer *sorter ) { const Integer ndof = nodeperelem*nvar; Real *LagrangeElemCoords = allocate<Real>(nodeperelem*ndim); Real *MaterialGradient = allocate<Real>(ndim*nodeperelem); // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG int plus1 = ndim == 2 ? 0 : 1; Real *ParentGradientX = allocate<Real>(ndim*ndim+plus1); Real detJ = 0.; Real *massel = allocate<Real>(local_capacity); Real *massel_lumped = allocate<Real>(ndof); // PRE-COMPUTE SPARSITY PATTERN OF THE LOCAL MATRIX - // LOCAL MASS MATRICES TYPICALLY HAVE LOTS OF NONZEROS constexpr Real tolerance = 1e-12; std::vector<Integer> nonzero_i_indices, nonzero_j_indices; Integer counter = 0; for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { if (std::abs(constant_mass_integrand[i*ndof+j]) > tolerance) { nonzero_i_indices.push_back(i); nonzero_j_indices.push_back(j); } } } // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS const Integer symmetric_local_capacity = nonzero_i_indices.size(); Real *symmetric_massel = allocate<Real>(symmetric_local_capacity); Real *symmetric_constant_mass_integrand = allocate<Real>(ngauss*symmetric_local_capacity); counter = 0; for (Integer igauss = 0; igauss < ngauss; ++igauss) { for (Integer i=0; i<symmetric_local_capacity; ++i) { const Real value = constant_mass_integrand[igauss*ndof*ndof+nonzero_i_indices[i]*ndof+nonzero_j_indices[i]]; symmetric_constant_mass_integrand[counter] = value; counter++; } } // PRE-COMPUTE ISOPARAMETRIC GRADIENTS std::vector<std::vector<Real>> current_Jms(ngauss); for (int g=0; g<ngauss; ++g) { std::vector<Real> current_Jm(ndim*nodeperelem); for (int j=0; j<nodeperelem; ++j) { for (int k=0; k<ndim; ++k) { current_Jm[k*nodeperelem+j] = Jm[k*ngauss*nodeperelem+j*ngauss+g]; } } current_Jms[g] = current_Jm; } // LOOP OVER ELEMETNS for (Integer elem=0; elem < nelem; ++elem) { // GET THE FIELDS AT THE ELEMENT LEVEL for (Integer i=0; i<nodeperelem; ++i) { const Integer inode = elements[elem*nodeperelem+i]; for (Integer j=0; j<ndim; ++j) { LagrangeElemCoords[i*ndim+j] = points[inode*ndim+j]; } } std::fill_n(massel,local_capacity,0.); std::fill_n(symmetric_massel,symmetric_local_capacity,0.); for (Integer igauss = 0; igauss < ngauss; ++igauss) { { // USING A STL BASED FILLER REMOVES THE ANNOYING BUG std::fill_n(ParentGradientX,ndim*ndim+plus1,0.); _matmul_(ndim,ndim,nodeperelem,current_Jms[igauss].data(),LagrangeElemCoords,ParentGradientX); const Real detX = _det_(ndim, ParentGradientX); detJ = AllGauss[igauss]*std::abs(detX); } // Multiply constant part of mass with detJ #ifdef __AVX__ using V2 = Fastor::SIMDVector<Real>; V2 _va, _vb, _vout; _vb.set(detJ); int Vsize = V2::Size; int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize); int i=0; for (; i<ROUND_; i+=Vsize) { _va.load(&symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i],false); _vout.load(&symmetric_massel[i],false); #ifdef __FMA__ _vout = fmadd(_va,_vb,_vout); #else _vout += _va*_vb; #endif _vout.store(&symmetric_massel[i],false); } for ( ; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #else for (int i=0; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #endif } // BUILD TOTAL LOCAL MASS MATRIX for (Integer i=0; i<symmetric_local_capacity; ++i) { const Real value = symmetric_massel[i]; massel[nonzero_i_indices[i]*ndof+nonzero_j_indices[i]] = value; } for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { massel[j*ndof+i] = massel[i*ndof+j]; } } // FOR LUMP MASS MATRIX if (mass_type == 0) { // LUMP MASS for (Integer i=0; i<ndof; ++i) { massel_lumped[i] = std::accumulate(&massel[i*ndof], &massel[(i+1)*ndof],0.); } // ASSEMBLE LUMPED MASS { for (Integer i = 0; i<nodeperelem; ++i) { UInteger T_idx = elements[elem*nodeperelem+i]*nvar; for (Integer iterator = 0; iterator < nvar; ++iterator) { mass[T_idx+iterator] += massel_lumped[i*nvar+iterator]; } } } } else { fill_global_data( local_rows_mass, local_cols_mass, massel, I_mass, J_mass, V_mass, elem, nvar, nodeperelem, elements, local_capacity, local_capacity, recompute_sparsity_pattern, squeeze_sparsity_pattern, data_local_indices, data_global_indices, sorted_elements, sorter); } } deallocate(ParentGradientX); deallocate(MaterialGradient); deallocate(LagrangeElemCoords); deallocate(massel); deallocate(symmetric_constant_mass_integrand); deallocate(symmetric_massel); deallocate(massel_lumped); } inline void _SymmetricNonZeroOneElementConstantMassIntegrand_( const UInteger* elements, const Real* points, const Real* Jm, const Real* AllGauss, const Real* constant_mass_integrand, Integer nelem, Integer ndim, Integer nvar, Integer ngauss, Integer nodeperelem, Integer local_capacity, Integer mass_type, const Integer* local_rows_mass, const Integer* local_cols_mass, int *I_mass, int *J_mass, Real *V_mass, Real *mass, int recompute_sparsity_pattern, int squeeze_sparsity_pattern, const int *data_local_indices, const int *data_global_indices, const UInteger *sorted_elements, const Integer *sorter ) { const Integer ndof = nodeperelem*nvar; Real *LagrangeElemCoords = allocate<Real>(nodeperelem*ndim); Real *MaterialGradient = allocate<Real>(ndim*nodeperelem); // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG int plus1 = ndim == 2 ? 0 : 1; Real *ParentGradientX = allocate<Real>(ndim*ndim+plus1); Real detJ = 0.; Real *massel = allocate<Real>(local_capacity); Real *massel_lumped = allocate<Real>(ndof); // PRE-COMPUTE SPARSITY PATTERN OF THE LOCAL MATRIX - // LOCAL MASS MATRICES TYPICALLY HAVE LOTS OF NONZEROS constexpr Real tolerance = 1e-12; std::vector<Integer> nonzero_i_indices, nonzero_j_indices; Integer counter = 0; for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { if (std::abs(constant_mass_integrand[i*ndof+j]) > tolerance) { nonzero_i_indices.push_back(i); nonzero_j_indices.push_back(j); } } } // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS const Integer symmetric_local_capacity = nonzero_i_indices.size(); Real *symmetric_massel = allocate<Real>(symmetric_local_capacity); Real *symmetric_constant_mass_integrand = allocate<Real>(ngauss*symmetric_local_capacity); counter = 0; for (Integer igauss = 0; igauss < ngauss; ++igauss) { for (Integer i=0; i<symmetric_local_capacity; ++i) { const Real value = constant_mass_integrand[igauss*ndof*ndof+nonzero_i_indices[i]*ndof+nonzero_j_indices[i]]; symmetric_constant_mass_integrand[counter] = value; counter++; } } // PRE-COMPUTE ISOPARAMETRIC GRADIENTS std::vector<std::vector<Real>> current_Jms(ngauss); for (int g=0; g<ngauss; ++g) { std::vector<Real> current_Jm(ndim*nodeperelem); for (int j=0; j<nodeperelem; ++j) { for (int k=0; k<ndim; ++k) { current_Jm[k*nodeperelem+j] = Jm[k*ngauss*nodeperelem+j*ngauss+g]; } } current_Jms[g] = current_Jm; } // COMPUTE MASS FOR ONE ELEMENT ONLY for (Integer elem=0; elem < 1; ++elem) { // GET THE FIELDS AT THE ELEMENT LEVEL for (Integer i=0; i<nodeperelem; ++i) { const Integer inode = elements[elem*nodeperelem+i]; for (Integer j=0; j<ndim; ++j) { LagrangeElemCoords[i*ndim+j] = points[inode*ndim+j]; } } std::fill_n(massel,local_capacity,0.); std::fill_n(symmetric_massel,symmetric_local_capacity,0.); for (Integer igauss = 0; igauss < ngauss; ++igauss) { { // USING A STL BASED FILLER REMOVES THE ANNOYING BUG std::fill_n(ParentGradientX,ndim*ndim+plus1,0.); _matmul_(ndim,ndim,nodeperelem,current_Jms[igauss].data(),LagrangeElemCoords,ParentGradientX); const Real detX = _det_(ndim, ParentGradientX); detJ = AllGauss[igauss]*std::abs(detX); } // Multiply constant part of mass with detJ #ifdef __AVX__ using V2 = Fastor::SIMDVector<Real>; V2 _va, _vb, _vout; _vb.set(detJ); int Vsize = V2::Size; int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize); int i=0; for (; i<ROUND_; i+=Vsize) { _va.load(&symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i],false); _vout.load(&symmetric_massel[i],false); #ifdef __FMA__ _vout = fmadd(_va,_vb,_vout); #else _vout += _va*_vb; #endif _vout.store(&symmetric_massel[i],false); } for ( ; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #else for (int i=0; i<symmetric_local_capacity; ++i) { symmetric_massel[i] += symmetric_constant_mass_integrand[igauss*symmetric_local_capacity+i]*detJ; } #endif } // BUILD TOTAL LOCAL MASS MATRIX for (Integer i=0; i<symmetric_local_capacity; ++i) { const Real value = symmetric_massel[i]; massel[nonzero_i_indices[i]*ndof+nonzero_j_indices[i]] = value; } for (Integer i=0; i<ndof; ++i) { for (Integer j=i; j<ndof; ++j) { massel[j*ndof+i] = massel[i*ndof+j]; } } // FOR LUMP MASS MATRIX if (mass_type == 0) { // LUMP MASS for (Integer i=0; i<ndof; ++i) { massel_lumped[i] = std::accumulate(&massel[i*ndof], &massel[(i+1)*ndof],0.); } } } // LOOP OVER ELEMETNS for (Integer elem=0; elem < nelem; ++elem) { // FOR LUMP MASS MATRIX if (mass_type == 0) { // ASSEMBLE LUMPED MASS { for (Integer i = 0; i<nodeperelem; ++i) { UInteger T_idx = elements[elem*nodeperelem+i]*nvar; for (Integer iterator = 0; iterator < nvar; ++iterator) { mass[T_idx+iterator] += massel_lumped[i*nvar+iterator]; } } } } else { fill_global_data( local_rows_mass, local_cols_mass, massel, I_mass, J_mass, V_mass, elem, nvar, nodeperelem, elements, local_capacity, local_capacity, recompute_sparsity_pattern, squeeze_sparsity_pattern, data_local_indices, data_global_indices, sorted_elements, sorter); } } deallocate(ParentGradientX); deallocate(MaterialGradient); deallocate(LagrangeElemCoords); deallocate(massel); deallocate(symmetric_constant_mass_integrand); deallocate(symmetric_massel); deallocate(massel_lumped); } #endif
{ "alphanum_fraction": 0.5294882511, "avg_line_length": 33.0952868852, "ext": "h", "hexsha": "8f7f5d35158f83dbb6644f23bf8103337f682261", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:06:51.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-30T09:44:10.000Z", "max_forks_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jdlaubrie/florence", "max_forks_repo_path": "Florence/VariationalPrinciple/_Mass_/_MassIntegrand_.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_issues_repo_issues_event_max_datetime": "2022-01-18T02:30:22.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-03T02:29:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jdlaubrie/florence", "max_issues_repo_path": "Florence/VariationalPrinciple/_Mass_/_MassIntegrand_.h", "max_line_length": 120, "max_stars_count": 65, "max_stars_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jdlaubrie/florence", "max_stars_repo_path": "Florence/VariationalPrinciple/_Mass_/_MassIntegrand_.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:45:09.000Z", "max_stars_repo_stars_event_min_datetime": "2017-08-04T10:21:13.000Z", "num_tokens": 7965, "size": 32301 }
/* multiset/gsl_multiset.h * based on combination/gsl_combination.h by Szymon Jaroszewicz * based on permutation/gsl_permutation.h by Brian Gough * * Copyright (C) 2009 Rhys Ulerich * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MULTISET_H__ #define __GSL_MULTISET_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_types.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS struct gsl_multiset_struct { size_t n; size_t k; size_t *data; }; typedef struct gsl_multiset_struct gsl_multiset; GSL_FUN gsl_multiset *gsl_multiset_alloc (const size_t n, const size_t k); GSL_FUN gsl_multiset *gsl_multiset_calloc (const size_t n, const size_t k); GSL_FUN void gsl_multiset_init_first (gsl_multiset * c); GSL_FUN void gsl_multiset_init_last (gsl_multiset * c); GSL_FUN void gsl_multiset_free (gsl_multiset * c); GSL_FUN int gsl_multiset_memcpy (gsl_multiset * dest, const gsl_multiset * src); GSL_FUN int gsl_multiset_fread (FILE * stream, gsl_multiset * c); GSL_FUN int gsl_multiset_fwrite (FILE * stream, const gsl_multiset * c); GSL_FUN int gsl_multiset_fscanf (FILE * stream, gsl_multiset * c); GSL_FUN int gsl_multiset_fprintf (FILE * stream, const gsl_multiset * c, const char *format); GSL_FUN size_t gsl_multiset_n (const gsl_multiset * c); GSL_FUN size_t gsl_multiset_k (const gsl_multiset * c); GSL_FUN size_t * gsl_multiset_data (const gsl_multiset * c); GSL_FUN int gsl_multiset_valid (gsl_multiset * c); GSL_FUN int gsl_multiset_next (gsl_multiset * c); GSL_FUN int gsl_multiset_prev (gsl_multiset * c); GSL_FUN INLINE_DECL size_t gsl_multiset_get (const gsl_multiset * c, const size_t i); #ifdef HAVE_INLINE INLINE_FUN size_t gsl_multiset_get (const gsl_multiset * c, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= c->k)) /* size_t is unsigned, can't be negative */ { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return c->data[i]; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_MULTISET_H__ */
{ "alphanum_fraction": 0.734029484, "avg_line_length": 31.3076923077, "ext": "h", "hexsha": "f77cd1646d578ec9e2f4422092bb2f33fb4959c4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multiset.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_multiset.h", "max_line_length": 94, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_multiset.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 871, "size": 3256 }
/** * * @file testing_dposv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Bilel Hadri, Hatem Ltaief * @date 2010-11-15 * @generated d Tue Jan 7 11:45:18 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_dmain.h" enum blas_order_type { blas_rowmajor = 101, blas_colmajor = 102 }; enum blas_cmach_type { blas_base = 151, blas_t = 152, blas_rnd = 153, blas_ieee = 154, blas_emin = 155, blas_emax = 156, blas_eps = 157, blas_prec = 158, blas_underflow = 159, blas_overflow = 160, blas_sfmin = 161}; enum blas_norm_type { blas_one_norm = 171, blas_real_one_norm = 172, blas_two_norm = 173, blas_frobenius_norm = 174, blas_inf_norm = 175, blas_real_inf_norm = 176, blas_max_norm = 177, blas_real_max_norm = 178 }; static void BLAS_error(char *rname, int err, int val, int x) { fprintf( stderr, "%s %d %d %d\n", rname, err, val, x ); abort(); } static void BLAS_dge_norm(enum blas_order_type order, enum blas_norm_type norm, int m, int n, const double *a, int lda, double *res) { int i, j; float anorm, v; char rname[] = "BLAS_dge_norm"; if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 ); if (norm == blas_frobenius_norm) { anorm = 0.0f; for (j = n; j; --j) { for (i = m; i; --i) { v = a[0]; anorm += v * v; a++; } a += lda - m; } anorm = sqrt( anorm ); } else if (norm == blas_inf_norm) { anorm = 0.0f; for (i = 0; i < m; ++i) { v = 0.0f; for (j = 0; j < n; ++j) { v += fabs( a[i + j * lda] ); } if (v > anorm) anorm = v; } } else { BLAS_error( rname, -2, norm, 0 ); return; } if (res) *res = anorm; } static double BLAS_dpow_di(double x, int n) { double rv = 1.0; if (n < 0) { n = -n; x = 1.0 / x; } for (; n; n >>= 1, x *= x) { if (n & 1) rv *= x; } return rv; } static double BLAS_dfpinfo(enum blas_cmach_type cmach) { double eps = 1.0, r = 1.0, o = 1.0, b = 2.0; int t = 53, l = 1024, m = -1021; char rname[] = "BLAS_dfpinfo"; if ((sizeof eps) == sizeof(float)) { t = 24; l = 128; m = -125; } else { t = 53; l = 1024; m = -1021; } /* for (i = 0; i < t; ++i) eps *= half; */ eps = BLAS_dpow_di( b, -t ); /* for (i = 0; i >= m; --i) r *= half; */ r = BLAS_dpow_di( b, m-1 ); o -= eps; /* for (i = 0; i < l; ++i) o *= b; */ o = (o * BLAS_dpow_di( b, l-1 )) * b; switch (cmach) { case blas_eps: return eps; case blas_sfmin: return r; default: BLAS_error( rname, -1, cmach, 0 ); break; } return 0.0; } static int check_factorization(int, double*, double*, int, int , double); static int check_solution(int, int, double*, int, double*, double*, int, double); static int check_estimator(PLASMA_enum, int, double *, int, double *, double, double, double); int testing_dposv(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 4){ USAGE("POSV", "N LDA NRHS LDB", " - N : the size of the matrix\n" " - LDA : leading dimension of the matrix A\n" " - NRHS : number of RHS\n" " - LDB : leading dimension of the RHS B\n"); return -1; } int N = atoi(argv[0]); int LDA = atoi(argv[1]); int NRHS = atoi(argv[2]); int LDB = atoi(argv[3]); double eps; int info_solution, info_factorization; int u, trans1, trans2; double *A1 = (double *)malloc(LDA*N*sizeof(double)); double *A2 = (double *)malloc(LDA*N*sizeof(double)); double *B1 = (double *)malloc(LDB*NRHS*sizeof(double)); double *B2 = (double *)malloc(LDB*NRHS*sizeof(double)); /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)){ printf("Out of Memory \n "); return -2; } eps = BLAS_dfpinfo( blas_eps ); for(u=0; u<2; u++) { trans1 = uplo[u] == PlasmaUpper ? PlasmaTrans : PlasmaNoTrans; trans2 = uplo[u] == PlasmaUpper ? PlasmaNoTrans : PlasmaTrans; /*------------------------------------------------------------- * TESTING DPOSV */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_dplgsy( (double)N, N, A1, LDA, 51 ); PLASMA_dlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_dplrnt( N, NRHS, B1, LDB, 371 ); PLASMA_dlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); printf("\n"); printf("------ TESTS FOR PLASMA DPOSV ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* PLASMA DPOSV */ PLASMA_dposv(uplo[u], N, NRHS, A2, LDA, B2, LDB); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ( (info_solution == 0) && (info_factorization == 0) ) { printf("***************************************************\n"); printf(" ---- TESTING DPOSV(%s) ...................... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else { printf("***************************************************\n"); printf(" - TESTING DPOSV(%s) ... FAILED !\n", uplostr[u]); printf("***************************************************\n"); } /*------------------------------------------------------------- * TESTING DPOTRF + DPOTRS */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_dplgsy( (double)N, N, A1, LDA, 51 ); PLASMA_dlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_dplrnt( N, NRHS, B1, LDB, 371 ); PLASMA_dlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); /* Plasma routines */ PLASMA_dpotrf(uplo[u], N, A2, LDA); PLASMA_dpotrs(uplo[u], N, NRHS, A2, LDA, B2, LDB); printf("\n"); printf("------ TESTS FOR PLASMA DPOTRF + DPOTRS ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)){ printf("***************************************************\n"); printf(" ---- TESTING DPOTRF + DPOTRS (%s)............ PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("****************************************************\n"); printf(" - TESTING DPOTRF + DPOTRS (%s)... FAILED !\n", uplostr[u]); printf("****************************************************\n"); } /*------------------------------------------------------------- * TESTING DPOTRF + ZPTRSM + DTRSM */ /* Initialize A1 and A2 for Symmetric Positif Matrix */ PLASMA_dplgsy( (double)N, N, A1, LDA, 51 ); PLASMA_dlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA ); /* Initialize B1 and B2 */ PLASMA_dplrnt( N, NRHS, B1, LDB, 371 ); PLASMA_dlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB ); /* PLASMA routines */ PLASMA_dpotrf(uplo[u], N, A2, LDA); PLASMA_dtrsm(PlasmaLeft, uplo[u], trans1, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); PLASMA_dtrsm(PlasmaLeft, uplo[u], trans2, PlasmaNonUnit, N, NRHS, 1.0, A2, LDA, B2, LDB); printf("\n"); printf("------ TESTS FOR PLASMA DPOTRF + DTRSM + DTRSM ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n", eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /* Check the factorization and the solution */ info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps); info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps); if ((info_solution == 0)&(info_factorization == 0)){ printf("***************************************************\n"); printf(" ---- TESTING DPOTRF + DTRSM + DTRSM (%s)..... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("***************************************************\n"); printf(" - TESTING DPOTRF + DTRSM + DTRSM (%s)... FAILED !\n", uplostr[u]); printf("***************************************************\n"); } /*------------------------------------------------------------- * TESTING ZPOCON on the last call */ { double Anorm = PLASMA_dlansy( PlasmaOneNorm, uplo[u], N, A1, LDA ); double Acond; info_solution = PLASMA_dpocon(uplo[u], N, A2, LDA, Anorm, &Acond); if ( info_solution == 0 ) { info_solution = check_estimator(uplo[u], N, A1, LDA, A2, Anorm, Acond, eps); } else { printf(" PLASMA_dpocon returned info = %d\n", info_solution ); } if ((info_solution == 0)){ printf("***************************************************\n"); printf(" ---- TESTING DPOTRF + ZPOCON (%s) ........... PASSED !\n", uplostr[u]); printf("***************************************************\n"); } else{ printf("**************************************************\n"); printf(" - TESTING DPOTRF + ZPOCON (%s) ... FAILED !\n", uplostr[u]); printf("**************************************************\n"); } } } free(A1); free(A2); free(B1); free(B2); return 0; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ static int check_factorization(int N, double *A1, double *A2, int LDA, int uplo, double eps) { double Anorm, Rnorm; double alpha; int info_factorization; int i,j; double *Residual = (double *)malloc(N*N*sizeof(double)); double *L1 = (double *)malloc(N*N*sizeof(double)); double *L2 = (double *)malloc(N*N*sizeof(double)); double *work = (double *)malloc(N*sizeof(double)); memset((void*)L1, 0, N*N*sizeof(double)); memset((void*)L2, 0, N*N*sizeof(double)); alpha= 1.0; LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } else{ LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_dlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_dtrmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, N, Residual, N, &Rnorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm ); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || isinf(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 60.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; } /*------------------------------------------------------------------------ * Check the accuracy of the solution of the linear system */ static int check_solution(int N, int NRHS, double *A1, int LDA, double *B1, double *B2, int LDB, double eps ) { int info_solution; double Rnorm, Anorm, Xnorm, Bnorm, result; double alpha, beta; double *work = (double *)malloc(N*sizeof(double)); alpha = 1.0; beta = -1.0; BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B2, LDB, &Xnorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm ); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Bnorm ); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, (alpha), A1, LDA, B2, LDB, (beta), B1, LDB); BLAS_dge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Rnorm ); if (getenv("PLASMA_TESTING_VERBOSE")) printf( "||A||_oo=%f\n||X||_oo=%f\n||B||_oo=%f\n||A X - B||_oo=%e\n", Anorm, Xnorm, Bnorm, Rnorm ); result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ; printf("============\n"); printf("Checking the Residual of the solution \n"); printf("-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \n", result); if ( isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } free(work); return info_solution; } /*------------------------------------------------------------------------ * Check the accuracy of the condition estimator */ static int check_estimator(PLASMA_enum uplo, int N, double *A1, int LDA, double *A2, double Anorm, double Acond, double eps) { int info_solution; double result, Acond_lapack; double invcond, invcond_lapack; info_solution = LAPACKE_dpocon(LAPACK_COL_MAJOR, lapack_const(uplo), N, A2, LDA, Anorm, &Acond_lapack); if ( info_solution != 0 ) { printf(" PLASMA_dgecon returned info = %d\n", info_solution ); return info_solution; } invcond_lapack = 1. / ( Acond_lapack ); invcond = 1. / ( Acond ); printf("============\n"); printf("Checking the condition number \n"); printf("-- Acond_plasma = %e, Acond_lapack = %e \n" "-- Ainvcond_plasma = %e, Ainvcond_lapack = %e \n", Acond, Acond_lapack, invcond, invcond_lapack ); result = fabs( Acond_lapack - Acond ) / eps; if ( result > 60. ) { printf("-- The solution is suspicious ! \n"); info_solution = 1; } else{ printf("-- The solution is CORRECT ! \n"); info_solution = 0; } return info_solution; }
{ "alphanum_fraction": 0.4913523901, "avg_line_length": 33.7085020243, "ext": "c", "hexsha": "0c2b34abc3dfa8078aae5d70290ca8390d6cb1c8", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_dposv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_dposv.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_dposv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4909, "size": 16652 }
///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation // NMatrix is Copyright (c) 2012, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == cblas.c // // Functions in this file allow us to call CBLAS functions using // arrays of function pointers, by ensuring that each has the same // signature. #ifndef CBLAS_C # define CBLAS_C #include <cblas.h> #include "nmatrix.h" //extern const enum CBLAS_ORDER; //extern const enum CBLAS_TRANSPOSE; inline void cblas_r32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) r32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc); else r32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.r[0], p.B, p.ldb, p.A, p.lda, p.beta.r[0], p.C, p.ldc); } inline void cblas_r32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { r32gemv(TransA, p.M, p.N, p.alpha.r[0], p.A, p.lda, p.B, p.ldb, p.beta.r[0], p.C, p.ldc); } inline void cblas_r64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) r64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc); else r64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.ra[0], p.B, p.ldb, p.A, p.lda, p.beta.ra[0], p.C, p.ldc); } inline void cblas_r64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { r64gemv(TransA, p.M, p.N, p.alpha.ra[0], p.A, p.lda, p.B, p.ldb, p.beta.ra[0], p.C, p.ldc); } inline void cblas_r128gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) r128gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc); else r128gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.rat, p.B, p.ldb, p.A, p.lda, p.beta.rat, p.C, p.ldc); } inline void cblas_r128gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { r128gemv(TransA, p.M, p.N, p.alpha.rat, p.A, p.lda, p.B, p.ldb, p.beta.rat, p.C, p.ldc); } inline void cblas_bgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { bgemv(TransA, p.M, p.N, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc); } inline void cblas_bgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) bgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.b[0], p.A, p.lda, p.B, p.ldb, p.beta.b[0], p.C, p.ldc); else bgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.b[0], p.B, p.ldb, p.A, p.lda, p.beta.b[0], p.C, p.ldc); } inline void cblas_i8gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { i8gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); } inline void cblas_i8gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) i8gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); else i8gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc); } inline void cblas_i16gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { i16gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); } inline void cblas_i16gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) i16gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); else i16gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc); } inline void cblas_i32gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { i32gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); } inline void cblas_i32gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) i32gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); else i32gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc); } inline void cblas_i64gemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { i64gemv(TransA, p.M, p.N, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); } inline void cblas_i64gemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) i64gemm(TransA, TransB, p.M, p.N, p.K, p.alpha.i[0], p.A, p.lda, p.B, p.ldb, p.beta.i[0], p.C, p.ldc); else i64gemm(TransB, TransA, p.N, p.M, p.K, p.alpha.i[0], p.B, p.ldb, p.A, p.lda, p.beta.i[0], p.C, p.ldc); } inline void cblas_vgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { if (Order == CblasColMajor) vgemm(TransA, TransB, p.M, p.N, p.K, p.alpha.v[0], p.A, p.lda, p.B, p.ldb, p.beta.v[0], p.C, p.ldc); else vgemm(TransB, TransA, p.N, p.M, p.K, p.alpha.v[0], p.B, p.ldb, p.A, p.lda, p.beta.v[0], p.C, p.ldc); } inline void cblas_sgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { cblas_sgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc); } inline void cblas_sgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { cblas_sgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc); } inline void cblas_dgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { cblas_dgemv(Order, TransA, p.M, p.N, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc); } inline void cblas_dgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { cblas_dgemm(Order, TransA, TransB, p.M, p.N, p.K, p.alpha.d[0], p.A, p.lda, p.B, p.ldb, p.beta.d[0], p.C, p.ldc); } inline void cblas_cgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { cblas_cgemv(Order, TransA, p.M, p.N, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc); } inline void cblas_cgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { cblas_cgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.c), p.A, p.lda, p.B, p.ldb, &(p.beta.c), p.C, p.ldc); } inline void cblas_zgemv_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, DENSE_PARAM p) { cblas_zgemv(Order, TransA, p.M, p.N, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc); } inline void cblas_zgemm_(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, DENSE_PARAM p) { cblas_zgemm(Order, TransA, TransB, p.M, p.N, p.K, &(p.alpha.z), p.A, p.lda, p.B, p.ldb, &(p.beta.z), p.C, p.ldc); } #endif
{ "alphanum_fraction": 0.6659000121, "avg_line_length": 55.0733333333, "ext": "c", "hexsha": "8f540ee319feeaa021d95c99e838085dce9cc30c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "kod3r/nmatrix", "max_forks_repo_path": "ext/nmatrix/cblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "kod3r/nmatrix", "max_issues_repo_path": "ext/nmatrix/cblas.c", "max_line_length": 144, "max_stars_count": 1, "max_stars_repo_head_hexsha": "53da083c08d44f820ad3925e42055b8c0f10c35a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "kod3r/nmatrix", "max_stars_repo_path": "ext/nmatrix/cblas.c", "max_stars_repo_stars_event_max_datetime": "2019-04-19T23:05:38.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-19T23:05:38.000Z", "num_tokens": 3074, "size": 8261 }
#ifndef XYWEBSERVER_TEST_UTILS_H_ #define XYWEBSERVER_TEST_UTILS_H_ #include <gtest/gtest.h> #include <gsl/pointers> #include "runtime/runtime.h" #define CO_ASSERT_EQ(val1, val2) \ ({ \ auto f = [&]() { ASSERT_EQ(val1, val2); }; \ f(); \ }) constexpr std::chrono::milliseconds time_deviation(7); class TestRuntimeCtxGuard { public: TestRuntimeCtxGuard( gsl::owner<std::function<xyco::runtime::Future<void>()> *> co_wrapper, bool in_runtime); TestRuntimeCtxGuard(const TestRuntimeCtxGuard &guard) = delete; TestRuntimeCtxGuard(TestRuntimeCtxGuard &&guard) = delete; auto operator=(const TestRuntimeCtxGuard &guard) -> TestRuntimeCtxGuard & = delete; auto operator=(TestRuntimeCtxGuard &&guard) -> TestRuntimeCtxGuard & = delete; ~TestRuntimeCtxGuard(); private: gsl::owner<std::function<xyco::runtime::Future<void>()> *> co_wrapper_; }; class TestRuntimeCtx { public: // run until co finished template <typename Fn> static auto co_run(Fn &&co) -> void requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) { // co_outer's lifetime is managed by the caller to avoid being destroyed // automatically before resumed. std::mutex mutex; std::unique_lock<std::mutex> lock_guard(mutex); std::condition_variable cv; auto co_outer = [&]() -> xyco::runtime::Future<void> { try { co_await co(); cv.notify_one(); } catch (std::exception e) { auto f = [&]() { ASSERT_NO_THROW(throw e); }; f(); cv.notify_one(); } }; runtime_->spawn(co_outer()); cv.wait(lock_guard); } template <typename Fn> static auto co_run_no_wait(Fn &&co) -> TestRuntimeCtxGuard requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) { auto *co_outer = gsl::owner<std::function<xyco::runtime::Future<void>()> *>( new std::function<xyco::runtime::Future<void>()>( [=]() -> xyco::runtime::Future<void> { co_await co(); })); return {co_outer, true}; } template <typename Fn> static auto co_run_without_runtime(Fn &&co) -> TestRuntimeCtxGuard requires(std::is_invocable_r_v<xyco::runtime::Future<void>, Fn>) { auto *co_outer = gsl::owner<std::function<xyco::runtime::Future<void>()> *>( new std::function<xyco::runtime::Future<void>()>( [=]() -> xyco::runtime::Future<void> { co_await co(); })); return {co_outer, false}; } private : static std::unique_ptr<xyco::runtime::Runtime> runtime_; }; #endif // XYWEBSERVER_TEST_UTILS_H_
{ "alphanum_fraction": 0.6293785311, "avg_line_length": 29.8314606742, "ext": "h", "hexsha": "72ba8d9bb15639cf0fcff2c0e0e62e8fa71b0702", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ddxy18/xyco", "max_forks_repo_path": "tests/utils.h", "max_issues_count": 17, "max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ddxy18/xyco", "max_issues_repo_path": "tests/utils.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ddxy18/xyco", "max_stars_repo_path": "tests/utils.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 676, "size": 2655 }
/* multifit_nlin/gsl_multifit_nlin.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MULTIFIT_NLIN_H__ #define __GSL_MULTIFIT_NLIN_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS int gsl_multifit_gradient (const gsl_matrix * J, const gsl_vector * f, gsl_vector * g); int gsl_multifit_covar (const gsl_matrix * J, double epsrel, gsl_matrix * covar); /* Definition of vector-valued functions with parameters based on gsl_vector */ struct gsl_multifit_function_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); size_t n; /* number of functions */ size_t p; /* number of independent variables */ void * params; }; typedef struct gsl_multifit_function_struct gsl_multifit_function ; #define GSL_MULTIFIT_FN_EVAL(F,x,y) (*((F)->f))(x,(F)->params,(y)) typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n, size_t p); int (*set) (void *state, gsl_multifit_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); int (*iterate) (void *state, gsl_multifit_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx); void (*free) (void *state); } gsl_multifit_fsolver_type; typedef struct { const gsl_multifit_fsolver_type * type; gsl_multifit_function * function ; gsl_vector * x ; gsl_vector * f ; gsl_vector * dx ; void *state; } gsl_multifit_fsolver; gsl_multifit_fsolver * gsl_multifit_fsolver_alloc (const gsl_multifit_fsolver_type * T, size_t n, size_t p); void gsl_multifit_fsolver_free (gsl_multifit_fsolver * s); int gsl_multifit_fsolver_set (gsl_multifit_fsolver * s, gsl_multifit_function * f, const gsl_vector * x); int gsl_multifit_fsolver_iterate (gsl_multifit_fsolver * s); const char * gsl_multifit_fsolver_name (const gsl_multifit_fsolver * s); gsl_vector * gsl_multifit_fsolver_position (const gsl_multifit_fsolver * s); /* Definition of vector-valued functions and gradient with parameters based on gsl_vector */ struct gsl_multifit_function_fdf_struct { int (* f) (const gsl_vector * x, void * params, gsl_vector * f); int (* df) (const gsl_vector * x, void * params, gsl_matrix * df); int (* fdf) (const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix *df); size_t n; /* number of functions */ size_t p; /* number of independent variables */ void * params; }; typedef struct gsl_multifit_function_fdf_struct gsl_multifit_function_fdf ; #define GSL_MULTIFIT_FN_EVAL_F(F,x,y) ((*((F)->f))(x,(F)->params,(y))) #define GSL_MULTIFIT_FN_EVAL_DF(F,x,dy) ((*((F)->df))(x,(F)->params,(dy))) #define GSL_MULTIFIT_FN_EVAL_F_DF(F,x,y,dy) ((*((F)->fdf))(x,(F)->params,(y),(dy))) typedef struct { const char *name; size_t size; int (*alloc) (void *state, size_t n, size_t p); int (*set) (void *state, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx); int (*iterate) (void *state, gsl_multifit_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx); void (*free) (void *state); } gsl_multifit_fdfsolver_type; typedef struct { const gsl_multifit_fdfsolver_type * type; gsl_multifit_function_fdf * fdf ; gsl_vector * x; gsl_vector * f; gsl_matrix * J; gsl_vector * dx; void *state; } gsl_multifit_fdfsolver; gsl_multifit_fdfsolver * gsl_multifit_fdfsolver_alloc (const gsl_multifit_fdfsolver_type * T, size_t n, size_t p); int gsl_multifit_fdfsolver_set (gsl_multifit_fdfsolver * s, gsl_multifit_function_fdf * fdf, const gsl_vector * x); int gsl_multifit_fdfsolver_iterate (gsl_multifit_fdfsolver * s); void gsl_multifit_fdfsolver_free (gsl_multifit_fdfsolver * s); const char * gsl_multifit_fdfsolver_name (const gsl_multifit_fdfsolver * s); gsl_vector * gsl_multifit_fdfsolver_position (const gsl_multifit_fdfsolver * s); int gsl_multifit_test_delta (const gsl_vector * dx, const gsl_vector * x, double epsabs, double epsrel); int gsl_multifit_test_gradient (const gsl_vector * g, double epsabs); /* extern const gsl_multifit_fsolver_type * gsl_multifit_fsolver_gradient; */ GSL_VAR const gsl_multifit_fdfsolver_type * gsl_multifit_fdfsolver_lmder; GSL_VAR const gsl_multifit_fdfsolver_type * gsl_multifit_fdfsolver_lmsder; __END_DECLS #endif /* __GSL_MULTIFIT_NLIN_H__ */
{ "alphanum_fraction": 0.7046099291, "avg_line_length": 32.6011560694, "ext": "h", "hexsha": "96bd014005615ef87951a48a73b678d75d69b5a9", "lang": "C", "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:53:15.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-01T15:12:21.000Z", "max_forks_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_forks_repo_licenses": [ "Xnet", "X11" ], "max_forks_repo_name": "robpearc/FoldDesign", "max_forks_repo_path": "bin/EvoDesignX/src/gsl/gsl_multifit_nlin.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_issues_repo_issues_event_max_datetime": "2017-05-09T10:24:03.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-29T22:11:01.000Z", "max_issues_repo_licenses": [ "Xnet", "X11" ], "max_issues_repo_name": "robpearc/FoldDesign", "max_issues_repo_path": "bin/EvoDesignX/src/gsl/gsl_multifit_nlin.h", "max_line_length": 131, "max_stars_count": 77, "max_stars_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf", "max_stars_repo_licenses": [ "Xnet", "X11" ], "max_stars_repo_name": "robpearc/FoldDesign", "max_stars_repo_path": "bin/EvoDesignX/src/gsl/gsl_multifit_nlin.h", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z", "num_tokens": 1576, "size": 5640 }
#include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> #include <libgen.h> #include <options/options.h> #include "../csm/csm_all.h" struct ld_noise_params { int seed; double discretization; double sigma; const char* file_input; const char* file_output; int lambertian; }; int main(int argc, const char * argv[]) { sm_set_program_name(argv[0]); options_banner("ld_noise: Adds noise to readings in a scan"); struct ld_noise_params p; struct option* ops = options_allocate(20); options_double(ops, "discretization", &p.discretization, 0.0, "Size of discretization (disabled if 0)"); options_double(ops, "sigma", &p.sigma, 0.0, "Std deviation of gaussian noise (disabled if 0)"); options_int(ops, "lambertian", &p.lambertian, 0, "Use lambertian model cov = sigma^2 / cos(beta^2) where beta is the incidence. Need have alpha or true_alpha."); options_int(ops, "seed", &p.seed, 0, "Seed for random number generator (if 0, use GSL_RNG_SEED env. variable)."); options_string(ops, "in", &p.file_input, "stdin", "Input file "); options_string(ops, "out", &p.file_output, "stdout", "Output file "); if(!options_parse_args(ops, argc, argv)) { fprintf(stderr, "A simple program for adding noise to sensor scans.\n\nUsage:\n"); options_print_help(ops, stderr); return -1; } FILE * in = open_file_for_reading(p.file_input); if(!in) return -3; FILE * out = open_file_for_writing(p.file_output); if(!out) return -2; gsl_rng_env_setup(); gsl_rng * rng = gsl_rng_alloc (gsl_rng_ranlxs0); if(p.seed != 0) gsl_rng_set(rng, (unsigned int) p.seed); LDP ld; int count = 0; while( (ld = ld_from_json_stream(in))) { if(!ld_valid_fields(ld)) { sm_error("Invalid laser data (#%d in file)\n", count); continue; } int i; for(i=0;i<ld->nrays;i++) { if(!ld->valid[i]) continue; double * reading = ld->readings + i; if(p.sigma > 0) { double add_sigma = p.sigma; if(p.lambertian) { int have_alpha = 0; double alpha = 0; if(!is_nan(ld->true_alpha[i])) { alpha = ld->true_alpha[i]; have_alpha = 1; } else if(ld->alpha_valid[i]) { alpha = ld->alpha[i];; have_alpha = 1; } else have_alpha = 0; if(have_alpha) { /* Recall that alpha points outside the surface */ double beta = (alpha+M_PI) - ld->theta[i]; add_sigma = p.sigma / cos(beta); } else { sm_error("Because lambertian is active, I need either true_alpha[] or alpha[]"); ld_write_as_json(ld, stderr); return -1; } } *reading += gsl_ran_gaussian(rng, add_sigma); if(is_nan(ld->readings_sigma[i])) { ld->readings_sigma[i] = add_sigma; } else { ld->readings_sigma[i] = sqrt(square(add_sigma) + square(ld->readings_sigma[i])); } } if(p.discretization > 0) *reading -= fmod(*reading , p.discretization); } ld_write_as_json(ld, out); ld_free(ld); } return 0; }
{ "alphanum_fraction": 0.6403626595, "avg_line_length": 26.1228070175, "ext": "c", "hexsha": "9bc41814e0b11f35ade86ebfb0c04c0fcd451857", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ozaslan/basics", "max_forks_repo_path": "csm/sm/apps/ld_noise.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ozaslan/basics", "max_issues_repo_path": "csm/sm/apps/ld_noise.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ozaslan/basics", "max_stars_repo_path": "csm/sm/apps/ld_noise.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 897, "size": 2978 }
/* interpolation/bicubic.c * * Copyright 2012 David Zaslavsky * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_interp2d.h> #define IDX2D(i, j, w) ((j) * ((w)->xsize) + (i)) typedef struct { double * zx; double * zy; double * zxy; size_t xsize; size_t ysize; } bicubic_state_t; static void bicubic_free (void * vstate); static void * bicubic_alloc(size_t xsize, size_t ysize) { bicubic_state_t *state; state = calloc(1, sizeof (bicubic_state_t)); if (state == NULL) { GSL_ERROR_NULL("failed to allocate space for state", GSL_ENOMEM); } state->zx = (double *) malloc (xsize * ysize * sizeof (double)); if (state->zx == NULL) { bicubic_free(state); GSL_ERROR_NULL("failed to allocate space for zx", GSL_ENOMEM); } state->zy = (double *) malloc (xsize * ysize * sizeof (double)); if (state->zy == NULL) { bicubic_free(state); GSL_ERROR_NULL("failed to allocate space for zy", GSL_ENOMEM); } state->zxy = (double *) malloc (xsize * ysize * sizeof (double)); if (state->zxy == NULL) { bicubic_free(state); GSL_ERROR_NULL("failed to allocate space for zxy", GSL_ENOMEM); } state->xsize = xsize; state->ysize = ysize; return state; } /* bicubic_alloc() */ static void bicubic_free (void * vstate) { bicubic_state_t *state = (bicubic_state_t *) vstate; RETURN_IF_NULL(state); if (state->zx) free (state->zx); if (state->zy) free (state->zy); if (state->zxy) free (state->zxy); free (state); } /* bicubic_free() */ static int bicubic_init(void * vstate, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize) { bicubic_state_t *state = (bicubic_state_t *) vstate; gsl_interp_accel *acc = gsl_interp_accel_alloc(); gsl_spline *spline; gsl_vector *x; gsl_vector *y; size_t i, j; x = gsl_vector_alloc(xsize); y = gsl_vector_alloc(xsize); spline = gsl_spline_alloc(gsl_interp_cspline, xsize); for (j = 0; j <= ysize - 1; j++) { for (i = 0; i <= xsize - 1; i++) { gsl_vector_set(x, i, xa[i]); gsl_vector_set(y, i, za[IDX2D(i, j, state)]); } gsl_spline_init(spline, x->data, y->data, xsize); for (i = 0; i <= xsize - 1; i++) { state->zx[IDX2D(i, j, state)] = gsl_spline_eval_deriv(spline, xa[i], acc); } } gsl_vector_free(x); gsl_vector_free(y); gsl_spline_free(spline); gsl_interp_accel_reset(acc); x = gsl_vector_alloc(ysize); y = gsl_vector_alloc(ysize); spline = gsl_spline_alloc(gsl_interp_cspline, ysize); for (i = 0; i <= xsize - 1; i++) { for (j = 0; j <= ysize - 1; j++) { gsl_vector_set(x, j, ya[j]); gsl_vector_set(y, j, za[IDX2D(i, j, state)]); } gsl_spline_init(spline, x->data, y->data, ysize); for (j = 0; j <= ysize - 1; j++) { state->zy[IDX2D(i, j, state)] = gsl_spline_eval_deriv(spline, ya[j], acc); } } gsl_vector_free(x); gsl_vector_free(y); gsl_spline_free(spline); gsl_interp_accel_reset(acc); x = gsl_vector_alloc(xsize); y = gsl_vector_alloc(xsize); spline = gsl_spline_alloc(gsl_interp_cspline, xsize); for (j = 0; j <= ysize - 1; j++) { for (i = 0; i <= xsize - 1; i++) { gsl_vector_set(x, i, xa[i]); gsl_vector_set(y, i, state->zy[IDX2D(i, j, state)]); } gsl_spline_init(spline, x->data, y->data, xsize); for (i = 0; i <= xsize - 1; i++) { state->zxy[IDX2D(i, j, state)] = gsl_spline_eval_deriv(spline, xa[i], acc); } } gsl_vector_free(x); gsl_vector_free(y); gsl_spline_free(spline); gsl_interp_accel_free(acc); return GSL_SUCCESS; } /* bicubic_init() */ static int bicubic_eval(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; double dx, dy; /* size of the grid cell */ double dt, du; /* * t and u are the positions within the grid cell at which we are computing * the interpolation, in units of grid cell size */ double t, u; double t0, t1, t2, t3, u0, u1, u2, u3; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* Get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; t2 = t*t; t3 = t*t2; u0 = 1; u1 = u; u2 = u*u; u3 = u*u2; *z = 0; v = zminmin; *z += v*t0*u0; v = zyminmin; *z += v*t0*u1; v = -3*zminmin + 3*zminmax - 2*zyminmin - zyminmax; *z += v*t0*u2; v = 2*zminmin - 2*zminmax + zyminmin + zyminmax; *z += v*t0*u3; v = zxminmin; *z += v*t1*u0; v = zxyminmin; *z += v*t1*u1; v = -3*zxminmin + 3*zxminmax - 2*zxyminmin - zxyminmax; *z += v*t1*u2; v = 2*zxminmin - 2*zxminmax + zxyminmin + zxyminmax; *z += v*t1*u3; v = -3*zminmin + 3*zmaxmin - 2*zxminmin - zxmaxmin; *z += v*t2*u0; v = -3*zyminmin + 3*zymaxmin - 2*zxyminmin - zxymaxmin; *z += v*t2*u1; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z += v*t2*u2; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z += v*t2*u3; v = 2*zminmin - 2*zmaxmin + zxminmin + zxmaxmin; *z += v*t3*u0; v = 2*zyminmin - 2*zymaxmin + zxyminmin + zxymaxmin; *z += v*t3*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z += v*t3*u2; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z += v*t3*u3; return GSL_SUCCESS; } /* bicubic_eval() */ static int bicubic_deriv_x(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_p) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; double dx, dy; /* size of the grid cell */ double dt, du; /* * t and u are the positions within the grid cell at which we are computing * the interpolation, in units of grid cell size */ double t, u; double t0, t1, t2, u0, u1, u2, u3; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; t2 = t*t; u0 = 1; u1 = u; u2 = u*u; u3 = u*u2; *z_p = 0; v = zxminmin; *z_p += v*t0*u0; v = zxyminmin; *z_p += v*t0*u1; v = -3*zxminmin + 3*zxminmax - 2*zxyminmin - zxyminmax; *z_p += v*t0*u2; v = 2*zxminmin - 2*zxminmax + zxyminmin + zxyminmax; *z_p += v*t0*u3; v = -3*zminmin + 3*zmaxmin - 2*zxminmin - zxmaxmin; *z_p += 2*v*t1*u0; v = -3*zyminmin + 3*zymaxmin - 2*zxyminmin - zxymaxmin; *z_p += 2*v*t1*u1; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z_p += 2*v*t1*u2; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z_p += 2*v*t1*u3; v = 2*zminmin - 2*zmaxmin + zxminmin + zxmaxmin; *z_p += 3*v*t2*u0; v = 2*zyminmin - 2*zymaxmin + zxyminmin + zxymaxmin; *z_p += 3*v*t2*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z_p += 3*v*t2*u2; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z_p += 3*v*t2*u3; *z_p *= dt; return GSL_SUCCESS; } /* bicubic_deriv_x() */ static int bicubic_deriv_y(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_p) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; /* dx and dy are the size of the grid cell */ double dx, dy; double dt, du; /* t and u are the positions within the grid cell at which we are * computing the interpolation, in units of grid cell size */ double t, u; double t0, t1, t2, t3, u0, u1, u2; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; t2 = t*t; t3 = t*t2; u0 = 1; u1 = u; u2 = u*u; *z_p = 0; v = zyminmin; *z_p += v*t0*u0; v = -3*zminmin + 3*zminmax - 2*zyminmin - zyminmax; *z_p += 2*v*t0*u1; v = 2*zminmin-2*zminmax + zyminmin + zyminmax; *z_p += 3*v*t0*u2; v = zxyminmin; *z_p += v*t1*u0; v = -3*zxminmin + 3*zxminmax - 2*zxyminmin - zxyminmax; *z_p += 2*v*t1*u1; v = 2*zxminmin - 2*zxminmax + zxyminmin + zxyminmax; *z_p += 3*v*t1*u2; v = -3*zyminmin + 3*zymaxmin - 2*zxyminmin - zxymaxmin; *z_p += v*t2*u0; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z_p += 2*v*t2*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z_p += 3*v*t2*u2; v = 2*zyminmin - 2*zymaxmin + zxyminmin + zxymaxmin; *z_p += v*t3*u0; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z_p += 2*v*t3*u1; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z_p += 3*v*t3*u2; *z_p *= du; return GSL_SUCCESS; } static int bicubic_deriv_xx(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_pp) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; double dx, dy; /* size of the grid cell */ double dt, du; /* * t and u are the positions within the grid cell at which we are computing * the interpolation, in units of grid cell size */ double t, u; double t0, t1, u0, u1, u2, u3; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; u0 = 1; u1 = u; u2 = u*u; u3 = u*u2; *z_pp = 0; v = -3*zminmin + 3*zmaxmin - 2*zxminmin - zxmaxmin; *z_pp += 2*v*t0*u0; v = -3*zyminmin + 3*zymaxmin - 2*zxyminmin - zxymaxmin; *z_pp += 2*v*t0*u1; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z_pp += 2*v*t0*u2; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z_pp += 2*v*t0*u3; v = 2*zminmin - 2*zmaxmin + zxminmin + zxmaxmin; *z_pp += 6*v*t1*u0; v = 2*zyminmin - 2*zymaxmin + zxyminmin + zxymaxmin; *z_pp += 6*v*t1*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z_pp += 6*v*t1*u2; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z_pp += 6*v*t1*u3; *z_pp *= dt*dt; return GSL_SUCCESS; } static int bicubic_deriv_xy(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_pp) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; double dx, dy; /* size of the grid cell */ double dt, du; /* * t and u are the positions within the grid cell at which we are computing * the interpolation, in units of grid cell size */ double t, u; double t0, t1, t2, u0, u1, u2; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; t2 = t*t; u0 = 1; u1 = u; u2 = u*u; *z_pp = 0; v = zxyminmin; *z_pp += v*t0*u0; v = -3*zxminmin + 3*zxminmax - 2*zxyminmin - zxyminmax; *z_pp += 2*v*t0*u1; v = 2*zxminmin - 2*zxminmax + zxyminmin + zxyminmax; *z_pp += 3*v*t0*u2; v = -3*zyminmin + 3*zymaxmin - 2*zxyminmin - zxymaxmin; *z_pp += 2*v*t1*u0; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z_pp += 4*v*t1*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z_pp += 6*v*t1*u2; v = 2*zyminmin - 2*zymaxmin + zxyminmin + zxymaxmin; *z_pp += 3*v*t2*u0; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z_pp += 6*v*t2*u1; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z_pp += 9*v*t2*u2; *z_pp *= dt*du; return GSL_SUCCESS; } static int bicubic_deriv_yy(const void * vstate, const double xarr[], const double yarr[], const double zarr[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z_pp) { bicubic_state_t *state = (bicubic_state_t *) vstate; double xmin, xmax, ymin, ymax; double zminmin, zminmax, zmaxmin, zmaxmax; double zxminmin, zxminmax, zxmaxmin, zxmaxmax; double zyminmin, zyminmax, zymaxmin, zymaxmax; double zxyminmin, zxyminmax, zxymaxmin, zxymaxmax; double dx, dy; /* size of the grid cell */ double dt, du; /* * t and u are the positions within the grid cell at which we are computing * the interpolation, in units of grid cell size */ double t, u; double t0, t1, t2, t3, u0, u1; double v; size_t xi, yi; /* first compute the indices into the data arrays where we are interpolating */ if (xa != NULL) xi = gsl_interp_accel_find(xa, xarr, xsize, x); else xi = gsl_interp_bsearch(xarr, x, 0, xsize - 1); if (ya != NULL) yi = gsl_interp_accel_find(ya, yarr, ysize, y); else yi = gsl_interp_bsearch(yarr, y, 0, ysize - 1); /* find the minimum and maximum values on the grid cell in each dimension */ xmin = xarr[xi]; xmax = xarr[xi + 1]; ymin = yarr[yi]; ymax = yarr[yi + 1]; zminmin = zarr[IDX2D(xi, yi, state)]; zminmax = zarr[IDX2D(xi, yi + 1, state)]; zmaxmin = zarr[IDX2D(xi + 1, yi, state)]; zmaxmax = zarr[IDX2D(xi + 1, yi + 1, state)]; /* get the width and height of the grid cell */ dx = xmax - xmin; dy = ymax - ymin; t = (x - xmin)/dx; u = (y - ymin)/dy; dt = 1./dx; /* partial t / partial x */ du = 1./dy; /* partial u / partial y */ zxminmin = state->zx[IDX2D(xi, yi, state)]/dt; zxminmax = state->zx[IDX2D(xi, yi + 1, state)]/dt; zxmaxmin = state->zx[IDX2D(xi + 1, yi, state)]/dt; zxmaxmax = state->zx[IDX2D(xi + 1, yi + 1, state)]/dt; zyminmin = state->zy[IDX2D(xi, yi, state)]/du; zyminmax = state->zy[IDX2D(xi, yi + 1, state)]/du; zymaxmin = state->zy[IDX2D(xi + 1, yi, state)]/du; zymaxmax = state->zy[IDX2D(xi + 1, yi + 1, state)]/du; zxyminmin = state->zxy[IDX2D(xi, yi, state)]/(dt*du); zxyminmax = state->zxy[IDX2D(xi, yi + 1, state)]/(dt*du); zxymaxmin = state->zxy[IDX2D(xi + 1, yi, state)]/(dt*du); zxymaxmax = state->zxy[IDX2D(xi + 1, yi + 1, state)]/(dt*du); t0 = 1; t1 = t; t2 = t*t; t3 = t*t2; u0 = 1; u1 = u; *z_pp = 0; v = -3*zminmin + 3*zminmax - 2*zyminmin - zyminmax; *z_pp += 2*v*t0*u0; v = 2*zminmin-2*zminmax + zyminmin + zyminmax; *z_pp += 6*v*t0*u1; v = -3*zxminmin + 3*zxminmax - 2*zxyminmin - zxyminmax; *z_pp += 2*v*t1*u0; v = 2*zxminmin - 2*zxminmax + zxyminmin + zxyminmax; *z_pp += 6*v*t1*u1; v = 9*zminmin - 9*zmaxmin + 9*zmaxmax - 9*zminmax + 6*zxminmin + 3*zxmaxmin - 3*zxmaxmax - 6*zxminmax + 6*zyminmin - 6*zymaxmin - 3*zymaxmax + 3*zyminmax + 4*zxyminmin + 2*zxymaxmin + zxymaxmax + 2*zxyminmax; *z_pp += 2*v*t2*u0; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 4*zxminmin - 2*zxmaxmin + 2*zxmaxmax + 4*zxminmax - 3*zyminmin + 3*zymaxmin + 3*zymaxmax - 3*zyminmax - 2*zxyminmin - zxymaxmin - zxymaxmax - 2*zxyminmax; *z_pp += 6*v*t2*u1; v = -6*zminmin + 6*zmaxmin - 6*zmaxmax + 6*zminmax - 3*zxminmin - 3*zxmaxmin + 3*zxmaxmax + 3*zxminmax - 4*zyminmin + 4*zymaxmin + 2*zymaxmax - 2*zyminmax - 2*zxyminmin - 2*zxymaxmin - zxymaxmax - zxyminmax; *z_pp += 2*v*t3*u0; v = 4*zminmin - 4*zmaxmin + 4*zmaxmax - 4*zminmax + 2*zxminmin + 2*zxmaxmin - 2*zxmaxmax - 2*zxminmax + 2*zyminmin - 2*zymaxmin - 2*zymaxmax + 2*zyminmax + zxyminmin + zxymaxmin + zxymaxmax + zxyminmax; *z_pp += 6*v*t3*u1; *z_pp *= du*du; return GSL_SUCCESS; } static const gsl_interp2d_type bicubic_type = { "bicubic", 4, &bicubic_alloc, &bicubic_init, &bicubic_eval, &bicubic_deriv_x, &bicubic_deriv_y, &bicubic_deriv_xx, &bicubic_deriv_xy, &bicubic_deriv_yy, &bicubic_free }; const gsl_interp2d_type * gsl_interp2d_bicubic = &bicubic_type; #undef IDX2D
{ "alphanum_fraction": 0.6206556569, "avg_line_length": 35.2344913151, "ext": "c", "hexsha": "7db14feee0a05b106360de1a6186f28411a2fb0f", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/bicubic.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/bicubic.c", "max_line_length": 210, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/interpolation/bicubic.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 11335, "size": 28399 }
#include <iostream> #define ARMA_64BIT_WORD #include <armadillo> #include <gsl/gsl_rng.h> #include <gsl/gsl_sf_psi.h> #include <list> #include "utils.h" #include "eval.h" using namespace std; using namespace arma; #include "data.h" struct model_settings { bool verbose; string outdir; string datadir; double a_theta; double b_theta; double a_beta; double b_beta; double a_tau; double b_tau; double a_delta; double b_delta; bool social_only; bool factor_only; bool fix_influence; bool item_bias; bool binary; bool directed; long seed; int save_freq; int eval_freq; int conv_freq; int max_iter; int min_iter; double likelihood_delta; bool svi; bool final_pass; bool final_pass_test; int sample_size; double delay; double forget; int k; void set(bool print, string out, string data, bool use_svi, double athe, double bthe, double abet, double bbet, double atau, double btau, double adelta, double bdelta, bool social, bool factor, bool bias, bool bin, bool dir, long rand, int savef, int evalf, int convf, int iter_max, int iter_min, double delta, bool finalpass, bool finalpasstest, int sample, double svi_delay, double svi_forget, bool fix, int num_factors) { verbose = print; outdir = out; datadir = data; svi = use_svi; a_theta = athe; b_theta = bthe; a_beta = abet; b_beta = bbet; a_tau = atau; b_tau = btau; a_delta = adelta; b_delta = bdelta; social_only = social; factor_only = factor; fix_influence = fix; item_bias = bias; binary = bin; directed = dir; seed = rand; save_freq = savef; eval_freq = evalf; conv_freq = convf; max_iter = iter_max; min_iter = iter_min; likelihood_delta = delta; final_pass = finalpass; final_pass_test = finalpasstest; sample_size = sample; delay = svi_delay; forget = svi_forget; k = num_factors; } void set_stochastic_inference(bool setting) { svi = setting; } void set_sample_size(int setting) { sample_size = setting; } void save(string filename) { FILE* file = fopen(filename.c_str(), "w"); fprintf(file, "data directory: %s\n", datadir.c_str()); fprintf(file, "\nmodel specification:\n"); if (social_only) { fprintf(file, "\tsocial factorization (SF) [ social factors only ]\n"); } else if (factor_only) { fprintf(file, "\tPoisson factorization (PF) [ general preference factors only ]\n"); } else { fprintf(file, "\tsocial Poisson factorization (SPF)\n"); } if (fix_influence) { fprintf(file,"\tsocial influence parameters fixed to 1\n"); } if (!social_only) { fprintf(file, "\tK = %d (number of latent factors for general preferences)\n", k); } fprintf(file, "\nshape and rate hyperparameters:\n"); if (!social_only) { fprintf(file, "\ttheta (%f, %f)\n", a_theta, b_theta); fprintf(file, "\tbeta (%f, %f)\n", a_beta, b_beta); } if (!factor_only) { fprintf(file, "\ttau (%f, %f)\n", a_tau, b_tau); } if (item_bias) { fprintf(file, "\tdelta (%.2f, %.2f)\n", a_delta, b_delta); } fprintf(file, "\ndata attributes:\n"); if (binary) { fprintf(file, "\tbinary ratings\n"); } else { fprintf(file, "\tinteger ratings\n"); } if (!factor_only) { if (directed) { fprintf(file, "\tdirected network\n"); } else { fprintf(file, "\tundirected network\n"); } } fprintf(file, "\ninference parameters:\n"); fprintf(file, "\tseed: %d\n", (int)seed); fprintf(file, "\tsave frequency: %d\n", save_freq); fprintf(file, "\tevaluation frequency: %d\n", eval_freq); fprintf(file, "\tconvergence check frequency: %d\n", conv_freq); fprintf(file, "\tmaximum number of iterations: %d\n", max_iter); fprintf(file, "\tminimum number of iterations: %d\n", min_iter); fprintf(file, "\tchange in log likelihood for convergence: %f\n", likelihood_delta); fprintf(file, "\tfinal pass after convergence: %s\n", final_pass ? "all users" : (final_pass_test ? "test users only" : "none")); if (svi) { fprintf(file, "\nStochastic variational inference parameters\n"); fprintf(file, "\tsample size: %d\n", sample_size); fprintf(file, "\tSVI delay (tau): %f\n", delay); fprintf(file, "\tSVI forgetting rate (kappa): %f\n", forget); } else { fprintf(file, "\nusing batch variational inference\n"); } fclose(file); } }; class SPF: protected Model { private: model_settings* settings; Data* data; // model parameters sp_fmat tau; // user influence sp_fmat logtau; // fake "log" user influence // it's really exp(E[log(tau)]) which != E[tau] fmat theta; // user preferences fmat beta; // item attributes fmat logtheta; // log variant of above fmat logbeta; // ditto fvec delta; // helper parameters sp_fmat a_tau; sp_fmat b_tau; fmat a_theta; fmat b_theta; fmat a_beta; fmat a_beta_user; fmat a_beta_old; fmat b_beta; fvec a_delta; float b_delta; fvec a_delta_user; fvec a_delta_old; // random number generator gsl_rng* rand_gen; void initialize_parameters(); void reset_helper_params(); void save_parameters(string label); // parameter updates void update_shape(int user, int item, int rating); double update_tau(int user); double update_theta(int user); void update_beta(int item); void update_delta(int item); double get_ave_log_likelihood(); void log_convergence(int iteration, double ave_ll, double delta_ll); void log_time(int iteration, double duration); void log_params(int iteration, double tau_change, double theta_change); void log_user(FILE* file, int user, int heldout, double rmse, double mae, double rank, int first, double crr, double ncrr, double ndcg); // define how to scale updates (training / sample size) (for SVI) double scale; // counts of number of times an item has been seen in a sample (for SVI) map<int,int> iter_count; void evaluate(string label); void evaluate(string label, bool write_rankings); public: SPF(model_settings* model_set, Data* dataset); void learn(); double predict(int user, int item); void evaluate(); };
{ "alphanum_fraction": 0.5462074405, "avg_line_length": 29.71484375, "ext": "h", "hexsha": "e0d0b9b90fba4fbf31a272074d847825923e1de0", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-04-06T20:17:32.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-13T00:22:21.000Z", "max_forks_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ajbc/spf", "max_forks_repo_path": "src/spf.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_issues_repo_issues_event_max_datetime": "2017-02-09T11:39:46.000Z", "max_issues_repo_issues_event_min_datetime": "2016-11-29T10:43:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ajbc/spf", "max_issues_repo_path": "src/spf.h", "max_line_length": 101, "max_stars_count": 28, "max_stars_repo_head_hexsha": "a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ajbc/spf", "max_stars_repo_path": "src/spf.h", "max_stars_repo_stars_event_max_datetime": "2021-09-08T19:56:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-08T23:07:07.000Z", "num_tokens": 1781, "size": 7607 }
#ifndef _RandomHistObject_H #define _RandomHistObject_H #include <gsl/gsl_histogram.h> #include <QObject> #include <QVector> #include "src_config.h" class RandomNumberGen; class _HIST_EXPORT_ RandomHistObject : public QObject { public: static RandomHistObject * getRandomHistObject (QObject * parent=0); void GUIRandomProc (QWidget * parent=0, Qt::WindowFlags flags=0); void GUIHistogramParams (QWidget * parent=0, Qt::WindowFlags flags=0); void calcHist (void); void GUIViewHist (QWidget * parent=0, Qt::WindowFlags flags=0); enum DistrFuncs { Uniform=0, Gaussian=1, Exponential=2 }; signals: void viewResults (QWidget * w); private: // // Functions // RandomHistObject (QObject * parent=0); virtual ~RandomHistObject (void); private: // // Variables // static RandomHistObject * self; RandomNumberGen * rGenerator; QVector<double> resNumb; gsl_histogram * hist; private: Q_OBJECT }; #endif
{ "alphanum_fraction": 0.6788537549, "avg_line_length": 20.24, "ext": "h", "hexsha": "3d64ddfaa7da5fb00ddc5e5ce1415530ff912962", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "YuriyRusinov/Histogram", "max_forks_repo_path": "src/gui/RandomHistObj.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "YuriyRusinov/Histogram", "max_issues_repo_path": "src/gui/RandomHistObj.h", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "76aff0621acf6d43449cabd5c54c950c77ba7c2c", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "YuriyRusinov/Histogram", "max_stars_repo_path": "src/gui/RandomHistObj.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 259, "size": 1012 }
#pragma once #include <gsl/span> #include <cstddef> namespace imageview { // Class representing a color in RGBA32 color space. class RGBA32 { public: constexpr RGBA32() noexcept = default; constexpr RGBA32(unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) noexcept : red(red), green(green), blue(blue), alpha(alpha) {} unsigned char red = 0; unsigned char green = 0; unsigned char blue = 0; unsigned char alpha = 0; }; // Implementation of the PixelFormat concept for RGBA32 pixel format. // In this pixel format the color is represented via 4 8-bit integers, // specifying the red, green, blue and alpha channels. When serializing to / // deserializing from a byte array, the order of the channels is RGBA (i.e. // not BGRA). class PixelFormatRGBA32 { public: using color_type = RGBA32; static constexpr int kBytesPerPixel = 4; constexpr color_type read(gsl::span<const std::byte, kBytesPerPixel> data) const; constexpr void write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const; }; constexpr bool operator==(const RGBA32& lhs, const RGBA32& rhs) { return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue && lhs.alpha == rhs.alpha; } constexpr bool operator!=(const RGBA32& lhs, const RGBA32& rhs) { return !(lhs == rhs); } constexpr PixelFormatRGBA32::color_type PixelFormatRGBA32::read(gsl::span<const std::byte, kBytesPerPixel> data) const { return color_type(static_cast<unsigned char>(data[0]), static_cast<unsigned char>(data[1]), static_cast<unsigned char>(data[2]), static_cast<unsigned char>(data[3])); } constexpr void PixelFormatRGBA32::write(const color_type& color, gsl::span<std::byte, kBytesPerPixel> data) const { data[0] = static_cast<std::byte>(color.red); data[1] = static_cast<std::byte>(color.green); data[2] = static_cast<std::byte>(color.blue); data[3] = static_cast<std::byte>(color.alpha); } } // namespace imageview
{ "alphanum_fraction": 0.7159318637, "avg_line_length": 35.0175438596, "ext": "h", "hexsha": "3d209c75d7987f05ed64c10b5dd1cc9fa0936d6a", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alexanderbelous/imageview", "max_issues_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_path": "include/imageview/pixel_formats/PixelFormatRGBA32.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 502, "size": 1996 }
#include "matrix.h" #include <cblas.h> #include <malloc.h> #include <stdio.h> #include <stdlib.h> Matrix *create_mat(char *path) { Matrix *m = malloc(sizeof(Matrix)); m->row_len = 0; m->col_len = 0; FILE *myfile = fopen(path, "r"); int ch = 0; while (ch != EOF) { ch = fgetc(myfile); if (m->row_len == 0 && ch == ' ') { m->col_len++; } if (ch == '\n') { m->row_len++; } }; m->col_len++; m->p_mat = calloc(m->row_len, sizeof(float *)); for (int i = 0; i < m->row_len; i++) { m->p_mat[i] = calloc(m->col_len, sizeof(float)); } rewind(myfile); for (int i = 0; i < m->row_len; i++) { for (int j = 0; j < m->col_len; j++) { if (!fscanf(myfile, "%f", &m->p_mat[i][j])) { break; } } } fclose(myfile); return m; } void delete_mat(Matrix *mat) { for (int i = 0; i < mat->row_len; i++) { free(mat->p_mat[i]); } free(mat->p_mat); free(mat); } void copy_mat(Matrix *target, Matrix *source) { delete_mat(target); target->row_len = source->row_len; target->col_len = source->col_len; target->p_mat = calloc(target->row_len, sizeof(float *)); for (int i = 0; i < target->row_len; i++) { target->p_mat[i] = calloc(target->col_len, sizeof(float)); } for (int i = 0; i < target->row_len; i++) { for (int j = 0; j < target->col_len; j++) { target->p_mat[i][j] = source->p_mat[i][j]; } } } Matrix *multiple_mat(Matrix *mat1, Matrix *mat2) { Matrix *result = malloc(sizeof(Matrix)); result->row_len = mat1->row_len; result->col_len = mat2->col_len; result->p_mat = calloc(result->row_len, sizeof(float *)); for (int i = 0; i < result->row_len; ++i) result->p_mat[i] = calloc(result->col_len, sizeof(float)); #pragma omp parallel for for (int i = 0; i < result->row_len; i++) { for (int k = 0; k < mat1->col_len; k++) { float tmp = mat1->p_mat[i][k]; for (int j = 0; j < result->col_len; j++) { result->p_mat[i][j] += tmp * mat2->p_mat[k][j]; } } } return result; } void write_mat(char *path, Matrix *mat) { FILE *myfile = fopen(path, "w"); for (int i = 0; i < mat->row_len; i++) { for (int j = 0; j < mat->col_len; j++) { if (j == mat->col_len - 1) { fprintf(myfile, "%f\n", mat->p_mat[i][j]); } else { fprintf(myfile, "%f ", mat->p_mat[i][j]); } } } } void display_mat(Matrix *m1) { for (int i = 0; i < m1->row_len; i++) { for (int j = 0; j < m1->col_len; j++) { if (j == m1->col_len - 1) { printf("%f\n", m1->p_mat[i][j]); } else { printf("%f ", m1->p_mat[i][j]); } } } } Matrix *calc_with_OpenBLAS(Matrix *m1, Matrix *m2) { Matrix *result = malloc(sizeof(Matrix)); result->row_len = m1->row_len; result->col_len = m2->col_len; result->p_mat = calloc(result->row_len, sizeof(float *)); for (int i = 0; i < result->row_len; ++i) result->p_mat[i] = calloc(result->col_len, sizeof(float)); const int M = m1->row_len; const int N = m2->col_len; const int K = m1->col_len; int lda = K; int ldb = N; int ldc = N; float *A = calloc(M * K, sizeof(float)); float *B = calloc(K * N, sizeof(float)); float *C = calloc(M * N, sizeof(float)); int k = 0; for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { A[k] = m1->p_mat[i][j]; k += 1; } } k = 0; for (int i = 0; i < K; i++) { for (int j = 0; j < N; j++) { B[k] = m2->p_mat[i][j]; k += 1; } } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, A, lda, B, ldb, 1.0f, C, ldc); k = 0; for (int i = 0; i < result->row_len; i++) { for (int j = 0; j < result->col_len; j++) { result->p_mat[i][j] = C[k]; k++; } } free(A); free(B); free(C); return result; }
{ "alphanum_fraction": 0.5219092332, "avg_line_length": 24.735483871, "ext": "c", "hexsha": "84b44490bc990c46c11dbb56b94d5abf29aee154", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_forks_repo_path": "project/3/matrix.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_issues_repo_path": "project/3/matrix.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "9d4fc9a902fff2f76e41314f5d6c52871d30a511", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Aries-Dawn/Cpp-Program-Design", "max_stars_repo_path": "project/3/matrix.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1363, "size": 3834 }
/* permutation/permutation.c * * Copyright (C) 2001, 2002 Nicolas Darnis * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Modified for GSL by Brian Gough. * Use in-place algorithms, no need for workspace * Use conventions for canonical form given in Knuth (opposite of Sedgewick) */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_permutation.h> int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p) { const size_t n = p->size; size_t i, k, s; size_t t = n; const size_t *const pp = p->data; size_t *const qq = q->data; if (q->size != p->size) { GSL_ERROR ("size of q does not match size of p", GSL_EINVAL); } for (i = 0; i < n; i++) { k = pp[i]; s = 1; while (k > i) { k = pp[k]; s++; } if (k < i) continue; /* Now have k == i, i.e the least in its cycle, and s == cycle length */ t -= s; qq[t] = i; k = pp[i]; s = 1; while (k > i) { qq[t + s] = k; k = pp[k]; s++; } if (t == 0) break; } return GSL_SUCCESS; } int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q) { size_t i, k, kk, first; const size_t n = p->size; size_t *const pp = p->data; const size_t *const qq = q->data; if (q->size != p->size) { GSL_ERROR ("size of q does not match size of p", GSL_EINVAL); } for (i = 0; i < n; i++) { pp[i] = i; } k = qq[0]; first = pp[k]; for (i = 1; i < n; i++) { kk = qq[i]; if (kk > first) { pp[k] = pp[kk]; k = kk; } else { pp[k] = first; k = kk; first = pp[kk]; } } pp[k] = first; return GSL_SUCCESS; } size_t gsl_permutation_inversions (const gsl_permutation * p) { size_t count = 0; size_t i, j; const size_t size = p->size; for (i = 0; i < size - 1; i++) { for (j = i + 1; j < size; j++) { if (p->data[i] > p->data[j]) { count++; } } } return count; } size_t gsl_permutation_linear_cycles (const gsl_permutation * p) { size_t i, k; size_t count = 0; const size_t size = p->size; for (i = 0; i < size; i++) { k = p->data[i]; while (k > i) { k = p->data[k]; } if (k < i) continue; count++; } return count; } size_t gsl_permutation_canonical_cycles (const gsl_permutation * p) { size_t i; size_t count = 1; size_t min = p->data[0]; for (i = 0; i < p->size; i++) { if (p->data[i] < min) { min = p->data[i]; count++; } } return count; }
{ "alphanum_fraction": 0.5210643016, "avg_line_length": 18.5025641026, "ext": "c", "hexsha": "080c8eebc09254cc69d1878db29cf0afa734950d", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/permutation/canonical.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/permutation/canonical.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/permutation/canonical.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1056, "size": 3608 }
/** * * @file qwrapper_slaswp.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:44:58 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_slaswp(Quark *quark, Quark_Task_Flags *task_flags, int n, float *A, int lda, int i1, int i2, const int *ipiv, int inc) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_slaswp_quark, task_flags, sizeof(int), &n, VALUE, sizeof(float)*lda*n, A, INOUT | LOCALITY, sizeof(int), &lda, VALUE, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*n, ipiv, INPUT, sizeof(int), &inc, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp_quark = PCORE_slaswp_quark #define CORE_slaswp_quark PCORE_slaswp_quark #endif void CORE_slaswp_quark(Quark *quark) { int n, lda, i1, i2, inc; int *ipiv; float *A; quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc); LAPACKE_slaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc ); } /***************************************************************************//** * **/ void QUARK_CORE_slaswp_f2(Quark *quark, Quark_Task_Flags *task_flags, int n, float *A, int lda, int i1, int i2, const int *ipiv, int inc, float *fake1, int szefake1, int flag1, float *fake2, int szefake2, int flag2) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_slaswp_f2_quark, task_flags, sizeof(int), &n, VALUE, sizeof(float)*lda*n, A, INOUT | LOCALITY, sizeof(int), &lda, VALUE, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*n, ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*szefake1, fake1, flag1, sizeof(float)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp_f2_quark = PCORE_slaswp_f2_quark #define CORE_slaswp_f2_quark PCORE_slaswp_f2_quark #endif void CORE_slaswp_f2_quark(Quark* quark) { int n, lda, i1, i2, inc; int *ipiv; float *A; void *fake1, *fake2; quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2); LAPACKE_slaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc ); } /***************************************************************************//** * **/ void QUARK_CORE_slaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, float *Aij, int i1, int i2, const int *ipiv, int inc, float *fakepanel) { DAG_CORE_LASWP; if (fakepanel == Aij) { QUARK_Insert_Task( quark, CORE_slaswp_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*1, fakepanel, SCRATCH, 0); } else { QUARK_Insert_Task( quark, CORE_slaswp_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*1, fakepanel, INOUT, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp_ontile_quark = PCORE_slaswp_ontile_quark #define CORE_slaswp_ontile_quark PCORE_slaswp_ontile_quark #endif void CORE_slaswp_ontile_quark(Quark *quark) { int i1, i2, inc; int *ipiv; float *A, *fake; PLASMA_desc descA; quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake); CORE_slaswp_ontile(descA, i1, i2, ipiv, inc); } /***************************************************************************//** * **/ void QUARK_CORE_slaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, float *Aij, int i1, int i2, const int *ipiv, int inc, float *fake1, int szefake1, int flag1, float *fake2, int szefake2, int flag2) { DAG_CORE_LASWP; QUARK_Insert_Task( quark, CORE_slaswp_ontile_f2_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*szefake1, fake1, flag1, sizeof(float)*szefake2, fake2, flag2, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswp_ontile_f2_quark = PCORE_slaswp_ontile_f2_quark #define CORE_slaswp_ontile_f2_quark PCORE_slaswp_ontile_f2_quark #endif void CORE_slaswp_ontile_f2_quark(Quark *quark) { int i1, i2, inc; int *ipiv; float *A; PLASMA_desc descA; void *fake1, *fake2; quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2); CORE_slaswp_ontile(descA, i1, i2, ipiv, inc); } /***************************************************************************//** * **/ void QUARK_CORE_sswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, float *Aij, int i1, int i2, const int *ipiv, int inc, const float *Akk, int ldak) { DAG_CORE_TRSM; QUARK_Insert_Task( quark, CORE_sswptr_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*ldak, Akk, INPUT, sizeof(int), &ldak, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_sswptr_ontile_quark = PCORE_sswptr_ontile_quark #define CORE_sswptr_ontile_quark PCORE_sswptr_ontile_quark #endif void CORE_sswptr_ontile_quark(Quark *quark) { int i1, i2, inc, ldak; int *ipiv; float *A, *Akk; PLASMA_desc descA; quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak); CORE_sswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak); } /***************************************************************************//** * **/ void QUARK_CORE_slaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_desc descA, float *Aij, int i1, int i2, const int *ipiv, int inc, float *fakepanel) { DAG_CORE_LASWP; if (fakepanel == Aij) { QUARK_Insert_Task( quark, CORE_slaswpc_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*1, fakepanel, SCRATCH, 0); } else { QUARK_Insert_Task( quark, CORE_slaswpc_ontile_quark, task_flags, sizeof(PLASMA_desc), &descA, VALUE, sizeof(float)*1, Aij, INOUT | LOCALITY, sizeof(int), &i1, VALUE, sizeof(int), &i2, VALUE, sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT, sizeof(int), &inc, VALUE, sizeof(float)*1, fakepanel, INOUT, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slaswpc_ontile_quark = PCORE_slaswpc_ontile_quark #define CORE_slaswpc_ontile_quark PCORE_slaswpc_ontile_quark #endif void CORE_slaswpc_ontile_quark(Quark *quark) { int i1, i2, inc; int *ipiv; float *A, *fake; PLASMA_desc descA; quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake); CORE_slaswpc_ontile(descA, i1, i2, ipiv, inc); }
{ "alphanum_fraction": 0.4739958551, "avg_line_length": 35.9326241135, "ext": "c", "hexsha": "ccc69716a8e765ede97ecaa30375037557d5b05f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_slaswp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2745, "size": 10133 }
// // rope.hpp // Fans // // Created by tqtifnypmb on 06/12/2017. // Copyright © 2017 tqtifnypmb. All rights reserved. // #pragma once #include <memory> #include <functional> #include <vector> #include <string> #include <gsl/gsl> #include "RopeNode.h" #include "Range.h" #include "RopeIter.h" #include "../types.h" namespace brick { class Rope { public: static constexpr size_t max_leaf_length = 1; Rope(Rope&& l, Rope&& r); Rope(); Rope(const Rope&); Rope(Rope&& r) = default; Rope& operator=(Rope&&) = default; Rope& operator=(const Rope&) = delete; template <class Converter> void insert(gsl::span<const char> bytes, size_t pos); void insert(const detail::CodePointList& cp, size_t pos); void erase(const Range& range); size_t size() const { return size_; } RopeIter begin() const; RopeIter end() const; std::reverse_iterator<RopeIter> rbegin() const { return std::reverse_iterator<RopeIter>(end()); } std::reverse_iterator<RopeIter> rend() const { return std::reverse_iterator<RopeIter>(begin()); } RopeIter iterator(size_t index) const; bool empty() const { return size_ == 0; } void swap(Rope& other) noexcept { std::swap(size_, other.size_); root_.swap(other.root_); } std::string string() const; detail::RopeNode* root_test() { return root_.get(); } detail::RopeNodePtr nextLeaf_test(detail::RopeNode* current) { return nextLeaf(current); } detail::RopeNodePtr prevLeaf_test(detail::RopeNode* current) { return prevLeaf(current); } void rebalance_test() { rebalance(); } std::tuple<detail::RopeNodePtr, size_t> get_test(detail::RopeNode* root, size_t index) { return getLeaf(root, index); } size_t lengthOfWholeRope_test(gsl::not_null<detail::RopeNode*> root) { return lengthOfWholeRope(root); } bool checkHeight(); bool checkLength(); private: friend class RopeIter; static const size_t npos = -1; Rope(std::vector<std::unique_ptr<detail::RopeNode>>& cplist); detail::RopeNodePtr nextLeaf(gsl::not_null<detail::RopeNode*> current) const; detail::RopeNodePtr prevLeaf(gsl::not_null<detail::RopeNode*> current) const; void removeLeaf(detail::RopeNodePtr node); size_t lengthOfWholeRope(gsl::not_null<detail::RopeNode*> root); std::vector<std::unique_ptr<detail::RopeNode>> collectLeaves(bool move) const; bool needBalance(); void rebalance(); std::tuple<detail::RopeNodePtr /* leaf */, size_t /* pos */> getLeaf(gsl::not_null<detail::RopeNode*> root, size_t index, detail::RopeNode** lastVisitedNode = nullptr) const; void insertSubRope(detail::RopeNodePtr leaf, size_t pos, std::unique_ptr<detail::RopeNode> subRope, size_t len); size_t size_ = 0; std::unique_ptr<detail::RopeNode> root_; }; template <class Converter> void Rope::insert(gsl::span<const char> bytes, size_t pos) { insert(Converter::encode(bytes), pos); } } // namespace brick
{ "alphanum_fraction": 0.6383844709, "avg_line_length": 24.196969697, "ext": "h", "hexsha": "638df980d5fa71f4a6f3bf0a48e5ae4e88bc04be", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_path": "src/rope/Rope.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tqtifnypmb/brick", "max_issues_repo_path": "src/rope/Rope.h", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_path": "src/rope/Rope.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 871, "size": 3194 }
// // Autogenerated based on code by L. J. Feldstein // #include <stdio.h> #include <gsl/gsl_matrix.h> #include "cimple_controller.h"
{ "alphanum_fraction": 0.7111111111, "avg_line_length": 16.875, "ext": "c", "hexsha": "5ca87dc09ccd06b208cc27e39f4a0ddd1ca74a7c", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_path": "Interface/Cimple/act_impl.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_path": "Interface/Cimple/act_impl.c", "max_line_length": 49, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_path": "Interface/Cimple/act_impl.c", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "num_tokens": 37, "size": 135 }
/* ** profile.c ** ** Program written in order to calculate profile, characteristic scales and shapes of haloes ** ** Written by Marcel Zemp */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <assert.h> #include <sys/time.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> #include <iof.h> #include <artsfc.h> #define NSPECIESREADMAX 3 #define NSPECIESPROFILEMAX 17 #define NSPECIESBACKGROUND 5 #define NSUBSPECIESMAX 9 #define NPROPERTIESMAX 2 /* ** Be careful with changing order of species here! ** Some loops assume that the order of species are this way. */ #define GAS 0 #define DARK 1 #define STAR 2 #define TOT 3 #define BARYON 4 #define GAS_METAL_SNII 5 #define STAR_METAL_SNII 6 #define BARYON_METAL_SNII 7 #define GAS_METAL_SNIa 8 #define STAR_METAL_SNIa 9 #define BARYON_METAL_SNIa 10 #define GAS_HI 11 #define GAS_HII 12 #define GAS_HeI 13 #define GAS_HeII 14 #define GAS_HeIII 15 #define GAS_H2 16 #define MASS_TOT 0 #define MASS_METAL_SNII 1 #define MASS_METAL_SNIa 2 #define MASS_HI 3 #define MASS_HII 4 #define MASS_HeI 5 #define MASS_HeII 6 #define MASS_HeIII 7 #define MASS_H2 8 #define TEMPERATURE 9 #define AGE 10 typedef struct profile_bin_properties { long int N; /* Number of particles/cells */ double M; /* Mass */ double Menc[2]; /* Enclosed mass - only for internal purposes */ double v[3]; /* Velocity vector */ double vdt[6]; /* Velocity dispersion tensor */ double L[3]; /* Angular momentum vector */ double *P; /* Additional properties */ } PROFILE_BIN_PROPERTIES; typedef struct profile_shape_properties { int NLoopConverged; long int N; /* Number of particles/cells */ double M; /* Mass */ double st[6]; /* Shape tensor */ double a[3]; /* Semi-major axis unit vector */ double b[3]; /* Intermediate axis unit vector */ double c[3]; /* Semi-minor axis unit vector */ double b_a; /* Axis ratio b/a */ double c_a; /* Axis ratio c/a */ double b_a_old; /* Axis ratio b/a for iteration */ double c_a_old; /* Axis ratio c/a for iteration */ /* double dmin; */ /* double dmax; */ /* double propertymin; */ /* double propertymax; */ /* double propertymean; */ } PROFILE_SHAPE_PROPERTIES; typedef struct profile_bin_structure { double ri[3]; double rm[3]; double ro[3]; PROFILE_BIN_PROPERTIES *bin; PROFILE_SHAPE_PROPERTIES *shape; } PROFILE_BIN_STRUCTURE; typedef struct halo_data_exclude { int ID; double rcentre[3]; double size; } HALO_DATA_EXCLUDE; typedef struct halo_data { int ID; int HostHaloID; int ExtraHaloID; int NBin[3]; int NHaloExclude; int SizeExcludeHaloData; int IsTruncated; double rcentre[3]; double vcentre[3]; double rcentrenew[3]; double vcentrenew[3]; double rmean, Mrmean; double rcrit, Mrcrit; double rfix, Mrfix; double rtrunc, Mrtrunc; double size, mass; double rhobg[NSPECIESBACKGROUND]; double rvcmax[NSPECIESBACKGROUND][2]; double Mrvcmax[NSPECIESBACKGROUND][2]; double rtruncindicator; double zAxis[3], zHeight; double rmin[3], rmax[3]; PROFILE_BIN_STRUCTURE ***pbs; HALO_DATA_EXCLUDE *hde; } HALO_DATA; typedef struct profile_particle { double r[3]; double v[3]; double *P; /* Properties array for masses and additional things */ } PROFILE_PARTICLE; typedef struct general_info { int DataFormat; int HaloCatalogueFormat; int HaloCatalogueNDim; int HaloCatalogueBinningCoordinateType; int ExcludeHaloCatalogueFormat; int ExcludeHaloCatalogueNDim; int ProfilingMode; int DataProcessingMode; int CentreType; int BinningCoordinateType; int BinningGridType[3]; int VelocityProjectionType; int ShapeDeterminationVolume; int ShapeTensorForm; int DoMetalSpecies; int DoChemicalSpecies; int DoGasTemperature; int DoStellarAge; int MoreCharacteristicsOutput; int HaloSize; int rmaxFromHaloCatalogue; int ExcludeParticles; int zAxisCatalogueSpecified; int NDimProfile, NBin[3]; int NSpeciesRead, NSpeciesProfile; int NHalo, NHaloExcludeGlobal, NCellData, NCellHalo; int SpeciesContained[NSPECIESPROFILEMAX]; int NParticlePerBlock[NSPECIESREADMAX], NParticleInBlock[NSPECIESREADMAX]; int NSubSpecies[NSPECIESREADMAX], NProperties[NSPECIESREADMAX]; int SizeStorage[NSPECIESREADMAX], NParticleInStorage[NSPECIESREADMAX]; int RecentreUse[NSPECIESREADMAX]; int SizeStorageIncrement; int NLoopRead, NLoopRecentre, NLoopProcessData, NLoopShapeIterationMax, ILoopRead; int OutputFrequencyShapeIteration; int pi[NSPECIESREADMAX][NSUBSPECIESMAX+NPROPERTIESMAX]; int bi[NSPECIESPROFILEMAX][NPROPERTIESMAX]; double rhomean, rhocrit; double rhoencmean, rhoenccrit, rhoencfix; double Deltamean, Deltacrit, Deltafix; double afix; double ascale; double rmin[3], rmax[3]; double NBinPerDex[3]; double bc[6]; double BinFactor; double rExclude; double rRecentre, fRecentreDist; double fcheckrvcmax; double slopertruncindicator; double frhobg; double ShapeIterationTolerance; double fhaloduplicate; double fhaloexcludesize, fhaloexcludedistance; /* double fincludeshapeproperty, fincludeshaperadius; */ double zAxis[3], zHeight; COSMOLOGICAL_PARAMETERS cp; UNIT_SYSTEM us, cosmous; char HaloCatalogueFileName[256], ExcludeHaloCatalogueFileName[256], zAxisCatalogueFileName[256], OutputName[256], MatterTypeName[NSPECIESPROFILEMAX][20]; /* char TotProfilesFileName[256], GasProfilesFileName[256], DarkProfilesFileName[256], StarProfilesFileName[256]; */ } GI; void usage(void); void set_default_values_general_info(GI *); void calculate_densities(GI *); void read_halocatalogue_ascii(GI *, HALO_DATA **); int read_halocatalogue_ascii_excludehalo(GI *, HALO_DATA *, HALO_DATA_EXCLUDE **); void initialise_halo_profile(GI *, HALO_DATA *); void reset_halo_profile_shape(GI, HALO_DATA *); void read_spherical_profiles(GI, HALO_DATA *); void put_particles_in_bins(GI, HALO_DATA *, const int, PROFILE_PARTICLE *); void put_particles_in_storage(GI *, HALO_DATA *, HALO_DATA_EXCLUDE *, const int, PROFILE_PARTICLE *, PROFILE_PARTICLE **); int intersect(double, int, HALO_DATA, int *, double *, double); void copy_pp(GI *, const int , const PROFILE_PARTICLE *, PROFILE_PARTICLE *); void calculate_coordinates_principal_axes(PROFILE_SHAPE_PROPERTIES *, double [3], double [3], double *); void calculate_recentred_halo_coordinates(GI, HALO_DATA *); void calculate_total_matter_distribution(GI, HALO_DATA *); void calculate_baryonic_matter_distribution(GI, HALO_DATA *); int diagonalise_matrix(double [3][3], double *, double [3], double *, double [3], double *, double [3]); double diagonalise_shape_tensors(GI, HALO_DATA *, int); void calculate_halo_properties(GI, HALO_DATA *); void calculate_derived_properties(GI, HALO_DATA *); void calculate_overdensity_characteristics(GI, HALO_DATA *); void calculate_truncation_characteristics(GI, HALO_DATA *); void remove_background(GI, HALO_DATA *); void calculate_halo_size(GI, HALO_DATA *); void calculate_velocity_characteristics(GI, HALO_DATA *); void determine_halo_hierarchy(GI, HALO_DATA *); void write_output_matter_profile(GI, HALO_DATA *); void write_output_shape_profile(GI, HALO_DATA *, int); int main(int argc, char **argv) { int index[3] = {-1,-1,-1}; int L = -1; int ICurrentBlockGas, ICurrentBlockDark, ICurrentBlockStar; int PositionPrecision, VerboseLevel; int LengthType_rmin[3], LengthType_rmax[3], LengthType_zHeight, LengthType_rRecentre, LengthType_rExclude; int LmaxGasAnalysis; int NThreads; int timestart, timeend, timestartsub, timeendsub, timestartloop, timeendloop, timediff; long int d, i, j, k; long int mothercellindex, childcellindex; long int Nparticleread, Ngasread, Ngasanalysis; double celllength, cellvolume; double LBox; int *cellrefined = NULL; long int *Icoordinates = NULL; double ***coordinates = NULL; double r[3], v[3]; double convergencefraction; double number_density; char cdummy[256]; struct timeval time; /* char TotDensityFileName[256], GasDensityFileName[256], DarkDensityFileName[256], StarDensityFileName[256]; */ /* FILE *TotDensityFile = NULL, *GasDensityFile = NULL, *DarkDensityFile = NULL, *StarDensityFile = NULL; */ /* XDR TotDensityXDR, GasDensityXDR, DarkDensityXDR, StarDensityXDR; */ /* ARRAY_HEADER ahtot, ahgas, ahdark, ahstar; */ /* ARRAY_PARTICLE aptot, apgas, apdark, apstar; */ GI gi; TIPSY_HEADER th; TIPSY_GAS_PARTICLE gp; TIPSY_DARK_PARTICLE dp; TIPSY_STAR_PARTICLE sp; TIPSY_GAS_PARTICLE_DPP gpdpp; TIPSY_DARK_PARTICLE_DPP dpdpp; TIPSY_STAR_PARTICLE_DPP spdpp; ART_DATA ad; ART_GAS_PROPERTIES agp; ART_STAR_PROPERTIES asp; ART_COORDINATES *ac = NULL; HALO_DATA *hd = NULL; HALO_DATA_EXCLUDE *hdeg = NULL; PROFILE_PARTICLE **pp = NULL; PROFILE_PARTICLE **pp_storage = NULL; COORDINATE_TRANSFORMATION cosmo2internal_ct; XDR xdrs; fpos_t *PosGasFile = NULL, *PosCoordinatesDataFile = NULL, *PosStarPropertiesFile = NULL; u_int PosXDR = 0; /* u_int PosTotDensityXDR = 0; */ /* u_int PosGasDensityXDR = 0; */ /* u_int PosDarkDensityXDR = 0; */ /* u_int PosStarDensityXDR = 0; */ /* ** Get time */ gettimeofday(&time,NULL); timestart = time.tv_sec; /* ** Set some default values */ PositionPrecision = 0; /* single precision */ VerboseLevel = 0; /* not verbose */ for (d = 0; d < 3; d++) { LengthType_rmin[d] = 0; /* comoving */ LengthType_rmax[d] = 0; /* comoving */ } LengthType_zHeight = 0; /* comoving */ LengthType_rExclude = 0; /* comoving */ LengthType_rRecentre = 0; /* comoving */ Nparticleread = 0; LmaxGasAnalysis = -1; LBox = 0; set_default_values_general_info(&gi); set_default_values_art_data(&ad); set_default_values_coordinate_transformation(&cosmo2internal_ct); /* ** Read in arguments */ i = 1; while (i < argc) { if ((strcmp(argv[i],"-h") == 0) || (strcmp(argv[i],"-help") == 0)) { usage(); } if (strcmp(argv[i],"-version") == 0) { fprintf(stderr,"profile (%s)\n",VERSION); exit(1); } if (strcmp(argv[i],"-spp") == 0) { PositionPrecision = 0; i++; } else if (strcmp(argv[i],"-dpp") == 0) { PositionPrecision = 1; i++; } else if (strcmp(argv[i],"-pfm") == 0) { i++; if (i >= argc) usage(); ad.particle_file_mode = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-DataFormat") == 0) { i++; if (i >= argc) usage(); gi.DataFormat = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-HaloCatalogueFormat") == 0) { i++; if (i >= argc) usage(); gi.HaloCatalogueFormat = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-HaloCatalogueNDim") == 0) { i++; if (i >= argc) usage(); gi.HaloCatalogueNDim = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-HaloCatalogueBinningCoordinateType") == 0) { i++; if (i >= argc) usage(); gi.HaloCatalogueBinningCoordinateType = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ExcludeHaloCatalogueFormat") == 0) { i++; if (i >= argc) usage(); gi.HaloCatalogueFormat = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ExcludeHaloCatalogueNDim") == 0) { i++; if (i >= argc) usage(); gi.ExcludeHaloCatalogueNDim = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ProfilingMode") == 0) { i++; if (i >= argc) usage(); gi.ProfilingMode = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-NDimProfile") == 0) { i++; if (i >= argc) usage(); gi.NDimProfile = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-DataProcessingMode") == 0) { i++; if (i >= argc) usage(); gi.DataProcessingMode = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ShapeDeterminationVolume") == 0) { i++; if (i >= argc) usage(); gi.ShapeDeterminationVolume = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ShapeTensorForm") == 0) { i++; if (i >= argc) usage(); gi.ShapeTensorForm = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-RecentreUseGas") == 0) { i++; if (i >= argc) usage(); gi.RecentreUse[GAS] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-RecentreUseDark") == 0) { i++; if (i >= argc) usage(); gi.RecentreUse[DARK] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-RecentreUseStar") == 0) { i++; if (i >= argc) usage(); gi.RecentreUse[STAR] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-DoMetalSpecies") == 0) { gi.DoMetalSpecies = 1; i++; } else if (strcmp(argv[i],"-DoChemicalSpecies") == 0) { gi.DoChemicalSpecies = 1; i++; } else if (strcmp(argv[i],"-DoGasTemperature") == 0) { gi.DoGasTemperature = 1; i++; } else if (strcmp(argv[i],"-DoStellarAge") == 0) { gi.DoStellarAge = 1; i++; } else if (strcmp(argv[i],"-MoreCharacteristicsOutput") == 0) { gi.MoreCharacteristicsOutput = 1; i++; } else if (strcmp(argv[i],"-HaloSize") == 0) { i++; if (i >= argc) usage(); gi.HaloSize = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ExcludeParticles") == 0) { i++; if (i >= argc) usage(); gi.ExcludeParticles = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-LengthType_rmin") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); LengthType_rmin[d-1] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-LengthType_rmax") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); LengthType_rmax[d-1] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-LengthType_zHeight") == 0) { i++; if (i >= argc) usage(); LengthType_zHeight = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-LengthType_rExclude") == 0) { i++; if (i >= argc) usage(); LengthType_rExclude = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-LengthType_rRecentre") == 0) { i++; if (i >= argc) usage(); LengthType_rRecentre = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ascale") == 0) { i++; if (i >= argc) usage(); gi.ascale = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rmin") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); gi.rmin[d-1] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rmax") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); gi.rmax[d-1] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-NBin") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); gi.NBin[d-1] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-NBinPerDex") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); gi.NBinPerDex[d-1] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-BinningGridType") == 0) { i++; if (i >= argc) usage(); d = atoi(argv[i]); i++; if (i >= argc) usage(); gi.BinningGridType[d-1] = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-CentreType") == 0) { i++; if (i >= argc) usage(); gi.CentreType = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-BinningCoordinateType") == 0) { i++; if (i >= argc) usage(); gi.BinningCoordinateType = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-VelocityProjectionType") == 0) { i++; if (i >= argc) usage(); gi.VelocityProjectionType = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-zAxis_x") == 0) { i++; if (i >= argc) usage(); gi.zAxis[0] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-zAxis_y") == 0) { i++; if (i >= argc) usage(); gi.zAxis[1] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-zAxis_z") == 0) { i++; if (i >= argc) usage(); gi.zAxis[2] = atof(argv[i]); i++; } else if (strcmp(argv[i],"-zHeight") == 0) { i++; if (i >= argc) usage(); gi.zHeight = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rmaxFromHaloCatalogue") == 0) { gi.rmaxFromHaloCatalogue = 1; i++; } else if (strcmp(argv[i],"-BinFactor") == 0) { i++; if (i >= argc) usage(); gi.BinFactor = atof(argv[i]); i++; } else if (strcmp(argv[i],"-Delta_mean") == 0) { i++; if (i >= argc) usage(); gi.Deltamean = atof(argv[i]); i++; } else if (strcmp(argv[i],"-Delta_crit") == 0) { i++; if (i >= argc) usage(); gi.Deltacrit = atof(argv[i]); i++; } else if (strcmp(argv[i],"-Delta_fix") == 0) { i++; if (i >= argc) usage(); gi.Deltafix = atof(argv[i]); i++; } else if (strcmp(argv[i],"-afix") == 0) { i++; if (i >= argc) usage(); gi.afix = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rExclude") == 0) { i++; if (i >= argc) usage(); gi.rExclude = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rRecentre") == 0) { i++; if (i >= argc) usage(); gi.rRecentre = atof(argv[i]); i++; } else if (strcmp(argv[i],"-fRecentreDist") == 0) { i++; if (i >= argc) usage(); gi.fRecentreDist = atof(argv[i]); i++; } else if (strcmp(argv[i],"-fcheckrvcmax") == 0) { i++; if (i >= argc) usage(); gi.fcheckrvcmax = atof(argv[i]); i++; } else if (strcmp(argv[i],"-slopertruncindicator") == 0) { i++; if (i >= argc) usage(); gi.slopertruncindicator = atof(argv[i]); i++; } else if (strcmp(argv[i],"-frhobg") == 0) { i++; if (i >= argc) usage(); gi.frhobg = atof(argv[i]); i++; } else if (strcmp(argv[i],"-ShapeIterationTolerance") == 0) { i++; if (i >= argc) usage(); gi.ShapeIterationTolerance = atof(argv[i]); i++; } else if (strcmp(argv[i],"-fhaloduplicate") == 0) { i++; if (i >= argc) usage(); gi.fhaloduplicate = atof(argv[i]); i++; } else if (strcmp(argv[i],"-fhaloexcludesize") == 0) { i++; if (i >= argc) usage(); gi.fhaloexcludesize = atof(argv[i]); i++; } else if (strcmp(argv[i],"-fhaloexcludedistance") == 0) { i++; if (i >= argc) usage(); gi.fhaloexcludedistance = atof(argv[i]); i++; } /* else if (strcmp(argv[i],"-fincludeshapeproperty") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* gi.fincludeshapeproperty = atof(argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-fincludeshaperadius") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* gi.fincludeshaperadius = atof(argv[i]); */ /* i++; */ /* } */ else if (strcmp(argv[i],"-OmegaM0") == 0) { i++; if (i >= argc) usage(); gi.cp.OmegaM0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-OmegaL0") == 0) { i++; if (i >= argc) usage(); gi.cp.OmegaL0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-OmegaK0") == 0) { i++; if (i >= argc) usage(); gi.cp.OmegaK0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-OmegaR0") == 0) { i++; if (i >= argc) usage(); gi.cp.OmegaR0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-h0_100") == 0) { i++; if (i >= argc) usage(); gi.cp.h0_100 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-LBox") == 0) { i++; if (i >= argc) usage(); LBox = atof(argv[i]); i++; } else if (strcmp(argv[i],"-LBox_internal") == 0) { i++; if (i >= argc) usage(); gi.us.LBox = atof(argv[i]); i++; } else if (strcmp(argv[i],"-rhocrit0_internal") == 0) { i++; if (i >= argc) usage(); gi.us.rhocrit0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-Hubble0_internal") == 0) { i++; if (i >= argc) usage(); gi.us.Hubble0 = atof(argv[i]); i++; } else if (strcmp(argv[i],"-NParticlePerBlockGas") == 0) { i++; if (i >= argc) usage(); gi.NParticlePerBlock[GAS] = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NParticlePerBlockDark") == 0) { i++; if (i >= argc) usage(); gi.NParticlePerBlock[DARK] = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NParticlePerBlockStar") == 0) { i++; if (i >= argc) usage(); gi.NParticlePerBlock[STAR] = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NCellData") == 0) { i++; if (i >= argc) usage(); gi.NCellData = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NCellHalo") == 0) { i++; if (i >= argc) usage(); gi.NCellHalo = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NLoopRecentre") == 0) { i++; if (i >= argc) usage(); gi.NLoopRecentre = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-NLoopShapeIterationMax") == 0) { i++; if (i >= argc) usage(); gi.NLoopShapeIterationMax = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-OutputFrequencySI") == 0) { i++; if (i >= argc) usage(); gi.OutputFrequencyShapeIteration = (int) atof(argv[i]); i++; } else if (strcmp(argv[i],"-LmaxGasAnalysis") == 0) { i++; if (i >= argc) usage(); LmaxGasAnalysis = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-GRAVITY") == 0) { i++; if (i >= argc) usage(); ad.GRAVITY = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-HYDRO") == 0) { i++; if (i >= argc) usage(); ad.HYDRO = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ADVECT_SPECIES") == 0) { i++; if (i >= argc) usage(); ad.ADVECT_SPECIES = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-STARFORM") == 0) { i++; if (i >= argc) usage(); ad.STARFORM = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ENRICH") == 0) { i++; if (i >= argc) usage(); ad.ENRICH = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ENRICH_SNIa") == 0) { i++; if (i >= argc) usage(); ad.ENRICH_SNIa = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-RADIATIVE_TRANSFER") == 0) { i++; if (i >= argc) usage(); ad.RADIATIVE_TRANSFER = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-ELECTRON_ION_NONEQUILIBRIUM") == 0) { i++; if (i >= argc) usage(); ad.ELECTRON_ION_NONEQUILIBRIUM = atoi(argv[i]); i++; } else if (strcmp(argv[i],"-HaloCatalogue") == 0) { i++; if (i >= argc) usage(); strcpy(gi.HaloCatalogueFileName,argv[i]); i++; } else if (strcmp(argv[i],"-ExcludeHaloCatalogue") == 0) { i++; if (i >= argc) usage(); strcpy(gi.ExcludeHaloCatalogueFileName,argv[i]); i++; } else if (strcmp(argv[i],"-zAxisCatalogue") == 0) { i++; if (i >= argc) usage(); strcpy(gi.zAxisCatalogueFileName,argv[i]); gi.zAxisCatalogueSpecified = 1; i++; } else if (strcmp(argv[i],"-Output") == 0) { i++; if (i >= argc) usage(); strcpy(gi.OutputName,argv[i]); i++; } else if (strcmp(argv[i],"-ARTHeader") == 0) { i++; if (i >= argc) usage(); strcpy(ad.HeaderFileName,argv[i]); i++; } else if (strcmp(argv[i],"-ARTCoordinatesData") == 0) { ad.darkcontained = 1; i++; if (i >= argc) usage(); strcpy(ad.CoordinatesDataFileName,argv[i]); i++; } else if (strcmp(argv[i],"-ARTStarProperties") == 0) { ad.starcontained = 1; i++; if (i >= argc) usage(); strcpy(ad.StarPropertiesFileName,argv[i]); i++; } else if (strcmp(argv[i],"-ARTGas") == 0) { ad.gascontained = 1; i++; if (i >= argc) usage(); strcpy(ad.GasFileName,argv[i]); i++; } /* else if (strcmp(argv[i],"-totprofilesfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(gi.TotProfilesFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-gasprofilesfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(gi.GasProfilesFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-darkprofilesfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(gi.DarkProfilesFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-starprofilesfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(gi.StarProfilesFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-totdensityfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(TotDensityFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-gasdensityfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(GasDensityFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-darkdensityfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(DarkDensityFileName,argv[i]); */ /* i++; */ /* } */ /* else if (strcmp(argv[i],"-stardensityfile") == 0) { */ /* i++; */ /* if (i >= argc) usage(); */ /* strcpy(StarDensityFileName,argv[i]); */ /* i++; */ /* } */ else if (strcmp(argv[i],"-verbose") == 0) { VerboseLevel = 1; i++; } else { usage(); } } /* ** Get number of threads */ NThreads = omp_get_max_threads(); fprintf(stderr,"Using in maximum %d OpenMP threads.\n\n",NThreads); /* ** Set some defaults and do some checks */ if (gi.ProfilingMode == 0) { if (gi.DataProcessingMode == 1) { fprintf(stderr,"No normal profiling possible with storage data processing mode. Reset DataProcessingMode = 0.\n\n"); gi.DataProcessingMode = 0; } if (gi.NLoopRecentre > 0) { if (!(gi.rRecentre > 0)) { fprintf(stderr,"No value for rRecentre set. Abort.\n\n"); exit(1); } if (gi.RecentreUse[GAS] == 0 && gi.RecentreUse[DARK] == 0 && gi.RecentreUse[STAR] == 0) { fprintf(stderr,"No recentring species set. Abort.\n\n"); exit(1); } } } if (gi.ProfilingMode == 1) { if (gi.NLoopRecentre > 0) { fprintf(stderr,"No recentering in shape profiling mode allowed. Reset NLoopRecentre = 0.\n\n"); gi.NLoopRecentre = 0; } if (gi.NDimProfile > 1) { fprintf(stderr,"Only one dimension in shape profiling mode allowed. Reset NDimProfile = 1.\n\n"); gi.NDimProfile = 1; } if (gi.DoGasTemperature) { fprintf(stderr,"No need for gas temperatures in shape profiling mode. Reset DoGasTemperature = 0.\n\n"); gi.DoGasTemperature = 0; } if (gi.DoStellarAge) { fprintf(stderr,"No need for stellar ages in shape profiling mode. Reset DoStellarAge = 0.\n\n"); gi.DoStellarAge = 0; } } if (gi.DataFormat == 0) { if (gi.DoMetalSpecies) { fprintf(stderr,"Doing metal species with Tipsy format is not enabled. Reset DoMetalSpecies = 0.\n\n"); gi.DoMetalSpecies = 0; } if (gi.DoChemicalSpecies) { fprintf(stderr,"Doing chemical species with Tipsy format is not enabled. Reset DoChemicalSpecies = 0.\n\n"); gi.DoChemicalSpecies = 0; } } if (gi.DoChemicalSpecies) { if (gi.DoMetalSpecies == 0) { fprintf(stderr,"DoMetalSpecies was automatically switched on since it is necessary for doing chemical species.\n\n"); gi.DoMetalSpecies = 1; } gi.NSpeciesProfile = 17; } else if (gi.DoMetalSpecies) { gi.NSpeciesProfile = 11; } assert(gi.NSpeciesRead <= NSPECIESREADMAX); assert(gi.NSpeciesProfile <= NSPECIESPROFILEMAX); for (j = 0; j < gi.NSpeciesRead; j++) assert(gi.NParticlePerBlock[j] > 0); assert(gi.NCellData > 0); assert(gi.NCellHalo > 0); assert(gi.ProfilingMode < 2); if (gi.ProfilingMode == 1) assert(gi.NDimProfile == 1); assert(gi.DataProcessingMode < 2); assert(gi.NDimProfile > 0); assert(gi.NDimProfile < 3); assert(gi.HaloCatalogueNDim < 3); assert(gi.ExcludeHaloCatalogueNDim < 3); if (gi.HaloCatalogueFormat == 1) assert(gi.HaloCatalogueNDim == 1); /* ** Prepare data arrays */ pp = malloc(gi.NSpeciesRead*sizeof(PROFILE_PARTICLE *)); assert(pp != NULL); pp_storage = malloc(gi.NSpeciesRead*sizeof(PROFILE_PARTICLE *)); assert(pp_storage != NULL); for (j = 0; j < gi.NSpeciesRead; j++) { if (j == GAS) { if (gi.DoMetalSpecies) { gi.NSubSpecies[GAS] += 2; gi.pi[GAS][MASS_METAL_SNII] = 1; gi.pi[GAS][MASS_METAL_SNIa] = 2; } if (gi.DoChemicalSpecies) { gi.NSubSpecies[GAS] += 6; gi.pi[GAS][MASS_HI] = 3; gi.pi[GAS][MASS_HII] = 4; gi.pi[GAS][MASS_HeI] = 5; gi.pi[GAS][MASS_HeII] = 6; gi.pi[GAS][MASS_HeIII] = 7; gi.pi[GAS][MASS_H2] = 8; } if (gi.DoGasTemperature) { gi.NProperties[GAS] += 1; gi.pi[GAS][TEMPERATURE] = gi.NSubSpecies[GAS]; } } else if (j == STAR) { if (gi.DoMetalSpecies) { gi.NSubSpecies[STAR] += 2; gi.pi[STAR][MASS_METAL_SNII] = 1; gi.pi[STAR][MASS_METAL_SNIa] = 2; } if (gi.DoStellarAge) { gi.NProperties[STAR] += 1; gi.pi[STAR][AGE] = gi.NSubSpecies[STAR]; } } assert(gi.NSubSpecies[j] > 0); } for (j = 0; j < gi.NSpeciesProfile; j++) gi.SpeciesContained[j] = 0; /* ** Read header files */ if (gi.DataFormat == 0) { /* ** Tipsy */ xdrstdio_create(&xdrs,stdin,XDR_DECODE); read_tipsy_xdr_header(&xdrs,&th); if (gi.ascale == 0) gi.ascale = th.time; if (gi.us.LBox == 0) gi.us.LBox = 1; if (gi.us.Hubble0 == 0) gi.us.Hubble0 = sqrt(8.0*M_PI/3.0); if (gi.us.rhocrit0 == 0) gi.us.rhocrit0 = 1; gi.bc[0] = -0.5*gi.us.LBox; gi.bc[1] = -0.5*gi.us.LBox; gi.bc[2] = -0.5*gi.us.LBox; gi.bc[3] = 0.5*gi.us.LBox; gi.bc[4] = 0.5*gi.us.LBox; gi.bc[5] = 0.5*gi.us.LBox; gi.SpeciesContained[GAS] = (th.ngas > 0)?1:0; gi.SpeciesContained[DARK] = (th.ndark > 0)?1:0; gi.SpeciesContained[STAR] = (th.nstar > 0)?1:0; } else if (gi.DataFormat == 1) { /* ** ART */ prepare_art_data(&ad); if (gi.ascale == 0) gi.ascale = ad.ah.abox; gi.cp.OmegaM0 = ad.ah.OmM0; gi.cp.OmegaB0 = ad.ah.OmB0; gi.cp.OmegaD0 = gi.cp.OmegaM0 - gi.cp.OmegaB0; gi.cp.OmegaL0 = ad.ah.OmL0; gi.cp.OmegaK0 = ad.ah.OmK0; gi.cp.h0_100 = ad.ah.h100; if (gi.us.LBox == 0) gi.us.LBox = ad.ah.Ngrid; if (gi.us.Hubble0 == 0) gi.us.Hubble0 = 2.0/sqrt(gi.cp.OmegaM0); if (gi.us.rhocrit0 == 0) gi.us.rhocrit0 = 1.0/gi.cp.OmegaM0; gi.bc[0] = 0; gi.bc[1] = 0; gi.bc[2] = 0; gi.bc[3] = gi.us.LBox; gi.bc[4] = gi.us.LBox; gi.bc[5] = gi.us.LBox; gi.SpeciesContained[GAS] = ad.gascontained; gi.SpeciesContained[DARK] = ad.darkcontained; gi.SpeciesContained[STAR] = ad.starcontained; for (i = ad.Lmindark; i <= ad.Lmaxdark; i++) ad.massdark[i] = ad.ah.mass[ad.Lmaxdark-i]; if (LmaxGasAnalysis == -1) LmaxGasAnalysis = ad.Lmaxgas; assert(LmaxGasAnalysis >= 0); assert(LmaxGasAnalysis <= ad.Lmaxgas); if (ad.gascontained) { PosGasFile = malloc(2*sizeof(fpos_t)); assert(PosGasFile != NULL); } if (ad.darkcontained || ad.starcontained) { PosCoordinatesDataFile = malloc(1*sizeof(fpos_t)); assert(PosCoordinatesDataFile != NULL); } if (ad.starcontained) { PosStarPropertiesFile = malloc(ad.Nstarproperties*sizeof(fpos_t)); assert(PosStarPropertiesFile != NULL); } } else { fprintf(stderr,"Not supported format!\n"); exit(1); } /* ** Set some parameters */ if (gi.SpeciesContained[GAS] || gi.SpeciesContained[DARK] || gi.SpeciesContained[STAR]) gi.SpeciesContained[TOT] = 1; if (gi.SpeciesContained[GAS] || gi.SpeciesContained[STAR]) gi.SpeciesContained[BARYON] = 1; if (gi.DoMetalSpecies) { if (gi.SpeciesContained[GAS]) { gi.SpeciesContained[GAS_METAL_SNII] = 1; gi.SpeciesContained[GAS_METAL_SNIa] = 1; } if (gi.SpeciesContained[STAR]) { gi.SpeciesContained[STAR_METAL_SNII] = 1; gi.SpeciesContained[STAR_METAL_SNIa] = 1; } if (gi.SpeciesContained[BARYON]) { gi.SpeciesContained[BARYON_METAL_SNII] = 1; gi.SpeciesContained[BARYON_METAL_SNIa] = 1; } } if (gi.DoChemicalSpecies && gi.SpeciesContained[GAS]) { gi.SpeciesContained[GAS_HI] = 1; gi.SpeciesContained[GAS_HII] = 1; gi.SpeciesContained[GAS_HeI] = 1; gi.SpeciesContained[GAS_HeII] = 1; gi.SpeciesContained[GAS_HeIII] = 1; gi.SpeciesContained[GAS_H2] = 1; } for (d = 0; d < 3; d++) { if (LengthType_rmin[d] == 1) gi.rmin[d] /= gi.ascale; if (LengthType_rmax[d] == 1) gi.rmax[d] /= gi.ascale; } if (LengthType_zHeight == 1) gi.zHeight /= gi.ascale; if (LengthType_rExclude == 1) gi.rExclude /= gi.ascale; if (LengthType_rRecentre == 1) gi.rRecentre /= gi.ascale; if (gi.cosmous.LBox == 0) gi.cosmous.LBox = LBox; if (gi.cosmous.Hubble0 == 0) gi.cosmous.Hubble0 = 100*gi.cp.h0_100*ConversionFactors.km_per_s_2_kpc_per_Gyr/1e3; if (gi.cosmous.rhocrit0 == 0) gi.cosmous.rhocrit0 = PhysicalConstants.rho_crit_cosmology*pow(gi.cp.h0_100,2); calculate_units_transformation(gi.cosmous,gi.us,&cosmo2internal_ct); /* ** Calculate densities in comoving coordinates */ calculate_densities(&gi); /* ** Read halo catalogue */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Reading halo catalogues ... "); if (gi.ProfilingMode == 0) { read_halocatalogue_ascii(&gi,&hd); } else if (gi.ProfilingMode == 1) { assert(gi.HaloCatalogueFormat == 2); read_halocatalogue_ascii(&gi,&hd); } else if (gi.ProfilingMode == 3) { /* if (gi.ProfilingMode == 3) read_spherical_profiles(gi,hd); */ /* for (i = 0; i < gi.NHalo; i++) { */ /* fprintf(stderr,"i %ld ID %d rmin %.6e rmax %.6e NBin %d\n",i,hd[i].ID,hd[i].rmin,hd[i].rmax,hd[i].NBin); */ /* for (j = 0; j <= hd[i].NBin; j++) { */ /* fprintf(stderr,"i %ld j %ld ri %.6e ro %.6e totpropertymin %.6e totpropertymax %.6e gaspropertymin %.6e gaspropertymax %.6e darkpropertymin %.6e darkpropertymax %.6e\n",i,j,hd[i].ps[j].ri,hd[i].ps[j].ro,hd[i].ps[j].totshape->propertymin,hd[i].ps[j].totshape->propertymax,hd[i].ps[j].gasshape->propertymin,hd[i].ps[j].gasshape->propertymax,hd[i].ps[j].darkshape->propertymin,hd[i].ps[j].darkshape->propertymax); */ /* } */ /* } */ } else { fprintf(stderr,"Not supported profiling mode!\n"); exit(1); } gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. Read in %d haloes. It took %d s = %d h %d m %d s.\n\n",gi.NHalo,timediff,timediff/3600,(timediff/60)%60,timediff%60); /* ** Read halo catalogue where particles are excluded */ if (gi.ExcludeParticles == 1) { gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Reading halo catalogues for particle exclusion ... "); i = read_halocatalogue_ascii_excludehalo(&gi,hd,&hdeg); j = 0; for (k = 0; k < gi.NHalo; k++) j += hd[k].NHaloExclude; gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. Read in %ld haloes in total leading to %d global and %ld local haloes for exclusion. It took %d s = %d h %d m %d s.\n\n",i,gi.NHaloExcludeGlobal,j,timediff,timediff/3600,(timediff/60)%60,timediff%60); } /* ** Get density files ready */ /* if (gi.ProfilingMode == 3) { */ /* TotDensityFile = fopen(TotDensityFileName,"r"); */ /* assert(TotDensityFile != NULL); */ /* xdrstdio_create(&TotDensityXDR,TotDensityFile,XDR_DECODE); */ /* read_array_xdr_header(&TotDensityXDR,&ahtot); */ /* allocate_array_particle(&ahtot,&aptot); */ /* if (gi.DataFormat == 0) assert(ahtot.N[0] == th.ntotal); */ /* PosTotDensityXDR = xdr_getpos(&TotDensityXDR); */ /* if (gi.SpeciesContained[GAS]) { */ /* GasDensityFile = fopen(GasDensityFileName,"r"); */ /* assert(GasDensityFile != NULL); */ /* xdrstdio_create(&GasDensityXDR,GasDensityFile,XDR_DECODE); */ /* read_array_xdr_header(&GasDensityXDR,&ahgas); */ /* allocate_array_particle(&ahgas,&apgas); */ /* if (gi.DataFormat == 0) assert(ahgas.N[0] == th.ngas); */ /* PosGasDensityXDR = xdr_getpos(&GasDensityXDR); */ /* } */ /* if (gi.SpeciesContained[DARK]) { */ /* DarkDensityFile = fopen(DarkDensityFileName,"r"); */ /* assert(DarkDensityFile != NULL); */ /* xdrstdio_create(&DarkDensityXDR,DarkDensityFile,XDR_DECODE); */ /* read_array_xdr_header(&DarkDensityXDR,&ahdark); */ /* allocate_array_particle(&ahdark,&apdark); */ /* if (gi.DataFormat == 0) assert(ahdark.N[0] == th.ndark); */ /* if (gi.DataFormat == 1) assert(ahdark.N[0] == ad.Ndark); */ /* PosDarkDensityXDR = xdr_getpos(&DarkDensityXDR); */ /* } */ /* if (gi.SpeciesContained[STAR]) { */ /* StarDensityFile = fopen(StarDensityFileName,"r"); */ /* assert(StarDensityFile != NULL); */ /* xdrstdio_create(&StarDensityXDR,StarDensityFile,XDR_DECODE); */ /* read_array_xdr_header(&StarDensityXDR,&ahstar); */ /* allocate_array_particle(&ahstar,&apstar); */ /* if (gi.DataFormat == 0) assert(ahstar.N[0] == th.nstar); */ /* if (gi.DataFormat == 1) assert(ahstar.N[0] == ad.Nstar); */ /* PosStarDensityXDR = xdr_getpos(&StarDensityXDR); */ /* } */ /* } */ /* ** Harvest data */ assert(gi.NLoopProcessData == 1); gi.NLoopRead = gi.NLoopRecentre + gi.NLoopProcessData; for (gi.ILoopRead = 0; gi.ILoopRead < gi.NLoopRead; gi.ILoopRead++) { gettimeofday(&time,NULL); timestartloop = time.tv_sec; fprintf(stderr,"Doing loop %d ...\n",gi.ILoopRead+1); if (gi.DataFormat == 0 && gi.NHalo > 0) { /* ** Tipsy data ** ** Set file pointers correctly */ if (gi.ILoopRead == 0) PosXDR = xdr_getpos(&xdrs); else xdr_setpos(&xdrs,PosXDR); /* if (gi.ProfilingMode == 3) { */ /* xdr_setpos(&TotDensityXDR,PosTotDensityXDR); */ /* if (gi.SpeciesContained[GAS]) xdr_setpos(&GasDensityXDR,PosGasDensityXDR); */ /* if (gi.SpeciesContained[DARK]) xdr_setpos(&DarkDensityXDR,PosDarkDensityXDR); */ /* if (gi.SpeciesContained[STAR]) xdr_setpos(&StarDensityXDR,PosStarDensityXDR); */ /* } */ /* ** Gas */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Processing gas ... "); pp[GAS] = malloc(gi.NParticlePerBlock[GAS]*sizeof(PROFILE_PARTICLE)); assert(pp[GAS] != NULL); for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) { pp[GAS][i].P = malloc((gi.NSubSpecies[GAS]+gi.NProperties[GAS])*sizeof(double)); assert(pp[GAS][i].P != NULL); } Nparticleread = 0; ICurrentBlockGas = 0; for (i = 0; i < th.ngas; i++) { if (PositionPrecision == 0) { read_tipsy_xdr_gas(&xdrs,&gp); for (k = 0; k < 3; k++) { pp[GAS][ICurrentBlockGas].r[k] = put_in_box(gp.pos[k],gi.bc[k],gi.bc[k+3]); pp[GAS][ICurrentBlockGas].v[k] = gp.vel[k]; } pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = gp.mass; if (gi.DoGasTemperature) { pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = gp.temp; } } else if (PositionPrecision == 1) { read_tipsy_xdr_gas_dpp(&xdrs,&gpdpp); for (k = 0; k < 3; k++) { pp[GAS][ICurrentBlockGas].r[k] = put_in_box(gpdpp.pos[k],gi.bc[k],gi.bc[k+3]); pp[GAS][ICurrentBlockGas].v[k] = gpdpp.vel[k]; } pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = gpdpp.mass; if (gi.DoGasTemperature) { pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = gpdpp.temp; } } /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&GasDensityXDR,&ahgas,&apgas); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pp[GAS][ICurrentBlockGas].property = apgas.fa[0]; */ /* pp[GAS][ICurrentBlockGas].propertytot = aptot.fa[0]; */ /* } */ Nparticleread++; ICurrentBlockGas++; if ((ICurrentBlockGas == gi.NParticlePerBlock[GAS]) || (Nparticleread == th.ngas)) { /* ** Block is full or we reached end of gas particles */ gi.NParticleInBlock[GAS] = ICurrentBlockGas; if (gi.DataProcessingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) put_particles_in_bins(gi,hd,GAS,pp[GAS]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,GAS,pp[GAS],&pp_storage[GAS]); ICurrentBlockGas = 0; } } /* for ngas */ for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) free(pp[GAS][i].P); free(pp[GAS]); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d gas particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.ngas); /* ** Dark Matter */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Processing dark matter ... "); pp[DARK] = malloc(gi.NParticlePerBlock[DARK]*sizeof(PROFILE_PARTICLE)); assert(pp[DARK] != NULL); for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) { pp[DARK][i].P = malloc((gi.NSubSpecies[DARK]+gi.NProperties[DARK])*sizeof(double)); assert(pp[DARK][i].P != NULL); } Nparticleread = 0; ICurrentBlockDark = 0; for (i = 0; i < th.ndark; i++) { if (PositionPrecision == 0) { read_tipsy_xdr_dark(&xdrs,&dp); for (k = 0; k < 3; k++) { pp[DARK][ICurrentBlockDark].r[k] = put_in_box(dp.pos[k],gi.bc[k],gi.bc[k+3]); pp[DARK][ICurrentBlockDark].v[k] = dp.vel[k]; } pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = dp.mass; } else if (PositionPrecision == 1) { read_tipsy_xdr_dark_dpp(&xdrs,&dpdpp); for (k = 0; k < 3; k++) { pp[DARK][ICurrentBlockDark].r[k] = put_in_box(dpdpp.pos[k],gi.bc[k],gi.bc[k+3]); pp[DARK][ICurrentBlockDark].v[k] = dpdpp.vel[k]; } pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = dpdpp.mass; } /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&DarkDensityXDR,&ahdark,&apdark); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pdp[ICurrentBlockDark].property = apdark.fa[0]; */ /* pdp[ICurrentBlockDark].propertytot = aptot.fa[0]; */ /* } */ Nparticleread++; ICurrentBlockDark++; if ((ICurrentBlockDark == gi.NParticlePerBlock[DARK]) || (Nparticleread == th.ndark)) { /* ** Block is full or we reached end of dark matter particles */ gi.NParticleInBlock[DARK] = ICurrentBlockDark; if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,DARK,pp[DARK]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,DARK,pp[DARK],&pp_storage[DARK]); ICurrentBlockDark = 0; } } /* for ndark */ for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) free(pp[DARK][i].P); free(pp[DARK]); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d dark matter particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.ndark); /* ** Stars */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Processing stars ... "); pp[STAR] = malloc(gi.NParticlePerBlock[STAR]*sizeof(PROFILE_PARTICLE)); assert(pp[STAR] != NULL); for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) { pp[STAR][i].P = malloc((gi.NSubSpecies[STAR]+gi.NProperties[STAR])*sizeof(double)); assert(pp[STAR][i].P != NULL); } Nparticleread = 0; ICurrentBlockStar = 0; for (i = 0; i < th.nstar; i++) { if (PositionPrecision == 0) { read_tipsy_xdr_star(&xdrs,&sp); for (k = 0; k < 3; k++) { pp[STAR][ICurrentBlockStar].r[k] = put_in_box(sp.pos[k],gi.bc[k],gi.bc[k+3]); pp[STAR][ICurrentBlockStar].v[k] = sp.vel[k]; } pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = sp.mass; if (gi.DoStellarAge) { pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = sp.tform; } } else if (PositionPrecision == 1) { read_tipsy_xdr_star_dpp(&xdrs,&spdpp); for (k = 0; k < 3; k++) { pp[STAR][ICurrentBlockStar].r[k] = put_in_box(spdpp.pos[k],gi.bc[k],gi.bc[k+3]); pp[STAR][ICurrentBlockStar].v[k] = spdpp.vel[k]; } pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = spdpp.mass; if (gi.DoStellarAge) { pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = spdpp.tform; } } /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&StarDensityXDR,&ahstar,&apstar); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pp[STAR][ICurrentBlockStar].property = apstar.fa[0]; */ /* pp[STAR][ICurrentBlockStar].propertytot = aptot.fa[0]; */ /* } */ Nparticleread++; ICurrentBlockStar++; if ((ICurrentBlockStar == gi.NParticlePerBlock[STAR]) || (Nparticleread == th.nstar)) { /* ** Block is full or we reached end of star matter particles */ gi.NParticleInBlock[STAR] = ICurrentBlockStar; if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,STAR,pp[STAR]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,STAR,pp[STAR],&pp_storage[STAR]); ICurrentBlockStar = 0; } } /* for nstar */ for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) free(pp[STAR][i].P); free(pp[STAR]); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d star particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,th.nstar); } else if (gi.DataFormat == 1 && gi.NHalo > 0) { /* ** ART data */ /* if (gi.ProfilingMode == 3) { */ /* xdr_setpos(&TotDensityXDR,PosTotDensityXDR); */ /* if (gi.SpeciesContained[GAS]) xdr_setpos(&GasDensityXDR,PosGasDensityXDR); */ /* if (gi.SpeciesContained[DARK]) xdr_setpos(&DarkDensityXDR,PosDarkDensityXDR); */ /* if (gi.SpeciesContained[STAR]) xdr_setpos(&StarDensityXDR,PosStarDensityXDR); */ /* } */ if (ad.gascontained && gi.ILoopRead >= gi.NLoopRecentre) { /* ** Gas */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Processing gas ... "); /* ** Set file pointers correctly */ if (gi.ILoopRead == gi.NLoopRecentre) { assert(fgetpos(ad.GasFile[0],&PosGasFile[0]) == 0); if (ad.GRAVITY || ad.RADIATIVE_TRANSFER) assert(fgetpos(ad.GasFile[1],&PosGasFile[1]) == 0); } else { assert(fsetpos(ad.GasFile[0],&PosGasFile[0]) == 0); if (ad.GRAVITY || ad.RADIATIVE_TRANSFER) assert(fsetpos(ad.GasFile[1],&PosGasFile[1]) == 0); } /* ** Get arrays ready */ pp[GAS] = malloc(gi.NParticlePerBlock[GAS]*sizeof(PROFILE_PARTICLE)); assert(pp[GAS] != NULL); for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) { pp[GAS][i].P = malloc((gi.NSubSpecies[GAS]+gi.NProperties[GAS])*sizeof(double)); assert(pp[GAS][i].P != NULL); } coordinates = malloc((ad.Lmaxgas+1)*sizeof(double **)); assert(coordinates != NULL); Icoordinates = malloc((ad.Lmaxgas+1)*sizeof(long int)); assert(Icoordinates != NULL); for (i = 0; i < (ad.Lmaxgas+1); i++) { Icoordinates[i] = 0; ad.Ncellrefined[i] = 0; } cellrefined = NULL; Ngasread = 0; ICurrentBlockGas = 0; Ngasanalysis = 0; init_sfc(&ad.asfci); /* ** Go through all levels */ for (i = ad.Lmingas; i <= LmaxGasAnalysis; i++) { /* ** Calculate level properties and read level header */ celllength = ad.rootcelllength/pow(2,i); cellvolume = celllength*celllength*celllength; read_art_nb_gas_header_level(&ad,i,&cellrefined); /* ** get coordinates array ready */ if (i < LmaxGasAnalysis) { coordinates[i] = malloc(ad.Ncellrefined[i]*sizeof(double *)); assert(coordinates[i] != NULL); for (j = 0; j < ad.Ncellrefined[i]; j++) { coordinates[i][j] = malloc(3*sizeof(double)); assert(coordinates[i][j] != NULL); } } /* ** Move file positions */ move_art_nb_gas_filepositions_level_begin(ad,i); /* ** Go through cells in this level */ for (j = 0; j < ad.Ncell[i]; j++) { read_art_nb_gas_properties(ad,&agp); Ngasread++; /* ** Calculate coordinates */ if (i == ad.Lmingas) { sfc_coords(ad.asfci,j,index); for (k = 0; k < 3; k++) { r[k] = index[k] + 0.5; } } else { for (k = 0; k < 3; k++) { mothercellindex = j/8; childcellindex = j%8; r[k] = coordinates[i-1][mothercellindex][k] + celllength*art_cell_delta[childcellindex][k]; } } /* ** Check if cell is refined */ if ((cellrefined[j] == 0) || (i == LmaxGasAnalysis)) { /* ** not refined or maximum level reached => add it for analysis */ Ngasanalysis++; for (k = 0; k < 3; k++) { v[k] = agp.momentum[k]/agp.gas_density; pp[GAS][ICurrentBlockGas].r[k] = r[k]; pp[GAS][ICurrentBlockGas].v[k] = v[k]; } pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_TOT]] = cellvolume*agp.gas_density; if (gi.DoMetalSpecies) { pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_METAL_SNII]] = cellvolume*agp.metal_density_SNII; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_METAL_SNIa]] = cellvolume*agp.metal_density_SNIa; } if (gi.DoChemicalSpecies) { pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HI]] = cellvolume*agp.HI_density; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HII]] = cellvolume*agp.HII_density; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeI]] = cellvolume*agp.HeI_density; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeII]] = cellvolume*agp.HeII_density; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_HeIII]] = cellvolume*agp.HeIII_density; pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][MASS_H2]] = cellvolume*agp.H2_density; } if (gi.DoGasTemperature) { /* ** Number density 1/LU^3 */ number_density = agp.HI_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/PhysicalConstants.m_proton; number_density += 2*agp.HII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/PhysicalConstants.m_proton; number_density += agp.HeI_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton); number_density += 2*agp.HeII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton); number_density += 3*agp.HeIII_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(4*PhysicalConstants.m_proton); number_density += agp.H2_density*(PhysicalConstants.Mo/cosmo2internal_ct.M_usf)/(2*PhysicalConstants.m_proton); /* ** Internal energy => internal energy per unit volume */ pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] = agp.internal_energy*(agp.gamma-1)/number_density; /* ** Convert to Joules */ pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] /= cosmo2internal_ct.M_usf*pow(cosmo2internal_ct.V_usf,2); pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] *= PhysicalConstants.Mo*pow(ConversionFactors.kpc_per_Gyr_2_km_per_s*1000,2); /* ** Gas temperature in Kelvin */ pp[GAS][ICurrentBlockGas].P[gi.pi[GAS][TEMPERATURE]] /= PhysicalConstants.k_Boltzmann; } /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&GasDensityXDR,&ahgas,&apgas); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pp[GAS][ICurrentBlockGas].property = apgas.fa[0]; */ /* pp[GAS][ICurrentBlockGas].propertytot = aptot.fa[0]; */ /* } */ ICurrentBlockGas++; if ((ICurrentBlockGas == gi.NParticlePerBlock[GAS]) || (Ngasread == ad.Ngas)) { /* ** Block is full or we reached end of gas particles */ gi.NParticleInBlock[GAS] = ICurrentBlockGas; if (gi.DataProcessingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) put_particles_in_bins(gi,hd,GAS,pp[GAS]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,GAS,pp[GAS],&pp_storage[GAS]); ICurrentBlockGas = 0; } } else if (i < LmaxGasAnalysis) { /* ** refined and lower level than LmaxGasAnalysis => add it to corresponding coordinates array */ for (k = 0; k < 3; k++) { coordinates[i][Icoordinates[i]][k] = r[k]; } Icoordinates[i]++; } } /* ** Move file positions */ move_art_nb_gas_filepositions_level_end(ad,i); /* ** Checks and free coordinates of level below */ if (i < LmaxGasAnalysis) assert(Icoordinates[i] == ad.Ncellrefined[i]); if (i > ad.Lmingas) { for (j = 0; j < ad.Ncellrefined[i-1]; j++) { free(coordinates[i-1][j]); } free(coordinates[i-1]); } } /* ** Some checks and free remaining arrays */ if (LmaxGasAnalysis == ad.Lmaxgas) { assert(ad.Ncellrefined[ad.Lmaxgas] == 0); assert(ad.Ngas == Ngasread); j = 0; k = 0; for (i = ad.Lmingas; i <= ad.Lmaxgas; i++) { j += ad.Ncell[i]; k += ad.Ncellrefined[i]; } assert(ad.Ngas == j); assert(ad.Ngas == k + Ngasanalysis); } for (i = 0; i < gi.NParticlePerBlock[GAS]; i++) free(pp[GAS][i].P); free(pp[GAS]); free(Icoordinates); free(cellrefined); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %ld gas particles whereof %ld used for analysis.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,ad.Ngas,Ngasanalysis); } /* if ad.gascontained && gi.ILoopRead >= gi.NLoopRecentre */ if (ad.darkcontained || ad.starcontained) { /* ** Dark Matter and Stars */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Processing dark matter and stars ... "); /* ** Set file pointers correctly */ if (gi.ILoopRead == 0) { assert(fgetpos(ad.CoordinatesDataFile,PosCoordinatesDataFile) == 0); for (i = 0; i < ad.Nstarproperties; i++) { assert(fgetpos(ad.StarPropertiesFile[i],&PosStarPropertiesFile[i]) == 0); } } else { assert(fsetpos(ad.CoordinatesDataFile,PosCoordinatesDataFile) == 0); for (i = 0; i < ad.Nstarproperties; i++) { assert(fsetpos(ad.StarPropertiesFile[i],&PosStarPropertiesFile[i]) == 0); } } /* ** Get arrays ready */ ac = malloc(ad.Nparticleperrecord*sizeof(ART_COORDINATES)); assert(ac != NULL); pp[DARK] = malloc(gi.NParticlePerBlock[DARK]*sizeof(PROFILE_PARTICLE)); assert(pp[DARK] != NULL); for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) { pp[DARK][i].P = malloc((gi.NSubSpecies[DARK]+gi.NProperties[DARK])*sizeof(double)); assert(pp[DARK][i].P != NULL); } if (ad.starcontained) { pp[STAR] = malloc(gi.NParticlePerBlock[STAR]*sizeof(PROFILE_PARTICLE)); assert(pp[STAR] != NULL); for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) { pp[STAR][i].P = malloc((gi.NSubSpecies[STAR]+gi.NProperties[STAR])*sizeof(double)); assert(pp[STAR][i].P != NULL); } move_art_nb_star_filepositions_begin(ad); } Nparticleread = 0; ICurrentBlockDark = 0; ICurrentBlockStar = 0; for (i = 0; i < ad.Nrecord; i++) { read_art_nb_coordinates_record(ad,ac); for (j = 0; j < ad.Nparticleperrecord; j++) { if (Nparticleread < ad.Ndark) { /* ** Dark Matter */ for (k = 0; k < 3; k++) { r[k] = put_in_box(ac[j].r[k]-ad.shift,gi.bc[k],gi.bc[k+3]); v[k] = ac[j].v[k]; pp[DARK][ICurrentBlockDark].r[k] = r[k]; pp[DARK][ICurrentBlockDark].v[k] = v[k]; } for (k = ad.Lmaxdark; k >=0; k--) { if (ad.ah.num[k] >= Nparticleread) L = ad.Lmaxdark-k; } pp[DARK][ICurrentBlockDark].P[gi.pi[DARK][MASS_TOT]] = ad.massdark[L]; /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&DarkDensityXDR,&ahdark,&apdark); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pp[DARK][ICurrentBlockDark].property = apdark.fa[0]; */ /* pp[DARK][ICurrentBlockDark].propertytot = aptot.fa[0]; */ /* } */ Nparticleread++; ICurrentBlockDark++; if ((ICurrentBlockDark == gi.NParticlePerBlock[DARK]) || (Nparticleread == ad.Ndark)) { /* ** Block is full or we reached end of dark matter particles */ gi.NParticleInBlock[DARK] = ICurrentBlockDark; if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,DARK,pp[DARK]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,DARK,pp[DARK],&pp_storage[DARK]); ICurrentBlockDark = 0; } } else if (Nparticleread < ad.Ndark+ad.Nstar) { /* ** Star */ for (k = 0; k < 3; k++) { r[k] = put_in_box(ac[j].r[k]-ad.shift,gi.bc[k],gi.bc[k+3]); v[k] = ac[j].v[k]; pp[STAR][ICurrentBlockStar].r[k] = r[k]; pp[STAR][ICurrentBlockStar].v[k] = v[k]; } /* ** Get other star properties */ read_art_nb_star_properties(ad,&asp); pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_TOT]] = asp.mass; if (gi.DoMetalSpecies && gi.ILoopRead >= gi.NLoopRecentre) { pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_METAL_SNII]] = asp.mass*asp.metallicity_SNII; pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][MASS_METAL_SNIa]] = asp.mass*asp.metallicity_SNIa; } if (gi.DoStellarAge) { pp[STAR][ICurrentBlockStar].P[gi.pi[STAR][AGE]] = asp.t_form; } /* if (gi.ProfilingMode == 3) { */ /* read_array_xdr_particle(&StarDensityXDR,&ahstar,&apstar); */ /* read_array_xdr_particle(&TotDensityXDR,&ahtot,&aptot); */ /* pp[STAR][ICurrentBlockStar].property = apstar.fa[0]; */ /* pp[STAR][ICurrentBlockStar].propertytot = aptot.fa[0]; */ /* } */ Nparticleread++; ICurrentBlockStar++; if ((ICurrentBlockStar == gi.NParticlePerBlock[STAR]) || (Nparticleread == ad.Ndark+ad.Nstar)) { /* ** Block is full or we reached end of star particles */ gi.NParticleInBlock[STAR] = ICurrentBlockStar; if (gi.DataProcessingMode == 0) put_particles_in_bins(gi,hd,STAR,pp[STAR]); else if (gi.DataProcessingMode == 1) put_particles_in_storage(&gi,hd,hdeg,STAR,pp[STAR],&pp_storage[STAR]); ICurrentBlockStar = 0; } } } } if (ad.starcontained) move_art_nb_star_filepositions_end(ad); free(ac); for (i = 0; i < gi.NParticlePerBlock[DARK]; i++) free(pp[DARK][i].P); free(pp[DARK]); if (ad.starcontained) { for (i = 0; i < gi.NParticlePerBlock[STAR]; i++) free(pp[STAR][i].P); free(pp[STAR]); } gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %ld dark matter and %ld star particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,ad.Ndark,ad.Nstar); } /* if ad.darkcontained || ad.starcontained */ } /* if DataFormat */ /* ** Do loop specific stuff */ if (gi.DataProcessingMode == 0) { if (gi.ProfilingMode == 0 && gi.ILoopRead < gi.NLoopRecentre) { /* ** Calculate recentred halo coordinates */ calculate_recentred_halo_coordinates(gi,hd); } else if (gi.ProfilingMode == 0 && gi.ILoopRead >= gi.NLoopRecentre) { /* ** Calculate total and baryonic matter distribution */ calculate_total_matter_distribution(gi,hd); calculate_baryonic_matter_distribution(gi,hd); } else if (gi.ProfilingMode == 1) { /* ** Diagonalise enclosed shape tensor */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Diagonalising shape tensors ... "); convergencefraction = diagonalise_shape_tensors(gi,hd,gi.ILoopRead+1); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. The fraction of converged bins so far is %g.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,convergencefraction); if (convergencefraction == 1 || (gi.ILoopRead+1)%gi.OutputFrequencyShapeIteration == 0 || gi.ILoopRead+1 == gi.NLoopShapeIterationMax) { gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Writing output ... "); write_output_shape_profile(gi,hd,gi.ILoopRead+1); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); } if (convergencefraction < 1 && gi.ILoopRead < gi.NLoopShapeIterationMax-1) { reset_halo_profile_shape(gi,hd); gi.NLoopRead++; gi.NLoopProcessData++; } } /* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 0) { */ /* double fproperty = gi.fincludeshapeproperty; */ /* /\* */ /* ** This is still under construction: the shape values are pretty sensitive to the selected set. */ /* ** Probably worth trying median in stead of mean => how to calculate median efficiently on the fly */ /* ** without storing data & sorting? */ /* ** Maybe try to loop over density iteration as well */ /* *\/ */ /* for (i = 0; i < gi.NHalo; i++) { */ /* for (j = 0; j < hd[i].NBin[0]+1; j++) { */ /* /\* */ /* ** Total matter */ /* *\/ */ /* if (hd[i].pbs[j].totshape->N > 0) hd[i].pbs[j].totshape->propertymean /= hd[i].pbs[j].totshape->N; */ /* hd[i].pbs[j].totshape->propertymin = hd[i].pbs[j].totshape->propertymean/fproperty; */ /* hd[i].pbs[j].totshape->propertymax = hd[i].pbs[j].totshape->propertymean*fproperty; */ /* /\* */ /* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].totshape->N, */ /* hd[i].pbs[j].totshape->propertymin,hd[i].pbs[j].totshape->propertymax,hd[i].pbs[j].totshape->propertymean); */ /* *\/ */ /* hd[i].pbs[j].totshape->N = 0; */ /* /\* */ /* ** Gas */ /* *\/ */ /* if (gi.SpeciesContained[GAS]) { */ /* if (hd[i].pbs[j].gasshape->N > 0) hd[i].pbs[j].gasshape->propertymean /= hd[i].pbs[j].gasshape->N; */ /* hd[i].pbs[j].gasshape->propertymin = hd[i].pbs[j].gasshape->propertymean/fproperty; */ /* hd[i].pbs[j].gasshape->propertymax = hd[i].pbs[j].gasshape->propertymean*fproperty; */ /* /\* */ /* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].gasshape->N, */ /* hd[i].pbs[j].gasshape->propertymin,hd[i].pbs[j].gasshape->propertymax,hd[i].pbs[j].gasshape->propertymean); */ /* *\/ */ /* hd[i].pbs[j].gasshape->N = 0; */ /* } */ /* /\* */ /* ** Dark matter */ /* *\/ */ /* if (gi.SpeciesContained[DARK]) { */ /* if (hd[i].pbs[j].darkshape->N > 0) hd[i].pbs[j].darkshape->propertymean /= hd[i].pbs[j].darkshape->N; */ /* hd[i].pbs[j].darkshape->propertymin = hd[i].pbs[j].darkshape->propertymean/fproperty; */ /* hd[i].pbs[j].darkshape->propertymax = hd[i].pbs[j].darkshape->propertymean*fproperty; */ /* /\* */ /* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].darkshape->N, */ /* hd[i].pbs[j].darkshape->propertymin,hd[i].pbs[j].darkshape->propertymax,hd[i].pbs[j].darkshape->propertymean); */ /* *\/ */ /* hd[i].pbs[j].darkshape->N = 0; */ /* } */ /* /\* */ /* ** Stars */ /* *\/ */ /* if (gi.SpeciesContained[STAR]) { */ /* if (hd[i].pbs[j].starshape->N > 0) hd[i].pbs[j].starshape->propertymean /= hd[i].pbs[j].starshape->N; */ /* hd[i].pbs[j].starshape->propertymin = hd[i].pbs[j].starshape->propertymean/fproperty; */ /* hd[i].pbs[j].starshape->propertymax = hd[i].pbs[j].starshape->propertymean*fproperty; */ /* /\* */ /* fprintf(stderr,"i %ld j %ld N %ld propertymin %.6e propertymean %.6e propertymax %.6e\n",i,j,hd[i].pbs[j].starshape->N, */ /* hd[i].pbs[j].starshape->propertymin,hd[i].pbs[j].starshape->propertymean,hd[i].pbs[j].starshape->propertymax); */ /* *\/ */ /* hd[i].pbs[j].starshape->N = 0; */ /* } */ /* } */ /* } */ /* gi.NLoopRead++; */ /* gi.NLoopProcessData++; */ /* } */ /* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 1) { */ /* /\* */ /* ** Close density files */ /* *\/ */ /* if (0) { */ /* xdr_destroy(&TotDensityXDR); */ /* fclose(TotDensityFile); */ /* if (gi.SpeciesContained[GAS]) { */ /* xdr_destroy(&GasDensityXDR); */ /* fclose(GasDensityFile); */ /* } */ /* if (gi.SpeciesContained[DARK]) { */ /* xdr_destroy(&DarkDensityXDR); */ /* fclose(DarkDensityFile); */ /* } */ /* if (gi.SpeciesContained[STAR]) { */ /* xdr_destroy(&StarDensityXDR); */ /* fclose(StarDensityFile); */ /* } */ /* } */ /* /\* */ /* ** Diagonalise local shape tensor */ /* *\/ */ /* diagonalise_shape_tensors(gi,hd,gi.ILoopRead+1); */ /* gi.NLoopRead++; */ /* gi.NLoopProcessData++; */ /* } */ /* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 2) { */ /* diagonalise_shape_tensors(gi,hd); */ /* } */ } else if (gi.DataProcessingMode == 1) { fprintf(stderr,"Put %d gas, %d dark matter and %d star particles into storage.\n",gi.NParticleInStorage[GAS],gi.NParticleInStorage[DARK],gi.NParticleInStorage[STAR]); } gettimeofday(&time,NULL); timeendloop = time.tv_sec; timediff = timeendloop-timestartloop; fprintf(stderr,"Done with loop %d. It took %d s = %d h %d m %d s.\n\n",gi.ILoopRead+1,timediff,timediff/3600,(timediff/60)%60,timediff%60); } /* for ILoopRead */ /* ** After-harvest tasks */ if (gi.ProfilingMode == 0) { /* ** Calculate halo properties */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Calculating halo properties ... "); calculate_halo_properties(gi,hd); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); /* ** Determine hierarchy of haloes */ if (gi.BinningCoordinateType == 0) { gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Determining hierarchy of haloes ... "); determine_halo_hierarchy(gi,hd); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); } /* ** Write output */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Writing output ... "); write_output_matter_profile(gi,hd); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); } if (gi.ProfilingMode == 1 && gi.DataProcessingMode == 1) { /* ** Diagonalise enclosed shape tensor */ for (i = 0; i < gi.NLoopShapeIterationMax; i++) { /* ** Put particles in bins */ gettimeofday(&time,NULL); timestartloop = time.tv_sec; fprintf(stderr,"Doing iteration %ld ...\n",i+1); for (j = 0; j < gi.NSpeciesRead; j++) { if (gi.SpeciesContained[j]) { gettimeofday(&time,NULL); timestartsub = time.tv_sec; if (j == GAS) strcpy(cdummy,"gas"); else if (j == DARK) strcpy(cdummy,"dark matter"); else if (j == STAR) strcpy(cdummy,"stars"); else strcpy(cdummy,"a matter type that should not be here"); fprintf(stderr,"Processing %s ... ",cdummy); put_particles_in_bins(gi,hd,j,pp_storage[j]); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; if (j == STAR) strcpy(cdummy,"star"); fprintf(stderr,"Done. It took %d s = %d h %d m %d s. Processed in total %d %s particles.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,gi.NParticleInStorage[j],cdummy); } } /* ** Diagonalise enclosed shape tensor */ gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Diagonalising shape tensors ... "); convergencefraction = diagonalise_shape_tensors(gi,hd,i+1); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s. The fraction of converged bins so far is %g.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60,convergencefraction); if (convergencefraction == 1 || (i+1)%gi.OutputFrequencyShapeIteration == 0 || i+1 == gi.NLoopShapeIterationMax) { gettimeofday(&time,NULL); timestartsub = time.tv_sec; fprintf(stderr,"Writing output ... "); write_output_shape_profile(gi,hd,i+1); gettimeofday(&time,NULL); timeendsub = time.tv_sec; timediff = timeendsub-timestartsub; fprintf(stderr,"Done. It took %d s = %d h %d m %d s.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); } if (convergencefraction < 1 && i < gi.NLoopShapeIterationMax-1) reset_halo_profile_shape(gi,hd); gettimeofday(&time,NULL); timeendloop = time.tv_sec; timediff = timeendloop-timestartloop; fprintf(stderr,"Done with iteration %ld. It took %d s = %d h %d m %d s.\n\n",i+1,timediff,timediff/3600,(timediff/60)%60,timediff%60); if (convergencefraction == 1) break; } } /* ** Some more output if desired */ if (VerboseLevel > 0) { /* ** 6DFOF */ if (gi.HaloCatalogueFormat == 1) { fprintf(stderr,"6DFOF specific parameters:\n\n"); fprintf(stderr,"BinFactor : %.6e\n",gi.BinFactor); if (gi.CentreType == 0) fprintf(stderr,"CentreType : centre-of-mass\n"); else if (gi.CentreType == 1) fprintf(stderr,"CentreType : potmin or denmax\n"); fprintf(stderr,"rmaxFromHaloCatalogue : %s\n",(gi.rmaxFromHaloCatalogue == 0)?"no":"yes"); fprintf(stderr,"\n"); } /* ** ART */ if (gi.DataFormat == 1) { fprintf(stderr,"ART general header:\n\n"); fprintf(stderr,"aunin : %.6e\n",ad.ah.aunin); fprintf(stderr,"auni0 : %.6e\n",ad.ah.auni0); fprintf(stderr,"amplt : %.6e\n",ad.ah.amplt); fprintf(stderr,"astep : %.6e\n",ad.ah.astep); fprintf(stderr,"istep : %d\n",ad.ah.istep); fprintf(stderr,"partw : %.6e\n",ad.ah.partw); fprintf(stderr,"tintg : %.6e\n",ad.ah.tintg); fprintf(stderr,"ekin : %.6e\n",ad.ah.ekin); fprintf(stderr,"ekin1 : %.6e\n",ad.ah.ekin1); fprintf(stderr,"ekin2 : %.6e\n",ad.ah.ekin2); fprintf(stderr,"au0 : %.6e\n",ad.ah.au0); fprintf(stderr,"aeu0 : %.6e\n",ad.ah.aeu0); fprintf(stderr,"Nrow : %d\n",ad.ah.Nrow); fprintf(stderr,"Ngrid : %d\n",ad.ah.Ngrid); fprintf(stderr,"Nspecies : %d\n",ad.ah.Nspecies); fprintf(stderr,"Nseed : %d\n",ad.ah.Nseed); fprintf(stderr,"OmM0 : %.6e\n",ad.ah.OmM0); fprintf(stderr,"OmL0 : %.6e\n",ad.ah.OmL0); fprintf(stderr,"h100 : %.6e\n",ad.ah.h100); fprintf(stderr,"Wp5 : %.6e\n",ad.ah.Wp5); fprintf(stderr,"OmK0 : %.6e\n",ad.ah.OmK0); fprintf(stderr,"OmB0 : %.6e\n",ad.ah.OmB0); fprintf(stderr,"magic1 : %.6e\n",ad.ah.magic1); fprintf(stderr,"DelDC : %.6e\n",ad.ah.DelDC); fprintf(stderr,"abox : %.6e\n",ad.ah.abox); fprintf(stderr,"Hbox : %.6e\n",ad.ah.Hbox); fprintf(stderr,"magic2 : %.6e\n",ad.ah.magic2); fprintf(stderr,"Banner : %s\n",ad.Banner); fprintf(stderr,"\n"); for (i = 0; i < 10; i++) { fprintf(stderr,"mass[%ld] : %.6e num[%ld] : %d\n",i,ad.ah.mass[i],i,ad.ah.num[i]); } fprintf(stderr,"\n"); fprintf(stderr,"ART data properties:\n\n"); fprintf(stderr,"Particle file mode : %d\n",ad.particle_file_mode); fprintf(stderr,"Nparticleperrecord : %d\n",ad.Nparticleperrecord); fprintf(stderr,"Nrecord : %d\n",ad.Nrecord); fprintf(stderr,"Nhydroproperties : %d\n",ad.Nhydroproperties); fprintf(stderr,"Notherproperties : %d\n",ad.Notherproperties); fprintf(stderr,"Nrtchemspecies : %d\n",ad.Nrtchemspecies); fprintf(stderr,"Nchemspecies : %d\n",ad.Nchemspecies); fprintf(stderr,"Nstarproperties : %d\n",ad.Nstarproperties); fprintf(stderr,"Lmingas : %d\n",ad.Lmingas); fprintf(stderr,"Lmaxgas : %d\n",ad.Lmaxgas); fprintf(stderr,"Lmindark : %d\n",ad.Lmindark); fprintf(stderr,"Lmaxdark : %d\n",ad.Lmaxdark); fprintf(stderr,"\n"); fprintf(stderr,"ART preprocessor flags:\n\n"); fprintf(stderr,"-GRAVITY : %s\n",(ad.GRAVITY == 0)?"not set":"set"); fprintf(stderr,"-HYDRO : %s\n",(ad.HYDRO == 0)?"not set":"set"); fprintf(stderr,"-ADVECT_SPECIES : %s\n",(ad.ADVECT_SPECIES == 0)?"not set":"set"); fprintf(stderr,"-STARFORM : %s\n",(ad.STARFORM == 0)?"not set":"set"); fprintf(stderr,"-ENRICH : %s\n",(ad.ENRICH == 0)?"not set":"set"); fprintf(stderr,"-ENRICH_SNIa : %s\n",(ad.ENRICH_SNIa == 0)?"not set":"set"); fprintf(stderr,"-RADIATIVE_TRANSFER : %s\n",(ad.RADIATIVE_TRANSFER == 0)?"not set":"set"); fprintf(stderr,"-ELECTRON_ION_NONEQUILIBRIUM : %s\n",(ad.ELECTRON_ION_NONEQUILIBRIUM == 0)?"not set":"set"); fprintf(stderr,"\n"); fprintf(stderr,"ART specific parameters:\n\n"); fprintf(stderr,"LmaxGasAnalysis : %d\n",LmaxGasAnalysis); fprintf(stderr,"\n"); } /* ** Cosmology */ fprintf(stderr,"Cosmology:\n\n"); fprintf(stderr,"OmegaM0 : %.6e\n",gi.cp.OmegaM0); fprintf(stderr,"OmegaL0 : %.6e\n",gi.cp.OmegaL0); fprintf(stderr,"OmegaK0 : %.6e\n",gi.cp.OmegaK0); fprintf(stderr,"OmegaR0 : %.6e\n",gi.cp.OmegaR0); fprintf(stderr,"h0_100 : %.6e\n",gi.cp.h0_100); fprintf(stderr,"\n"); /* ** Unit system */ fprintf(stderr,"Unit System:\n\n"); fprintf(stderr,"LBox : %.6e LU\n",gi.us.LBox); fprintf(stderr,"Hubble0 : %.6e TU^{-1}\n",gi.us.Hubble0); fprintf(stderr,"rhocrit0 : %.6e MU LU^{-3}\n",gi.us.rhocrit0); fprintf(stderr,"\n"); /* ** Internal units */ fprintf(stderr,"Internal units:\n\n"); fprintf(stderr,"LU : %.6e kpc\n",1.0/cosmo2internal_ct.L_usf); fprintf(stderr,"TU : %.6e Gyr\n",1.0/cosmo2internal_ct.T_usf); fprintf(stderr,"VU : %.6e kpc Gyr^{-1} = %.6e km s^{-1}\n",1.0/cosmo2internal_ct.V_usf,1.0/cosmo2internal_ct.V_usf*ConversionFactors.kpc_per_Gyr_2_km_per_s); fprintf(stderr,"MU : %.6e Mo\n",1.0/cosmo2internal_ct.M_usf); fprintf(stderr,"\n"); /* ** Data properties */ fprintf(stderr,"Data properties:\n\n"); switch(gi.DataFormat) { case 0: strcpy(cdummy,"Tipsy"); break; case 1: strcpy(cdummy,"ART"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Data format : %s\n",cdummy); fprintf(stderr,"Contains anything : %s\n",(gi.SpeciesContained[TOT])?"yes":"no"); fprintf(stderr,"Contains gas : %s\n",(gi.SpeciesContained[GAS])?"yes":"no"); fprintf(stderr,"Contains dark matter : %s\n",(gi.SpeciesContained[DARK])?"yes":"no"); fprintf(stderr,"Contains stars : %s\n",(gi.SpeciesContained[STAR])?"yes":"no"); fprintf(stderr,"Contains baryons : %s\n",(gi.SpeciesContained[BARYON])?"yes":"no"); fprintf(stderr,"a : %.6e\n",gi.ascale); fprintf(stderr,"LBox : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", cosmo2internal_ct.L_usf*LBox,LBox,gi.ascale*LBox); fprintf(stderr,"Box : [%.6e ... %.6e] x [%.6e ... %.6e] x [%.6e ... %.6e] LU (comoving)\n",gi.bc[0],gi.bc[3],gi.bc[1],gi.bc[4],gi.bc[2],gi.bc[5]); fprintf(stderr,"\n"); /* ** Profiling parameters */ fprintf(stderr,"Profiling parameters:\n\n"); switch(gi.ProfilingMode) { case 0: strcpy(cdummy,"profiles"); break; case 1: strcpy(cdummy,"shape determination"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Profiling mode : %s\n",cdummy); switch(gi.DataProcessingMode) { case 0: strcpy(cdummy,"read data again in every loop"); break; case 1: strcpy(cdummy,"store data in memory"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Data processing mode : %s\n",cdummy); fprintf(stderr,"Do metal species : %s\n",(gi.DoMetalSpecies)?"yes":"no"); fprintf(stderr,"Do chemical species : %s\n",(gi.DoChemicalSpecies)?"yes":"no"); fprintf(stderr,"Do gas temperature : %s\n",(gi.DoGasTemperature)?"yes":"no"); fprintf(stderr,"Do stellar age : %s\n",(gi.DoStellarAge)?"yes":"no"); fprintf(stderr,"More characteristics output : %s\n",(gi.MoreCharacteristicsOutput)?"yes":"no"); fprintf(stderr,"Exclude particles : %s\n",(gi.ExcludeParticles)?"yes":"no"); fprintf(stderr,"Number of profile dimensions : %d\n",gi.NDimProfile); fprintf(stderr,"Number of read species : %d\n",gi.NSpeciesRead); fprintf(stderr,"Number of profiled species : %d\n",gi.NSpeciesProfile); for (i = 0; i < gi.NSpeciesRead; i++) { switch(i) { case GAS: strcpy(cdummy,"gas"); break; case DARK: strcpy(cdummy,"dark matter"); break; case STAR: strcpy(cdummy,"stars"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Number of subspecies / properties : %d / %d (%s)\n",gi.NSubSpecies[i],gi.NProperties[i],cdummy); } fprintf(stderr,"NParticlePerBlockGas : %d\n",gi.NParticlePerBlock[GAS]); fprintf(stderr,"NParticlePerBlockDark : %d\n",gi.NParticlePerBlock[DARK]); fprintf(stderr,"NParticlePerBlockStar : %d\n",gi.NParticlePerBlock[STAR]); fprintf(stderr,"NCellData : %d\n",gi.NCellData); fprintf(stderr,"NCellHalo : %d\n",gi.NCellHalo); fprintf(stderr,"NLoopProcessData : %d\n",gi.NLoopProcessData); fprintf(stderr,"NLoopRead : %d\n",gi.NLoopRead); fprintf(stderr,"\n"); /* ** Halo catalogue */ fprintf(stderr,"Halo catalogue properties:\n\n"); switch(gi.HaloCatalogueFormat) { case 0: strcpy(cdummy,"generic"); break; case 1: strcpy(cdummy,"6DFOF"); break; case 2: strcpy(cdummy,"characteristics"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Halocatalogue format : %s\n",cdummy); switch(gi.HaloCatalogueBinningCoordinateType) { case 0: strcpy(cdummy,"spherical"); break; case 1: strcpy(cdummy,"cylindrical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Halocatalogue binning type : %s\n",cdummy); fprintf(stderr,"Halocatalogue dimension : %d\n",gi.HaloCatalogueNDim); fprintf(stderr,"NHalo : %d\n",gi.NHalo); fprintf(stderr,"\n"); /* ** Exclude halo catalogue */ fprintf(stderr,"Exclude halo catalogue properties:\n\n"); if (gi.ExcludeParticles) { switch(gi.ExcludeHaloCatalogueFormat) { case 0: strcpy(cdummy,"generic"); break; case 1: strcpy(cdummy,"6DFOF"); break; case 2: strcpy(cdummy,"characteristics"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"ExcludeHalocatalogue format : %s\n",cdummy); fprintf(stderr,"ExcludeHalocatalogue binning type : spherical\n"); fprintf(stderr,"ExcludeHalocatalogue dimension : %d\n",gi.ExcludeHaloCatalogueNDim); fprintf(stderr,"NHaloExcludeGlobal : %d\n",gi.NHaloExcludeGlobal); } else { fprintf(stderr,"No particles were excluded.\n"); } fprintf(stderr,"\n"); /* ** Recentring */ fprintf(stderr,"Recentring:\n\n"); if (gi.NLoopRecentre > 0) { switch(LengthType_rRecentre) { case 0: strcpy(cdummy,"comoving"); break; case 1: strcpy(cdummy,"physical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Length type rRecentre : %s\n",cdummy); fprintf(stderr,"rRecentre : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", gi.rRecentre,gi.rRecentre/cosmo2internal_ct.L_usf,gi.ascale*gi.rRecentre/cosmo2internal_ct.L_usf); fprintf(stderr,"fRecentreDist : %.6e\n",gi.fRecentreDist); fprintf(stderr,"NLoopRecentre : %d\n",gi.NLoopRecentre); for (i = 0; i < gi.NSpeciesRead; i++) { switch(i) { case GAS: strcpy(cdummy,"gas"); break; case DARK: strcpy(cdummy,"dark matter"); break; case STAR: strcpy(cdummy,"stars"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Recentre use %s : %s\n",cdummy,gi.RecentreUse[i]?"yes":"no"); } } else { fprintf(stderr,"No recentring was done.\n"); } fprintf(stderr,"\n"); /* ** Profiles */ if (gi.ProfilingMode == 0) { fprintf(stderr,"General profiling properties:\n\n"); switch(gi.BinningCoordinateType) { case 0: strcpy(cdummy,"spherical"); break; case 1: strcpy(cdummy,"cylindrical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Binning : %s\n",cdummy); switch(gi.VelocityProjectionType) { case 0: strcpy(cdummy,"coordinate axes"); break; case 1: strcpy(cdummy,"spherical"); break; case 2: strcpy(cdummy,"cylindrical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Velocity projection : %s\n",cdummy); fprintf(stderr,"\n"); /* ** Spherical profiles */ if (gi.BinningCoordinateType == 0) { fprintf(stderr,"Spherical profiles:\n\n"); switch(gi.HaloSize) { case 0: strcpy(cdummy,"rmean"); break; case 1: strcpy(cdummy,"rcrit"); break; case 2: strcpy(cdummy,"rfix"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Halo size : %s\n",cdummy); fprintf(stderr,"rho_mean : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n", gi.rhomean,gi.rhomean*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf, gi.rhomean*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf)); fprintf(stderr,"rho_crit : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n", gi.rhocrit,gi.rhocrit*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf, gi.rhocrit*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf)); fprintf(stderr,"Delta_mean : %.6e\n",gi.Deltamean); fprintf(stderr,"Delta_crit : %.6e\n",gi.Deltacrit); fprintf(stderr,"Delta_fix : %.6e\n",gi.Deltafix); fprintf(stderr,"afix : %.6e\n",gi.afix); fprintf(stderr,"rhoenc_mean : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n", gi.rhoencmean,gi.rhoencmean*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf, gi.rhoencmean*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf)); fprintf(stderr,"rhoenc_crit : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n", gi.rhoenccrit,gi.rhoenccrit*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf, gi.rhoenccrit*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf)); fprintf(stderr,"rhoenc_fix : %.6e MU LU^{-3} (comoving) = %.6e Mo kpc^{-3} (comoving) = %.6e Mo kpc^{-3} (physical)\n", gi.rhoencfix,gi.rhoencfix*pow(cosmo2internal_ct.L_usf,3)/cosmo2internal_ct.M_usf, gi.rhoencfix*pow(cosmo2internal_ct.L_usf,3)/(pow(gi.ascale,3)*cosmo2internal_ct.M_usf)); switch(LengthType_rExclude) { case 0: strcpy(cdummy,"comoving"); break; case 1: strcpy(cdummy,"physical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Length type rExclude : %s\n",cdummy); fprintf(stderr,"rExclude : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", gi.rExclude,gi.rExclude/cosmo2internal_ct.L_usf,gi.ascale*gi.rExclude/cosmo2internal_ct.L_usf); fprintf(stderr,"fcheckrvcmax : %.6e\n",gi.fcheckrvcmax); fprintf(stderr,"slopertruncindicator : %.6e\n",gi.slopertruncindicator); fprintf(stderr,"frhobg : %.6e\n",gi.frhobg); fprintf(stderr,"fhaloduplicate : %.6e\n",gi.fhaloduplicate); fprintf(stderr,"fhaloexcludesize : %.6e\n",gi.fhaloexcludesize); fprintf(stderr,"fhaloexcludedistance : %.6e\n",gi.fhaloexcludedistance); fprintf(stderr,"\n"); } /* ** Cylindrical profiles */ if (gi.BinningCoordinateType == 1) { fprintf(stderr,"Cylindrical profiles:\n\n"); fprintf(stderr,"zAxis_x : %.6e LU\n",gi.zAxis[0]); fprintf(stderr,"zAxis_y : %.6e LU\n",gi.zAxis[1]); fprintf(stderr,"zAxis_z : %.6e LU\n",gi.zAxis[2]); switch(LengthType_zHeight) { case 0: strcpy(cdummy,"comoving"); break; case 1: strcpy(cdummy,"physical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Length type zHeight : %s\n",cdummy); fprintf(stderr,"zHeight : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", gi.zHeight,gi.zHeight/cosmo2internal_ct.L_usf,gi.ascale*gi.zHeight/cosmo2internal_ct.L_usf); fprintf(stderr,"\n"); } } /* ** Shape */ if (gi.ProfilingMode == 1) { fprintf(stderr,"Shape determination:\n\n"); switch(gi.ShapeDeterminationVolume) { case 0: strcpy(cdummy,"differential volume"); break; case 1: strcpy(cdummy,"enclosed volume"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Shape determination volume : %s\n",cdummy); switch(gi.ShapeTensorForm) { case 0: strcpy(cdummy,"S_ij"); break; case 1: strcpy(cdummy,"S_ij/r^2"); break; case 2: strcpy(cdummy,"S_ij/r_ell^2"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Shape tensor form : %s\n",cdummy); fprintf(stderr,"NLoopShapeIterationMax : %d\n",gi.NLoopShapeIterationMax); fprintf(stderr,"OutputFrequencyShapeIteration : %d\n",gi.OutputFrequencyShapeIteration); fprintf(stderr,"ShapeIterationTolerance : %.6e\n",gi.ShapeIterationTolerance); fprintf(stderr,"\n"); } /* ** Global binning grid parameters */ fprintf(stderr,"Global binning grid parameters:\n\n"); for (d = 0; d < gi.NDimProfile; d++) { fprintf(stderr,"Dimension %ld:\n",d+1); switch(LengthType_rmin[d]) { case 0: strcpy(cdummy,"comoving"); break; case 1: strcpy(cdummy,"physical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Length type rmin : %s\n",cdummy); switch(LengthType_rmax[d]) { case 0: strcpy(cdummy,"comoving"); break; case 1: strcpy(cdummy,"physical"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Length type rmax : %s\n",cdummy); if (gi.rmin[d] >= 0) { fprintf(stderr,"rmin : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", gi.rmin[d],gi.rmin[d]/cosmo2internal_ct.L_usf,gi.ascale*gi.rmin[d]/cosmo2internal_ct.L_usf); } else fprintf(stderr,"rmin : not set\n"); if (gi.rmax[d] >= 0) { fprintf(stderr,"rmax : %.6e LU (comoving) = %.6e kpc (comoving) = %.6e kpc (physical)\n", gi.rmax[d],gi.rmax[d]/cosmo2internal_ct.L_usf,gi.ascale*gi.rmax[d]/cosmo2internal_ct.L_usf); } else fprintf(stderr,"rmax : not set\n"); if (gi.NBin[d] > 0) fprintf(stderr,"NBin : %d\n",gi.NBin[d]); else fprintf(stderr,"NBin : not set\n"); if (gi.NBinPerDex[d] > 0) fprintf(stderr,"NBinPerDex : %g\n",gi.NBinPerDex[d]); else fprintf(stderr,"NBinPerDex : not set\n"); switch(gi.BinningGridType[d]) { case 0: strcpy(cdummy,"logarithmic"); break; case 1: strcpy(cdummy,"linear"); break; default: strcpy(cdummy,"not supported"); } fprintf(stderr,"Binning grid type : %s\n",cdummy); fprintf(stderr,"\n"); } } gettimeofday(&time,NULL); timeend = time.tv_sec; timediff = timeend-timestart; fprintf(stderr,"Done with profiling. It took %d s = %d h %d m %d s in total.\n",timediff,timediff/3600,(timediff/60)%60,timediff%60); exit(0); } void usage(void) { fprintf(stderr,"\n"); fprintf(stderr,"profile (%s)\n",VERSION); fprintf(stderr,"\n"); fprintf(stderr,"Program calculates the profiles and characteristics of haloes.\n"); fprintf(stderr,"\n"); fprintf(stderr,"You can specify the following arguments:\n"); fprintf(stderr,"\n"); fprintf(stderr,"-spp : set this flag if Tipsy XDR input files have single precision positions (default)\n"); fprintf(stderr,"-dpp : set this flag if Tipsy XDR input files have double precision positions\n"); fprintf(stderr,"-pfm <value> : set this flag for ART native binary particle file mode: 0 everything double precision; 1 positions and velocities double precision, times single precision; 2 everything single precision (default: 0)\n"); fprintf(stderr,"-ProfilingMode <value> : 0 = NDimProfile-dimensional profiles / 1 = shape determination (default: 0)\n"); fprintf(stderr,"-NDimProfile <value> : number of dimensions for profiling (default: 1)\n"); fprintf(stderr,"-DataProcessingMode <value> : 0 = read data again in every loop / 1 = store data in memory (default: 0)\n"); fprintf(stderr,"-DataFormat <value> : 0 = Tipsy / 1 = ART (default: 0)\n"); fprintf(stderr,"-HaloCatalogueFormat <value> : 0 = generic / 1 = 6DFOF / 2 = characteristics (default: 0)\n"); fprintf(stderr,"-HaloCatalogueNDim <value> : dimension of halo catalouge (default: 1)\n"); fprintf(stderr,"-ShapeDeterminationVolume <value> : 0 = differential volume / 1 enclosed volume (default: 0)\n"); fprintf(stderr,"-ShapeTensorForm <value> : 0 = S_ij / 1 = S_ij/r^2 / 2 = S_ij/r_ell^2 (default: 0)\n"); fprintf(stderr,"-DoMetalSpecies : set this flag for doing metal species\n"); fprintf(stderr,"-DoChemicalSpecies : set this flag for doing chemical species\n"); fprintf(stderr,"-DoGasTemperature : set this flag for doing gas temperature\n"); fprintf(stderr,"-DoStellarAge : set this flag for doing stellar age\n"); fprintf(stderr,"-MoreCharacteristicsOutput : set this flag for more characteristics output\n"); fprintf(stderr,"-RecentreUseGas <value> : 0 = no / 1 = yes (default: 0)\n"); fprintf(stderr,"-RecentreUseDark <value> : 0 = no / 1 = yes (default: 1)\n"); fprintf(stderr,"-RecentreUseStar <value> : 0 = no / 1 = yes (default: 1)\n"); fprintf(stderr,"-HaloSize <value> : 0 = rmean / 1 = rcrit / 2 = rfix (default: 0)\n"); fprintf(stderr,"-ExcludeParticles <value> : 0 = don't exclude any particles / 1 = exclude particles in specified halo catalogue (default: 0)\n"); fprintf(stderr,"-LengthType_rmin <d> <value> : d = dimension (1/2/3) / 0 = comoving / 1 = physical (default: 0)\n"); fprintf(stderr,"-LengthType_rmax <d> <value> : d = dimension (1/2/3) / 0 = comoving / 1 = physical (default: 0)\n"); fprintf(stderr,"-LengthType_zHeight <value> : 0 = comoving / 1 = physical (default: 0)\n"); fprintf(stderr,"-LengthType_rExclude <value> : 0 = comoving / 1 = physical (default: 0)\n"); fprintf(stderr,"-LengthType_rRecentre <value> : 0 = comoving / 1 = physical (default: 0)\n"); fprintf(stderr,"-rmin <d> <value> : d = dimension (1/2/3) / global minimum grid radius for dimension d [LU] - overwrites values form halo catalogue (default: not set)\n"); fprintf(stderr,"-rmax <d> <value> : d = dimension (1/2/3) / global maximum grid radius for dimension d [LU] - overwrites values form halo catalogue (default: not set)\n"); fprintf(stderr,"-NBin <d> <value> : d = dimension (1/2/3) / global number of bins between rmin and rmax for dimension d - overwrites values form halo catalogue (default: not set)\n"); fprintf(stderr,"-NBinPerDex <d> <value> : d = dimension (1/2/3) / global number of bins per decade between rmin and rmax for dimension d (can be a float) (default: not set)\n"); fprintf(stderr,"-BinningGridType <d> <value> : d = dimension (1/2/3) / global binning grid type: 0 = logarithmic / 1 = linear (default: 0)\n"); fprintf(stderr,"-BinningCoordinateType <value> : 0 = spherical coordinates / 1 = cylindrical coordinates (default: 0)\n"); fprintf(stderr,"-VelocityProjectionType <value> : 0 = coordinate axes / 1 = spherical coordinates / 2 = cylindrical coordinates (default: 0)\n"); fprintf(stderr,"-zAxis_x : x-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n"); fprintf(stderr,"-zAxis_y : y-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n"); fprintf(stderr,"-zAxis_z : z-component of global z-axis for cylindrical coordinates [LU] - overwrites values form z-axis catalogue (default: not set)\n"); fprintf(stderr,"-zHeight : height above mid-plane for inclusion for cylindrical binning [LU] - overwrites values form z-axis catalogue (default: not set)\n"); fprintf(stderr,"-CentreType <value> : 0 = centre-of-mass centres / 1 = potmin or denmax centres (only for 6DFOF halocatalogue) (default: 0)\n"); fprintf(stderr,"-BinFactor <value> : extra factor for rmax determined form 6DFOF file (default: 5) (only for 6DFOF halocatalogue)\n"); fprintf(stderr,"-rmaxFromHaloCatalogue : set this flag for rmax determined from 6DFOF file (only for 6DFOF halocatalogue)\n"); fprintf(stderr,"-OmegaM0 <value> : OmegaM0 value (default: 0) (only necessary for Tipsy format)\n"); fprintf(stderr,"-OmegaL0 <value> : OmegaL0 value (default: 0) (only necessary for Tipsy format)\n"); fprintf(stderr,"-OmegaK0 <value> : OmegaK0 value (default: 0) (only necessary for Tipsy format)\n"); fprintf(stderr,"-OmegaR0 <value> : OmegaR0 value (default: 0) (only necessary for Tipsy format)\n"); fprintf(stderr,"-h0_100 <value> : h0_100 value (default: 0) (only necessary for Tipsy format)\n"); fprintf(stderr,"-LBox <value> : box length (comoving) [kpc]\n"); fprintf(stderr,"-LBox_internal <value> : box length (comoving) [LU] (default: standard value depending on file format)\n"); fprintf(stderr,"-Hubble0_internal <value> : Hubble parameter today [TU^{-1}] (default: standard value depending on file format)\n"); fprintf(stderr,"-rhocrit0_internal <value> : critical density today [MU LU^{-3}] (default: standard value depending on file format)\n"); fprintf(stderr,"-Delta_mean <value> : overdensity with respect to current background density (default: 200)\n"); fprintf(stderr,"-Delta_crit <value> : overdensity with respect to current critical density (default: 200)\n"); fprintf(stderr,"-Delta_fix <value> : overdensity with respect to background density at afix (default: 200)\n"); fprintf(stderr,"-afix <value> : scale factor for fixed overdensity (default: 1)\n"); fprintf(stderr,"-ascale <value> : scale factor of the data (default: set from data, needed for non-cosmological simulations)\n"); fprintf(stderr,"-LmaxGasAnalysis <value> : maximum level of gas analysed [counting from 0] (default: Lmaxgas in data)\n"); fprintf(stderr,"-NParticlePerBockGas <value> : number of gas particles per block (default: 1e7)\n"); fprintf(stderr,"-NParticlePerBlockDark <value> : number of dark matter particles per block (default: 1e7)\n"); fprintf(stderr,"-NParticlePerBlockStar <value> : number of star particles per block (default: 1e7)\n"); fprintf(stderr,"-NCellData <value> : number of cells per dimension in linked cell method for data loops (default: 20)\n"); fprintf(stderr,"-NCellHalo <value> : number of cells per dimension in linked cell method for halo loops (default: 10)\n"); fprintf(stderr,"-NLoopRecentre <value> : number of loops for recentering (default: 0)\n"); fprintf(stderr,"-rRecentre <value> : radius for recentering [LU] (default: 0 LU)\n"); fprintf(stderr,"-fRecentreDist <value> : factor for subsequential decrease of region in recentering loops (default: 1.5)\n"); fprintf(stderr,"-rExclude <value> : radius for exclusion [LU] (default: 0 LU)\n"); fprintf(stderr,"-NLoopShapeIterationMax <value> : number of maximum loops for shape iteration (default: 50)\n"); fprintf(stderr,"-GRAVITY <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format] \n"); fprintf(stderr,"-HYDRO <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-ADVECT_SPECIES <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-STARFORM <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-ENRICH <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-ENRICH_SNIa <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-RADIATIVE_TRANSFER <value> : 0 = flag not set / 1 = flag set (default: 1) [only necessary for ART format]\n"); fprintf(stderr,"-ELECTRON_ION_NONEQUILIBRIUM <value> : 0 = flag not set / 1 = flag set (default: 0) [only necessary for ART format]\n"); fprintf(stderr,"-verbose : verbose\n"); fprintf(stderr,"< <name> : name of input file in Tipsy XDR format\n"); fprintf(stderr,"-ARTHeader <name> : header file in ART native binary format\n"); fprintf(stderr,"-ARTCoordinatesData <name> : coordinates data file in ART native binary format\n"); fprintf(stderr,"-ARTStarProperties <name> : star properties file in ART native binary format\n"); fprintf(stderr,"-ARTGas <name> : gas file in ART native binary format\n"); fprintf(stderr,"-HaloCatalogue <name> : halo catalouge file\n"); fprintf(stderr,"-ExcludeHaloCatalogue <name> : halo catalouge file (only characteristics format supported)\n"); fprintf(stderr,"-zAxisCatalogue <name> : z-axis catalouge file\n"); fprintf(stderr,"-Output <name> : name of output files (endings like .characteristics etc. appended automatically)\n"); fprintf(stderr,"\n"); exit(1); } void set_default_values_general_info(GI *gi) { int d, i; /* ** Cosmological parameters */ gi->cp.OmegaM0 = 0; gi->cp.OmegaD0 = 0; gi->cp.OmegaB0 = 0; gi->cp.OmegaL0 = 0; gi->cp.OmegaK0 = 0; gi->cp.OmegaR0 = 0; gi->cp.h0_100 = 0; gi->us.LBox = 0; gi->us.Hubble0 = 0; gi->us.rhocrit0 = 0; gi->cosmous.LBox = 0; gi->cosmous.Hubble0 = 0; gi->cosmous.rhocrit0 = 0; /* ** General parameters */ gi->DataFormat = 0; /* Tipsy */ gi->HaloCatalogueFormat = 0; /* generic */ gi->HaloCatalogueNDim = 1; /* 1-dimensional profiles */ gi->HaloCatalogueBinningCoordinateType = 0; /* spherical */ gi->ExcludeHaloCatalogueFormat = 2; /* characteristics */ gi->ExcludeHaloCatalogueNDim = 1; /* 1-dimensional profiles */ gi->ProfilingMode = 0; /* normal profile */ gi->DataProcessingMode = 0; /* looping */ gi->ShapeDeterminationVolume = 0; /* differential volume */ gi->ShapeTensorForm = 0; /* no weights */ gi->DoMetalSpecies = 0; /* no metal species */ gi->DoChemicalSpecies = 0; /* no chemical species */ gi->DoGasTemperature = 0; /* no gas temperature */ gi->DoStellarAge = 0; /* no stellar age */ gi->MoreCharacteristicsOutput = 0; /* not more characteristics output */ gi->HaloSize = 0; /* rmean */ gi->ExcludeParticles = 0; /* no particles excluded */ gi->zAxisCatalogueSpecified = 0; /* no z-axis catalogue sepcified */ gi->CentreType = 0; gi->VelocityProjectionType = 0; gi->rmaxFromHaloCatalogue = 0; gi->NDimProfile = 1; gi->NSpeciesRead = 3; gi->NSpeciesProfile = 5; gi->NHalo = 0; gi->NHaloExcludeGlobal = 0; /* ** Binning structure */ gi->BinningCoordinateType = 0; /* spherical */ for (d = 0; d < 3; d++) { gi->rmin[d] = -1; gi->rmax[d] = -1; gi->NBin[d] = 0; gi->NBinPerDex[d] = 0; gi->BinningGridType[d] = 0; /* logarithmic */ } gi->zAxis[0] = 0; gi->zAxis[1] = 0; gi->zAxis[2] = 0; gi->zHeight = 0; gi->SizeStorageIncrement = 1e7; for (d = 0; d < NSPECIESREADMAX; d++) { gi->NParticlePerBlock[d] = 1e7; gi->NParticleInBlock[d] = 0; gi->SizeStorage[d] = 0; gi->NParticleInStorage[d] = 0; gi->NSubSpecies[d] = 1; gi->NProperties[d] = 0; for (i = 0; i < NSUBSPECIESMAX+NPROPERTIESMAX; i++) { gi->pi[d][i] = 0; } } for (d = 0; d < NSPECIESPROFILEMAX; d++) { for (i = 0; i < NPROPERTIESMAX; i++) { gi->bi[d][i] = 0; } } gi->RecentreUse[GAS] = 0; gi->RecentreUse[DARK] = 1; gi->RecentreUse[STAR] = 1; gi->NCellData = 20; gi->NCellHalo = 10; gi->NLoopShapeIterationMax = 50; gi->NLoopProcessData = 1; gi->OutputFrequencyShapeIteration = 10; gi->ascale = 0; gi->rhomean = 0; gi->rhocrit = 0; gi->Deltamean = 200; gi->Deltacrit = 200; gi->Deltafix = 200; gi->afix = 1; gi->BinFactor = 5; gi->rExclude = 0; gi->rRecentre = 0; gi->fRecentreDist = 1.5; gi->NLoopRecentre = 0; gi->fcheckrvcmax = 2.0; gi->slopertruncindicator = -0.5; gi->frhobg = 1.2; gi->ShapeIterationTolerance = 1e-5; gi->fhaloduplicate = 0; gi->fhaloexcludesize = 0.5; gi->fhaloexcludedistance = 0.5; /* gi->fincludeshapeproperty = 1.1; */ /* gi->fincludeshaperadius = 2; */ strcpy(gi->MatterTypeName[TOT],"tot"); strcpy(gi->MatterTypeName[GAS],"gas"); strcpy(gi->MatterTypeName[DARK],"dark"); strcpy(gi->MatterTypeName[STAR],"star"); strcpy(gi->MatterTypeName[BARYON],"baryon"); strcpy(gi->MatterTypeName[GAS_METAL_SNII],"gas_metal_SNII"); strcpy(gi->MatterTypeName[GAS_METAL_SNIa],"gas_metal_SNIa"); strcpy(gi->MatterTypeName[STAR_METAL_SNII],"star_metal_SNII"); strcpy(gi->MatterTypeName[STAR_METAL_SNIa],"star_metal_SNIa"); strcpy(gi->MatterTypeName[BARYON_METAL_SNII],"baryon_metal_SNII"); strcpy(gi->MatterTypeName[BARYON_METAL_SNIa],"baryon_metal_SNIa"); strcpy(gi->MatterTypeName[GAS_HI],"gas_HI"); strcpy(gi->MatterTypeName[GAS_HII],"gas_HII"); strcpy(gi->MatterTypeName[GAS_HeI],"gas_HeI"); strcpy(gi->MatterTypeName[GAS_HeII],"gas_HeII"); strcpy(gi->MatterTypeName[GAS_HeIII],"gas_HeIII"); strcpy(gi->MatterTypeName[GAS_H2],"gas_H2"); } void calculate_densities(GI *gi) { double E, OmegaM; E = Ecosmo(gi->ascale,gi->cp); OmegaM = gi->cp.OmegaM0/(pow(gi->ascale,3)*E*E); assert(gi->Deltamean > 0); assert(gi->Deltacrit > 0); assert(gi->Deltafix > 0); /* ** The following densities are all comoving densities at ascale */ gi->rhocrit = gi->us.rhocrit0*E*E*pow(gi->ascale,3); gi->rhomean = OmegaM*gi->rhocrit; gi->rhoencmean = gi->Deltamean*gi->rhomean; gi->rhoenccrit = gi->Deltacrit*gi->rhocrit; /* ** Calculate fixed density at afix */ E = Ecosmo(gi->afix,gi->cp); OmegaM = gi->cp.OmegaM0/(pow(gi->afix,3)*E*E); gi->rhoencfix = gi->Deltafix*OmegaM*gi->us.rhocrit0*E*E; /* physical density */ gi->rhoencfix *= pow(gi->ascale,3); /* comoving density at ascale */ } void read_halocatalogue_ascii(GI *gi, HALO_DATA **hdin) { int SizeHaloDataIncrement = 1000; int SizeHaloData = SizeHaloDataIncrement; int d, n[3], i, j, idummy, ID, IDz, NBin[3], NHaloRead; double ddummy; double r[3], v[3], rcom[3], rpotorden[3], zAxis[3], zHeight; double rmin[3], rmax[3]; double mass, radius; char cdummy[1000]; HALO_DATA *hd; FILE *HaloCatalogueFile = NULL, *zAxisCatalogueFile = NULL; HaloCatalogueFile = fopen(gi->HaloCatalogueFileName,"r"); assert(HaloCatalogueFile != NULL); if (gi->zAxisCatalogueSpecified) { zAxisCatalogueFile = fopen(gi->zAxisCatalogueFileName,"r"); assert(zAxisCatalogueFile != NULL); fgets(cdummy,1000,zAxisCatalogueFile); } hd = *hdin; hd = realloc(hd,SizeHaloData*sizeof(HALO_DATA)); assert(hd != NULL); /* ** Read header line if present, then read all halos */ if (gi->HaloCatalogueFormat == 0 || gi->HaloCatalogueFormat == 2) fgets(cdummy,1000,HaloCatalogueFile); NHaloRead = 0; while (1) { /* ** Set some default values */ for (d = 0; d < 3; d++) { rmin[d] = 0; rmax[d] = 0; NBin[d] = 1; /* at least one bin */ zAxis[d] = 0; } zHeight = 0; /* ** Read halo catalogues */ if (gi->HaloCatalogueFormat == 0) { /* ** Generic format */ fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]); fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy; for (d = 0; d < gi->HaloCatalogueNDim; d++) { fscanf(HaloCatalogueFile,"%lg",&ddummy); rmin[d] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); rmax[d] = ddummy; fscanf(HaloCatalogueFile,"%i",&idummy); NBin[d] = (idummy > 0)?idummy:NBin[d]; /* NBin between rmin and rmax => no correction for logarithmic bins */ } if (gi->HaloCatalogueBinningCoordinateType == 1) { fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zHeight = ddummy; } if (feof(HaloCatalogueFile)) break; } else if (gi->HaloCatalogueFormat == 1) { /* ** 6DFOF format */ fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy; fscanf(HaloCatalogueFile,"%i",&idummy); /* N = idummy; */ fscanf(HaloCatalogueFile,"%lg",&ddummy); mass = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); radius = ddummy; /* dispersion in coordinates */ fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]); fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]); fscanf(HaloCatalogueFile,"%lg",&ddummy); rcom[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]); fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]); fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]); fscanf(HaloCatalogueFile,"%lg",&ddummy); rpotorden[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]); fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy; if (feof(HaloCatalogueFile)) break; if (gi->CentreType == 0) { for (d = 0; d < 3; d++) r[d] = rcom[d]; } else if (gi->CentreType == 1) { for (d = 0; d < 3; d++) r[d] = rpotorden[d]; } else { fprintf(stderr,"Not supported center type!\n"); exit(1); } rmin[0] = 0; if (gi->rmaxFromHaloCatalogue == 1) { /* ** Estimate maximum radius; assume isothermal sphere scaling */ rmax[0] = sqrt((3.0*mass/(4.0*M_PI*radius*radius*radius))/gi->rhoencmean)*radius*gi->BinFactor; assert(rmax[0] > 0); } else { rmax[0] = 0; } } else if (gi->HaloCatalogueFormat == 2) { /* ** Characteristics format */ fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]); fscanf(HaloCatalogueFile,"%lg",&ddummy); v[0] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[1] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); v[2] = ddummy; for (d = 0; d < gi->HaloCatalogueNDim; d++) { fscanf(HaloCatalogueFile,"%lg",&ddummy); rmin[d] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); rmax[d] = ddummy; fscanf(HaloCatalogueFile,"%i",&idummy); NBin[d] = (idummy > 0)?idummy:NBin[d]; if (gi->BinningGridType[d] == 0) { /* ** Correct for logarithmic binning: innermost bin is already counted here. ** HaloCatalogue needs to have same binning type as the profiling done now. ** No way to check this at the moment. */ NBin[d] -= 1; } } if (gi->HaloCatalogueBinningCoordinateType == 0) { fgets(cdummy,1000,HaloCatalogueFile); } else if (gi->HaloCatalogueBinningCoordinateType == 1) { fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); zHeight = ddummy; } if (feof(HaloCatalogueFile)) break; } else { fprintf(stderr,"Not supported halo catalogue format!\n"); exit(1); } if (gi->BinningCoordinateType == 1) { /* ** Use z-axis catalogue values if specified */ if (gi->zAxisCatalogueSpecified) { fscanf(zAxisCatalogueFile,"%i",&idummy); IDz = idummy; fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[0] = ddummy; fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[1] = ddummy; fscanf(zAxisCatalogueFile,"%lg",&ddummy); zAxis[2] = ddummy; fscanf(zAxisCatalogueFile,"%lg",&ddummy); zHeight = ddummy; assert(ID == IDz); } /* ** Use global values if specified */ if (gi->zAxis[0] != 0 || gi->zAxis[1] != 0 || gi->zAxis[2] != 0) { for (d = 0; d < 3; d++) zAxis[d] = gi->zAxis[d]; } if (gi->zHeight > 0) zHeight = gi->zHeight; } NHaloRead++; if (SizeHaloData < NHaloRead){ SizeHaloData += SizeHaloDataIncrement; hd = realloc(hd,SizeHaloData*sizeof(HALO_DATA)); assert(hd != NULL); } i = NHaloRead-1; /* ** Basic halo properties */ hd[i].ID = ID; for (d = 0; d < 3; d++) { hd[i].rcentre[d] = r[d]; hd[i].vcentre[d] = v[d]; } /* ** Set-up bin structure */ if (gi->BinningCoordinateType == 1) { ddummy = 1.0/sqrt(pow(zAxis[0],2)+pow(zAxis[1],2)+pow(zAxis[2],2)); assert(ddummy > 0 && !isnan(ddummy) && !isinf(ddummy)); for (d = 0; d < 3; d++) hd[i].zAxis[d] = zAxis[d]*ddummy; if (zHeight > 0) rmax[1] = zHeight; } for (d = 0; d < 3; d++) { hd[i].rmin[d] = (gi->rmin[d] >= 0)?gi->rmin[d]:rmin[d]; hd[i].rmax[d] = (gi->rmax[d] >= 0)?gi->rmax[d]:rmax[d]; hd[i].NBin[d] = (gi->NBin[d] > 0)?gi->NBin[d]:NBin[d]; assert(hd[i].rmax[d] >= hd[i].rmin[d]); assert(hd[i].NBin[d] > 0); if (gi->BinningGridType[d] == 0 && d < gi->NDimProfile) { /* ** Logarithmic bins */ assert(hd[i].rmin[d] > 0); assert(hd[i].rmax[d] > 0); assert(hd[i].rmax[d] > hd[i].rmin[d]); hd[i].NBin[d] += 1; /* account for inner bin from 0-rmin */ if (gi->NBinPerDex[d] > 0) { /* ** Calculate NBin and rmax */ hd[i].NBin[d] = (int)((log10(hd[i].rmax[d])-log10(hd[i].rmin[d]))*gi->NBinPerDex[d]) + 1; hd[i].rmax[d] = hd[i].rmin[d]*pow(10,hd[i].NBin[d]/gi->NBinPerDex[d]); hd[i].NBin[d] += 1; /* account for inner bin from 0-rmin */ } } if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1) { /* ** 2-dimensional binning in cylindrical coordinates */ hd[i].NBin[d] *= 2; } } if (gi->BinningCoordinateType == 1) hd[i].zHeight = hd[i].rmax[1]; /* ** Allocate bins */ hd[i].pbs = malloc(hd[i].NBin[0]*sizeof(PROFILE_BIN_STRUCTURE**)); assert(hd[i].pbs != NULL); for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { hd[i].pbs[n[0]] = malloc(hd[i].NBin[1]*sizeof(PROFILE_BIN_STRUCTURE*)); assert(hd[i].pbs[n[0]] != NULL); for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) { hd[i].pbs[n[0]][n[1]] = malloc(hd[i].NBin[2]*sizeof(PROFILE_BIN_STRUCTURE)); assert(hd[i].pbs[n[0]][n[1]] != NULL); for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) { if (gi->ProfilingMode == 0) { hd[i].pbs[n[0]][n[1]][n[2]].bin = malloc(gi->NSpeciesProfile*sizeof(PROFILE_BIN_PROPERTIES)); assert(hd[i].pbs[n[0]][n[1]][n[2]].bin != NULL); hd[i].pbs[n[0]][n[1]][n[2]].shape = NULL; for (j = 0; j < gi->NSpeciesProfile; j++) { if (j < gi->NSpeciesRead && gi->NProperties[j] > 0) { hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P = malloc(gi->NProperties[j]*sizeof(double)); assert(hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P != NULL); } else { hd[i].pbs[n[0]][n[1]][n[2]].bin[j].P = NULL; } } } else if (gi->ProfilingMode == 1) { hd[i].pbs[n[0]][n[1]][n[2]].shape = malloc(gi->NSpeciesProfile*sizeof(PROFILE_SHAPE_PROPERTIES)); assert(hd[i].pbs[n[0]][n[1]][n[2]].shape != NULL); hd[i].pbs[n[0]][n[1]][n[2]].bin = NULL; } } } } /* ** Initialise halo profile */ initialise_halo_profile(gi,&hd[i]); } fclose(HaloCatalogueFile); if (gi->zAxisCatalogueSpecified) fclose(zAxisCatalogueFile); *hdin = hd; gi->NHalo = NHaloRead; } int read_halocatalogue_ascii_excludehalo(GI *gi, HALO_DATA *hd, HALO_DATA_EXCLUDE **hdegin) { int SizeHaloDataIncrement = 1000; int SizeHaloData = SizeHaloDataIncrement; int d, i, j, k, l, idummy, ID, NHaloRead, NIndexArray; int MoveToGlobalList, ContainedInHaloDataList, Ntot, Ncheck; int *IndexArray = NULL; double ddummy; double r[3], rcheck[3]; double dsph; double sizeorig, size; double *SizeArray = NULL; char cdummy[1000]; HALO_DATA_EXCLUDE *hdeg; FILE *HaloCatalogueFile = NULL; HaloCatalogueFile = fopen(gi->ExcludeHaloCatalogueFileName,"r"); assert(HaloCatalogueFile != NULL); for (j = 0; j < gi->NHalo; j++) { hd[j].SizeExcludeHaloData = SizeHaloDataIncrement; hd[j].hde = realloc(hd[j].hde,hd[j].SizeExcludeHaloData*sizeof(HALO_DATA_EXCLUDE)); assert(hd[j].hde != NULL); } hdeg = *hdegin; hdeg = realloc(hdeg,SizeHaloData*sizeof(HALO_DATA_EXCLUDE)); assert(hdeg != NULL); IndexArray = malloc(gi->NHalo*sizeof(int)); assert(IndexArray != NULL); SizeArray = malloc(gi->NHalo*sizeof(double)); assert(SizeArray != NULL); /* ** Read header line if present, then read all halos */ if (gi->ExcludeHaloCatalogueFormat == 2) fgets(cdummy,1000,HaloCatalogueFile); NHaloRead = 0; while (1) { if (gi->ExcludeHaloCatalogueFormat == 2) { fscanf(HaloCatalogueFile,"%i",&idummy); ID = idummy; fscanf(HaloCatalogueFile,"%lg",&ddummy); r[0] = put_in_box(ddummy,gi->bc[0],gi->bc[3]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[1] = put_in_box(ddummy,gi->bc[1],gi->bc[4]); fscanf(HaloCatalogueFile,"%lg",&ddummy); r[2] = put_in_box(ddummy,gi->bc[2],gi->bc[5]); fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[0] = ddummy; */ fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[1] = ddummy; */ fscanf(HaloCatalogueFile,"%lg",&ddummy); /* v[2] = ddummy; */ for (d = 0; d < gi->ExcludeHaloCatalogueNDim; d++) { fscanf(HaloCatalogueFile,"%lg",&ddummy); /* rmin[d] = ddummy; */ fscanf(HaloCatalogueFile,"%lg",&ddummy); /* rmax[d] = ddummy; */ fscanf(HaloCatalogueFile,"%i",&idummy); /* NBin[d] = idummy; */ } fscanf(HaloCatalogueFile,"%lg",&ddummy); sizeorig = ddummy; fgets(cdummy,1000,HaloCatalogueFile); if (feof(HaloCatalogueFile)) break; sizeorig *= gi->fhaloexcludesize; } else { fprintf(stderr,"Not supported halo catalogue format!\n"); exit(1); } NHaloRead++; /* ** Now determine if it is a excluded halo */ ContainedInHaloDataList = 0; NIndexArray = 0; for (i = 0; i < gi->NHalo; i++) { if (hd[i].ID == ID) { ContainedInHaloDataList = 1; continue; /* Don't exclude yourself */ } for (d = 0; d < 3; d++) { rcheck[d] = correct_position(hd[i].rcentre[d],r[d],gi->us.LBox); rcheck[d] = rcheck[d]-hd[i].rcentre[d]; } dsph = sqrt(rcheck[0]*rcheck[0]+rcheck[1]*rcheck[1]+rcheck[2]*rcheck[2]); /* ** Check if spheres overlap, i.e. some particles need to be excluded */ if (dsph <= hd[i].rmax[0]+sizeorig) { /* ** Check if halo centre is contained ** => if yes take fraction fhaloexcludedistance of the distance as size */ if (sizeorig > dsph) size = gi->fhaloexcludedistance*dsph; else size = sizeorig; if (size > 0) { hd[i].NHaloExclude++; NIndexArray++; IndexArray[NIndexArray-1] = i; SizeArray[NIndexArray-1] = size; if (hd[i].SizeExcludeHaloData < hd[i].NHaloExclude) { hd[i].SizeExcludeHaloData += SizeHaloDataIncrement; hd[i].hde = realloc(hd[i].hde,hd[i].SizeExcludeHaloData*sizeof(HALO_DATA_EXCLUDE)); assert(hd[i].hde != NULL); } j = hd[i].NHaloExclude-1; hd[i].hde[j].ID = ID; for (d = 0; d < 3; d++) hd[i].hde[j].rcentre[d] = r[d]; hd[i].hde[j].size = size; } } } /* ** In the case of DataProcessingMode == 0 we're done now. ** But if we use DataProcessingMode == 1 we can move the haloes that have a single size and ** are not in the hd halo list to the global exclude list, i.e. we never have to consider ** these particles at all. */ if (gi->DataProcessingMode == 1 && NIndexArray > 0) { MoveToGlobalList = 0; Ntot = 0; Ncheck = 0; /* ** Only if in all appearances the halo has the same size move it to the global list */ if (NIndexArray == 1) MoveToGlobalList = 1; else if (NIndexArray > 1) { for (j = 1; j < NIndexArray; j++) { Ntot++; if (SizeArray[j] == SizeArray[j-1]) Ncheck++; } if (Ntot == Ncheck) MoveToGlobalList = 1; } /* ** Halo is not allowed to be in the halo data list */ if (ContainedInHaloDataList) MoveToGlobalList = 0; /* ** Move to global exclusion list */ if (MoveToGlobalList) { for (j = 0; j < NIndexArray; j++) { i = IndexArray[j]; /* ** Transfer the halo => only need to do that once (j == 0) */ if (j == 0) { gi->NHaloExcludeGlobal++; if (SizeHaloData < gi->NHaloExcludeGlobal) { SizeHaloData += SizeHaloDataIncrement; hdeg = realloc(hdeg,SizeHaloData*sizeof(HALO_DATA_EXCLUDE)); assert(hdeg != NULL); } l = gi->NHaloExcludeGlobal-1; hdeg[l].ID = ID; for (k = 0; k < 3; k++) hdeg[l].rcentre[k] = r[k]; hdeg[l].size = SizeArray[0]; } /* ** Remove the haloes from the local list */ assert(hd[i].hde[hd[i].NHaloExclude-1].ID == ID); hd[i].NHaloExclude--; } } } } /* while loop */ fclose(HaloCatalogueFile); free(IndexArray); free(SizeArray); *hdegin = hdeg; return NHaloRead; } void initialise_halo_profile(GI *gi, HALO_DATA *hd) { int d, n[3], j, l; double dr[3] = {0,0,0}; const double ex[3] = {1,0,0}; const double ey[3] = {0,1,0}; const double ez[3] = {0,0,1}; PROFILE_BIN_STRUCTURE *pbs; PROFILE_BIN_PROPERTIES *bin; PROFILE_SHAPE_PROPERTIES *shape; hd->HostHaloID = -1; hd->ExtraHaloID = -1; hd->NHaloExclude = 0; hd->SizeExcludeHaloData = 0; hd->IsTruncated = 0; hd->rmean = 0; hd->Mrmean = 0; hd->rcrit = 0; hd->Mrcrit = 0; hd->rfix = 0; hd->Mrfix = 0; hd->rtrunc = 0; hd->Mrtrunc = 0; hd->rtruncindicator = 0; hd->size = 0; hd->mass = 0; for (d = 0; d < 3; d++) { hd->rcentrenew[d] = 0; hd->vcentrenew[d] = 0; } for (j = 0; j < NSPECIESBACKGROUND; j++) { hd->rhobg[j] = 0; for (l = 0; l < 2; l++) { hd->rvcmax[j][l] = 0; hd->Mrvcmax[j][l] = 0; } } /* ** Calculate bin spacings */ for (d = 0; d < gi->NDimProfile; d++) { if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1) { if (gi->BinningGridType[d] == 0) { dr[d] = (log(hd->rmax[d])-log(hd->rmin[d]))/(hd->NBin[d]/2-1); } else if (gi->BinningGridType[d] == 1) { dr[d] = (hd->rmax[d]-hd->rmin[d])/(hd->NBin[d]/2); } } else { if (gi->BinningGridType[d] == 0) { dr[d] = (log(hd->rmax[d])-log(hd->rmin[d]))/(hd->NBin[d]-1); } else if (gi->BinningGridType[d] == 1) { dr[d] = (hd->rmax[d]-hd->rmin[d])/hd->NBin[d]; } } } /* ** Initialise bins */ for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) { for (n[1] = 0; n[1] < hd->NBin[1]; n[1]++) { for (n[2] = 0; n[2] < hd->NBin[2]; n[2]++) { pbs = &hd->pbs[n[0]][n[1]][n[2]]; /* ** Calculate coordinates of bins */ for (d = 0; d < gi->NDimProfile; d++) { if (gi->NDimProfile == 2 && gi->BinningCoordinateType == 1 && d == 1 && n[1] >= hd->NBin[1]/2) { l = hd->NBin[1]/2; pbs->ri[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].ro[d]; pbs->rm[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].rm[d]; pbs->ro[d] = (-1)*hd->pbs[n[0]][n[1]-l][n[2]].ri[d]; } else { if (gi->BinningGridType[d] == 0) { if (n[d] == 0) { pbs->ri[d] = 0; pbs->rm[d] = exp(log(hd->rmin[d])-0.5*dr[d]); pbs->ro[d] = hd->rmin[d]; } else { pbs->ri[d] = exp(log(hd->rmin[d]) + (n[d]-1)*dr[d]); pbs->rm[d] = exp(log(hd->rmin[d]) + (n[d]-0.5)*dr[d]); pbs->ro[d] = exp(log(hd->rmin[d]) + n[d]*dr[d]); } } else if (gi->BinningGridType[d] == 1) { pbs->ri[d] = hd->rmin[d] + n[d]*dr[d]; pbs->rm[d] = hd->rmin[d] + (n[d]+0.5)*dr[d]; pbs->ro[d] = hd->rmin[d] + (n[d]+1)*dr[d]; } } } /* ** Initialise bin and shape structures */ for (j = 0; j < gi->NSpeciesProfile; j++) { if (gi->SpeciesContained[j]) { if (gi->ProfilingMode == 0) { /* ** Bin */ bin = &pbs->bin[j]; bin->N = 0; bin->M = 0; bin->Menc[0] = 0; bin->Menc[1] = 0; for (d = 0; d < 3; d++) { bin->v[d] = 0; bin->L[d] = 0; } for (d = 0; d < 6; d++) { bin->vdt[d] = 0; } if (j < gi->NSpeciesRead) { for (d = 0; d < gi->NProperties[j]; d++) { bin->P[d] = 0; } } } else if (gi->ProfilingMode == 1) { /* ** Shape */ shape = &pbs->shape[j]; shape->NLoopConverged = 0; shape->N = 0; shape->M = 0; shape->b_a = 0; shape->c_a = 0; shape->b_a_old = 0; shape->c_a_old = 0; /* shape->dmin = 0; */ /* shape->dmax = 0; */ /* shape->propertymin = 0; */ /* shape->propertymax = 0; */ /* shape->propertymean = 0; */ for (d = 0; d < 3; d++) { shape->a[d] = ex[d]; shape->b[d] = ey[d]; shape->c[d] = ez[d]; } for (d = 0; d < 6; d++) { shape->st[d] = 0; } } } /* if SpeciesContained */ } /* for NSpeciesProfile */ } /* for n[2] */ } /* for n[1] */ } /* for n[0] */ } void reset_halo_profile_shape(GI gi, HALO_DATA *hd) { int d, n[3], i, j; PROFILE_SHAPE_PROPERTIES *shape; #pragma omp parallel for default(none) private(d,n,i,j,shape) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) { for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) { for (j = 0; j < gi.NSpeciesProfile; j++) { if (gi.SpeciesContained[j]) { shape = &hd[i].pbs[n[0]][n[1]][n[2]].shape[j]; shape->N = 0; shape->M = 0; for (d = 0; d < 6; d++) shape->st[d] = 0; } } } } } } } void add_particle_to_shape_tensor(GI gi, PROFILE_SHAPE_PROPERTIES *shape, double M, double r[3], double dsph, double dell) { int d; double fst; switch(gi.ShapeTensorForm) { case 0: fst = 1; break; case 1: fst = 1/pow(dsph,2); break; case 2: fst = 1/pow(dell,2); break; default: fst = 1; } shape->N++; shape->M += M; for (d = 0; d < 3; d++) shape->st[d] += M*r[d]*r[d]*fst; shape->st[3] += M*r[0]*r[1]*fst; shape->st[4] += M*r[0]*r[2]*fst; shape->st[5] += M*r[1]*r[2]*fst; } void put_particles_in_bins(GI gi, HALO_DATA *hd, const int MatterType, PROFILE_PARTICLE *pp) { int d, n[3], i, j, k, l; int index[3]; int NParticle = 0; int ParticleAccepted, InThisBin, LoopBroken; int ***HeadIndex, *NextIndex; double r[3], rell[3], v[3], vproj[3]; double eA[3], eB[3], eC[3]; double dsph, dell, size; double dist[3], shift[3]; double M; PROFILE_BIN_STRUCTURE *pbs; PROFILE_BIN_PROPERTIES *bin; PROFILE_SHAPE_PROPERTIES *shape; if (gi.DataProcessingMode == 0) NParticle = gi.NParticleInBlock[MatterType]; else if (gi.DataProcessingMode == 1) NParticle = gi.NParticleInStorage[MatterType]; /* ** Initialise linked list stuff */ HeadIndex = malloc(gi.NCellData*sizeof(int **)); assert(HeadIndex != NULL); for (i = 0; i < gi.NCellData; i ++) { HeadIndex[i] = malloc(gi.NCellData*sizeof(int *)); assert(HeadIndex[i] != NULL); for (j = 0; j < gi.NCellData; j++) { HeadIndex[i][j] = malloc(gi.NCellData*sizeof(int)); assert(HeadIndex[i][j] != NULL); } } NextIndex = malloc(NParticle*sizeof(int)); assert(NextIndex != NULL); for (i = 0; i < gi.NCellData; i++) { for (j = 0; j < gi.NCellData; j++) { for (k = 0; k < gi.NCellData; k++) { HeadIndex[i][j][k] = -1; } } } for (j = 0; j < NParticle; j++) NextIndex[j] = -1; for (d = 0; d < 3; d++) shift[d] = 0-gi.bc[d]; /* ** Generate linked list */ for (j = 0; j < NParticle; j++) { for (d = 0; d < 3; d++) { index[d] = (int)(gi.NCellData*(pp[j].r[d]+shift[d])/gi.us.LBox); if (index[d] == gi.NCellData) index[d] = gi.NCellData-1; /* Case where particles are exactly on the boundary */ assert(index[d] >= 0 && index[d] < gi.NCellData); } NextIndex[j] = HeadIndex[index[0]][index[1]][index[2]]; HeadIndex[index[0]][index[1]][index[2]] = j; } /* ** Go through linked list */ for (index[0] = 0; index[0] < gi.NCellData; index[0]++) { for (index[1] = 0; index[1] < gi.NCellData; index[1]++) { for (index[2] = 0; index[2] < gi.NCellData; index[2]++) { #pragma omp parallel for default(none) private(d,n,i,j,k,l,ParticleAccepted,InThisBin,LoopBroken,r,rell,v,vproj,eA,eB,eC,dsph,dell,size,dist,M,pbs,bin,shape) shared(gi,hd,pp,index,shift,HeadIndex,NextIndex) for (i = 0; i < gi.NHalo; i++) { if (gi.ILoopRead < gi.NLoopRecentre && gi.RecentreUse[MatterType] == 1) { /* ** Recentre halo coordinates */ size = gi.rRecentre; size *= pow(gi.fRecentreDist,gi.NLoopRecentre-1-gi.ILoopRead); assert(size > 0); if (intersect(gi.us.LBox,gi.NCellData,hd[i],index,shift,size)) { j = HeadIndex[index[0]][index[1]][index[2]]; while (j >= 0) { for (d = 0; d < 3; d++) { r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox); r[d] = r[d]-hd[i].rcentre[d]; } dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); if (dsph <= size) { M = pp[j].P[gi.pi[MatterType][MASS_TOT]]; hd[i].Mrtrunc += M; /* temporarily use Mrtrunc */ for (d = 0; d < 3; d++) { hd[i].rcentrenew[d] += M*correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox); hd[i].vcentrenew[d] += M*pp[j].v[d]; } } j = NextIndex[j]; } /* while j >= 0 */ } /* if intersect */ } /* if recentre */ else if (gi.ILoopRead >= gi.NLoopRecentre) { /* ** Process data */ size = hd[i].rmax[0]; if (gi.ProfilingMode == 0 && gi.BinningCoordinateType == 1) size = sqrt(pow(hd[i].rmax[0],2)+pow(hd[i].zHeight,2)); /* if (gi.ProfilingMode == 3) size = gi.fincludeshaperadius*hd[i].rmax[0]; */ if (intersect(gi.us.LBox,gi.NCellData,hd[i],index,shift,size)) { j = HeadIndex[index[0]][index[1]][index[2]]; while (j >= 0) { for (d = 0; d < 3; d++) { r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi.us.LBox); r[d] = r[d]-hd[i].rcentre[d]; } dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); if (dsph <= size) { /* ** Now check if it is outside an excluded subhalo */ ParticleAccepted = 1; if (gi.ExcludeParticles == 1) { for (l = 0; l < hd[i].NHaloExclude; l++) { for (d = 0; d < 3; d++) { rell[d] = correct_position(hd[i].hde[l].rcentre[d],pp[j].r[d],gi.us.LBox); rell[d] = rell[d]-hd[i].hde[l].rcentre[d]; } dell = sqrt(rell[0]*rell[0]+rell[1]*rell[1]+rell[2]*rell[2]); if (dell <= hd[i].hde[l].size) { ParticleAccepted = 0; break; } } } /* ** Check if it is outside the cylindrical disc */ if (gi.ProfilingMode == 0 && gi.BinningCoordinateType == 1) { calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC); dell = fabs(r[0]*eC[0] + r[1]*eC[1] + r[2]*eC[2]); if (dell > hd[i].zHeight) ParticleAccepted = 0; } if (ParticleAccepted) { for (d = 0; d < 3; d++) { v[d] = pp[j].v[d]-hd[i].vcentre[d]; } if (gi.ProfilingMode == 0) { /* ** Normal binning mode */ for (d = 0; d < 3; d++) { dist[d] = -1; } if (gi.BinningCoordinateType == 0) { /* spherical */ dist[0] = dsph; } else if (gi.BinningCoordinateType == 1) { /* cylindrical */ calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC); dist[0] = r[0]*eA[0] + r[1]*eA[1] + r[2]*eA[2]; dist[1] = r[0]*eC[0] + r[1]*eC[1] + r[2]*eC[2]; assert(!(dist[0] < 0)); } else { for (d = 0; d < 3; d++) { dist[d] = -1; } } LoopBroken = 0; /* ** Go through radial bins from outside inwards => larger bin volume further out */ for (n[0] = hd[i].NBin[0]-1; n[0] >= 0 && !LoopBroken; n[0]--) { for (n[1] = 0; n[1] < hd[i].NBin[1] && !LoopBroken; n[1]++) { for (n[2] = 0; n[2] < hd[i].NBin[2] && !LoopBroken; n[2]++) { pbs = &hd[i].pbs[n[0]][n[1]][n[2]]; InThisBin = 1; for (d = 0; d < gi.NDimProfile; d++) { if (!(pbs->ri[d] <= dist[d] && pbs->ro[d] > dist[d])) InThisBin = 0; } if (InThisBin) { /* ** Calculate velocity */ if (gi.VelocityProjectionType == 1) { calculate_unit_vectors_spherical(r,eA,eB,eC); vproj[0] = v[0]*eA[0] + v[1]*eA[1] + v[2]*eA[2]; vproj[1] = v[0]*eB[0] + v[1]*eB[1] + v[2]*eB[2]; vproj[2] = v[0]*eC[0] + v[1]*eC[1] + v[2]*eC[2]; } else if (gi.VelocityProjectionType == 2) { calculate_unit_vectors_cylindrical(r,hd[i].zAxis,eA,eB,eC); vproj[0] = v[0]*eA[0] + v[1]*eA[1] + v[2]*eA[2]; vproj[1] = v[0]*eB[0] + v[1]*eB[1] + v[2]*eB[2]; vproj[2] = v[0]*eC[0] + v[1]*eC[1] + v[2]*eC[2]; } else { vproj[0] = v[0]; vproj[1] = v[1]; vproj[2] = v[2]; } /* ** Current matter type with sub species */ for (l = 0; l < gi.NSubSpecies[MatterType]; l++) { bin = NULL; if (MatterType == GAS) { if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[GAS]; else if (l == gi.pi[MatterType][MASS_METAL_SNII]) bin = &pbs->bin[GAS_METAL_SNII]; else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) bin = &pbs->bin[GAS_METAL_SNIa]; else if (l == gi.pi[MatterType][MASS_HI]) bin = &pbs->bin[GAS_HI]; else if (l == gi.pi[MatterType][MASS_HII]) bin = &pbs->bin[GAS_HII]; else if (l == gi.pi[MatterType][MASS_HeI]) bin = &pbs->bin[GAS_HeI]; else if (l == gi.pi[MatterType][MASS_HeII]) bin = &pbs->bin[GAS_HeII]; else if (l == gi.pi[MatterType][MASS_HeIII]) bin = &pbs->bin[GAS_HeIII]; else if (l == gi.pi[MatterType][MASS_H2]) bin = &pbs->bin[GAS_H2]; } else if (MatterType == DARK) { if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[DARK]; } else if (MatterType == STAR) { if (l == gi.pi[MatterType][MASS_TOT]) bin = &pbs->bin[STAR]; else if (l == gi.pi[MatterType][MASS_METAL_SNII]) bin = &pbs->bin[STAR_METAL_SNII]; else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) bin = &pbs->bin[STAR_METAL_SNIa]; } assert(bin != NULL); M = pp[j].P[l]; bin->N += 1; bin->M += M; for (d = 0; d < 3; d++) { bin->v[d] += M*vproj[d]; bin->vdt[d] += M*vproj[d]*vproj[d]; } bin->vdt[3] += M*vproj[0]*vproj[1]; bin->vdt[4] += M*vproj[0]*vproj[2]; bin->vdt[5] += M*vproj[1]*vproj[2]; bin->L[0] += M*(r[1]*v[2]-r[2]*v[1]); bin->L[1] += M*(r[2]*v[0]-r[0]*v[2]); bin->L[2] += M*(r[0]*v[1]-r[1]*v[0]); } /* ** Additional properties */ bin = &pbs->bin[MatterType]; assert(bin != NULL); M = pp[j].P[gi.pi[MatterType][MASS_TOT]]; for (l = 0; l < gi.NProperties[MatterType]; l++) { bin->P[l] += M*pp[j].P[l+gi.NSubSpecies[MatterType]]; } LoopBroken = 1; break; } /* if InThisBin */ } /* for n[2] */ } /* for n[1] */ } /* for n[0] */ } /* if ProfilingMode */ else if (gi.ProfilingMode == 1) { /* ** For the shape determination particles can be in more than one bin! => No break! ** Only radial bins are used. */ for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { n[1] = 0; n[2] = 0; pbs = &hd[i].pbs[n[0]][n[1]][n[2]]; /* ** Current matter type with sub species */ for (l = 0; l < gi.NSubSpecies[MatterType]; l++) { shape = NULL; if (MatterType == GAS) { if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[GAS]; else if (l == gi.pi[MatterType][MASS_METAL_SNII]) shape = &pbs->shape[GAS_METAL_SNII]; else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) shape = &pbs->shape[GAS_METAL_SNIa]; else if (l == gi.pi[MatterType][MASS_HI]) shape = &pbs->shape[GAS_HI]; else if (l == gi.pi[MatterType][MASS_HII]) shape = &pbs->shape[GAS_HII]; else if (l == gi.pi[MatterType][MASS_HeI]) shape = &pbs->shape[GAS_HeI]; else if (l == gi.pi[MatterType][MASS_HeII]) shape = &pbs->shape[GAS_HeII]; else if (l == gi.pi[MatterType][MASS_HeIII]) shape = &pbs->shape[GAS_HeIII]; else if (l == gi.pi[MatterType][MASS_H2]) shape = &pbs->shape[GAS_H2]; } else if (MatterType == DARK) { if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[DARK]; } else if (MatterType == STAR) { if (l == gi.pi[MatterType][MASS_TOT]) shape = &pbs->shape[STAR]; else if (l == gi.pi[MatterType][MASS_METAL_SNII]) shape = &pbs->shape[STAR_METAL_SNII]; else if (l == gi.pi[MatterType][MASS_METAL_SNIa]) shape = &pbs->shape[STAR_METAL_SNIa]; } assert(shape != NULL); calculate_coordinates_principal_axes(shape,r,rell,&dell); InThisBin = 0; if (gi.ShapeDeterminationVolume == 0) { if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1; } else if (gi.ShapeDeterminationVolume == 1) { if (pbs->ro[0] > dell) InThisBin = 1; } if (InThisBin) add_particle_to_shape_tensor(gi,shape,pp[j].P[l],r,dsph,dell); } /* ** Total matter */ if (MatterType == GAS || MatterType == DARK || MatterType == STAR) { calculate_coordinates_principal_axes(&pbs->shape[TOT],r,rell,&dell); InThisBin = 0; if (gi.ShapeDeterminationVolume == 0) { if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1; } else if (gi.ShapeDeterminationVolume == 1) { if (pbs->ro[0] > dell) InThisBin = 1; } if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[TOT],pp[j].P[gi.pi[MatterType][MASS_TOT]],r,dsph,dell); } /* ** Baryonic matter */ if (MatterType == GAS || MatterType == STAR) { calculate_coordinates_principal_axes(&pbs->shape[BARYON],r,rell,&dell); InThisBin = 0; if (gi.ShapeDeterminationVolume == 0) { if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1; } else if (gi.ShapeDeterminationVolume == 1) { if (pbs->ro[0] > dell) InThisBin = 1; } if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON],pp[j].P[gi.pi[MatterType][MASS_TOT]],r,dsph,dell); if (gi.DoMetalSpecies) { calculate_coordinates_principal_axes(&pbs->shape[BARYON_METAL_SNII],r,rell,&dell); InThisBin = 0; if (gi.ShapeDeterminationVolume == 0) { if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1; } else if (gi.ShapeDeterminationVolume == 1) { if (pbs->ro[0] > dell) InThisBin = 1; } if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON_METAL_SNII],pp[j].P[gi.pi[MatterType][MASS_METAL_SNII]],r,dsph,dell); calculate_coordinates_principal_axes(&pbs->shape[BARYON_METAL_SNIa],r,rell,&dell); InThisBin = 0; if (gi.ShapeDeterminationVolume == 0) { if (pbs->ri[0] <= dell && pbs->ro[0] > dell) InThisBin = 1; } else if (gi.ShapeDeterminationVolume == 1) { if (pbs->ro[0] > dell) InThisBin = 1; } if (InThisBin) add_particle_to_shape_tensor(gi,&pbs->shape[BARYON_METAL_SNIa],pp[j].P[gi.pi[MatterType][MASS_METAL_SNIa]],r,dsph,dell); } } } /* for n[0] */ } /* else if ProfilingMode */ /* else if (gi.ProfilingMode == 3 && gi.ILoopRead == 0) { */ /* for (l = 0; l < hd[i].NBin+1; l++) { */ /* if (hd[i].pbs[l].ri <= d && hd[i].pbs[l].ro > d) { */ /* /\* */ /* ** Total mass */ /* *\/ */ /* hd[i].pbs[l].totshape->N++; */ /* hd[i].pbs[l].totshape->propertymean += pgp[i].propertytot; */ /* /\* */ /* ** Gas */ /* *\/ */ /* hd[i].pbs[l].gasshape->N++; */ /* hd[i].pbs[l].gasshape->propertymean += pgp[i].property; */ /* } */ /* } */ /* } /\* else if ProfilingMode *\/ */ /* else if (gi.ProfilingMode == 3 && gi.ILoopRead > 0) { */ /* for (l = 0; l < hd[i].NBin+1; l++) { */ /* /\* */ /* ** Total mass */ /* *\/ */ /* calculate_coordinates_principal_axes(hd[i].pbs[l].totshape,r,rell,&dell); */ /* if (hd[i].pbs[l].totshape->propertymin <= pgp[i].propertytot && */ /* pgp[i].propertytot <= hd[i].pbs[l].totshape->propertymax && */ /* gi.fincludeshaperadius*hd[i].pbs[l].ro > d) */ /* add_particle_to_shape_tensor(gi,hd[i].pbs[l].totshape,pgp[i].M,r,d,dell); */ /* /\* */ /* ** Gas */ /* *\/ */ /* calculate_coordinates_principal_axes(hd[i].pbs[l].gasshape,r,rell,&dell); */ /* if (hd[i].pbs[l].gasshape->propertymin <= pgp[i].property && */ /* pgp[i].property <= hd[i].pbs[l].gasshape->propertymax && */ /* gi.fincludeshaperadius*hd[i].pbs[l].ro > d) */ /* add_particle_to_shape_tensor(gi,hd[i].pbs[l].gasshape,pgp[i].M,r,d,dell); */ /* } */ /* } /\* else if ProfilingMode *\/ */ } /* if ParticleAccepted */ } /* if dsph <= size */ j = NextIndex[j]; } /* while j >= 0 */ } /* if intersect */ } /* if process data */ } /* for gi.NHalo */ } /* for index[2] */ } /* for index[1] */ } /* for index[0] */ for (i = 0; i < gi.NCellData; i ++) { for (j = 0; j < gi.NCellData; j++) { free(HeadIndex[i][j]); } free(HeadIndex[i]); } free(HeadIndex); free(NextIndex); } void put_particles_in_storage(GI *gi, HALO_DATA *hd, HALO_DATA_EXCLUDE *hdeg, const int MatterType, PROFILE_PARTICLE *pp, PROFILE_PARTICLE **pp_storage_in) { int d, i, j, k, l; int index[3]; int NParticle = 0; int ParticleAccepted; int ***HeadIndex, *NextIndex, *AlreadyStored; double r[3], rexclude[3], dsph, dexclude, size, shift[3]; PROFILE_PARTICLE *pp_storage; NParticle = gi->NParticleInBlock[MatterType]; pp_storage = *pp_storage_in; /* ** Initialise linked list stuff */ HeadIndex = malloc(gi->NCellData*sizeof(int **)); assert(HeadIndex != NULL); for (i = 0; i < gi->NCellData; i ++) { HeadIndex[i] = malloc(gi->NCellData*sizeof(int *)); assert(HeadIndex[i] != NULL); for (j = 0; j < gi->NCellData; j++) { HeadIndex[i][j] = malloc(gi->NCellData*sizeof(int)); assert(HeadIndex[i][j] != NULL); } } NextIndex = malloc(NParticle*sizeof(int)); assert(NextIndex != NULL); for (i = 0; i < gi->NCellData; i++) { for (j = 0; j < gi->NCellData; j++) { for (k = 0; k < gi->NCellData; k++) { HeadIndex[i][j][k] = -1; } } } for (i = 0; i < NParticle; i++) NextIndex[i] = -1; for (i = 0; i < 3; i++) shift[i] = 0-gi->bc[i]; /* ** Array for quick and dirty way to keep track which particle is already stored */ AlreadyStored = malloc(NParticle*sizeof(int)); assert(AlreadyStored != NULL); for (i = 0; i < NParticle; i++) AlreadyStored[i] = 0; /* ** Generate linked list */ for (i = 0; i < NParticle; i++) { for (j = 0; j < 3; j++) { index[j] = (int)(gi->NCellData*(pp[i].r[j]+shift[j])/gi->us.LBox); if (index[j] == gi->NCellData) index[j] = gi->NCellData-1; /* Case where particles are exactly on the boundary */ assert(index[j] >= 0 && index[j] < gi->NCellData); } NextIndex[i] = HeadIndex[index[0]][index[1]][index[2]]; HeadIndex[index[0]][index[1]][index[2]] = i; } /* ** Go through linked list */ for (index[0] = 0; index[0] < gi->NCellData; index[0]++) { for (index[1] = 0; index[1] < gi->NCellData; index[1]++) { for (index[2] = 0; index[2] < gi->NCellData; index[2]++) { for (i = 0; i < gi->NHalo; i++) { /* ** Process data */ size = hd[i].rmax[0]; if (gi->ProfilingMode == 0 && gi->BinningCoordinateType == 1) size = sqrt(pow(hd[i].rmax[0],2)+pow(hd[i].zHeight,2)); if (intersect(gi->us.LBox,gi->NCellData,hd[i],index,shift,size)) { j = HeadIndex[index[0]][index[1]][index[2]]; while (j >= 0) { for (d = 0; d < 3; d++) { r[d] = correct_position(hd[i].rcentre[d],pp[j].r[d],gi->us.LBox); r[d] = r[d]-hd[i].rcentre[d]; } dsph = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); if (dsph <= size && AlreadyStored[j] == 0) { /* ** Now check if it is outside a globally excluded subhalo */ ParticleAccepted = 1; if (gi->ExcludeParticles) { for (l = 0; l < gi->NHaloExcludeGlobal; l++) { for (d = 0; d < 3; d++) { rexclude[d] = correct_position(hdeg[l].rcentre[d],pp[j].r[d],gi->us.LBox); rexclude[d] = rexclude[d]-hdeg[l].rcentre[d]; } dexclude = sqrt(rexclude[0]*rexclude[0]+rexclude[1]*rexclude[1]+rexclude[2]*rexclude[2]); if (dexclude <= hdeg[l].size) { ParticleAccepted = 0; break; } } } if (ParticleAccepted) { /* ** Add particle to storage */ gi->NParticleInStorage[MatterType]++; if (gi->SizeStorage[MatterType] < gi->NParticleInStorage[MatterType]) { gi->SizeStorage[MatterType] += gi->SizeStorageIncrement; pp_storage = realloc(pp_storage,gi->SizeStorage[MatterType]*sizeof(PROFILE_PARTICLE)); assert(pp_storage != NULL); for (l = gi->SizeStorage[MatterType]-gi->SizeStorageIncrement; l < gi->SizeStorage[MatterType]; l++) { pp_storage[l].P = malloc((gi->NSubSpecies[MatterType]+gi->NProperties[MatterType])*sizeof(double)); assert(pp_storage[l].P != NULL); } } copy_pp(gi,MatterType,&pp[j],&pp_storage[gi->NParticleInStorage[MatterType]-1]); AlreadyStored[j] = 1; } } j = NextIndex[j]; } } } } } } for (i = 0; i < gi->NCellData; i ++) { for (j = 0; j < gi->NCellData; j++) { free(HeadIndex[i][j]); } free(HeadIndex[i]); } free(HeadIndex); free(NextIndex); free(AlreadyStored); *pp_storage_in = pp_storage; } int intersect(double LBox, int NCell, HALO_DATA hd, int index[3], double shift[3], double size) { int d; double celllength, distance, dcheck; double rhalo[3], rcell[3], dsph[3]; celllength = LBox/NCell; for (d = 0; d < 3; d++) { rhalo[d] = hd.rcentre[d]; rcell[d] = index[d]*celllength - shift[d]; /* lower edge */ dsph[d] = rhalo[d] - rcell[d]; /* ** Check if the upper edge is closer */ if (dsph[d] > 0) { dsph[d] -= celllength; if (dsph[d] < 0) { dsph[d] = 0; /* contained */ } } /* ** Check if a periodic copy of the cell is closer */ dcheck = LBox - celllength - fabs(dsph[d]); if (dcheck < fabs(dsph[d])) { dsph[d] = dcheck; } } distance = sqrt(dsph[0]*dsph[0]+dsph[1]*dsph[1]+dsph[2]*dsph[2]); if (distance <= size) return 1; else return 0; } void copy_pp(GI *gi, const int MatterType, const PROFILE_PARTICLE *from_pp, PROFILE_PARTICLE *to_pp) { int d; for (d = 0; d < 3; d++) { to_pp->r[d] = from_pp->r[d]; to_pp->v[d] = from_pp->v[d]; } for (d = 0; d < gi->NSubSpecies[MatterType]+gi->NProperties[MatterType]; d++) { to_pp->P[d] = from_pp->P[d]; } } void calculate_coordinates_principal_axes(PROFILE_SHAPE_PROPERTIES *shape, double r[3], double rell[3], double *dell) { rell[0] = 0; rell[0] += r[0]*shape->a[0]; rell[0] += r[1]*shape->a[1]; rell[0] += r[2]*shape->a[2]; rell[1] = 0; rell[1] += r[0]*shape->b[0]; rell[1] += r[1]*shape->b[1]; rell[1] += r[2]*shape->b[2]; rell[2] = 0; rell[2] += r[0]*shape->c[0]; rell[2] += r[1]*shape->c[1]; rell[2] += r[2]*shape->c[2]; *dell = 0; *dell += rell[0]*rell[0]; *dell += rell[1]*rell[1]/pow(shape->b_a,2); *dell += rell[2]*rell[2]/pow(shape->c_a,2); *dell = sqrt(*dell); } void calculate_recentred_halo_coordinates(GI gi, HALO_DATA *hd) { int d, i; #pragma omp parallel for default(none) private(d,i) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { if (hd[i].Mrtrunc > 0) { for (d = 0; d < 3; d++) { hd[i].rcentre[d] = hd[i].rcentrenew[d]/hd[i].Mrtrunc; hd[i].vcentre[d] = hd[i].vcentrenew[d]/hd[i].Mrtrunc; hd[i].rcentrenew[d] = 0; hd[i].vcentrenew[d] = 0; } } hd[i].Mrtrunc = 0; } } void calculate_total_matter_distribution(GI gi, HALO_DATA *hd) { int d, n[3], i, j; PROFILE_BIN_STRUCTURE *pbs; #pragma omp parallel for default(none) private(d,n,i,j,pbs) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) { for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) { pbs = &hd[i].pbs[n[0]][n[1]][n[2]]; for (j = 0; j < gi.NSpeciesRead; j++) { if (gi.SpeciesContained[j]) { pbs->bin[TOT].N += pbs->bin[j].N; pbs->bin[TOT].M += pbs->bin[j].M; for (d = 0; d < 3; d++) { pbs->bin[TOT].v[d] += pbs->bin[j].v[d]; pbs->bin[TOT].L[d] += pbs->bin[j].L[d]; } for (d = 0; d < 6; d++) { pbs->bin[TOT].vdt[d] += pbs->bin[j].vdt[d]; } } /* if SpeciesContained */ } /* for NSpeciesRead */ } /* for n[2] */ } /* for n[1] */ } /* for n[0] */ } /* for NHalo */ } void calculate_baryonic_matter_distribution(GI gi, HALO_DATA *hd) { int d, n[3], i, j; PROFILE_BIN_STRUCTURE *pbs; #pragma omp parallel for default(none) private(d,n,i,j,pbs) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { for (n[1] = 0; n[1] < hd[i].NBin[1]; n[1]++) { for (n[2] = 0; n[2] < hd[i].NBin[2]; n[2]++) { pbs = &hd[i].pbs[n[0]][n[1]][n[2]]; for (j = 0; j < gi.NSpeciesRead; j++) { if (j == DARK) continue; if (gi.SpeciesContained[j]) { pbs->bin[BARYON].N += pbs->bin[j].N; pbs->bin[BARYON].M += pbs->bin[j].M; for (d = 0; d < 3; d++) { pbs->bin[BARYON].v[d] += pbs->bin[j].v[d]; pbs->bin[BARYON].L[d] += pbs->bin[j].L[d]; } for (d = 0; d < 6; d++) { pbs->bin[BARYON].vdt[d] += pbs->bin[j].vdt[d]; } } /* if SpeciesContained */ } /* for NSpeciesRead */ if (gi.DoMetalSpecies) { for (j = GAS_METAL_SNII; j <= STAR_METAL_SNII; j++) { if (gi.SpeciesContained[j]) { pbs->bin[BARYON_METAL_SNII].N += pbs->bin[j].N; pbs->bin[BARYON_METAL_SNII].M += pbs->bin[j].M; for (d = 0; d < 3; d++) { pbs->bin[BARYON_METAL_SNII].v[d] += pbs->bin[j].v[d]; pbs->bin[BARYON_METAL_SNII].L[d] += pbs->bin[j].L[d]; } for (d = 0; d < 6; d++) { pbs->bin[BARYON_METAL_SNII].vdt[d] += pbs->bin[j].vdt[d]; } } /* if SpeciesContained */ } /* for METAL_SNII */ for (j = GAS_METAL_SNIa; j <= STAR_METAL_SNIa; j++) { if (gi.SpeciesContained[j]) { pbs->bin[BARYON_METAL_SNIa].N += pbs->bin[j].N; pbs->bin[BARYON_METAL_SNIa].M += pbs->bin[j].M; for (d = 0; d < 3; d++) { pbs->bin[BARYON_METAL_SNIa].v[d] += pbs->bin[j].v[d]; pbs->bin[BARYON_METAL_SNIa].L[d] += pbs->bin[j].L[d]; } for (d = 0; d < 6; d++) { pbs->bin[BARYON_METAL_SNIa].vdt[d] += pbs->bin[j].vdt[d]; } } /* if SpeciesContained */ } /* for METAL_SNIa */ } /* if DoMetalSpecies */ } /* for n[2] */ } /* for n[1] */ } /* for n[0] */ } /* for NHalo */ } int diagonalise_matrix(double min[3][3], double *evala, double eveca[3], double *evalb, double evecb[3], double *evalc, double evecc[3]) { int i, j, N; int status1, status2; double x, y, z; double data[9]; gsl_matrix_view m; gsl_vector *eval; gsl_matrix *evec; gsl_eigen_symmv_workspace *w; N = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { data[N] = min[i][j]; N++; } } m = gsl_matrix_view_array(data,3,3); eval = gsl_vector_alloc(3); evec = gsl_matrix_alloc(3,3); w = gsl_eigen_symmv_alloc(3); status1 = gsl_eigen_symmv(&m.matrix,eval,evec,w); status2 = gsl_eigen_symmv_sort(eval,evec,GSL_EIGEN_SORT_ABS_DESC); if (status1) fprintf(stderr,"GSL error: %s\n",gsl_strerror(status1)); if (status2) fprintf(stderr,"GSL error: %s\n",gsl_strerror(status2)); *evala = gsl_vector_get(eval,0); eveca[0] = gsl_matrix_get(evec,0,0); eveca[1] = gsl_matrix_get(evec,1,0); eveca[2] = gsl_matrix_get(evec,2,0); *evalb = gsl_vector_get(eval,1); evecb[0] = gsl_matrix_get(evec,0,1); evecb[1] = gsl_matrix_get(evec,1,1); evecb[2] = gsl_matrix_get(evec,2,1); *evalc = gsl_vector_get(eval,2); evecc[0] = gsl_matrix_get(evec,0,2); evecc[1] = gsl_matrix_get(evec,1,2); evecc[2] = gsl_matrix_get(evec,2,2); gsl_vector_free(eval); gsl_matrix_free(evec); gsl_eigen_symmv_free(w); /* ** Check for right-handedness and orientation */ if (eveca[0] < 0) { eveca[0] *= -1; eveca[1] *= -1; eveca[2] *= -1; } if (evecb[1] < 0) { evecb[0] *= -1; evecb[1] *= -1; evecb[2] *= -1; } x = eveca[1]*evecb[2] - eveca[2]*evecb[1]; y = eveca[2]*evecb[0] - eveca[0]*evecb[2]; z = eveca[0]*evecb[1] - eveca[1]*evecb[0]; if (x*evecc[0] + y*evecc[1] + z*evecc[2] < 0) { evecc[0] *= -1; evecc[1] *= -1; evecc[2] *= -1; } return status1+status2; } double diagonalise_shape_tensors(GI gi, HALO_DATA *hd, int ILoop) { int d, n[3], i, j; int status; int Ntot, Nconverged; double m[3][3]; double evala, evalb, evalc; double eveca[3], evecb[3], evecc[3]; const double ex[3] = {1,0,0}; const double ey[3] = {0,1,0}; const double ez[3] = {0,0,1}; double sp, ec[3]; double re_b_a, re_c_a; PROFILE_SHAPE_PROPERTIES *shape; Ntot = 0; Nconverged = 0; for (i = 0; i < gi.NHalo; i++) { /* ** Go from outside inwards for the alignment */ for (n[0] = hd[i].NBin[0]-1; n[0] >= 0; n[0]--) { n[1] = 0; n[2] = 0; for (j = 0; j < gi.NSpeciesProfile; j++) { if (gi.SpeciesContained[j]) { shape = &hd[i].pbs[n[0]][n[1]][n[2]].shape[j]; if (shape->NLoopConverged == 0) { Ntot++; shape->b_a_old = shape->b_a; shape->c_a_old = shape->c_a; /* ** Calculate shape */ if (shape->N > 2) { /* ** Only calculate a shape if there are at least 3 particles */ assert(shape->M > 0); m[0][0] = shape->st[0]/shape->M; m[1][1] = shape->st[1]/shape->M; m[2][2] = shape->st[2]/shape->M; m[0][1] = shape->st[3]/shape->M; m[0][2] = shape->st[4]/shape->M; m[1][2] = shape->st[5]/shape->M; m[1][0] = m[0][1]; m[2][0] = m[0][2]; m[2][1] = m[1][2]; status = diagonalise_matrix(m,&evala,eveca,&evalb,evecb,&evalc,evecc); if (status) fprintf(stderr,"This was halo ID %d Bin %d\n",hd[i].ID,n[0]); shape->b_a = sqrt(evalb/evala); shape->c_a = sqrt(evalc/evala); for (d = 0; d < 3; d++) { shape->a[d] = eveca[d]; shape->b[d] = evecb[d]; shape->c[d] = evecc[d]; } } else { if (n[0] == hd[i].NBin[0]-1) { /* ** Set values for sphere */ shape->b_a = 1; shape->c_a = 1; for (d = 0; d < 3; d++) { shape->a[d] = ex[d]; shape->b[d] = ey[d]; shape->c[d] = ez[d]; } } else { /* ** Copy values from outer bin */ shape->b_a = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b_a; shape->c_a = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].c_a; for (d = 0; d < 3; d++) { shape->a[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].a[d]; shape->b[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b[d]; shape->c[d] = hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].c[d]; } } } /* ** Align orientation */ if (n[0] < hd[i].NBin[0]-1) { sp = 0; for (d = 0; d < 3; d++) sp += shape->a[d]*hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].a[d]; if (sp < 0) { for (d = 0; d < 3; d++) shape->a[d] *= -1; } sp = 0; for (d = 0; d < 3; d++) sp += shape->b[d]*hd[i].pbs[n[0]+1][n[1]][n[2]].shape[j].b[d]; if (sp < 0) { for (d = 0; d < 3; d++) shape->b[d] *= -1; } ec[0] = shape->a[1]*shape->b[2] - shape->a[2]*shape->b[1]; ec[1] = shape->a[2]*shape->b[0] - shape->a[0]*shape->b[2]; ec[2] = shape->a[0]*shape->b[1] - shape->a[1]*shape->b[0]; sp = 0; for (d = 0; d < 3; d++) sp += ec[d]*shape->c[d]; if (sp < 0) { for (d = 0; d < 3; d++) shape->c[d] *= -1; } } /* ** Check if already converged */ re_b_a = (shape->b_a-shape->b_a_old)/shape->b_a_old; re_c_a = (shape->c_a-shape->c_a_old)/shape->c_a_old; if (fabs(re_b_a) <= gi.ShapeIterationTolerance && fabs(re_c_a) <= gi.ShapeIterationTolerance && shape->N > 2) { Nconverged++; shape->NLoopConverged = ILoop; } } else { Ntot++; Nconverged++; } } /* if SpeciesContained */ } /* for NSpeciesProfile */ } /* for NBin[0] */ } /* for NHalo */ return (double)Nconverged/(double)Ntot; } void calculate_halo_properties(GI gi, HALO_DATA *hd) { int i; #pragma omp parallel for default(none) private(i) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { /* ** Calculate derived properties */ calculate_derived_properties(gi,&hd[i]); /* ** Calculate overdensity characteristics */ calculate_overdensity_characteristics(gi,&hd[i]); /* ** Calculate truncation of halo */ calculate_truncation_characteristics(gi,&hd[i]); /* ** Remove background ** Attention: Numbers and velocities not correct any more! */ remove_background(gi,&hd[i]); /* ** Calculate size & mass */ calculate_halo_size(gi,&hd[i]); /* ** Calculate velocity characteristics */ calculate_velocity_characteristics(gi,&hd[i]); } } void calculate_derived_properties(GI gi, HALO_DATA *hd) { int d, n[3], j; PROFILE_BIN_PROPERTIES *bin; for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) { for (n[1] = 0; n[1] < hd->NBin[1]; n[1]++) { for (n[2] = 0; n[2] < hd->NBin[2]; n[2]++) { for (j = 0; j < gi.NSpeciesProfile; j++) { if (gi.SpeciesContained[j]) { bin = &hd->pbs[n[0]][n[1]][n[2]].bin[j]; for (d = 0; d < 3; d++) { if (bin->M > 0) bin->v[d] /= bin->M; } for (d = 0; d < 6; d++) { if (bin->M > 0) bin->vdt[d] /= bin->M; } if (bin->N > 1) { for (d = 0; d < 3; d++) bin->vdt[d] -= pow(bin->v[d],2); bin->vdt[3] -= bin->v[0]*bin->v[1]; bin->vdt[4] -= bin->v[0]*bin->v[2]; bin->vdt[5] -= bin->v[1]*bin->v[2]; } else { for (d = 0; d < 6; d++) bin->vdt[d] = 0; } for (d = 0; d <= n[0]; d++) { bin->Menc[0] += hd->pbs[d][n[1]][n[2]].bin[j].M; } bin->Menc[1] = bin->Menc[0]; if (j < gi.NSpeciesRead) { for (d = 0; d < gi.NProperties[j]; d++) { if (bin->M > 0) bin->P[d] /= bin->M; } } } } } } } } void calculate_overdensity_characteristics(GI gi, HALO_DATA *hd) { int n[3], j; int Ncheck, Scheck; double rscale[3], Mrscale[3], rhoencscale[3]; double radius[2], rhoenc[2], Menc[2], Venc[2]; double minter, dinter, rcheck, Mrcheck; double rminok; for (j = 0; j < 3; j++) { rscale[j] = 0; Mrscale[j] = 0; } rhoencscale[0] = gi.rhoencmean; rhoencscale[1] = gi.rhoenccrit; rhoencscale[2] = gi.rhoencfix; rminok = gi.rExclude; /* ** Search from inside out! */ for (n[0] = 1; n[0] < hd->NBin[0]; n[0]++) { n[1] = 0; n[2] = 0; radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0]; radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0]; Venc[0] = 4*M_PI*pow(radius[0],3)/3.0; Venc[1] = 4*M_PI*pow(radius[1],3)/3.0; Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0]; Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0]; rhoenc[0] = Menc[0]/Venc[0]; rhoenc[1] = Menc[1]/Venc[1]; for (j = 0; j < 3; j++) { if (rhoenc[0] >= rhoencscale[j] && rhoenc[1] < rhoencscale[j] && rscale[j] == 0) { minter = (log(radius[1])-log(radius[0]))/(log(rhoenc[1])-log(rhoenc[0])); dinter = log(rhoencscale[j])-log(rhoenc[0]); rcheck = exp(log(radius[0])+minter*dinter); minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0])); dinter = log(rcheck)-log(radius[0]); Mrcheck = exp(log(Menc[0])+minter*dinter); if (rcheck >= rminok) { rscale[j] = rcheck; Mrscale[j] = Mrcheck; assert(rscale[j] > 0); assert(Mrscale[j] > 0); } } /* if */ } /* for j */ /* ** Check if all overdensity scales have been found already */ Ncheck = 0; Scheck = 0; for (j = 0; j < 3; j++) { Ncheck++; if (rscale[j] > 0) Scheck++; } if (Scheck == Ncheck) break; } /* for n[0] */ hd->rmean = rscale[0]; hd->rcrit = rscale[1]; hd->rfix = rscale[2]; hd->Mrmean = Mrscale[0]; hd->Mrcrit = Mrscale[1]; hd->Mrfix = Mrscale[2]; } /* ** Indicator: local minimum in enclosed density at scales larger than rminok ** i.e. bump is significant enough to cause a minimum or saddle in enclosed density ** => in practise use the location where the value of slopertruncindicator is reached */ void calculate_truncation_characteristics(GI gi, HALO_DATA *hd) { int n[3], j; int StartIndex; double radius[2], logslope[2], Menc[2]; double minter, dinter, rcheck, V; double rho[NSPECIESBACKGROUND], rhomin[NSPECIESBACKGROUND]; double slope; double rminok; slope = 3 + gi.slopertruncindicator; rminok = gi.rExclude; StartIndex = -1; /* ** Search from inside out! */ for (n[0] = 2; n[0] < hd->NBin[0]; n[0]++) { n[1] = 0; n[2] = 0; radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].rm[0]; radius[1] = hd->pbs[n[0]][n[1]][n[2]].rm[0]; if (hd->pbs[n[0]-2][n[1]][n[2]].bin[TOT].Menc[0] > 0) { logslope[0] = log(hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].bin[TOT].Menc[0]); logslope[1] = log(hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0]); } else { logslope[0] = 0; logslope[1] = 0; } logslope[0] /= log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].ro[0]); logslope[1] /= log(hd->pbs[n[0]][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0]); if (logslope[0] <= slope && logslope[1] > slope && hd->rtruncindicator == 0) { minter = (log(radius[1])-log(radius[0]))/(logslope[1]-logslope[0]); dinter = slope-logslope[0]; rcheck = exp(log(radius[0])+minter*dinter); if (rcheck >= rminok && hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].M > 0) { StartIndex = n[0]; hd->rtruncindicator = rcheck; assert(hd->rtruncindicator > 0); } } if (hd->rtruncindicator > 0) break; } /* ** Now determine rtrunc ** We define the location of the absolute minimum (within specified range of frhobg) ** of the local density within rtruncindicator as rtrunc */ if (StartIndex > 0) { for (j = 0; j < NSPECIESBACKGROUND; j++) rhomin[j] = 1e100; for (n[0] = StartIndex; n[0] > 0; n[0]--) { n[1] = 0; n[2] = 0; V = 4*M_PI*(pow(hd->pbs[n[0]][n[1]][n[2]].ro[0],3)-pow(hd->pbs[n[0]][n[1]][n[2]].ri[0],3))/3.0; for (j = 0; j < 5; j++) rho[j] = (gi.SpeciesContained[j])?hd->pbs[n[0]][n[1]][n[2]].bin[j].M/V:0; if (rho[TOT] < gi.frhobg*rhomin[TOT] && rho[TOT] > 0 && hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0] > 0 && hd->pbs[n[0]][n[1]][n[2]].rm[0] >= rminok) { for (j = 0; j < NSPECIESBACKGROUND; j++) { if (rho[j] < rhomin[j] && rho[j] > 0 && gi.SpeciesContained[j]) rhomin[j] = rho[j]; } hd->rtrunc = hd->pbs[n[0]][n[1]][n[2]].rm[0]; assert(hd->rtrunc > 0); radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0]; radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0]; Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[TOT].Menc[0]; Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[TOT].Menc[0]; minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0])); dinter = log(hd->rtrunc)-log(radius[0]); hd->Mrtrunc = exp(log(Menc[0])+minter*dinter); assert(hd->Mrtrunc > 0); for (j = 0; j < NSPECIESBACKGROUND; j++) { if (gi.SpeciesContained[j]) { if (rho[j] > 0 && rhomin[j] != 1e100) hd->rhobg[j] = 0.5*(rho[j]+rhomin[j]); else if (rho[j] == 0 && rhomin[j] != 1e100) hd->rhobg[j] = rhomin[j]; } } } } } } void remove_background(GI gi, HALO_DATA *hd) { int n[3], j; double Venc; if (hd->rtrunc > 0) { hd->Mrtrunc -= hd->rhobg[TOT]*4*M_PI*pow(hd->rtrunc,3)/3.0; if (hd->Mrtrunc > 0) { /* ** Calculate enclosed mass with background removed */ for (n[0] = 0; n[0] < hd->NBin[0]; n[0]++) { n[1] = 0; n[2] = 0; Venc = 4*M_PI*pow(hd->pbs[n[0]][n[1]][n[2]].ro[0],3)/3.0; for (j = 0; j < NSPECIESBACKGROUND; j++) { if(gi.SpeciesContained[j]) hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[1] -= hd->rhobg[j]*Venc; } } } else { /* ** Unphysical truncation scale found ** => probably noisy profile */ hd->rtrunc = 0; hd->Mrtrunc = 0; } } } void calculate_halo_size(GI gi, HALO_DATA *hd) { if (gi.HaloSize == 0) { hd->size = hd->rmean; hd->mass = hd->Mrmean; } else if (gi.HaloSize == 1) { hd->size = hd->rcrit; hd->mass = hd->Mrcrit; } else if (gi.HaloSize == 2) { hd->size = hd->rfix; hd->mass = hd->Mrfix; } if (hd->rtrunc > 0 && (hd->rtrunc < hd->size || hd->size == 0)) { hd->IsTruncated = 1; hd->size = hd->rtrunc; hd->mass = hd->Mrtrunc; } } void calculate_velocity_characteristics(GI gi, HALO_DATA *hd) { int n[3], j, k, l; int Ncheck, Scheck; double rscale[NSPECIESBACKGROUND][2], Mrscale[NSPECIESBACKGROUND][2]; double radius[2], logslope[2], Menc[2]; double minter, dinter, rcheck, Mrcheck, Qcheck, Qcomp; double slope; slope = 1; for (j = 0; j < NSPECIESBACKGROUND; j++) { for (l = 0; l < 2; l++) { rscale[j][l] = 0; Mrscale[j][l] = 0; } } n[1] = 0; n[2] = 0; for (n[0] = 2; n[0] < hd->NBin[0]; n[0]++) { for (j = 0; j < NSPECIESBACKGROUND; j++) { for (l = 0; l < 2; l++) { radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].rm[0]; radius[1] = hd->pbs[n[0]][n[1]][n[2]].rm[0]; if (hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l] > 0) { logslope[0] = (log(hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l])-log(hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l])); logslope[1] = (log(hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[l])-log(hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l])); } else { logslope[0] = 0; logslope[1] = 0; } logslope[0] /= log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-2][n[1]][n[2]].ro[0]); logslope[1] /= log(hd->pbs[n[0]][n[1]][n[2]].ro[0])-log(hd->pbs[n[0]-1][n[1]][n[2]].ro[0]); if (logslope[0] >= slope && logslope[1] < slope) { minter = (log(radius[1])-log(radius[0]))/(logslope[1]-logslope[0]); dinter = slope-logslope[0]; rcheck = exp(log(radius[0])+minter*dinter); if (rcheck <= hd->pbs[n[0]-1][n[1]][n[2]].ro[0]) { radius[0] = hd->pbs[n[0]-2][n[1]][n[2]].ro[0]; radius[1] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0]; Menc[0] = hd->pbs[n[0]-2][n[1]][n[2]].bin[j].Menc[l]; Menc[1] = hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l]; } else { radius[0] = hd->pbs[n[0]-1][n[1]][n[2]].ro[0]; radius[1] = hd->pbs[n[0]][n[1]][n[2]].ro[0]; Menc[0] = hd->pbs[n[0]-1][n[1]][n[2]].bin[j].Menc[l]; Menc[1] = hd->pbs[n[0]][n[1]][n[2]].bin[j].Menc[l]; } minter = (log(Menc[1])-log(Menc[0]))/(log(radius[1])-log(radius[0])); dinter = log(rcheck)-log(radius[0]); Mrcheck = exp(log(Menc[0])+minter*dinter); /* ** Check criteria */ Qcheck = Mrcheck/rcheck; Ncheck = 0; Scheck = 0; for (k = n[0]; k < hd->NBin[0] && hd->pbs[k][n[1]][n[2]].ro[0] <= gi.fcheckrvcmax*rcheck; k++) { Ncheck++; Qcomp = hd->pbs[k][n[1]][n[2]].bin[j].Menc[l]; Qcomp /= hd->pbs[k][n[1]][n[2]].ro[0]; if (Qcheck >= Qcomp) Scheck++; } if (Scheck == Ncheck) { /* ** The circular velocity curve is generally nicely behaving ** => for the first local maximum there is no size restriction (sometimes halos have rvcmax around size) ** => if more than one local maximum => take the highest local maximum within the size of the halo ** => avoid peaks in the outer parts of the halo */ if (rscale[j][l] == 0) { rscale[j][l] = rcheck; Mrscale[j][l] = Mrcheck; } else if (Mrcheck/rcheck > Mrscale[j][l]/rscale[j][l] && rcheck <= hd->size) { rscale[j][l] = rcheck; Mrscale[j][l] = Mrcheck; } assert(rscale[j][l] > 0); assert(Mrscale[j][l] > 0); } } /* if logslope */ } /* for l */ } /* for j */ } /* for n[0] */ for (j = 0; j < NSPECIESBACKGROUND; j++) { for (l = 0; l < 2; l++) { hd->rvcmax[j][l] = rscale[j][l]; hd->Mrvcmax[j][l] = Mrscale[j][l]; } } } void determine_halo_hierarchy(GI gi, HALO_DATA *hd) { int i, j, k; int index[3]; int index0, index1, index2; int ***HeadIndex, *NextIndex; double r[3], shift[3]; double d, size, sizeother, *sizecomp; /* ** Initialise linked list stuff */ HeadIndex = malloc(gi.NCellHalo*sizeof(int **)); assert(HeadIndex != NULL); for (i = 0; i < gi.NCellHalo; i ++) { HeadIndex[i] = malloc(gi.NCellHalo*sizeof(int *)); assert(HeadIndex[i] != NULL); for (j = 0; j < gi.NCellHalo; j++) { HeadIndex[i][j] = malloc(gi.NCellHalo*sizeof(int)); assert(HeadIndex[i][j] != NULL); } } NextIndex = malloc(gi.NHalo*sizeof(int)); assert(NextIndex != NULL); for (i = 0; i < gi.NCellHalo; i++) { for (j = 0; j < gi.NCellHalo; j++) { for (k = 0; k < gi.NCellHalo; k++) { HeadIndex[i][j][k] = -1; } } } for (i = 0; i < gi.NHalo; i++) NextIndex[i] = -1; for (i = 0; i < 3; i++) shift[i] = 0-gi.bc[i]; /* ** Generate linked list */ for (i = 0; i < gi.NHalo; i++) { for (j = 0; j < 3; j++) { index[j] = (int)(gi.NCellHalo*(hd[i].rcentre[j]+shift[j])/gi.us.LBox); if (index[j] == gi.NCellHalo) index[j] = gi.NCellHalo-1; /* Case where haloes are exactly on the boundary */ assert(index[j] >= 0 && index[j] < gi.NCellHalo); } NextIndex[i] = HeadIndex[index[0]][index[1]][index[2]]; HeadIndex[index[0]][index[1]][index[2]] = i; } /* ** Find top level haloes */ sizecomp = malloc(gi.NHalo*sizeof(double)); assert(sizecomp != NULL); for (i = 0; i < gi.NHalo; i++) sizecomp[i] = 0; for (i = 0; i < gi.NHalo; i++) { size = hd[i].size; /* ** Go through linked list */ #pragma omp parallel for default(none) private(index,index0,index1,index2,j,k,r,d) shared(gi,hd,i,size,sizecomp,shift,HeadIndex,NextIndex) for (index0 = 0; index0 < gi.NCellHalo; index0++) { for (index1 = 0; index1 < gi.NCellHalo; index1++) { for (index2 = 0; index2 < gi.NCellHalo; index2++) { index[0] = index0; index[1] = index1; index[2] = index2; if (intersect(gi.us.LBox,gi.NCellHalo,hd[i],index,shift,size)) { j = HeadIndex[index[0]][index[1]][index[2]]; while (j >= 0) { if (j != i) { for (k = 0; k < 3; k++) { r[k] = correct_position(hd[i].rcentre[k],hd[j].rcentre[k],gi.us.LBox); r[k] = r[k] - hd[i].rcentre[k]; } d = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); if (d <= size) { /* ** contained => use largest sized halo */ if (size > sizecomp[j]) { sizecomp[j] = size; hd[j].HostHaloID = hd[i].ID; } } } j = NextIndex[j]; } } } } } } /* ** Find duplicates and mergers */ #pragma omp parallel for default(none) private(i,j,k,r,d,size,sizeother) shared(gi,hd) for (i = 0; i < gi.NHalo; i++) { for (j = i+1; j < gi.NHalo; j++) { if (hd[i].HostHaloID == hd[j].ID && hd[j].HostHaloID == hd[i].ID) { /* ** Found a pair */ for (k = 0; k < 3; k++) { r[k] = correct_position(hd[i].rcentre[k],hd[j].rcentre[k],gi.us.LBox); r[k] = r[k] - hd[i].rcentre[k]; } d = sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]); size = hd[i].size; sizeother = hd[j].size; /* ** Check if the pair is close enough */ if (d <= gi.fhaloduplicate*(0.5*(size+sizeother))) { /* ** Found a duplicate */ if (size >= sizeother) { hd[j].ExtraHaloID = hd[i].ID; hd[i].HostHaloID = -1; for (k = 0; k < gi.NHalo; k++) { if (hd[k].HostHaloID == hd[j].ID) hd[k].HostHaloID = hd[i].ID; } } else { hd[i].ExtraHaloID = hd[j].ID; hd[j].HostHaloID = -1; for (k = 0; k < gi.NHalo; k++) { if (hd[k].HostHaloID == hd[i].ID) hd[k].HostHaloID = hd[j].ID; } } } else { /* ** Probably a merger */ hd[i].HostHaloID = -1; hd[j].HostHaloID = -1; hd[i].ExtraHaloID = hd[j].ID; hd[j].ExtraHaloID = hd[i].ID; } } } } free(sizecomp); for (i = 0; i < gi.NCellHalo; i ++) { for (j = 0; j < gi.NCellHalo; j++) { free(HeadIndex[i][j]); } free(HeadIndex[i]); } free(HeadIndex); free(NextIndex); } void write_output_matter_profile(GI gi, HALO_DATA *hd) { int d, n[3], i, j, k, l; int NBinMax[3] = {0,0,0}; char outputfilename[256]; FILE *outputfile; PROFILE_BIN_PROPERTIES *bin; /* ** Characteristics */ if (gi.BinningCoordinateType == 0 && gi.NDimProfile == 1) sprintf(outputfilename,"%s.profile.sph.d1.characteristics",gi.OutputName); else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 1) sprintf(outputfilename,"%s.profile.cyl.d1.characteristics",gi.OutputName); else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 2) sprintf(outputfilename,"%s.profile.cyl.d2.characteristics",gi.OutputName); outputfile = fopen(outputfilename,"w"); assert(outputfile != NULL); fprintf(outputfile,"#ID/1 r_x/2 r_y/3 r_z/4 v_x/5 v_y/6 v_z/7"); k = 8; for (d = 0; d < gi.NDimProfile; d++) { fprintf(outputfile," rmin_%d/%d rmax_%d/%d NBin_%d/%d",d+1,k,d+1,k+1,d+1,k+2); k += 3; } if (gi.BinningCoordinateType == 0) { fprintf(outputfile," size/%d mass/%d",k,k+1); k += 2; fprintf(outputfile," rvcmax_tot/%d Mrvcmax_tot/%d",k,k+1); k += 2; fprintf(outputfile," rvcmax_dark/%d Mrvcmax_dark/%d",k,k+1); k += 2; fprintf(outputfile," IsTruncated/%d HostHaloID/%d ExtraHaloID/%d",k,k+1,k+2); k += 3; if (gi.MoreCharacteristicsOutput) { fprintf(outputfile," rmean/%d Mrmean/%d",k,k+1); k += 2; fprintf(outputfile," rcrit/%d Mrcrit/%d",k,k+1); k += 2; fprintf(outputfile," rfix/%d Mrfix/%d",k,k+1); k += 2; fprintf(outputfile," rtrunc/%d Mrtrunc/%d",k,k+1); k += 2; fprintf(outputfile," rvcmax_tot/%d Mrvcmax_tot/%d rvcmax_tottrunc/%d Mrvcmax_tottrunc/%d",k,k+1,k+2,k+3); k += 4; fprintf(outputfile," rvcmax_dark/%d Mrvcmax_dark/%d rvcmax_darktrunc/%d Mrvcmax_darktrunc/%d",k,k+1,k+2,k+3); k += 4; fprintf(outputfile," rhobg_tot/%d rhobg_gas/%d rhobg_dark/%d rhobg_star/%d rhobg_baryon/%d",k,k+1,k+2,k+3,k+4); k += 5; fprintf(outputfile," rtruncindicator/%d",k); } } else if (gi.BinningCoordinateType == 1) { fprintf(outputfile," zAxis_x/%d zAxis_y/%d zAxis_z/%d zHeight/%d",k,k+1,k+2,k+3); } fprintf(outputfile,"\n"); for (i = 0; i < gi.NHalo; i++) { fprintf(outputfile,"%d",hd[i].ID); fprintf(outputfile," %.6e %.6e %.6e",hd[i].rcentre[0],hd[i].rcentre[1],hd[i].rcentre[2]); fprintf(outputfile," %.6e %.6e %.6e",hd[i].vcentre[0],hd[i].vcentre[1],hd[i].vcentre[2]); for (d = 0; d < gi.NDimProfile; d++) fprintf(outputfile," %.6e %.6e %d",hd[i].rmin[d],hd[i].rmax[d],hd[i].NBin[d]); if (gi.BinningCoordinateType == 0) { fprintf(outputfile," %.6e %.6e",hd[i].size,hd[i].mass); l = hd[i].IsTruncated; fprintf(outputfile," %.6e %.6e",hd[i].rvcmax[TOT][l],hd[i].Mrvcmax[TOT][l]); fprintf(outputfile," %.6e %.6e",hd[i].rvcmax[DARK][l],hd[i].Mrvcmax[DARK][l]); fprintf(outputfile," %d %d %d",hd[i].IsTruncated,hd[i].HostHaloID,hd[i].ExtraHaloID); if (gi.MoreCharacteristicsOutput) { fprintf(outputfile," %.6e %.6e",hd[i].rmean,hd[i].Mrmean); fprintf(outputfile," %.6e %.6e",hd[i].rcrit,hd[i].Mrcrit); fprintf(outputfile," %.6e %.6e",hd[i].rfix,hd[i].Mrfix); fprintf(outputfile," %.6e %.6e",hd[i].rtrunc,hd[i].Mrtrunc); fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].rvcmax[TOT][0],hd[i].Mrvcmax[TOT][0],hd[i].rvcmax[TOT][1],hd[i].Mrvcmax[TOT][1]); fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].rvcmax[DARK][0],hd[i].Mrvcmax[DARK][0],hd[i].rvcmax[DARK][1],hd[i].Mrvcmax[DARK][1]); fprintf(outputfile," %.6e %.6e %.6e %.6e %.6e",hd[i].rhobg[TOT],hd[i].rhobg[GAS],hd[i].rhobg[DARK],hd[i].rhobg[STAR],hd[i].rhobg[BARYON]); fprintf(outputfile," %.6e",hd[i].rtruncindicator); } } else if (gi.BinningCoordinateType == 1) { fprintf(outputfile," %.6e %.6e %.6e %.6e",hd[i].zAxis[0],hd[i].zAxis[1],hd[i].zAxis[2],hd[i].zHeight); } fprintf(outputfile,"\n"); } fclose(outputfile); /* ** Matter profiles */ for (j = 0; j < gi.NSpeciesProfile; j++) { if (gi.SpeciesContained[j]) { n[2] = 0; for (i = 0; i < gi.NHalo; i++) NBinMax[1] = (hd[i].NBin[1]>NBinMax[1])?hd[i].NBin[1]:NBinMax[1]; for (n[1] = 0; n[1] < NBinMax[1]; n[1]++) { if (gi.BinningCoordinateType == 0 && gi.NDimProfile == 1) { assert(n[1] == 0); sprintf(outputfilename,"%s.profile.sph.d1.pro.%s",gi.OutputName,gi.MatterTypeName[j]); } else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 1) { assert(n[1] == 0); sprintf(outputfilename,"%s.profile.cyl.d1.pro.%s",gi.OutputName,gi.MatterTypeName[j]); } else if (gi.BinningCoordinateType == 1 && gi.NDimProfile == 2) { if (n[1] < NBinMax[1]/2) { d = n[1]+1; sprintf(outputfilename,"%s.profile.cyl.d2.p%03d.pro.%s",gi.OutputName,d,gi.MatterTypeName[j]); } else { d = n[1]+1-NBinMax[1]/2; sprintf(outputfilename,"%s.profile.cyl.d2.m%03d.pro.%s",gi.OutputName,d,gi.MatterTypeName[j]); } } else { sprintf(outputfilename,"garbage"); } outputfile = fopen(outputfilename,"w"); assert(outputfile != NULL); fprintf(outputfile,"#ID/1"); k = 2; for (d = 0; d < gi.NDimProfile; d++) { fprintf(outputfile," ri_%d/%d rm_%d/%d ro_%d/%d",d+1,k,d+1,k+1,d+1,k+2); k += 3; } fprintf(outputfile," M/%d N/%d",k,k+1); k += 2; fprintf(outputfile," v_1/%d v_2/%d v_3/%d",k,k+1,k+2); k += 3; fprintf(outputfile," vdt_11/%d vdt_22/%d vdt_33/%d vdt_12/%d vdt_13/%d vdt_23/%d",k,k+1,k+2,k+3,k+4,k+5); k += 6; fprintf(outputfile," L_x/%d L_y/%d L_z/%d",k,k+1,k+2); k +=3; if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," T[K]/%d",k); if (j == STAR && gi.DoStellarAge) fprintf(outputfile," Age/%d",k); fprintf(outputfile,"\n"); for (i = 0; i < gi.NHalo; i++) { for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { if (hd[i].NBin[1] <= n[1]) { /* ** Less bins in 2. dimension for this halo than maximum of all haloes ** => just output 0 ** Necessary to keep the file structure intact */ fprintf(outputfile,"%d",0); for (d = 0; d < gi.NDimProfile; d++) { fprintf(outputfile," %.6e %.6e %.6e",0.0,0.0,0.0); } fprintf(outputfile," %.6e %d",0.0,0); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",0.0); for (d = 0; d < 6; d++) fprintf(outputfile," %.6e",0.0); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",0.0); if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," %.6e",0.0); if (j == STAR && gi.DoStellarAge) fprintf(outputfile," %.6e",0.0); fprintf(outputfile,"\n"); } else { bin = &hd[i].pbs[n[0]][n[1]][n[2]].bin[j]; fprintf(outputfile,"%d",hd[i].ID); for (d = 0; d < gi.NDimProfile; d++) { fprintf(outputfile," %.6e %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].ri[d],hd[i].pbs[n[0]][n[1]][n[2]].rm[d],hd[i].pbs[n[0]][n[1]][n[2]].ro[d]); } fprintf(outputfile," %.6e %ld",bin->M,bin->N); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",bin->v[d]); for (d = 0; d < 6; d++) fprintf(outputfile," %.6e",bin->vdt[d]); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",bin->L[d]); if (j == GAS && gi.DoGasTemperature) fprintf(outputfile," %.6e",bin->P[gi.pi[GAS][TEMPERATURE]-gi.NSubSpecies[GAS]]); if (j == STAR && gi.DoStellarAge) fprintf(outputfile," %.6e",bin->P[gi.pi[STAR][AGE]-gi.NSubSpecies[STAR]]); fprintf(outputfile,"\n"); } } /* for n[0] */ } /* for NHalo */ fclose(outputfile); } /* for n[1] */ } /* if SpeciesContained */ } /* for NSpeciesProfile */ } void write_output_shape_profile(GI gi, HALO_DATA *hd, int ILoop) { int d, n[3], i, j; char outputfilename[256]; FILE *outputfile; /* ** Characteristics */ sprintf(outputfilename,"%s.shape.%03d.characteristics",gi.OutputName,ILoop); outputfile = fopen(outputfilename,"w"); assert(outputfile != NULL); fprintf(outputfile,"#ID/1 r_x/2 r_y/3 r_z/4 v_x/5 v_y/6 v_z/7 rmin/8 rmax/9 NBin/10\n"); for (i = 0; i < gi.NHalo; i++) { fprintf(outputfile,"%d",hd[i].ID); fprintf(outputfile," %.6e %.6e %.6e",hd[i].rcentre[0],hd[i].rcentre[1],hd[i].rcentre[2]); fprintf(outputfile," %.6e %.6e %.6e",hd[i].vcentre[0],hd[i].vcentre[1],hd[i].vcentre[2]); fprintf(outputfile," %.6e %.6e",hd[i].rmin[0],hd[i].rmax[0]); fprintf(outputfile," %d",hd[i].NBin[0]); fprintf(outputfile,"\n"); } fclose(outputfile); /* ** Matter profiles */ for (j = 0; j < gi.NSpeciesProfile; j++) { if (gi.SpeciesContained[j]) { n[2] = 0; n[1] = 0; sprintf(outputfilename,"%s.shape.%03d.pro.%s",gi.OutputName,ILoop,gi.MatterTypeName[j]); outputfile = fopen(outputfilename,"w"); assert(outputfile != NULL); fprintf(outputfile,"#ID/1 ri/2 rm/3 ro/4 M/5 N/6 b:a/7 c:a/8 a_x/9 a_y/10 a_z/11 b_x/12 b_y/13 b_z/14 c_x/15 c_y/16 c_z/17 re_b:a/18 re_c:a/19 NLoopConverged/20\n"); for (i = 0; i < gi.NHalo; i++) { for (n[0] = 0; n[0] < hd[i].NBin[0]; n[0]++) { fprintf(outputfile,"%d",hd[i].ID); fprintf(outputfile," %.6e %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].ri[0],hd[i].pbs[n[0]][n[1]][n[2]].rm[0],hd[i].pbs[n[0]][n[1]][n[2]].ro[0]); fprintf(outputfile," %.6e %ld",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].M,hd[i].pbs[n[0]][n[1]][n[2]].shape[j].N); fprintf(outputfile," %.6e %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a,hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].a[d]); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b[d]); for (d = 0; d < 3; d++) fprintf(outputfile," %.6e",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c[d]); fprintf(outputfile," %.6e",(hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a/hd[i].pbs[n[0]][n[1]][n[2]].shape[j].b_a_old)-1); fprintf(outputfile," %.6e",(hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a/hd[i].pbs[n[0]][n[1]][n[2]].shape[j].c_a_old)-1); fprintf(outputfile," %d",hd[i].pbs[n[0]][n[1]][n[2]].shape[j].NLoopConverged); fprintf(outputfile,"\n"); } } fclose(outputfile); } /* if SpeciesContained */ } /* for NSpeciesProfile */ } /* void read_spherical_profiles(GI gi, HALO_DATA *hd) { */ /* int i, j, k; */ /* int ID, IDold, hit, NHaloFound, idummy; */ /* double V, M, property; */ /* double ddummy; */ /* double fproperty = 1.1; */ /* char cdummy[1000]; */ /* FILE *InputFile; */ /* /\* */ /* ** Total matter */ /* *\/ */ /* InputFile = fopen(gi.TotProfilesFileName,"r"); */ /* assert(InputFile != NULL); */ /* NHaloFound = 0; */ /* fgets(cdummy,1000,InputFile); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (1) { */ /* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (j = 0; j < 16; j++) fscanf(InputFile,"%le",&ddummy); */ /* if (feof(InputFile)) break; */ /* hit = 0; */ /* for (i = 0; i < gi.NHalo; i++) { */ /* if (hd[i].ID == ID) { */ /* property = M/V; */ /* hd[i].pbs[0].totshape->propertymin = property/fproperty; */ /* hd[i].pbs[0].totshape->propertymax = property*fproperty; */ /* for (j = 1; j < hd[i].NBin+1; j++) { */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (k = 0; k < 16; k++) fscanf(InputFile,"%le",&ddummy); */ /* property = M/V; */ /* assert(hd[i].ID == ID); */ /* hd[i].pbs[j].totshape->propertymin = property/fproperty; */ /* hd[i].pbs[j].totshape->propertymax = property*fproperty; */ /* } */ /* NHaloFound++; */ /* hit = 1; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* if (hit == 1) break; */ /* } */ /* if (NHaloFound == gi.NHalo) break; */ /* if (hit == 0) { */ /* /\* */ /* ** Halo is not in list */ /* *\/ */ /* IDold = ID; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (IDold == ID) { */ /* for (i = 0; i < 22; i++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* } */ /* } */ /* fclose(InputFile); */ /* /\* */ /* ** Gas */ /* *\/ */ /* if (gi.SpeciesContained[GAS]) { */ /* InputFile = fopen(gi.GasProfilesFileName,"r"); */ /* assert(InputFile != NULL); */ /* NHaloFound = 0; */ /* fgets(cdummy,1000,InputFile); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (1) { */ /* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (j = 0; j < 32; j++) fscanf(InputFile,"%le",&ddummy); */ /* if (feof(InputFile)) break; */ /* hit = 0; */ /* for (i = 0; i < gi.NHalo; i++) { */ /* if (hd[i].ID == ID) { */ /* property = M/V; */ /* hd[i].pbs[0].gasshape->propertymin = property/fproperty; */ /* hd[i].pbs[0].gasshape->propertymax = property*fproperty; */ /* for (j = 1; j < hd[i].NBin+1; j++) { */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (k = 0; k < 32; k++) fscanf(InputFile,"%le",&ddummy); */ /* property = M/V; */ /* assert(hd[i].ID == ID); */ /* hd[i].pbs[j].gasshape->propertymin = property/fproperty; */ /* hd[i].pbs[j].gasshape->propertymax = property*fproperty; */ /* } */ /* NHaloFound++; */ /* hit = 1; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* if (hit == 1) break; */ /* } */ /* if (NHaloFound == gi.NHalo) break; */ /* if (hit == 0) { */ /* /\* */ /* ** Halo is not in list */ /* *\/ */ /* IDold = ID; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (IDold == ID) { */ /* for (i = 0; i < 38; i++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* } */ /* } */ /* fclose(InputFile); */ /* } */ /* /\* */ /* ** Dark matter */ /* *\/ */ /* if (gi.SpeciesContained[DARK]) { */ /* InputFile = fopen(gi.DarkProfilesFileName,"r"); */ /* assert(InputFile != NULL); */ /* NHaloFound = 0; */ /* fgets(cdummy,1000,InputFile); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (1) { */ /* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (j = 0; j < 15; j++) fscanf(InputFile,"%le",&ddummy); */ /* if (feof(InputFile)) break; */ /* hit = 0; */ /* for (i = 0; i < gi.NHalo; i++) { */ /* if (hd[i].ID == ID) { */ /* property = M/V; */ /* hd[i].pbs[0].darkshape->propertymin = property/fproperty; */ /* hd[i].pbs[0].darkshape->propertymax = property*fproperty; */ /* for (j = 1; j < hd[i].NBin+1; j++) { */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (k = 0; k < 15; k++) fscanf(InputFile,"%le",&ddummy); */ /* property = M/V; */ /* assert(hd[i].ID == ID); */ /* hd[i].pbs[j].darkshape->propertymin = property/fproperty; */ /* hd[i].pbs[j].darkshape->propertymax = property*fproperty; */ /* } */ /* NHaloFound++; */ /* hit = 1; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* if (hit == 1) break; */ /* } */ /* if (NHaloFound == gi.NHalo) break; */ /* if (hit == 0) { */ /* /\* */ /* ** Halo is not in list */ /* *\/ */ /* IDold = ID; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (IDold == ID) { */ /* for (i = 0; i < 21; i++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* } */ /* } */ /* fclose(InputFile); */ /* } */ /* /\* */ /* ** Stars */ /* *\/ */ /* if (gi.SpeciesContained[STAR]) { */ /* InputFile = fopen(gi.StarProfilesFileName,"r"); */ /* assert(InputFile != NULL); */ /* NHaloFound = 0; */ /* fgets(cdummy,1000,InputFile); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (1) { */ /* for (j = 0; j < 3; j++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (j = 0; j < 21; j++) fscanf(InputFile,"%le",&ddummy); */ /* if (feof(InputFile)) break; */ /* hit = 0; */ /* for (i = 0; i < gi.NHalo; i++) { */ /* if (hd[i].ID == ID) { */ /* property = M/V; */ /* hd[i].pbs[0].starshape->propertymin = property/fproperty; */ /* hd[i].pbs[0].starshape->propertymax = property*fproperty; */ /* for (j = 1; j < hd[i].NBin+1; j++) { */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* for (k = 0; k < 3; k++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); V = ddummy; */ /* fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%le",&ddummy); M = ddummy; */ /* for (k = 0; k < 21; k++) fscanf(InputFile,"%le",&ddummy); */ /* property = M/V; */ /* assert(hd[i].ID == ID); */ /* hd[i].pbs[j].starshape->propertymin = property/fproperty; */ /* hd[i].pbs[j].starshape->propertymax = property*fproperty; */ /* } */ /* NHaloFound++; */ /* hit = 1; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* if (hit == 1) break; */ /* } */ /* if (NHaloFound == gi.NHalo) break; */ /* if (hit == 0) { */ /* /\* */ /* ** Halo is not in list */ /* *\/ */ /* IDold = ID; */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* while (IDold == ID) { */ /* for (i = 0; i < 27; i++) fscanf(InputFile,"%le",&ddummy); */ /* fscanf(InputFile,"%i",&idummy); ID = idummy; */ /* } */ /* } */ /* } */ /* fclose(InputFile); */ /* } */ /* } */
{ "alphanum_fraction": 0.5774980125, "avg_line_length": 36.2586762754, "ext": "c", "hexsha": "d91d6b2934c8082f22ed8792b72d14014964153b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-10-10T13:16:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-10T13:16:25.000Z", "max_forks_repo_head_hexsha": "6a8d4c74692aa06e230225b7fb9b828ee76ccd4d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mzemp/profile", "max_forks_repo_path": "profile.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6a8d4c74692aa06e230225b7fb9b828ee76ccd4d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mzemp/profile", "max_issues_repo_path": "profile.c", "max_line_length": 418, "max_stars_count": null, "max_stars_repo_head_hexsha": "6a8d4c74692aa06e230225b7fb9b828ee76ccd4d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mzemp/profile", "max_stars_repo_path": "profile.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 66892, "size": 191192 }
/* integration/rational.c * * Copyright (C) 2017 Konrad Griessinger, Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * The code in this module is based on IQPACK, specifically the LGPL * implementation found in HERMITE_RULE: * https://people.sc.fsu.edu/~jburkardt/c_src/hermite_rule/hermite_rule.html */ #include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_sf_gamma.h> static int rational_check(const size_t n, const gsl_integration_fixed_params * params) { if (fabs(params->b - params->a) <= GSL_DBL_EPSILON) { GSL_ERROR("|b - a| too small", GSL_EDOM); } else if (params->alpha <= -1.0) { GSL_ERROR("alpha must be > -1", GSL_EDOM); } else if (params->beta >= 0.0 || params->alpha+params->beta+2*n >= 0.0 || 0.0 >= params->alpha+2*n) { GSL_ERROR("beta < alpha + beta + 2n < 0 is required", GSL_EDOM); } else if (params->a + params->b <= 0.0) { GSL_ERROR("a + b <= 0 is not allowed", GSL_EDOM); } else { return GSL_SUCCESS; } } static int rational_init(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params) { const double absum = params->beta + params->alpha; const double a1 = params->alpha + 1.0; const double aba1 = absum*a1; double ab2i = absum + 2.0; size_t i; /* construct the diagonal and subdiagonal elements of Jacobi matrix */ diag[0] = -a1/(absum + 2.0); subdiag[0] = sqrt( -diag[0] * ( params->beta + 1.0 ) / ( (absum + 2.0)*(absum + 3.0) ) ); for (i = 1; i < n-1; i++) { ab2i += 2.0; diag[i] = ( -aba1 - 2.0 * i * ( absum + i + 1.0 ) ) / ( ab2i * ( ab2i - 2.0 ) ); subdiag[i] = sqrt( (i+1.0) * ( params->alpha + i + 1.0 ) / ( ab2i - 1.0 ) * ( params->beta + i + 1.0 ) / ( ab2i * ab2i ) * ( absum + i + 1.0 ) / ( ab2i + 1.0 ) ); } diag[n-1] = ( -aba1 - 2.0 * (n-1.0) * ( absum + n ) ) / ( (absum + 2.0*n) * ( absum + 2.0*n - 2.0 ) ); subdiag[n-1] = 0.0; params->zemu = gsl_sf_gamma(params->alpha + 1.0) * gsl_sf_gamma(-absum - 1.0) / gsl_sf_gamma(-params->beta); params->shft = params->a; params->slp = params->b + params->a; params->al = params->alpha; params->be = params->beta; return GSL_SUCCESS; } static const gsl_integration_fixed_type rational_type = { rational_check, rational_init }; const gsl_integration_fixed_type *gsl_integration_fixed_rational = &rational_type;
{ "alphanum_fraction": 0.6366223909, "avg_line_length": 32.5979381443, "ext": "c", "hexsha": "b6f1960fd06de0267c5a6205888313a2fee74497", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/rational.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/rational.c", "max_line_length": 168, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/integration/rational.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 1027, "size": 3162 }
#include <jni.h> #include <assert.h> #include <lapacke.h> /* LU */ JNIEXPORT jint Java_JAMAJni_LUDecomposition_dgetrf (JNIEnv *env, jclass klass, jint matrix_layout, jint m, jint n, jdoubleArray a, jint lda, jintArray ipiv){ double *aElems; lapack_int *ipivElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); ipivElems = (*env)-> GetIntArrayElements (env, ipiv, NULL); assert(aElems && ipivElems); info = LAPACKE_dgetrf ((int) matrix_layout, (lapack_int) m, (lapack_int) n, aElems, (lapack_int) lda, ipivElems); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseIntArrayElements (env, ipiv, ipivElems, 0); return info; } JNIEXPORT jint Java_JAMAJni_LUDecomposition_dgetrs (JNIEnv *env, jclass klass, jint matrix_layout, jchar trans, jint n, jint nrhs, jdoubleArray a, jint lda, jintArray ipiv, jdoubleArray b, jint ldb){ double *bElems; double *aElems; lapack_int *ipivElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); bElems = (*env)-> GetDoubleArrayElements (env, b, NULL); ipivElems = (*env)-> GetIntArrayElements (env, ipiv, NULL); assert(aElems && bElems && ipivElems); info = LAPACKE_dgetrs ((int) matrix_layout, (char) trans, (lapack_int) n, (lapack_int) nrhs, aElems, (lapack_int) lda, ipivElems, bElems, (lapack_int) ldb); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, JNI_ABORT); (*env)-> ReleaseDoubleArrayElements (env, b, bElems, 0); (*env)-> ReleaseIntArrayElements (env, ipiv, ipivElems, JNI_ABORT); return info; }
{ "alphanum_fraction": 0.6684749849, "avg_line_length": 31.3018867925, "ext": "c", "hexsha": "b843ee9f2e6cc1ed71118bfffd06ec6a62ddbbbe", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_forks_repo_licenses": [ "AAL" ], "max_forks_repo_name": "dw6ja/JAMAJni", "max_forks_repo_path": "src/jni_lapacke/c/LUDecomposition.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AAL" ], "max_issues_repo_name": "dw6ja/JAMAJni", "max_issues_repo_path": "src/jni_lapacke/c/LUDecomposition.c", "max_line_length": 199, "max_stars_count": null, "max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_stars_repo_licenses": [ "AAL" ], "max_stars_repo_name": "dw6ja/JAMAJni", "max_stars_repo_path": "src/jni_lapacke/c/LUDecomposition.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 525, "size": 1659 }
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_permutation.h> #include "matrixUtils.h" #include "../mcmc/mvnormMCMC/mvrandist.h" /*A collection of matrix functions*/ /*Alexander G. Shanku*/ /*Wed 12/05/2012 12:44:41 EST*/ //// Makes a matrix filled with random U(0,1) elements //// gsl_matrix fill_rand_matrix(gsl_matrix *X, gsl_rng *r_num){ int i,j; /*int step = 0;*/ int n = X->size1; int m = X->size2; for (i = 0; i < m; ++i){ for (j = 0; j < n; ++j){ gsl_matrix_set(X, i, j, gsl_rng_uniform(r_num)); } } return(*X); } //// Makes a matrix filled with sequential elements, starting with 0 //// gsl_matrix fill_matrix(gsl_matrix *X){ int i,j; int n = X->size1; int m = X->size2; for (i = 0; i < m; ++i){ for (j = 0; j < n; ++j){ gsl_matrix_set(X, i, j, i+(j*m)); } } return(*X); } //// Do LU decomp, get determinant and keep input matrix untouched //// double matrix_determ(gsl_matrix *X){ int s; int n = X->size1; int m = X->size2; gsl_matrix *a_copy = gsl_matrix_alloc(m, n); gsl_matrix_memcpy(a_copy, X ); gsl_permutation *P = gsl_permutation_alloc(n); gsl_linalg_LU_decomp(a_copy, P, &s); double my_det = gsl_linalg_LU_det (a_copy, s); return(my_det); } //// Get trace of given matrix //// double matrix_trace(gsl_matrix *X){ int i, m; m = X->size1; double trace = 0.0; for(i=0;i<m;i++){ trace += gsl_matrix_get(X,i,i); } return(trace); } //// Multivariate Gamma function //// double mv_gamma(double a, double d){ double val = 1.0; int i; for(i = 1; i <= d; i++){ val *= gsl_sf_gamma(a - (0.5 * (i - 1))); } val *= pow(M_PI, (d * (d - 1) / 4.0)); return(val); } //// Get Inverse Wishart PDF //// double iwishpdf(gsl_matrix *X, gsl_matrix *Scale, gsl_matrix *inv, double dof){ // From http://en.wikipedia.org/wiki/Inverse-Wishart_distribution double X_det, scale_det, denom, pdf, trace, numerator; int m = X->size1; int n = X->size2; // Allocate matrix for inv(X) gsl_matrix *for_mult = gsl_matrix_alloc(m, n); // Get determinant of X and Scale matrix X_det = matrix_determ(X); scale_det = matrix_determ(Scale); // Invert X inv_matrix(X,inv); // Multiple Scale * inv(X) gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Scale, inv, 1.0, for_mult); // Get trace of above. trace = matrix_trace(for_mult); numerator = pow(scale_det, dof / 2.0) * pow(X_det, (-dof-m-1)/ 2.0) * exp(-0.5 * trace); denom = pow(2,dof * m / 2) * mv_gamma(dof/2, m); pdf = (numerator/denom); return(pdf); } //// Invert a matrix and keep input matrix untouched //// gsl_matrix inv_matrix(gsl_matrix *X, gsl_matrix *inv){ int s; int n = X->size1; int m = X->size2; gsl_matrix *a_copy = gsl_matrix_alloc(m, n); gsl_matrix_memcpy( a_copy, X ); gsl_permutation *P = gsl_permutation_alloc(n); gsl_linalg_LU_decomp(a_copy, P, &s); gsl_linalg_LU_invert(a_copy, P, inv); return(*inv); } //// Print a matrix to stdout //// void print_matrix(gsl_matrix *X){ int i, j; int n = X->size1; int m = X->size2; printf("\n"); for(i=0; i<n; i++){ for(j=0; j<m; j++){ printf("%05.2f ", gsl_matrix_get(X, i, j)); } printf("\n"); } } ///////// Added Sat 01/19/2013 15:24:41 EST ///////// gsl_vector array_to_gsl_vec(gsl_vector *dest, double src[3]){ int i; int n = dest->size; for (i = 0; i < n; ++i){ gsl_vector_set(dest, i, src[i]); } return(*dest); } ///// Transform user supplied matrix into a gsl matrix //// gsl_matrix mdarray_to_gsl_mat(gsl_matrix *dest, double src[3][3]){ int i, j; int n = dest->size1; int m = dest->size2; for (i = 0; i < m; ++i){ for (j = 0; j < n; ++j){ gsl_matrix_set(dest, i, j, src[i][j]); } } return(*dest); } //// Print a vector to stdout //// void print_vector(gsl_vector *src){ int i; int n = src->size; printf("\n"); for (i = 0; i < n; ++i){ printf("%05.4f ", gsl_vector_get(src,i)); } printf("\n"); } //// Do cholesky decomp to matrix //// gsl_matrix get_chol(gsl_matrix *src, gsl_matrix *dest){ gsl_matrix_memcpy(dest, src); gsl_linalg_cholesky_decomp(dest); return(*dest); } //// Add gaussian noise to chol decomp matrix //// gsl_matrix mat_noise(gsl_matrix *src, gsl_rng *r_num){ int i,j; int n = src->size1; int m = src->size2; double tmp; for(i = 0; i < n; i++){ for(j = 0; j < m; j++){ if(i >= j){ tmp = gsl_matrix_get(src,i,j) + gsl_ran_gaussian(r_num,0.05); gsl_matrix_set(src, i, j, tmp); } } } return(*src); } //// Transform cholesky decomp matrix into vector //// void fill_chol_vec(gsl_matrix *src, gsl_vector *dest){ int i, j, count = 0; for(i = 0; i < src->size1; i++){ for(j=0;j<src->size2;j++){ if(i<=j){ gsl_vector_set(dest,count++, gsl_matrix_get(src,i,j)); } } } } //// Add gaussian noise to each element in vector //// gsl_vector vec_noise(gsl_rng *r_num, gsl_vector *src, gsl_vector *dest){ int i; int n = src->size; double tmp; for(i=0;i<n;i++){ tmp = gsl_vector_get(src,i) + gsl_ran_gaussian(r_num, 0.05); gsl_vector_set(dest,i,tmp); } return(*dest); } //// Multiply cholesky decomp matrix by its transpose //// gsl_matrix chol_mult(gsl_matrix *src, gsl_matrix *dest){ gsl_blas_dgemm(CblasNoTrans, CblasTrans,1.0, src, src,1.0, dest); return(*dest); } //// Zeros out everything but lower tri-- in place //// //// From adk's adkGSL.c //// gsl_matrix gsl_matrix_lower_tri(gsl_matrix *src){ int i, j; for(i = 0; i < src->size1; i++){ for(j = 0; j < src->size2; j++){ if(i<j) gsl_matrix_set(src,i,j,0.0); } } return(*src); } // Random Wishart matrix. Taken from Andy Kern's mvnorm_gsl.c /*void rwishartGelman(gsl_matrix *Scale, double dof){ *//* Wishart distribution random number generator */ /* * n gives the dimension of the random matrix * dof degrees of freedom * scale scale matrix of dimension n x n * result output variable with a single random matrix Wishart distribution generation */ /* int i; gsl_vector gsl_vector_alloc(ndim) gsl_vector_set_all(mean,0.0); gsl_matrix_set_all(output,0.0); for(i = 0; i < dof; i++){ gsl_vector_set_all(xm,0); rmvnorm_prealloc(r, n, mean, scale, work, xm); gsl_vector_outer_product(xm,xm,work2); gsl_matrix_add(output,work2); } } */ /*void rwishartGelman(const gsl_rng *r, const int n, const int dof, const gsl_matrix *scale, gsl_matrix *work,gsl_matrix *work2, gsl_vector *mean,gsl_vector *xm, gsl_matrix *output) rwishartGelman(r, ndim, nsnps+ndim, p2->winv, p2->work,p2->work2, p2->means, p2->xm, p2->covMat); */
{ "alphanum_fraction": 0.6392219947, "avg_line_length": 21.8466453674, "ext": "c", "hexsha": "1ac4a12fac1f94e6f2bc2c04b4045d861c8ba7bf", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z", "max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewkern/pgLib", "max_forks_repo_path": "matrixUtils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewkern/pgLib", "max_issues_repo_path": "matrixUtils.c", "max_line_length": 93, "max_stars_count": 3, "max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewkern/pgLib", "max_stars_repo_path": "matrixUtils.c", "max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z", "num_tokens": 2279, "size": 6838 }
#include <cblas.h> void openblas_mul_double(double *a, double *b, double *c, int m, int k, int n) { cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1., a, k, b, n, 0., c, n ); }
{ "alphanum_fraction": 0.4923076923, "avg_line_length": 17.3333333333, "ext": "c", "hexsha": "7052e4bcdbc7f90082aabd961d57607b16775523", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hsyis/object-detection-yolo2-tiny", "max_forks_repo_path": "proj3/src/dnn_openblas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hsyis/object-detection-yolo2-tiny", "max_issues_repo_path": "proj3/src/dnn_openblas.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hsyis/object-detection-yolo2-tiny", "max_stars_repo_path": "proj3/src/dnn_openblas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 89, "size": 260 }
/* Useful general-purpose functions. * * Krzysztof Chalupka, 2017. */ #include <stdio.h> #include <gsl/gsl_blas.h> #include "utils.h" void crit_err(char *msg){ fprintf(stderr, "%s, exiting.\n", msg); exit(1); } int get_nlines(char *fname){ /* Check how many lines there are in a file. */ int nlines = 0; FILE *f = fopen(fname, "r"); while(!feof(f)) if (fgetc(f) == '\n') nlines++; fclose(f); printf("%d lines read from %s.\n\n", nlines, fname); return nlines; } void print_intarray(int *arr, int n){ int i; printf("["); for(i = 0; i < n; i++) printf("%d ", arr[i]); printf("]"); } void print_gsl_vector(gsl_vector *vec){ int i; for (i = 0; i < vec->size; i++) printf("%.4f ", vec->data[i]); } gsl_vector *vector_sub(gsl_vector *v1, gsl_vector *v2){ /* Create a new vector equal to v1 - v2. */ gsl_vector *res = gsl_vector_calloc(v1->size); gsl_vector_add(res, v1); gsl_vector_sub(res, v2); return res; } double vector_dist(gsl_vector *v1, gsl_vector *v2){ /* Compute the Euclidean distance between vectors. */ double dist; gsl_vector *tmp = vector_sub(v1, v2); dist = gsl_blas_dnrm2(tmp); free(tmp); return dist; } gsl_vector **load_vectors_from_file(char *fname, int nvecs) { int vec_id; FILE *f; gsl_vector **vecs; double vals[2] = {0., 0.}; /* Allocate the vector array. */ vecs = (gsl_vector **) calloc(nvecs, sizeof(gsl_vector *)); /* Load the vectors from a file into an array. */ f = fopen(fname, "r"); vec_id = 0; while(fscanf(f,"%lf %lf", &vals[0], &vals[1]) != EOF){ vecs[vec_id] = gsl_vector_alloc(2); gsl_vector_set(vecs[vec_id], 0, vals[0]); gsl_vector_set(vecs[vec_id], 1, vals[1]); vec_id++; } /* Clean up. */ fclose(f); printf("Data: \n"); for (vec_id = 0; vec_id < nvecs; vec_id++) printf("[%f, %f]\n", vecs[vec_id]->data[0], vecs[vec_id]->data[1]); printf("\n"); return vecs; }
{ "alphanum_fraction": 0.6036866359, "avg_line_length": 22.1931818182, "ext": "c", "hexsha": "bb945d4f6eb92ecf4f1551ee80e85031105b5479", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kjchalup/algorithm_design", "max_forks_repo_path": "skiena/utils/utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kjchalup/algorithm_design", "max_issues_repo_path": "skiena/utils/utils.c", "max_line_length": 61, "max_stars_count": null, "max_stars_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kjchalup/algorithm_design", "max_stars_repo_path": "skiena/utils/utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 646, "size": 1953 }
/* # Program to run a Monte Carlo radiation transfer through the 2D # simulations of GRB jets. # # Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State # ver 0.1 July 8, 2015 # ver 1.1 July 20, 2015: added record of number of scatterings, included # all terms in weight. Should now give correct light curves. # ver 1.2 July 21, 2015: added parameter file to keep track of input # params of each simulation # ver 2.0 July 22, 2015: corrected the problem that arises when there is # no scattering in the time span of one frame. Fixed output arrays dimension. # ver 2.1 July 25, 2015: fixed bug that did not make the number of # scattering grow with the number of photons. # ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to # speed things up. Gained about factor 2 # ver 3.1 July 29, 2015: added radial spread of photon injection points # ver 3.2 July 31, 2015: added Gamma to the weight of photons!!! # ver 4.0 Aug 5, 2015: try to speed up by inverting cycle # ver 4.1 Aug 8, 2015: add spherical test as an option # ver 4.2 Aug 9, 2015: saving files appending rather than re-writing # ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature # ver 4.4 Aug 13, 2015: added cylindrical test # ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test # ver 4.6 Aug 21, 2015: corrected mean free path for large radii # ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings # ver 5.1 Aug 25, 2015: cleaned-up coding # ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections * * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path so you just need to supply the sub directory of MC_XXX as a command line argument */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <math.h> #include <gsl/gsl_rng.h> #include "mclib.h" #define THISRUN "Spherical" #define FILEPATH "/Volumes/parsotat/Documents/16TI/" #define FILEROOT "rhd_jet_big_13_hdf5_plt_cnt_" #define MC_PATH "CMC_16TI_SPHERICAL/" #define MCPAR "mc.par" int main(int argc, char **argv) { //compile each time a macro is changed, have to supply the subfolder within the MC_PATH directory as a command line argument to the C program eg. MCRAT 1/ // Define variables char flash_prefix[200]=""; char flash_file[200]=""; char mc_dir[200]="" ; char mc_file[200]="" ; char mc_filename[200]=""; char mc_operation[200]=""; char this_run[200]=THISRUN; char *cyl="Cylindrical"; char *sph="Spherical"; int file_count = 0; DIR * dirp; struct dirent * entry; char spect;//type of spectrum char restrt;//restart or not double fps, theta_jmin, theta_jmax ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians double inj_radius, ph_weight ;//radius at chich photons are injected into sim int frm0,last_frm, frm2, photon_num ;//frame starting from, last frame of sim, frame of last injection, number of photons (not necessary any more) double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL; double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter double dt_max=0, thescatt=0, accum_time=0; double gamma_infinity=0; double time_now=0, time_step=0, avg_scatt=0; double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0;// *ph_cosanglePtr=NULL ; int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0; struct photon *phPtr=NULL; //pointer to array of photons long seed; const gsl_rng_type * T; gsl_rng * rand; gsl_rng_env_setup(); T = gsl_rng_ranlxs0; rand = gsl_rng_alloc (T); //make strings of proper directories etc. snprintf(flash_prefix,sizeof(flash_prefix),"%s%s",FILEPATH,FILEROOT ); snprintf(mc_dir,sizeof(flash_prefix),"%s%s%s",FILEPATH,MC_PATH, argv[1]); snprintf(mc_file,sizeof(flash_prefix),"%s%s",mc_dir,MCPAR); printf(">> mc.py: I am working on path: %s \n",mc_dir); printf(">> mc.py: Reading mc.par\n"); readMcPar(mc_file, &fps, &theta_jmin, &theta_jmax,&inj_radius,&frm0,&last_frm,&frm2,&photon_num, &ph_weight, &spect, &restrt); if (restrt=='c') { printf(">> mc.py: Reading checkpoint\n"); readCheckpoint(mc_dir, &phPtr, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now); for (i=0;i<num_ph;i++) { printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(phPtr+i)->p0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt ); } if (restrt=='c') { printf("Starting from photons injected at frame: %d out of %d\n", framestart, frm2); printf("Continuing scattering %d photons from frame: %d\n", num_ph, scatt_framestart); printf("The time now is: %e\n", time_now); } else { printf("Continuing simulation by injecting photons at frame: %d out of %d\n", framestart, frm2); //starting with new photon injection is same as restarting sim } } else { //remove everything from MC directory to ensure no corruption of data if theres other files there besides the mc.par file //for a checkpoint implementation, need to find the latest checkpoint file and read it and not delete the files printf(">> mc.py: Cleaning directory\n"); dirp = opendir(mc_dir); while ((entry = readdir(dirp)) != NULL) { if (entry->d_type == DT_REG) { /* If the entry is a regular file */ file_count++; //count how many files are in dorectory } } //printf("File count %d\n", file_count); if (file_count>2) { for (i=0;i<=last_frm;i++) { snprintf(mc_filename,sizeof(flash_prefix),"%s%s%d%s", mc_dir,"mcdata_",i,"_P0.dat"); if( access( mc_filename, F_OK ) != -1 ) { snprintf(mc_operation,sizeof(flash_prefix),"%s%s%s%d%s","exec rm ", mc_dir,"mcdata_",i,"_*.dat"); //prepares string to remove *.dat in mc_dir //printf("%s",mc_operation); system(mc_operation); } } } framestart=frm0; //if restarting then start from parameters given in mc.par file scatt_framestart=framestart; } dt_max=1.0/fps; //loop over frames //for a checkpoint implementation, start from the last saved "frame" value and go to the saved "frm2" value for (frame=framestart;frame<=frm2;frame++) { if (restrt=='r') { time_now=frame/fps; //for a checkpoint implmentation, load the saved "time_now" value when reading the ckeckpoint file otherwise calculate it normally } printf(">> mc.py: Working on Frame %d\n", frame); if (restrt=='r') { //put proper number at the end of the flash file if (frame<10) { snprintf(flash_file,sizeof(flash_prefix), "%s%.3d%d",flash_prefix,000,frame); } else if (frame<100) { snprintf(flash_file,sizeof(flash_prefix), "%s%.2d%d",flash_prefix,00,frame); } else if (frame<1000) { snprintf(flash_file,sizeof(flash_prefix), "%s%d%d",flash_prefix,0,frame); } else { snprintf(flash_file,sizeof(flash_prefix), "%s%d",flash_prefix,frame); } printf(">> mc.py: Opening FLASH file %s\n",flash_file); //read in FLASH file //for a checkpoint implmentation, dont need to read the file yet readAndDecimate(flash_file, inj_radius, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num); //check for run type if(strcmp(cyl, this_run)==0) { //printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num ); } //determine where to place photons and how many should go in a given place //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data printf(">> mc.py: Injecting photons\n"); photonInjection(&phPtr, &num_ph, inj_radius, ph_weight, spect, array_num, fps, theta_jmin, theta_jmax, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rand ); printf("%d\n",num_ph); //num_ph is one more photon than i actually have /* for (i=0;i<num_ph;i++) printf("%e,%e,%e \n",(phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2 ); */ } //scatter photons all the way thoughout the jet //for a checkpoint implmentation, start from the last saved "scatt_frame" value eh start_frame=frame or start_frame=cont_frame if (restrt=='r') { scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint() } for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame++) { printf(">>\n"); printf(">> mc.py: Working on photons injected at frame: %d out of %d\n", frame, frm2); printf(">> mc.py: %s: Working on frame %d\n", THISRUN, scatt_frame); printf(">> mc.py: Opening file...\n"); //put proper number at the end of the flash file if (scatt_frame<10) { snprintf(flash_file,sizeof(flash_prefix), "%s%.3d%d",flash_prefix,000,scatt_frame); } else if (scatt_frame<100) { snprintf(flash_file,sizeof(flash_prefix), "%s%.2d%d",flash_prefix,00,scatt_frame); } else if (scatt_frame<1000) { snprintf(flash_file,sizeof(flash_prefix), "%s%d%d",flash_prefix,0,scatt_frame); } else { snprintf(flash_file,sizeof(flash_prefix), "%s%d",flash_prefix,scatt_frame); } readAndDecimate(flash_file, inj_radius, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\ &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num); //printf("The result of read and decimate are arrays with %d elements\n", array_num); //check for run type if(strcmp(cyl, this_run)==0) { printf("In cylindrical prep\n"); cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num); } else if (strcmp(sph, this_run)==0) { sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num ); } printf(">> mc.py: propagating and scattering %d photons\n", num_ph); frame_scatt_cnt=0; while (time_now<((scatt_frame+1)/fps)) { //if simulation time is less than the simulation time of the next frame, keep scattering in this frame //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path //and choose the photon with the smallest mfp and calculate the timestep ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, &time_step, xPtr, yPtr, velxPtr, velyPtr, dens_labPtr, tempPtr,\ &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_tempPtr, rand); //printf("In main: %e, %d, %e, %e\n", *(ph_num_scatt+ph_scatt_index), ph_scatt_index, time_step, time_now); //printf("In main: %e, %d, %e, %e\n",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); if (time_step<dt_max) { //update number of scatterings and time //(*(ph_num_scatt+ph_scatt_index))+=1; ((phPtr+ph_scatt_index)->num_scatt)+=1; frame_scatt_cnt+=1; time_now+=time_step; updatePhotonPosition(phPtr, num_ph, time_step); //scatter the photon //printf("Passed Parameters: %e, %e, %e\n", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr)); photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr), (ph_tempPtr), rand ); if (frame_scatt_cnt%1000 == 0) { printf("Scattering Number: %d\n", frame_scatt_cnt); printf("The local temp is: %e, Local energy: %e\n", (ph_tempPtr), (ph_tempPtr)*(1.380658e-16/1.6e-9)); printf("Average photon energy is: %e keV\n", averagePhotonEnergy(phPtr, num_ph)/1.6e-9); //write function to average over the photons p0*c and then do (/1.6e-9) } } else { time_now+=dt_max; //for each photon update its position based on its momentum updatePhotonPosition(phPtr, num_ph, dt_max); } //printf("In main 2: %e, %d, %e, %e\n", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now); } //get scattering statistics phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt); printf("The number of scatterings in this frame is: %d\n", frame_scatt_cnt); printf("The last time step was: %lf.\nThe time now is: %lf\n", time_step,time_now); printf("The maximum number of scatterings for a photon is: %d\nThe minimum number of scattering for a photon is: %d\n", max_scatt, min_scatt); printf("The average number of scatterings thus far is: %lf\n", avg_scatt); printPhotons(phPtr, num_ph, scatt_frame , mc_dir); //for a checkpoint implmentation,save the checkpoint file here after every 5 frames or something //save the photons data, the scattering number data, the scatt_frame value, and the frame value //WHAT IF THE PROGRAM STOPS AFTER THE LAST SCATT_FRAME, DURING THE FIRST SCATT_FRAME OF NEW FRAME VARIABLE - save restrt variable as 'r' printf(">> mc.py: Making checkpoint file\n"); saveCheckpoint(mc_dir, frame, scatt_frame, num_ph, time_now, phPtr, last_frm); free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr); free(gammaPtr);free(dens_labPtr);free(tempPtr); xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL; szxPtr=NULL; szyPtr=NULL; tempPtr=NULL; } restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file free(phPtr); phPtr=NULL; } gsl_rng_free (rand); return 0; }
{ "alphanum_fraction": 0.5974080019, "avg_line_length": 47.6515580737, "ext": "c", "hexsha": "690c22241cbe497c38271f6237aebd93e4434ca2", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_line_length": 236, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "num_tokens": 4431, "size": 16821 }
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef error_e0b666c0_4caa_4710_bb62_0f8a9d0e579e_h #define error_e0b666c0_4caa_4710_bb62_0f8a9d0e579e_h #include <gslib/type.h> __gslib_begin__ struct errinfo { gchar* desc; gchar* file; int line; void* user; }; typedef void* (*error_dump)(void*); gs_export extern void* error_dump_callstack(void*); gs_export extern void _set_error(const gchar* desc, error_dump dump, void* user, const gchar* file, int line); gs_export extern void _set_last_error(const gchar* desc, error_dump dump, void* user, const gchar* file, int line); gs_export extern void pop_error(); gs_export extern errinfo* get_last_error(); gs_export extern void reset_error(); #ifndef swsc_char #define swsc_char(x) _t(x) #endif #ifdef set_error #undef set_error #endif #define set_error(desc, ...) do { \ assert(!desc); \ string str; \ str.format(desc, __VA_ARGS__); \ _set_error(str.c_str(), 0, 0, swsc_char(__FILE__), __LINE__); \ } while(0) #ifdef set_last_error #undef set_last_error #endif #define set_last_error(desc, ...) do { \ assert(!desc); \ string str; \ str.format(desc, _VA_ARGS__); \ _set_last_error(str.c_str(), 0, 0, swsc_char(__FILE__), __LINE__); \ } while(0) //gs_export extern void dumperr_file(void); gs_export extern void trace_hold(const gchar* fmt, ...); gs_export extern void _trace_to_clipboard(); #ifdef _GS_TRACE_TO_CLIPBOARD #define trace(fmt, ...) do { trace_hold(fmt, __VA_ARGS__); } while(0) #define trace_to_clipboard _trace_to_clipboard #elif defined (DEBUG) || defined (_DEBUG) gs_export extern void trace(const gchar* fmt, ...); gs_export extern void trace_all(const gchar* str); #define trace_to_clipboard __noop #else #define trace(fmt, ...) __noop #define trace_all __noop; #define trace_to_clipboard __noop #endif /* beep an alarm */ gs_export extern void sound_alarm(); __gslib_end__ #endif
{ "alphanum_fraction": 0.7174317618, "avg_line_length": 32.24, "ext": "h", "hexsha": "03d84723c2b05fb8bbe367e49d5609d8785e3312", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/gslib/error.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/gslib/error.h", "max_line_length": 116, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/gslib/error.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 791, "size": 3224 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <gsl/gsl_interp.h> #include "allvars.h" #include "proto.h" void line_convolution() { FILE *fp; int info, i, j, nq; double flux, err, tline, taup, tcon, fcon, fcon_err, dtau; double *yrec_line; // double sigma, taud; double *Larr, *ybuf, *Cq, *ICq, *ave, *yave; gsl_interp_accel *gsl_acc_conv, *gsl_acc_error_conv; gsl_interp *gsl_linear_conv, *gsl_linear_error_conv; gsl_acc_conv = gsl_interp_accel_alloc(); gsl_acc_error_conv = gsl_interp_accel_alloc(); gsl_linear_conv = gsl_interp_alloc(gsl_interp_linear, ncon); gsl_linear_error_conv = gsl_interp_alloc(gsl_interp_linear, ncon); gsl_interp_init(gsl_linear_conv, Tcon, Fcon, ncon); gsl_interp_init(gsl_linear_error_conv, Tcon, Fcerrs, ncon); yrec_line = array_malloc(nline_data); // ave // taud = exp(theta_best[1]); // sigma = exp(theta_best[0]) * sqrt(taud/2.0); nq = 2*(flag_detrend + 1); Larr = workspace; ybuf = Larr + nq*nall_data; Cq = ybuf + nall_data; ICq = Cq + nq*nq; ave = ICq + nq*nq; yave = ave + nall_data; set_covar_mat(theta_best); for(i=0; i<nall_data*nall_data; i++) { Cmat[i] = Smat[i] + Nmat[i]; } for(i=0; i<ncon_data; i++) { if(flag_detrend==0) { Larr[i*nq+0] = 1.0; Larr[i*nq+1] = 0.0; } else { Larr[i*nq + 0] = 1.0; Larr[i*nq + 1] = Tcon_data[i]; Larr[i*nq + 2] = 0.0; Larr[i*nq + 3] = 0.0; } } for(i=0; i<nline_data; i++) { if(flag_detrend==0) { Larr[(i+ncon_data)*nq+0] = 0.0; Larr[(i+ncon_data)*nq+1] = 1.0; } else { Larr[(i+ncon_data)*nq + 0] = 0.0; Larr[(i+ncon_data)*nq + 1] = 0.0; Larr[(i+ncon_data)*nq + 2] = 1.0; Larr[(i+ncon_data)*nq + 3] = Tline_data[i]; } } memcpy(ICmat, Cmat, nall_data*nall_data*sizeof(double)); inverse_mat(ICmat, nall_data, &info); multiply_mat_MN(ICmat, Larr, Tmat1, nall_data, nq, nall_data); multiply_mat_MN_transposeA(Larr, Tmat1, ICq, nq, nq, nall_data); memcpy(Cq, ICq, nq*nq*sizeof(double)); inverse_mat(Cq, nq, &info); multiply_mat_MN_transposeA(Larr, ICmat, Tmat1, nq, nall_data, nall_data); multiply_mat_MN(Cq, Tmat1, Tmat2, nq, nall_data, nq); multiply_mat_MN(Tmat2, Fall_data, ave, nq, 1, nall_data); multiply_mat_MN(Larr, ave, yave, nall_data, 1, nq); //printf("%f %f\n", ave[0], ave[1]); dtau = TF_tau[1] - TF_tau[0]; fp = fopen("data/line_conv.txt", "w"); for(i=0; i<nline_data; i++) { flux = 0.0; err = 0.0; tline = Tline_data[i]; for(j=0; j<ntau; j++) { taup = TF_tau[j]; tcon = tline - taup; if(tcon >=Tcon[0] && tcon <= Tcon[ncon-1]) { fcon = gsl_interp_eval(gsl_linear_conv, Tcon, Fcon, tcon, gsl_acc_conv); fcon_err = gsl_interp_eval(gsl_linear_error_conv, Tcon, Fcerrs, tcon, gsl_acc_error_conv); flux += fcon * TF[j]; err += pow(fcon_err * TF[j] * dtau, 2); } } flux *= dtau; err = sqrt(err); yrec_line[i] = flux + yave[i+ncon_data]; fprintf(fp, "%f %e %e\n", tline, yrec_line[i]*scale_line, err*scale_line); } fclose(fp); gsl_interp_free(gsl_linear_conv); gsl_interp_free(gsl_linear_error_conv); gsl_interp_accel_free(gsl_acc_conv); gsl_interp_accel_free(gsl_acc_error_conv); }
{ "alphanum_fraction": 0.6190193165, "avg_line_length": 25.6870229008, "ext": "c", "hexsha": "4bed5a9433db4a813de0df7265c55cdb9c906978", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z", "max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/MICA", "max_forks_repo_path": "src/lineconv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/MICA", "max_issues_repo_path": "src/lineconv.c", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/MICA", "max_stars_repo_path": "src/lineconv.c", "max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z", "num_tokens": 1257, "size": 3365 }
#ifndef TFDH_GSL_WRAPPERS_H #define TFDH_GSL_WRAPPERS_H #include <gsl/gsl_spline.h> #include <vector> namespace GSL { // simple functor class to help interfacing with gsl_function. // derived classes representing a function f(x) should hold any needed // parameters as member variables, and operator()(double x) should evaluate // the function f(x). // // NOTE: the GSL wrappers below could in principle take C++11 lambdas instead // of this custom function object, however i did not find an elegant // way to call these lambdas using GSL's C interfaces... class FunctionObject { public: virtual ~FunctionObject() = default; virtual double operator()(double x) const = 0; }; // simple wrapper class around GSL splines class Spline { private: gsl_interp_accel* acc; gsl_spline* spline; public: Spline(const std::vector<double>& x, const std::vector<double>& f); ~Spline(); double eval(double r) const; }; // find a root of func in the interval x1 to x2 // one of (x1,x2) or (x2,x1) MUST bracket a root // implemented using GSL's Brent rootfinder method double findRoot(const GSL::FunctionObject& func, double x1, double x2, double eps_abs, double eps_rel); // definite integral of func from x1 to x2 // implemented using GSL's adaptive Gauss quadrature double integrate(const GSL::FunctionObject& func, double x1, double x2, double eps_abs, double eps_rel); } #endif // TFDH_GSL_WRAPPERS_H
{ "alphanum_fraction": 0.6949934124, "avg_line_length": 29.7647058824, "ext": "h", "hexsha": "083613107f2cb25d58921a5ac40a4192136c7597", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fmahebert/tfdh", "max_forks_repo_path": "src/GslWrappers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "fmahebert/tfdh", "max_issues_repo_path": "src/GslWrappers.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fmahebert/tfdh", "max_stars_repo_path": "src/GslWrappers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 388, "size": 1518 }
#include <stdio.h> #include <math.h> #include <sys/types.h> #include <time.h> #include <complex.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_sf_gamma.h> #define FALSE 0 #define TRUE 1 #ifndef M_PI #define M_PI 3.141592653589793238462643383280 /* pi */ #endif #define LN2PI 1.83787706640934548356065947 extern char parameterfilename[50]; extern char parameterlogfilename[50]; #define MBIG 1000000000 #define MSEED 161803398 #define MZ 0 #define FAC (1.0/MBIG) #define MIN(A,B) ((A) < (B) ? (A) : (B)) #define MAX(A,B) ((A) > (B) ? (A) : (B)) enum {NOT_AVAILABLE=0, ABOVE_DETECTION=1, BELOW_DETECTION=2, MEASURED=3}; typedef struct { int n; int m; int **a; } Matrix; void ReadParam( char*, void*, char* ) ; void ExperimentNumber( char*, char* ); void Error( char* ); void FileError( char*, char* ); double ***doublematrix3( int, int, int ); double **doublematrix( int, int ); int **integermatrix( int, int ); uint **uintegermatrix( int, int ); uint *uintegervector( int ); char **charmatrix( int, int ); double *doublevector( int ); int *integervector( int ); char *charvector( int ); void Int_HeapSort(int*, int); void HeapSort( double*, int ); void circmeanvar( double*, int, double*, double* ); void meanvar( double*, int, double*, double* ); void meanvarl( long double*, int, long double*, long double* ); void wmeanvar( long double *x, int n, long double *m, long double *s2 ); double mean( double*, int, int ); int choldc_block(double**, long long); uint binomialRNG(uint, double, const gsl_rng*); void multinomialRNG(uint, const double*, size_t, unsigned int*, const gsl_rng*); int poissonRNG(double, const gsl_rng*); int uniform_intRNG(int, int, const gsl_rng*); double normalRNG(double, double, const gsl_rng*); double betaRNG(double, double, const gsl_rng*); double chisqRNG(double, const gsl_rng*); double scaleinvchisqRNG(double, double, const gsl_rng*); double invgammaRNG(double, double, const gsl_rng*); double gammaRNG(double, double, const gsl_rng*); double uniformRNG(double, double, const gsl_rng*); double paretoRNG(double, double, const gsl_rng*); void dirichlet_multinomialRNG(uint, const double*, size_t, uint*, const gsl_rng*); void dirichletRNG(const double*, size_t, double*, const gsl_rng*); uint beta_binomialRNG(uint, double, double, const gsl_rng*); uint negative_binomialRNG(double, double, const gsl_rng*); uint beta_negative_binomialRNG(uint, double, double, const gsl_rng*); /* Matrix *wishartRNG(int, int, Matrix*, Matrix*, const gsl_rng*); */ /* void MVNRNG(int, Matrix*, Matrix*, Matrix*, const gsl_rng*); */ double poissonCMF(const double, const double, int); double gamma_scalePDF(const double, const double, const double); double betaPDF(const double, const double, const double); double exponentialPDF(const double, const double); double poissonPMF(const double, const double); double geometricPDF(const double, const double); double trnormalPDF(const double, const double, const double); double normalCDF(const double, const double, const double, int); double normalPDF(const double, const double, const double); double binomialPMF(const double, const double, const double); double multinomialPMF(const unsigned int, const double*, const double*); double uniformPDF(const double, const double, const double); double logisticPDF(const double, const double, const double); double betabinomialPMF(const double, const double, const double, const double); /* double MVNPDF(Matrix*, Matrix*, Matrix*, const double, int); */ double identity(double); double logit(double); double invlogit(double); Matrix *MatrixInit(Matrix*, int, int, int*); Matrix *MatrixDestroy(Matrix*); /* Matrix *Matrix_Init(Matrix*, char*, int, int); */ /* Matrix *Matrix_Fill(Matrix*, int, int, ...); */ /* Matrix *Matrix_Destroy(Matrix*); */ /* Matrix *Matrix_Copy(Matrix*, Matrix*); */ /* Matrix *Matrix_Sub_Copy(Matrix*, Matrix*, int); */ /* Matrix *Matrix_Scalar_Multiply(Matrix*, double, Matrix*); */ /* Matrix *Matrix_Multiply(Matrix*, Matrix*, Matrix*); */ /* Matrix *Matrix_Multiply(Matrix*, Matrix*, Matrix*); */ /* Matrix *Matrix_Cholesky(Matrix*, Matrix*); */ /* Matrix *Matrix_Invert(Matrix*, Matrix*); */ /* Matrix *Matrix_Add(Matrix*, Matrix*, Matrix*); */ /* Matrix *Matrix_Add_Diagonal(Matrix*, Matrix*); */ /* Matrix *Matrix_Subtract(Matrix*, Matrix*, Matrix*); */ /* Matrix *Matrix_Transpose(Matrix*, Matrix*); */ /* double Matrix_Log_Determinant(Matrix*, int); */ /* void Matrix_Print(Matrix*); */ double rtnewt(void(*)(double, double*, double*, double*), double, double, double, double*); double rtbis( double (*)(double, double*), double, double, double, int*, double* ); size_t strlen(const char*); char *strncpy(char*, const char*, size_t); char *strcpy(char*, const char*); char *strcat(char*, const char*); char *strchr ( const char*, int ); int strcmp (const char*, const char*); void *calloc(size_t, size_t); void *malloc(size_t); void free(void*); void exit(int); double von_mises_cdf ( double x, double a, double b ); double von_mises_cdf_inv ( double cdf, double a, double b );
{ "alphanum_fraction": 0.7133449545, "avg_line_length": 36.8785714286, "ext": "h", "hexsha": "ae790a3938b4758f53122d0bfffee4ff3583d7bf", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_forks_repo_path": "func.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_issues_repo_path": "func.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_stars_repo_path": "func.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1366, "size": 5163 }
/* multifit/test.c * * Copyright (C) 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* These tests are based on the NIST Statistical Reference Datasets See http://www.nist.gov/itl/div898/strd/index.html for more information. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_multifit_nlin.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_ieee_utils.h> #include "test_longley.c" #include "test_filip.c" #include "test_pontius.c" #include "test_brown.c" #include "test_enso.c" #include "test_kirby2.c" #include "test_hahn1.c" #include "test_nelson.c" #include "test_fn.c" #include "test_estimator.c" void test_lmder (gsl_multifit_function_fdf * f, double x0[], double * X, double F[], double * cov); void test_fdf (const char * name, gsl_multifit_function_fdf * f, double x0[], double x[], double sumsq, double sigma[]); int main (void) { gsl_ieee_env_setup(); test_longley(); test_filip(); test_pontius(); test_estimator(); { gsl_multifit_function_fdf f = make_fdf (&brown_f, &brown_df, &brown_fdf, brown_N, brown_P, 0); test_lmder(&f, brown_x0, &brown_X[0][0], brown_F, &brown_cov[0][0]); } { gsl_multifit_function_fdf f = make_fdf (&enso_f, &enso_df, &enso_fdf, enso_N, enso_P, 0); test_fdf("nist-ENSO", &f, enso_x0, enso_x, enso_sumsq, enso_sigma); } { gsl_multifit_function_fdf f = make_fdf (&kirby2_f, &kirby2_df, &kirby2_fdf, kirby2_N, kirby2_P, 0); test_fdf("nist-kirby2", &f, kirby2_x0, kirby2_x, kirby2_sumsq, kirby2_sigma); } { gsl_multifit_function_fdf f = make_fdf (&hahn1_f, &hahn1_df, &hahn1_fdf, hahn1_N, hahn1_P, 0); test_fdf("nist-hahn1", &f, hahn1_x0, hahn1_x, hahn1_sumsq, hahn1_sigma); } #ifdef JUNK { gsl_multifit_function_fdf f = make_fdf (&nelson_f, &nelson_df, &nelson_fdf, nelson_N, nelson_P, 0); test_fdf("nist-nelson", &f, nelson_x0, nelson_x, nelson_sumsq, nelson_sigma); } #endif /* now summarize the results */ exit (gsl_test_summary ()); } void test_lmder (gsl_multifit_function_fdf * f, double x0[], double * X, double F[], double * cov) { const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; const size_t n = f->n; const size_t p = f->p; int status; size_t iter = 0, i; gsl_vector_view x = gsl_vector_view_array (x0, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, f, &x.vector); do { status = gsl_multifit_fdfsolver_iterate (s); for (i = 0 ; i < p; i++) { gsl_test_rel (gsl_vector_get (s->x, i), X[p*iter+i], 1e-5, "lmsder, iter=%u, x%u", iter, i); } gsl_test_rel (gsl_blas_dnrm2 (s->f), F[iter], 1e-5, "lmsder, iter=%u, f", iter); iter++; } while (iter < 20); { size_t i, j; gsl_matrix * covar = gsl_matrix_alloc (4, 4); gsl_multifit_covar (s->J, 0.0, covar); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { gsl_test_rel (gsl_matrix_get(covar,i,j), cov[i*p + j], 1e-7, "gsl_multifit_covar cov(%d,%d)", i, j) ; } } gsl_matrix_free (covar); } gsl_multifit_fdfsolver_free (s); } void test_fdf (const char * name, gsl_multifit_function_fdf * f, double x0[], double x_final[], double f_sumsq, double sigma[]) { const gsl_multifit_fdfsolver_type *T; gsl_multifit_fdfsolver *s; const size_t n = f->n; const size_t p = f->p; int status; size_t iter = 0; gsl_vector_view x = gsl_vector_view_array (x0, p); T = gsl_multifit_fdfsolver_lmsder; s = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (s, f, &x.vector); do { status = gsl_multifit_fdfsolver_iterate (s); #ifdef DEBUG printf("iter = %d status = %d |f| = %.18e x = \n", iter, status, gsl_blas_dnrm2 (s->f)); gsl_vector_fprintf(stdout, s->x, "%.8e"); #endif status = gsl_multifit_test_delta (s->dx, s->x, 0.0, 1e-7); iter++; } while (status == GSL_CONTINUE && iter < 1000); { size_t i; gsl_matrix * covar = gsl_matrix_alloc (p, p); gsl_multifit_covar (s->J, 0.0, covar); for (i = 0 ; i < p; i++) { gsl_test_rel (gsl_vector_get (s->x, i), x_final[i], 1e-5, "%s, lmsder, x%u", name, i); } { double s2 = pow(gsl_blas_dnrm2 (s->f), 2.0); gsl_test_rel (s2, f_sumsq, 1e-5, "%s, lmsder, |f|^2", name); for (i = 0; i < p; i++) { double ei = sqrt(s2/(n-p))*sqrt(gsl_matrix_get(covar,i,i)); gsl_test_rel (ei, sigma[i], 1e-4, "%s, sigma(%d)", name, i) ; } } gsl_matrix_free (covar); } /* Check that there is no hidden state, restarting should produce identical results. */ { int status0, status1; size_t i; gsl_multifit_fdfsolver *t = gsl_multifit_fdfsolver_alloc (T, n, p); gsl_multifit_fdfsolver_set (t, f, &x.vector); /* do a few extra iterations to stir things up */ gsl_multifit_fdfsolver_set (s, f, &x.vector); for (i = 0; i < 3; i++) { gsl_multifit_fdfsolver_iterate (s); } gsl_multifit_fdfsolver_set (s, f, &x.vector); do { status0 = gsl_multifit_fdfsolver_iterate (s); status1 = gsl_multifit_fdfsolver_iterate (t); gsl_test_int(status0, status1, "%s, lmsder status after set iter=%u", name, iter); for (i = 0; i < p; i++) { double sxi = gsl_vector_get(s->x,i); double txi = gsl_vector_get(t->x,i); #ifdef DEBUG printf("%d %g %g\n", i, sxi, txi); #endif gsl_test_rel(sxi, txi, 1e-15, "%s, lmsder after set, %u/%u", name, iter, i); } #ifdef DEBUG printf("iter = %d status = %d |f| = %.18e x = \n", iter, status, gsl_blas_dnrm2 (s->f)); gsl_vector_fprintf(stdout, s->x, "%.8e"); #endif status0 = gsl_multifit_test_delta (s->dx, s->x, 0.0, 1e-7); status1 = gsl_multifit_test_delta (t->dx, s->x, 0.0, 1e-7); gsl_test_int(status0, status1, "%s, lmsder test delta status after set iter=%u", name, iter); iter++; } while (status1 == GSL_CONTINUE && iter < 1000); gsl_multifit_fdfsolver_free (t); } gsl_multifit_fdfsolver_free (s); }
{ "alphanum_fraction": 0.5910423887, "avg_line_length": 26.4154929577, "ext": "c", "hexsha": "309efcf5835be820cc66b8cf110840180493117a", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/test.c", "max_line_length": 101, "max_stars_count": 14, "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_path": "folding_libs/gsl-1.14/multifit/test.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 2419, "size": 7502 }
/* specfunc/legendre_H3d.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_trig.h> #include <gsl/gsl_sf_legendre.h> #include "error.h" #include "legendre.h" /* See [Abbott+Schaefer, Ap.J. 308, 546 (1986)] for * enough details to follow what is happening here. */ /* Logarithm of normalization factor, Log[N(ell,lambda)]. * N(ell,lambda) = Product[ lambda^2 + n^2, {n,0,ell} ] * = |Gamma(ell + 1 + I lambda)|^2 lambda sinh(Pi lambda) / Pi * Assumes ell >= 0. */ static int legendre_H3d_lnnorm(const int ell, const double lambda, double * result) { double abs_lam = fabs(lambda); if(abs_lam == 0.0) { *result = 0.0; GSL_ERROR ("error", GSL_EDOM); } else if(lambda > (ell + 1.0)/GSL_ROOT3_DBL_EPSILON) { /* There is a cancellation between the sinh(Pi lambda) * term and the log(gamma(ell + 1 + i lambda) in the * result below, so we show some care and save some digits. * Note that the above guarantees that lambda is large, * since ell >= 0. We use Stirling and a simple expansion * of sinh. */ double rat = (ell+1.0)/lambda; double ln_lam2ell2 = 2.0*log(lambda) + log(1.0 + rat*rat); double lg_corrected = -2.0*(ell+1.0) + M_LNPI + (ell+0.5)*ln_lam2ell2 + 1.0/(288.0*lambda*lambda); double angle_terms = lambda * 2.0 * rat * (1.0 - rat*rat/3.0); *result = log(abs_lam) + lg_corrected + angle_terms - M_LNPI; return GSL_SUCCESS; } else { gsl_sf_result lg_r; gsl_sf_result lg_theta; gsl_sf_result ln_sinh; gsl_sf_lngamma_complex_e(ell+1.0, lambda, &lg_r, &lg_theta); gsl_sf_lnsinh_e(M_PI * abs_lam, &ln_sinh); *result = log(abs_lam) + ln_sinh.val + 2.0*lg_r.val - M_LNPI; return GSL_SUCCESS; } } /* Calculate series for small eta*lambda. * Assumes eta > 0, lambda != 0. * * This is just the defining hypergeometric for the Legendre function. * * P^{mu}_{-1/2 + I lam}(z) = 1/Gamma(l+3/2) ((z+1)/(z-1)^(mu/2) * 2F1(1/2 - I lam, 1/2 + I lam; l+3/2; (1-z)/2) * We use * z = cosh(eta) * (z-1)/2 = sinh^2(eta/2) * * And recall * H3d = sqrt(Pi Norm /(2 lam^2 sinh(eta))) P^{-l-1/2}_{-1/2 + I lam}(cosh(eta)) */ static int legendre_H3d_series(const int ell, const double lambda, const double eta, gsl_sf_result * result) { const int nmax = 5000; const double shheta = sinh(0.5*eta); const double ln_zp1 = M_LN2 + log(1.0 + shheta*shheta); const double ln_zm1 = M_LN2 + 2.0*log(shheta); const double zeta = -shheta*shheta; gsl_sf_result lg_lp32; double term = 1.0; double sum = 1.0; double sum_err = 0.0; gsl_sf_result lnsheta; double lnN; double lnpre_val, lnpre_err, lnprepow; int stat_e; int n; gsl_sf_lngamma_e(ell + 3.0/2.0, &lg_lp32); gsl_sf_lnsinh_e(eta, &lnsheta); legendre_H3d_lnnorm(ell, lambda, &lnN); lnprepow = 0.5*(ell + 0.5) * (ln_zm1 - ln_zp1); lnpre_val = lnprepow + 0.5*(lnN + M_LNPI - M_LN2 - lnsheta.val) - lg_lp32.val - log(fabs(lambda)); lnpre_err = lnsheta.err + lg_lp32.err + GSL_DBL_EPSILON * fabs(lnpre_val); lnpre_err += 2.0*GSL_DBL_EPSILON * (fabs(lnN) + M_LNPI + M_LN2); lnpre_err += 2.0*GSL_DBL_EPSILON * (0.5*(ell + 0.5) * (fabs(ln_zm1) + fabs(ln_zp1))); for(n=1; n<nmax; n++) { double aR = n - 0.5; term *= (aR*aR + lambda*lambda)*zeta/(ell + n + 0.5)/n; sum += term; sum_err += 2.0*GSL_DBL_EPSILON*fabs(term); if(fabs(term/sum) < 2.0 * GSL_DBL_EPSILON) break; } stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, sum, fabs(term)+sum_err, result); return GSL_ERROR_SELECT_2(stat_e, (n==nmax ? GSL_EMAXITER : GSL_SUCCESS)); } /* Evaluate legendre_H3d(ell+1)/legendre_H3d(ell) * by continued fraction. */ #if 0 static int legendre_H3d_CF1(const int ell, const double lambda, const double coth_eta, gsl_sf_result * result) { const double RECUR_BIG = GSL_SQRT_DBL_MAX; const int maxiter = 5000; int n = 1; double Anm2 = 1.0; double Bnm2 = 0.0; double Anm1 = 0.0; double Bnm1 = 1.0; double a1 = hypot(lambda, ell+1.0); double b1 = (2.0*ell + 3.0) * coth_eta; double An = b1*Anm1 + a1*Anm2; double Bn = b1*Bnm1 + a1*Bnm2; double an, bn; double fn = An/Bn; while(n < maxiter) { double old_fn; double del; n++; Anm2 = Anm1; Bnm2 = Bnm1; Anm1 = An; Bnm1 = Bn; an = -(lambda*lambda + ((double)ell + n)*((double)ell + n)); bn = (2.0*ell + 2.0*n + 1.0) * coth_eta; An = bn*Anm1 + an*Anm2; Bn = bn*Bnm1 + an*Bnm2; if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) { An /= RECUR_BIG; Bn /= RECUR_BIG; Anm1 /= RECUR_BIG; Bnm1 /= RECUR_BIG; Anm2 /= RECUR_BIG; Bnm2 /= RECUR_BIG; } old_fn = fn; fn = An/Bn; del = old_fn/fn; if(fabs(del - 1.0) < 4.0*GSL_DBL_EPSILON) break; } result->val = fn; result->err = 2.0 * GSL_DBL_EPSILON * (sqrt(n)+1.0) * fabs(fn); if(n >= maxiter) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } #endif /* 0 */ /* Evaluate legendre_H3d(ell+1)/legendre_H3d(ell) * by continued fraction. Use the Gautschi (Euler) * equivalent series. */ /* FIXME: Maybe we have to worry about this. The a_k are * not positive and there can be a blow-up. It happened * for J_nu once or twice. Then we should probably use * the method above. */ static int legendre_H3d_CF1_ser(const int ell, const double lambda, const double coth_eta, gsl_sf_result * result) { const double pre = hypot(lambda, ell+1.0)/((2.0*ell+3)*coth_eta); const int maxk = 20000; double tk = 1.0; double sum = 1.0; double rhok = 0.0; double sum_err = 0.0; int k; for(k=1; k<maxk; k++) { double tlk = (2.0*ell + 1.0 + 2.0*k); double l1k = (ell + 1.0 + k); double ak = -(lambda*lambda + l1k*l1k)/(tlk*(tlk+2.0)*coth_eta*coth_eta); rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok)); tk *= rhok; sum += tk; sum_err += 2.0 * GSL_DBL_EPSILON * k * fabs(tk); if(fabs(tk/sum) < GSL_DBL_EPSILON) break; } result->val = pre * sum; result->err = fabs(pre * tk); result->err += fabs(pre * sum_err); result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val); if(k >= maxk) GSL_ERROR ("error", GSL_EMAXITER); else return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_legendre_H3d_0_e(const double lambda, const double eta, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(eta < 0.0) { DOMAIN_ERROR(result); } else if(eta == 0.0 || lambda == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else { const double lam_eta = lambda * eta; gsl_sf_result s; gsl_sf_sin_err_e(lam_eta, 2.0*GSL_DBL_EPSILON * fabs(lam_eta), &s); if(eta > -0.5*GSL_LOG_DBL_EPSILON) { double f = 2.0 / lambda * exp(-eta); result->val = f * s.val; result->err = fabs(f * s.val) * (fabs(eta) + 1.0) * GSL_DBL_EPSILON; result->err += fabs(f) * s.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } else { double f = 1.0/(lambda*sinh(eta)); result->val = f * s.val; result->err = fabs(f * s.val) * (fabs(eta) + 1.0) * GSL_DBL_EPSILON; result->err += fabs(f) * s.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); } return GSL_SUCCESS; } } int gsl_sf_legendre_H3d_1_e(const double lambda, const double eta, gsl_sf_result * result) { const double xi = fabs(eta*lambda); const double lsq = lambda*lambda; const double lsqp1 = lsq + 1.0; /* CHECK_POINTER(result) */ if(eta < 0.0) { DOMAIN_ERROR(result); } else if(eta == 0.0 || lambda == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(xi < GSL_ROOT5_DBL_EPSILON && eta < GSL_ROOT5_DBL_EPSILON) { double etasq = eta*eta; double xisq = xi*xi; double term1 = (etasq + xisq)/3.0; double term2 = -(2.0*etasq*etasq + 5.0*etasq*xisq + 3.0*xisq*xisq)/90.0; double sinh_term = 1.0 - eta*eta/6.0 * (1.0 - 7.0/60.0*eta*eta); double pre = sinh_term/sqrt(lsqp1) / eta; result->val = pre * (term1 + term2); result->err = pre * GSL_DBL_EPSILON * (fabs(term1) + fabs(term2)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { double sin_term; /* Sin(xi)/xi */ double cos_term; /* Cos(xi) */ double coth_term; /* eta/Tanh(eta) */ double sinh_term; /* eta/Sinh(eta) */ double sin_term_err; double cos_term_err; double t1; double pre_val; double pre_err; double term1; double term2; if(xi < GSL_ROOT5_DBL_EPSILON) { sin_term = 1.0 - xi*xi/6.0 * (1.0 - xi*xi/20.0); cos_term = 1.0 - 0.5*xi*xi * (1.0 - xi*xi/12.0); sin_term_err = GSL_DBL_EPSILON; cos_term_err = GSL_DBL_EPSILON; } else { gsl_sf_result sin_xi_result; gsl_sf_result cos_xi_result; gsl_sf_sin_e(xi, &sin_xi_result); gsl_sf_cos_e(xi, &cos_xi_result); sin_term = sin_xi_result.val/xi; cos_term = cos_xi_result.val; sin_term_err = sin_xi_result.err/fabs(xi); cos_term_err = cos_xi_result.err; } if(eta < GSL_ROOT5_DBL_EPSILON) { coth_term = 1.0 + eta*eta/3.0 * (1.0 - eta*eta/15.0); sinh_term = 1.0 - eta*eta/6.0 * (1.0 - 7.0/60.0*eta*eta); } else { coth_term = eta/tanh(eta); sinh_term = eta/sinh(eta); } t1 = sqrt(lsqp1) * eta; pre_val = sinh_term/t1; pre_err = 2.0 * GSL_DBL_EPSILON * fabs(pre_val); term1 = sin_term*coth_term; term2 = cos_term; result->val = pre_val * (term1 - term2); result->err = pre_err * fabs(term1 - term2); result->err += pre_val * (sin_term_err * coth_term + cos_term_err); result->err += pre_val * fabs(term1-term2) * (fabs(eta) + 1.0) * GSL_DBL_EPSILON; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_legendre_H3d_e(const int ell, const double lambda, const double eta, gsl_sf_result * result) { const double abs_lam = fabs(lambda); const double lsq = abs_lam*abs_lam; const double xi = abs_lam * eta; const double cosh_eta = cosh(eta); /* CHECK_POINTER(result) */ if(eta < 0.0) { DOMAIN_ERROR(result); } else if(eta > GSL_LOG_DBL_MAX) { /* cosh(eta) is too big. */ OVERFLOW_ERROR(result); } else if(ell == 0) { return gsl_sf_legendre_H3d_0_e(lambda, eta, result); } else if(ell == 1) { return gsl_sf_legendre_H3d_1_e(lambda, eta, result); } else if(eta == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(xi < 1.0) { return legendre_H3d_series(ell, lambda, eta, result); } else if((ell*ell+lsq)/sqrt(1.0+lsq)/(cosh_eta*cosh_eta) < 5.0*GSL_ROOT3_DBL_EPSILON) { /* Large argument. */ gsl_sf_result P; double lm; int stat_P = gsl_sf_conicalP_large_x_e(-ell-0.5, lambda, cosh_eta, &P, &lm); if(P.val == 0.0) { result->val = 0.0; result->err = 0.0; return stat_P; } else { double lnN; gsl_sf_result lnsh; double ln_abslam; double lnpre_val, lnpre_err; int stat_e; gsl_sf_lnsinh_e(eta, &lnsh); legendre_H3d_lnnorm(ell, lambda, &lnN); ln_abslam = log(abs_lam); lnpre_val = 0.5*(M_LNPI + lnN - M_LN2 - lnsh.val) - ln_abslam; lnpre_err = lnsh.err; lnpre_err += 2.0 * GSL_DBL_EPSILON * (0.5*(M_LNPI + M_LN2 + fabs(lnN)) + fabs(ln_abslam)); lnpre_err += 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val); stat_e = gsl_sf_exp_mult_err_e(lnpre_val + lm, lnpre_err, P.val, P.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_P); } } else if(abs_lam > 1000.0*ell*ell) { /* Large degree. */ gsl_sf_result P; double lm; int stat_P = gsl_sf_conicalP_xgt1_neg_mu_largetau_e(ell+0.5, lambda, cosh_eta, eta, &P, &lm); if(P.val == 0.0) { result->val = 0.0; result->err = 0.0; return stat_P; } else { double lnN; gsl_sf_result lnsh; double ln_abslam; double lnpre_val, lnpre_err; int stat_e; gsl_sf_lnsinh_e(eta, &lnsh); legendre_H3d_lnnorm(ell, lambda, &lnN); ln_abslam = log(abs_lam); lnpre_val = 0.5*(M_LNPI + lnN - M_LN2 - lnsh.val) - ln_abslam; lnpre_err = lnsh.err; lnpre_err += GSL_DBL_EPSILON * (0.5*(M_LNPI + M_LN2 + fabs(lnN)) + fabs(ln_abslam)); lnpre_err += 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val); stat_e = gsl_sf_exp_mult_err_e(lnpre_val + lm, lnpre_err, P.val, P.err, result); return GSL_ERROR_SELECT_2(stat_e, stat_P); } } else { /* Backward recurrence. */ const double coth_eta = 1.0/tanh(eta); const double coth_err_mult = fabs(eta) + 1.0; gsl_sf_result rH; int stat_CF1 = legendre_H3d_CF1_ser(ell, lambda, coth_eta, &rH); double Hlm1; double Hl = GSL_SQRT_DBL_MIN; double Hlp1 = rH.val * Hl; int lp; for(lp=ell; lp>0; lp--) { double root_term_0 = hypot(lambda,lp); double root_term_1 = hypot(lambda,lp+1.0); Hlm1 = ((2.0*lp + 1.0)*coth_eta*Hl - root_term_1 * Hlp1)/root_term_0; Hlp1 = Hl; Hl = Hlm1; } if(fabs(Hl) > fabs(Hlp1)) { gsl_sf_result H0; int stat_H0 = gsl_sf_legendre_H3d_0_e(lambda, eta, &H0); result->val = GSL_SQRT_DBL_MIN/Hl * H0.val; result->err = GSL_SQRT_DBL_MIN/fabs(Hl) * H0.err; result->err += fabs(rH.err/rH.val) * (ell+1.0) * coth_err_mult * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_H0, stat_CF1); } else { gsl_sf_result H1; int stat_H1 = gsl_sf_legendre_H3d_1_e(lambda, eta, &H1); result->val = GSL_SQRT_DBL_MIN/Hlp1 * H1.val; result->err = GSL_SQRT_DBL_MIN/fabs(Hlp1) * H1.err; result->err += fabs(rH.err/rH.val) * (ell+1.0) * coth_err_mult * fabs(result->val); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_H1, stat_CF1); } } } int gsl_sf_legendre_H3d_array(const int lmax, const double lambda, const double eta, double * result_array) { /* CHECK_POINTER(result_array) */ if(eta < 0.0 || lmax < 0) { int ell; for(ell=0; ell<=lmax; ell++) result_array[ell] = 0.0; GSL_ERROR ("domain error", GSL_EDOM); } else if(eta > GSL_LOG_DBL_MAX) { /* cosh(eta) is too big. */ int ell; for(ell=0; ell<=lmax; ell++) result_array[ell] = 0.0; GSL_ERROR ("overflow", GSL_EOVRFLW); } else if(lmax == 0) { gsl_sf_result H0; int stat = gsl_sf_legendre_H3d_e(0, lambda, eta, &H0); result_array[0] = H0.val; return stat; } else { /* Not the most efficient method. But what the hell... it's simple. */ gsl_sf_result r_Hlp1; gsl_sf_result r_Hl; int stat_lmax = gsl_sf_legendre_H3d_e(lmax, lambda, eta, &r_Hlp1); int stat_lmaxm1 = gsl_sf_legendre_H3d_e(lmax-1, lambda, eta, &r_Hl); int stat_max = GSL_ERROR_SELECT_2(stat_lmax, stat_lmaxm1); const double coth_eta = 1.0/tanh(eta); int stat_recursion = GSL_SUCCESS; double Hlp1 = r_Hlp1.val; double Hl = r_Hl.val; double Hlm1; int ell; result_array[lmax] = Hlp1; result_array[lmax-1] = Hl; for(ell=lmax-1; ell>0; ell--) { double root_term_0 = hypot(lambda,ell); double root_term_1 = hypot(lambda,ell+1.0); Hlm1 = ((2.0*ell + 1.0)*coth_eta*Hl - root_term_1 * Hlp1)/root_term_0; result_array[ell-1] = Hlm1; if(!(Hlm1 < GSL_DBL_MAX)) stat_recursion = GSL_EOVRFLW; Hlp1 = Hl; Hl = Hlm1; } return GSL_ERROR_SELECT_2(stat_recursion, stat_max); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_legendre_H3d_0(const double lambda, const double eta) { EVAL_RESULT(gsl_sf_legendre_H3d_0_e(lambda, eta, &result)); } double gsl_sf_legendre_H3d_1(const double lambda, const double eta) { EVAL_RESULT(gsl_sf_legendre_H3d_1_e(lambda, eta, &result)); } double gsl_sf_legendre_H3d(const int l, const double lambda, const double eta) { EVAL_RESULT(gsl_sf_legendre_H3d_e(l, lambda, eta, &result)); }
{ "alphanum_fraction": 0.6122156649, "avg_line_length": 30.6731107206, "ext": "c", "hexsha": "8b58423dd8dc60738858af3833d0fe10d006e60d", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/legendre_H3d.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/legendre_H3d.c", "max_line_length": 103, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/legendre_H3d.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 6154, "size": 17453 }
/** */ #include "aXe_grism.h" #include <gsl/gsl_spline.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include "fringe_conf.h" #include "fringe_model.h" #include "fringe_utils.h" #define MIN(x,y) (((x)<(y))?(x):(y)) #define MAX(x,y) (((x)>(y))?(x):(y)) /** * Function: fringe_correct_PET * Performs fringe corrections to PET pixel lists * * The main function to compute and perform the fringe * correction to a list of PET pixels. for every pixel in * the PET list the pixel throughput function is * computed, and the relevant information from * the fringing model is extracted. Then the fringe * amplitude is computed and the count value of the pixel * is corrected. Also the PET pixel list is simultaneously * parsed and corrected for the fringing. * * Parameters: * @param fconf - the fringe configuration file * @param act_beam - the beam aperture * @param obj_pet - the PET pixel * @param bck_pet - the PET pixel */ void fringe_correct_PET(const fringe_conf *fconf, const beam act_beam, ap_pixel *obj_pet, ap_pixel *bck_pet) { ap_pixel *obj_pix=NULL; ap_pixel *bck_pix=NULL; //d_point angles; pixel_tput *p_tput ; gsl_vector **tput_vectors=NULL; //int ii=0; //int jj=0; int index; int pix_index; double lambda_mean; double pixel_ampl; double fringe_factor; double fringe_tot; optical_property *optprops; // allocate the pixel throughput structure p_tput = alloc_pixel_tput(); // allocate memory for the optical property structure optprops = alloc_optprops_list(fconf); // compute the mean wavelength lambda_mean = (gsl_vector_get(fconf->fringe_range, 0) + (gsl_vector_get(fconf->fringe_range, 1) - gsl_vector_get(fconf->fringe_range, 0))/2.0)/1.0e+04; // initialize some values in the optical property list init_optprops_list(fconf, lambda_mean, optprops); // initialize the PET pixel storages obj_pix = obj_pet; bck_pix = bck_pet; fringe_tot = 0.0; pix_index = 0; // go over the whole PET list while (obj_pix->p_x != -1) { // check whether the pixel has to be fringe corrected // at all, based on boundaries given in the configuration if ( obj_pix->lambda < gsl_vector_get(fconf->fringe_range, 0) || obj_pix->lambda > gsl_vector_get(fconf->fringe_range, 1) || obj_pix->dlambda > fconf->max_dispersion) { // count up the object PET obj_pix++; // count up the background PET if (bck_pet) bck_pix++; // jump to the next PET pixel continue; } // determine the filter throughput values // tput_vectors = evaluate_pixel_throughput(fconf, act_beam, obj_pix); // for the ISR with the WFC value tput_vectors = get_gauss_throughput(fconf, obj_pix, 80.0); // fill the optical thickness of the layers // into the structure fill_optprops_thickness(fconf->opt_layers, obj_pix->p_x, obj_pix->p_y, optprops); pixel_ampl = 0.0; for (index=0; index < (int)tput_vectors[0]->size; index++) { // fill all information in the optical // property list fill_optprops_all(fconf->opt_layers, gsl_vector_get(tput_vectors[0],index), optprops); // compute and add the contribution at a wavelength pixel_ampl += gsl_vector_get(tput_vectors[1],index)* fringe_contrib_single(optprops, fconf); } //put together the fringe correction factor fringe_factor = fconf->fringe_amp * pixel_ampl + 1.0; #ifdef DEBUGFCONF fprintf(stderr, "Wavelength: %f, dispersion: %f, fringe factor: %f, (x,y): (%i, %i)\n", obj_pix->lambda, obj_pix->dlambda, fringe_factor, obj_pix->p_x, obj_pix->p_y); #endif // correct the object PET obj_pix->count /= fringe_factor; //obj_pix->count = fringe_factor; //fprintf(stdout, "%e ",obj_pix->count); fringe_tot += fringe_factor; pix_index++; // treat the background PET pixel if (bck_pet) { if (bck_pix->p_x != obj_pix->p_x || bck_pix->p_y != obj_pix->p_y) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "aXe_FRINGECORR: The sequence of pixels\n" "in the object PET and background PET differs.\n" "Something must be wrong!\n"); // correct also the background PET bck_pix->count /= fringe_factor; // count up the background PET bck_pix++; } // count up the object PET obj_pix++; // obj_pix->p_x = -1; } // if (pix_index) // fprintf(stdout,"Mean fringe factor: %f\n", fringe_tot/(double)pix_index); if (tput_vectors) { // release the memory in the vectors gsl_vector_free(tput_vectors[0]); gsl_vector_free(tput_vectors[1]); free(tput_vectors); } // free the optical property structure free_optprops_list(optprops); // free the memory free_pixel_tput(p_tput); } /** * Function: evaluate_pixel_throughput * Computes the wavelength and filter throughputs for a PET pixel. * * The function computes and returns two vector, one with wavelength * steps and the second with the pixel throughputs at those wavelengths. * This data is computed to a single PET pixel according to the settings * in the fringe configuration file. * * Parameters: * @param fconf - the fringe configuration file * @param act_beam - the beam aperture * @param obj_pix - the PET pixel * * Returns: * @return double_vector - the wavelength and filter throughput steps */ gsl_vector ** evaluate_pixel_throughput(const fringe_conf *fconf, const beam act_beam, const ap_pixel *obj_pix) { pixel_tput *p_tput ; gsl_vector **double_vector; gsl_vector *lambda_values; gsl_vector *through_values; interpolator *interp; double stepsize; double lambda_act; double through_act; double through_tot; double abs_min; double abs_max; int index; // allocate the pixel throughput structure p_tput = alloc_pixel_tput(); // allocate the space for the vectors lambda_values = gsl_vector_alloc(fconf->num_steps + 1); through_values = gsl_vector_alloc(fconf->num_steps + 1); // allocate space for the return vector double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *)); compute_pixel_tput(act_beam, obj_pix, p_tput); #ifdef DEBUGFCONF print_pixel_tput(p_tput); #endif // convert the pixel throughput information // into an interplator interp = create_interp_tput(p_tput); abs_min = MAX(interp->xmin, gsl_vector_get(fconf->fringe_range, 0)); abs_max = MIN(interp->xmax, gsl_vector_get(fconf->fringe_range, 1)); // compute the steps in wavelength stepsize = (abs_max - abs_min)/(double)fconf->num_steps; // set the lower wavelength end lambda_act = abs_min; // loop over the wavelength through_tot = 0.0; for (index=0; index < fconf->num_steps; index++) { // set the wavelength value gsl_vector_set(lambda_values, index, lambda_act); // compute the throughput through_act = eval_interp(interp, lambda_act); // compute the total throughput through_tot += through_act; // set the thoughput value gsl_vector_set(through_values, index, through_act); lambda_act += stepsize; } // treat the last step separately, avoiding // to leave the allowed interpolation range // due to rounding errors gsl_vector_set(lambda_values, fconf->num_steps, abs_max); through_act = eval_interp(interp, abs_max); through_tot += through_act; gsl_vector_set(through_values, fconf->num_steps, through_act); for (index=0; index < (int)through_values->size; index++) { // normalize the filter throughput values gsl_vector_set(through_values, index, gsl_vector_get(through_values, index)/through_tot); // convert the wavelength from AA to micron gsl_vector_set(lambda_values, index, gsl_vector_get(lambda_values, index)*1.0e-04); } #ifdef DEBUGFCONF through_tot = 0.0; for (index=0; index < through_values->size; index++) { fprintf(stderr, "Wavelength: %f, Throughput: %f\n", gsl_vector_get(lambda_values, index), gsl_vector_get(through_values, index)); through_tot += gsl_vector_get(through_values, index); } fprintf(stderr, "Total throughput: %f\n", through_tot); #endif // build up the output array double_vector[0] = lambda_values; double_vector[1] = through_values; // free the memory of the interpolator free_interp(interp); // free the memory of the pixel throughput free_pixel_tput(p_tput); // return the two gsl vectors return double_vector; } /** * Function: get_gauss_throughput * * Parameters: * @param fconf - the fringe configuration file * @param act_beam - the beam aperture * @param obj_pix - the PET pixel * * Returns: * @return double_vector - the wavelength and filter throughput steps */ gsl_vector ** get_gauss_throughput(const fringe_conf *fconf, const ap_pixel *obj_pix, const double fwhm) { pixel_tput *p_tput ; gsl_vector **double_vector; gsl_vector *lambda_values; gsl_vector *through_values; //interpolator *interp; double stepsize; double lambda_act; double through_act; double through_tot; double abs_min; double abs_max; double sigma; double arg; int index; // convert the FWHM into sigma sigma = fwhm / 2.35482; // allocate the pixel throughput structure p_tput = alloc_pixel_tput(); // allocate the space for the vectors lambda_values = gsl_vector_alloc(fconf->num_steps + 1); through_values = gsl_vector_alloc(fconf->num_steps + 1); // allocate space for the return vector double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *)); // compute the minimum and maximum wavelength abs_min = MAX(obj_pix->lambda - 2.5 * fwhm, gsl_vector_get(fconf->fringe_range, 0)); abs_max = MIN(obj_pix->lambda + 2.5 * fwhm, gsl_vector_get(fconf->fringe_range, 1)); // compute the steps in wavelength stepsize = (abs_max - abs_min)/(double)fconf->num_steps; // set the lower wavelength end lambda_act = abs_min; // loop over the wavelength through_tot = 0.0; for (index=0; index < fconf->num_steps; index++) { // set the wavelength value gsl_vector_set(lambda_values, index, lambda_act); // z=(coord-g(2))/g(3) // sumgauss=sumgauss+DBLE(g(1)*EXP(-0.5*z**2)) arg = (lambda_act - obj_pix->lambda) / sigma; // compute the throughput through_act = exp(-0.5*arg*arg); // compute the total throughput through_tot += through_act; // set the thoughput value gsl_vector_set(through_values, index, through_act); // increment the wavelength lambda_act += stepsize; } // treat the last step separately, avoiding // to leave the allowed interpolation range // due to rounding errors gsl_vector_set(lambda_values, fconf->num_steps, abs_max); arg = (abs_max - obj_pix->lambda) / sigma; through_act = exp(-0.5*arg*arg); through_tot += through_act; gsl_vector_set(through_values, fconf->num_steps, through_act); for (index=0; index < (int)through_values->size; index++) { // normalize the filter throughput values gsl_vector_set(through_values, index, gsl_vector_get(through_values, index)/through_tot); // convert the wavelength from AA to micron gsl_vector_set(lambda_values, index, gsl_vector_get(lambda_values, index)*1.0e-04); } #ifdef DEBUGFCONF through_tot = 0.0; for (index=0; index < through_values->size; index++) { fprintf(stderr, "Wavelength: %f, Throughput: %f\n", gsl_vector_get(lambda_values, index), gsl_vector_get(through_values, index)); through_tot += gsl_vector_get(through_values, index); } fprintf(stderr, "Total throughput: %f\n", through_tot); #endif // build up the output array double_vector[0] = lambda_values; double_vector[1] = through_values; return double_vector; } /** * Function: create_interp_tput * The function creates and returns an interpolator * for a pixel throughput function. The interpolator * structure is allocated, data is filled in and * finally initialized. * * Parameters: * @param p_tput - the pixel throughput structure * * Returns: * @return interp - the new interpolator */ interpolator * create_interp_tput(const pixel_tput *p_tput) { interpolator *interp; double *xvals; double *yvals; // allocate memory for the independent values xvals = (double *) malloc(4 * sizeof(double)); if (!xvals) { aXe_message (aXe_M_ERROR, __FILE__, __LINE__, "Memory allocation failed"); } // allocate memory for the dependent values yvals = (double *) malloc(4 * sizeof(double)); if (!yvals) { aXe_message (aXe_M_ERROR, __FILE__, __LINE__, "Memory allocation failed"); } // set the independent vector values xvals[0] = gsl_vector_get(p_tput->lambda_values, 0); xvals[1] = gsl_vector_get(p_tput->lambda_values, 1); xvals[2] = gsl_vector_get(p_tput->lambda_values, 2); xvals[3] = gsl_vector_get(p_tput->lambda_values, 3); // set the dependent vector values yvals[0] = 0.0; yvals[1] = p_tput->tp_max; yvals[2] = p_tput->tp_max; yvals[3] = 0.0; // create the interpolator interp = create_interp(4, FILTER_INTERP_TYPE, xvals, yvals); // return the interpolator return interp; } /** * Function: compute_pixel_tput * The function computes all relevant data to characterize * the pixel throughput function for an individual PET pixel. * The information is written into a pixel throughput structure. * * Parameters: * @param act_beam - the beam aperture * @param obj_pix - the PET pixel * @param p_tput - the pixel throughput structure */ void compute_pixel_tput(const beam act_beam, const ap_pixel *obj_pix, pixel_tput *p_tput) { d_point angles; double theta_2a; double theta_3a; double theta_1b; double theta_2b; double sin_theta_2a; double sin_theta_3a; double sin_theta_1b; double cos_theta_1b; double sin_theta_2b; double dist1; double dist2; // compute the anngles alpha and beta angles = compute_tput_angles(act_beam, obj_pix); // the computation of p_min-p3 in the // design document theta_1b = M_PI_2 + angles.x - angles.y; theta_2b = angles.y; // compute the sin's and cos's neede sin_theta_1b = sin(theta_1b); cos_theta_1b = cos(theta_1b); sin_theta_2b = sin(theta_2b); // compute one delta dist2 = obj_pix->dlambda * sin_theta_1b / sin_theta_2b; // the computation of p_h-p0 in the // design document theta_2a = M_PI - angles.y; theta_3a = angles.y - angles.x - M_PI_4; // next line due to sin(angle) = sin(180-angle) sin_theta_2a = sin_theta_2b; sin_theta_3a = sin(theta_3a); // compute the second delta dist1 = obj_pix->dlambda * M_SQRT1_2 * sin_theta_3a / sin_theta_2a; // determine the maximum throughput p_tput->tp_max = 1.0/MAX(fabs(sin_theta_1b), fabs(cos_theta_1b)); // put together the distances, using // the deltas and the dispersion gsl_vector_set(p_tput->lambda_values, 0, obj_pix->lambda - dist1 - dist2); gsl_vector_set(p_tput->lambda_values, 1, obj_pix->lambda - dist1); gsl_vector_set(p_tput->lambda_values, 2, obj_pix->lambda + dist1); gsl_vector_set(p_tput->lambda_values, 3, obj_pix->lambda + dist1 + dist2); // sort the distances gsl_sort_vector(p_tput->lambda_values); } /** * Function: compute_tput_angles * The function computes the angles which characterize * a pixel in the lambda-cross dispersion plane. * In detail this is the angle between the lambda-axis * and the x-axis, and the angle between the lambda abd * the cross dispersion axis. * The two angles are computed from the basic pixel * and beam data. * * * Parameters: * @param act_beam - the beam aperture * @param act_pet - the PET pixel * * Returns: * @return angles - the relevant pixel angles */ d_point compute_tput_angles(const beam act_beam, const ap_pixel *act_pet) { d_point angles; // compute the angle 'alpha' between lambda-axis and // x-axis angles.x = -atan2(act_beam.spec_trace->deriv(act_pet->xi, act_beam.spec_trace->data),1.0); // compute the angle beta between lambda and cross dispersion axis angles.y = act_beam.orient + angles.x; // return the two angles return angles; } /** * Function: alloc_pixel_tput * The function allocates and returns memory * for a pixel throughput function * * Returns: * @return p_tput -the new allocated pixel throughput structure */ pixel_tput * alloc_pixel_tput() { pixel_tput *p_tput; // allcoate the pointer p_tput = (pixel_tput *) malloc(sizeof(pixel_tput)); // allocate the vector in the structure p_tput->lambda_values = gsl_vector_alloc(4); // return the structure return p_tput; } /** * Function: print_pixel_tput * The function prints the content of a pixel throughput * structure onto the screen. * * Parameters: * @param p_tput - the pixel throughput structure */ void print_pixel_tput(pixel_tput *p_tput) { fprintf(stdout, "l_min: %f, l_1: %f, l_2: %f, l_max: %f; tp_max: %f\n\n", gsl_vector_get(p_tput->lambda_values,0), gsl_vector_get(p_tput->lambda_values,1), gsl_vector_get(p_tput->lambda_values,2), gsl_vector_get(p_tput->lambda_values,3), p_tput->tp_max); } /** * Function: free_pixel_tput * The function releases the memory allocated * in a pixel throughput function. * * Parameters: * @param p_tput - the pixel throughput structure */ void free_pixel_tput(pixel_tput *p_tput) { // free the gsl-vector gsl_vector_free(p_tput->lambda_values); // free everything free(p_tput); // set it to NULL p_tput = NULL; }
{ "alphanum_fraction": 0.6940071959, "avg_line_length": 26.6686656672, "ext": "c", "hexsha": "7864cd54dddb9eb694f0d47818aecff7f2c0945c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/fringe_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/fringe_utils.c", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/fringe_utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4830, "size": 17788 }
/** * * @file qwrapper_dgemm_tile.c * * PLASMA core_blas quark wrapper * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mark Gates * @date 2010-11-15 * @generated d Tue Jan 7 11:44:59 2014 * **/ #include <cblas.h> #include "common.h" /***************************************************************************//** * * Version of dgemm for tile storage, to avoid dependency problem when * computations are done within the tile. alpha and beta are passed as * pointers so they can depend on runtime values. * * @param[in] Alock * Pointer to tile owning submatrix A. * * @param[in] Block * Pointer to tile owning submatrix B. * * @param[in] Clock * Pointer to tile owning submatrix C. * **/ void QUARK_CORE_dgemm_tile(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum transA, PLASMA_enum transB, int m, int n, int k, int nb, const double *alpha, const double *A, int lda, const double *B, int ldb, const double *beta, double *C, int ldc, const double *Alock, const double *Block, const double *Clock) { DAG_CORE_GEMM; QUARK_Insert_Task(quark, CORE_dgemm_tile_quark, task_flags, sizeof(PLASMA_enum), &transA, VALUE, sizeof(PLASMA_enum), &transB, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(int), &k, VALUE, sizeof(double), alpha, INPUT, sizeof(double)*nb*nb, A, NODEP, /* input; see Alock */ sizeof(int), &lda, VALUE, sizeof(double)*nb*nb, B, NODEP, /* input; see Block */ sizeof(int), &ldb, VALUE, sizeof(double), beta, INPUT, sizeof(double)*nb*nb, C, NODEP, /* inout; see Clock */ sizeof(int), &ldc, VALUE, sizeof(double)*nb*nb, Alock, INPUT, sizeof(double)*nb, Block, INPUT, sizeof(double)*nb, Clock, INOUT, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dgemm_tile_quark = PCORE_dgemm_tile_quark #define CORE_dgemm_tile_quark PCORE_dgemm_tile_quark #endif void CORE_dgemm_tile_quark(Quark *quark) { PLASMA_enum transA, transB; int m, n, k, lda, ldb, ldc; const double *alpha, *beta; const double *A, *B; double *C; quark_unpack_args_13( quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc ); cblas_dgemm( CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, m, n, k, (*alpha), A, lda, B, ldb, (*beta), C, ldc ); }
{ "alphanum_fraction": 0.4886083744, "avg_line_length": 36.4943820225, "ext": "c", "hexsha": "08a5a574802c28c40f2b6ef39f9e51b40f3c45f0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas-qwrapper/qwrapper_dgemm_tile.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas-qwrapper/qwrapper_dgemm_tile.c", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_dgemm_tile.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 798, "size": 3248 }
//Converts LSFs (line spectral frequencies) to polynomial representation along cols or rows of X. //Works by getting p_sym and p_asym and then roots and then lsf2poly. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifdef __cplusplus namespace ov { extern "C" { #endif int lsf2poly_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim); int lsf2poly_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim); int lsf2poly_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim) { const float z = 0.0f, o = 1.0f; const int F = (dim==0) ? R : C; //num LSFs const int nr = 2*F + 2; //length roots const int P = F + 2; //length psym and pasym const int Po = P - 1; //num output poly coeffs int r, c, p, f; float *roots, *psym, *pasym; //Checks if (R<1) { fprintf(stderr,"error in lsf2poly_s: nrows X must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in lsf2poly_s: ncols X must be positive\n"); return 1; } //Initialize if (!(psym=(float *)malloc((size_t)(2*P)*sizeof(float)))) { fprintf(stderr,"error in lsf2poly_s: problem with malloc. "); perror("malloc"); return 1; } if (!(pasym=(float *)malloc((size_t)(2*P)*sizeof(float)))) { fprintf(stderr,"error in lsf2poly_s: problem with malloc. "); perror("malloc"); return 1; } if (!(roots=(float *)malloc((size_t)(2*nr)*sizeof(float)))) { fprintf(stderr,"error in lsf2poly_s: problem with malloc. "); perror("malloc"); return 1; } roots[0] = o; roots[nr] = -o; roots[1] = roots[nr+1] = z; if (dim==0) { if (iscolmajor) { //cblas_scopy(C,&o,0,Y,Po); for (c=0; c<C; c++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cosf(X[f+c*R]); roots[2*f+3] = sinf(X[f+c*R]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_scopy(2*P,&z,0,psym,1); cblas_scopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (r=0; r<P-1; r++) { for (p=r+1; p>0; p--) { pasym[2*p] = fmaf(-roots[4*r],pasym[2*p-2],fmaf(roots[4*r+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fmaf(-roots[4*r],pasym[2*p-1],fmaf(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fmaf(-roots[4*r+2],psym[2*p-2],fmaf(roots[4*r+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fmaf(-roots[4*r+2],psym[2*p-1],fmaf(-roots[4*r+3],psym[2*p-2],psym[2*p+1])); } } for (r=0; r<Po; r++) { Y[r+c*Po] = 0.5f*(psym[2*(Po-r)]-pasym[2*(Po-r)]); } } } else { //cblas_scopy(C,&o,0,Y,1); for (c=0; c<C; c++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cosf(X[c+f*C]); roots[2*f+3] = sinf(X[c+f*C]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_scopy(2*P,&z,0,psym,1); cblas_scopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (r=0; r<P-1; r++) { for (p=r+1; p>0; p--) { pasym[2*p] = fmaf(-roots[4*r],pasym[2*p-2],fmaf(roots[4*r+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fmaf(-roots[4*r],pasym[2*p-1],fmaf(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fmaf(-roots[4*r+2],psym[2*p-2],fmaf(roots[4*r+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fmaf(-roots[4*r+2],psym[2*p-1],fmaf(-roots[4*r+3],psym[2*p-2],psym[2*p+1])); } } for (r=0; r<Po; r++) { Y[c+r*C] = 0.5f*(psym[2*(Po-r)]-pasym[2*(Po-r)]); } } } } else if (dim==1) { if (iscolmajor) { //cblas_scopy(R,&o,0,Y,1); for (r=0; r<R; r++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cosf(X[r+f*R]); roots[2*f+3] = sinf(X[r+f*R]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_scopy(2*P,&z,0,psym,1); cblas_scopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (c=0; c<P-1; c++) { for (p=c+1; p>0; p--) { pasym[2*p] = fmaf(-roots[4*c],pasym[2*p-2],fmaf(roots[4*c+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fmaf(-roots[4*c],pasym[2*p-1],fmaf(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fmaf(-roots[4*c+2],psym[2*p-2],fmaf(roots[4*c+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fmaf(-roots[4*c+2],psym[2*p-1],fmaf(-roots[4*c+3],psym[2*p-2],psym[2*p+1])); } } for (c=0; c<Po; c++) { Y[r+c*R] = 0.5f*(psym[2*(Po-c)]-pasym[2*(Po-c)]); } } } else { //cblas_scopy(R,&o,0,Y,Po); for (r=0; r<R; r++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cosf(X[f+r*C]); roots[2*f+3] = sinf(X[f+r*C]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_scopy(2*P,&z,0,psym,1); cblas_scopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (c=0; c<P-1; c++) { for (p=c+1; p>0; p--) { pasym[2*p] = fmaf(-roots[4*c],pasym[2*p-2],fmaf(roots[4*c+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fmaf(-roots[4*c],pasym[2*p-1],fmaf(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fmaf(-roots[4*c+2],psym[2*p-2],fmaf(roots[4*c+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fmaf(-roots[4*c+2],psym[2*p-1],fmaf(-roots[4*c+3],psym[2*p-2],psym[2*p+1])); } } for (c=0; c<Po; c++) { Y[c+r*Po] = 0.5f*(psym[2*(Po-c)]-pasym[2*(Po-c)]); } } } } else { fprintf(stderr,"error in lsf2poly_s: dim must be 0 or 1.\n"); return 1; } //Exit free(roots); free(psym); free(pasym); return 0; } int lsf2poly_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim) { const double z = 0.0, o = 1.0; const int F = (dim==0) ? R : C; //num LSFs const int nr = 2*F + 2; //length roots const int P = F + 2; //length psym and pasym const int Po = P - 1; //num output poly coeffs int r, c, p, f; double *roots, *psym, *pasym; //Checks if (R<1) { fprintf(stderr,"error in lsf2poly_d: nrows X must be positive\n"); return 1; } if (C<1) { fprintf(stderr,"error in lsf2poly_d: ncols X must be positive\n"); return 1; } //Initialize if (!(psym=(double *)malloc((size_t)(2*P)*sizeof(double)))) { fprintf(stderr,"error in lsf2poly_d: problem with malloc. "); perror("malloc"); return 1; } if (!(pasym=(double *)malloc((size_t)(2*P)*sizeof(double)))) { fprintf(stderr,"error in lsf2poly_d: problem with malloc. "); perror("malloc"); return 1; } if (!(roots=(double *)malloc((size_t)(2*nr)*sizeof(double)))) { fprintf(stderr,"error in lsf2poly_d: problem with malloc. "); perror("malloc"); return 1; } roots[0] = o; roots[nr] = -o; roots[1] = roots[nr+1] = z; if (dim==0) { if (iscolmajor) { for (c=0; c<C; c++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cos(X[f+c*R]); roots[2*f+3] = sin(X[f+c*R]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_dcopy(2*P,&z,0,psym,1); cblas_dcopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (r=0; r<P-1; r++) { for (p=r+1; p>0; p--) { pasym[2*p] = fma(-roots[4*r],pasym[2*p-2],fma(roots[4*r+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fma(-roots[4*r],pasym[2*p-1],fma(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fma(-roots[4*r+2],psym[2*p-2],fma(roots[4*r+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fma(-roots[4*r+2],psym[2*p-1],fma(-roots[4*r+3],psym[2*p-2],psym[2*p+1])); } } for (r=0; r<Po; r++) { Y[r+c*Po] = 0.5*(psym[2*(Po-r)]-pasym[2*(Po-r)]); } } } else { for (c=0; c<C; c++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cos(X[c+f*C]); roots[2*f+3] = sin(X[c+f*C]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_dcopy(2*P,&z,0,psym,1); cblas_dcopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (r=0; r<P-1; r++) { for (p=r+1; p>0; p--) { pasym[2*p] = fma(-roots[4*r],pasym[2*p-2],fma(roots[4*r+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fma(-roots[4*r],pasym[2*p-1],fma(-roots[4*r+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fma(-roots[4*r+2],psym[2*p-2],fma(roots[4*r+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fma(-roots[4*r+2],psym[2*p-1],fma(-roots[4*r+3],psym[2*p-2],psym[2*p+1])); } } for (r=0; r<Po; r++) { Y[c+r*C] = 0.5*(psym[2*(Po-r)]-pasym[2*(Po-r)]); } } } } else if (dim==1) { if (iscolmajor) { for (r=0; r<R; r++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cos(X[r+f*R]); roots[2*f+3] = sin(X[r+f*R]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_dcopy(2*P,&z,0,psym,1); cblas_dcopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (c=0; c<P-1; c++) { for (p=c+1; p>0; p--) { pasym[2*p] = fma(-roots[4*c],pasym[2*p-2],fma(roots[4*c+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fma(-roots[4*c],pasym[2*p-1],fma(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fma(-roots[4*c+2],psym[2*p-2],fma(roots[4*c+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fma(-roots[4*c+2],psym[2*p-1],fma(-roots[4*c+3],psym[2*p-2],psym[2*p+1])); } } for (c=0; c<Po; c++) { Y[r+c*R] = 0.5*(psym[2*(Po-c)]-pasym[2*(Po-c)]); } } } else { for (r=0; r<R; r++) { for (f=0; f<F; f++) { roots[2*f+2] = roots[4*F-2*f+2] = cos(X[f+r*C]); roots[2*f+3] = sin(X[f+r*C]); roots[4*F-2*f+3] = -roots[2*f+3]; } cblas_dcopy(2*P,&z,0,psym,1); cblas_dcopy(2*P,&z,0,pasym,1); psym[0] = pasym[0] = o; for (c=0; c<P-1; c++) { for (p=c+1; p>0; p--) { pasym[2*p] = fma(-roots[4*c],pasym[2*p-2],fma(roots[4*c+1],pasym[2*p-1],pasym[2*p])); pasym[2*p+1] = fma(-roots[4*c],pasym[2*p-1],fma(-roots[4*c+1],pasym[2*p-2],pasym[2*p+1])); psym[2*p] = fma(-roots[4*c+2],psym[2*p-2],fma(roots[4*c+3],psym[2*p-1],psym[2*p])); psym[2*p+1] = fma(-roots[4*c+2],psym[2*p-1],fma(-roots[4*c+3],psym[2*p-2],psym[2*p+1])); } } for (c=0; c<Po; c++) { Y[c+r*Po] = 0.5*(psym[2*(Po-c)]-pasym[2*(Po-c)]); } } } } else { fprintf(stderr,"error in lsf2poly_d: dim must be 0 or 1.\n"); return 1; } //Exit free(roots); free(psym); free(pasym); return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4142721819, "avg_line_length": 43.2354948805, "ext": "c", "hexsha": "d614a9441e224b5280af478a9f5f9710aa99f8ae", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "erikedwards4/aud", "max_forks_repo_path": "c/lsf2poly.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "erikedwards4/aud", "max_issues_repo_path": "c/lsf2poly.c", "max_line_length": 159, "max_stars_count": null, "max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "erikedwards4/aud", "max_stars_repo_path": "c/lsf2poly.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4680, "size": 12668 }
/* Excited States software: KGS Contributors: See CONTRIBUTORS.txt Contact: kgs-contact@simtk.org Copyright (C) 2009-2017 Stanford University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: This entire text, including the above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef JACOBIANRELATED_H #define JACOBIANRELATED_H #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> ///These values have to be chosen according to the numerical analysis static const double SINGVAL_TOL = 0.000000000001; // only generic 10^-12 //static const double SINGVAL_TOL = 0.000001; // include non-generic 10^-10 static const double RIGID_TOL = 0.0000000001; //depends on molecule, but 10^-10 seems a good fit! //static const double RIGID_TOL = 0.000001; //depends on molecule ToDo: Adapt to obtain on-the-fly parameter selection class NullSpaceRet { public: // static gsl_matrix* Ut;//The Ut from the SVD static gsl_matrix* V;//The V from the SVD static gsl_vector* singularValues; int nullspaceSize; int m, n; // gsl_matrix* P;//Null-space projection matrix gsl_matrix* m_nullspaceBasis; //basis of the nullspace // gsl_matrix* Jinv;//Jacobian pseudo-inverse gsl_vector* m_rigidAngles; gsl_vector* m_rigidHBonds; int m_numCoordinated; int m_numRigid; int m_numRigidHBonds; NullSpaceRet (int input_m, int input_n); ~NullSpaceRet (); void print(); // A function to make the projection operation more efficient; void NullSpacePostCompute(); /// A function that identifies rigidified dihedral angles void RigidityAnalysis(gsl_matrix* HBondJacobian); //A function to project a vector on the nullspace void ProjectOnNullSpace (gsl_vector *to_project, gsl_vector *after_project); // To manipulate owner configations of NullSpaceRet instances void numOwners(unsigned int numOwners); unsigned int numOwners() const; private: unsigned int numOwners_; }; void nr_svd(gsl_matrix* a_g, int m, int n, double w[], gsl_matrix* v_out); void ComputeNullSpace(gsl_matrix* Jac, NullSpaceRet* Ret); //void ProjectOnNullSpace (NullSpaceRet* nullspace, gsl_vector *e, gsl_vector *to_project, gsl_vector *after_project); void TorsionUpdate(NullSpaceRet* nullspace, gsl_vector *e, double lambda, gsl_vector *dTheta); #endif
{ "alphanum_fraction": 0.7815489047, "avg_line_length": 36.0111111111, "ext": "h", "hexsha": "4cbd7c6edf6d56e7b0b4753c2fa4b01f8864e200", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_path": "src/JacobianRelated.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_path": "src/JacobianRelated.h", "max_line_length": 118, "max_stars_count": 1, "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_path": "src/JacobianRelated.h", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "num_tokens": 806, "size": 3241 }
#ifndef PRECISION_RECALL_H_G2FJDYVV #define PRECISION_RECALL_H_G2FJDYVV #include <gsl/gsl> #include <opencv2/core/base.hpp> #include <opencv2/core/types.hpp> #include <opencv2/imgproc.hpp> #include <optional> #include <string_view> #include <util/common_structures.h> namespace sens_loc::apps { /// Defines the color and line strength used for backprojection. struct backproject_style { backproject_style() = default; backproject_style(int r, int g, int b, int strength) : color{CV_RGB(r, g, b)} , strength{strength} { Expects(strength > 0); Expects(r >= 0); Expects(g >= 0); Expects(b >= 0); Expects(r < 256); Expects(g < 256); Expects(b < 256); } cv::Scalar color = CV_RGB(0, 0, 0); int strength = 1; }; /// Composition of styles on how the backprojections are plotted. /// \sa backproject_style struct backproject_config { backproject_style true_positive; backproject_style false_negative; backproject_style false_positive; }; struct recognition_analysis_input { std::string_view depth_image_pattern; std::string_view pose_file_pattern; std::string_view intrinsic_file; std::optional<std::string_view> mask_file; cv::NormTypes matching_norm; float keypoint_distance_threshold; /// Unit-Conversion for the ICP of kinect images. No other depth images /// are treated with ICP, so this is dirty set to a constant. const float unit_factor = 0.001F; }; struct recognition_analysis_output_options { std::optional<std::string> backproject_pattern; std::optional<std::string> original_files; std::optional<std::string> stat_file; std::optional<std::string> backprojection_selected_histo; std::optional<std::string> relevant_histo; std::optional<std::string> true_positive_histo; std::optional<std::string> false_positive_histo; std::optional<std::string> true_positive_distance_histo; std::optional<std::string> false_positive_distance_histo; }; int analyze_recognition_performance( util::processing_input in, const recognition_analysis_input& required_data, const recognition_analysis_output_options& output_options, const backproject_config& backproject_config); } // namespace sens_loc::apps #endif /* end of include guard: PRECISION_RECALL_H_G2FJDYVV */
{ "alphanum_fraction": 0.6826538769, "avg_line_length": 33.36, "ext": "h", "hexsha": "295e8f6734e2bda945214c4d6f3c23c9f953b288", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_line_length": 75, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/apps/feature_performance/recognition_performance.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 579, "size": 2502 }