Search is not available for this dataset
text
string
meta
dict
/* test.c * * Copyright (C) 2012-2014, 2016 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 <stdio.h> #include <stdlib.h> #include <math.h> #include <unistd.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_test.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_spmatrix.h> /* create_random_sparse() Create a random sparse matrix with approximately M*N*density non-zero entries Inputs: M - number of rows N - number of columns density - sparse density \in [0,1] 0 = no non-zero entries 1 = all m*n entries are filled r - random number generator Return: pointer to sparse matrix in triplet format (must be freed by caller) Notes: 1) non-zero matrix entries are uniformly distributed in [0,1] */ static gsl_spmatrix * create_random_sparse(const size_t M, const size_t N, const double density, const gsl_rng *r) { size_t nnzwanted = (size_t) floor(M * N * GSL_MIN(density, 1.0)); gsl_spmatrix *m = gsl_spmatrix_alloc_nzmax(M, N, nnzwanted, GSL_SPMATRIX_TRIPLET); while (gsl_spmatrix_nnz(m) < nnzwanted) { /* generate a random row and column */ size_t i = gsl_rng_uniform(r) * M; size_t j = gsl_rng_uniform(r) * N; /* generate random m_{ij} and add it */ double x = gsl_rng_uniform(r); gsl_spmatrix_set(m, i, j, x); } return m; } /* create_random_sparse() */ static gsl_spmatrix * create_random_sparse_int(const size_t M, const size_t N, const double density, const gsl_rng *r) { const double lower = 1.0; const double upper = 10.0; size_t nnzwanted = (size_t) floor(M * N * GSL_MIN(density, 1.0)); gsl_spmatrix *m = gsl_spmatrix_alloc_nzmax(M, N, nnzwanted, GSL_SPMATRIX_TRIPLET); while (gsl_spmatrix_nnz(m) < nnzwanted) { /* generate a random row and column */ size_t i = gsl_rng_uniform(r) * M; size_t j = gsl_rng_uniform(r) * N; /* generate random m_{ij} and add it */ int x = (int) (gsl_rng_uniform(r) * (upper - lower) + lower); gsl_spmatrix_set(m, i, j, (double) x); } return m; } static void test_getset(const size_t M, const size_t N, const double density, const gsl_rng *r) { int status; size_t i, j; /* test that a newly allocated matrix is initialized to zero */ { size_t nzmax = (size_t) (0.5 * M * N); gsl_spmatrix *mt = gsl_spmatrix_alloc_nzmax(M, N, nzmax, GSL_SPMATRIX_TRIPLET); gsl_spmatrix *mccs = gsl_spmatrix_alloc_nzmax(M, N, nzmax, GSL_SPMATRIX_CCS); gsl_spmatrix *mcrs = gsl_spmatrix_alloc_nzmax(M, N, nzmax, GSL_SPMATRIX_CRS); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double mtij = gsl_spmatrix_get(mt, i, j); double mcij = gsl_spmatrix_get(mccs, i, j); double mrij = gsl_spmatrix_get(mcrs, i, j); if (mtij != 0.0) status = 1; if (mcij != 0.0) status = 2; if (mrij != 0.0) status = 3; } } gsl_test(status == 1, "test_getset: triplet M=%zu N=%zu not initialized to zero", M, N); gsl_test(status == 2, "test_getset: CCS M=%zu N=%zu not initialized to zero", M, N); gsl_test(status == 3, "test_getset: CRS M=%zu N=%zu not initialized to zero", M, N); gsl_spmatrix_free(mt); gsl_spmatrix_free(mccs); gsl_spmatrix_free(mcrs); } /* test triplet versions of _get and _set */ { const double val = 0.75; size_t k = 0; gsl_spmatrix *m = gsl_spmatrix_alloc(M, N); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double x = (double) ++k; double y; gsl_spmatrix_set(m, i, j, x); y = gsl_spmatrix_get(m, i, j); if (x != y) status = 1; } } gsl_test(status, "test_getset: M=%zu N=%zu _get != _set", M, N); /* test setting an element to 0 */ gsl_spmatrix_set(m, 0, 0, 1.0); gsl_spmatrix_set(m, 0, 0, 0.0); status = gsl_spmatrix_get(m, 0, 0) != 0.0; gsl_test(status, "test_getset: M=%zu N=%zu m(0,0) = %f", M, N, gsl_spmatrix_get(m, 0, 0)); /* test gsl_spmatrix_set_zero() */ gsl_spmatrix_set(m, 0, 0, 1.0); gsl_spmatrix_set_zero(m); status = gsl_spmatrix_get(m, 0, 0) != 0.0; gsl_test(status, "test_getset: M=%zu N=%zu set_zero m(0,0) = %f", M, N, gsl_spmatrix_get(m, 0, 0)); /* resassemble matrix to ensure nz is calculated correctly */ k = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double x = (double) ++k; gsl_spmatrix_set(m, i, j, x); } } status = gsl_spmatrix_nnz(m) != M * N; gsl_test(status, "test_getset: M=%zu N=%zu set_zero nz = %zu", M, N, gsl_spmatrix_nnz(m)); /* test gsl_spmatrix_ptr() */ status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double mij = gsl_spmatrix_get(m, i, j); double *ptr = gsl_spmatrix_ptr(m, i, j); *ptr += val; if (gsl_spmatrix_get(m, i, j) != mij + val) status = 2; } } gsl_test(status == 2, "test_getset: M=%zu N=%zu triplet ptr", M, N); gsl_spmatrix_free(m); } /* test duplicate values are handled correctly */ { size_t min = GSL_MIN(M, N); size_t expected_nnz = min; size_t nnz; size_t k = 0; gsl_spmatrix *m = gsl_spmatrix_alloc(M, N); status = 0; for (i = 0; i < min; ++i) { for (j = 0; j < 5; ++j) { double x = (double) ++k; double y; gsl_spmatrix_set(m, i, i, x); y = gsl_spmatrix_get(m, i, i); if (x != y) status = 1; } } gsl_test(status, "test_getset: duplicate test M=%zu N=%zu _get != _set", M, N); nnz = gsl_spmatrix_nnz(m); status = nnz != expected_nnz; gsl_test(status, "test_getset: duplicate test M=%zu N=%zu nnz=%zu, expected=%zu", M, N, nnz, expected_nnz); gsl_spmatrix_free(m); } /* test CCS version of gsl_spmatrix_get() */ { const double val = 0.75; gsl_spmatrix *T = create_random_sparse(M, N, density, r); gsl_spmatrix *C = gsl_spmatrix_ccs(T); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Tij = gsl_spmatrix_get(T, i, j); double Cij = gsl_spmatrix_get(C, i, j); double *ptr = gsl_spmatrix_ptr(C, i, j); if (Tij != Cij) status = 1; if (ptr) { *ptr += val; Cij = gsl_spmatrix_get(C, i, j); if (Tij + val != Cij) status = 2; } } } gsl_test(status == 1, "test_getset: M=%zu N=%zu CCS get", M, N); gsl_test(status == 2, "test_getset: M=%zu N=%zu CCS ptr", M, N); gsl_spmatrix_free(T); gsl_spmatrix_free(C); } /* test CRS version of gsl_spmatrix_get() */ { const double val = 0.75; gsl_spmatrix *T = create_random_sparse(M, N, density, r); gsl_spmatrix *C = gsl_spmatrix_crs(T); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Tij = gsl_spmatrix_get(T, i, j); double Cij = gsl_spmatrix_get(C, i, j); double *ptr = gsl_spmatrix_ptr(C, i, j); if (Tij != Cij) status = 1; if (ptr) { *ptr += val; Cij = gsl_spmatrix_get(C, i, j); if (Tij + val != Cij) status = 2; } } } gsl_test(status == 1, "test_getset: M=%zu N=%zu CRS get", M, N); gsl_test(status == 2, "test_getset: M=%zu N=%zu CRS ptr", M, N); gsl_spmatrix_free(T); gsl_spmatrix_free(C); } } /* test_getset() */ static void test_memcpy(const size_t M, const size_t N, const double density, const gsl_rng *r) { int status; { gsl_spmatrix *A = create_random_sparse(M, N, density, r); gsl_spmatrix *A_ccs = gsl_spmatrix_ccs(A); gsl_spmatrix *A_crs = gsl_spmatrix_crs(A); gsl_spmatrix *B_t, *B_ccs, *B_crs; B_t = gsl_spmatrix_alloc(M, N); gsl_spmatrix_memcpy(B_t, A); status = gsl_spmatrix_equal(A, B_t) != 1; gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu triplet format", M, N); B_ccs = gsl_spmatrix_alloc_nzmax(M, N, A_ccs->nzmax, GSL_SPMATRIX_CCS); B_crs = gsl_spmatrix_alloc_nzmax(M, N, A_ccs->nzmax, GSL_SPMATRIX_CRS); gsl_spmatrix_memcpy(B_ccs, A_ccs); gsl_spmatrix_memcpy(B_crs, A_crs); status = gsl_spmatrix_equal(A_ccs, B_ccs) != 1; gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu CCS", M, N); status = gsl_spmatrix_equal(A_crs, B_crs) != 1; gsl_test(status, "test_memcpy: _memcpy M=%zu N=%zu CRS", M, N); gsl_spmatrix_free(A); gsl_spmatrix_free(A_ccs); gsl_spmatrix_free(A_crs); gsl_spmatrix_free(B_t); gsl_spmatrix_free(B_ccs); gsl_spmatrix_free(B_crs); } /* test transpose_memcpy */ { gsl_spmatrix *A = create_random_sparse(M, N, density, r); gsl_spmatrix *AT = gsl_spmatrix_alloc(N, M); gsl_spmatrix *B = gsl_spmatrix_ccs(A); gsl_spmatrix *BT = gsl_spmatrix_alloc_nzmax(N, M, 1, GSL_SPMATRIX_CCS); gsl_spmatrix *C = gsl_spmatrix_crs(A); gsl_spmatrix *CT = gsl_spmatrix_alloc_nzmax(N, M, 1, GSL_SPMATRIX_CRS); size_t i, j; gsl_spmatrix_transpose_memcpy(AT, A); gsl_spmatrix_transpose_memcpy(BT, B); gsl_spmatrix_transpose_memcpy(CT, C); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double ATji = gsl_spmatrix_get(AT, j, i); if (Aij != ATji) status = 1; } } gsl_test(status, "test_memcpy: _transpose_memcpy M=%zu N=%zu triplet format", M, N); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double Bij = gsl_spmatrix_get(B, i, j); double BTji = gsl_spmatrix_get(BT, j, i); if ((Bij != BTji) || (Aij != Bij)) status = 1; } } gsl_test(status, "test_memcpy: _transpose_memcpy M=%zu N=%zu CCS format", M, N); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double Cij = gsl_spmatrix_get(C, i, j); double CTji = gsl_spmatrix_get(CT, j, i); if ((Cij != CTji) || (Aij != Cij)) status = 1; } } gsl_test(status, "test_memcpy: _transpose_memcpy M=%zu N=%zu CRS format", M, N); gsl_spmatrix_free(A); gsl_spmatrix_free(AT); gsl_spmatrix_free(B); gsl_spmatrix_free(BT); gsl_spmatrix_free(C); gsl_spmatrix_free(CT); } } /* test_memcpy() */ static void test_transpose(const size_t M, const size_t N, const double density, const gsl_rng *r) { int status; gsl_spmatrix *A = create_random_sparse(M, N, density, r); gsl_spmatrix *AT = gsl_spmatrix_alloc_nzmax(M, N, A->nz, A->sptype); gsl_spmatrix *AT2 = gsl_spmatrix_alloc_nzmax(M, N, A->nz, A->sptype); gsl_spmatrix *AT2_ccs, *AT2_crs; size_t i, j; /* test triplet transpose */ gsl_spmatrix_memcpy(AT, A); gsl_spmatrix_memcpy(AT2, A); gsl_spmatrix_transpose(AT); gsl_spmatrix_transpose2(AT2); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double ATji = gsl_spmatrix_get(AT, j, i); double AT2ji = gsl_spmatrix_get(AT2, j, i); if (Aij != ATji) status = 1; if (Aij != AT2ji) status = 2; } } gsl_test(status == 1, "test_transpose: transpose M=%zu N=%zu triplet format", M, N); gsl_test(status == 2, "test_transpose: transpose2 M=%zu N=%zu triplet format", M, N); /* test CCS transpose */ AT2_ccs = gsl_spmatrix_ccs(A); gsl_spmatrix_transpose2(AT2_ccs); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double AT2ji = gsl_spmatrix_get(AT2_ccs, j, i); if (Aij != AT2ji) status = 2; } } gsl_test(status == 2, "test_transpose: transpose2 M=%zu N=%zu CCS format", M, N); /* test CRS transpose */ AT2_crs = gsl_spmatrix_crs(A); gsl_spmatrix_transpose2(AT2_crs); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double Aij = gsl_spmatrix_get(A, i, j); double AT2ji = gsl_spmatrix_get(AT2_crs, j, i); if (Aij != AT2ji) status = 2; } } gsl_test(status == 2, "test_transpose: transpose2 M=%zu N=%zu CRS format", M, N); gsl_spmatrix_free(A); gsl_spmatrix_free(AT); gsl_spmatrix_free(AT2); gsl_spmatrix_free(AT2_ccs); gsl_spmatrix_free(AT2_crs); } static void test_ops(const size_t M, const size_t N, const double density, const gsl_rng *r) { size_t i, j; int status; /* test gsl_spmatrix_add */ { gsl_spmatrix *A = create_random_sparse(M, N, density, r); gsl_spmatrix *B = create_random_sparse(M, N, density, r); gsl_spmatrix *A_ccs = gsl_spmatrix_ccs(A); gsl_spmatrix *B_ccs = gsl_spmatrix_ccs(B); gsl_spmatrix *C_ccs = gsl_spmatrix_alloc_nzmax(M, N, 1, GSL_SPMATRIX_CCS); gsl_spmatrix *A_crs = gsl_spmatrix_crs(A); gsl_spmatrix *B_crs = gsl_spmatrix_crs(B); gsl_spmatrix *C_crs = gsl_spmatrix_alloc_nzmax(M, N, 1, GSL_SPMATRIX_CRS); gsl_spmatrix_add(C_ccs, A_ccs, B_ccs); gsl_spmatrix_add(C_crs, A_crs, B_crs); status = 0; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { double aij, bij, cij; aij = gsl_spmatrix_get(A_ccs, i, j); bij = gsl_spmatrix_get(B_ccs, i, j); cij = gsl_spmatrix_get(C_ccs, i, j); if (aij + bij != cij) status = 1; aij = gsl_spmatrix_get(A_crs, i, j); bij = gsl_spmatrix_get(B_crs, i, j); cij = gsl_spmatrix_get(C_crs, i, j); if (aij + bij != cij) status = 2; } } gsl_test(status == 1, "test_ops: add M=%zu N=%zu CCS", M, N); gsl_test(status == 2, "test_ops: add M=%zu N=%zu CRS", M, N); gsl_spmatrix_free(A); gsl_spmatrix_free(B); gsl_spmatrix_free(A_ccs); gsl_spmatrix_free(B_ccs); gsl_spmatrix_free(C_ccs); gsl_spmatrix_free(A_crs); gsl_spmatrix_free(B_crs); gsl_spmatrix_free(C_crs); } } /* test_ops() */ static void test_io_ascii(const size_t M, const size_t N, const double density, const gsl_rng *r) { int status; gsl_spmatrix *A = create_random_sparse_int(M, N, density, r); char filename[] = "test.dat"; /* test triplet I/O */ { FILE *f = fopen(filename, "w"); gsl_spmatrix_fprintf(f, A, "%g"); fclose(f); } { FILE *f = fopen(filename, "r"); gsl_spmatrix *B = gsl_spmatrix_fscanf(f); status = gsl_spmatrix_equal(A, B) != 1; gsl_test(status, "test_io_ascii: fprintf/fscanf M=%zu N=%zu triplet format", M, N); fclose(f); gsl_spmatrix_free(B); } /* test CCS I/O */ { FILE *f = fopen(filename, "w"); gsl_spmatrix *A_ccs = gsl_spmatrix_ccs(A); gsl_spmatrix_fprintf(f, A_ccs, "%g"); fclose(f); gsl_spmatrix_free(A_ccs); } { FILE *f = fopen(filename, "r"); gsl_spmatrix *B = gsl_spmatrix_fscanf(f); status = gsl_spmatrix_equal(A, B) != 1; gsl_test(status, "test_io_ascii: fprintf/fscanf M=%zu N=%zu CCS format", M, N); fclose(f); gsl_spmatrix_free(B); } /* test CRS I/O */ { FILE *f = fopen(filename, "w"); gsl_spmatrix *A_crs = gsl_spmatrix_crs(A); gsl_spmatrix_fprintf(f, A_crs, "%g"); fclose(f); gsl_spmatrix_free(A_crs); } { FILE *f = fopen(filename, "r"); gsl_spmatrix *B = gsl_spmatrix_fscanf(f); status = gsl_spmatrix_equal(A, B) != 1; gsl_test(status, "test_io_ascii: fprintf/fscanf M=%zu N=%zu CRS format", M, N); fclose(f); gsl_spmatrix_free(B); } unlink(filename); gsl_spmatrix_free(A); } static void test_io_binary(const size_t M, const size_t N, const double density, const gsl_rng *r) { int status; gsl_spmatrix *A = create_random_sparse(M, N, density, r); gsl_spmatrix *A_ccs, *A_crs; char filename[] = "test.dat"; /* test triplet I/O */ { FILE *f = fopen(filename, "wb"); gsl_spmatrix_fwrite(f, A); fclose(f); } { FILE *f = fopen(filename, "rb"); gsl_spmatrix *B = gsl_spmatrix_alloc_nzmax(M, N, A->nz, A->sptype); gsl_spmatrix_fread(f, B); status = gsl_spmatrix_equal(A, B) != 1; gsl_test(status, "test_io_binary: fwrite/fread M=%zu N=%zu triplet format", M, N); fclose(f); gsl_spmatrix_free(B); } /* test CCS I/O */ A_ccs = gsl_spmatrix_ccs(A); { FILE *f = fopen(filename, "wb"); gsl_spmatrix_fwrite(f, A_ccs); fclose(f); } { FILE *f = fopen(filename, "rb"); gsl_spmatrix *B = gsl_spmatrix_alloc_nzmax(M, N, A->nz, GSL_SPMATRIX_CCS); gsl_spmatrix_fread(f, B); status = gsl_spmatrix_equal(A_ccs, B) != 1; gsl_test(status, "test_io_binary: fwrite/fread M=%zu N=%zu CCS format", M, N); fclose(f); gsl_spmatrix_free(B); } /* test CRS I/O */ A_crs = gsl_spmatrix_crs(A); { FILE *f = fopen(filename, "wb"); gsl_spmatrix_fwrite(f, A_crs); fclose(f); } { FILE *f = fopen(filename, "rb"); gsl_spmatrix *B = gsl_spmatrix_alloc_nzmax(M, N, A->nz, GSL_SPMATRIX_CRS); gsl_spmatrix_fread(f, B); status = gsl_spmatrix_equal(A_crs, B) != 1; gsl_test(status, "test_io_binary: fwrite/fread M=%zu N=%zu CRS format", M, N); fclose(f); gsl_spmatrix_free(B); } unlink(filename); gsl_spmatrix_free(A); gsl_spmatrix_free(A_ccs); gsl_spmatrix_free(A_crs); } int main() { gsl_rng *r = gsl_rng_alloc(gsl_rng_default); test_memcpy(10, 10, 0.2, r); test_memcpy(10, 15, 0.3, r); test_memcpy(53, 213, 0.4, r); test_memcpy(920, 2, 0.2, r); test_memcpy(2, 920, 0.3, r); test_getset(20, 20, 0.3, r); test_getset(30, 20, 0.3, r); test_getset(15, 210, 0.3, r); test_transpose(50, 50, 0.5, r); test_transpose(10, 40, 0.3, r); test_transpose(40, 10, 0.3, r); test_transpose(57, 13, 0.2, r); test_ops(20, 20, 0.2, r); test_ops(50, 20, 0.3, r); test_ops(20, 50, 0.3, r); test_ops(76, 43, 0.4, r); test_io_ascii(30, 30, 0.3, r); test_io_ascii(20, 10, 0.2, r); test_io_ascii(10, 20, 0.2, r); test_io_ascii(34, 78, 0.3, r); test_io_binary(50, 50, 0.3, r); test_io_binary(25, 10, 0.2, r); test_io_binary(10, 25, 0.2, r); test_io_binary(101, 253, 0.3, r); gsl_rng_free(r); exit (gsl_test_summary()); } /* main() */
{ "alphanum_fraction": 0.5692708846, "avg_line_length": 25.9923273657, "ext": "c", "hexsha": "2951b8c42e1f3a8800d0dfe0b25c5378330b0919", "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": "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/spmatrix/test.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/test.c", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/test.c", "max_stars_repo_stars_event_max_datetime": "2020-10-18T13:15:00.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-18T13:15:00.000Z", "num_tokens": 6663, "size": 20326 }
/* * * * */ #include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <cblas.h> #include <string.h> // memcpy #include <math.h> #include <stdarg.h> #include "cgraph.h" #include "cg_operation.h" #include "cg_types.h" #include "cg_variables.h" #include "cg_errors.h" #include "cg_constants.h" #include "cg_enums.h" #include "cg_factory.h" #include "cg_math.h" #include "cg_ops.h" void cg_assert(int cond, const char * rawcond, const char * fmt, ...) { if(cond) return; char temp[1024]; va_list vl; va_start(vl, fmt); vsprintf(temp, fmt, vl); va_end(vl); fprintf(stdout, "Fatal error, assertion failed: %s\n", rawcond); fprintf(stdout, temp); fprintf(stdout, "\n"); exit(-1); } #define CHECK_RESULT(node) \ if(node->error != NULL){\ return node;\ } /* * Works only with constant types */ CGNode* copyNode(CGNode* node){ CGNode* n = calloc(1, sizeof(CGNode)); if(node->type != CGNT_CONSTANT){ fprintf(stderr, "Call to copyNode with a non-constant node.\n... This should not happen, but who knows these days.\n"); fprintf(stderr, "copy node with nodetype = %d\n", node->type); exit(-1); } n->type = CGNT_CONSTANT; n->constant = calloc(1, sizeof(CGPConstant)); n->constant->type = node->constant->type; n->result = NULL; n->diff = NULL; switch(node->constant->type){ case CGVT_DOUBLE: { CGDouble* d = calloc(1, sizeof(CGDouble)); d->value = ((CGDouble*)node->constant->value)->value; n->constant->value = d; break; } case CGVT_VECTOR: { CGVector* V = calloc(1, sizeof(CGVector)); CGVector* src = (CGVector*)node->constant->value; V->len = src->len; if(src->data != NULL) { V->data = calloc(V->len, sizeof(cg_float)); memcpy(V->data, src->data, V->len * sizeof(cg_float)); } #ifdef CG_USE_OPENCL V->buf = NULL; V->loc = CG_DATALOC_HOST_MEM; #endif n->constant->value = V; break; } case CGVT_MATRIX: { CGMatrix* M = calloc(1, sizeof(CGMatrix)); CGMatrix* src = (CGMatrix*)node->constant->value; uint64_t size = src->cols * src->rows; M->rows = src->rows; M->cols = src->cols; if(src->data != NULL) { M->data = calloc(size, sizeof(cg_float)); memcpy(M->data, src->data, size*sizeof(cg_float)); } #ifdef CG_USE_OPENCL M->buf = NULL; M->loc = CG_DATALOC_HOST_MEM; #endif n->constant->value = M; break; } } return n; } // @Deprecated @NotUsed void* copyNodeValue(CGNode* node){ if(node->type != CGNT_CONSTANT){ fprintf(stderr, "Call to copyNodeValue with a non-constant node.\n... This should not happen, but who knows these days."); exit(-1); } switch(node->constant->type){ case CGVT_DOUBLE: { CGDouble* d = calloc(1, sizeof(CGDouble)); d->value = ((CGDouble*)node->constant->value)->value; return d; } case CGVT_VECTOR: { CGVector* V = calloc(1, sizeof(CGVector)); CGVector* src = (CGVector*)node->constant->value; V->len = src->len; V->data = calloc(V->len, sizeof(cg_float)); memcpy(V->data, src->data, V->len*sizeof(cg_float)); return V; } case CGVT_MATRIX: { CGMatrix* M = calloc(1, sizeof(CGMatrix)); CGMatrix* src = (CGMatrix*)node->constant->value; uint64_t size = src->cols * src->rows; M->rows = src->rows; M->cols = src->cols; M->data = calloc(size, sizeof(cg_float)); memcpy(M->data, src->data, size*sizeof(cg_float)); return M; } } } /* * @Deprecated */ void* copyRNodeValue(CGResultNode* node){ switch(node->type){ case CGVT_DOUBLE: { CGDouble* d = calloc(1, sizeof(CGDouble)); d->value = ((CGDouble*)node->value)->value; return d; } case CGVT_VECTOR: { CGVector* V = calloc(1, sizeof(CGVector)); CGVector* src = (CGVector*)node->value; V->len = src->len; V->data = calloc(V->len, sizeof(cg_float)); memcpy(V->data, src->data, V->len*sizeof(cg_float)); return V; } case CGVT_MATRIX: { CGMatrix* M = calloc(1, sizeof(CGMatrix)); CGMatrix* src = (CGMatrix*)node->value; uint64_t size = src->cols * src->rows; M->rows = src->rows; M->cols = src->cols; M->data = calloc(size, sizeof(cg_float)); memcpy(M->data, src->data, size*sizeof(cg_float)); return M; } } } CGResultNode* copyResultNode(CGResultNode* node){ CGResultNode* res = calloc(1, sizeof(CGResultNode)); switch(node->type){ case CGVT_DOUBLE: { CGDouble* d = calloc(1, sizeof(CGDouble)); CGDouble* d2 = (CGDouble*)node->value; d->value = d2->value; res->value = d; break; } case CGVT_VECTOR: { CGVector* V = calloc(1, sizeof(CGVector)); CGVector* src = (CGVector*)node->value; V->len = src->len; V->data = calloc(V->len, sizeof(cg_float)); #ifdef CG_USE_OPENCL V->buf = src->buf; #endif memcpy(V->data, src->data, V->len*sizeof(cg_float)); res->value = V; break; } case CGVT_MATRIX: { CGMatrix* M = calloc(1, sizeof(CGMatrix)); CGMatrix* src = (CGMatrix*)node->value; uint64_t size = src->cols * src->rows; M->rows = src->rows; M->cols = src->cols; M->data = calloc(size, sizeof(cg_float)); #ifdef CG_USE_OPENCL M->buf = src->buf; #endif memcpy(M->data, src->data, size*sizeof(cg_float)); res->value = M; break; } } res->type = node->type; return res; } CGMatrix* vectorToMatrix(CGVector* v){ CGMatrix* m = calloc(1, sizeof(CGMatrix)); m->rows = v->len; m->cols = 1; m->data = v->data; return m; } /* * Computational Graph traversing */ CGResultNode* processUnaryOperation(CGraph* graph, CGUnaryOperationType type, CGNode* uhs, CGNode* parentNode){ CGVarType uhsType = CGVT_DOUBLE; void* uhsValue = NULL; CGResultNode* newres = NULL; CGResultNode* lhsResult = computeCGNode(graph, uhs); CHECK_RESULT(lhsResult) uhsType = lhsResult->type; uhsValue = lhsResult->value; switch(type){ case CGUOT_EXP:{ if(uhsType == CGVT_DOUBLE){ newres = expD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = expV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = expM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_LOG:{ if(uhsType == CGVT_DOUBLE){ newres = logD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = logV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = logM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_MINUS:{ if(uhsType == CGVT_DOUBLE){ CGDouble* rhs = calloc(1, sizeof(CGDouble)); rhs->value = -1; CGResultNode* res = mulDD((CGDouble*)uhsValue, rhs, graph, parentNode); freeDoubleValue(rhs); parentNode->result = res; return res; } if(uhsType == CGVT_VECTOR){ CGDouble* lhs = calloc(1, sizeof(CGDouble)); lhs->value = -1; CGResultNode* res = mulDV(lhs, (CGVector*)uhsValue, graph, parentNode); free(lhs); parentNode->result = res; return res; } if(uhsType == CGVT_MATRIX){ CGDouble* lhs = calloc(1, sizeof(CGDouble)); lhs->value = -1; CGResultNode* res = mulDM(lhs, (CGMatrix*)uhsValue, graph, parentNode); free(lhs); parentNode->result = res; return res; } break; } case CGUOT_SIN:{ if(uhsType == CGVT_DOUBLE){ newres = sinD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = sinV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = sinM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_COS:{ if(uhsType == CGVT_DOUBLE){ newres = cosD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = cosV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = cosM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_TAN:{ if(uhsType == CGVT_DOUBLE){ newres = tanD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = tanV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = tanM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_TANH:{ if(uhsType == CGVT_DOUBLE){ newres = tanhD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = tanhV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = tanhM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_INV:{ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation `%s` is not implemented/supported", getUnaryOperationTypeString(type)); newres = returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, parentNode, msg); } case CGUOT_TRANSPOSE:{ if(uhsType == CGVT_DOUBLE){ newres = transposeD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = transposeV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = transposeM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_RELU:{ if(uhsType == CGVT_DOUBLE){ newres = reluD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = reluV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = reluM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGUOT_SOFTPLUS:{ if(uhsType == CGVT_DOUBLE){ newres = softplusD((CGDouble*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_VECTOR){ newres = softplusV((CGVector*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } if(uhsType == CGVT_MATRIX){ newres = softplusM((CGMatrix*)uhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } } char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation [%s %s] cannot be applied", getVariableTypeString(uhsType), getUnaryOperationTypeString(type)); newres = returnResultError(graph, CGET_INCOMPATIBLE_ARGS_EXCEPTION, parentNode, msg); return newres; } CGResultNode* processBinaryOperation(CGraph* graph, CGBinaryOperationType type, CGNode* lhs, CGNode* rhs, CGNode* parentNode){ CGVarType lhsType = CGVT_DOUBLE; CGVarType rhsType = CGVT_DOUBLE; CGResultNode* newres = NULL; void* lhsValue = NULL; void* rhsValue = NULL; CGResultNode* lhsResult = computeCGNode(graph, lhs); CHECK_RESULT(lhsResult) lhsType = lhsResult->type; lhsValue = lhsResult->value; CGResultNode* rhsResult = computeCGNode(graph, rhs); CHECK_RESULT(rhsResult) rhsType = rhsResult->type; rhsValue = rhsResult->value; switch(type){ case CGBOT_ADD:{ if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = addDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = addVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){ newres = addVD((CGVector*)rhsValue, (CGDouble*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = addMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){ newres = addMD((CGMatrix*)rhsValue, (CGDouble*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){ newres = addVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){ newres = addMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){ newres = addMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){ newres = addMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_SUB:{ if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = subDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = subVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){ newres = subDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = subMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){ newres = subDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){ newres = subVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){ newres = subMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){ newres = subMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){ newres = subVM((CGVector*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_DIV:{ if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = divDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = divVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){ newres = divDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){ newres = divVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = divMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){ newres = divMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){ newres = divDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_MULT:{ // TODO: update if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){ newres = mulMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } // TODO: update if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){ newres = mulMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } // TODO: update if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){ newres = mulMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = mulDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){ newres = mulDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = mulDV((CGDouble*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){ newres = mulDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = mulDM((CGDouble*)rhsValue, (CGMatrix*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){ newres = crossVV((CGVector*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_POW:{ if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = powDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = powVD((CGVector*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = powMD((CGMatrix*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_DOT: { /* * The following are the same as MUL */ if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_DOUBLE)){ newres = mulDD((CGDouble*)lhsValue, (CGDouble*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_VECTOR)){ newres = mulDV((CGDouble*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_DOUBLE)){ newres = mulDV((CGDouble*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_DOUBLE) && (rhsType == CGVT_MATRIX)){ newres = mulDM((CGDouble*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_DOUBLE)){ newres = mulDM((CGDouble*)rhsValue, (CGMatrix*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } /* here starts dot specific impl */ if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_MATRIX)){ newres = dotMM((CGMatrix*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_MATRIX) && (rhsType == CGVT_VECTOR)){ newres = dotMV((CGMatrix*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){ newres = dotVM((CGVector*)lhsValue, (CGMatrix*)rhsValue, graph, parentNode); //newres = dotMM(vectorToMatrix((CGVector*)lhsValue), (CGMatrix*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } /* if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_MATRIX)){ newres = mulMV((CGMatrix*)rhsValue, (CGVector*)lhsValue, graph, parentNode); parentNode->result = newres; return newres; } */ if((lhsType == CGVT_VECTOR) && (rhsType == CGVT_VECTOR)){ newres = dotVV((CGVector*)lhsValue, (CGVector*)rhsValue, graph, parentNode); parentNode->result = newres; return newres; } break; } case CGBOT_TMULT:{ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation `%s` is not implemented/supported", getBinaryOperationTypeString(type)); return returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, parentNode, msg); } } char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation [%s %s %s] cannot be applied", getVariableTypeString(lhsType), getBinaryOperationTypeString(type), getVariableTypeString(rhsType)); return returnResultError(graph, CGET_INCOMPATIBLE_ARGS_EXCEPTION, parentNode, msg); } CGResultNode* computeRawNode(CGNode* node){ CGraph* tmp_G = makeGraph("temp_g"); tmp_G->root = node; storeNodesInGraph(tmp_G, node); CGResultNode* res = computeGraph(tmp_G); res = copyResultNode(res); freeGraph(tmp_G); free(tmp_G); return res; } CGResultNode* computeCGNode(CGraph* graph, CGNode* node){ CGResultNode* result = NULL; if(node->result != NULL){ return node->result; } switch(node->type){ case CGNT_CONSTANT:{ result = constantNodeToResultNodeCopy(node); break; } case CGNT_VARIABLE:{ if(graph == NULL) { char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Cannot compute variable`%s` without the graph instance", node->var->name); return returnResultError(graph, CGET_NO_GRAPH_INSTANCE, node, msg); } CGNode* constantNode = *map_get(&graph->vars, node->var->name); if(constantNode == NULL) { char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "No variable `%s` was found in graph `%s`", node->var->name, graph!=NULL?graph->name:"[anonymous]"); return returnResultError(graph, CGET_VARIABLE_DOES_NOT_EXIST, node, msg); } CGResultNode* rnode = computeCGNode(graph, constantNode); CHECK_RESULT(rnode) constantNode->result = rnode; node->result = copyResultNode(rnode); result = node->result; break; } case CGNT_BINARY_OPERATION: result = processBinaryOperation(graph, node->bop->type, node->bop->lhs, node->bop->rhs, node); break; case CGNT_UNARY_OPERATION: result = processUnaryOperation(graph, node->uop->type, node->uop->uhs, node); break; /* * TODO: add this test to unittest */ case CGNT_AXIS_BOUND_OPERATION: { //CGResultNode* res = computeCGNode(graph, node->axop->uhs); switch(node->axop->type){ case CGABOT_SUM:{ CGResultNode* newres = computeCGNode(graph, node->axop->uhs); CHECK_RESULT(newres) if(newres->type == CGVT_DOUBLE){ result = sumD((CGDouble*)newres->value, graph, node); } if(newres->type == CGVT_VECTOR){ result = sumV((CGVector*)newres->value, graph, node); } if(newres->type == CGVT_MATRIX){ result = sumM((CGMatrix*)newres->value, graph, node, node->axop->axis); } break; } case CGABOT_MAX:{ result = max(node, graph); break; } case CGABOT_MIN:{ result = min(node, graph); break; } case CGABOT_MEAN:{ result = mean(node, graph); break; } case CGABOT_SOFTMAX:{ char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation [CGABOT_SOFTMAX] is not implemented/supported"); return returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, node, msg); //CGResultNode* res = computeCGNode(graph, node->axop->uhs); //break; } case CGABOT_ARGMAX:{ result = argmax(node, graph); break; } case CGABOT_ARGMIN:{ result = argmin(node, graph); break; } default: break; } break; } case CGNT_GRAPH:{ result = computeGraph(node->graph); break; /* char msg[MAX_ERR_FMT_LEN]; snprintf(msg, MAX_ERR_FMT_LEN, "Operation [GRAPH] is not implemented/supported"); return returnResultError(graph, CGET_OPERATION_NOT_IMPLEMENTED, node, msg); */ } case CGNT_CROSS_ENTROPY_LOSS_FUNC: { CGResultNode* X_res = computeCGNode(graph, node->crossEntropyLoss->x); CGNode* X = resultNodeToConstantNodeCopy(X_res); CGNode* X_val = softmax_node(X); CGResultNode* x_res = computeRawNode(X_val); CGResultNode* y_res = computeCGNode(graph, node->crossEntropyLoss->y); result = crossEntropy(x_res, y_res, node->crossEntropyLoss->num_classes); freeResultNode(x_res); free(x_res); break; } } node->result = reduceDim(result); if(node->diff == NULL) switch(node->result->type){ case CGVT_DOUBLE: node->diff = makeZeroDoubleConstantNode(); break; case CGVT_VECTOR:{ CGVector* v = (CGVector*)node->result ->value; node->diff = makeZeroVectorConstantNode(v->len); break; } case CGVT_MATRIX:{ CGMatrix* v = (CGMatrix*)node->result ->value; node->diff = makeZeroMatrixConstantNode(v->rows, v->cols); break; } } return node->result; } CGResultNode* reduceDim(CGResultNode* result){ //return result; switch(result->type){ case CGVT_DOUBLE:{ return result; } case CGVT_VECTOR:{ CGVector* vec = (CGVector*)result->value; if (vec->len > 1) return result; #ifdef CG_USE_OPENCL copyDataToHost(result); #endif CGDouble* d = calloc(1, sizeof(CGDouble)); d->value = vec->data[0]; freeVectorValue(result->value); free(result->value); result->type = CGVT_DOUBLE; result->value = d; return result; } case CGVT_MATRIX:{ CGMatrix* mat = (CGMatrix*)result->value; if((mat->rows>1) &&(mat->cols>1)) return result; if((mat->rows == 1) && (mat->cols == 1)){ copyDataToHost(result); CGDouble* d = calloc(1, sizeof(CGDouble)); d->value = mat->data[0]; freeMatrixValue(result->value); free(result->value); result->type = CGVT_DOUBLE; result->value = d; return result; } if(mat->rows == 1){ CGVector* vec = calloc(1, sizeof(CGVector)); vec->len = mat->cols; vec->data = mat->data; //TODO: Memory leak here #ifdef CG_USE_OPENCL vec->buf = mat->buf; #endif //freeMatrixValue(result->value); free(result->value); result->type = CGVT_VECTOR; result->value = vec; return result; } return result; } } } CGResultNode* computeGraph(CGraph* graph){ resetGraphResultNodes(graph, graph->root); CGResultNode* res = computeCGNode(graph, graph->root); copyDataToHost(res); return res; } CGResultNode* computeGraphNode(CGraph* graph, CGNode* node){ storeNodesInGraph(graph, node); resetGraphResultNodes(graph, node); return computeCGNode(graph, node); } void storeNodesInGraph(CGraph* graph, CGNode* node){ int idx = -1; vec_find(&graph->nodes, node, idx); if(idx != -1) return; vec_push(&graph->nodes, node); switch(node->type){ case CGNT_CONSTANT: break; case CGNT_VARIABLE: break; case CGNT_BINARY_OPERATION: storeNodesInGraph(graph, node->bop->lhs); storeNodesInGraph(graph, node->bop->rhs); break; case CGNT_UNARY_OPERATION: storeNodesInGraph(graph, node->uop->uhs); break; case CGNT_AXIS_BOUND_OPERATION: storeNodesInGraph(graph, node->axop->uhs); break; case CGNT_GRAPH: storeNodesInGraph(graph, node->graph->root); break; case CGNT_CROSS_ENTROPY_LOSS_FUNC: storeNodesInGraph(graph, node->crossEntropyLoss->x); storeNodesInGraph(graph, node->crossEntropyLoss->y); break; } } void resetGraphResultNodes(CGraph* graph, CGNode* node){ if(node->result != NULL){ freeResultNode(node->result); free(node->result); node->result = NULL; } if(node->diff != NULL){ freeNode(graph, node->diff); free(node->diff); node->diff = NULL; } switch(node->type){ case CGNT_CONSTANT: break; case CGNT_VARIABLE:{ CGNode* var = graphGetVar(graph, node->var->name); if(var != NULL) resetGraphResultNodes(graph, var); break; } case CGNT_BINARY_OPERATION: resetGraphResultNodes(graph, node->bop->lhs); resetGraphResultNodes(graph, node->bop->rhs); break; case CGNT_UNARY_OPERATION: resetGraphResultNodes(graph, node->uop->uhs); break; case CGNT_AXIS_BOUND_OPERATION: resetGraphResultNodes(graph, node->axop->uhs); break; case CGNT_GRAPH: resetGraphResultNodes(graph, node->graph->root); break; case CGNT_CROSS_ENTROPY_LOSS_FUNC: resetGraphResultNodes(graph, node->crossEntropyLoss->x); resetGraphResultNodes(graph, node->crossEntropyLoss->y); break; } } void graphSetVar_lua(CGraph* graph, const char* name, CGNode* value){ CGNode** old = map_get(&graph->vars, name); if(old != NULL){ //freeNode(graph, *old); map_remove(&graph->vars, name); } int res = map_set(&graph->vars, name, value); }
{ "alphanum_fraction": 0.6425326245, "avg_line_length": 25.293398533, "ext": "c", "hexsha": "3bce30b8ef797fe056ec696a66b1d0ccdb857bfd", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z", "max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "praisethemoon/ccgraph", "max_forks_repo_path": "source/libcgraph/source/cgraph.c", "max_issues_count": 27, "max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Enehcruon/cgraph", "max_issues_repo_path": "source/libcgraph/source/cgraph.c", "max_line_length": 174, "max_stars_count": 8, "max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Enehcruon/cgraph", "max_stars_repo_path": "source/libcgraph/source/cgraph.c", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z", "num_tokens": 9223, "size": 31035 }
#ifndef LIBTENSOR_CBLAS_H_H #define LIBTENSOR_CBLAS_H_H extern "C" { // Fixes older cblas.h versions without extern "C" #include <cblas.h> } #endif // LIBTENSOR_CBLAS_H_H
{ "alphanum_fraction": 0.7542857143, "avg_line_length": 19.4444444444, "ext": "h", "hexsha": "fb35afa43e81e52174112196f329a627e67f152c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-11-23T16:27:39.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-17T12:35:47.000Z", "max_forks_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "maxscheurer/libtensor", "max_forks_repo_path": "libtensor/linalg/cblas_h.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_issues_repo_issues_event_max_datetime": "2021-12-03T08:07:09.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-04T20:26:12.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "maxscheurer/libtensor", "max_issues_repo_path": "libtensor/linalg/cblas_h.h", "max_line_length": 64, "max_stars_count": null, "max_stars_repo_head_hexsha": "288ed0596b24356d187d2fa40c05b0dacd00b413", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "maxscheurer/libtensor", "max_stars_repo_path": "libtensor/linalg/cblas_h.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 57, "size": 175 }
/* * 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 painterpath_d2d84280_c369_48f2_99f8_28652ad13baa_h #define painterpath_d2d84280_c369_48f2_99f8_28652ad13baa_h #include <ariel/config.h> #include <gslib/std.h> __ariel_begin__ class painter_path; typedef list<painter_path> painter_paths; class ariel_export painter_linestrip { public: typedef vector<vec2> points; typedef points::iterator ptiter; typedef points::const_iterator ptciter; protected: bool _closed; points _pts; public: painter_linestrip(); ~painter_linestrip() {} int get_size() const { return (int)_pts.size(); } void get_bound_rect(rectf& rc) const; vec2& get_point(int i) { return _pts.at(i); } const vec2& get_point(int i) const { return _pts.at(i); } vec2& get_last_point() { return _pts.back(); } const vec2& get_last_point() const { return _pts.back(); } void add_point(const vec2& pt) { _pts.push_back(pt); } void set_point(int i, const vec2& pt) { _pts.at(i) = pt; } void reserve(int s) { _pts.reserve(s); } void clear() { _pts.clear(); } void swap(painter_linestrip& another); void finish(); void transform(const mat3& m); vec2* expand(int size); void expand_to(int size) { _pts.resize(size); } void reverse(); void offset(const painter_linestrip& org, float off); int point_inside(const vec2& pt) const; bool is_closed() const { return _closed; } void set_closed(bool c) { _closed = c; } bool is_clockwise() const; bool is_convex() const; bool is_convex(int i) const; void tracing() const; void trace_segments() const; void trace_mel(float z) const; protected: enum { st_clockwise_mask = 1, st_convex_mask = 2, }; mutable uint _tst_table; mutable bool _is_clock_wise; mutable bool _is_convex; protected: bool is_clockwise_inited() const { return (_tst_table & st_clockwise_mask) != 0; } void set_clockwise_inited() const { _tst_table |= st_clockwise_mask; } bool is_convex_inited() const { return (_tst_table & st_convex_mask) != 0; } void set_convex_inited() const { _tst_table |= st_convex_mask; } }; typedef list<painter_linestrip> linestrips; typedef vector<painter_linestrip*> linestripvec; typedef linestrips painter_linestrips; /* create a random access view for linestrips */ ariel_export extern void append_linestrips_rav(linestripvec& rav, linestrips& src); ariel_export extern void create_linestrips_rav(linestripvec& rav, linestrips& src); class ariel_export painter_path { public: enum tag { pt_moveto, pt_lineto, pt_quadto, pt_cubicto, }; class __gs_novtable ariel_export node abstract { public: virtual ~node() {} virtual tag get_tag() const = 0; virtual const vec2& get_point() const = 0; virtual void set_point(const vec2&) = 0; virtual void interpolate(painter_linestrip& c, const node* last, float step_len) const = 0; public: template<class _c> _c* as_node() { return static_cast<_c*>(this); } template<class _c> const _c* as_const_node() const { return static_cast<const _c*>(this); } }; template<tag _tag> class node_tpl: public node { public: node_tpl() {} node_tpl(float x, float y): _pt(x, y) {} node_tpl(const vec2& pt): _pt(pt) {} public: tag get_tag() const override { return _tag; } const vec2& get_point() const override { return _pt; } void set_point(const vec2& pt) override { _pt = pt; } void interpolate(painter_linestrip& c, const node*, float) const override { c.add_point(_pt); } protected: vec2 _pt; }; typedef node_tpl<pt_moveto> move_to_node; typedef node_tpl<pt_lineto> line_to_node; class ariel_export quad_to_node: public node_tpl<pt_quadto> { public: quad_to_node() {} quad_to_node(const vec2& p1, const vec2& p2): node_tpl(p2) { _c = p1; } void set_control(const vec2& c) { _c = c; } const vec2& get_control() const { return _c; } void interpolate(painter_linestrip& c, const node* last, float step_len) const override; protected: vec2 _c; }; class ariel_export cubic_to_node: public node_tpl<pt_cubicto> { public: cubic_to_node() {} cubic_to_node(const vec2& p1, const vec2& p2, const vec2 p3): node_tpl(p3) { _c[0] = p1, _c[1] = p2; } void set_control1(const vec2& c) { _c[0] = c; } void set_control2(const vec2& c) { _c[1] = c; } const vec2& get_control1() const { return _c[0]; } const vec2& get_control2() const { return _c[1]; } void interpolate(painter_linestrip& c, const node* last, float step_len) const override; protected: vec2 _c[2]; }; typedef vector<node*> node_list; typedef node_list::iterator iterator; typedef node_list::const_iterator const_iterator; typedef vector<int> indices; protected: node_list _nodelist; public: painter_path() {} painter_path(const painter_path& path) { duplicate(path); } ~painter_path() { destroy(); } bool empty() const { return _nodelist.empty(); } int size() const { return (int)_nodelist.size(); } void resize(int len); void destroy(); void duplicate(const painter_path& path); void add_path(const painter_path& path); void add_rect(const rectf& rc); void swap(painter_path& path); iterator begin() { return _nodelist.begin(); } iterator end() { return _nodelist.end(); } const_iterator begin() const { return _nodelist.begin(); } const_iterator end() const { return _nodelist.end(); } node* get_node(int i) { return _nodelist.at(i); } const node* get_node(int i) const { return _nodelist.at(i); } void close_path(); void close_sub_path(); void get_boundary_box(rectf& rc) const; void move_to(float x, float y) { move_to(vec2(x, y)); } void line_to(float x, float y) { line_to(vec2(x, y)); } void arc_to(float x, float y, float r) { arc_to(vec2(x, y), r); } void rarc_to(float x, float y, float r) { rarc_to(vec2(x, y), r); } void quad_to(float x1, float y1, float x2, float y2) { quad_to(vec2(x1, y1), vec2(x2, y2)); } void cubic_to(float x1, float y1, float x2, float y2, float x3, float y3) { cubic_to(vec2(x1, y1), vec2(x2, y2), vec2(x3, y3)); } void move_to(const vec2& pt) { _nodelist.push_back(new move_to_node(pt)); } void line_to(const vec2& pt) { _nodelist.push_back(new line_to_node(pt)); } void quad_to(const vec2& p1, const vec2& p2) { _nodelist.push_back(new quad_to_node(p1, p2)); } void cubic_to(const vec2& p1, const vec2& p2, const vec2& p3) { _nodelist.push_back(new cubic_to_node(p1, p2, p3)); } void arc_to(const vec2& p1, const vec2& p2, float r); void arc_to(const vec2& pt, float r); void rarc_to(const vec2& pt, float r); void transform(const mat3& m); void get_linestrips(linestrips& c, float step_len = -1.f) const; int get_control_contour(painter_linestrip& ls, int start) const; int get_sub_path(painter_path& sp, int start) const; void to_sub_paths(painter_paths& paths) const; bool is_clockwise() const; bool is_convex() const; void simplify(painter_path& path) const; void reverse(); void tracing() const; void tracing_segments() const; }; typedef painter_path::node painter_node; struct ariel_export path_info { const painter_node* node[2]; path_info() { node[0] = node[1] = 0; } path_info(const painter_node* n1, const painter_node* n2) { node[0] = n1, node[1] = n2; } int get_order() const; int get_point_count() const; bool get_points(vec2 pt[], int cnt) const; void tracing() const; }; enum curve_type { ct_quad, ct_cubic, }; struct __gs_novtable ariel_export curve_splitter abstract { vec2 fixedpt; float ratio; curve_splitter* child[2]; curve_splitter* parent; public: curve_splitter(); virtual ~curve_splitter(); virtual curve_type get_type() const = 0; virtual int get_point_count() const = 0; virtual bool get_points(vec2 p[], int count) const = 0; virtual void split(float t) = 0; virtual void interpolate(vec2& p, float t) const = 0; virtual float reparameterize(const vec2& p) const = 0; virtual void tracing() const = 0; bool is_leaf() const; }; struct ariel_export curve_splitter_quad: public curve_splitter { vec2 cp[3]; vec3 para[2]; public: curve_splitter_quad(const vec2 p[3]); curve_type get_type() const override { return ct_quad; } int get_point_count() const override { return 3; } bool get_points(vec2 p[], int count) const override; void split(float t) override; void interpolate(vec2& p, float t) const override; float reparameterize(const vec2& p) const override; void tracing() const override; }; struct ariel_export curve_splitter_cubic: public curve_splitter { vec2 cp[4]; vec4 para[2]; public: curve_splitter_cubic(const vec2 p[4]); curve_type get_type() const override { return ct_cubic; } int get_point_count() const override { return 4; } bool get_points(vec2 p[], int count) const override; void split(float t) override; void interpolate(vec2& p, float t) const override; float reparameterize(const vec2& p) const override; void tracing() const override; }; struct ariel_export curve_helper { static curve_splitter* create_splitter(const path_info* pnf); static curve_splitter* create_next_splitter(vec2& p, curve_splitter* cs, float t); static curve_splitter* query_splitter(curve_splitter* cs, float t); static curve_splitter* query_splitter(curve_splitter* cs, const vec2& p); static curve_splitter* query_splitter(curve_splitter* cs, const vec2& p1, const vec2& p2); }; struct ariel_export painter_helper { enum { merge_straight_line = 0x01, fix_loop = 0x02, fix_inflection = 0x04, reduce_straight_curve = 0x08, reduce_short_line = 0x10, }; static void transform(painter_path& output, const painter_path& path, uint mask); static void close_sub_paths(painter_path& output, const painter_path& path); }; __ariel_end__ #endif
{ "alphanum_fraction": 0.6506951341, "avg_line_length": 35.5411764706, "ext": "h", "hexsha": "64d0d22c3de35a18d7ce9f2fe27d7449c3c63095", "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/painterpath.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/painterpath.h", "max_line_length": 134, "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/painterpath.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": 3196, "size": 12084 }
#include <math.h> #include <stdlib.h> #if !defined(__APPLE__) #include <malloc.h> #endif #include <stdio.h> #include <assert.h> #include <time.h> #include <string.h> #include <fftw3.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_erf.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_legendre.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_sf_expint.h> #include <gsl/gsl_deriv.h> #include <gsl/gsl_interp2d.h> #include <gsl/gsl_spline2d.h> #include "../cosmolike_core_fast/theory/basics.c" #include "../cosmolike_core_fast/theory/structs.c" #include "../cosmolike_core_fast/theory/parameters.c" #include "../cosmolike_core_fast/emu17/P_cb/emu.c" #include "../cosmolike_core_fast/theory/recompute.c" #include "../cosmolike_core_fast/theory/cosmo3D.c" #include "../cosmolike_core_fast/theory/redshift_spline.c" #include "../cosmolike_core_fast/theory/halo.c" #include "../cosmolike_core_fast/theory/HOD.c" #include "../cosmolike_core_fast/theory/pt.c" #include "../cosmolike_core_fast/theory/cosmo2D_fourier.c" #include "../cosmolike_core_fast/theory/IA.c" // #include "../cosmolike_core_fast/theory/cluster.c" #include "../cosmolike_core_fast/theory/BAO.c" #include "../cosmolike_core_fast/theory/external_prior.c" #include "../cosmolike_core_fast/theory/init_baryon.c" #include "init_LSSxCMB.c" // Naming convention: // g = galaxy positions ("g" as in "galaxy") // k = kappa CMB ("k" as in "kappa") // s = kappa from source galaxies ("s" as in "shear") // And alphabetical order typedef double (*C_tomo_pointer)(double l, int n1, int n2); void twopoint_via_hankel(double **xi, double *logthetamin, double *logthetamax, C_tomo_pointer C_tomo, int ni, int nj, int N_Bessel); #include "../cosmolike_core_fast/theory/CMBxLSS_fourier.c" typedef struct input_cosmo_params_local { double omega_m; double sigma_8; double n_s; double w0; double wa; double omega_b; double h0; double MGSigma; double MGmu; } input_cosmo_params_local; typedef struct input_nuisance_params_local { double bias[10]; double source_z_bias[10]; double source_z_s; double lens_z_bias[10]; double lens_z_s; double shear_m[10]; double A_ia; double beta_ia; double eta_ia; double eta_ia_highz; double lf[6]; double m_lambda[6]; double bary[3]; } input_nuisance_params_local; double C_shear_tomo_sys(double ell,int z1,int z2); // double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs); double C_gl_tomo_sys(double ell,int zl,int zs); double C_ks_sys(double ell, int zs); void set_data_shear(int Ncl, double *ell, double *data, int start); void set_data_ggl(int Ncl, double *ell, double *data, int start); void set_data_clustering(int Ncl, double *ell, double *data, int start); void set_data_gk(double *ell, double *data, int start); void set_data_ks(double *ell, double *data, int start); void set_data_kk(double *ell, double *data, int start); // void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3); // double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3); void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3); double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3); void write_datavector_wrapper(char *details, input_cosmo_params_local ic, input_nuisance_params_local in); double log_like_wrapper(input_cosmo_params_local ic, input_nuisance_params_local in); int get_N_tomo_shear(void); int get_N_tomo_clustering(void); int get_N_ggl(void); int get_N_ell(void); int get_N_tomo_shear(void){ return tomo.shear_Nbin; } int get_N_tomo_clustering(void){ return tomo.clustering_Nbin; } int get_N_ggl(void){ return tomo.ggl_Npowerspectra; } int get_N_ell(void){ return like.Ncl; } double C_shear_tomo_sys(double ell, int z1, int z2) { double C; // C= C_shear_tomo_nointerp(ell,z1,z2); // if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2); if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2); //if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2); // clock_t t1, t2; t1=clock(); // if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2); if(like.IA==1) C = C_shear_tomo_nointerp_IA1(ell,z1,z2); // t2 = clock(); printf("shear %d-%d: %le\n",z1,z2, (double)(t2-t1)/CLOCKS_PER_SEC); if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2); if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]); //printf("%le %d %d %le\n",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2)); return C; } double C_gl_tomo_sys(double ell,int zl,int zs) { double C; // C=C_gl_tomo_nointerp(ell,zl,zs); // if(like.IA==1) C += C_gI_nointerp(ell,zl,zs); if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs); if(like.IA==1) C = C_ggl_IA(ell,zl,zs); if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs); if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]); return C; } // double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs) // { // double C; // C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs); // //if(like.IA!=0) C += // if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]); // return C; // } double C_ks_sys(double ell, int zs) { double C; C = C_ks_nointerp(ell,zs); if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]); return C; } void set_data_shear(int Ncl, double *ell, double *data, int start) { int i,z1,z2,nz; double a; for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){ z1 = Z1(nz); z2 = Z2(nz); for (i = 0; i < Ncl; i++){ if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);} else {data[Ncl*nz+i] = 0.;} } } } void set_data_ggl(int Ncl, double *ell, double *data, int start) { int i, zl,zs,nz; for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){ zl = ZL(nz); zs = ZS(nz); #ifdef ONESAMPLE if(zl==0){ for (i = 0; i < Ncl; i++){data[start+(Ncl*nz)+i] = 0.;} } else{ #endif for (i = 0; i < Ncl; i++){ if (test_kmax(ell[i],zl)){ data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs); } else{ data[start+(Ncl*nz)+i] = 0.; } } #ifdef ONESAMPLE } #endif } } void set_data_clustering(int Ncl, double *ell, double *data, int start){ int i, nz; for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){ //printf("%d %e %e\n",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz)); for (i = 0; i < Ncl; i++){ if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);} else{data[start+(Ncl*nz)+i] = 0.;} //printf("%d %d %le %le\n",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]); } } } void set_data_gk(double *ell, double *data, int start) { #ifdef ONESAMPLE int nz=0; for (int i=0; i<like.Ncl; i++) {data[start+(like.Ncl*nz)+i] = 0.;} for (nz=1; nz<tomo.clustering_Nbin; nz++){ #else for (int nz=0; nz<tomo.clustering_Nbin; nz++){ #endif for (int i=0; i<like.Ncl; i++){ if (ell[i]<like.lmax_kappacmb && test_kmax(ell[i],nz)){ data[start+(like.Ncl*nz)+i] = C_gk_nointerp(ell[i],nz); } else{ data[start+(like.Ncl*nz)+i] = 0.; } } } } void set_data_ks(double *ell, double *data, int start) { for (int nz=0; nz<tomo.shear_Nbin; nz++){ for (int i=0; i<like.Ncl; i++){ if (ell[i]<like.lmax_kappacmb) { data[start+(like.Ncl*nz)+i] = C_ks_sys(ell[i],nz); } else{ data[start+(like.Ncl*nz)+i] = 0.; } } } } void set_data_kk(double *ell, double *data, int start) { for (int i=0; i<like.Ncl; i++){ if (ell[i]<like.lmax_kappacmb){ data[start+i] = C_kk_nointerp(ell[i]); } else{ data[start+i] = 0.; } } } int set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu) { cosmology.Omega_m=OMM; cosmology.Omega_v= 1.0-cosmology.Omega_m; cosmology.sigma_8=S8; cosmology.n_spec= NS; cosmology.w0=W0; cosmology.wa=WA; cosmology.omb=OMB; cosmology.h0=H0; cosmology.MGSigma=MGSigma; cosmology.MGmu=MGmu; if (cosmology.Omega_m < 0.1 || cosmology.Omega_m > 0.6) return 0; if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0; if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0; if (cosmology.n_spec < 0.85 || cosmology.n_spec > 1.05) return 0; if (cosmology.w0 < -2.0 || cosmology.w0 > -0.0) return 0; if (cosmology.wa < -2.5 || cosmology.wa > 2.5) return 0; if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0; if (cosmology.MGmu < -3.0 || cosmology.MGmu > 3.0) return 0; if (cosmology.MGSigma < -3.0 || cosmology.MGSigma > 3.0) return 0; // DESY1 extension paper flat priors //CH BEGINS //CH: to use for running planck15_BA0_w0_wa prior alone) //printf("like_fourier.c from WFIRST_forecasts: cosmology bounds set for running with planck15_BA0_w0_wa prior\n"); //if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0; //if (cosmology.omb < 0.01 || cosmology.omb > 0.1) return 0; //if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0; //if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0; //if (cosmology.w0 < -2.1 || cosmology.w0 > 1.5) return 0; //if (cosmology.wa < -5.0 || cosmology.wa > 2.6) return 0; //if (cosmology.h0 < 0.3 || cosmology.h0 > 0.9) return 0; //CH ENDS return 1; } void set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10) { nuisance.shear_calibration_m[0] = M1; nuisance.shear_calibration_m[1] = M2; nuisance.shear_calibration_m[2] = M3; nuisance.shear_calibration_m[3] = M4; nuisance.shear_calibration_m[4] = M5; nuisance.shear_calibration_m[5] = M6; nuisance.shear_calibration_m[6] = M7; nuisance.shear_calibration_m[7] = M8; nuisance.shear_calibration_m[8] = M9; nuisance.shear_calibration_m[9] = M10; } int set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1) { int i; nuisance.bias_zphot_shear[0]=SP1; nuisance.bias_zphot_shear[1]=SP2; nuisance.bias_zphot_shear[2]=SP3; nuisance.bias_zphot_shear[3]=SP4; nuisance.bias_zphot_shear[4]=SP5; nuisance.bias_zphot_shear[5]=SP6; nuisance.bias_zphot_shear[6]=SP7; nuisance.bias_zphot_shear[7]=SP8; nuisance.bias_zphot_shear[8]=SP9; nuisance.bias_zphot_shear[9]=SP10; for (i=0;i<tomo.shear_Nbin; i++){ nuisance.sigma_zphot_shear[i]=SPS1; if (nuisance.sigma_zphot_shear[i]<0.0001) return 0; } return 1; } int set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10,double CPS1) { int i; nuisance.bias_zphot_clustering[0]=CP1; nuisance.bias_zphot_clustering[1]=CP2; nuisance.bias_zphot_clustering[2]=CP3; nuisance.bias_zphot_clustering[3]=CP4; nuisance.bias_zphot_clustering[4]=CP5; nuisance.bias_zphot_clustering[5]=CP6; nuisance.bias_zphot_clustering[6]=CP7; nuisance.bias_zphot_clustering[7]=CP8; nuisance.bias_zphot_clustering[8]=CP9; nuisance.bias_zphot_clustering[9]=CP10; for (i=0;i<tomo.clustering_Nbin; i++){ nuisance.sigma_zphot_clustering[i]=CPS1; if (nuisance.sigma_zphot_clustering[i]<0.0001) return 0; } return 1; } int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q) { nuisance.A_ia=A_ia; nuisance.beta_ia=beta_ia; nuisance.eta_ia=eta_ia; nuisance.eta_ia_highz=eta_ia_highz; nuisance.LF_alpha=LF_alpha; nuisance.LF_P=LF_P; nuisance.LF_Q=LF_Q; nuisance.LF_red_alpha=LF_red_alpha; nuisance.LF_red_P=LF_red_P; nuisance.LF_red_Q=LF_red_Q; if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0; if (nuisance.beta_ia < -4.0 || nuisance.beta_ia > 6.0) return 0; if (nuisance.eta_ia < -10.0 || nuisance.eta_ia> 10.0) return 0; if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0; // if(like.IA!=0){ // if (check_LF()) return 0; // } return 1; } // int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz) // { // // nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior // // nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior // // nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior // // nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior // // fiducial values and priors from Murata et al. (2018) except for redshift-related parameters // nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0] // nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0] // nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5] // nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5] // nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5] // nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5] // if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0; // if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0; // if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0; // if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0; // if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0; // if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0; // return 1; // } int set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10) { int i; gbias.b[0] = B1; gbias.b[1] = B2; gbias.b[2] = B3; gbias.b[3] = B4; gbias.b[4] = B5; gbias.b[5] = B6; gbias.b[6] = B7; gbias.b[7] = B8; gbias.b[8] = B9; gbias.b[9] = B10; for (i = 0; i < 10; i++){ // printf("in set routine %d %le\n",i,gbias.b[i]); #ifdef ONESAMPLE if (gbias.b[i] < 0.4 || gbias.b[i] > 5.0) return 0; #else if (gbias.b[i] < 0.4 || gbias.b[i] > 3.0) return 0; #endif } return 1; } // double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3) double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3) { int i,j,k,m=0,l; static double *pred; static double *ell; static double *ell_Cluster; static double darg; double chisqr,a,log_L_prior=0.0, log_L=0.0;; if(ell==0){ pred= create_double_vector(0, like.Ndata-1); ell= create_double_vector(0, like.Ncl-1); darg=(log(like.lmax)-log(like.lmin))/like.Ncl; for (l=0;l<like.Ncl;l++){ ell[l]=exp(log(like.lmin)+(l+0.5)*darg); } // ell_Cluster= create_double_vector(0, Cluster.lbin-1); // darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin; // for (l=0;l<Cluster.lbin;l++){ // ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg); // } } if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){ printf("Cosmology out of bounds\n"); return -1.0e15; } set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10); if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1)==0){ printf("Shear photo-z sigma too small\n"); return -1.0e15; } if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1)==0){ printf("Clustering photo-z sigma too small\n"); return -1.0e15; } if (set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q)==0){ printf("IA parameters out of bounds\n"); return -1.0e15; } if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){ printf("Bias out of bounds\n"); return -1.0e15; } // if (set_nuisance_cluster_Mobs(mass_obs_norm, mass_obs_slope, mass_z_slope, mass_obs_scatter_norm, mass_obs_scatter_mass_slope, mass_obs_scatter_z_slope)==0){ // printf("Mobs out of bounds\n"); // return -1.0e15; // } printf("like %le %le %le %le %le %le %le %le\n",cosmology.Omega_m, cosmology.Omega_v,cosmology.sigma_8,cosmology.n_spec,cosmology.w0,cosmology.wa,cosmology.omb,cosmology.h0); // printf("like %le %le %le %le\n",gbias.b[0][0], gbias.b[1][0], gbias.b[2][0], gbias.b[3][0]); // for (i=0; i<10; i++){ // printf("nuisance %le %le %le\n",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]); // } log_L_prior=0.0; // if(like.Aubourg_Planck_BAO_SN==1) log_L_prior+=log_L_Planck_BAO_SN(); // if(like.SN==1) log_L_prior+=log_L_SN(); //if(like.BAO==1) log_L_prior+=log_L_BAO(); // if(like.Planck==1) log_L_prior+=log_L_Planck(); // if(like.Planck15_BAO_w0wa==1) log_L_prior+=log_L_Planck15_BAO_w0wa();//CH //if(like.Planck15_BAO_H070p6_JLA_w0wa==1) log_L_prior+=log_L_Planck15_BAO_H070p6_JLA_w0wa();//CH // if(like.IA!=0) log_L_prior+=log_L_ia(); // if(like.IA!=0) log_L_prior+=log_like_f_red(); if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz(); if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz(); if(like.shearcalib==1) log_L_prior+=log_L_shear_calib(); if(like.IA!=0) { log_L = 0.0; log_L -= pow((nuisance.A_ia - prior.A_ia[0])/prior.A_ia[1],2.0); log_L -= pow((nuisance.beta_ia - prior.beta_ia[0])/prior.beta_ia[1],2.0); log_L -= pow((nuisance.eta_ia - prior.eta_ia[0])/prior.eta_ia[1],2.0); log_L -= pow((nuisance.eta_ia_highz - prior.eta_ia_highz[0])/prior.eta_ia_highz[1],2.0); log_L_prior+=0.5*log_L; } if(like.baryons==1){; log_L = 0.0; log_L -= pow((Q1 - prior.bary_Q1[0])/prior.bary_Q1[1],2.0); log_L -= pow((Q2 - prior.bary_Q2[0])/prior.bary_Q2[1],2.0); log_L -= pow((Q3 - prior.bary_Q3[0])/prior.bary_Q3[1],2.0); log_L_prior+=0.5*log_L; } // if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs(); // printf("%d %d %d %d\n",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib); // printf("logl %le %le %le %le\n",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs()); int start=0; // clock_t t1, t2; // t1 = clock(); if(like.shear_shear==1) { set_data_shear(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.shear_Npowerspectra; } // t2 = clock(); printf("shear: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.shear_pos==1){ set_data_ggl(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.ggl_Npowerspectra; } // t2 = clock(); printf("ggl: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.pos_pos==1){ set_data_clustering(like.Ncl,ell,pred, start); start=start+like.Ncl*tomo.clustering_Npowerspectra; } // t2 = clock(); printf("gg: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.gk==1) { set_data_gk(ell, pred, start); start += like.Ncl*tomo.clustering_Nbin; } // t2 = clock(); printf("gk: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.ks==1) { set_data_ks(ell, pred, start); start += like.Ncl*tomo.shear_Nbin; } // t2 = clock(); printf("ks: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.kk==1) { set_data_kk(ell, pred, start); start += like.Ncl; } // t2 = clock(); printf("kk: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; chisqr=0.0; for (i=0; i<like.Ndata; i++){ for (j=0; j<like.Ndata; j++){ a=(pred[i]-data_read(1,i)+Q1*bary_read(1,0,i)+Q2*bary_read(1,1,i)+Q3*bary_read(1,2,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)+Q1*bary_read(1,0,j)+Q2*bary_read(1,1,j)+Q3*bary_read(1,2,j)); //a=(pred[i]-data_read(1,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)); chisqr=chisqr+a; } // if (fabs(data_read(1,i)) < 1.e-25){ // printf("%d %le %le %le\n",i,data_read(1,i),pred[i],invcov_read(1,i,i)); // } } // t2 = clock(); printf("chisqr: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if (chisqr<0.0){ printf("error: chisqr = %le\n",chisqr); //exit(EXIT_FAILURE); } printf("%le\n",chisqr); return -0.5*chisqr+log_L_prior; } // void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3) void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3) { int i,j,k,m=0,l; static double *pred; static double *ell; // static double *ell_Cluster; static double darg; double chisqr,a,log_L_prior=0.0; if(ell==0){ pred= create_double_vector(0, like.Ndata-1); ell= create_double_vector(0, like.Ncl-1); darg=(log(like.lmax)-log(like.lmin))/like.Ncl; for (l=0;l<like.Ncl;l++){ ell[l]=exp(log(like.lmin)+(l+0.5)*darg); } // ell_Cluster= create_double_vector(0, Cluster.lbin-1); // darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin; // for (l=0;l<Cluster.lbin;l++){ // ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg); // } } // for (l=0;l<like.Ncl;l++){ // printf("%d %le\n",i,ell[l]); // } // clock_t t1, t2; // t1 = clock(); set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu); set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10); set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1); set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1); set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q); set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10); // set_nuisance_cluster_Mobs(mass_obs_norm,mass_obs_slope,mass_z_slope,mass_obs_scatter_norm,mass_obs_scatter_mass_slope,mass_obs_scatter_z_slope); // t2 = clock(); printf("setting: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; int start=0; if(like.shear_shear==1) { set_data_shear(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.shear_Npowerspectra; } // t2 = clock(); printf("shear: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.shear_pos==1){ //printf("ggl\n"); set_data_ggl(like.Ncl, ell, pred, start); start=start+like.Ncl*tomo.ggl_Npowerspectra; } // t2 = clock(); printf("ggl: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.pos_pos==1){ //printf("clustering\n"); set_data_clustering(like.Ncl,ell,pred, start); start=start+like.Ncl*tomo.clustering_Npowerspectra; } // t2 = clock(); printf("gg: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.gk==1) { printf("Computing data vector: gk\n"); set_data_gk(ell, pred, start); start += like.Ncl * tomo.clustering_Nbin; } // t2 = clock(); printf("gk: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if(like.ks==1) { printf("Computing data vector: ks\n"); set_data_ks(ell, pred, start); start += like.Ncl * tomo.shear_Nbin; } // t2 = clock(); printf("ks: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; if (like.kk) { printf("Computing data vector: kk\n"); set_data_kk(ell, pred, start); start += like.Ncl; } // t2 = clock(); printf("kk: %le\n", (double)(t2-t1)/CLOCKS_PER_SEC); t1 = t2; FILE *F; char filename[300]; if (strstr(details,"FM") != NULL){ sprintf(filename,"%s",details); } else {sprintf(filename,"datav/%s_%s",like.probes,details);} F=fopen(filename,"w"); for (i=0;i<like.Ndata; i++){ fprintf(F,"%d %le\n",i,pred[i]); //printf("%d %le\n",i,pred[i]); } fclose(F); // printf("&gbias.b1_function %p\n",&gbias.b1_function); // printf("gbias.b1_function %p\n",gbias.b1_function); // printf("bgal_z %p\n",bgal_z); // printf("&bgal_z %p\n",&bgal_z); // printf("b1_per_bin %p\n",b1_per_bin); // printf("&b1_per_bin %p\n",&b1_per_bin); } void write_datavector_wrapper(char *details, input_cosmo_params_local ic, input_nuisance_params_local in) { // compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, // in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], // in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], // in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], // in.source_z_s, // in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], // in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], // in.lens_z_s, // in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], // in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], // in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, // in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], // in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3], // in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]); compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], in.lens_z_s, in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], in.bary[0], in.bary[1], in.bary[2]); } double log_like_wrapper(input_cosmo_params_local ic, input_nuisance_params_local in) { // double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, // in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], // in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], // in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], // in.source_z_s, // in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], // in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], // in.lens_z_s, // in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], // in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], // in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, // in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], // in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3], // in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]); double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], in.lens_z_s, in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], in.bary[0], in.bary[1], in.bary[2]); return like; } double log_like_wrapper_1sample(input_cosmo_params_local ic, input_nuisance_params_local in) // Only used in sampling, not in datav { double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu, in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], in.source_z_s, in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz, in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], in.bary[0], in.bary[1], in.bary[2]); return like; } void save_zdistr_sources(int zs){ double z,dz =(redshift.shear_zdistrpar_zmax-redshift.shear_zdistrpar_zmin)/300.0; printf("Printing redshift distribution n(z) for source redshift bin %d\n",zs); FILE *F1; char filename[300]; sprintf(filename,"zdistris/zdist_sources_bin%d.txt",zs); F1 = fopen(filename,"w"); for (z =redshift.shear_zdistrpar_zmin; z< redshift.shear_zdistrpar_zmax; z+= dz){ fprintf(F1,"%e %e\n", z, zdistr_photoz(z,zs)); } } void save_zdistr_lenses(int zl){ double z,dz =(redshift.clustering_zdistrpar_zmax-redshift.clustering_zdistrpar_zmin)/300.0; printf("Printing redshift distribution n(z) and bias b(z) for lens redshift bin %d\n",zl); FILE *F1; char filename[300]; sprintf(filename,"zdistris/zdist_lenses_bin%d.txt", zl); F1 = fopen(filename,"w"); for (z =redshift.clustering_zdistrpar_zmin; z< redshift.clustering_zdistrpar_zmax; z+= dz){ fprintf(F1,"%e %e\n", z, pf_photoz(z,zl)); } } int main(int argc, char** argv) { int i; char arg1[400],arg2[400],arg3[400]; /* here, do your time-consuming job */ int sce=atoi(argv[1]); int N_scenarios=2; double sigma_zphot_shear[3]={0.05,0.05}; double sigma_zphot_clustering[3]={0.03,0.03}; double area_table[2]={12300.0,16500.0}; // Y1 corresponds to DESC SRD Y1, Y6 corresponds to assuming that we cover the full SO area=0.4*fsky and at a depth of 26.1 which is in a range of reasonable scenarios (see https://github.com/LSSTDESC/ObsStrat/tree/static/static ) double nsource_table[2]={11.0,23.0}; double nlens_table[2]={18.0,41.0}; char survey_designation[2][200]={"LSSTxSO_Y1","LSSTxSO_Y6"}; char tomo_binning_source[2][200]={"source_std","source_std"}; // even for lens=src, this setting is valid, because the input lens/src zfiles are generated with the same z-cut:(0.2,1.2) char source_zfile[2][400]={"src_LSSTY1ext_2-island","src_LSSTY6ext_2-island"}; #ifdef ONESAMPLE char lens_zfile[2][400]={"src_LSSTY1ext_2-island","src_LSSTY6ext_2-island"}; char tomo_binning_lens[2][200]={"lens=src","lens=src"}; nlens_table[0] = nsource_table[0]; nlens_table[1] = nsource_table[1]; sigma_zphot_clustering[0] = sigma_zphot_shear[0]; sigma_zphot_clustering[1] = sigma_zphot_shear[1]; #else char lens_zfile[2][400]={"lens_LSSTY1ext_2-island", "lens_LSSTY6ext_2-island"}; char tomo_binning_lens[2][200]={"LSST_gold","LSST_gold"}; #endif char cmb_yr[2][100]={"so_Y1","so_Y5"}; init_cosmo_runmode("halofit"); init_bary(argv[2]); init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10); init_priors(0.002,sigma_zphot_shear[sce],0.001,0.001,sigma_zphot_clustering[sce],0.001,0.001,3.0,1.2,3.8,2.0,16.0,5.0,0.8); init_survey(survey_designation[sce],nsource_table[sce],nlens_table[sce],area_table[sce]); sprintf(arg1,"zdistris/%s",source_zfile[sce]); sprintf(arg2,"zdistris/%s",lens_zfile[sce]); init_galaxies(arg1,arg2,"outlier_sim","outlier_sim",tomo_binning_source[sce],tomo_binning_lens[sce]); init_IA("NLA_HF","GAMA"); init_probes("6x2pt"); init_cmb(cmb_yr[sce]); #ifdef ONESAMPLE sprintf(arg3,"%s_1sample_%s_outext_2-island",survey_designation[sce],argv[2]); #else sprintf(arg3,"%s_%s_outext_2-island",survey_designation[sce],argv[2]); #endif compute_data_vector(arg3,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,\ gbias.b[0],gbias.b[1],gbias.b[2],gbias.b[3],gbias.b[4],\ gbias.b[5],gbias.b[6],gbias.b[7],gbias.b[8],gbias.b[9],\ 0.0,0.0,0.0,0.0,0.0,\ 0.0,0.0,0.0,0.0,0.0,\ sigma_zphot_shear[sce],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,sigma_zphot_clustering[sce],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0); return 0; }
{ "alphanum_fraction": 0.6875615279, "avg_line_length": 47.9716646989, "ext": "c", "hexsha": "4992b63bd49a6950f1275605fe113d19780ece9d", "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": "43dfce33112480e17878b2de3421775ec9df296c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CosmoLike/LSSTxSO", "max_forks_repo_path": "like_fourier_fast_outext_2-island.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c", "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": "CosmoLike/LSSTxSO", "max_issues_repo_path": "like_fourier_fast_outext_2-island.c", "max_line_length": 999, "max_stars_count": null, "max_stars_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CosmoLike/LSSTxSO", "max_stars_repo_path": "like_fourier_fast_outext_2-island.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15067, "size": 40632 }
/* filter/impulse.c * * Impulse detecting filters * * 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 <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_filter.h> static int filter_impulse(const double scale, const double epsilon, const double t, const gsl_vector * x, const gsl_vector * xmedian, gsl_vector * y, gsl_vector * xsigma, size_t * noutlier, gsl_vector_int * ioutlier); /* gsl_filter_impulse_alloc() Allocate a workspace for impulse detection filtering. Inputs: K - number of samples in window; if even, it is rounded up to the next odd, to have a symmetric window Return: pointer to workspace */ gsl_filter_impulse_workspace * gsl_filter_impulse_alloc(const size_t K) { gsl_filter_impulse_workspace *w; w = calloc(1, sizeof(gsl_filter_impulse_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->movstat_workspace_p = gsl_movstat_alloc(K); if (w->movstat_workspace_p == 0) { gsl_filter_impulse_free(w); return NULL; } return w; } void gsl_filter_impulse_free(gsl_filter_impulse_workspace * w) { if (w->movstat_workspace_p) gsl_movstat_free(w->movstat_workspace_p); free(w); } /* gsl_filter_impulse() Apply an impulse detection filter to an input vector. The filter output is y_i = { x_i, |x_i - m_i| <= t * S_i { m_i, |x_i - m_i| > t * S_i where m_i is the median of the window W_i^H and S_i is the scale estimate (MAD, IQR, S_n, Q_n) Inputs: endtype - how to handle signal end points scale_type - which statistic to use for scale estimate (MAD, IQR, etc) t - number of standard deviations required to identity outliers (>= 0) x - input vector, size n y - (output) filtered vector, size n xmedian - (output) vector of median values of x, size n xmedian_i = median of window centered on x_i xsigma - (output) vector of estimated local standard deviations of x, size n xsigma_i = sigma for i-th window: scale*MAD noutlier - (output) number of outliers detected ioutlier - (output) int array indicating outliers identified, size n; may be NULL ioutlier_i = 1 if outlier detected, 0 if not w - workspace Notes: */ int gsl_filter_impulse(const gsl_filter_end_t endtype, const gsl_filter_scale_t scale_type, const double t, const gsl_vector * x, gsl_vector * y, gsl_vector * xmedian, gsl_vector * xsigma, size_t * noutlier, gsl_vector_int * ioutlier, gsl_filter_impulse_workspace * w) { const size_t n = x->size; if (n != y->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else if (xmedian->size != n) { GSL_ERROR("xmedian vector must match input size", GSL_EBADLEN); } else if (xsigma->size != n) { GSL_ERROR("xsigma vector must match input size", GSL_EBADLEN); } else if ((ioutlier != NULL) && (ioutlier->size != n)) { GSL_ERROR("ioutlier vector must match input size", GSL_EBADLEN); } else if (t < 0.0) { GSL_ERROR("t must be non-negative", GSL_EDOM); } else { int status; double scale = 1.0; switch (scale_type) { case GSL_FILTER_SCALE_MAD: { /* compute window medians and MADs */ gsl_movstat_mad(endtype, x, xmedian, xsigma, w->movstat_workspace_p); break; } case GSL_FILTER_SCALE_IQR: { /* multiplication factor for IQR to estimate stddev for Gaussian signal */ scale = 0.741301109252801; /* calculate the window medians */ gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p); /* calculate window IQRs */ gsl_movstat_qqr(endtype, x, 0.25, xsigma, w->movstat_workspace_p); break; } case GSL_FILTER_SCALE_SN: { /* calculate the window medians */ gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p); /* calculate window S_n values */ gsl_movstat_Sn(endtype, x, xsigma, w->movstat_workspace_p); break; } case GSL_FILTER_SCALE_QN: { /* calculate the window medians */ gsl_movstat_median(endtype, x, xmedian, w->movstat_workspace_p); /* calculate window Q_n values */ gsl_movstat_Qn(endtype, x, xsigma, w->movstat_workspace_p); break; } default: GSL_ERROR("unknown scale type", GSL_EDOM); break; } /* apply impulse detecting filter using previously computed scale estimate */ status = filter_impulse(scale, 0.0, t, x, xmedian, y, xsigma, noutlier, ioutlier); return status; } } /* filter_impulse() Apply an impulse detection filter to an input vector. The filter output is y_i = { x_i, |x_i - m_i| <= t * S_i OR S_i < epsilon { m_i, |x_i - m_i| > t * S_i where m_i is the median of the window W_i^H and S_i is the scale estimate (MAD, IQR, etc) Inputs: scale - scale factor to multiply xsigma to get unbiased estimate of stddev for Gaussian data epsilon - minimum allowed scale estimate for identifying outliers t - number of standard deviations required to identity outliers (>= 0) x - input vector, size n xmedian - vector of median values of x, size n xmedian_i = median of window centered on x_i y - (output) filtered vector, size n xsigma - (output) vector of estimated local standard deviations of x, size n xsigma_i = S_n for i-th window noutlier - (output) number of outliers detected ioutlier - (output) int array indicating outliers identified, size n; may be NULL ioutlier_i = 1 if outlier detected, 0 if not Notes: 1) If S_i = 0 or is very small for a particular sample, then the filter may erroneously flag the sample as an outlier, since it will act as a standard median filter. To avoid this scenario, the parameter epsilon specifies the minimum value of S_i which can be used in the filter test. Any samples for which S_i < epsilon are passed through unchanged. */ static int filter_impulse(const double scale, const double epsilon, const double t, const gsl_vector * x, const gsl_vector * xmedian, gsl_vector * y, gsl_vector * xsigma, size_t * noutlier, gsl_vector_int * ioutlier) { const size_t n = x->size; if (n != y->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else if (xmedian->size != n) { GSL_ERROR("xmedian vector must match input size", GSL_EBADLEN); } else if (xsigma->size != n) { GSL_ERROR("xsigma vector must match input size", GSL_EBADLEN); } else if ((ioutlier != NULL) && (ioutlier->size != n)) { GSL_ERROR("ioutlier vector must match input size", GSL_EBADLEN); } else if (t < 0.0) { GSL_ERROR("t must be non-negative", GSL_EDOM); } else { size_t i; *noutlier = 0; /* build output vector */ for (i = 0; i < n; ++i) { double xi = gsl_vector_get(x, i); double xmedi = gsl_vector_get(xmedian, i); double absdevi = fabs(xi - xmedi); /* absolute deviation for this sample */ double *xsigmai = gsl_vector_ptr(xsigma, i); /* multiply by scale factor to get estimate of standard deviation */ *xsigmai *= scale; /* * If the absolute deviation for this sample is more than t stddevs * for this window (and S_i is sufficiently large to avoid scale implosion), * set the output value to the window median, otherwise use the original sample */ if ((*xsigmai >= epsilon) && (absdevi > t * (*xsigmai))) { gsl_vector_set(y, i, xmedi); ++(*noutlier); if (ioutlier) gsl_vector_int_set(ioutlier, i, 1); } else { gsl_vector_set(y, i, xi); if (ioutlier) gsl_vector_int_set(ioutlier, i, 0); } } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.6179235206, "avg_line_length": 32.9647887324, "ext": "c", "hexsha": "201aa1050746c468b9cb635749180893f3fdf96b", "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": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/filter/impulse.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "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": "karanbirsandhu/nu-sense", "max_issues_repo_path": "test/lib/gsl-2.6/filter/impulse.c", "max_line_length": 133, "max_stars_count": null, "max_stars_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "karanbirsandhu/nu-sense", "max_stars_repo_path": "test/lib/gsl-2.6/filter/impulse.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2341, "size": 9362 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <math.h> #include <float.h> #include <iniparser.h> #include "tdsearch_gridsearch.h" #ifdef TDSEARCH_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "tdsearch_greens.h" #include "sacio.h" #include "parmt_utils.h" #include "iscl/array/array.h" #include "iscl/memory/memory.h" #include "iscl/os/os.h" #include "iscl/signal/convolve.h" #define NTSTAR 12 /*!< Default number of t*'s in the grid search. */ #define TSTAR0 0.1 /*!< Default first t* in grid search. */ #define TSTAR1 1.2 /*!< Default last t* in grid search. */ #define NDEPTH 12 /*!< Default number of depths in grid search. */ #define DEPTH0 0.0 /*!< First depth in grid search (km). */ #define DEPTH1 3.0 /*!< Last depth in grid search (km). */ #define DOUBLE_PAGE_SIZE sysconf(_SC_PAGE_SIZE)/sizeof(double) #define PAGE_SIZE sysconf(_SC_PAGE_SIZE) #define LDG 6 /*! * @brief Sets the default grid search parameters. * * @param[out] tds On exit contains the default grid search settings such * as the t* range, depth range, and toggles off the max * time shift. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_setDefaults(struct tdSearch_struct *tds) { int ierr; memset(tds, 0, sizeof(struct tdSearch_struct)); tds->maxShiftTime = DBL_MAX; ierr = tdsearch_gridSearch_defineTstarGrid(NTSTAR, TSTAR0, TSTAR1, tds); if (ierr != 0) { fprintf(stderr, "%s: Failed to set t* grid\n", __func__); return -1; } ierr = tdsearch_gridSearch_defineDepthGrid(NDEPTH, DEPTH0, DEPTH1, tds); if (ierr != 0) { fprintf(stderr, "%s: Failed to set depth grid\n", __func__); return -1; } return ierr; } //============================================================================// /*! * @brief Frees memory on the grid-search structure. * * @param[out] tds On exit all memory has been freed and parameters set to * 0 or NULL. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_free(struct tdSearch_struct *tds) { memory_free64f(&tds->G); memory_free64f(&tds->Gxc); memory_free64f(&tds->tstar); memory_free64f(&tds->depths); memory_free64f(&tds->synthetic); memory_free64f(&tds->xcorr); memory_free32i(&tds->lags); memory_free32i(&tds->grnsMatrixPtr); memory_free32i(&tds->grnsXCMatrixPtr); memset(tds, 0, sizeof(struct tdSearch_struct)); return 0; } //============================================================================// /*! * @brief Defines the t* grid in grid search. * * @param[in] ntstars Number of t*'s in grid search (> 0). * @param[in] tstar0 First t* in grid search (>= 0). * @param[in] tstar1 Final t* in grid search (>= tstar0). * * @param[out] tds Grid search structure with t* grid. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_defineTstarGrid(const int ntstars, const double tstar0, const double tstar1, struct tdSearch_struct *tds) { int ierr; tds->ntstar = 0; if (ntstars < 1 || tstar0 < 0.0 || tstar0 > tstar1) { if (ntstars < 1) { fprintf(stderr, "%s: Error no t*'s %d in search\n", __func__, ntstars); } if (tstar0 < 0.0) { fprintf(stderr, "%s: Error tstar0 %f must be non-negative\n", __func__, tstar0); } if (tstar0 > tstar1) { fprintf(stderr, "%s: Error tstar0 %f > tstar1 %f\n", __func__, tstar0, tstar1); } return -1; } tds->ntstar = ntstars; memory_free64f(&tds->tstar); tds->tstar = array_linspace64f(tstar0, tstar1, ntstars, &ierr); return ierr; } //============================================================================// /*! * @brief Defines the depth grid in grid search. * * @param[in] ndepths Number of depths in grid search (> 0). * @param[in] depth0 First depth (km) in grid search (>= 0). * @param[in] depth1 Final depth (km) in grid search (>= depth0). * * @param[out] tds Grid search structure with depth grid. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_defineDepthGrid(const int ndepths, const double depth0, const double depth1, struct tdSearch_struct *tds) { int ierr; tds->ndepth = 0; if (ndepths < 1 || depth0 < 0.0 || depth0 > depth1) { if (ndepths < 1) { fprintf(stderr, "%s: Error no depthss %d in search\n", __func__, ndepths); } if (depth0 < 0.0) { fprintf(stderr, "%s: Error depth0 %f must be non-negative\n", __func__, depth0); } if (depth0 > depth1) { fprintf(stderr, "%s: Error depth0 %f > depth1 %f\n", __func__, depth0, depth1); } return -1; } tds->ndepth = ndepths; memory_free64f(&tds->depths); tds->depths = array_linspace64f(depth0, depth1, ndepths, &ierr); return ierr; } //============================================================================// /*! * @brief Reads the grid search parameters from the ini file. * * @param[in] iniFile Name of ini file with parameters. * * @param[out] tds On successful exit contains the grid search parameters. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_initializeFromFile(const char *iniFile, struct tdSearch_struct *tds) { double depth0, depth1, tstar0, tstar1; dictionary *ini; int ierr, ndepth, ntstar; // Set the defaults ierr = 0; tdsearch_gridSearch_setDefaults(tds); // Verify the file exists if (!os_path_isfile(iniFile)) { fprintf(stderr, "%s: Error ini file %s doesn't exist\n", __func__, iniFile); return -1; } ini = iniparser_load(iniFile); // Unpack the parameter file tds->maxShiftTime = iniparser_getdouble(ini, "tdSearch:gridSearch:maxShiftTime\0", DBL_MAX); if (tds->maxShiftTime < DBL_MAX) { if (tds->maxShiftTime <= 0.0) { fprintf(stderr, "%s: Max shift time must be positive\n", __func__); ierr = 1; goto ERROR; } } // Number of t*'s ntstar = iniparser_getint(ini, "tdSearch:gridSearch:ntstar\0", NTSTAR); if (ntstar < 1) { fprintf(stderr, "%s: number of t*'s must be positive\n", __func__); ierr = 1; goto ERROR; } // Number of depths ndepth = iniparser_getint(ini, "tdSearch:gridSearch:ndepths\0", NDEPTH); if (ndepth < 1) { fprintf(stderr, "%s: number of depths must be positive\n", __func__); ierr = 1; goto ERROR; } // Depth grid search range depth0 = iniparser_getdouble(ini, "tdSearch:gridSearch:depth0\0", DEPTH0); depth1 = iniparser_getdouble(ini, "tdSearch:gridSearch:depth1\0", DEPTH1); if (depth0 >= depth1) { fprintf(stderr, "%s: depth0 >= depth1 is invalid\n", __func__); ierr = 1; goto ERROR; } // t* grid search range tstar0 = iniparser_getdouble(ini, "tdSearch:gridSearch:tstar0\0", TSTAR0); tstar1 = iniparser_getdouble(ini, "tdSearch:gridSearch:tstar1\0", TSTAR1); if (tstar0 >= tstar1) { fprintf(stderr, "%s: tstar0 >= tstar1 is invalid\n", __func__); ierr = 1; goto ERROR; } // Create the grid ierr = tdsearch_gridSearch_defineTstarGrid(ntstar, tstar0, tstar1, tds); if (ierr != 0) { fprintf(stderr, "%s: Error defining t* grid\n", __func__); goto ERROR; } ierr = tdsearch_gridSearch_defineDepthGrid(ndepth, depth0, depth1, tds); if (ierr != 0) { fprintf(stderr, "%s: Error defining depth grid\n", __func__); goto ERROR; } ERROR:; iniparser_freedict(ini); return ierr; } //============================================================================// /*! * @brief Returns the number of depths in the grid search. * * @param[in] tds Holds the number of t*'s. * * @result The number of t*'s in the grid search. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_getNumberOfTstars(const struct tdSearch_struct tds) { return tds.ntstar; } //============================================================================// /*! * @brief Returns the number of depths in the grid search. * * @param[in] tds Holds the number of depths. * * @result The number of depths in the grid search. * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_getNumberOfDepths(const struct tdSearch_struct tds) { return tds.ndepth; } //============================================================================// /*! * @brief Convenience utility for computing the index corresponding to the * 2D row major depth x t* grid. * * @param[in] it The t* index [0,ntstar-1]. * @param[in] id The depth indx [0,ndepth-1]. * @param[in] ntstar The number of t*'s in the grid search. * * @result The grid search index (= id*ntstar + it). * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_gridToIndex2(const int it, const int id, const int ntstar) { int idt; idt = id*ntstar + it; return idt; } //============================================================================// /*! * @brief Convenience utility for computing the index corresponding to the * 2D row major depth x t* grid. * * @param[in] it The t* index [0,ntstar-1]. * @param[in] id The depth indx [0,ndepth-1]. * @param[in] tds Grid search structure holding the number of ntstar's * in the grid search. * * @result The grid search index (= id*tds.ntstar + it). * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_gridToIndex(const int it, const int id, const struct tdSearch_struct tds) { int idt, ntstar; ntstar = tdsearch_gridSearch_getNumberOfTstars(tds); idt = tdsearch_gridSearch_gridToIndex2(it, id, ntstar); return idt; } //============================================================================// /*! * @brief Computes the forward modeling matrix, G, so that estimates, e, can * can be efficiently generated via \f$ G m = e \f$ for any moment * tensor, m. The columns of G represent cross-correlations of the * Green's functions corresponding to the \f$ m_{ij} \f$ moment tensor * component so that the estimate, e, is a cross-correlogram. * * @param[in] iobs Observation index in the range [0,nobs-1]. * @param[in] data Structure containing the data. * @param[in] grns Structure containing the Green's functions. * * @param[in,out] tds On input contains the initialized tds structure. * @param[in,out] tds On exit the forward modeling matrix G has been set. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdsearch_gridSearch_setForwardModelingMatrices( const int iobs, const struct tdSearchData_struct data, const struct tdSearchGreens_struct grns, struct tdSearch_struct *tds) { double *G, *Gxc, *work; int *grnsMatrixPtr, *grnsXCMatrixPtr, indices[6], i, idep, idt, ierr, indx, it, jndx, kndx, lxc, lxcMax, lxc0, ntstar, ndepth, npgrns, npts; // Reset pointers memory_free64f(&tds->G); memory_free64f(&tds->Gxc); memory_free32i(&tds->grnsMatrixPtr); memory_free32i(&tds->grnsXCMatrixPtr); // Check sizes ndepth = grns.ndepth; ntstar = grns.ntstar; if (ndepth != tds->ndepth || ntstar != tds->ntstar) { if (ndepth != tds->ndepth) { fprintf(stderr, "%s: Error ndepth %d != tds->ndepth %d\n", __func__, ndepth, tds->ndepth); } if (ntstar != tds->ntstar) { fprintf(stderr, "%s: Error ntstar %d != tds->ntstar %d\n", __func__, ntstar, tds->ntstar); } return -1; } npts = data.obs[iobs].npts; if (npts < 1) { fprintf(stderr, "%s: Error data has no points\n", __func__); return -1; } tds->dnorm = cblas_dnrm2(npts, data.obs[iobs].data, 1); if (fabs(tds->dnorm) < DBL_EPSILON) { fprintf(stderr, "%s: Error - data is identically zero\n", __func__); return -1; } tds->npts = npts; sacio_getFloatHeader(SAC_FLOAT_DELTA, data.obs[iobs].header, &tds->dt); // Set the Green's functions forward modeling matrix size lxcMax = 0; grnsMatrixPtr = memory_calloc32i(ndepth*ntstar+1); grnsXCMatrixPtr = memory_calloc32i(ndepth*ntstar+1); grnsMatrixPtr[0] = 0; grnsXCMatrixPtr[0] = 0; for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { // Get the Green's functions indices ierr = tdsearch_greens_getGreensFunctionsIndices(iobs, it, idep, grns, indices); if (ierr != 0) { fprintf(stderr, "%s: Failed to get indices\n", __func__); return -1; } // Compute the cross-correlation length at (dep, t*) idt = tdsearch_gridSearch_gridToIndex2(it, idep, ntstar); lxc0 = 0; for (i=0; i<6; i++) { indx = indices[i]; npgrns = grns.grns[indx].npts; if (npgrns < 1) { fprintf(stderr, "%s: Error - no points in grns fn\n", __func__); return -1; } lxc = npgrns + npts - 1; lxcMax = MAX(lxcMax, lxc); if (i == 0) { lxc0 = lxc; grnsMatrixPtr[idt+1] = grnsMatrixPtr[idt] + npgrns; grnsXCMatrixPtr[idt+1] = grnsXCMatrixPtr[idt] + lxc; } if (lxc != lxc0) { fprintf(stderr, "%s: Inconsistent column sizes\n", __func__); return -1; } } } } if (lxcMax < 1) { fprintf(stderr, "%s: Error - cross-correlations are empty\n", __func__); return -1; } // Set the forward modeling matrices tds->nptsGrns = grnsMatrixPtr[ndepth*ntstar]; G = memory_calloc64f(LDG*grnsMatrixPtr[ndepth*ntstar]); Gxc = memory_calloc64f(LDG*grnsXCMatrixPtr[ndepth*ntstar]); work = memory_calloc64f(lxcMax); for (idep=0; idep<ndepth; idep++) { for (it=0; it<ntstar; it++) { idt = tdsearch_gridSearch_gridToIndex2(it, idep, ntstar); // Get the Green's functions indices ierr = tdsearch_greens_getGreensFunctionsIndices(iobs, it, idep, grns, indices); // Compute the cross-correlation length at (dep, t*) idt = tdsearch_gridSearch_gridToIndex2(it, idep, ntstar); jndx = LDG*grnsMatrixPtr[idt]; kndx = LDG*grnsXCMatrixPtr[idt]; for (i=0; i<6; i++) { indx = indices[i]; npgrns = grns.grns[indx].npts; signal_convolve_correlate64f_work(npts, data.obs[iobs].data, npgrns, grns.grns[indx].data, CONVCOR_FULL, lxc, work); //printf("%e %e\n",cblas_dnrm2(npgrns, grns.grns[indx].data, 1), // cblas_dnrm2(lxc, work, 1)); cblas_dcopy(npgrns, grns.grns[indx].data, 1, &G[jndx+i], LDG); cblas_dcopy(lxc, work, 1, &Gxc[kndx+i], LDG); } //printf("%d\n", grnsMatrixPtr[idt+1]); } } tds->G = G; tds->Gxc = Gxc; tds->grnsMatrixPtr = grnsMatrixPtr; tds->grnsXCMatrixPtr = grnsXCMatrixPtr; memory_free64f(&work); return 0; } //============================================================================// /*! * @brief Sets the moment tensor on the tdSearch structure. * * @param[in] m6 moment tensor in NED system packed: * \f$ \{ m_{xx}, m_{yy}, m_{zz}, * m_{xy}, m_{xz}, m_{yz} \} \f$. * * @param[out] tds On successful exit contains the moment tensor. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * * @author Ben Baker, ISTI * */ int tdSearch_gridSearch_setMomentTensor(const double *__restrict__ m6, struct tdSearch_struct *tds) { tds->lhaveMT = false; array_zeros64f_work(8, tds->mt); // NOTE - this is padded if (m6 == NULL) { fprintf(stderr, "%s: Error moment tensor cannot be NULL\n", __func__); return -1; } array_copy64f_work(6, m6, tds->mt); tds->lhaveMT = true; return 0; } //============================================================================// /*! * @brief Sets the moment tensor elements on the grid search structure. * * @param[in] m11 m11 moment tensor in Newton meters. * @param[in] m22 m22 moment tensor in Newton meters. * @param[in] m33 m33 moment tensor in Newton meters. * @param[in] m12 m12 moment tensor in Newton meters. * @param[in] m13 m13 moment tensor in Newton meters. * @param[in] m23 m23 moment tensor in Newton meters. * @param[in] basis The appropriate moment tensor basis. * @param[in] basis CE_USE indicates the moment tensor is in up, south * east coordinates like what one would obtain from * the GCMT catalog. * @param[in] basis CE_NED indicates the moment tensor is in north, east, * down coordinates and is consistent with Programs in * Seismology. * * @param[in,out] tds On input contains the initialized grid search * structure. * @param[in,out] tds On exit contains the input moment tensor. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * */ int tdSearch_gridSearch_setMomentTensorFromElements( const double m11, const double m22, const double m33, const double m12, const double m13, const double m23, const enum compearthCoordSystem_enum basis, struct tdSearch_struct *tds) { double mt[6], mtNED[6]; int ierr; tds->lhaveMT = false; mt[0] = m11; mt[1] = m22; mt[2] = m33; mt[3] = m12; mt[4] = m13; mt[5] = m23; ierr = compearth_convertMT(1, basis, CE_NED, mt, mtNED); if (ierr != 0) { printf("%s: Failed to set moment tensor\n", __func__); return -1; } ierr = tdSearch_gridSearch_setMomentTensor(mtNED, tds); if (ierr != 0) { printf("%s: Failed to set moment tensor\n", __func__); return -1; } return 0; } //============================================================================// /*! * @brief Sets the moment tensor information from an event structure. * * @param[in] event Contains the event on which the moment tensor is defined. * @param[in,out] tds On input this is the initialized grid search structure. * @param[in,out] tds On exit contains the given moment tensor. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * */ int tdSearch_gridSearch_setMomentTensorFromEvent( const struct tdSearchEventParms_struct event, struct tdSearch_struct *tds) { int ierr; ierr = tdSearch_gridSearch_setMomentTensorFromElements( event.m11, event.m22, event.m33, event.m12, event.m13, event.m23, event.basis, tds); if (ierr != 0) { fprintf(stderr, "%s: Error setting moment tensor\n", __func__); return -1; } return 0; } //============================================================================// /*! * @brief Computes the cross-correlations between the data and synthetics * at each (t*,depth) in the grid search. * * @param[in,out] tds On input contains the initialized grid search * structure with the Green's functions and source * properties. * @param[in,out] tds On exit contains the result of the cross-correlations * and lags at each (t*,depth) in the grid search. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * */ int tdSearch_gridSearch_performGridSearch(struct tdSearch_struct *tds) { double *u, *ud, dnorm, unorm; int id, idt, indx, iopt, it, jndx, l1, l2, lxc, maxlags, ndepth, ndt, nlag, npgrns, nrows, ntstar; const int ncols = 6; enum isclError_enum ierr; tds->itopt =-1; tds->idopt =-1; ndepth = tds->ndepth; ntstar = tds->ntstar; ndt = ntstar*ndepth; dnorm = tds->dnorm; memory_free64f(&tds->xcorr); memory_free64f(&tds->synthetic); memory_free32i(&tds->lags); // Some easy checks if (!tds->lhaveMT) { fprintf(stderr, "%s: Error moment tensor not set\n", __func__); return -1; } if (tds->G == NULL || tds->Gxc == NULL || tds->grnsMatrixPtr == NULL || tds->grnsXCMatrixPtr == NULL) { fprintf(stderr, "%s: You need to set the forward modeling matrices\n", __func__); return -1; } maxlags =-1; if (tds->maxShiftTime < DBL_MAX) { maxlags = (int) (tds->maxShiftTime/tds->dt + 0.5); } // Set output space tds->xcorr = memory_calloc64f(ndt); tds->lags = memory_calloc32i(ndt); // Compute the cross-correlation nrows = tds->grnsXCMatrixPtr[ndt]; ud = memory_calloc64f(nrows); cblas_dgemv(CblasRowMajor, CblasNoTrans, nrows, ncols, 1.0, tds->Gxc, LDG, tds->mt, 1, 0.0, ud, 1); // Compute the synthetics nrows = tds->grnsMatrixPtr[ndt]; u = memory_calloc64f(nrows); cblas_dgemv(CblasRowMajor, CblasNoTrans, nrows, ncols, 1.0, tds->G, LDG, tds->mt, 1, 0.0, u, 1); // Now do the grid search for (id=0; id<ndepth; id++) { for (it=0; it<ntstar; it++) { idt = tdsearch_gridSearch_gridToIndex(it, id, *tds); indx = tds->grnsMatrixPtr[idt]; jndx = tds->grnsXCMatrixPtr[idt]; lxc = tds->grnsXCMatrixPtr[idt+1] - tds->grnsXCMatrixPtr[idt]; npgrns = tds->grnsMatrixPtr[idt+1] - tds->grnsMatrixPtr[idt]; unorm = cblas_dnrm2(npgrns, &u[indx], 1); if (maxlags < 0) { iopt = array_argmax64f(lxc, &ud[jndx], &ierr); } else { l1 = MAX(0, npgrns - maxlags); l2 = MIN(lxc-1, npgrns + maxlags); nlag = l2 - l1 + 1; iopt = l1 + array_argmax64f(nlag, &ud[jndx+l1], &ierr); /* for (int k=0; k<lxc; k++) { printf("%d %e\n",k, ud[jndx+k]); } getchar(); */ } tds->xcorr[idt] = ud[jndx+iopt]/(dnorm*unorm); // Compute the lag where the times range from [-npts+1:npgrns-1] tds->lags[idt] =-npgrns + 1 + iopt; //printf("%f %f %f %d\n", tds->depths[id], tds->tstar[it], xc, idelay); } //printf("\n"); } tds->synthetic = u; memory_free64f(&ud); // Compute the optimum indices iopt = array_argmax64f(ndt, tds->xcorr, &ierr); tds->idopt = iopt/tds->ntstar; tds->itopt = iopt - tds->idopt*tds->ntstar; if (tdsearch_gridSearch_gridToIndex(tds->itopt, tds->idopt, *tds) != iopt) { fprintf(stdout, "%s: Switching to slow optimum computation\n", __func__); for (id=0; id<ndepth; id++) { for (it=0; it<ntstar; it++) { idt = tdsearch_gridSearch_gridToIndex(it, id, *tds); if (iopt == idt) { tds->idopt = id; tds->itopt = it; } } } } return 0; } //============================================================================// /*! * @brief Writes a map of the max of the cross-correlograms as a function * of t* and depth in a format useful for Gnpulot as well as a * corresponding Gnuplot plotting script. * * @param[in] dirnm Directory where the heat map is to be written. * @param[in] froot The root name of the heat map. * @param[in] tds Grid search structure with the tabulated * cross-correlogram maximums. * * @result 0 indicates success. * * @ingroup tdsearch_gridsearch * */ int tdsearch_gridSearch_writeHeatMap(const char *dirnm, const char *froot, const struct tdSearch_struct tds) { FILE *ofl; char fname[PATH_MAX], fgnu[PATH_MAX], cmd[256]; int id, idt, it; memset(fname, 0, PATH_MAX*sizeof(char)); if (!tds.xcorr || !tds.lags) { fprintf(stderr, "%s: Error gridsearch likely not performed\n", __func__); return -1; } if (!tds.tstar || !tds.depths) { fprintf(stderr, "%s: Error tds likely not initialized\n", __func__); return -1; } if (dirnm != NULL) { sprintf(fname, "%s/%s.surf_txt", dirnm, froot); } else { sprintf(fname, "./%s.surf_txt", froot); } ofl = fopen(fname, "w"); for (id=0; id<tds.ndepth; id++) { for (it=0; it<tds.ntstar; it++) { idt = tdsearch_gridSearch_gridToIndex(it, id, tds); fprintf(ofl, "%f %f %e %d\n", tds.tstar[it], tds.depths[id], tds.xcorr[idt], tds.lags[idt]); } fprintf(ofl, "\n"); } fclose(ofl); // and the gnuplot file memset(fgnu, 0, PATH_MAX*sizeof(char)); if (dirnm != NULL) { sprintf(fgnu, "%s/%s.gnu", dirnm, froot); } else { sprintf(fgnu, "./%s.gnu", froot); } ofl = fopen(fgnu, "w"); fprintf(ofl, "#!/usr/bin/gnuplot -persist\n"); fprintf(ofl, "set pm3d map\n"); fprintf(ofl, "set xlabel 't*'\n"); fprintf(ofl, "set ylabel 'Depth (km)'\n"); fprintf(ofl, "set title 'Cross-Correlation'\n"); fprintf(ofl, "set grid\n"); fprintf(ofl, "set xrange [%f:%f]\n", tds.tstar[0], tds.tstar[MAX(0, tds.ntstar-1)]); fprintf(ofl, "set yrange [%f:%f]\n", tds.depths[MAX(0, tds.ndepth-1)], tds.depths[0]); fprintf(ofl, "splot '%s.surf_txt' u 1:2:3\n", froot); fclose(ofl); // change permissions memset(cmd, 0, 256*sizeof(char)); sprintf(cmd, "chmod 0755 %s", fgnu); system(cmd); return 0; } //============================================================================// /*! * @brief Makes a shifted synthetic seismogram corresponding to the * given observation, t*, and depth. * * @param[in] iobs Observation index in the range [0,nobs-1]. * @param[in] it t* index in the range [0,tds.ntstar-1]. * @param[in] id Depth index in the range [0,tds.ndepth]. * @param[in] data Contains the observed seismograms. * @param[in] grns Contains the Green's functions used to make * the synthetic seisogram. * @param[in] tds Contains the time lags computed in the grid search. * * @param[out] synth Structure containing the synthetic seismogram. * @result 0 indicates success. * * @ingroup tdsearch_gridsearch */ int tdSearch_gridSearch_makeSACSynthetic( const int iobs, const int it, const int id, const struct tdSearchData_struct data, const struct tdSearchGreens_struct grns, const struct tdSearch_struct tds, struct sacData_struct *synth) { double epoch; int idt, ierr, igrns, npGrns; memset(synth, 0, sizeof(struct sacData_struct)); // Pick off the header if (it < 0 || it >= tds.ntstar || id < 0 || id >= tds.ndepth) { fprintf(stderr, "%s: Invalid (t*,depth) index (%d,%d)\n", __func__, it, id); return - 1; } if (tds.synthetic == NULL || tds.lags == NULL) { if (tds.synthetic == NULL) { fprintf(stderr, "%s: Error tds.synethetic is NULL\n", __func__); } if (tds.lags == NULL) { fprintf(stderr, "%s: Error tds.lags is NULL\n", __func__); } return -1; } idt = tdsearch_gridSearch_gridToIndex(it, id, tds); igrns = tdsearch_greens_getGreensFunctionIndex(G11_GRNS, iobs, it, id, grns); if (idt < 0 || igrns < 0) { fprintf(stderr, "%s: Failed getting an index\n", __func__); return -1; } // Copy header sacio_copyHeader(grns.grns[igrns].header, &synth->header); // Copy corresponding synthetic synth->npts = grns.grns[igrns].npts; synth->data = sacio_malloc64f(synth->npts); npGrns = tds.grnsMatrixPtr[idt+1] - tds.grnsMatrixPtr[idt]; if (npGrns != synth->npts) { fprintf(stderr, "%s: Size mismatch\n", __func__); sacio_free(synth); return -1; } array_copy64f_work(npGrns, &tds.synthetic[tds.grnsMatrixPtr[idt]], synth->data); // Get the component inline with the estimate sacio_setCharacterHeader(SAC_CHAR_KCMPNM, data.obs[iobs].header.kcmpnm, &synth->header); // Fix the timing ierr = sacio_getEpochalStartTime(synth->header, &epoch); if (ierr != 0) { fprintf(stderr, "%s: Failed to get start time\n", __func__); return -1; } epoch = epoch + (double) tds.lags[idt]*tds.dt; sacio_setEpochalStartTime(epoch, &synth->header); return 0; } //============================================================================//
{ "alphanum_fraction": 0.54358711, "avg_line_length": 33.3219251337, "ext": "c", "hexsha": "948426cd5a62b2a8902fa9c4916dd6bf5a396d31", "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": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/tdsearch", "max_forks_repo_path": "src/gridsearch.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Intel" ], "max_issues_repo_name": "bakerb845/tdsearch", "max_issues_repo_path": "src/gridsearch.c", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/tdsearch", "max_stars_repo_path": "src/gridsearch.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8594, "size": 31156 }
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, liyanrong@ihep.ac.cn * Thu, Aug 4, 2016 */ /*! * \file dnest_line2d.c * \brief run dnest for 2d line analysis. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <float.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_interp.h> #include <mpi.h> #include "brains.h" DNestFptrSet *fptrset_line2d; /*! * this function does dnest sampling. */ int dnest_line2d(int argc, char **argv) { int i; set_blr_model2d(); num_params_blr = num_params_blr_model + num_params_nlr + num_params_res + num_params_linecenter + 1; /* include line sys err */ num_params_blr_tot = num_params_blr; num_params = parset.n_con_recon + num_params_blr_tot + num_params_var; idx_resp = num_params_blr_tot + num_params_drw + num_params_trend; idx_difftrend = idx_resp + num_params_resp; idx_linecenter = num_params_blr_model + num_params_nlr + num_params_res; par_fix = (int *) malloc(num_params * sizeof(int)); par_fix_val = (double *) malloc(num_params * sizeof(double)); par_range_model = malloc( num_params * sizeof(double *)); par_prior_gaussian = malloc( num_params * sizeof(double *)); for(i=0; i<num_params; i++) { par_range_model[i] = malloc(2*sizeof(double)); par_prior_gaussian[i] = malloc(2*sizeof(double)); } par_prior_model = malloc( num_params * sizeof(int)); fptrset_line2d = dnest_malloc_fptrset(); /* setup functions used for dnest*/ fptrset_line2d->from_prior = from_prior_line2d; fptrset_line2d->print_particle = print_particle_line2d; fptrset_line2d->restart_action = restart_action_2d; fptrset_line2d->accept_action = accept_action_2d; fptrset_line2d->kill_action = kill_action_2d; fptrset_line2d->perturb = perturb_line2d; fptrset_line2d->read_particle = read_particle_line2d; if(parset.flag_exam_prior != 1) { fptrset_line2d->log_likelihoods_cal_initial = log_likelihoods_cal_initial_line2d; fptrset_line2d->log_likelihoods_cal_restart = log_likelihoods_cal_restart_line2d; fptrset_line2d->log_likelihoods_cal = log_likelihoods_cal_line2d; } else { fptrset_line2d->log_likelihoods_cal_initial = log_likelihoods_cal_line2d_exam; fptrset_line2d->log_likelihoods_cal_restart = log_likelihoods_cal_line2d_exam; fptrset_line2d->log_likelihoods_cal = log_likelihoods_cal_line2d_exam; } set_par_range_model2d(); /* setup the fixed parameters */ set_par_fix_blrmodel(); /* setup the remaining paramters */ for(i=num_params_blr_model; i<num_params; i++) { par_fix[i] = 0; par_fix_val[i] = -DBL_MAX; } /* cope with narrow line */ if(parset.flag_narrowline == 2) { /* flux */ if(parset.flux_narrowline_err == 0.0) { par_fix[num_params_blr_model] = 1.0; par_fix_val[num_params_blr_model] = 0.0; } } if(parset.flag_narrowline >= 2) { /* width */ if(parset.width_narrowline_err == 0.0) { par_fix[num_params_blr_model+1] = 1.0; par_fix_val[num_params_blr_model+1] = 0.0; } /* shift */ if(parset.shift_narrowline_err == 0.0) { par_fix[num_params_blr_model+2] = 1.0; par_fix_val[num_params_blr_model+2] = 0.0; } } /* if flag_fixvar is true, fix continuum variation parameter sigma and tau */ if(parset.flag_fixvar == 1) { par_fix[num_params_blr + 1] = 1; par_fix_val[num_params_blr + 1] = var_param[1]; par_fix[num_params_blr + 2] = 1; par_fix_val[num_params_blr + 2] = var_param[2]; } /* fix systematic error of line */ if(parset.flag_line_sys_err != 1) { par_fix[num_params_blr-1] = 1; par_fix_val[num_params_blr-1] = log(1.0); } /* fix systematic error of continuum */ if(parset.flag_con_sys_err != 1) { par_fix[num_params_blr] = 1; par_fix_val[num_params_blr] = log(1.0); } /* fix non-linear response */ if(parset.flag_nonlinear !=1) { par_fix[idx_resp + 1] = 1; par_fix_val[idx_resp + 1] = 0.0; } print_par_names_model2d(); force_update = parset.flag_force_update; if(parset.flag_para_name != 1) logz_line2d = dnest(argc, argv, fptrset_line2d, num_params, dnest_options_file); dnest_free_fptrset(fptrset_line2d); return 0; } /*! * this function setups parameter ranges. * * The order of parameters is: \n * I. blr model.............() \n * II. narrow line...........(if flag_narrowline is true)\n * III. spectral broadening...() \n * IV. line center...........(if flag_linecenter is true)\n * V. systematic error......() \n * VI. variability...........() \n * VII. long-term trend.......() \n * VIII.response A and Ag.....() \n * IX. different trend.......(if flag_difftend is ture) \n * X. continuum light curve.() \n */ void set_par_range_model2d() { int i, j, i1, i2; /* setup parameter range, BLR parameters first */ for(i=0; i<num_params_blr_model; i++) { par_range_model[i][0] = blr_range_model[i][0]; par_range_model[i][1] = blr_range_model[i][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; } /* cope with narrow line */ for(i=num_params_blr_model; i<num_params_blr_model + num_params_nlr; i++) { par_range_model[i][0] = nlr_range_model[i - num_params_blr_model][0]; par_range_model[i][1] = nlr_range_model[i - num_params_blr_model][1]; par_prior_model[i] = nlr_prior_model[i - num_params_blr_model]; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; /* note that for logarithm prior of flux, this value is not used, so does not matter */ } /* cope with spectral broadening */ for(i=num_params_blr_model + num_params_nlr; i<num_params_blr_model + num_params_nlr + num_params_res; i++) { par_range_model[i][0] = -10.0; par_range_model[i][1] = 10.0; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } /* cope with line center */ for(i=num_params_blr-num_params_linecenter-1; i< num_params_blr-1; i++) { par_range_model[i][0] = -10.0; par_range_model[i][1] = 10.0; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } /* the last is systematic error */ i = num_params_blr-1; par_range_model[i][0] = sys_err_line_range[0]; par_range_model[i][1] = sys_err_line_range[1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; /* variability parameters */ /* first systematic error */ i = num_params_blr; par_range_model[i][0] = var_range_model[0][0]; par_range_model[i][1] = var_range_model[0][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; for(i=num_params_blr+1; i<num_params_drw + num_params_blr; i++) { if(var_param_std[i-num_params_blr] > 0.0) { par_range_model[i][0] = var_param[i-num_params_blr] - 5.0 * var_param_std[i-num_params_blr]; par_range_model[i][1] = var_param[i-num_params_blr] + 5.0 * var_param_std[i-num_params_blr]; /* make sure that the range lies within the initial range */ par_range_model[i][0] = fmax(par_range_model[i][0], var_range_model[i-num_params_blr][0]); par_range_model[i][1] = fmin(par_range_model[i][1], var_range_model[i-num_params_blr][1]); par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = var_param[i-num_params_blr]; par_prior_gaussian[i][1] = var_param_std[i-num_params_blr]; } else { par_range_model[i][0] = var_range_model[i-num_params_blr][0]; par_range_model[i][1] = var_range_model[i-num_params_blr][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; } } /* long-term trend of continuum */ for(i=num_params_drw + num_params_blr; i< num_params_drw + num_params_trend + num_params_blr; i++) { par_range_model[i][0] = var_range_model[3][0]; par_range_model[i][1] = var_range_model[3][1]; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } /* response A and Ag */ j = 0; i1 = idx_resp; i2 = idx_resp + num_params_resp; for(i=i1; i<i2; i++) { par_range_model[i][0] = resp_range[j][0]; par_range_model[i][1] = resp_range[j][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; j++; } /* different trend in continuum and line */ j = 0; i1 = idx_difftrend; i2 = idx_difftrend + num_params_difftrend; for(i=i1; i< i2; i++) { par_range_model[i][0] = var_range_model[4 + j][0]; par_range_model[i][1] = var_range_model[4 + j][1]; par_prior_model[i] = UNIFORM; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 0.0; j++; } /* continuum ligth curve values */ for(i=num_params_blr+num_params_var; i<num_params; i++) { par_range_model[i][0] = var_range_model[4+num_params_difftrend][0]; par_range_model[i][1] = var_range_model[4+num_params_difftrend][1]; par_prior_model[i] = GAUSSIAN; par_prior_gaussian[i][0] = 0.0; par_prior_gaussian[i][1] = 1.0; } return; } /*! * print names and prior ranges for parameters * */ void print_par_names_model2d() { if(thistask != roottask) return; int i, j; FILE *fp; char fname[BRAINS_MAX_STR_LENGTH], str_fmt[BRAINS_MAX_STR_LENGTH]; sprintf(fname, "%s/%s", parset.file_dir, "data/para_names_model2d.txt"); fp = fopen(fname, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", fname); exit(0); } strcpy(str_fmt, "%4d %-15s %10.6f %10.6f %4d %4d %15.6e\n"); printf("# Print parameter name in %s\n", fname); fprintf(fp, "#*************************************************\n"); fprint_version(fp); fprintf(fp, "#*************************************************\n"); fprintf(fp, "%4s %-15s %10s %10s %4s %4s %15s\n", "#", "Par", "Min", "Max", "Prior", "Fix", "Val"); i=-1; for(j=0; j<num_params_blr_model; j++) { i++; fprintf(fp, str_fmt, i, "BLR model", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<num_params_nlr; j++) { i++; fprintf(fp, str_fmt, i, "narrow line", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<num_params_res; j++) { i++; fprintf(fp, str_fmt, i, "line broaden", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<num_params_linecenter; j++) { i++; fprintf(fp, str_fmt, i, "line center", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } i++; fprintf(fp, str_fmt, i, "sys_err_line", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "sys_err_con", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "sigmad", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "taud", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); for(j=0; j<num_params_trend; j++) { i++; fprintf(fp, str_fmt, i, "trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } i++; fprintf(fp, str_fmt, i, "A", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); i++; fprintf(fp, str_fmt, i, "Ag", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); for(j=0; j<num_params_difftrend; j++) { i++; fprintf(fp, str_fmt, i, "diff trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } for(j=0; j<parset.n_con_recon; j++) { i++; fprintf(fp, str_fmt, i, "time series", par_range_model[i][0], par_range_model[i][1], par_prior_model[i], par_fix[i], par_fix_val[i]); } fclose(fp); } /*! * this function generates a sample from prior. */ void from_prior_line2d(void *model) { int i; double *pm = (double *)model; for(i=0; i<num_params; i++) { if(par_prior_model[i] == GAUSSIAN) { pm[i] = dnest_randn()*par_prior_gaussian[i][1] + par_prior_gaussian[i][0]; dnest_wrap(&pm[i], par_range_model[i][0], par_range_model[i][1]); } else { pm[i] = par_range_model[i][0] + dnest_rand() * (par_range_model[i][1] - par_range_model[i][0]); } } /* cope with fixed parameters */ for(i=0; i<num_params_blr + num_params_var; i++) { if(par_fix[i] == 1) pm[i] = par_fix_val[i]; } which_parameter_update = -1; return; } /*! * this function calculates likelihood at initial step. */ double log_likelihoods_cal_initial_line2d(const void *model) { double logL; logL = prob_initial_line2d(model); return logL; } /*! * this function calculates likelihood at initial step. */ double log_likelihoods_cal_restart_line2d(const void *model) { double logL; logL = prob_restart_line2d(model); return logL; } /*! * this function calculates likelihood. */ double log_likelihoods_cal_line2d(const void *model) { double logL; logL = prob_line2d(model); return logL; } /*! * this function prints out parameters. */ void print_particle_line2d(FILE *fp, const void *model) { int i; double *pm = (double *)model; for(i=0; i<num_params; i++) { fprintf(fp, "%e ", pm[i] ); } fprintf(fp, "\n"); return; } /*! * This function read the particle from the file. */ void read_particle_line2d(FILE *fp, void *model) { int j; double *psample = (double *)model; for(j=0; j < dnest_num_params; j++) { if(fscanf(fp, "%lf", psample+j) < 1) { printf("%f\n", *psample); fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file); exit(0); } } return; } /*! * this function perturbs parameters. */ double perturb_line2d(void *model) { double *pm = (double *)model; double logH = 0.0, limit1, limit2, width, rnd; int which, which_level; /* * fixed parameters need not to update * perturb important parameters more frequently */ do { rnd = dnest_rand(); if(rnd < fmax(0.2, 1.0*(num_params_blr+num_params_var)/num_params)) which = dnest_rand_int(num_params_blr + num_params_var); else which = dnest_rand_int(parset.n_con_recon) + num_params_blr + num_params_var; }while(par_fix[which] == 1); which_parameter_update = which; /* level-dependent width */ which_level_update = dnest_get_which_level_update(); which_level = which_level_update > (size_levels-10)?(size_levels-10):which_level_update; if( which_level > 0) { limit1 = limits[(which_level-1) * num_params *2 + which *2]; limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1]; width = limit2 - limit1; } else { width = ( par_range_model[which][1] - par_range_model[which][0] ); } width /= (2.35); if(par_prior_model[which] == GAUSSIAN) { logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) ); pm[which] += dnest_randh() * width; dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]); logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) ); } else { pm[which] += dnest_randh() * width; dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]); } return logH; } /*! * this function calculates likelihood. */ double log_likelihoods_cal_line2d_exam(const void *model) { return 0.0; } void accept_action_2d() { int param; double *ptemp; // the parameter previously updated param = which_parameter_update; // continuum parameter is updated if(param >= num_params_blr) { /* *note that (response) Fline is also changed as long as Fcon is changed. *num_params_blr-the parameter is the systematic error of continuum. *the change of this parameter also changes continuum reconstruction. */ ptemp = Fcon_rm_particles[which_particle_update]; Fcon_rm_particles[which_particle_update] = Fcon_rm_particles_perturb[which_particle_update]; Fcon_rm_particles_perturb[which_particle_update] = ptemp; if(force_update != 1) { ptemp = Fline_at_data_particles[which_particle_update]; Fline_at_data_particles[which_particle_update] = Fline_at_data_particles_perturb[which_particle_update]; Fline_at_data_particles_perturb[which_particle_update] = ptemp; } } else if( param < num_params_blr -1 && force_update != 1) { /* BLR parameter is updated * Note a) that the (num_par_blr-1)-th parameter is systematic error of line. * when this parameter is updated, Trans2D and Fline are unchanged. * b) Fline is always changed, except for param = num_params_blr-1. */ { ptemp = TransTau_particles[which_particle_update]; TransTau_particles[which_particle_update] = TransTau_particles_perturb[which_particle_update]; TransTau_particles_perturb[which_particle_update] = ptemp; ptemp = Trans2D_at_veldata_particles[which_particle_update]; Trans2D_at_veldata_particles[which_particle_update] = Trans2D_at_veldata_particles_perturb[which_particle_update]; Trans2D_at_veldata_particles_perturb[which_particle_update] = ptemp; ptemp = Fline_at_data_particles[which_particle_update]; Fline_at_data_particles[which_particle_update] = Fline_at_data_particles_perturb[which_particle_update]; Fline_at_data_particles_perturb[which_particle_update] = ptemp; } } return; } /* * action when particle i is killed in cdnest sampling. * particle i_copy's properties is copyed to particle i. */ void kill_action_2d(int i, int i_copy) { memcpy(Fcon_rm_particles[i], Fcon_rm_particles[i_copy], parset.n_con_recon * sizeof(double)); memcpy(Fline_at_data_particles[i], Fline_at_data_particles[i_copy], n_line_data * n_vel_data_ext * sizeof(double)); memcpy(TransTau_particles[i], TransTau_particles[i_copy], parset.n_tau*sizeof(double)); memcpy(Trans2D_at_veldata_particles[i], Trans2D_at_veldata_particles[i_copy], parset.n_tau * n_vel_data_ext * sizeof(double)); return; }
{ "alphanum_fraction": 0.6485240808, "avg_line_length": 29.4809160305, "ext": "c", "hexsha": "46d544376614c095454fcc54a6756ce98b6f3897", "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": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_path": "src/dnest_line2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "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": "yzxamos/BRAINS", "max_issues_repo_path": "src/dnest_line2d.c", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_path": "src/dnest_line2d.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5793, "size": 19310 }
/* * Copyright 2016 Maikel Nadolski * * 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 HMM_IO_H_ #define HMM_IO_H_ #include <map> #include <istream> #include <Eigen/Dense> #include <gsl_assert.h> #include <range/v3/all.hpp> #include <iostream> #include "maikel/hmm/hidden_markov_model.h" #include "maikel/function_profiler.h" namespace maikel { namespace hmm { struct getline_error: public std::runtime_error { getline_error(std::string s): std::runtime_error(s) {} }; struct read_ascii_matrix_error: public std::runtime_error { read_ascii_matrix_error(std::string s): std::runtime_error(s) {} }; struct read_sequence_error: public std::runtime_error { read_sequence_error(std::string s): std::runtime_error(s) {} }; inline std::istream& getline(std::istream& in, std::istringstream& linestream) { Expects(in); std::string line; if (!std::getline(in, line)) throw getline_error("Could not read the line from given stream."); linestream.str(line); linestream.clear(); return in; } template <class size_type> std::pair<size_type, size_type> getdims(std::istream& in) { Expects(in); std::pair<size_type, size_type> dim; std::istringstream line(ranges::front(ranges::getlines(in))); if (!(line >> dim.first >> dim.second)) throw read_ascii_matrix_error("Could not read dimensions."); return dim; } template <class float_type> typename std::enable_if< std::is_floating_point<float_type>::value, Eigen::Matrix<float_type, Eigen::Dynamic, Eigen::Dynamic>>::type read_ascii_matrix(std::istream& in, std::size_t rows, std::size_t cols) { Expects(in); typename Eigen::Matrix<float_type, Eigen::Dynamic, Eigen::Dynamic> matrix(rows, cols); std::istringstream line; for (std::size_t i = 0; i < rows; ++i) { getline(in, line); for (std::size_t j = 0; j < cols; ++j) if (!(line >> matrix(i,j))) throw read_ascii_matrix_error("Could not read entries in line: " + line.str() + "."); } Ensures(gsl::narrow<std::size_t>(matrix.rows()) == rows && gsl::narrow<std::size_t>(matrix.cols()) == cols); return matrix; } template <class Derived> Eigen::DenseBase<Derived>& normalize_rows(Eigen::DenseBase<Derived>& matrix) { using Index = typename Eigen::DenseBase<Derived>::Index; for (Index i = 0; i < matrix.rows(); ++i) matrix.row(i) /= matrix.row(i).sum(); return matrix; } template <class float_type> typename std::enable_if< std::is_floating_point<float_type>::value, hidden_markov_model<float_type>>::type read_hidden_markov_model(std::istream& in) { Expects(in); using matrix = typename hidden_markov_model<float_type>::matrix; using row_vector = typename hidden_markov_model<float_type>::row_vector; using index = typename hidden_markov_model<float_type>::size_type; index states; index symbols; std::tie(states, symbols) = getdims<index>(in); matrix A = read_ascii_matrix<float_type>(in, states, states); matrix B = read_ascii_matrix<float_type>(in, states, symbols); row_vector pi = read_ascii_matrix<float_type>(in, 1, states); normalize_rows(A); normalize_rows(B); normalize_rows(pi); Ensures(A.rows() == states && A.cols() == states); Ensures(B.rows() == states && B.cols() == symbols); Ensures(pi.rows() == 1 && pi.cols() == states); return hidden_markov_model<float_type>(A, B, pi); } template <class float_type> typename std::enable_if< std::is_floating_point<float_type>::value, void>::type print_model_parameters(std::ostream& out, hidden_markov_model<float_type> const& model) { out << "N= " << model.states() << "\n"; out << "M= " << model.symbols() << "\n"; out << "A:\n" << model.A << "\n"; out << "B:\n" << model.B << "\n"; out << "pi:\n" << model.pi << "\n"; out << std::flush; } template <class size_type> size_type read_sequence_length(std::istream& in) { std::string line; std::getline(in, line); std::istringstream linestream(line); size_type length; linestream >> length; return length; } template <class Integral> std::map<std::string, Integral> read_symbol_map(std::istream& in) { std::map<std::string, Integral> symbol_to_index; Integral count{}; std::string buffer; std::getline(in, buffer); std::istringstream lstream(buffer); while (lstream >> buffer) if (symbol_to_index.insert(make_pair(buffer, count)).second) ++count; return symbol_to_index; } template <class Integral> std::vector<Integral> read_sequence(std::istream& in) { std::vector<Integral> sequence; std::map<std::string, Integral> symbol_to_index = read_symbol_map<Integral>(in); sequence.reserve(read_sequence_length<std::size_t>(in)); auto symbol_map = [&symbol_to_index] (std::string const& symbol) { auto found = symbol_to_index.find(symbol); if (found == symbol_to_index.end()) throw read_sequence_error("Unkown Symbols in Input."); return found->second; }; auto sequence_input = ranges::istream_range<std::string>(in); ranges::copy(sequence_input | ranges::view::transform(symbol_map), ranges::back_inserter(sequence)); return sequence; } template <class Integral, class Symbol> std::vector<Integral> read_sequence(std::istream& in, std::map<Symbol,Integral>& symbol_to_index) { MAIKEL_PROFILER; std::vector<Integral> sequence; sequence.reserve(read_sequence_length<std::size_t>(in)); auto symbol_map = [&symbol_to_index] (Symbol const& symbol) { auto found = symbol_to_index.find(symbol); if (found == symbol_to_index.end()) throw read_sequence_error("Unkown Symbols in Input."); return found->second; }; auto sequence_input = ranges::istream_range<Symbol>(in); ranges::copy(sequence_input | ranges::view::transform(symbol_map), ranges::back_inserter(sequence)); return sequence; } } // namespace hmm } // namespace maikel #endif /* HMM_IO_H_ */
{ "alphanum_fraction": 0.6468627735, "avg_line_length": 34.1633663366, "ext": "h", "hexsha": "640e11d981b723b573644deb5514e70520e72882", "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": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_path": "include/maikel/hmm/io.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "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": "maikel/Hidden-Markov-Model", "max_issues_repo_path": "include/maikel/hmm/io.h", "max_line_length": 106, "max_stars_count": 1, "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_path": "include/maikel/hmm/io.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "num_tokens": 1677, "size": 6901 }
#include <math.h> #include <gsl/gsl_errno.h> #include "bicycle.h" //#include <stdio.h> //#include <gsl/gsl_matrix.h> //#include <gsl/gsl_odeiv.h> void eval_qdots(double qd[], const double q[], const double u[], const Bicycle_t *bike) { qd[0] = (-sin(q[2])*u[0] + cos(q[2])*u[2]) / cos(q[1]); qd[1] = cos(q[2])*u[0] + sin(q[2])*u[2]; qd[2] = sin(q[2])*tan(q[1])*u[0] + u[1] - cos(q[2])*tan(q[1])*u[2]; qd[3] = u[3] - u[1]; qd[4] = u[4] - u[2]; qd[5] = sin(q[4])*u[0] - cos(q[4])*u[1] + u[5]; qd[6] = -bike->rr*cos(q[0])*(qd[2] + qd[3]) - bike->rrt*(sin(q[0])*qd[1] + cos(q[0])*cos(q[1])*(qd[2] + qd[3])); qd[7] = -bike->rr*sin(q[0])*(qd[2] + qd[3]) + bike->rrt*(cos(q[0])*qd[1] + sin(q[0])*cos(q[1])*(qd[2] + qd[3])); } // eval_qdots void Bicycle_to_Bicycle_benchmark(Bicycle_benchmark_t *bike_b, const Bicycle_t *bike) { } // Bicycle_to_Bicycle_benchmark void Bicycle_benchmark_to_Bicycle(Bicycle_t *bike, const Bicycle_benchmark_t *bike_b) { } // Bicycle_benchmark_to_Bicycle void eval_dependent_speeds(double u[], double B[3][6], const int ind[], const int dep[]) { double Bi[3][3], Bd[3][3], Bd_adj[3][3], Bd_det, ui[3], ud[3]; // Independent speeds ui[0] = u[ind[0]]; ui[1] = u[ind[1]]; ui[2] = u[ind[2]]; // Dependent speeds ud[0] = u[dep[0]]; ud[1] = u[dep[1]]; ud[2] = u[dep[2]]; // Form -Bi Bi[0][0] = -B[0][ind[0]]; Bi[0][1] = -B[0][ind[1]]; Bi[0][2] = -B[0][ind[2]]; Bi[1][0] = -B[1][ind[0]]; Bi[1][1] = -B[1][ind[1]]; Bi[1][2] = -B[1][ind[2]]; Bi[2][0] = -B[2][ind[0]]; Bi[2][1] = -B[2][ind[1]]; Bi[2][2] = -B[2][ind[2]]; // Form Bd Bd[0][0] = B[0][dep[0]]; Bd[0][1] = B[0][dep[1]]; Bd[0][2] = B[0][dep[2]]; Bd[1][0] = B[1][dep[0]]; Bd[1][1] = B[1][dep[1]]; Bd[1][2] = B[1][dep[2]]; Bd[2][0] = B[2][dep[0]]; Bd[2][1] = B[2][dep[1]]; Bd[2][2] = B[2][dep[2]]; // Forming Bd_adj and Bd_det madj3(Bd_adj, Bd); mdet3(&Bd_det, Bd); // Bd_adj * (-Bi), store the result in Bd instead of creating a new matrix to // store the result mm3(Bd, Bd_adj, Bi); mv3(ud, Bd, ui); // Form the dependent speeds u[dep[0]] = ud[0] / Bd_det; u[dep[1]] = ud[1] / Bd_det; u[dep[2]] = ud[2] / Bd_det; } // eval_dependent_speeds /* * 3x3 Matrix - Matrix multiplication */ void mm3(double AB[3][3], double A[][3], double B[][3]) { unsigned short i, j, k; double sum; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { sum = 0.0; for (k = 0; k < 3; k++) { sum += A[i][k] * B[k][j]; } // for k AB[i][j] = sum; } // for j } // for i } // mm3 /* * 3x3 Matrix - 3x1 Vector multiplication */ void mv3(double Ab[3], double A[3][3], double b[3]) { unsigned short i, j; double sum; for (i = 0; i < 3; i++) { sum = 0.0; for (j = 0; j < 3; j++) { sum += A[i][j]*b[j]; } // for j Ab[i] = sum; } // for i } // mv 3 /* * 3x3 Matrix adjugate */ void madj3(double adj[3][3], double m[3][3]) { adj[0][0] = m[1][1]*m[2][2] - m[1][2]*m[2][1]; adj[0][1] = m[0][2]*m[2][1] - m[0][1]*m[2][2]; adj[0][2] = m[0][1]*m[1][2] - m[0][2]*m[1][1]; adj[1][0] = m[1][2]*m[2][0] - m[1][0]*m[2][2]; adj[1][1] = m[0][0]*m[2][2] - m[0][2]*m[2][0]; adj[1][2] = m[0][2]*m[1][0] - m[0][0]*m[1][2]; adj[2][0] = m[1][0]*m[2][1] - m[1][1]*m[2][0]; adj[2][1] = m[0][1]*m[2][0] - m[0][0]*m[2][1]; adj[2][2] = m[0][0]*m[1][1] - m[0][1]*m[1][0]; } // madj3 /* * Determinant of a 3x3 matrix */ void mdet3(double *det, double m[3][3]) { *det = m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1]) + m[0][1]*(m[1][2]*m[2][0] - m[1][0]*m[2][2]) + m[0][2]*(m[1][0]*m[2][1] - m[1][1]*m[2][0]); } // mdet3 void form_constraint_matrix(double B[3][6], const double q[], const Bicycle_t *bike) { double den = sqrt(pow(sin(q[1])*sin(q[4]) - cos(q[1])*sin(q[2])*cos(q[4]), 2) + pow(cos(q[1])*cos(q[3]), 2)), g31 = (sin(q[1])*sin(q[4]) - cos(q[1])*sin(q[2])*cos(q[5])) / den, g33 = cos(q[1])*cos(q[2]) / den; B[0][0] = cos(q[4])*sin(q[4])*(g33*bike->rf + cos(q[1])*cos(q[2])*bike->rft); B[0][1] = bike->ls + pow(sin(q[4]), 2)*(g33*bike->rf + cos(q[1])*cos(q[2])*bike->rft); B[0][2] = bike->rrt*sin(q[2]); B[0][3] = - cos(q[2])*(bike->rr + cos(q[1])*bike->rrt); B[0][4] = - (sin(q[1])*bike->rft + sin(q[4])*(g31*bike->rf + bike->lf)); B[0][5] = cos(q[4])*(g33*bike->rf + cos(q[1])*cos(q[2])*bike->rft); B[1][0] = - bike->ls + cos(q[2])*(bike->rr + cos(q[1])*bike->rrt) - pow(cos(q[4]), 2)*(g33*bike->rf + cos(q[1])*cos(q[2])*bike->rft); B[1][1] = -cos(q[4])*sin(q[4])*(g33*bike->rf + cos(q[1])*cos(q[2])*bike->rft); B[1][2] = bike->lr + sin(q[2])*(bike->rr + cos(q[1])*bike->rrt); B[1][3] = 0.0; B[1][4] = cos(q[4])*(bike->lf + g31*bike->rf) + cos(q[1])*sin(q[2])*bike->rft; B[1][5] = 0.0; B[2][0] = 0.0; B[2][1] = 0.0; B[2][2] = 0.0; B[2][3] = 0.0; B[2][4] = 0.0; B[2][5] = 0.0; } // form_constraint_matrix
{ "alphanum_fraction": 0.4747292419, "avg_line_length": 27.7, "ext": "c", "hexsha": "b65aaa402cda29892326f778e323f06e157ef1bf", "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": "d201b75d3e8fd8295b375e52eb4ce4c1f35adfb4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "certik/pydy", "max_forks_repo_path": "examples/bicycle/c_lib/bicycle.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d201b75d3e8fd8295b375e52eb4ce4c1f35adfb4", "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": "certik/pydy", "max_issues_repo_path": "examples/bicycle/c_lib/bicycle.c", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d201b75d3e8fd8295b375e52eb4ce4c1f35adfb4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "certik/pydy", "max_stars_repo_path": "examples/bicycle/c_lib/bicycle.c", "max_stars_repo_stars_event_max_datetime": "2016-05-09T06:57:10.000Z", "max_stars_repo_stars_event_min_datetime": "2016-05-09T06:57:10.000Z", "num_tokens": 2382, "size": 4986 }
/* * * ML fitting of size (sigma, s) and number of photons (n) * of already localized dots using a 2D Gaussian model provided by gaussianInt2. * * Only one dot at a time is considered, hence the 1 in mlfit1sn * * Uses 3D images however only a xy-plane at at time is used for the * fitting. * * See also: * mlfit1.c, fitting of xy * df_mlfit1sn.c, a MATLAB interface * * 2017.04.12. Valgrind ok. * * Future work: * - Return the fitting status * - Study the failed cases * - More restrictions on the search domain, i.e., cap sigma depending * on the window size ==9245== Invalid write of size 8 ==9245== at 0x1094C9: mlfit1sn_dot (mlfit1sn.c:227) ==9245== by 0x109A9B: mlfit1sn (mlfit1sn.c:278) ==9245== by 0x109A9B: unit_tests (mlfit1sn.c:346) ==9245== by 0x57F73F0: (below main) (libc-start.c:291) ==9245== Address 0x5babf98 is 24 bytes after a block of size 32,000 in arena "client" ==9245== */ #include <assert.h> #include <inttypes.h> #include <stdint.h> #include <stdio.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_statistics.h> #include "gaussianInt2.h" #include "mlfit.h" #include "blit3.h" // // Headers // // Number of photons in signal double estimateNphot(double *, size_t); // Locate multiple dots in a volume int mlfit1sn(double * , size_t , size_t , size_t , double * , size_t , double * ); // Localization for single dot int mlfit1sn_dot(double *, size_t, double *, double *); // Cost function double my_f (const gsl_vector *, void *); // Random number in a range double rand_range(double, double); int unit_tests(void); // 0: no information, 1: per dot, 2: even more #ifndef verbose #define verbose 0 #endif // When low on bugs, // replace gsl_vector_get(v,i) by v->data[i*v->stride] // #define GSL_RANGE_CHECK_OFF // Globals #if verbose>1 uint32_t maxInterations = 5; #else uint32_t maxInterations = 5000; #endif double convCriteria = 1e-6; // In theory also the window size, denoted Ws in most places // Optimization constants typedef struct { double * R; // local region double * G; // A already allocated temporary space for the Gaussian kernel size_t Rw; // R and G has size Rw*Rw double sigma; // For constant sigma fitting double bg; double x; double y; double midvalue; // value of central pixel in model - bg } optParams; double my_f (const gsl_vector *v, void *params) // The function to optimize { optParams *p = (optParams *) params; size_t Rw = p->Rw; double * R = p->R; double * GI = p->G; double bg = p->bg; double x = p->x; double y = p->y; // Get the other parameters ... double sigma = gsl_vector_get(v, 0); double Nphot = gsl_vector_get(v, 1); #if verbose > 1 printf("Rw: %lu\n", Rw); printf("Nphot: %f\n", Nphot); printf("sigma: %f\n", sigma); printf("bg : %f\n", bg); printf("x: %f, y: %f\n", x, y); printf("GI:\n"); showRegion(GI, Rw); #endif if(sigma<0) return(INFINITY); if(Nphot<0) return(INFINITY); // Create Gaussian ... double mu[] = {x,y}; gaussianInt2(GI, mu, &sigma, Rw); p->midvalue = Nphot*GI[ (Rw*Rw-1)/2 ]; for(size_t kk = 0; kk<Rw*Rw; kk++) GI[kk] = bg+Nphot*GI[kk]; /* * from LL2PG.m * model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2); * mask = disk2d((size(patch,1)-1)/2); * %L = -sum(sum(-(patch-model).^2./model - .5*log(model))); * L = -sum(sum( mask.*( -(patch-model).^2./model - .5*log(model) ) )); */ double E = 0; for (size_t kk=0; kk<Rw*Rw; kk++) { E+= (GI[kk]-R[kk])*(GI[kk]-R[kk])/GI[kk] - .5*log(GI[kk]); // ML //E+= (GI[kk]-R[kk])*(GI[kk]-R[kk]); // Quadratic } // E = -E; #if verbose > 1 printf("E: %f\n", E); #endif return E; } int mlfit1sn_dot(double * V, size_t Vm, double * D, double * F) // Localization for a dot roughly centered in V of size Vm x Vm // D[0], D[1], D[3] are the global coordinates of the dot // F are the fitted coordinates { // Non-optimized parameters optParams par; par.R = V; par.Rw = Vm; par.x = D[0]-nearbyint(D[0]); par.y = D[1]-nearbyint(D[1]); // par.z required for accurate nphot counting, sigma is invariant to // this shift par.bg = estimateBG(V, Vm); par.G = malloc(Vm*Vm*sizeof(double)); #if verbose>0 printf("localizeDot\n"); printf("x: %f y: %f\n", par.x, par.y); printf("bg: %f\n", par.bg); #endif const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2; gsl_multimin_fminimizer *s = NULL; gsl_vector *ss, *x; gsl_multimin_function minex_func; size_t iter = 0; int status; double size; /* Starting point */ x = gsl_vector_alloc (2); gsl_vector_set(x, 0, 1.2); // sigma double nphot0 =estimateNphot(V, Vm); gsl_vector_set(x, 1, nphot0); // Nphot /* Set initial step sizes */ ss = gsl_vector_alloc(2); gsl_vector_set(ss, 0, 0.1); // sigma gsl_vector_set(ss, 1, nphot0/100); // Number of photons /* Initialize method and iterate */ minex_func.n = 2; minex_func.f = my_f; minex_func.params = &par; s = gsl_multimin_fminimizer_alloc (T, 2); gsl_multimin_fminimizer_set (s, &minex_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, convCriteria); if (status == GSL_SUCCESS) { #if verbose > 0 printf ("converged to minimum at\n"); printf ("%5lu sigma:%10.3e NP:%10.3e f() = %7.3f size = %10.3e\n", iter, gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), s->fval, size); #endif } } while (status == GSL_CONTINUE && iter < maxInterations); F[0] = gsl_vector_get(s->x, 0); F[1] = par.midvalue; F[2] = s->fval; F[3] = status; F[4] = par.bg; gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); free(par.G); return status; } int mlfit1sn(double * V, size_t Vm, size_t Vn, size_t Vp, double * D, size_t Dm, double * F) // run the localization routine for a list of dots, D [3xDm] { // Return values have to be checked gsl_set_error_handler_off(); // as a custom error handler can also be used. int Ws_pref = 15; // Window size is Ws x Ws int Ws = Ws_pref; double * W = malloc(Ws_pref*Ws_pref*sizeof(double)); for(size_t kk =0; kk<Dm; kk++) { // Copy the neighbourhood around each D into W int hasRegion = 0; for(Ws = Ws_pref; Ws>7; Ws = Ws-2) { if(getRegion(W, Ws, V, Vm, Vn, Vp, D+kk*3) == 0) { hasRegion = 1; break; } else { #if verbose >0 printf("Ws: %d not possible\n", Ws); #endif } } #if verbose>0 printf("Ws: %d\n", Ws); #endif if(hasRegion == 1) { #if verbose > 1 printf("W:\n"); showRegion(W, Ws); #endif // Local fitting in W #if verbose > 0 int status = mlfit1sn_dot(W, Ws, D+kk*3, F+kk*5); printf("Status: %d\n", status); #else mlfit1sn_dot(W, Ws, D+kk*3, F+kk*5); #endif } else { F[kk*5] = -1; F[kk*5+1] = -1; F[kk*5+2] = -1; F[kk*5+3] = -3; F[kk*5+4] = 0; } } free(W); return 0; } #ifdef standalone int unit_tests() { double * V; // image int Vm = 1024; int Vn = 1024; int Vp = 60; double * D; // list of dots size_t Dm = 1000; // number of dots double * F; // fitted dots printf("Image size: %dx%dx%d\n", Vm, Vn, Vp); printf("Localizing %lu dots\n", Dm); V = malloc(Vm*Vn*Vp*sizeof(double)); D = malloc(3*Dm*sizeof(double)); F = malloc(4*Dm*sizeof(double)); // Initialize the data for(int kk=0; kk<Vm*Vn*Vp; kk++) V[kk] = rand_range(0,0); for(uint32_t kk=0; kk<Dm; kk++) { size_t pos = kk*3; D[pos] = rand_range(-1, Vm+1); D[pos+1] = rand_range(6, Vn-7); D[pos+2] = rand_range(6, Vp-7); if(D[pos] < 6) D[pos] = 6; if(D[pos+1] < 6) D[pos+1] = 6; if(D[pos+2] < 6) D[pos+2] = 6; #if verbose > 0 printf("D %03d %f %f %f\n", kk, D[pos], D[pos+1], D[pos+2]); #endif } for(uint32_t kk=0; kk<Dm; kk++) { size_t pos = D[kk*3] + D[kk*3+1]*Vm + D[kk*3+2]*Vm*Vn; V[pos] = 5; } D[0] = 100; D[1] = 100; D[2] = 30; V[(int) D[0]+(int) D[1]*Vm+(int) D[2]*Vm*Vn] = 7; V[(int) D[0]+1+(int) D[1]*Vm+(int) D[2]*Vm*Vn] = 6; // Run the optimization mlfit1sn(V, Vm, Vn, Vp, D, Dm, F); // In next version, also supply clustering information #if verbose >0 for(size_t kk = 0; kk<Dm; kk++) { size_t pos = kk*3; size_t dpos = kk*4; printf("%6lu (%f, %f, %f) : s: %f, n: %f e: %f status: %d\n", kk, D[pos], D[pos+1], D[pos+2], F[dpos], F[dpos+1], F[dpos+2], (int) F[dpos+3]); } #endif free(F); free(D); free(V); return 0; } int main(int argc, char ** argv) // For testing, not used any more, see the MATLAB interface in // df_mlfit.c { printf("%s\n", argv[0]); if(argc == 1) { return unit_tests(); } return 1; } #endif
{ "alphanum_fraction": 0.5918344767, "avg_line_length": 23.1743589744, "ext": "c", "hexsha": "21b17493404df0881be6488b0ff111e8530d1bd7", "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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elgw/dotter", "max_forks_repo_path": "common/mex/mlfit1sn.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "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": "elgw/dotter", "max_issues_repo_path": "common/mex/mlfit1sn.c", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elgw/dotter", "max_stars_repo_path": "common/mex/mlfit1sn.c", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "num_tokens": 3237, "size": 9038 }
#ifdef HAVE_GSL #include <gsl/gsl_sf_fermi_dirac.h> #include <gsl/gsl_sf_bessel.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_sf_result.h> #include <gsl/gsl_errno.h> #else #include <stddef.h> #ifdef __cplusplus extern "C" { #endif typedef double gsl_multifit_linear_workspace ; typedef struct { size_t size; double *v;} gsl_vector ; typedef struct { size_t size_rows; size_t size_columns; double* m;} gsl_matrix ; double gsl_sf_fermi_dirac_mhalf(double x); double gsl_sf_fermi_dirac_half(double x); double gsl_sf_bessel_Kn(const int n, const double x); double gsl_vector_get (const gsl_vector * v, size_t i); gsl_matrix *gsl_matrix_alloc (size_t i, size_t j); gsl_vector *gsl_vector_alloc (size_t i); void gsl_matrix_set (gsl_matrix *m, size_t i, size_t j, double x); void gsl_vector_set (gsl_vector *v, size_t i, double x); void gsl_vector_free (gsl_vector * v); void gsl_matrix_free (gsl_matrix * v); gsl_multifit_linear_workspace *gsl_multifit_linear_alloc (size_t m,size_t n); void gsl_multifit_linear_free (gsl_multifit_linear_workspace *); int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double * chisq, gsl_multifit_linear_workspace * work); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7528259231, "avg_line_length": 36.8611111111, "ext": "h", "hexsha": "dc2a5b60acdfac57d889b353d2b5361c2c77c752", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:38:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-28T08:01:32.000Z", "max_forks_repo_head_hexsha": "d229248898b34630e166966bd00b0c4e0a1a2411", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gonsie/ddcMD", "max_forks_repo_path": "src/gsl.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "d229248898b34630e166966bd00b0c4e0a1a2411", "max_issues_repo_issues_event_max_datetime": "2021-12-06T04:58:31.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-29T06:55:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gonsie/ddcMD", "max_issues_repo_path": "src/gsl.h", "max_line_length": 183, "max_stars_count": 20, "max_stars_repo_head_hexsha": "d229248898b34630e166966bd00b0c4e0a1a2411", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gonsie/ddcMD", "max_stars_repo_path": "src/gsl.h", "max_stars_repo_stars_event_max_datetime": "2022-03-08T07:28:45.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-28T01:14:22.000Z", "num_tokens": 389, "size": 1327 }
#include <petsc.h> EXTERN_C_BEGIN extern void formInitial(int*,int*,int*,double*, double*,double*); extern void formFunction(const int*,const int*,const int*,const double*, const double*,const double[],const double[],double[]); EXTERN_C_END typedef struct AppCtx { PetscInt nx,ny,nz; PetscScalar h[3]; } AppCtx; #undef __FUNCT__ #define __FUNCT__ "FormInitial" PetscErrorCode FormInitial(PetscReal t, Vec X, void *ctx) { PetscScalar *x; AppCtx *app = (AppCtx*) ctx; PetscErrorCode ierr; PetscFunctionBegin; ierr = VecGetArray(X,&x);CHKERRQ(ierr); /**/ formInitial(&app->nx,&app->ny,&app->nz,app->h, &t,x); /**/ ierr = VecRestoreArray(X,&x);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "FormFunction" PetscErrorCode FormFunction(TS ts, PetscReal t, Vec X, Vec Xdot,Vec F, void *ctx) { const PetscScalar *x; const PetscScalar *xdot; PetscScalar *f; AppCtx *app = (AppCtx*) ctx; PetscErrorCode ierr; PetscFunctionBegin; ierr = VecGetArrayRead(X,&x);CHKERRQ(ierr); ierr = VecGetArrayRead(Xdot,&xdot);CHKERRQ(ierr); ierr = VecGetArray(F,&f);CHKERRQ(ierr); /**/ formFunction(&app->nx,&app->ny,&app->nz,app->h, &t,x,xdot,f); /**/ ierr = VecRestoreArrayRead(X,&x);CHKERRQ(ierr); ierr = VecRestoreArrayRead(Xdot,&xdot);CHKERRQ(ierr); ierr = VecRestoreArray(F,&f);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "RunTest" PetscErrorCode RunTest(int nx, int ny, int nz, int loops, double *wt) { Vec x,f; TS ts; AppCtx _app,*app=&_app; double t1,t2; PetscErrorCode ierr; PetscFunctionBegin; app->nx = nx; app->h[0] = 1./(nx-1); app->ny = ny; app->h[1] = 1./(ny-1); app->nz = nz; app->h[2] = 1./(nz-1); ierr = VecCreate(PETSC_COMM_SELF,&x);CHKERRQ(ierr); ierr = VecSetSizes(x,nx*ny*nz,nx*ny*nz);CHKERRQ(ierr); ierr = VecSetUp(x);CHKERRQ(ierr); ierr = VecDuplicate(x,&f);CHKERRQ(ierr); ierr = TSCreate(PETSC_COMM_SELF,&ts);CHKERRQ(ierr); ierr = TSSetProblemType(ts,TS_NONLINEAR);CHKERRQ(ierr); ierr = TSSetType(ts,TSTHETA);CHKERRQ(ierr); ierr = TSThetaSetTheta(ts,1.0);CHKERRQ(ierr); ierr = TSSetTimeStep(ts,0.01);CHKERRQ(ierr); ierr = TSSetTime(ts,0.0);CHKERRQ(ierr); ierr = TSSetDuration(ts,10,1.0);CHKERRQ(ierr); ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);CHKERRQ(ierr); ierr = TSSetSolution(ts,x);CHKERRQ(ierr); ierr = TSSetIFunction(ts,f,FormFunction,app);CHKERRQ(ierr); ierr = PetscOptionsSetValue(NULL,"-snes_mf","1");CHKERRQ(ierr); { SNES snes; KSP ksp; ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr); ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr); ierr = KSPSetType(ksp,KSPCG);CHKERRQ(ierr); } ierr = TSSetFromOptions(ts);CHKERRQ(ierr); ierr = TSSetUp(ts);CHKERRQ(ierr); *wt = 1e300; while (loops-- > 0) { ierr = FormInitial(0.0,x,app);CHKERRQ(ierr); ierr = PetscTime(&t1);CHKERRQ(ierr); ierr = TSSolve(ts,x);CHKERRQ(ierr); ierr = PetscTime(&t2);CHKERRQ(ierr); *wt = PetscMin(*wt,t2-t1); } ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&f);CHKERRQ(ierr); ierr = TSDestroy(&ts);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "GetInt" PetscErrorCode GetInt(const char* name, PetscInt *v, PetscInt defv) { PetscErrorCode ierr; PetscFunctionBegin; *v = defv; ierr = PetscOptionsGetInt(NULL,NULL,name,v,NULL);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "main" int main(int argc, char *argv[]) { double wt; PetscInt n,start,step,stop,samples; PetscErrorCode ierr; ierr = PetscInitialize(&argc,&argv,NULL,NULL);CHKERRQ(ierr); ierr = GetInt("-start", &start, 12);CHKERRQ(ierr); ierr = GetInt("-step", &step, 4);CHKERRQ(ierr); ierr = GetInt("-stop", &stop, start);CHKERRQ(ierr); ierr = GetInt("-samples", &samples, 1);CHKERRQ(ierr); for (n=start; n<=stop; n+=step){ int nx=n+1, ny=n+1, nz=n+1; ierr = RunTest(nx,ny,nz,samples,&wt);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF, "Grid %3d x %3d x %3d -> %f seconds (%2d samples)\n", nx,ny,nz,wt,samples);CHKERRQ(ierr); } ierr = PetscFinalize();CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.6438636364, "avg_line_length": 29.3333333333, "ext": "c", "hexsha": "3ee5bc9ba5412acf786f9030283c574765f784cc", "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": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pcmagic/stokes_flow", "max_forks_repo_path": "pkgs/petsc4py-3.7.0/demo/perftest/driver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "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": "pcmagic/stokes_flow", "max_issues_repo_path": "pkgs/petsc4py-3.7.0/demo/perftest/driver.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "464d512d3739eee77b33d1ebf2f27dae6cfa0423", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pcmagic/stokes_flow", "max_stars_repo_path": "pkgs/petsc4py-3.7.0/demo/perftest/driver.c", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "num_tokens": 1373, "size": 4400 }
/** * * @file core_strasm.c * * PLASMA core_blas kernel * 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:46 2014 * **/ #include <cblas.h> #include <math.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_float * * CORE_strasm - Computes the sums of the absolute values of elements in a same * row or column in a triangular matrix. * This function is an auxiliary function to triangular matrix norm computations. * ******************************************************************************* * * @param[in] storev * Specifies whether the sums are made per column or row. * = PlasmaColumnwise: Computes the sum on each column * = PlasmaRowwise: Computes the sum on each row * * @param[in] uplo * Specifies whether the matrix A is upper triangular or lower triangular * = PlasmaUpper: Upper triangle of A is referenced; * = PlasmaLower: Lower triangle of A is referenced. * * @param[in] diag * Specifies whether or not A is unit triangular: * = PlasmaNonUnit: A is non unit; * = PlasmaUnit: A us unit. * * @param[in] M * M specifies the number of rows of the matrix A. M >= 0. * * @param[in] N * N specifies the number of columns of the matrix A. N >= 0. * * @param[in] A * A is a M-by-N matrix. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,M). * * @param[in,out] work * Array of dimension M if storev = PlasmaRowwise; N otherwise. * On exit, contains the sums of the absolute values per column or row * added to the input values. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_strasm = PCORE_strasm #define CORE_strasm PCORE_strasm #endif void CORE_strasm(PLASMA_enum storev, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const float *A, int lda, float *work) { const float *tmpA; int i, j, imax; int idiag = (diag == PlasmaUnit) ? 1 : 0; /* * PlasmaUpper / PlasmaColumnwise */ if (uplo == PlasmaUpper ) { M = min(M, N); if (storev == PlasmaColumnwise) { for (j = 0; j < N; j++) { tmpA = A+(j*lda); imax = min(j+1-idiag, M); if ( j < M ) work[j] += idiag; for (i = 0; i < imax; i++) { work[j] += fabsf(*tmpA); tmpA++; } } } /* * PlasmaUpper / PlasmaRowwise */ else { if (diag == PlasmaUnit) { for (i = 0; i < M; i++) { work[i] += 1.; } } for (j = 0; j < N; j++) { tmpA = A+(j*lda); imax = min(j+1-idiag, M); for (i = 0; i < imax; i++) { work[i] += fabsf(*tmpA); tmpA++; } } } } else { N = min(M, N); /* * PlasmaLower / PlasmaColumnwise */ if (storev == PlasmaColumnwise) { for (j = 0; j < N; j++) { tmpA = A + j * (lda+1) + idiag; work[j] += idiag; for (i = j+idiag; i < M; i++) { work[j] += fabsf(*tmpA); tmpA++; } } } /* * PlasmaLower / PlasmaRowwise */ else { if (diag == PlasmaUnit) { for (i = 0; i < N; i++) { work[i] += 1.; } } for (j = 0; j < N; j++) { tmpA = A + j * (lda+1) + idiag; for (i = j+idiag; i < M; i++) { work[i] += fabsf(*tmpA); tmpA++; } } } } }
{ "alphanum_fraction": 0.4307186473, "avg_line_length": 28.3866666667, "ext": "c", "hexsha": "da628df1b2b7e95f9b29358ca083ee5b5695d54f", "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/core_strasm.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/core_strasm.c", "max_line_length": 82, "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/core_strasm.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1079, "size": 4258 }
#ifndef INFMCMC_H #define INFMCMC_H #include <complex.h> #include <fftw3.h> #include <gsl/gsl_rng.h> //void sampleRMWH(CHAIN *C); //void sampleIndependenceSampler(CHAIN *C); //void updateMean(CHAIN *C); //void updateVar(CHAIN *C); struct _CHAIN { int nj, nk; // number of Fourier coefficients in x/y direction respectively int numKeptSamples; int sizeObsVector; int currentIter; int accepted; double _shortTimeAccProbAvg; double _bLow, _bHigh; double *currentPhysicalState, *avgPhysicalState, *varPhysicalState, *_M2; double *proposedPhysicalState; double logLHDCurrentState; double accProb, avgAccProb; double rwmhStepSize, alphaPrior, priorVar, priorStd; // -- potentially not used -- double *currentStateObservations, *proposedStateObservations; double *data; double currentLSQFunctional; double currentStateL2Norm2; double obsStdDev; // -------------------------- fftw_complex *currentSpectralState, *avgSpectralState; fftw_complex *priorDraw, *proposedSpectralState; fftw_plan _c2r; fftw_plan _r2c; gsl_rng *r; }; typedef struct _CHAIN CHAIN; typedef struct _CHAIN INFCHAIN; void infmcmc_initChain(INFCHAIN *C, const int nj, const int nk); void infmcmc_freeChain(INFCHAIN *C); void infmcmc_resetChain(INFCHAIN *C); void infmcmc_proposeRWMH(INFCHAIN *C); void infmcmc_updateRWMH(INFCHAIN *C, double logLHDOfProposal); void infmcmc_seedWithPriorDraw(INFCHAIN *C); void infmcmc_writeChainInfo(const INFCHAIN *C, FILE *fp); void infmcmc_writeVFChain(const INFCHAIN *U, const INFCHAIN *V, FILE *fp); void infmcmc_writeChain(const INFCHAIN *C, FILE *fp); void infmcmc_printChain(INFCHAIN *C); void infmcmc_setRWMHStepSize(INFCHAIN *C, double beta); void infmcmc_adaptRWMHStepSize(INFCHAIN *C, double inc); void infmcmc_setPriorAlpha(INFCHAIN *C, double alpha); void infmcmc_setPriorVar(INFCHAIN *C, double var); double infmcmc_L2Current(INFCHAIN *C); double infmcmc_L2Proposed(INFCHAIN *C); double infmcmc_L2Prior(INFCHAIN *C); void infmcmc_seedWithDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2); void infmcmc_proposeDivFreeRWMH(INFCHAIN *C1, INFCHAIN *C2); void infmcmc_updateVectorFieldRWMH(INFCHAIN *C1, INFCHAIN *C2, double logLHDOfProposal); void randomPriorDrawOLD(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs); #endif
{ "alphanum_fraction": 0.7741237559, "avg_line_length": 31.6575342466, "ext": "h", "hexsha": "8860be61a0f137b488b9844c8fa788ed74da93d3", "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": "b745c933203c52732a5daac12e84f52d7af13266", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dmcdougall/mcmclib", "max_forks_repo_path": "mcmclib/infmcmc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "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": "dmcdougall/mcmclib", "max_issues_repo_path": "mcmclib/infmcmc.h", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dmcdougall/mcmclib", "max_stars_repo_path": "mcmclib/infmcmc.h", "max_stars_repo_stars_event_max_datetime": "2015-11-21T22:02:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-21T22:02:58.000Z", "num_tokens": 703, "size": 2311 }
// Copyright (c) 2021 Stig Rune Sellevag // // This file is distributed under the MIT License. See the accompanying file // LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms // and conditions. #ifndef SCILIB_LINALG_MATRIX_DECOMPOSITION_H #define SCILIB_LINALG_MATRIX_DECOMPOSITION_H #ifdef USE_MKL #include <mkl.h> #else #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" #endif #include <lapacke.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #include <scilib/mdarray.h> #include <scilib/linalg_impl/lapack_types.h> #include <experimental/mdspan> #include <exception> #include <cassert> #include <type_traits> namespace Sci { namespace Linalg { namespace stdex = std::experimental; // LU factorization. template <class Layout> inline void lu(Sci::Matrix_view<double, Layout> a, Sci::Vector_view<BLAS_INT, Layout> ipiv) { static_assert(a.is_contiguous()); static_assert(ipiv.is_contiguous()); const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0)); const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1)); assert(static_cast<BLAS_INT>(ipiv.size()) >= std::min(m, n)); auto matrix_layout = LAPACK_ROW_MAJOR; BLAS_INT lda = n; if constexpr (std::is_same_v<Layout, stdex::layout_left>) { matrix_layout = LAPACK_COL_MAJOR; lda = m; } BLAS_INT info = LAPACKE_dgetrf(matrix_layout, m, n, a.data(), lda, ipiv.data()); if (info < 0) { throw std::runtime_error("dgetrf: illegal input parameter"); } if (info > 0) { throw std::runtime_error("dgetrf: U matrix is singular"); } } template <class Layout, class Allocator_a, class Allocator_ipiv> inline void lu(Sci::Matrix<double, Layout, Allocator_a>& a, Sci::Vector<BLAS_INT, Layout, Allocator_ipiv>& ipiv) { lu(a.view(), ipiv.view()); } // QR factorization. template <class Layout> inline void qr(Sci::Matrix_view<double, Layout> a, Sci::Matrix_view<double, Layout> q, Sci::Matrix_view<double, Layout> r) { assert(q.extent(0) == a.extent(0) && q.extent(1) == a.extent(1)); assert(r.extent(0) == a.extent(0) && r.extent(1) == a.extent(1)); const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0)); const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1)); auto matrix_layout = LAPACK_ROW_MAJOR; BLAS_INT lda = n; if constexpr (std::is_same_v<Layout, stdex::layout_left>) { matrix_layout = LAPACK_COL_MAJOR; lda = m; } Sci::copy(a, q); Sci::Vector<double, Layout> tau(std::min(m, n)); // Compute QR factorization: BLAS_INT info = LAPACKE_dgeqrf(matrix_layout, m, n, q.data(), lda, tau.data()); if (info != 0) { throw std::runtime_error("dgeqrf failed"); } // Compute Q: info = LAPACKE_dorgqr(matrix_layout, m, n, n, q.data(), lda, tau.data()); if (info != 0) { throw std::runtime_error("dorgqr failed"); } // Compute R: matrix_product(transposed(q), a, r); transposed(q); } template <class Layout, class Allocator> inline void qr(Sci::Matrix<double, Layout, Allocator>& a, Sci::Matrix<double, Layout, Allocator>& q, Sci::Matrix<double, Layout, Allocator>& r) { qr(a.view(), q.view(), r.view()); } // Singular value decomposition. template <class Layout> inline void svd(Sci::Matrix_view<double, Layout> a, Sci::Vector_view<double, Layout> s, Sci::Matrix_view<double, Layout> u, Sci::Matrix_view<double, Layout> vt) { const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0)); const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1)); const BLAS_INT ldu = m; const BLAS_INT ldvt = n; assert(static_cast<BLAS_INT>(s.extent(0)) == std::min(m, n)); assert(static_cast<BLAS_INT>(u.extent(0)) == m); assert(static_cast<BLAS_INT>(u.extent(1)) == ldu); assert(static_cast<BLAS_INT>(vt.extent(0)) == n); assert(static_cast<BLAS_INT>(vt.extent(1)) == ldvt); auto matrix_layout = LAPACK_ROW_MAJOR; BLAS_INT lda = n; if constexpr (std::is_same_v<Layout, stdex::layout_left>) { matrix_layout = LAPACK_COL_MAJOR; lda = m; } Sci::Vector<double, Layout> superb(std::min(m, n) - 1); BLAS_INT info = LAPACKE_dgesvd(matrix_layout, 'A', 'A', m, n, a.data(), lda, s.data(), u.data(), ldu, vt.data(), ldvt, superb.data()); if (info != 0) { throw std::runtime_error("dgesvd failed"); } } template <class Layout, class Allocator> inline void svd(Sci::Matrix<double, Layout, Allocator>& a, Sci::Vector<double, Layout, Allocator>& s, Sci::Matrix<double, Layout, Allocator>& u, Sci::Matrix<double, Layout, Allocator>& vt) { svd(a.view(), s.view(), u.view(), vt.view()); } } // namespace Linalg } // namespace Sci #endif // SCILIB_LINALG_MATRIX_DECOMPOSITION_H
{ "alphanum_fraction": 0.6411940299, "avg_line_length": 29.0462427746, "ext": "h", "hexsha": "6302ce512a1a57388f480873f780924ee1944442", "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": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_path": "include/scilib/linalg_impl/matrix_decomposition.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "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": "stigrs/scilib", "max_issues_repo_path": "include/scilib/linalg_impl/matrix_decomposition.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_path": "include/scilib/linalg_impl/matrix_decomposition.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1364, "size": 5025 }
/* * Copyright 2020 Makani Technologies LLC * * 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 SIM_PHYSICS_AVL_AERO_DATABASE_H_ #define SIM_PHYSICS_AVL_AERO_DATABASE_H_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <stdint.h> #include <string> #include "common/c_math/linalg.h" #include "common/c_math/vec3.h" #include "common/macros.h" #include "sim/sim_params.h" #include "sim/sim_types.h" #include "system/labels.h" class AvlAeroDatabase { friend class AeroTest; public: AvlAeroDatabase(const std::string &filename, const AeroSimParams &aero_sim_params); ~AvlAeroDatabase(); // Applies coefficient fudge factors. // // Args: // coeff_offsets: Offsets to apply. // force_coeff_w_scale_factors: Scale factors [#] to apply to the // force coefficients. These scale factors should be represented in // the wind axes. // moment_coeff_b_scale_factors: Scale factors [#] to apply to the // moment coefficients. These scale factors should be represented in // the body axes. void ApplyCoeffAdjustments(const AeroCoeffOffsets &coeff_offsets, const AeroCoeffs &force_coeff_w_scale_factors, const AeroCoeffs &moment_coeff_b_scale_factors); // Returns the total force-moment coefficient at a specific (alpha, // beta, omega_hat, flap deflection) operating point. void CalcForceMomentCoeff(double alpha, double beta, const Vec3 &omega_hat, const Vec &flaps, ForceMoment *cfm, double thrust_coeff) const { CalcForceMomentCoeff(alpha, beta, omega_hat, flaps, cfm, thrust_coeff, nullptr); } // See function above. Optionally returns the breakdown of the // force-moment coefficient into control and stability derivatives // if aero_coeffs is not null. void CalcForceMomentCoeff(double alpha, double beta, const Vec3 &omega_hat, const Vec &flaps, ForceMoment *cfm, double thrust_coeff, AvlAeroCoeffs *aero_coeffs) const; // Returns the nominal elevator deflection for a given angle-of-attack // and sideslip angle. double GetNominalElevatorDeflection(double alpha, double beta) const; double reynolds_number() const { return reynolds_number_; } int32_t num_flaps() const { return num_flaps_; } const Vec3 &omega_hat_0() const { return omega_hat_0_; } private: // Returns true if the database passes basic sign checks. bool IsValid() const; // Reduces flap effectiveness at large deflections. void AdjustNonlinearFlaps(const Vec &flaps, Vec *flaps_nonlin) const; // Returns the nominal force-moment coefficient and the control and // stability derivatives. void CalcAvlAeroCoeffs(double alpha, double beta, AvlAeroCoeffs *coeffs) const; const AeroSimParams &aero_sim_params_; double reynolds_number_; int32_t num_flaps_; gsl_vector *alphads_, *betads_; gsl_matrix *eleds_; Vec3 omega_hat_0_; gsl_matrix *CX_, *CY_, *CZ_, *CL_, *CM_, *CN_; gsl_matrix *CXp_, *CYp_, *CZp_, *CLp_, *CMp_, *CNp_; gsl_matrix *CXq_, *CYq_, *CZq_, *CLq_, *CMq_, *CNq_; gsl_matrix *CXr_, *CYr_, *CZr_, *CLr_, *CMr_, *CNr_; gsl_matrix *CXd_[kNumFlaps]; gsl_matrix *CYd_[kNumFlaps]; gsl_matrix *CZd_[kNumFlaps]; gsl_matrix *CLd_[kNumFlaps]; gsl_matrix *CMd_[kNumFlaps]; gsl_matrix *CNd_[kNumFlaps]; DISALLOW_COPY_AND_ASSIGN(AvlAeroDatabase); }; #endif // SIM_PHYSICS_AVL_AERO_DATABASE_H_
{ "alphanum_fraction": 0.698809813, "avg_line_length": 35.188034188, "ext": "h", "hexsha": "916175129d9754eb3f9500fc6e1c242354a2024f", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "sim/physics/avl_aero_database.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "sim/physics/avl_aero_database.h", "max_line_length": 77, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "sim/physics/avl_aero_database.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 1049, "size": 4117 }
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2018 Couchbase, Inc * * 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 "dcp/dcp-types.h" #include "evp_engine_test.h" #include "evp_store_single_threaded_test.h" #include "vbucket_fwd.h" #include <memcached/engine_error.h> #include <gsl/gsl> class Item; class MockDcpProducer; class MockActiveStream; struct dcp_message_producers; /** * Test fixture for unit tests related to DCP. */ class DCPTest : public EventuallyPersistentEngineTest { protected: void SetUp() override; void TearDown() override; // Create a DCP producer; initially with no streams associated. void create_dcp_producer( int flags = 0, IncludeValue includeVal = IncludeValue::Yes, IncludeXattrs includeXattrs = IncludeXattrs::Yes, std::vector<std::pair<std::string, std::string>> controls = {}); // Setup a DCP producer and attach a stream and cursor to it. void setup_dcp_stream( int flags = 0, IncludeValue includeVal = IncludeValue::Yes, IncludeXattrs includeXattrs = IncludeXattrs::Yes, std::vector<std::pair<std::string, std::string>> controls = {}); void destroy_dcp_stream(); struct StreamRequestResult { ENGINE_ERROR_CODE status; uint64_t rollbackSeqno; }; /** * Helper function to simplify calling producer->streamRequest() - provides * sensible default values for common invocations. */ static StreamRequestResult doStreamRequest(DcpProducer& producer, uint64_t startSeqno = 0, uint64_t endSeqno = ~0, uint64_t snapStart = 0, uint64_t snapEnd = ~0, uint64_t vbUUID = 0); /** * Helper function to simplify the process of preparing DCP items to be * fetched from the stream via step(). * Should be called once all expected items are present in the vbuckets' * checkpoint, it will then run the correct background tasks to * copy CheckpointManager items to the producers' readyQ. */ static void prepareCheckpointItemsForStep( dcp_message_producers& msgProducers, MockDcpProducer& producer, VBucket& vb); /* * Creates an item with the key \"key\", containing json data and xattrs. * @return a unique_ptr to a newly created item. */ std::unique_ptr<Item> makeItemWithXattrs(); /* * Creates an item with the key \"key\", containing json data and no xattrs. * @return a unique_ptr to a newly created item. */ std::unique_ptr<Item> makeItemWithoutXattrs(); /* Add items onto the vbucket and wait for the checkpoint to be removed */ void addItemsAndRemoveCheckpoint(int numItems); void removeCheckpoint(int numItems); void runCheckpointProcessor(dcp_message_producers& producers); std::shared_ptr<MockDcpProducer> producer; std::shared_ptr<MockActiveStream> stream; VBucketPtr vb0; /* * Fake callback emulating dcp_add_failover_log */ static ENGINE_ERROR_CODE fakeDcpAddFailoverLog( vbucket_failover_t* entry, size_t nentries, gsl::not_null<const void*> cookie) { callbackCount++; return ENGINE_SUCCESS; } // callbackCount needs to be static as its used inside of the static // function fakeDcpAddFailoverLog. static int callbackCount; };
{ "alphanum_fraction": 0.6461246741, "avg_line_length": 34.5819672131, "ext": "h", "hexsha": "f01c97774b63c3b7efde1738190dcde15eca9cf2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-15T16:52:37.000Z", "max_forks_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hrajput89/kv_engine", "max_forks_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "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": "hrajput89/kv_engine", "max_issues_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "33fb1ab2c9787f55555e5f7edea38807b3dbc371", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hrajput89/kv_engine", "max_stars_repo_path": "engines/ep/tests/module_tests/dcp_test.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 935, "size": 4219 }
/* specfunc/gsl_sf_trig.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 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. */ /* Author: G. Jungman */ #ifndef __GSL_SF_TRIG_H__ #define __GSL_SF_TRIG_H__ #include <gsl/gsl_sf_result.h> #include <gsl/gsl_types.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 /* Sin(x) with GSL semantics. This is actually important * because we want to control the error estimate, and trying * to guess the error for the standard library implementation * every time it is used would be a little goofy. */ GSL_EXPORT int gsl_sf_sin_e(double x, gsl_sf_result * result); GSL_EXPORT double gsl_sf_sin(const double x); /* Cos(x) with GSL semantics. */ GSL_EXPORT int gsl_sf_cos_e(double x, gsl_sf_result * result); GSL_EXPORT double gsl_sf_cos(const double x); /* Hypot(x,y) with GSL semantics. */ GSL_EXPORT int gsl_sf_hypot_e(const double x, const double y, gsl_sf_result * result); GSL_EXPORT double gsl_sf_hypot(const double x, const double y); /* Sin(z) for complex z * * exceptions: GSL_EOVRFLW */ GSL_EXPORT int gsl_sf_complex_sin_e(const double zr, const double zi, gsl_sf_result * szr, gsl_sf_result * szi); /* Cos(z) for complex z * * exceptions: GSL_EOVRFLW */ GSL_EXPORT int gsl_sf_complex_cos_e(const double zr, const double zi, gsl_sf_result * czr, gsl_sf_result * czi); /* Log(Sin(z)) for complex z * * exceptions: GSL_EDOM, GSL_ELOSS */ GSL_EXPORT int gsl_sf_complex_logsin_e(const double zr, const double zi, gsl_sf_result * lszr, gsl_sf_result * lszi); /* Sinc(x) = sin(pi x) / (pi x) * * exceptions: none */ GSL_EXPORT int gsl_sf_sinc_e(double x, gsl_sf_result * result); GSL_EXPORT double gsl_sf_sinc(const double x); /* Log(Sinh(x)), x > 0 * * exceptions: GSL_EDOM */ GSL_EXPORT int gsl_sf_lnsinh_e(const double x, gsl_sf_result * result); GSL_EXPORT double gsl_sf_lnsinh(const double x); /* Log(Cosh(x)) * * exceptions: none */ GSL_EXPORT int gsl_sf_lncosh_e(const double x, gsl_sf_result * result); GSL_EXPORT double gsl_sf_lncosh(const double x); /* Convert polar to rectlinear coordinates. * * exceptions: GSL_ELOSS */ GSL_EXPORT int gsl_sf_polar_to_rect(const double r, const double theta, gsl_sf_result * x, gsl_sf_result * y); /* Convert rectilinear to polar coordinates. * return argument in range [-pi, pi] * * exceptions: GSL_EDOM */ GSL_EXPORT int gsl_sf_rect_to_polar(const double x, const double y, gsl_sf_result * r, gsl_sf_result * theta); /* Sin(x) for quantity with an associated error. */ GSL_EXPORT int gsl_sf_sin_err_e(const double x, const double dx, gsl_sf_result * result); /* Cos(x) for quantity with an associated error. */ GSL_EXPORT int gsl_sf_cos_err_e(const double x, const double dx, gsl_sf_result * result); /* Force an angle to lie in the range (-pi,pi]. * * exceptions: GSL_ELOSS */ GSL_EXPORT int gsl_sf_angle_restrict_symm_e(double * theta); GSL_EXPORT double gsl_sf_angle_restrict_symm(const double theta); /* Force an angle to lie in the range [0, 2pi) * * exceptions: GSL_ELOSS */ GSL_EXPORT int gsl_sf_angle_restrict_pos_e(double * theta); GSL_EXPORT double gsl_sf_angle_restrict_pos(const double theta); GSL_EXPORT int gsl_sf_angle_restrict_symm_err_e(const double theta, gsl_sf_result * result); GSL_EXPORT int gsl_sf_angle_restrict_pos_err_e(const double theta, gsl_sf_result * result); __END_DECLS #endif /* __GSL_SF_TRIG_H__ */
{ "alphanum_fraction": 0.7497065039, "avg_line_length": 27.6558441558, "ext": "h", "hexsha": "45f23d7b87bc70e7cc1103c0ad83595c3ba7157d", "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": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sf_trig.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "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": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sf_trig.h", "max_line_length": 117, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sf_trig.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1122, "size": 4259 }
#ifndef GBNET_MODELORNOR #define GBNET_MODELORNOR #include <cmath> #include <time.h> #include <gsl/gsl_rstat.h> #include "ModelBase.h" #include "GraphORNOR.h" namespace gbn { class ModelORNOR: public ModelBase { private: protected: public: ModelORNOR(); ~ModelORNOR() override; ModelORNOR(const network_t, const evidence_dict_t, const prior_active_tf_set_t = prior_active_tf_set_t(), const double [3 * 3] = gbn::SPRIOR, double z_alpha = 25., double z_beta = 25., double z0_alpha = 25., double z0_beta = 25., double t_alpha = 25., double t_beta = 25., unsigned int = 3, bool = true, bool = true, bool = false, double = 2., double = 2., double = 2., double = 2., double = 8., double = 2.); }; } #endif
{ "alphanum_fraction": 0.5680272109, "avg_line_length": 26.7272727273, "ext": "h", "hexsha": "7c683c2868a343858f66229bb283a4909e64595b", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umbibio/gbnet", "max_forks_repo_path": "libgbnet/include/ModelORNOR.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "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": "umbibio/gbnet", "max_issues_repo_path": "libgbnet/include/ModelORNOR.h", "max_line_length": 190, "max_stars_count": null, "max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umbibio/gbnet", "max_stars_repo_path": "libgbnet/include/ModelORNOR.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 228, "size": 882 }
#include <assert.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <asf.h> #include "asf_tiff.h" #include <gsl/gsl_math.h> #include <proj_api.h> #include "asf_jpeg.h" #include <png.h> #include "envi.h" #include "dateUtil.h" #include <time.h> #include "matrix.h" #include <asf_nan.h> #include <asf_endian.h> #include <asf_meta.h> #include <asf_export.h> #include <asf_raster.h> #include <float_image.h> #include <spheroids.h> #include <typlim.h> #include <hdf5.h> #include <netcdf.h> #define RES 16 #define MAX_PTS 256 void nc_meta_double(int group_id, char *name, char *desc, char *units, double *value) { int var_id; char *str = (char *) MALLOC(sizeof(char)*1024); nc_def_var(group_id, name, NC_DOUBLE, 0, 0, &var_id); nc_put_att_text(group_id, var_id, "long_name", strlen(desc), desc); if (units && strlen(units) > 0) { strcpy(str, units); nc_put_att_text(group_id, var_id, "units", strlen(str), str); } nc_put_var_double(group_id, var_id, value); } void nc_meta_float(int group_id, char *name, char *desc, char *units, float *value) { int var_id; char *str = (char *) MALLOC(sizeof(char)*1024); nc_def_var(group_id, name, NC_FLOAT, 0, 0, &var_id); nc_put_att_text(group_id, var_id, "long_name", strlen(desc), desc); if (units && strlen(units) > 0) { strcpy(str, units); nc_put_att_text(group_id, var_id, "units", strlen(str), str); } nc_put_var_float(group_id, var_id, value); } void nc_meta_int(int group_id, char *name, char *desc, char *units, int *value) { int var_id; char *str = (char *) MALLOC(sizeof(char)*1024); nc_def_var(group_id, name, NC_INT, 0, 0, &var_id); nc_put_att_text(group_id, var_id, "long_name", strlen(desc), desc); if (units && strlen(units) > 0) { strcpy(str, units); nc_put_att_text(group_id, var_id, "units", strlen(str), str); } nc_put_var_int(group_id, var_id, value); } void nc_meta_str(int group_id, char *name, char *desc, char *units, char *value) { int var_id; const char *str_value = (char *) MALLOC(sizeof(char)*strlen(value)); strcpy(str_value, value); char *str = (char *) MALLOC(sizeof(char)*1024); nc_def_var(group_id, name, NC_STRING, 0, 0, &var_id); nc_put_att_text(group_id, var_id, "long_name", strlen(desc), desc); if (units && strlen(units) > 0) { strcpy(str, units); nc_put_att_text(group_id, var_id, "units", strlen(str), str); } nc_put_var_string(group_id, var_id, &str_value); } netcdf_t *initialize_netcdf_file(const char *output_file, meta_parameters *meta) { int ii, status, ncid, var_id; int dim_xgrid_id, dim_ygrid_id, dim_lat_id, dim_lon_id, dim_time_id; char *spatial_ref=NULL, *datum=NULL, *spheroid=NULL; // Convenience variables meta_general *mg = meta->general; meta_sar *ms = meta->sar; meta_state_vectors *mo = meta->state_vectors; meta_projection *mp = meta->projection; // Assign parameters int projected = FALSE; int band_count = mg->band_count; int variable_count = band_count + 3; if (mp && mp->type != SCANSAR_PROJECTION) { projected = TRUE; variable_count += 2; } size_t line_count = mg->line_count; size_t sample_count = mg->sample_count; // Assign data type nc_type datatype; if (mg->data_type == BYTE) datatype = NC_CHAR; else if (mg->data_type == REAL32) datatype = NC_FLOAT; // Initialize the netCDF pointer structure netcdf_t *netcdf = (netcdf_t *) MALLOC(sizeof(netcdf_t)); netcdf->var_count = variable_count; netcdf->var_id = (int *) MALLOC(sizeof(int)*variable_count); // Create the actual file status = nc_create(output_file, NC_CLOBBER|NC_NETCDF4, &ncid); netcdf->ncid = ncid; if (status != NC_NOERR) asfPrintError("Could not open netCDF file (%s).\n", nc_strerror(status)); // Define dimensions if (projected) { nc_def_dim(ncid, "xgrid", sample_count, &dim_xgrid_id); nc_def_dim(ncid, "ygrid", line_count, &dim_ygrid_id); } else { status = nc_def_dim(ncid, "longitude", sample_count, &dim_lon_id); if (status != NC_NOERR) asfPrintError("Problem with longitude definition\n"); status = nc_def_dim(ncid, "latitude", line_count, &dim_lat_id); if (status != NC_NOERR) asfPrintError("Problem with latitude definition\n"); } status = nc_def_dim(ncid, "time", 1, &dim_time_id); if (status != NC_NOERR) asfPrintError("Problem with time definition\n"); // Define projection char *str = (char *) MALLOC(sizeof(char)*1024); double lfValue; if (projected) { nc_def_var(ncid, "projection", NC_CHAR, 0, 0, &var_id); if (mp->type == UNIVERSAL_TRANSVERSE_MERCATOR) { strcpy(str, "transverse_mercator"); nc_put_att_text(ncid, var_id, "grid_mapping_name", strlen(str), str); nc_put_att_double(ncid, var_id, "scale_factor_at_central_meridian", NC_DOUBLE, 1, &mp->param.utm.scale_factor); nc_put_att_double(ncid, var_id, "longitude_of_central_meridian", NC_DOUBLE, 1, &mp->param.utm.lon0); nc_put_att_double(ncid, var_id, "latitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.utm.lat0); nc_put_att_double(ncid, var_id, "false_easting", NC_DOUBLE, 1, &mp->param.utm.false_easting); nc_put_att_double(ncid, var_id, "false_northing", NC_DOUBLE, 1, &mp->param.utm.false_northing); strcpy(str, "xgrid"); nc_put_att_text(ncid, var_id, "projection_x_coordinate", strlen(str), str); strcpy(str, "ygrid"); nc_put_att_text(ncid, var_id, "projection_y_coordinate", strlen(str), str); strcpy(str, "m"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); nc_put_att_double(ncid, var_id, "grid_boundary_top_projected_y", NC_DOUBLE, 1, &mp->startY); lfValue = mp->startY + mg->line_count * mp->perY; nc_put_att_double(ncid, var_id, "grid_boundary_bottom_projected_y", NC_DOUBLE, 1, &lfValue); lfValue = mp->startX + mg->sample_count * mp->perX; nc_put_att_double(ncid, var_id, "grid_boundary_right_projected_x", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "grid_boundary_left_projected_x", NC_DOUBLE, 1, &mp->startX); spatial_ref = (char *) MALLOC(sizeof(char)*1024); datum = (char *) datum_toString(mp->datum); spheroid = (char *) spheroid_toString(mp->spheroid); double flat = mp->re_major/(mp->re_major - mp->re_minor); sprintf(spatial_ref, "PROJCS[\"%s_UTM_Zone_%d%c\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.1lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",%.1lf],PARAMETER[\"False_Northing\",%.1lf],PARAMETER[\"Central_Meridian\",%.1lf],PARAMETER[\"Scale_Factor\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.1lf],UNIT[\"Meter\",1]]", spheroid, mp->param.utm.zone, mp->hem, spheroid, datum, spheroid, mp->re_major, flat, mp->param.utm.false_easting, mp->param.utm.false_northing, mp->param.utm.lon0, mp->param.utm.scale_factor, mp->param.utm.lat0); nc_put_att_text(ncid, var_id, "spatial_ref", strlen(spatial_ref), spatial_ref); sprintf(str, "+proj=utm +zone=%d", mp->param.utm.zone); if (meta->general->center_latitude < 0) strcat(str, " +south"); nc_put_att_text(ncid, var_id, "proj4text", strlen(str), str); nc_put_att_int(ncid, var_id, "zone", NC_INT, 1, &mp->param.utm.zone); nc_put_att_double(ncid, var_id, "semimajor_radius", NC_DOUBLE, 1, &mp->re_major); nc_put_att_double(ncid, var_id, "semiminor_radius", NC_DOUBLE, 1, &mp->re_minor); sprintf(str, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX, mp->startY, mp->perY); nc_put_att_text(ncid, var_id, "GeoTransform", strlen(str), str); } else if (mp->type == POLAR_STEREOGRAPHIC) { strcpy(str, "polar_stereographic"); nc_put_att_text(ncid, var_id, "grid_mapping_name", strlen(str), str); lfValue = 90.0; nc_put_att_double(ncid, var_id, "straight_vertical_longitude_from_pole", NC_DOUBLE, 1, &mp->param.ps.slon); nc_put_att_double(ncid, var_id, "longitude_of_central_meridian", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "standard_parallel", NC_DOUBLE, 1, &mp->param.ps.slat); nc_put_att_double(ncid, var_id, "false_easting", NC_DOUBLE, 1, &mp->param.ps.false_easting); nc_put_att_double(ncid, var_id, "false_northing", NC_DOUBLE, 1, &mp->param.ps.false_northing); strcpy(str, "xgrid"); nc_put_att_text(ncid, var_id, "projection_x_coordinate", strlen(str), str); strcpy(str, "ygrid"); nc_put_att_text(ncid, var_id, "projection_y_coordinate", strlen(str), str); strcpy(str, "m"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); nc_put_att_double(ncid, var_id, "grid_boundary_top_projected_y", NC_DOUBLE, 1, &mp->startY); lfValue = mp->startY + mg->line_count * mp->perY; nc_put_att_double(ncid, var_id, "grid_boundary_bottom_projected_y", NC_DOUBLE, 1, &lfValue); lfValue = mp->startX + mg->sample_count * mp->perX; nc_put_att_double(ncid, var_id, "grid_boundary_right_projected_x", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "grid_boundary_left_projected_x", NC_DOUBLE, 1, &mp->startX); spatial_ref = (char *) MALLOC(sizeof(char)*1024); datum = (char *) datum_toString(mp->datum); spheroid = (char *) spheroid_toString(mp->spheroid); double flat = mp->re_major/(mp->re_major - mp->re_minor); sprintf(spatial_ref, "PROJCS[\"Stereographic_North_Pole\",GEOGCS[\"unnamed ellipse\",DATUM[\"D_unknown\",SPHEROID[\"Unknown\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0002247191011236]],PROJECTION[\"Stereographic_North_Pole\"],PARAMETER[\"standard_parallel_1\",%.4lf],PARAMETER[\"central_meridian\",%.4lf],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",%.3lf],PARAMETER[\"false_northing\",%.3lf],UNIT[\"Meter\",1,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"3411\"]]", mp->re_major, flat, mp->param.ps.slat, mp->param.ps.slon, mp->param.ps.false_easting, mp->param.ps.false_northing); nc_put_att_text(ncid, var_id, "spatial_ref", strlen(spatial_ref), spatial_ref); if (mp->param.ps.is_north_pole) sprintf(str, "+proj=stere +lat_0=90.0000 +lat_ts=%.4lf " "+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf " "+units=m +no_defs", mp->param.ps.slat, mp->param.ps.slon, mp->param.ps.false_easting, mp->param.ps.false_northing, mp->re_major, mp->re_minor); else sprintf(str, "+proj=stere +lat_0=-90.0000 +lat_ts=%.4lf " "+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf " "+units=m +no_defs", mp->param.ps.slat, mp->param.ps.slon, mp->param.ps.false_easting, mp->param.ps.false_northing, mp->re_major, mp->re_minor); nc_put_att_text(ncid, var_id, "proj4text", strlen(str), str); nc_put_att_double(ncid, var_id, "latitude_of_true_scale", NC_DOUBLE, 1, &mp->param.ps.slat); nc_put_att_double(ncid, var_id, "longitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.ps.slon); nc_put_att_double(ncid, var_id, "semimajor_radius", NC_DOUBLE, 1, &mp->re_major); nc_put_att_double(ncid, var_id, "semiminor_radius", NC_DOUBLE, 1, &mp->re_minor); sprintf(str, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX, mp->startY, mp->perY); nc_put_att_text(ncid, var_id, "GeoTransform", strlen(str), str); } else if (mp->type == ALBERS_EQUAL_AREA) { strcpy(str, "albers_conical_equal_area"); nc_put_att_text(ncid, var_id, "grid_mapping_name", strlen(str), str); lfValue = 90.0; nc_put_att_double(ncid, var_id, "standard_parallel_1", NC_DOUBLE, 1, &mp->param.albers.std_parallel1); nc_put_att_double(ncid, var_id, "standard_parallel_2", NC_DOUBLE, 1, &mp->param.albers.std_parallel2); nc_put_att_double(ncid, var_id, "longitude_of_central_meridian", NC_DOUBLE, 1, &mp->param.albers.center_meridian); nc_put_att_double(ncid, var_id, "latitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.albers.orig_latitude); nc_put_att_double(ncid, var_id, "false_easting", NC_DOUBLE, 1, &mp->param.albers.false_easting); nc_put_att_double(ncid, var_id, "false_northing", NC_DOUBLE, 1, &mp->param.albers.false_northing); strcpy(str, "xgrid"); nc_put_att_text(ncid, var_id, "projection_x_coordinate", strlen(str), str); strcpy(str, "ygrid"); nc_put_att_text(ncid, var_id, "projection_y_coordinate", strlen(str), str); strcpy(str, "m"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); nc_put_att_double(ncid, var_id, "grid_boundary_top_projected_y", NC_DOUBLE, 1, &mp->startY); lfValue = mp->startY + mg->line_count * mp->perY; nc_put_att_double(ncid, var_id, "grid_boundary_bottom_projected_y", NC_DOUBLE, 1, &lfValue); lfValue = mp->startX + mg->sample_count * mp->perX; nc_put_att_double(ncid, var_id, "grid_boundary_right_projected_x", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "grid_boundary_left_projected_x", NC_DOUBLE, 1, &mp->startX); spatial_ref = (char *) MALLOC(sizeof(char)*1024); datum = (char *) datum_toString(mp->datum); spheroid = (char *) spheroid_toString(mp->spheroid); double flat = mp->re_major/(mp->re_major - mp->re_minor); sprintf(spatial_ref, "PROJCS[\"Albers_Equal_Area_Conic\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Standard_Parallel_1\",%.4lf],PARAMETER[\"Standard_Parallel_2\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]", datum, datum, spheroid, mp->re_major, flat, mp->param.albers.false_easting, mp->param.albers.false_northing, mp->param.albers.center_meridian, mp->param.albers.std_parallel1, mp->param.albers.std_parallel2, mp->param.albers.orig_latitude); nc_put_att_text(ncid, var_id, "spatial_ref", strlen(spatial_ref), spatial_ref); sprintf(str, "+proj=aea +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf " "+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf", mp->param.albers.std_parallel1, mp->param.albers.std_parallel2, mp->param.albers.orig_latitude, mp->param.albers.center_meridian, mp->param.albers.false_easting, mp->param.albers.false_northing); nc_put_att_text(ncid, var_id, "proj4text", strlen(str), str); nc_put_att_double(ncid, var_id, "latitude_of_true_scale", NC_DOUBLE, 1, &mp->param.ps.slat); nc_put_att_double(ncid, var_id, "longitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.ps.slon); nc_put_att_double(ncid, var_id, "semimajor_radius", NC_DOUBLE, 1, &mp->re_major); nc_put_att_double(ncid, var_id, "semiminor_radius", NC_DOUBLE, 1, &mp->re_minor); sprintf(str, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX, mp->startY, mp->perY); nc_put_att_text(ncid, var_id, "GeoTransform", strlen(str), str); } else if (mp->type == LAMBERT_CONFORMAL_CONIC) { strcpy(str, "lambert_conformal_conic"); nc_put_att_text(ncid, var_id, "grid_mapping_name", strlen(str), str); lfValue = 90.0; nc_put_att_double(ncid, var_id, "standard_parallel_1", NC_DOUBLE, 1, &mp->param.lamcc.plat1); nc_put_att_double(ncid, var_id, "standard_parallel_2", NC_DOUBLE, 1, &mp->param.lamcc.plat2); nc_put_att_double(ncid, var_id, "longitude_of_central_meridian", NC_DOUBLE, 1, &mp->param.lamcc.lon0); nc_put_att_double(ncid, var_id, "latitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.lamcc.lat0); nc_put_att_double(ncid, var_id, "false_easting", NC_DOUBLE, 1, &mp->param.lamcc.false_easting); nc_put_att_double(ncid, var_id, "false_northing", NC_DOUBLE, 1, &mp->param.lamcc.false_northing); strcpy(str, "xgrid"); nc_put_att_text(ncid, var_id, "projection_x_coordinate", strlen(str), str); strcpy(str, "ygrid"); nc_put_att_text(ncid, var_id, "projection_y_coordinate", strlen(str), str); strcpy(str, "m"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); nc_put_att_double(ncid, var_id, "grid_boundary_top_projected_y", NC_DOUBLE, 1, &mp->startY); lfValue = mp->startY + mg->line_count * mp->perY; nc_put_att_double(ncid, var_id, "grid_boundary_bottom_projected_y", NC_DOUBLE, 1, &lfValue); lfValue = mp->startX + mg->sample_count * mp->perX; nc_put_att_double(ncid, var_id, "grid_boundary_right_projected_x", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "grid_boundary_left_projected_x", NC_DOUBLE, 1, &mp->startX); spatial_ref = (char *) MALLOC(sizeof(char)*1024); datum = (char *) datum_toString(mp->datum); spheroid = (char *) spheroid_toString(mp->spheroid); double flat = mp->re_major/(mp->re_major - mp->re_minor); sprintf(spatial_ref, "PROJCS[\"Lambert_Conformal_Conic\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Standard_Parallel_1\",%.4lf],PARAMETER[\"Standard_Parallel_2\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]", datum, datum, spheroid, mp->re_major, flat, mp->param.lamcc.false_easting, mp->param.lamcc.false_northing, mp->param.lamcc.lon0, mp->param.lamcc.plat1, mp->param.lamcc.plat2, mp->param.lamcc.lat0); nc_put_att_text(ncid, var_id, "spatial_ref", strlen(spatial_ref), spatial_ref); sprintf(str, "+proj=lcc +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf " "+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf", mp->param.lamcc.plat1, mp->param.lamcc.plat2, mp->param.lamcc.lat0, mp->param.lamcc.lon0, mp->param.lamcc.false_easting, mp->param.lamcc.false_northing); nc_put_att_text(ncid, var_id, "proj4text", strlen(str), str); nc_put_att_double(ncid, var_id, "semimajor_radius", NC_DOUBLE, 1, &mp->re_major); nc_put_att_double(ncid, var_id, "semiminor_radius", NC_DOUBLE, 1, &mp->re_minor); sprintf(str, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX, mp->startY, mp->perY); nc_put_att_text(ncid, var_id, "GeoTransform", strlen(str), str); } else if (mp->type == LAMBERT_AZIMUTHAL_EQUAL_AREA) { strcpy(str, "lambert_azimuthal_equal_area"); nc_put_att_text(ncid, var_id, "grid_mapping_name", strlen(str), str); nc_put_att_double(ncid, var_id, "longitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.lamaz.center_lon); nc_put_att_double(ncid, var_id, "latitude_of_projection_origin", NC_DOUBLE, 1, &mp->param.lamaz.center_lat); nc_put_att_double(ncid, var_id, "false_easting", NC_DOUBLE, 1, &mp->param.lamaz.false_easting); nc_put_att_double(ncid, var_id, "false_northing", NC_DOUBLE, 1, &mp->param.lamaz.false_northing); strcpy(str, "xgrid"); nc_put_att_text(ncid, var_id, "projection_x_coordinate", strlen(str), str); strcpy(str, "ygrid"); nc_put_att_text(ncid, var_id, "projection_y_coordinate", strlen(str), str); strcpy(str, "m"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); nc_put_att_double(ncid, var_id, "grid_boundary_top_projected_y", NC_DOUBLE, 1, &mp->startY); lfValue = mp->startY + mg->line_count * mp->perY; nc_put_att_double(ncid, var_id, "grid_boundary_bottom_projected_y", NC_DOUBLE, 1, &lfValue); lfValue = mp->startX + mg->sample_count * mp->perX; nc_put_att_double(ncid, var_id, "grid_boundary_right_projected_x", NC_DOUBLE, 1, &lfValue); nc_put_att_double(ncid, var_id, "grid_boundary_left_projected_x", NC_DOUBLE, 1, &mp->startX); spatial_ref = (char *) MALLOC(sizeof(char)*1024); datum = (char *) datum_toString(mp->datum); spheroid = (char *) spheroid_toString(mp->spheroid); double flat = mp->re_major/(mp->re_major - mp->re_minor); sprintf(spatial_ref, "PROJCS[\"Lambert_Azimuthal_Equal_Area\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]", datum, datum, spheroid, mp->re_major, flat, mp->param.lamaz.false_easting, mp->param.lamaz.false_northing, mp->param.lamaz.center_lon, mp->param.lamaz.center_lat); nc_put_att_text(ncid, var_id, "spatial_ref", strlen(spatial_ref), spatial_ref); sprintf(str, "+proj=laea +lat_0=%.4lf +lon_0=%.4lf +x_0=%.3lf " "+y_0=%.3lf", mp->param.lamaz.center_lat, mp->param.lamaz.center_lon, mp->param.lamaz.false_easting, mp->param.lamaz.false_northing); nc_put_att_text(ncid, var_id, "proj4text", strlen(str), str); nc_put_att_double(ncid, var_id, "semimajor_radius", NC_DOUBLE, 1, &mp->re_major); nc_put_att_double(ncid, var_id, "semiminor_radius", NC_DOUBLE, 1, &mp->re_minor); sprintf(str, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX, mp->startY, mp->perY); nc_put_att_text(ncid, var_id, "GeoTransform", strlen(str), str); } } // Define variables and data attributes char **band_name = extract_band_names(meta->general->bands, band_count); int dims_bands[3]; dims_bands[0] = dim_time_id; if (projected) { dims_bands[1] = dim_ygrid_id; dims_bands[2] = dim_xgrid_id; } else { dims_bands[1] = dim_lon_id; dims_bands[2] = dim_lat_id; } for (ii=0; ii<band_count; ii++) { sprintf(str, "%s_AMPLITUDE_IMAGE", band_name[ii]); nc_def_var(ncid, str, datatype, 3, dims_bands, &var_id); netcdf->var_id[ii] = var_id; nc_def_var_deflate(ncid, var_id, 0, 1, 6); lfValue = -999.0; nc_put_att_double(ncid, var_id, "FillValue", NC_DOUBLE, 1, &lfValue); sprintf(str, "%s", mg->sensor); if (mg->image_data_type < 9) strcat(str, " radar backscatter"); if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB) strcat(str, " in dB"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); strcpy(str, "area: backcatter value"); nc_put_att_text(ncid, var_id, "cell_methods", strlen(str), str); strcpy(str, "1"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); strcpy(str, "unitless normalized radar cross-section"); if (mg->radiometry >= r_SIGMA && mg->radiometry <= r_GAMMA) strcat(str, " stored as powerscale"); else if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB) strcat(str, " stored as dB=10*log10(*)"); nc_put_att_text(ncid, var_id, "units_description", strlen(str), str); strcpy(str, "longitude latitude"); nc_put_att_text(ncid, var_id, "coordinates", strlen(str), str); if (projected) { strcpy(str, "projection"); nc_put_att_text(ncid, var_id, "grid_mapping", strlen(str), str); } } // Define other attributes ymd_date ymd; hms_time hms; parse_date(mg->acquisition_date, &ymd, &hms); // Time ii = band_count; int dims_time[1] = { dim_time_id }; nc_def_var(ncid, "time", NC_FLOAT, 1, dims_time, &var_id); netcdf->var_id[ii] = var_id; strcpy(str, "seconds since 1900-01-01T00:00:00Z"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); strcpy(str, "scene center time"); nc_put_att_text(ncid, var_id, "references", strlen(str), str); strcpy(str, "time"); nc_put_att_text(ncid, var_id, "standard_name", strlen(str), str); strcpy(str, "T"); nc_put_att_text(ncid, var_id, "axis", strlen(str), str); strcpy(str, "serial date"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); // Longitude ii++; if (projected) { int dims_lon[2] = { dim_ygrid_id, dim_xgrid_id }; nc_def_var(ncid, "longitude", NC_FLOAT, 2, dims_lon, &var_id); } else { int dims_lon[2] = { dim_lon_id, dim_lat_id }; nc_def_var(ncid, "longitude", NC_FLOAT, 2, dims_lon, &var_id); } netcdf->var_id[ii] = var_id; nc_def_var_deflate(ncid, var_id, 0, 1, 6); strcpy(str, "longitude"); nc_put_att_text(ncid, var_id, "standard_name", strlen(str), str); strcpy(str, "longitude"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); strcpy(str, "degrees_east"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); double *valid_range = (double *) MALLOC(sizeof(double)*2); valid_range[0] = -180.0; valid_range[1] = 180.0; nc_put_att_double(ncid, var_id, "valid_range", NC_DOUBLE, 2, valid_range); FREE(valid_range); lfValue = -999.0; nc_put_att_double(ncid, var_id, "FillValue", NC_DOUBLE, 1, &lfValue); // Latitude ii++; if (projected) { int dims_lat[2] = { dim_ygrid_id, dim_xgrid_id }; nc_def_var(ncid, "latitude", NC_FLOAT, 2, dims_lat, &var_id); } else { int dims_lat[2] = { dim_lat_id, dim_lon_id }; nc_def_var(ncid, "latitude", NC_FLOAT, 2, dims_lat, &var_id); } netcdf->var_id[ii] = var_id; nc_def_var_deflate(ncid, var_id, 0, 1, 6); strcpy(str, "latitude"); nc_put_att_text(ncid, var_id, "standard_name", strlen(str), str); strcpy(str, "latitude"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); strcpy(str, "degrees_north"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); valid_range = (double *) MALLOC(sizeof(double)*2); valid_range[0] = -90.0; valid_range[1] = 90.0; nc_put_att_double(ncid, var_id, "valid_range", NC_DOUBLE, 2, valid_range); FREE(valid_range); lfValue = -999.0; nc_put_att_double(ncid, var_id, "FillValue", NC_DOUBLE, 1, &lfValue); if (projected) { // ygrid ii++; int dims_ygrid[1] = { dim_ygrid_id }; nc_def_var(ncid, "ygrid", NC_FLOAT, 1, dims_ygrid, &var_id); netcdf->var_id[ii] = var_id; nc_def_var_deflate(ncid, var_id, 0, 1, 6); strcpy(str, "projection_y_coordinates"); nc_put_att_text(ncid, var_id, "standard_name", strlen(str), str); strcpy(str, "projection_grid_y_centers"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); strcpy(str, "meters"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); strcpy(str, "Y"); nc_put_att_text(ncid, var_id, "axis", strlen(str), str); // xgrid ii++; int dims_xgrid[1] = { dim_xgrid_id }; nc_def_var(ncid, "xgrid", NC_FLOAT, 1, dims_xgrid, &var_id); netcdf->var_id[ii] = var_id; nc_def_var_deflate(ncid, var_id, 0, 1, 6); strcpy(str, "projection_x_coordinates"); nc_put_att_text(ncid, var_id, "standard_name", strlen(str), str); strcpy(str, "projection_grid_x_centers"); nc_put_att_text(ncid, var_id, "long_name", strlen(str), str); strcpy(str, "meters"); nc_put_att_text(ncid, var_id, "units", strlen(str), str); strcpy(str, "X"); nc_put_att_text(ncid, var_id, "axis", strlen(str), str); } // Define global attributes strcpy(str, "CF-1.4"); nc_put_att_text(ncid, NC_GLOBAL, "Conventions", strlen(str), str); strcpy(str, "Alaska Satellite Facility"); nc_put_att_text(ncid, NC_GLOBAL, "institution", strlen(str), str); sprintf(str, "%s %s %s image", mg->sensor, mg->sensor_name, mg->mode); nc_put_att_text(ncid, NC_GLOBAL, "title", strlen(str), str); if (mg->image_data_type == AMPLITUDE_IMAGE) strcpy(str, "SAR backcatter image"); nc_put_att_text(ncid, NC_GLOBAL, "source", strlen(str), str); sprintf(str, "%s", mg->basename); nc_put_att_text(ncid, NC_GLOBAL, "original_file", strlen(str), str); if (strcmp_case(mg->sensor, "RSAT-1") == 0) sprintf(str, "Copyright Canadian Space Agency, %d", ymd.year); else if (strncmp_case(mg->sensor, "ERS", 3) == 0) sprintf(str, "Copyright European Space Agency, %d", ymd.year); else if (strcmp_case(mg->sensor, "JERS-1") == 0 || strcmp_case(mg->sensor, "ALOS") == 0) sprintf(str, "Copyright Japan Aerospace Exploration Agency , %d", ymd.year); nc_put_att_text(ncid, NC_GLOBAL, "comment", strlen(str), str); strcpy(str, "Documentation available at: www.asf.alaska.edu"); nc_put_att_text(ncid, NC_GLOBAL, "references", strlen(str), str); time_t t; struct tm *timeinfo; time(&t); timeinfo = gmtime(&t); sprintf(str, "%s", asctime(timeinfo)); chomp(str); strcat(str, ", UTC: netCDF File created."); nc_put_att_text(ncid, NC_GLOBAL, "history", strlen(str), str); // Metadata int meta_id; nc_def_grp(ncid, "metadata", &meta_id); // Metadata - general block nc_meta_str(meta_id, "general_name", "file name", NULL, mg->basename); nc_meta_str(meta_id, "general_sensor", "imaging satellite", NULL, mg->sensor); nc_meta_str(meta_id, "general_sensor_name", "imaging sensor", NULL, mg->sensor_name); nc_meta_str(meta_id, "general_mode", "imaging mode", NULL, mg->mode); nc_meta_str(meta_id, "general_processor", "name and version of processor", NULL, mg->processor); nc_meta_str(meta_id, "general_data_type", "type of samples (e.g. REAL64)", NULL, data_type2str(mg->data_type)); nc_meta_str(meta_id, "general_image_data_type", "image data type (e.g. AMPLITUDE_IMAGE)", NULL, image_data_type2str(mg->image_data_type)); nc_meta_str(meta_id, "general_radiometry", "radiometry (e.g. SIGMA)", NULL, radiometry2str(mg->radiometry)); nc_meta_str(meta_id, "general_acquisition_date", "acquisition date of the image", NULL, mg->acquisition_date); nc_meta_int(meta_id, "general_orbit", "orbit number of image", NULL, &mg->orbit); if (mg->orbit_direction == 'A') strcpy(str, "Ascending"); else strcpy(str, "Descending"); nc_meta_str(meta_id, "general_orbit_direction", "orbit direction", NULL, str); nc_meta_int(meta_id, "general_frame", "frame number of image", NULL, &mg->frame); nc_meta_int(meta_id, "general_band_count", "number of bands in image", NULL, &mg->band_count); nc_meta_str(meta_id, "general_bands", "bands of the sensor", NULL, &mg->bands); nc_meta_int(meta_id, "general_line_count", "number of lines in image", NULL, &mg->line_count); nc_meta_int(meta_id, "general_sample_count", "number of samples in image", NULL, &mg->sample_count); nc_meta_int(meta_id, "general_start_line", "first line relative to original image", NULL, &mg->start_line); nc_meta_int(meta_id, "general_start_sample", "first sample relative to original image", NULL, &mg->start_sample); nc_meta_double(meta_id, "general_x_pixel_size", "range pixel size", "m", &mg->x_pixel_size); nc_meta_double(meta_id, "general_y_pixel_size", "azimuth pixel size", "m", &mg->y_pixel_size); nc_meta_double(meta_id, "general_center_latitude", "approximate image center latitude", "degrees_north", &mg->center_latitude); nc_meta_double(meta_id, "general_center_longitude", "approximate image center longitude", "degrees_east", &mg->center_longitude); nc_meta_double(meta_id, "general_re_major", "major (equator) axis of earth", "m", &mg->re_major); nc_meta_double(meta_id, "general_re_minor", "minor (polar) axis of earth", "m", &mg->re_minor); nc_meta_double(meta_id, "general_bit_error_rate", "fraction of bits which are in error", NULL, &mg->bit_error_rate); nc_meta_int(meta_id, "general_missing_lines", "number of missing lines in data take", NULL, &mg->missing_lines); nc_meta_float(meta_id, "general_no_data", "value indicating no data for a pixel", NULL, &mg->no_data); if (ms) { // Metadata - SAR block if (ms->image_type == 'S') sprintf(str, "slant range"); else if (ms->image_type == 'G') sprintf(str, "ground range"); else if (ms->image_type == 'P') sprintf(str, "projected"); else if (ms->image_type == 'R') sprintf(str, "georeferenced"); nc_meta_str(meta_id, "sar_image_type", "image type", NULL, str); if (ms->look_direction == 'R') sprintf(str, "right"); else if (ms->look_direction == 'L') sprintf(str, "left"); nc_meta_str(meta_id, "sar_look_direction", "SAR satellite look direction", NULL, str); nc_meta_int(meta_id, "sar_look_count", "number of looks to take from SLC", NULL, &ms->look_count); nc_meta_int(meta_id, "sar_multilook", "multilooking flag", NULL, &ms->multilook); nc_meta_int(meta_id, "sar_deskewed", "zero doppler deskew flag", NULL, &ms->deskewed); nc_meta_int(meta_id, "sar_original_line_count", "number of lines in original image", NULL, &ms->original_line_count); nc_meta_int(meta_id, "sar_original_sample_count", "number of samples in original image", NULL, &ms->original_sample_count); nc_meta_double(meta_id, "sar_line_increment", "line increment for sampling", NULL, &ms->line_increment); nc_meta_double(meta_id, "sar_sample_increment", "sample increment for sampling", NULL, &ms->sample_increment); nc_meta_double(meta_id, "sar_range_time_per_pixel", "time per pixel in range", "s", &ms->range_time_per_pixel); nc_meta_double(meta_id, "sar_azimuth_time_per_pixel", "time per pixel in azimuth", "s", &ms->azimuth_time_per_pixel); nc_meta_double(meta_id, "sar_slant_range_first_pixel", "slant range to first pixel", "m", &ms->slant_range_first_pixel); nc_meta_double(meta_id, "sar_slant_shift", "error correction factor in slant range", "m", &ms->slant_shift); nc_meta_double(meta_id, "sar_time_shift", "error correction factor in time", "s", &ms->time_shift); nc_meta_double(meta_id, "sar_wavelength", "SAR carrier wavelength", "m", &ms->wavelength); nc_meta_double(meta_id, "sar_pulse_repetition_frequency", "pulse repetition frequency", "Hz", &ms->prf); nc_meta_double(meta_id, "sar_earth_radius", "earth radius at scene center", "m", &ms->earth_radius); nc_meta_double(meta_id, "sar_satellite_height", "satellite height from earth's center", "m", &ms->satellite_height); nc_meta_double(meta_id, "sar_range_doppler_centroid", "range doppler centroid", "Hz", &ms->range_doppler_coefficients[0]); nc_meta_double(meta_id, "sar_range_doppler_linear", "range doppler per range pixel", "Hz/pixel", &ms->range_doppler_coefficients[1]); nc_meta_double(meta_id, "sar_range_doppler_quadratic", "range doppler per range pixel square", "Hz/pixel^2", &ms->range_doppler_coefficients[2]); nc_meta_double(meta_id, "sar_azimuth_doppler_centroid", "azimuth doppler centroid", "Hz", &ms->azimuth_doppler_coefficients[0]); nc_meta_double(meta_id, "sar_azimuth_doppler_linear", "azimuth doppler per azimuth pixel", "Hz/pixel", &ms->azimuth_doppler_coefficients[1]); nc_meta_double(meta_id, "sar_azimuth_doppler_quadratic", "azimuth doppler per azimuth per azimuth pixel square", "Hz/pixel^2", &ms->azimuth_doppler_coefficients[2]); } char tmp[50]; if (mo) { // Metadata - state vector block nc_meta_int(meta_id, "orbit_year", "year of image start", NULL, &mo->year); nc_meta_int(meta_id, "orbit_day_of_year", "day of the year at image start", NULL, &mo->julDay); nc_meta_double(meta_id, "orbit_second_of_day", "second of the day at image start", "seconds", &mo->second); int vector_count = mo->vector_count; nc_meta_int(meta_id, "orbit_vector_count", "number of state vectors", NULL, &vector_count); for (ii=0; ii<vector_count; ii++) { sprintf(tmp, "orbit_vector[%d]_time", ii+1); nc_meta_double(meta_id, tmp, "time relative to image start", "s", &mo->vecs[ii].time); sprintf(tmp, "orbit_vector[%d]_position_x", ii+1); nc_meta_double(meta_id, tmp, "x coordinate, earth-fixed", "m", &mo->vecs[ii].vec.pos.x); sprintf(tmp, "orbit_vector[%d]_position_y", ii+1); nc_meta_double(meta_id, tmp, "y coordinate, earth-fixed", "m", &mo->vecs[ii].vec.pos.y); sprintf(tmp, "orbit_vector[%d]_position_z", ii+1); nc_meta_double(meta_id, tmp, "z coordinate, earth-fixed", "m", &mo->vecs[ii].vec.pos.z); sprintf(tmp, "orbit_vector[%d]_velocity_x", ii+1); nc_meta_double(meta_id, tmp, "x velocity, earth-fixed", "m/s", &mo->vecs[ii].vec.vel.x); sprintf(tmp, "orbit_vector[%d]_velocity_y", ii+1); nc_meta_double(meta_id, tmp, "y velocity, earth-fixed", "m/s", &mo->vecs[ii].vec.vel.y); sprintf(tmp, "orbit_vector[%d]_velocity_z", ii+1); nc_meta_double(meta_id, tmp, "z velocity, earth-fixed", "m/s", &mo->vecs[ii].vec.vel.z); } } // Finish off definition block nc_enddef(ncid); // Write ASF metadata to XML file char *output_file_name = (char *) MALLOC(sizeof(char)*(strlen(output_file)+5)); sprintf(output_file_name, "%s.xml", output_file); meta_write_xml(meta, output_file_name); FREE(output_file_name); // Clean up FREE(str); if (spatial_ref) FREE(spatial_ref); return netcdf; } void finalize_netcdf_file(netcdf_t *netcdf, meta_parameters *md) { int ncid = netcdf->ncid; int n = md->general->band_count; int nl = md->general->line_count; int ns = md->general->sample_count; long pixel_count = md->general->line_count * md->general->sample_count; int projected = FALSE; if (md->projection && md->projection->type != SCANSAR_PROJECTION) projected = TRUE; // Extra bands - Time float time = (float) seconds_from_str(md->general->acquisition_date); asfPrintStatus("Storing band 'time' ...\n"); nc_put_var_float(ncid, netcdf->var_id[n], &time); // Extra bands - longitude n++; int ii, kk; double *value = (double *) MALLOC(sizeof(double)*MAX_PTS); double *l = (double *) MALLOC(sizeof(double)*MAX_PTS); double *s = (double *) MALLOC(sizeof(double)*MAX_PTS); double line, sample, lat, lon, first_value; float *lons = (float *) MALLOC(sizeof(float)*pixel_count); asfPrintStatus("Generating band 'longitude' ...\n"); meta_get_latLon(md, 0, 0, 0.0, &lat, &lon); if (lon < 0.0) first_value = lon + 360.0; else first_value = lon; asfPrintStatus("Calculating grid for quadratic fit ...\n"); for (ii=0; ii<RES; ii++) { for (kk=0; kk<RES; kk++) { line = ii * nl / RES; sample = kk * ns / RES; meta_get_latLon(md, line, sample, 0.0, &lat, &lon); l[ii*RES+kk] = line; s[ii*RES+kk] = sample; if (lon < 0.0) value[ii*RES+kk] = lon + 360.0; else value[ii*RES+kk] = lon; } asfLineMeter(ii, nl); } quadratic_2d q = find_quadratic(value, l, s, MAX_PTS); q.A = first_value; for (ii=0; ii<nl; ii++) { for (kk=0; kk<ns; kk++) { lons[ii*ns+kk] = (float) (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk + q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii + q.K*kk*kk*kk) - 360.0; if (lons[ii*ns+kk] < -180.0) lons[ii*ns+kk] += 360.0; } asfLineMeter(ii, nl); } asfPrintStatus("Storing band 'longitude' ...\n"); nc_put_var_float(ncid, netcdf->var_id[n], &lons[0]); FREE(lons); // Extra bands - Latitude n++; float *lats = (float *) MALLOC(sizeof(float)*pixel_count); asfPrintStatus("Generating band 'latitude' ...\n"); meta_get_latLon(md, 0, 0, 0.0, &lat, &lon); first_value = lat + 180.0; asfPrintStatus("Calculating grid for quadratic fit ...\n"); for (ii=0; ii<RES; ii++) { for (kk=0; kk<RES; kk++) { line = ii * nl / RES; sample = kk * ns / RES; meta_get_latLon(md, line, sample, 0.0, &lat, &lon); l[ii*RES+kk] = line; s[ii*RES+kk] = sample; value[ii*RES+kk] = lat + 180.0; } asfLineMeter(ii, nl); } q = find_quadratic(value, l, s, MAX_PTS); q.A = first_value; for (ii=0; ii<nl; ii++) { for (kk=0; kk<ns; kk++) { if (md->general->orbit_direction == 'A') lats[(nl-ii-1)*ns+kk] = (float) (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk + q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii + q.K*kk*kk*kk) - 180.0; else lats[ii*ns+kk] = (float) (q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk + q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii + q.K*kk*kk*kk) - 180.0; } asfLineMeter(ii, nl); } asfPrintStatus("Storing band 'latitude' ...\n"); nc_put_var_float(ncid, netcdf->var_id[n], &lats[0]); FREE(lats); if (projected) { // Extra bands - ygrid n++; float *ygrids = (float *) MALLOC(sizeof(float)*pixel_count); for (ii=0; ii<nl; ii++) { for (kk=0; kk<ns; kk++) ygrids[ii*ns+kk] = md->projection->startY + kk*md->projection->perY; asfLineMeter(ii, nl); } asfPrintStatus("Storing band 'ygrid' ...\n"); nc_put_var_float(ncid, netcdf->var_id[n], &ygrids[0]); FREE(ygrids); // Extra bands - xgrid n++; float *xgrids = (float *) MALLOC(sizeof(float)*pixel_count); for (ii=0; ii<nl; ii++) { for (kk=0; kk<ns; kk++) xgrids[ii*ns+kk] = md->projection->startX + kk*md->projection->perX; asfLineMeter(ii, nl); } asfPrintStatus("Storing band 'xgrid' ...\n"); nc_put_var_float(ncid, netcdf->var_id[n], &xgrids[0]); FREE(xgrids); } // Close file and clean up int status = nc_close(ncid); if (status != NC_NOERR) asfPrintError("Could not close netCDF file (%s).\n", nc_strerror(status)); FREE(netcdf->var_id); FREE(netcdf); }
{ "alphanum_fraction": 0.6636677377, "avg_line_length": 43.225308642, "ext": "c", "hexsha": "f0927900e9cc060be2827853717828c79f438c3e", "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_export/export_netcdf.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_export/export_netcdf.c", "max_line_length": 509, "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_export/export_netcdf.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": 13406, "size": 42015 }
#include <cublas.h> #include <cblas.h> #include <stdio.h> #include <stdlib.h> void checkStatus(char* message, cublasStatus status) { if (status != CUBLAS_STATUS_SUCCESS) { fprintf (stderr, "!!!! %s fail %d\n", message, status); exit(EXIT_FAILURE); } } double cblas_ddot (const int n, const double *x, const int incx, const double *y, const int incy) { double result; double *cuA, *cuB; cublasStatus status; status = cublasInit(); checkStatus("init", status); status = cublasAlloc(n, sizeof(double),(void**)&cuA); checkStatus("A", status); status = cublasAlloc(n, sizeof(double),(void**)&cuB); checkStatus("B", status); status = cublasSetVector(n, sizeof(double), x, incx, cuA, incx); checkStatus("setA", status); status = cublasSetVector(n, sizeof(double), y, incy, cuB, incy); checkStatus("setB", status); result = cublasDdot(n, cuA, incx, cuB, incy); status = cublasFree(cuA); checkStatus("freeA", status); status = cublasFree(cuB); checkStatus("freeB", status); // cublasShutdown(); return result; } void cblas_dgemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) { double *cuA, *cuB, *cuC; cublasStatus status; status = cublasInit(); checkStatus("init", status); status = cublasAlloc(M * N, sizeof(double),(void**)&cuA); checkStatus("A", status); status = cublasAlloc(N * K, sizeof(double),(void**)&cuB); checkStatus("B", status); status = cublasAlloc(M * K, sizeof(double),(void**)&cuC); checkStatus("C", status); status = cublasSetMatrix(M, N, sizeof(double), A, lda, cuA, lda); checkStatus("setA", status); status = cublasSetMatrix(M, N, sizeof(double), B, ldb, cuB, ldb); checkStatus("setB", status); // status = cublasSetMatrix(M, N, sizeof(double), C, ldc, cuC, ldc); // checkStatus("setC", status); // HACK: ignore trans cublasDgemm('N', 'N', M, N, K, alpha, cuA, lda, cuB, ldb, beta, cuC, ldc); //checkStatus("dgemm", status); status = cublasGetMatrix(M, N, sizeof(double), cuC, ldc, C, ldc); checkStatus("setB", status); status = cublasFree(cuA); checkStatus("freeA", status); status = cublasFree(cuB); checkStatus("freeB", status); status = cublasFree(cuC); checkStatus("freeC", status); // cublasShutdown(); }
{ "alphanum_fraction": 0.6537396122, "avg_line_length": 29.7294117647, "ext": "c", "hexsha": "9b9f6a28d02ca50fd21a4363b7d2e247be9ba96f", "lang": "C", "max_forks_count": 154, "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_path": "perf/src/main/c/cudawrapper.c", "max_issues_count": 59, "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_path": "perf/src/main/c/cudawrapper.c", "max_line_length": 99, "max_stars_count": 624, "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_path": "perf/src/main/c/cudawrapper.c", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "num_tokens": 747, "size": 2527 }
static char help[] = "Solves a 1D Poisson problem with DMDA and KSP.\n\n"; #include <petsc.h> extern PetscErrorCode formdirichletlaplacian(DM, Mat); extern PetscErrorCode formExactAndRHS(DM, Vec, Vec); int main(int argc,char **args) { PetscErrorCode ierr; DM da; KSP ksp; Mat A; Vec b,u,uexact; PetscReal errnorm; DMDALocalInfo info; PetscInitialize(&argc,&args,(char*)0,help); ierr = DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, 9,1,1,NULL, &da); CHKERRQ(ierr); ierr = DMSetFromOptions(da); CHKERRQ(ierr); ierr = DMSetUp(da); CHKERRQ(ierr); ierr = DMDASetUniformCoordinates(da,0.0,1.0,-1.0,-1.0,-1.0,-1.0); CHKERRQ(ierr); ierr = DMCreateMatrix(da,&A);CHKERRQ(ierr); ierr = MatSetOptionsPrefix(A,"a_"); CHKERRQ(ierr); ierr = MatSetFromOptions(A); CHKERRQ(ierr); ierr = DMCreateGlobalVector(da,&b);CHKERRQ(ierr); ierr = VecDuplicate(b,&u); CHKERRQ(ierr); ierr = VecDuplicate(b,&uexact); CHKERRQ(ierr); ierr = formExactAndRHS(da,uexact,b); CHKERRQ(ierr); ierr = formdirichletlaplacian(da,A); CHKERRQ(ierr); ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr); ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr); ierr = KSPSolve(ksp,b,u); CHKERRQ(ierr); ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uxact ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr); ierr = DMDAGetLocalInfo(da,&info);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD, "on %d point grid: error |u-uexact|_inf = %g\n", info.mx,errnorm); CHKERRQ(ierr); VecDestroy(&u); VecDestroy(&uexact); VecDestroy(&b); MatDestroy(&A); KSPDestroy(&ksp); DMDestroy(&da); return PetscFinalize(); } PetscErrorCode formdirichletlaplacian(DM da, Mat A) { PetscErrorCode ierr; DMDALocalInfo info; PetscInt i; ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); for (i=info.xs; i<info.xs+info.xm; i++) { PetscReal v[3]; PetscInt row = i, col[3]; PetscInt ncols=0; if ( (i==0) || (i==info.mx-1) ) { col[ncols] = i; v[ncols++] = 1.0; } else { col[ncols] = i; v[ncols++] = 2.0; if (i-1>0) { col[ncols] = i-1; v[ncols++] = -1.0; } if (i+1<info.mx-1) { col[ncols] = i+1; v[ncols++] = -1.0; } } ierr = MatSetValues(A,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr); } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); return 0; } PetscErrorCode formExactAndRHS(DM da, Vec uexact, Vec b) { PetscErrorCode ierr; DMDALocalInfo info; PetscInt i; PetscReal h, x, *ab, *auexact; ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr); h = 1.0/(info.mx-1); ierr = DMDAVecGetArray(da, b, &ab);CHKERRQ(ierr); ierr = DMDAVecGetArray(da, uexact, &auexact);CHKERRQ(ierr); for (i=info.xs; i<info.xs+info.xm; i++) { x = i * h; auexact[i] = x*x * (1.0 - x*x); if ( (i>0) && (i<info.mx-1) ) ab[i] = h*h * (12.0 * x*x - 2.0); else ab[i] = 0.0; } ierr = DMDAVecRestoreArray(da, uexact, &auexact);CHKERRQ(ierr); ierr = DMDAVecRestoreArray(da, b, &ab); CHKERRQ(ierr); ierr = VecAssemblyBegin(b); CHKERRQ(ierr); ierr = VecAssemblyEnd(b); CHKERRQ(ierr); ierr = VecAssemblyBegin(uexact); CHKERRQ(ierr); ierr = VecAssemblyEnd(uexact); CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.6138222849, "avg_line_length": 35.099009901, "ext": "c", "hexsha": "45861967770912e991ba668e46cf9bb8e2a440d7", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch3/solns/poisson1D.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch3/solns/poisson1D.c", "max_line_length": 82, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch3/solns/poisson1D.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 1205, "size": 3545 }
#include <stdlib.h> #include <stdio.h> #include <time.h> #include "datatools.h" /* helper functions */ #include "matadd.h" /* my matrix add fucntion */ #include "matmat.h" /* my matrix add fucntion */ #include "matvec.h" /* my matrix add fucntion */ #if defined(__MACH__) && defined(__APPLE__) #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #define NREPEAT 100 /* repeat count for the experiment loop */ #define mytimer clock #define delta_t(a,b) (1e3 * (b - a) / CLOCKS_PER_SEC) int main(int argc, char *argv[]) { int i, m, n, k, N = NREPEAT; double **A, **B, **C; double tcpu1; clock_t t1, t2; m = 2; n = 6; k = 7; /* Allocate memory */ A = malloc_2d(m,k); B = malloc_2d(k,n); C = malloc_2d(m,n); if (A == NULL || B == NULL | C == NULL) { fprintf(stderr, "Memory allocation error...\n"); /* Free memory */ free_2d(A); free_2d(B); free_2d(C); exit(EXIT_FAILURE); } /* initialize with useful data - last argument is reference */ init_data_2d(m,k,A,1); init_data_2d(k,n,B,2); // printf("dette er A \n"); // print_matrix_2d(m,k,A); // printf("\n"); // printf("dette er b \n"); // print_matrix_1d(n, b); // printf("\n"); /* timings for matadd */ t1 = mytimer(); for (i = 0; i < N; i++) { // matrix addition matmat(m,n,k,A,B,C); } t2 = mytimer(); tcpu1 = delta_t(t1, t2) / N; printf("dette er C \n"); print_matrix_2d(m,n, C); printf("\n"); // check_results("main", m, n, C); /* Print n and results */ printf("%4d %4d %8.3f\n", m, n, tcpu1); /* Free memory */ free_2d(A); free_2d(B); free_2d(C); /* BLAS */ int ii, incx, nn; double aa, xx[5] = {2.0,2.0,2.0,2.0,2.0}; nn = 5; aa= 3.0; incx=1; cblas_dscal(nn,aa,xx,incx); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5807713807, "avg_line_length": 19.2365591398, "ext": "c", "hexsha": "5eb5a069975926ed5060f9aa6ed573bfe6bafc4f", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-01-18T16:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-22T10:34:10.000Z", "max_forks_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "anderslaunerbaek/HPC", "max_forks_repo_path": "exercises/mat_operations/main_5.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "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": "anderslaunerbaek/HPC", "max_issues_repo_path": "exercises/mat_operations/main_5.c", "max_line_length": 63, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c63201022e2715112bc38dcc2a53316ea1e2b055", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "anderslaunerbaek/HPC", "max_stars_repo_path": "exercises/mat_operations/main_5.c", "max_stars_repo_stars_event_max_datetime": "2022-01-06T08:58:43.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-06T08:58:43.000Z", "num_tokens": 649, "size": 1789 }
//============================================================================== // // Copyright 2018 The InsideLoop Authors. All Rights Reserved. // // 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 IL_BLAS_DEFINE_H #define IL_BLAS_DEFINE_H #ifdef IL_MKL #include <mkl_cblas.h> #define IL_CBLAS_INT MKL_INT #define IL_CBLAS_LAYOUT CBLAS_LAYOUT #define IL_CBLAS_PCOMPLEX64 float* #define IL_CBLAS_PCOMPLEX128 double* #define IL_CBLAS_PCOMPLEX64_ANS float* #define IL_CBLAS_PCOMPLEX128_ANS double* #elif IL_OPENBLAS #include <cblas.h> #define IL_CBLAS_INT int #define IL_CBLAS_LAYOUT CBLAS_ORDER #define IL_CBLAS_PCOMPLEX64 float* #define IL_CBLAS_PCOMPLEX128 double* #define IL_CBLAS_PCOMPLEX64_ANS openblas_complex_float* #define IL_CBLAS_PCOMPLEX128_ANS openblas_complex_double* #endif #endif // IL_BLAS_DEFINE_H
{ "alphanum_fraction": 0.7054263566, "avg_line_length": 31.5333333333, "ext": "h", "hexsha": "805cca43d9e562739bef715046ccd433e0e81dd1", "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": "5385e908d85697e32fa065b45f608df84d3177a3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "insideloop/InsideLoop", "max_forks_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "5385e908d85697e32fa065b45f608df84d3177a3", "max_issues_repo_issues_event_max_datetime": "2017-03-14T11:08:32.000Z", "max_issues_repo_issues_event_min_datetime": "2017-03-10T17:28:33.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "insideloop/InsideLoop", "max_issues_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_line_length": 80, "max_stars_count": 19, "max_stars_repo_head_hexsha": "5385e908d85697e32fa065b45f608df84d3177a3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "insideloop/InsideLoop", "max_stars_repo_path": "il/linearAlgebra/dense/blas/blas_config.h", "max_stars_repo_stars_event_max_datetime": "2017-08-18T01:26:52.000Z", "max_stars_repo_stars_event_min_datetime": "2016-12-08T14:16:28.000Z", "num_tokens": 329, "size": 1419 }
/* * author: Achim Gaedke * created: May 2001 * file: pygsl/src/constmodule.c * $Id: constmodule.c,v 1.11 2007/11/26 20:25:09 schnizer Exp $ * * * Changes: * 7. October 2003 Added support for gsl-1.4 constants. */ #include <Python.h> #include <gsl/gsl_math.h> #include <gsl/gsl_const_num.h> #include <pygsl/pygsl_features.h> #ifdef _PYGSL_GSL_HAS_CGS #include <gsl/gsl_const_cgs.h> #endif #ifdef _PYGSL_GSL_HAS_CGSM #include <gsl/gsl_const_cgsm.h> #endif #ifdef _PYGSL_GSL_HAS_MKS #include <gsl/gsl_const_mks.h> #endif #ifdef _PYGSL_GSL_HAS_MKSA #include <gsl/gsl_const_mksa.h> #endif static PyMethodDef constMethods[] = { {NULL, NULL} /* Sentinel */ }; typedef struct { char* name; double value; char* doc; } constConstants; constConstants m_array[]={ #include "const_m_array.c" {NULL,0,NULL} }; #ifdef _PYGSL_GSL_HAS_MKS constConstants mks_array[]={ #include "const_mks_array.c" {NULL,0,NULL} }; #endif #ifdef _PYGSL_GSL_HAS_CGS constConstants cgs_array[]={ #include "const_cgs_array.c" {NULL,0,NULL} }; #endif #ifdef _PYGSL_GSL_HAS_MKSA constConstants mksa_array[]={ #include "const_mksa_array.c" {NULL,0,NULL} }; #endif #ifdef _PYGSL_GSL_HAS_CGSM constConstants cgsm_array[]={ #include "const_cgsm_array.c" {NULL,0,NULL} }; #endif constConstants num_array[]={ #include "const_num_array.c" {NULL,0,NULL} }; static void add_constants(constConstants* constants, PyObject* m) { int i=0; while (constants[i].name!=NULL) { PyObject* floatObject=PyFloat_FromDouble(constants[i].value); if (floatObject==NULL) break; PyModule_AddObject(m,constants[i].name,floatObject); /* Py_DECREF(floatObject); */ i++; } } DL_EXPORT(void) initconst(void) { PyObject* const_module = Py_InitModule("const", constMethods); #ifdef _PYGSL_GSL_HAS_MKS PyObject* mks_module = PyImport_AddModule("pygsl.const.mks"); #endif #ifdef _PYGSL_GSL_HAS_CGS PyObject* cgs_module = PyImport_AddModule("pygsl.const.cgs"); #endif #ifdef _PYGSL_GSL_HAS_MKSA PyObject* mksa_module = PyImport_AddModule("pygsl.const.mksa"); #endif #ifdef _PYGSL_GSL_HAS_CGSM PyObject* cgsm_module = PyImport_AddModule("pygsl.const.cgsm"); #endif PyObject* math_module = PyImport_AddModule("pygsl.const.m"); PyObject* num_module = PyImport_AddModule("pygsl.const.num"); /* distribute constants on modules */ add_constants(m_array , const_module); add_constants(num_array, const_module); #ifdef _PYGSL_GSL_HAS_MKS add_constants(mks_array, const_module); add_constants(mks_array, mks_module); #endif #ifdef _PYGSL_GSL_HAS_CGS add_constants(cgs_array, cgs_module); #endif #ifdef _PYGSL_GSL_HAS_MKSA add_constants(mksa_array, const_module); add_constants(mksa_array, mksa_module); #endif #ifdef _PYGSL_GSL_HAS_CGSM add_constants(cgsm_array, cgsm_module); #endif add_constants(num_array, num_module); add_constants(m_array , math_module); PyModule_AddObject(const_module, "m", math_module); #ifdef _PYGSL_GSL_HAS_CGS PyModule_AddObject(const_module, "cgs", cgs_module); #endif #ifdef _PYGSL_GSL_HAS_MKS PyModule_AddObject(const_module, "mks", mks_module); #endif #ifdef _PYGSL_GSL_HAS_CGSM PyModule_AddObject(const_module, "cgsm", cgsm_module); #endif #ifdef _PYGSL_GSL_HAS_MKSA PyModule_AddObject(const_module, "mksa", mksa_module); #endif PyModule_AddObject(const_module, "num", num_module); return; }
{ "alphanum_fraction": 0.7479435958, "avg_line_length": 21.275, "ext": "c", "hexsha": "96be4cccd5c63eefcd0db3ad45eba60fc5209bb5", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "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": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/constmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1050, "size": 3404 }
#include <stdio.h> #include <stdlib.h> #include <math.h> //#include "helpers.h" //#include "polifitgsl.h" #include <gsl/gsl_multifit.h> #include <stdbool.h> #define NMAX 20 #define NDIM 3 #define G 19.94 #define RMIN 0.01 #define moddiff(a,b) ((a>b) ? (a-b) : (b-a)) #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) #define TWOPI 6.28318531 #define PI 3.14159265 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #define ROWMINUS1(r) ((r-1)%3 < 0 ? 3+(r-1)%3 : (r-1)%3) // QATS #define PARITY 1 // QATS: Parity of box (down = -1, up = 1) #define TRSZ 133//35 // occultquad fns double rc(double x, double y); double rj(double x, double y, double z, double p); double ellec(double k); double ellk(double k); double rf(double x, double y, double z); double max(double a, double b); double min(double a, double b); double transit_x[TRSZ] = {-1. , -0.99999997, -0.99999975, -0.99999893, -0.99999673, -0.99999187, -0.99998243, -0.99996575, -0.99993828, -0.99989547, -0.99983165, -0.99973989, -0.99961185, -0.9994377 , -0.99920598, -0.99890342, -0.99851485, -0.99802306, -0.99740861, -0.99664973, -0.99572212, -0.9945988 , -0.99324991, -0.99164249, -0.98974027, -0.98750342, -0.98488824, -0.98184684, -0.97832675, -0.97427047, -0.969615 , -0.96429112, -0.95822276, -0.95132602, -0.94350812, -0.93466609, -0.92468507, -0.91343624, -0.90077419, -0.88653352, -0.87052436, -0.85252643, -0.83228096, -0.80947943, -0.78374739, -0.75462061, -0.72150825, -0.68363324, -0.63992968, -0.6 , -0.56470588, -0.52941176, -0.49411765, -0.45882353, -0.42352941, -0.38823529, -0.35294118, -0.31764706, -0.28235294, -0.24705882, -0.21176471, -0.17647059, -0.14117647, -0.10588235, -0.07058824, -0.03529412, 0. , 0.03529412, 0.07058824, 0.10588235, 0.14117647, 0.17647059, 0.21176471, 0.24705882, 0.28235294, 0.31764706, 0.35294118, 0.38823529, 0.42352941, 0.45882353, 0.49411765, 0.52941176, 0.56470588, 0.6 , 0.63992968, 0.68363324, 0.72150825, 0.75462061, 0.78374739, 0.80947943, 0.83228096, 0.85252643, 0.87052436, 0.88653352, 0.90077419, 0.91343624, 0.92468507, 0.93466609, 0.94350812, 0.95132602, 0.95822276, 0.96429112, 0.969615 , 0.97427047, 0.97832675, 0.98184684, 0.98488824, 0.98750342, 0.98974027, 0.99164249, 0.99324991, 0.9945988 , 0.99572212, 0.99664973, 0.99740861, 0.99802306, 0.99851485, 0.99890342, 0.99920598, 0.9994377 , 0.99961185, 0.99973989, 0.99983165, 0.99989547, 0.99993828, 0.99996575, 0.99998243, 0.99999187, 0.99999673, 0.99999893, 0.99999975, 0.99999997, 1. }; double transit_y[TRSZ] = {0.01836735, 0.03673469, 0.05510204, 0.07346939, 0.09183673, 0.11020408, 0.12857143, 0.14693878, 0.16530612, 0.18367347, 0.20204082, 0.22040816, 0.23877551, 0.25714286, 0.2755102 , 0.29387755, 0.3122449 , 0.33061224, 0.34897959, 0.36734694, 0.38571429, 0.40408163, 0.42244898, 0.44081633, 0.45918367, 0.47755102, 0.49591837, 0.51428571, 0.53265306, 0.55102041, 0.56938776, 0.5877551 , 0.60612245, 0.6244898 , 0.64285714, 0.66122449, 0.67959184, 0.69795918, 0.71632653, 0.73469388, 0.75306122, 0.77142857, 0.78979592, 0.80816327, 0.82653061, 0.84489796, 0.86326531, 0.88163265, 0.9 , 0.9146101 , 0.92606848, 0.93633897, 0.94555515, 0.95382419, 0.96123311, 0.96785322, 0.97374342, 0.97895253, 0.98352113, 0.98748293, 0.99086579, 0.99369256, 0.99598168, 0.99774766, 0.99900147, 0.99975074, 1. , 0.99975074, 0.99900147, 0.99774766, 0.99598168, 0.99369256, 0.99086579, 0.98748293, 0.98352113, 0.97895253, 0.97374342, 0.96785322, 0.96123311, 0.95382419, 0.94555515, 0.93633897, 0.92606848, 0.9146101 , 0.9 , 0.88163265, 0.86326531, 0.84489796, 0.82653061, 0.80816327, 0.78979592, 0.77142857, 0.75306122, 0.73469388, 0.71632653, 0.69795918, 0.67959184, 0.66122449, 0.64285714, 0.6244898 , 0.60612245, 0.5877551 , 0.56938776, 0.55102041, 0.53265306, 0.51428571, 0.49591837, 0.47755102, 0.45918367, 0.44081633, 0.42244898, 0.40408163, 0.38571429, 0.36734694, 0.34897959, 0.33061224, 0.3122449 , 0.29387755, 0.2755102 , 0.25714286, 0.23877551, 0.22040816, 0.20204082, 0.18367347, 0.16530612, 0.14693878, 0.12857143, 0.11020408, 0.09183673, 0.07346939, 0.05510204, 0.03673469, 0.01836735}; /* ================================================== */ /* =============== occultquad algs ================== */ /* ============= Mandel & Agol 2002 =============== */ /* ================================================== */ int occultquad(double *mu0, double *muo1, double *z0, double u1, double u2, double p, int nz) { /* Input: ************************************* z0 impact parameter in units of rs u1 linear limb-darkening coefficient (gamma_1 in paper) u2 quadratic limb-darkening coefficient (gamma_2 in paper) p occulting star size in units of rs nz number of points in the light curve (# elements in z0) Output: *********************************** default: muo1, fraction of flux at each z0 for a limb-darkened source optional: mu0, fraction of flux at each z0 for a uniform source Limb darkening has the form: I(r)=[1-u1*(1-sqrt(1-(r/rs)^2))-u2*(1-sqrt(1-(r/rs)^2))^2]/(1-u1/3-u2/6)/pi */ int i; double *lambdad, *etad, *lambdae, pi, x1, x2, x3, z, omega, kap0 = 0.0, kap1 = 0.0, \ q, Kk=0., Ek=0., Pk=0., n;//, tol = 1e-8; lambdad = (double *)malloc(nz*sizeof(double)); lambdae = (double *)malloc(nz*sizeof(double)); etad = (double *)malloc(nz*sizeof(double)); if(fabs(p - 0.5) < 1.0e-4) p = 0.5; omega=1.0-u1/3.0-u2/6.0; pi=acos(-1.0); // trivial case of no planet if(p<=0.) {for(i=0;i<nz;i++) {muo1[i]=1.; mu0[i]=1.;}} for(i = 0; i < nz; i++) { z = z0[i]; // if(fabs(p - z) < tol) z = p; // if(fabs((p-1.)-z) < tol) z = p-1.; // if(fabs((1.-p)-z) < tol) z = 1.-p; // if(z < tol) z = 0.; x1 = pow((p - z), 2.0); x2 = pow((p + z), 2.0); x3 = p*p - z*z; //source is unocculted: if(z >= 1.0 + p) { //printf("zone 1\n"); lambdad[i] = 0.0; etad[i] = 0.0; lambdae[i] = 0.0; muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3. * (p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0 - lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone1: %+.3e %+.3e %+.3e %+.3e %+.4e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i]); } continue; } //source is completely occulted: if(p >= 1.0 && z <= p - 1.0) { //printf("zone 2\n"); lambdad[i] = 0.0; //from Errata etad[i] = 0.5; //error in Fortran code corrected here, following Eastman's python code lambdae[i] = 1.0; muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3. * (p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone2: %+.3e %+.3e %+.3e %+.3e %+.4e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i]); } continue; } //source is partly occulted and occulting object crosses the limb: if(z >= fabs(1.0 - p) && z <= 1.0 + p) { //printf("zone 3\n"); kap1 = acos(min((1.0-p*p+z*z)/2.0/z,1.0)); kap0 = acos(min((p*p+z*z-1.0)/2.0/p/z,1.0)); lambdae[i] = p*p*kap0+kap1; lambdae[i] = (lambdae[i] - 0.50*sqrt(max(4.0*z*z-pow((1.0+z*z-p*p), 2.0),0.0)))/pi; //etad[i] = 0.5/pi * (kap1 + p*p * (p*p + 2.*z*z) * kap0 - 1. + 5.*p*p + z*z)/4. * sqrt((1.-x1)*(x2-1.))); //added from Eastman's code etad[i] = 0.5; lambdad[i] = 0.0; } //occulting object transits the source but doesn't completely cover it: if(z <= 1.0 - p) { //printf("zone 4\n"); lambdae[i] = p*p; } //edge of the occulting star lies at the origin if(fabs(z-p) < 1e-4*(z+p)) { //printf("zone 5\n"); if(p == 0.5) { //printf("zone 6\n"); lambdad[i] = 1.0/3.0-4.0/pi/9.0; etad[i] = 3.0/32.0; muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3. * (p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone6: %+.3e %+.3e %+.3e %+.3e %+.4e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i]); } continue; } if(z >= 0.5) { //printf("zone 5.1\n"); q = 0.5/p; Kk = ellk(q); Ek = ellec(q); // lambda3, eta1 in MA02; subtract 2/3 HSF(p-z)?! verify this. lambdad[i] = 1.0/3.0+16.0*p/9.0/pi*(2.0*p*p-1.0)*Ek- \ (32.0*pow(p, 4.0)-20.0*p*p+3.0)/9.0/pi/p*Kk - 2./3.*(p>z); etad[i] = 0.5/pi*(kap1+p*p*(p*p+2.0*z*z)*kap0 - \ (1.0+5.0*p*p+z*z)/4.0*sqrt((1.0-x1)*(x2-1.0))); //printf("zone 5.1: %+.3e +%.3e +%.3e +%.3e +%.3e +%.3e\n", z, Kk, Ek, lambdad[i], etad[i], muo1[i]); //continue; } if(z<0.5) { //printf("zone 5.2\n"); q = 2.0*p; Kk = ellk(q); Ek = ellec(q); //lambda4, eta2 in MA02; NO HSF(p-z)... lambdad[i] = 1.0/3.0+2.0/9.0/pi*(4.0*(2.0*p*p-1.0)*Ek + (1.0-4.0*p*p)*Kk); etad[i] = p*p/2.0*(p*p+2.0*z*z); muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i]) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone5.2: %+.3e %+.3e %+.3e %+.3e %+.4e %+.3e %+.3e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i], Kk, Ek); } continue; } muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3. * (p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone3,4,5,5.1: %+.3e %+.3e %+.3e %+.3e %+.4e %+.3e %+.3e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i], Kk, Ek); } //printf("zone 5.1: %+.3e +%.3e +%.3e +%.3e +%.3e +%.3e\n", z, Kk, Ek, lambdad[i], etad[i], muo1[i]); continue; } //occulting star partly occults the source and crosses the limb: if((z > 0.5 + fabs(p - 0.5) && z < 1.0 + p) || (p > 0.5 \ && z >= fabs(1.0-p) && z < p)) { //printf("zone 3.1\n"); q = sqrt((1.0-pow((p-z), 2.0))/4.0/z/p); Kk = ellk(q); Ek = ellec(q); n = 1.0/x1-1.0; Pk = Kk-n/3.0*rj(0.0,1.0-q*q,1.0,1.0+n); lambdad[i] = 1.0/9.0/pi/sqrt(p*z)*(((1.0-x2)*(2.0*x2+ \ x1-3.0)-3.0*x3*(x2-2.0))*Kk+4.0*p*z*(z*z+ \ 7.0*p*p-4.0)*Ek-3.0*x3/x1*Pk); etad[i] = 1.0/2.0/pi*(kap1+p*p*(p*p+2.0*z*z)*kap0- \ (1.0+5.0*p*p+z*z)/4.0*sqrt((1.0-x1)*(x2-1.0))); muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3.*(p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; //printf("z, Kk, Ek, Pk, lambdad, etad, muo1: %+.3e %+.3e %+.3e %+.3e %+.3e %+.3e %+.3e\n", z, Kk, Ek, Pk, lambdad[i], etad[i], muo1[i]); if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone3.1: %+.3e %+.3e %+.3e %+.3e %+.4e %+.3e %+.3e %+.3e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i], Kk, Ek, Pk); } continue; } //occulting star transits the source: if(p <= 1.0 && z <= (1.0 - p)*1.0001) { //printf("zone 4.1\n"); q = sqrt((x2-x1)/(1.0-x1)); Kk = ellk(q); Ek = ellec(q); n = x2/x1-1.0; Pk = Kk-n/3.0*rj(0.0,1.0-q*q,1.0,1.0+n); lambdad[i] = 2.0/9.0/pi/sqrt(1.0-x1)*((1.0-5.0*z*z+p*p+ \ x3*x3)*Kk+(1.0-x1)*(z*z+7.0*p*p-4.0)*Ek-3.0*x3/x1*Pk); if(fabs(p+z-1.0) <= 1.0e-4) { // need the 2/3 HEAVISIDE STEP FUNCTION (p-1/2) lambda5 in MA02 lambdad[i] = 2.0/3.0/pi*acos(1.0-2.0*p)-4.0/9.0/pi* \ sqrt(p*(1.0-p))*(3.0+2.0*p-8.0*p*p) - 2./3.*(p>0.5); } etad[i] = p*p/2.0*(p*p+2.0*z*z); } muo1[i] = 1.0 - ((1.0 - u1 - 2.0 * u2) * lambdae[i] + \ (u1 + 2.0 * u2) * (lambdad[i] + 2./3. * (p > z)) + \ u2 * etad[i])/omega; mu0[i] = 1.0-lambdae[i]; if((muo1[i]-1. > 1e-4) || muo1[i]<-1e-4) { printf("zone4.1: %+.3e %+.3e %+.3e %+.3e %+.4e %+.3e %+.3e %+.3e\n", z, lambdae[i], lambdad[i], etad[i], muo1[i], Kk, Ek, Pk); } } free(lambdae); free(lambdad); free(etad); //free(mu); return 0; } double min(double a, double b) { if(a < b) return a; else return b; } double max(double a, double b) { if(a > b) return a; else return b; } double rc(double x, double y) { double rc, ERRTOL,TINY,SQRTNY,BIG,TNBG,COMP1,COMP2,THIRD,C1,C2, C3,C4; ERRTOL=0.04; TINY=1.69e-38; SQRTNY=1.3e-19; BIG=3.0e37; TNBG=TINY*BIG; COMP1=2.236/SQRTNY; COMP2=TNBG*TNBG/25.0; THIRD=1.0/3.0; C1=0.3; C2=1.0/7.0; C3=0.375; C4=9.0/22.0; double alamb,ave,s,w,xt,yt; if(x < 0.0 || y == 0.0 || (x+fabs(y)) < TINY || (x+fabs(y)) > BIG || (y < -COMP1 && x > 0 && x < COMP2)){ printf("Invalid argument(s) in rc\n"); return 0; } if(y > 0.0) { xt=x; yt=y; w=1.0; } else { xt=x-y; yt=-y; w=sqrt(x)/sqrt(xt); } s = ERRTOL*10.0; while(fabs(s) > ERRTOL) { alamb = 2.0*sqrt(xt)*sqrt(yt)+yt; xt = 0.25*(xt+alamb); yt =0.25*(yt+alamb); ave = THIRD*(xt+yt+yt); s = (yt-ave)/ave; } rc = w*(1.0+s*s*(C1+s*(C2+s*(C3+s*C4))))/sqrt(ave); return rc; } double rj(double x, double y, double z, double p) { double rj, ERRTOL,TINY,BIG,C1,C2,C3,C4,C5,C6,C7,C8, tempmax; ERRTOL=0.05; TINY=2.5e-13; BIG=9.0e11; C1=3.0/14.0; C2=1.0/3.0; C3=3.0/22.0; C4=3.0/26.0; C5=.750*C3; C6=1.50*C4; C7=.50*C2; C8=C3+C3; double a = 0.0,alamb,alpha,ave,b = 0.0,beta,delp,delx,dely,delz,ea,eb,ec,ed,ee, \ fac,pt,rcx = 0.0,rho,sqrtx,sqrty,sqrtz,sum,tau,xt,yt,zt; if(x < 0.0 || y < 0.0 || z < 0.0 || (x+y) < TINY || (x+z) < TINY || (y+z) < TINY || fabs(p) < TINY \ || x > BIG || y > BIG || z > BIG || fabs(p) > BIG) { return 0; } sum=0.0; fac=1.0; if(p > 0.0) { xt=x; yt=y; zt=z; pt=p; } else { xt = min(x, y); xt = min(xt,z); zt = max(x, y); zt = max(zt, z); yt = x+y+z-xt-zt; a = 1.0/(yt-p); b = a*(zt-yt)*(yt-xt); pt = yt+b; rho = xt*zt/yt; tau = p*pt/yt; rcx = rc(rho,tau); } tempmax = ERRTOL*10.0; while(tempmax > ERRTOL) { sqrtx = sqrt(xt); sqrty = sqrt(yt); sqrtz = sqrt(zt); alamb = sqrtx*(sqrty+sqrtz)+sqrty*sqrtz; alpha = pow((pt*(sqrtx+sqrty+sqrtz)+sqrtx*sqrty*sqrtz), 2.0); beta = pt*(pt+alamb)*(pt + alamb); sum = sum+fac*rc(alpha,beta); fac = 0.25*fac; xt = 0.25*(xt+alamb); yt = 0.25*(yt+alamb); zt = 0.250*(zt+alamb); pt = 0.25*(pt+alamb); ave = 0.2*(xt+yt+zt+pt+pt); delx = (ave-xt)/ave; dely = (ave-yt)/ave; delz = (ave-zt)/ave; delp = (ave-pt)/ave; tempmax = max(fabs(delx), fabs(dely)); tempmax = max(tempmax, fabs(delz)); tempmax = max(tempmax, fabs(delp)); } ea = delx*(dely+delz)+dely*delz; eb = delx*dely*delz; ec = delp*delp; ed = ea-3.0*ec; ee = eb+2.0*delp*(ea-ec); rj = 3.0*sum+fac*(1.0+ed*(-C1+C5*ed-C6*ee)+eb*(C7+delp*(-C8+delp*C4)) +\ delp*ea*(C2-delp*C3)-C2*delp*ec)/(ave*sqrt(ave)); if(p < 0.0) rj=a*(b*rj+3.0*(rcx-rf(xt,yt,zt))); return rj; } double ellec(double k) { double m1,a1,a2,a3,a4,b1,b2,b3,b4,ee1,ee2,ellec; // Computes polynomial approximation for the complete elliptic // integral of the second kind (Hasting's approximation): m1=1.0-k*k; a1=0.44325141463; a2=0.06260601220; a3=0.04757383546; a4=0.01736506451; b1=0.24998368310; b2=0.09200180037; b3=0.04069697526; b4=0.00526449639; ee1=1.0+m1*(a1+m1*(a2+m1*(a3+m1*a4))); ee2=m1*(b1+m1*(b2+m1*(b3+m1*b4)))*log(1.0/m1); ellec=ee1+ee2; /* double rd(double x, double y, double z); double rf(double x, double y, double z); double q; q=(1.0-k)*(1.0+k); ellec=rf(0, q, 1.0)-sqrt(k)*rd(0, q, 1.0)/3.0; */ return ellec; } double ellk(double k) { double a0,a1,a2,a3,a4,b0,b1,b2,b3,b4,ellk, ek1,ek2,m1; // Computes polynomial approximation for the complete elliptic // integral of the first kind (Hasting's approximation): m1=1.0-k*k; a0=1.38629436112; a1=0.09666344259; a2=0.03590092383; a3=0.03742563713; a4=0.01451196212; b0=0.5; b1=0.12498593597; b2=0.06880248576; b3=0.03328355346; b4=0.00441787012; ek1=a0+m1*(a1+m1*(a2+m1*(a3+m1*a4))); ek2=(b0+m1*(b1+m1*(b2+m1*(b3+m1*b4))))*log(m1); ellk=ek1-ek2; /* double rf(double x, double y, double z); ellk=rf(0, (1.0-k)*(1.0+k), 1.0); */ return ellk; } double rf(double x, double y, double z) { double rf, ERRTOL,TINY,BIG,THIRD,C1,C2,C3,C4, tempmax; ERRTOL=0.08; TINY=1.5e-38; BIG=3.0e37; THIRD=1.0/3.0; C1=1.0/24.0; C2=0.1; C3=3.0/44.0; C4=1.0/14.0; double alamb,ave,delx,dely,delz,e2,e3,sqrtx,sqrty,sqrtz,xt,yt,zt; if(min(x,y) < 0.0 || z < 0.0 || min(x+y, x+z) < TINY || y+z < TINY || max(x,y) > BIG || z > BIG) { printf("Invalid argument(s) in rf\n"); return 0; } xt=x; yt=y; zt=z; tempmax = ERRTOL*10.0; while(tempmax > ERRTOL) { sqrtx=sqrt(xt); sqrty=sqrt(yt); sqrtz=sqrt(zt); alamb=sqrtx*(sqrty+sqrtz)+sqrty*sqrtz; xt=0.25*(xt+alamb); yt=0.25*(yt+alamb); zt=0.25*(zt+alamb); ave=THIRD*(xt+yt+zt); delx=(ave-xt)/ave; dely=(ave-yt)/ave; delz=(ave-zt)/ave; tempmax = max(fabs(delx), fabs(dely)); tempmax = max(tempmax, fabs(delz)); } e2=delx*dely-delz*delz; e3=delx*dely*delz; rf=(1.0+(C1*e2-C2-C3*e3)*e2+C4*e3)/sqrt(ave); return rf; } /* ================================================== */ /* =============== QATS algorithms ================== */ /* ============= Carter & Agol 2012 =============== */ /* ================================================== */ int test(int a, int b, int *c) { if (a < b) {*c=a;} else if (a > b) {*c=b;} return 0; } void shConvol(double *y, int N, int q, double *d) { // Box convolution (computes D in eqn 15. // Assumed d has size d[N-q+1] and y has size y[N] int n, j; for (n=0; n<=N-q; n++) { d[n] = 0; for (j=0; j<q; j++) { d[n] += PARITY*y[j+n]; } } } double maximum(double *v, int lb, int rb, int *index) { // Maximum of vector v btw. indices lb and rb. Index of maximum is index. double m = v[lb]; int i; *index = lb; for (i=lb; i<=rb; i++) { if (v[i] > m) { m = v[i]; *index = i; } } return m; } void omegaBounds(int m, int M, int DeltaMin, int DeltaMax, int N, int q, int *lb, int *rb) { // Returns bounds for omega set as listed in paper (eqns 16-18) *lb = ((m-1)*DeltaMin > N-DeltaMax-(M-m)*DeltaMax ? (m-1)*DeltaMin : N-DeltaMax-(M-m)*DeltaMax); *rb = (DeltaMax-q+(m-1)*DeltaMax < N-q-(M-m)*DeltaMin ? DeltaMax-q+(m-1)*DeltaMax : N-q-(M-m)*DeltaMin); } void gammaBounds(int m, int n, int DeltaMin, int DeltaMax, int q, int *lb, int *rb) { // Returns bounds for gamma set as listed in paper (eqns 19-21) *lb = ((m-1)*DeltaMin > n-DeltaMax ? (m-1)*DeltaMin : n-DeltaMax); *rb = (DeltaMax-q+(m-1)*DeltaMax < n-DeltaMin ? DeltaMax-q+(m-1)*DeltaMax : n-DeltaMin); } void computeSmnRow(double *d, int M, int m, int DeltaMin, int DeltaMax, int N, int q, double **Smn) { // Recursive generation of Smn (eqns 22, 23) called by computeSmn int omegaLb, omegaRb, gammaLb, gammaRb, index, n; if (m !=1 ) {computeSmnRow(d, M, m-1, DeltaMin, DeltaMax, N, q, Smn);} omegaBounds(m, M, DeltaMin, DeltaMax, N, q, &omegaLb, &omegaRb); for (n=omegaLb; n <= omegaRb; n++) { if (m==1) { Smn[m-1][n] = d[n]; } else { gammaBounds(m-1, n, DeltaMin, DeltaMax, q, &gammaLb, &gammaRb); Smn[m-1][n] = d[n]+maximum(Smn[m-2], gammaLb, gammaRb, &index); } } } void computeSmn(double *d, int M, int DeltaMin, int DeltaMax, int N, int q, double **Smn, double *Sbest) { // Assumed Smn has been allocated as M X N-q+1, d is data, others are from paper (eqns 22, 23). // Sbest holds merit for this set of parameters. Memory Intensive; refer to computeSmnInPlace. int omegaLb, omegaRb, index; computeSmnRow(d, M, M, DeltaMin, DeltaMax, N, q, Smn); omegaBounds(M, M, DeltaMin, DeltaMax, N, q, &omegaLb, &omegaRb); *Sbest = maximum(Smn[M-1], omegaLb, omegaRb, &index) / sqrt(((double)M) * q); } void computeSmnInPlace(double *d, int M, int DeltaMin, int DeltaMax, int N, int q, double **Smn, double *Sbest) { // Assumed Smn has been allocated as 3 x N-q+1. Use this algorithm to compute 'Sbest' from Smn // (eqns 22, 23) when returned indices are not important. This computation should be used to // produce the "spectrum." Much less memory intensive than computing Smn in full. int omegaLb, omegaRb, gammaLb, gammaRb, index, m, n; int r = 1; for (m=1; m <= M; m++) { omegaBounds(m, M, DeltaMin, DeltaMax, N, q, &omegaLb, &omegaRb); if (m != 1) { for (n=omegaLb; n<=omegaRb; n++) { gammaBounds(m-1, n, DeltaMin, DeltaMax, q, &gammaLb, &gammaRb); Smn[r][n] = d[n] + maximum(Smn[ROWMINUS1(r)], gammaLb, gammaRb, &index); } } else { for (n=omegaLb; n<=omegaRb; n++) { Smn[r][n] = d[n] ; } } r = (r+1) % 3; } omegaBounds(M, M, DeltaMin, DeltaMax, N, q, &omegaLb, &omegaRb); *Sbest = maximum(Smn[ROWMINUS1(r)], omegaLb, omegaRb, &index) / sqrt(((double)M) * q); } void optIndices(int M, int DeltaMin, int DeltaMax, int N, int q, double **Smn, int *indices) { // Optimal starting indices for M, DeltaMin, DeltaMax, q (according to eqns. 25, 26). // Given Smn (Eqns. 22,23) // Assumed indices has been allocated as having M values. Called by qats_indices. int omegaLb, omegaRb, gammaLb, gammaRb, index, m; omegaBounds(M, M, DeltaMin, DeltaMax, N, q, &omegaLb, &omegaRb); maximum(Smn[M-1], omegaLb, omegaRb, &index); indices[M-1] = index; for (m=M-1; m>=1; m--) { gammaBounds(m, indices[m], DeltaMin, DeltaMax, q, &gammaLb, &gammaRb); maximum(Smn[m-1], gammaLb, gammaRb, &index); indices[m-1] = index; } } void qats(double *d, int DeltaMin, int DeltaMax, int N, int q, double *Sbest, int *Mbest) { // Determine highest likelihood for this set of input parameters // (Algorithm 1, for a single value of q). Start indices are not returned. // Useful for calculating the QATS "spectrum." // Assumed d is pre-convolved data (D in Eqn. 15 -- see shConvol above) int MMin = floor((N+q-1.0)/DeltaMax); int MMax = floor((N-q-0.0)/DeltaMin) + 1; double c_Sbest; int M, i; *Sbest = -100000000.; for (M=MMin; M <= MMax; M++) { double **Smn = malloc(3 * sizeof(*Smn)); for (i=0;i<3;i++) { Smn[i] = malloc((N-q+1) * sizeof(*(Smn[i]))); } computeSmnInPlace(d, M, DeltaMin, DeltaMax, N, q, Smn, &c_Sbest); if (c_Sbest > *Sbest) { *Sbest = c_Sbest; *Mbest = M; } //else{ // printf("c_Sbest<=Sbest %d %12.6f %12.6f\n", M, c_Sbest, Sbest); //} for (i=0;i<3;i++) { free(Smn[i]); } free(Smn); } } void qats_indices(double *d, int M, int DeltaMin, int DeltaMax, int N, int q, double *Sbest, int *indices) { // For a specific collection of M, DeltaMin, DeltaMax, and q find the optimal starting indices of transit. // Use after finding the most likely parameters with detectMqNoTimes or even wider search on DeltaMin, DeltaMax or q. double **Smn = malloc(M * sizeof(*Smn)); int i; for (i = 0; i < M; i++) { Smn[i] = malloc((N-q+1) * sizeof(*(Smn[i]))); } computeSmn(d, M, DeltaMin, DeltaMax, N, q, Smn, Sbest); optIndices(M, DeltaMin, DeltaMax, N, q, Smn, indices); for (i = 0; i < M; i++) { free(Smn[i]); } free(Smn); } int get_qats_indices(int M, int DeltaMin, int DeltaMax, int q, int N, double *y, int *indices, double *Sbest) { //since q=1, no need for convolution //double *d = malloc(N*sizeof(double)); //shConvol(y, N, q, d); qats_indices(y, M, DeltaMin, DeltaMax, N, q, Sbest, indices); //free(d); return 0; } int get_qats_likelihood(int DeltaMin, int DeltaMax, int q, int N, double *y, double *Sbest, int *Mbest){ //since q=1, no need for convolution //double *d = malloc(N*sizeof(double)); //shConvol(y, N, q, d); // Calculate D_n qats(y, DeltaMin, DeltaMax, N, q, Sbest, Mbest); //free(d); return 0; } /* =========================================================== */ /* =============== polynomial, transit fits ================== */ /* =========================================================== */ double poly_eval(double *coeffs, int Ncoeffs, double x) { // Evaluates polynomial given coefficients, Ncoeff = degree + 1, and data array x int i; double ans = 0.0; /* if (Ncoeffs<1) { printf("Ncoeffs = %in", Ncoeffs); } */ for (i=0; i<Ncoeffs; i++) { ans = ans + coeffs[i]*pow(x, i); } return ans; } int binarysearch(double *A, double key, long ilo, long ihi, long sz) { if (ihi < ilo) { if (ilo > sz) { return sz; } return ilo; } long imid = (ilo + ihi) / 2; if (A[imid] > key) { return binarysearch(A, key, ilo, imid-1, sz); } else if (A[imid] < key) { return binarysearch(A, key, imid+1, ihi, sz); } else { return imid; } } double interp1d(double x0, double x1, double y0, double y1, double xnew) { int i; double ynew; ynew = y0*(1. - (xnew-x0)/(x1-x0)) + y1*(xnew - x0)/(x1-x0); return ynew; } int resample_time(double *t, double *x, double *tbary, double *xshift, long sz) { /* resample time from t to t-tbary, assuming delchisq at transits are PEAKS */ long i, j, i_lo, i_hi, Npts; double t_lo, t_hi, xnew, temp; for (i = 0; i < sz-1; i++){ t_lo = t[i] - tbary[i]; t_hi = t[i+1] - tbary[i+1]; if (t_lo>t_hi) { temp = t_lo; t_lo = t_hi; t_hi = temp; } i_lo = binarysearch(t, t_lo, 0, sz, sz); i_hi = binarysearch(t, t_hi, 0, sz, sz); /* printf("tlo,t_hi,i_lo,i_hi = %12.6f, %12.6f, %i, %i\n", t_lo, t_hi, i_lo, i_hi); */ Npts = i_hi-i_lo; if (Npts>0) { for (j = 0; j < Npts; j++) { xnew = interp1d(t_lo, t_hi, x[i], x[i+1], t[i_lo+j]); // change >= to <= if delchisq at transits are DIPS if (xnew>=xshift[i_lo+j]) { xshift[i_lo+j] = xnew; /*printf("%li, %li, %12.6f, %12.6f, %12.6f\n", i, i_lo+j, t[i_lo+j], xnew, xshift[i_lo+j]);*/ } } } } return 0; } bool polynomialfit_w(int obs, int degree, double *dx, double *dy, double *derr, double *store) /* n, p */ { /* if (obs<1) {printf("Nobs = %i; ", obs);} if (degree<1) {printf("degree = %i\n", degree);} */ gsl_multifit_linear_workspace *ws; gsl_matrix *cov, *X; gsl_vector *y, *w, *c; double chisq; int i, j; X = gsl_matrix_alloc(obs, degree); y = gsl_vector_alloc(obs); w = gsl_vector_alloc(obs); c = gsl_vector_alloc(degree); cov = gsl_matrix_alloc(degree, degree); for(i=0; i < obs; i++) { for(j=0; j < degree; j++) { gsl_matrix_set(X, i, j, pow(dx[i], j)); } gsl_vector_set(y, i, dy[i]); gsl_vector_set(w, i, 1.0/(derr[i]*derr[i])); } ws = gsl_multifit_linear_alloc(obs, degree); gsl_multifit_wlinear(X, w, y, c, cov, &chisq, ws); /* store result ... */ for(i=0; i < degree; i++) { store[i] = gsl_vector_get(c, i); } gsl_multifit_linear_free(ws); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(w); gsl_vector_free(c); return true; /* we do not "analyse" the result (cov matrix mainly) to know if the fit is "good" */ } bool polynomialfit(int obs, int degree, double *dx, double *dy, double *store) /* n, p */ { gsl_multifit_linear_workspace *ws; gsl_matrix *cov, *X; gsl_vector *y, *c; double chisq; int i, j; X = gsl_matrix_alloc(obs, degree); y = gsl_vector_alloc(obs); c = gsl_vector_alloc(degree); cov = gsl_matrix_alloc(degree, degree); for(i=0; i < obs; i++) { for(j=0; j < degree; j++) { gsl_matrix_set(X, i, j, pow(dx[i], j)); } gsl_vector_set(y, i, dy[i]); } ws = gsl_multifit_linear_alloc(obs, degree); gsl_multifit_linear(X, y, c, cov, &chisq, ws); /* store result ... */ for(i=0; i < degree; i++) { store[i] = gsl_vector_get(c, i); } gsl_multifit_linear_free(ws); gsl_matrix_free(X); gsl_matrix_free(cov); gsl_vector_free(y); gsl_vector_free(c); return true; /* we do not "analyse" the result (cov matrix mainly) to know if the fit is "good" */ } double mean(double *x, unsigned long sz) { double meanval = 0.0; unsigned long i; for (i=0;i<sz;i++) { meanval = meanval + x[i]; } meanval = meanval / (double)sz; return meanval; } /* sorts the input array in place... void quick_sort(int *a, int n) { int i, j, p, t; if (n < 2) return; p = a[n / 2]; for (i = 0, j = n - 1;; i++, j--) { while (a[i] < p) i++; while (p < a[j]) j--; if (i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } quick_sort(a, i); quick_sort(a + i, n - i); } */ double utransit(double *x, double *y, double xnew) { double *coeffs; double ynew; coeffs = malloc(3*sizeof(double)); polynomialfit(3, 3, x, y, coeffs); ynew = poly_eval(coeffs, 3, xnew); free(coeffs); return ynew; } /* computing delta chi-square (chi_polyonly - chi_poly*tran) NO transit masking int dchi_fn(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { long lw, mt, rw; int i, j, k, ii, npts; double *tt, *ff, *eff, *fmod, *efmod, *coeff_tran, *coeff_notran; double chisq_notran, chisq_tran, tmp_notran, tmp_tran, tmean; double *u_x, *u_y; u_x = malloc(3*sizeof(double)); u_y = malloc(3*sizeof(double)); u_y[0] = 1.0; u_y[2] = 1.0; for (i=0; i < ndep; i++) { u_y[1] = 1.0 - depth[i]; for (j=0; j < ndur; j++) { npts = duration[j]+2*cwidth[j]; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); coeff_tran = malloc((porder[j]+1)*sizeof(double)); coeff_notran = malloc((porder[j]+1)*sizeof(double)); for (k=0; k < njumps-1; k++) { //lt = jumps[k]+MIN(10, cwidth[j]); //lw = lt - cwidth[j]; //rt = lt + duration[j] - 1; //mt = lt + duration[j]/2; //rw = rt + cwidth[j]; lw = jumps[k]; mt = jumps[k] + cwidth[j] + duration[j]/2; rw = jumps[k] + 2*cwidth[j] + duration[j] - 1; //printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw); while (rw < jumps[k+1]) { //while (rt < jumps[k+1]-MIN(10, cwidth[j])-1) { chisq_notran=0; chisq_tran=0; lw = MAX(lw, jumps[k]); rw = MIN(rw, jumps[k+1]-1); npts = rw-lw+1; for (ii=0; ii < npts; ii++) { tt[ii] = t[lw+ii]; ff[ii] = f[lw+ii]; eff[ii] = ef[lw+ii]; //fmod[ii] = f[lw+ii]; //efmod[ii] = ef[lw+ii]; //if (cwidth[j]+1 <= ii && ii<=duration[j]+cwidth[j]-2) { //fmod[ii] = fmod[ii] / (1.-depth[i]); //efmod[ii] = ef[lw+ii] / (1.-depth[i]); //} } tmean = mean(tt, npts); for (ii=0; ii<npts;ii++) { tt[ii] = tt[ii] - tmean; } u_x[0]=tt[cwidth[j]]; u_x[1]=tt[cwidth[j]+duration[j]/2]; u_x[2]=tt[duration[j]+cwidth[j]-1]; for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { fmod[ii] = utransit(u_x, u_y, tt[ii]); } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } //if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { printf("\n"); } polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeff_notran); polynomialfit_w(npts, porder[j]+1, tt, fmod, efmod, coeff_tran); //for (ii=0;ii<porder[j]+1; ii++) { //printf("%.8e ", coeff_notran[ii]); //} //printf("\n"); for (ii=0; ii < npts; ii++) { //printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii])); tmp_notran = (poly_eval(coeff_notran, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeff_tran, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; //if (ii % 6==0) {printf("\n");} } dchi[i*ndur*Ntot + j*Ntot + mt] = chisq_notran-chisq_tran; //lt+=1; //lw=lt-cwidth[j]; //mt+=1; //rt+=1; //rw=rt+cwidth[j]; lw=lw+1; mt=mt+1; rw=rw+1; } //printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw); } free(tt); free(ff); free(eff); free(fmod); free(efmod); } } return 0; } */ int dchiChoosePC(double *dchi, double *t, int *rinds, double *f, double *ef, double depth, int *duration, int ndur, int Nrinds, int porder, int cwidth) { int ii, jj, j, k, npts, i_lo, lw, mt; double *tt, *ff, *eff, *fmod, *efmod, *coeffs, *ttt, *fff, *efff; double chisq_notran, chisq_tran, t_tmp, tmp_notran, tmp_tran, tmean; coeffs = malloc((porder+1)*sizeof(double)); printf("ok here we go\n"); printf("%d, %d, %d = \n", Nrinds, porder, cwidth); for (j=0;j<ndur;j++) { npts = duration[j] + 2*cwidth; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); ttt = malloc((npts-duration[j])*sizeof(double)); fff = malloc((npts-duration[j])*sizeof(double)); efff = malloc((npts-duration[j])*sizeof(double)); printf("j=%d\n", j); for (k=0;k<Nrinds;k++) { mt = rinds[k]; lw = rinds[k] - cwidth - duration[j]/2; //rw = rinds[k] + cwidth + duration[j]/2 - 1; chisq_notran=0; chisq_tran=0; for (ii=0;ii<npts;ii++) { tt[ii] = t[lw+ii]; ff[ii] = f[lw+ii]; eff[ii] = ef[lw+ii]; } tmean = mean(tt, npts); for (ii=0; ii<npts;ii++) { tt[ii] = tt[ii] - tmean; } for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (cwidth <= ii && ii <=duration[j]+cwidth-1) { t_tmp = tt[ii]/tt[cwidth]; if (t_tmp <= transit_x[0] | t_tmp >= transit_x[TRSZ-1]) { fmod[ii] = 1.0; } else { i_lo = binarysearch(transit_x, t_tmp, 0, TRSZ, TRSZ); fmod[ii] = 1. - depth * interp1d(transit_x[i_lo], transit_x[i_lo+1], transit_y[i_lo], transit_y[i_lo+1], t_tmp); //pow((1.-(tt[ii]*tt[ii])/(tt[cwidth[j]]*tt[cwidth[j]])), 0.2);//utransit(u_x, u_y, tt[ii]); } } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } jj=0; for (ii=0; ii<npts;ii++) { if (cwidth <= ii && ii <=duration[j]+cwidth-1) { } else { ttt[jj] = tt[ii]; fff[jj] = ff[ii]; efff[jj] = eff[ii]; jj+=1; } } polynomialfit_w(npts-duration[j], porder+1, ttt, fff, efff, coeffs); for (ii=0; ii < npts; ii++) { /*printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii]));*/ tmp_notran = (poly_eval(coeffs, porder+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeffs, porder+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; /*if (ii % 6==0) { printf("\n"); }*/ } dchi[j*Nrinds + k] = chisq_notran - chisq_tran; } printf("got to here"); free(tt); free(ff); free(eff); free(fmod); free(efmod); free(ttt); free(fff); free(efff); } printf("before free(coeffs); "); free(coeffs); printf("after free(coeffs)"); return 0; } // dchi computation (chi_polyonly - chi_poly*tran) with transits NOT MASKED in polyfitting // testing single cwidth sides int dchi_fn(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { long lw, mt, rw, lt, rt; int i, j, k, ii, npts, jj, i_lo, i_hi; double *tt, *ff, *eff, *fmod, *efmod, *coeffs_tran, *coeffs_notran;//, *ttt, *fff, *efff; double chisq_notran, chisq_tran, tmp_notran, tmp_tran, tmean, t_tmp; for (i=0; i < ndep; i++) { for (j=0; j < ndur; j++) { //npts = duration[j]+2*cwidth[j]; coeffs_notran = malloc((porder[j]+1)*sizeof(double)); coeffs_tran = malloc((porder[j]+1)*sizeof(double)); for (k=0; k < njumps-1; k++) { lw = jumps[k]; mt = jumps[k] + 5 + duration[j]/2; lt = jumps[k] + 5; rt = jumps[k] + 5 + duration[j] - 1; //printf("%d %d %d %d %d\n", duration[j], cwidth[j], MIN(cwidth[j], duration[j]), lw, mt); rw = rt + cwidth[j];//jumps[k] + 2*cwidth[j] + duration[j] - 1; jj=0; while (rt < jumps[k+1]-5) { chisq_notran=0; chisq_tran=0; //lw = MAX(lw, jumps[k]); //rw = MIN(rw, jumps[k+1]-1); npts = rw-lw+1; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); for (ii=0; ii < npts; ii++) { tt[ii] = t[lw+ii] - t[mt]; ff[ii] = f[lw+ii]; eff[ii] = ef[lw+ii]; } //tmean = mean(tt, npts); //for (ii=0; ii<npts;ii++) { // tt[ii] = tt[ii] - tmean; // // no weighting // eff[ii] = ef[lw+ii]; //} for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (t[lt] <= t[lw+ii] && t[lw+ii] <= t[rt]) { t_tmp = tt[ii]/(duration[j]*0.0204340278*0.5); if (t_tmp <= transit_x[0] | t_tmp >= transit_x[TRSZ-1]) { } else { i_lo = binarysearch(transit_x, t_tmp, 0, TRSZ, TRSZ); fmod[ii] = 1. - depth[i] * interp1d(transit_x[i_lo], transit_x[i_lo+1], transit_y[i_lo], transit_y[i_lo+1], t_tmp); } } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeffs_notran); polynomialfit_w(npts, porder[j]+1, tt, fmod, efmod, coeffs_tran); for (ii=0; ii < npts; ii++) { tmp_notran = (poly_eval(coeffs_notran, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeffs_tran, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; } dchi[i*ndur*Ntot + j*Ntot + mt] = (chisq_notran/(npts-1) - chisq_tran/(npts-3));// /npts; mt=mt+1; lt=lt+1; rt=rt+1; jj+=1; if (mt <= jumps[k]+cwidth[j]+duration[j]/2) {lw = jumps[k];} else {lw=lw+1;} if (mt >= jumps[k+1]-1-cwidth[j]-duration[j]/2) {rw = jumps[k+1]-1;} else {rw=rw+1;} free(tt); free(ff); free(eff); free(fmod); free(efmod); } } free(coeffs_notran); free(coeffs_tran); } } return 0; } // dchi computation (chi_polyonly - chi_poly*tran) with transits NOT MASKED in polyfitting int dchi_fn2(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { long lw, mt, rw; int i, j, k, ii, npts, jj, i_lo, i_hi; double *tt, *ff, *eff, *fmod, *efmod, *coeffs_tran, *coeffs_notran;//, *ttt, *fff, *efff; double chisq_notran, chisq_tran, tmp_notran, tmp_tran, tmean, t_tmp; //double *u_x, *u_y; //u_x = malloc(3*sizeof(double)); //u_y = malloc(3*sizeof(double)); //u_y[0] = 1.0; //u_y[2] = 1.0; for (i=0; i < ndep; i++) { //u_y[1] = 1.0 - depth[i]; for (j=0; j < ndur; j++) { npts = duration[j]+2*cwidth[j]; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); coeffs_notran = malloc((porder[j]+1)*sizeof(double)); coeffs_tran = malloc((porder[j]+1)*sizeof(double)); //ttt = malloc((npts-duration[j])*sizeof(double)); //fff = malloc((npts-duration[j])*sizeof(double)); //efff = malloc((npts-duration[j])*sizeof(double)); for (k=0; k < njumps-1; k++) { /* lt = jumps[k]+MIN(10, cwidth[j]); lw = lt - cwidth[j]; rt = lt + duration[j] - 1; mt = lt + duration[j]/2; rw = rt + cwidth[j]; */ lw = jumps[k]; mt = jumps[k] + cwidth[j] + duration[j]/2; rw = jumps[k] + 2*cwidth[j] + duration[j] - 1; jj=0; /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ while (rw < jumps[k+1]) { /*while (rt < jumps[k+1]-MIN(10, cwidth[j])-1) {*/ chisq_notran=0; chisq_tran=0; lw = MAX(lw, jumps[k]); rw = MIN(rw, jumps[k+1]-1); npts = rw-lw+1; for (ii=0; ii < npts; ii++) { tt[ii] = t[lw+ii]; ff[ii] = f[lw+ii]; //eff[ii] = ef[lw+ii]; /* fmod[ii] = f[lw+ii]; efmod[ii] = ef[lw+ii]; if (cwidth[j]+1 <= ii && ii<=duration[j]+cwidth[j]-2) { fmod[ii] = fmod[ii] / (1.-depth[i]); efmod[ii] = ef[lw+ii] / (1.-depth[i]); } */ } tmean = mean(tt, npts); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n%d %d %d %d %d\n", i, j, k, lw, npts); // } for (ii=0; ii<npts;ii++) { tt[ii] = tt[ii] - tmean; // no weighting eff[ii] = ef[lw+ii]; // Gaussian weighting //eff[ii] = ef[lw+ii] / exp(-tt[ii]*tt[ii] / (2. * (duration[j]+cwidth[j]) * (duration[j]+cwidth[j]) * 0.00018188455877)); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", tt[ii]); // } } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) {printf("\n");} //u_x[0]=tt[cwidth[j]]; //u_x[1]=tt[cwidth[j]+duration[j]/2]; //u_x[2]=tt[duration[j]+cwidth[j]-1]; for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { t_tmp = tt[ii]/(duration[j]*0.0204340278*0.5); if (t_tmp <= transit_x[0] | t_tmp >= transit_x[TRSZ-1]) { //fmod[ii] = 1.0; } else { i_lo = binarysearch(transit_x, t_tmp, 0, TRSZ, TRSZ); fmod[ii] = 1. - depth[i] * interp1d(transit_x[i_lo], transit_x[i_lo+1], transit_y[i_lo], transit_y[i_lo+1], t_tmp); //pow((1.-(tt[ii]*tt[ii])/(tt[cwidth[j]]*tt[cwidth[j]])), 0.2);//utransit(u_x, u_y, tt[ii]); } } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", ff[ii]); // } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n"); // for (ii=0;ii<npts;ii++) { // printf("%.7f ", fmod[ii]); // } // printf("\n"); // } // // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<npts;ii++) { // printf("%.7f ", eff[ii]); // } // printf("\n"); // } /* jj=0; for (ii=0; ii<npts;ii++) { if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { } else { ttt[jj] = tt[ii]; fff[jj] = ff[ii]; efff[jj] = eff[ii]; jj+=1; } } */ //polynomialfit_w(npts-duration[j], porder[j]+1, ttt, fff, efff, coeffs); polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeffs_notran); polynomialfit_w(npts, porder[j]+1, tt, fmod, efmod, coeffs_tran); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<porder[j]+1;ii++) { // printf("%.7e ", coeffs_tran[ii]); // } // printf("\n"); // } for (ii=0; ii < npts; ii++) { /*printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii]));*/ tmp_notran = (poly_eval(coeffs_notran, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeffs_tran, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", poly_eval(coeffs_tran, porder[j]+1, tt[ii])); // } } dchi[i*ndur*Ntot + j*Ntot + mt] = chisq_notran - chisq_tran; /* lt+=1; lw=lt-cwidth[j]; mt+=1; rt+=1; rw=rt+cwidth[j]; */ lw=lw+1; mt=mt+1; rw=rw+1; jj+=1; } /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ } free(tt); free(ff); free(eff); free(fmod); free(efmod); //free(ttt); //free(fff); //free(efff); free(coeffs_notran); free(coeffs_tran); } } //free(u_x); //free(u_y); return 0; } // dchi computation (chi_polyonly - chi_poly*tran) with transits MASKED in polyfitting int dchi_fn_mask(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { long lw, mt, rw; int i, j, k, ii, npts, jj, i_lo, i_hi; double *tt, *ff, *eff, *fmod, *efmod, *coeffs, *ttt, *fff, *efff; //*coeffs_tran, *coeffs_notran; double chisq_notran, chisq_tran, tmp_notran, tmp_tran, tmean, t_tmp; //double *u_x, *u_y; //u_x = malloc(3*sizeof(double)); //u_y = malloc(3*sizeof(double)); //u_y[0] = 1.0; //u_y[2] = 1.0; for (i=0; i < ndep; i++) { //u_y[1] = 1.0 - depth[i]; for (j=0; j < ndur; j++) { npts = duration[j]+2*cwidth[j]; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); //coeffs_notran = malloc((porder[j]+1)*sizeof(double)); //coeffs_tran = malloc((porder[j]+1)*sizeof(double)); coeffs = malloc((porder[j]+1)*sizeof(double)); ttt = malloc((npts-duration[j])*sizeof(double)); fff = malloc((npts-duration[j])*sizeof(double)); efff = malloc((npts-duration[j])*sizeof(double)); for (k=0; k < njumps-1; k++) { /* lt = jumps[k]+MIN(10, cwidth[j]); lw = lt - cwidth[j]; rt = lt + duration[j] - 1; mt = lt + duration[j]/2; rw = rt + cwidth[j]; */ lw = jumps[k]; mt = jumps[k] + cwidth[j] + duration[j]/2; rw = jumps[k] + 2*cwidth[j] + duration[j] - 1; jj=0; /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ while (rw < jumps[k+1]) { /*while (rt < jumps[k+1]-MIN(10, cwidth[j])-1) {*/ chisq_notran=0; chisq_tran=0; lw = MAX(lw, jumps[k]); rw = MIN(rw, jumps[k+1]-1); npts = rw-lw+1; for (ii=0; ii < npts; ii++) { tt[ii] = t[lw+ii]; ff[ii] = f[lw+ii]; //eff[ii] = ef[lw+ii]; /* fmod[ii] = f[lw+ii]; efmod[ii] = ef[lw+ii]; if (cwidth[j]+1 <= ii && ii<=duration[j]+cwidth[j]-2) { fmod[ii] = fmod[ii] / (1.-depth[i]); efmod[ii] = ef[lw+ii] / (1.-depth[i]); } */ } tmean = mean(tt, npts); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n%d %d %d %d %d\n", i, j, k, lw, npts); // } for (ii=0; ii<npts;ii++) { tt[ii] = tt[ii] - tmean; // no weighting eff[ii] = ef[lw+ii]; // Gaussian weighting //eff[ii] = ef[lw+ii] / exp(-tt[ii]*tt[ii] / (2. * (duration[j]+cwidth[j]) * (duration[j]+cwidth[j]) * 0.00018188455877)); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", tt[ii]); // } } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) {printf("\n");} //u_x[0]=tt[cwidth[j]]; //u_x[1]=tt[cwidth[j]+duration[j]/2]; //u_x[2]=tt[duration[j]+cwidth[j]-1]; jj=0; for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { t_tmp = tt[ii]/(duration[j]*0.0204340278*0.5); if (t_tmp <= transit_x[0] | t_tmp >= transit_x[TRSZ-1]) { //fmod[ii] = 1.0; } else { i_lo = binarysearch(transit_x, t_tmp, 0, TRSZ, TRSZ); fmod[ii] = 1. - depth[i] * interp1d(transit_x[i_lo], transit_x[i_lo+1], transit_y[i_lo], transit_y[i_lo+1], t_tmp); //pow((1.-(tt[ii]*tt[ii])/(tt[cwidth[j]]*tt[cwidth[j]])), 0.2);//utransit(u_x, u_y, tt[ii]); } } else { // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", ff[ii]); // } ttt[jj] = tt[ii]; fff[jj] = ff[ii]; efff[jj] = ef[ii]; jj+=1; } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n"); // for (ii=0;ii<npts;ii++) { // printf("%.7f ", fmod[ii]); // } // printf("\n"); // } // // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<npts;ii++) { // printf("%.7f ", eff[ii]); // } // printf("\n"); // } /* jj=0; for (ii=0; ii<npts;ii++) { if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { } else { ttt[jj] = tt[ii]; fff[jj] = ff[ii]; efff[jj] = eff[ii]; jj+=1; } } */ polynomialfit_w(npts-duration[j], porder[j]+1, ttt, fff, efff, coeffs); //polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeffs_notran); //polynomialfit_w(npts, porder[j]+1, tt, fmod, efmod, coeffs_tran); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<porder[j]+1;ii++) { // printf("%.7e ", coeffs_tran[ii]); // } // printf("\n"); // } for (ii=0; ii < npts; ii++) { /*printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii]));*/ tmp_notran = (poly_eval(coeffs, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeffs, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); //tmp_notran = (poly_eval(coeffs_notran, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; //tmp_tran = (poly_eval(coeffs_tran, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", poly_eval(coeffs_tran, porder[j]+1, tt[ii])); // } } dchi[i*ndur*Ntot + j*Ntot + mt] = chisq_notran/(npts-porder[j]-1) - chisq_tran/(npts-porder[j]-1-2); /* lt+=1; lw=lt-cwidth[j]; mt+=1; rt+=1; rw=rt+cwidth[j]; */ lw=lw+1; mt=mt+1; rw=rw+1; jj+=1; } /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ } free(tt); free(ff); free(eff); free(fmod); free(efmod); free(ttt); free(fff); free(efff); //free(coeffs_notran); //free(coeffs_tran); free(coeffs); } } //free(u_x); //free(u_y); return 0; } // dchi computation but w/ gaussian weighting for polynomial fit int dchi_fn_gs(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { long lw, mt, rw; int i, j, k, ii, npts, jj, i_lo, i_hi; double *tt, *ff, *eff, *fmod, *efmod, *coeffs_tran, *coeffs_notran;//, *ttt, *fff, *efff; double chisq_notran, chisq_tran, tmp_notran, tmp_tran, tmean, t_tmp; //double *u_x, *u_y; //u_x = malloc(3*sizeof(double)); //u_y = malloc(3*sizeof(double)); //u_y[0] = 1.0; //u_y[2] = 1.0; for (i=0; i < ndep; i++) { //u_y[1] = 1.0 - depth[i]; for (j=0; j < ndur; j++) { npts = duration[j]+2*cwidth[j]; tt = malloc(npts*sizeof(double)); ff = malloc(npts*sizeof(double)); eff = malloc(npts*sizeof(double)); fmod = malloc(npts*sizeof(double)); efmod = malloc(npts*sizeof(double)); coeffs_notran = malloc((porder[j]+1)*sizeof(double)); coeffs_tran = malloc((porder[j]+1)*sizeof(double)); //ttt = malloc((npts-duration[j])*sizeof(double)); //fff = malloc((npts-duration[j])*sizeof(double)); //efff = malloc((npts-duration[j])*sizeof(double)); for (k=0; k < njumps-1; k++) { /* lt = jumps[k]+MIN(10, cwidth[j]); lw = lt - cwidth[j]; rt = lt + duration[j] - 1; mt = lt + duration[j]/2; rw = rt + cwidth[j]; */ lw = jumps[k]; mt = jumps[k] + cwidth[j] + duration[j]/2; rw = jumps[k] + 2*cwidth[j] + duration[j] - 1; jj=0; /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ while (rw < jumps[k+1]) { /*while (rt < jumps[k+1]-MIN(10, cwidth[j])-1) {*/ chisq_notran=0; chisq_tran=0; lw = MAX(lw, jumps[k]); rw = MIN(rw, jumps[k+1]-1); npts = rw-lw+1; for (ii=0; ii < npts; ii++) { tt[ii] = t[lw+ii]; ff[ii] = f[lw+ii]; //eff[ii] = ef[lw+ii]; /* fmod[ii] = f[lw+ii]; efmod[ii] = ef[lw+ii]; if (cwidth[j]+1 <= ii && ii<=duration[j]+cwidth[j]-2) { fmod[ii] = fmod[ii] / (1.-depth[i]); efmod[ii] = ef[lw+ii] / (1.-depth[i]); } */ } tmean = mean(tt, npts); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n%d %d %d %d %d\n", i, j, k, lw, npts); // } for (ii=0; ii<npts;ii++) { tt[ii] = tt[ii] - tmean; // no weighting //eff[ii] = ef[lw+ii]; // Gaussian weighting eff[ii] = ef[lw+ii] / exp(-tt[ii]*tt[ii] / (2. * (duration[j]+cwidth[j]) * (duration[j]+cwidth[j]) * 0.00018188455877)); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", tt[ii]); // } } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) {printf("\n");} //u_x[0]=tt[cwidth[j]]; //u_x[1]=tt[cwidth[j]+duration[j]/2]; //u_x[2]=tt[duration[j]+cwidth[j]-1]; for (ii=0; ii<npts;ii++) { fmod[ii] = 1.0; if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { t_tmp = tt[ii]/(duration[j]*0.0204340278*0.5); if (t_tmp <= transit_x[0] | t_tmp >= transit_x[TRSZ-1]) { //fmod[ii] = 1.0; } else { i_lo = binarysearch(transit_x, t_tmp, 0, TRSZ, TRSZ); fmod[ii] = 1. - depth[i] * interp1d(transit_x[i_lo], transit_x[i_lo+1], transit_y[i_lo], transit_y[i_lo+1], t_tmp); //pow((1.-(tt[ii]*tt[ii])/(tt[cwidth[j]]*tt[cwidth[j]])), 0.2);//utransit(u_x, u_y, tt[ii]); } } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", ff[ii]); // } efmod[ii] = eff[ii] / fmod[ii]; fmod[ii] = ff[ii] / fmod[ii]; } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("\n"); // for (ii=0;ii<npts;ii++) { // printf("%.7f ", fmod[ii]); // } // printf("\n"); // } // // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<npts;ii++) { // printf("%.7f ", eff[ii]); // } // printf("\n"); // } /* jj=0; for (ii=0; ii<npts;ii++) { if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { } else { ttt[jj] = tt[ii]; fff[jj] = ff[ii]; efff[jj] = eff[ii]; jj+=1; } } */ //polynomialfit_w(npts-duration[j], porder[j]+1, ttt, fff, efff, coeffs); polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeffs_notran); polynomialfit_w(npts, porder[j]+1, tt, fmod, efmod, coeffs_tran); // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // for (ii=0;ii<porder[j]+1;ii++) { // printf("%.7e ", coeffs_tran[ii]); // } // printf("\n"); // } for (ii=0; ii < npts; ii++) { /*printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii]));*/ tmp_notran = (poly_eval(coeffs_notran, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; tmp_tran = (poly_eval(coeffs_tran, porder[j]+1, tt[ii]) - fmod[ii])/(efmod[ii]); chisq_notran = chisq_notran + tmp_notran*tmp_notran; chisq_tran = chisq_tran + tmp_tran*tmp_tran; // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%.7f ", poly_eval(coeffs_tran, porder[j]+1, tt[ii])); // } } dchi[i*ndur*Ntot + j*Ntot + mt] = chisq_notran - chisq_tran; /* lt+=1; lw=lt-cwidth[j]; mt+=1; rt+=1; rw=rt+cwidth[j]; */ lw=lw+1; mt=mt+1; rw=rw+1; jj+=1; } /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ } free(tt); free(ff); free(eff); free(fmod); free(efmod); //free(ttt); //free(fff); //free(efff); free(coeffs_notran); free(coeffs_tran); } } //free(u_x); //free(u_y); return 0; } //// new dchi, (N_dof - chi_poly*tran), w/ transits masked during polyfitting //int dchi_fn(double *dchi, double *t, long *jumps, double *f, double *ef, double *depth, // long *duration, int ndep, int ndur, int njumps, long *porder, long *cwidth, long Ntot) { // long lw, mt, rw; // int i, j, k, ii, npts, jj; // double *mod, *tt, *ff, *eff, *coeffs; // double chisq_tran, tmp_tran, tmean; // double *u_x, *u_y; // u_x = malloc(3*sizeof(double)); // u_y = malloc(3*sizeof(double)); // u_y[0] = 1.0; // u_y[2] = 1.0; // for (i=0; i < ndep; i++) { // u_y[1] = 1.0 - depth[i]; // for (j=0; j < ndur; j++) { // npts = duration[j]+2*cwidth[j]; // tt = malloc(npts*sizeof(double)); // mod = malloc(npts*sizeof(double)); // coeffs = malloc((porder[j]+1)*sizeof(double)); // //tt = malloc((npts-duration[j])*sizeof(double)); // ff = malloc((npts)*sizeof(double)); // eff = malloc((npts)*sizeof(double)); // // for (k=0; k < njumps-1; k++) { // /* // lt = jumps[k]+MIN(10, cwidth[j]); // lw = lt - cwidth[j]; // rt = lt + duration[j] - 1; // mt = lt + duration[j]/2; // rw = rt + cwidth[j]; // */ // // lw = jumps[k]; // mt = jumps[k] + cwidth[j] + duration[j]/2; // rw = jumps[k] + 2*cwidth[j] + duration[j] - 1; // // /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ // while (rw < jumps[k+1]) { // /*while (rt < jumps[k+1]-MIN(10, cwidth[j])-1) {*/ // chisq_tran=0; // lw = MAX(lw, jumps[k]); // rw = MIN(rw, jumps[k+1]-1); // npts = rw-lw+1; // for (ii=0; ii < npts; ii++) { // tt[ii] = t[lw+ii]; // ff[ii] = f[lw+ii]; // eff[ii] = ef[lw+ii]; // /* // fmod[ii] = f[lw+ii]; // efmod[ii] = ef[lw+ii]; // if (cwidth[j]+1 <= ii && ii<=duration[j]+cwidth[j]-2) { // fmod[ii] = fmod[ii] / (1.-depth[i]); // efmod[ii] = ef[lw+ii] / (1.-depth[i]); // } // */ // } // tmean = mean(tt, npts); // for (ii=0; ii<npts;ii++) { // tt[ii] = tt[ii] - tmean; // } // u_x[0]=tt[cwidth[j]]; // u_x[1]=tt[cwidth[j]+duration[j]/2]; // u_x[2]=tt[duration[j]+cwidth[j]-1]; // for (ii=0; ii<npts;ii++) { // mod[ii] = 1.0; // if (cwidth[j] <= ii && ii <=duration[j]+cwidth[j]-1) { // mod[ii] = utransit(u_x, u_y, tt[ii]); // //printf("tran %d %d %d %.5e\n", k, ii, jj, mod[ii]); // } // ff[ii] = ff[ii] / mod[ii]; // eff[ii] = eff[ii] / mod[ii]; // //printf("NOtran %d %d %d %.5e %.5e %.5e\n", k, ii, jj, tt[jj], tt0[ii], f[lw+ii]); // // } // // polynomialfit_w(npts, porder[j]+1, tt, ff, eff, coeffs); // // /* // for (ii=0;ii<porder[j]+1; ii++) { // printf("%.8e ", coeff_notran[ii]); // } // printf("\n"); // */ // for (ii=0; ii < npts; ii++) { // /*printf("%10.8f ", poly_eval(coeff_notran, porder[j]+1, tt[ii]));*/ // tmp_tran = (poly_eval(coeffs, porder[j]+1, tt[ii]) - ff[ii])/eff[ii]; // chisq_tran = chisq_tran + tmp_tran*tmp_tran; // /*if (ii % 6==0) { // printf("\n"); // }*/ // } // if (i==0 && j==0 && k%10==0 && lw==jumps[0]) { // printf("%d %d %d %ld %d \n", i, j, k, lw, npts); // for (ii=0; ii<npts;ii++) { // printf("%10.8f ", tt[ii]); // } // printf("\n"); // for (ii=0; ii<npts;ii++) { // printf("%10.8f ", ff[ii]); // } // printf("\n"); // for (ii=0; ii<npts;ii++) { // printf("%10.8f ", eff[ii]); // } // printf("\n"); // for (ii=0;ii<porder[j]+1; ii++) { // printf("%.8e ", coeffs[ii]); // } // printf("\n"); // for (ii=0; ii<npts;ii++) { // printf("%10.8f ", poly_eval(coeffs, porder[j]+1, tt[ii])); // } // printf("\n"); // printf("%.8e\n", chisq_tran); // } // dchi[i*ndur*Ntot + j*Ntot + mt] = npts - porder[j] - 1 - chisq_tran; // /* // lt+=1; // lw=lt-cwidth[j]; // mt+=1; // rt+=1; // rw=rt+cwidth[j]; // */ // lw=lw+1; // mt=mt+1; // rw=rw+1; // } // /*printf("%d %d %d %ld %ld %ld\n", i, j, k, lw, mt, rw);*/ // } // free(tt); // free(ff); // free(eff); // free(mod); // free(coeffs); // } // } // free(u_x); // free(u_y); // return 0; //} int poly_lc(double *polvals, double *t, double *f, double *ef, double *model, long *jumps, int porder, int njumps) { int i, j, k, npts, ooe, porder_orig; double *tt0, *tt, *fmod, *efmod, *coeffs; double t0mean, tmean; for (i=0; i < njumps-1; i++) { npts = jumps[i+1]-jumps[i]; ooe = 0; tt0 = malloc(npts*sizeof(double)); for (j=0;j<npts;j++) { tt0[j] = t[jumps[i]+j]; if (model[jumps[i]+j]>=1.) { ooe+=1; } } if (ooe<porder+1) { //printf("%i, %i, %.5f, %.5f\n", ooe, porder+1, model[jumps[i]], model[jumps[i+1]-1]); free(tt0); /*printf("Npts out of eclipse = %i", ooe);*/ } else { //if ((model[jumps[i]]<1.) || (model[jumps[i+1]-1]<1.)) {porder_orig=porder; porder=1;} coeffs = malloc((porder+1)*sizeof(double)); t0mean = mean(tt0, npts); tt = malloc(ooe*sizeof(double)); fmod = malloc(ooe*sizeof(double)); efmod = malloc(ooe*sizeof(double)); k=0; for (j=0; j<npts; j++) { tt0[j] = tt0[j] - t0mean; if (model[jumps[i]+j]>=1.) { tt[k] = t[jumps[i]+j]; fmod[k] = f[jumps[i]+j] / model[jumps[i]+j]; efmod[k] = ef[jumps[i]+j] / model[jumps[i]+j]; k+=1; } } tmean = mean(tt, ooe); for (k=0;k<ooe;k++) { tt[k] = tt[k] - tmean; } polynomialfit_w(ooe, porder+1, tt, fmod, efmod, coeffs); for (j=0;j<npts;j++) { polvals[jumps[i]+j] = poly_eval(coeffs, porder+1, tt0[j]); } //if ((model[jumps[i]]<1.) || (model[jumps[i+1]-1]<1.)) {porder=porder_orig;} free(tt0); free(tt); free(fmod); free(efmod); free(coeffs); } } return 0; } int poly_lc_ooe(double *polvals, double *t, double *f, double *ef, double *model, long *jumps, int porder, int njumps) { int i, j, k, npts, ooe, porder_orig; double *tt0, *tt, *fmod, *efmod, *coeffs; double t0mean, tmean; for (i=0; i < njumps-1; i++) { npts = jumps[i+1]-jumps[i]; ooe = 0; tt0 = malloc(npts*sizeof(double)); for (j=0;j<npts;j++) { tt0[j] = t[jumps[i]+j]; if (model[jumps[i]+j]>0.) { ooe+=1; } } if (ooe<porder+1) { /*printf("%.5f, %.5f\n", model[jumps[i]], model[jumps[i+1]-1]);*/ //printf("ooe<porder+1; %i %i\n", ooe, porder+1); free(tt0); /*printf("Npts out of eclipse = %i", ooe);*/ } else { //if ((model[jumps[i]]<1.) || (model[jumps[i+1]-1]<1.)) {porder_orig=porder; porder=1;} coeffs = malloc((porder+1)*sizeof(double)); t0mean = mean(tt0, npts); tt = malloc(ooe*sizeof(double)); fmod = malloc(ooe*sizeof(double)); efmod = malloc(ooe*sizeof(double)); k=0; for (j=0; j<npts; j++) { tt0[j] = tt0[j] - t0mean; if (model[jumps[i]+j]>0.) { tt[k] = t[jumps[i]+j]; fmod[k] = f[jumps[i]+j] / model[jumps[i]+j]; efmod[k] = ef[jumps[i]+j] / model[jumps[i]+j]; k+=1; } } tmean = mean(tt, ooe); for (k=0;k<ooe;k++) { tt[k] = tt[k] - tmean; } //printf("\nBefore polyfit, porder=%i, ooe=%i, npts=%i, t=%.5f\n", porder, ooe, npts, tt[0]); polynomialfit_w(ooe, porder+1, tt, fmod, efmod, coeffs); //printf("After polyfit\n"); for (j=0;j<npts;j++) { polvals[jumps[i]+j] = poly_eval(coeffs, porder+1, tt0[j]); //printf("%.5f ", polvals[jumps[i]+j]); } //if ((model[jumps[i]]<1.) || (model[jumps[i+1]-1]<1.)) {porder=porder_orig;} free(tt0); free(tt); free(fmod); free(efmod); free(coeffs); } } return 0; } double getE(double M, double e) { double E = M, eps = 1.0e-7; int niter; while(fabs(E - e*sin(E) - M) > eps && niter<30) { E = E - (E - e*sin(E) - M) / (1.0 - e*cos(E)); } return E; } int rsky(double *t, double *f, double e, double P, double t0, double eps, int Npts) { int ii; double M, E; double n=TWOPI/P; for (ii=0;ii<Npts;ii++) { if (e > eps) { M = n*(t[ii] - t0); E = getE(M, e); f[ii] = 2. * atan((sqrt((1.+e)/(1.-e))) * tan(E/2.0)); } else { f[ii] = (t[ii]-t0)/P - (int)((t[ii]-t0)/P)*TWOPI; } } return 0; }
{ "alphanum_fraction": 0.4765095937, "avg_line_length": 33.8167938931, "ext": "c", "hexsha": "4690c634a5b55e049f859e99f77b8d707cc1173d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-31T10:27:14.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-31T10:27:14.000Z", "max_forks_repo_head_hexsha": "250d7934a4f64edc7494749257c07e50415f8c19", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "savvytruffle/cauldron", "max_forks_repo_path": "helpers.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "250d7934a4f64edc7494749257c07e50415f8c19", "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": "savvytruffle/cauldron", "max_issues_repo_path": "helpers.c", "max_line_length": 149, "max_stars_count": 4, "max_stars_repo_head_hexsha": "250d7934a4f64edc7494749257c07e50415f8c19", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "savvytruffle/cauldron", "max_stars_repo_path": "helpers.c", "max_stars_repo_stars_event_max_datetime": "2020-02-17T00:05:56.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-22T04:41:18.000Z", "num_tokens": 25963, "size": 70880 }
/* Copyright 2016. The Regents of the University of California. * Copyright 2016-2020. Uecker Lab. University Medical Center Göttingen. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2016 Jonathan Tamir <jtamir@eecs.berkeley.edu> * 2016-2020 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2019-2020 Moritz Blumenthal */ #include <assert.h> #include <complex.h> #include <stdbool.h> #include "misc/misc.h" #ifdef USE_MACPORTS #include <cblas_openblas.h> #elif USE_MKL #include <mkl.h> #else #include <cblas.h> #endif #ifdef _OPENMP #include <omp.h> #endif #ifdef USE_CUDA #include <cuComplex.h> #include <cublas_v2.h> #include "num/gpuops.h" #endif #include "blas.h" #ifdef USE_CUDA //blas2_* means, we use the new blas interface, i.e. scalar parameters are written an read by pointers. //These pointers can point to cpu or gpu memory. //blas_* uses the old interface where scalar parameters/results are provided/written by value/return. static void cublas_error(int line, cublasStatus_t code) { error("cublas error: %d in line %d \n", code, line); } #define CUBLAS_ERROR(x) ({ cublasStatus_t errval = (x); if (CUBLAS_STATUS_SUCCESS != errval) cublas_error(__LINE__, errval); }) static cublasHandle_t handle; static _Bool handle_created = false; static cublasHandle_t get_handle(void) { if (!handle_created) CUBLAS_ERROR(cublasCreate(&handle)); handle_created = true; return handle; } static void destroy_handle(void) { CUBLAS_ERROR(cublasDestroy(handle)); handle_created = false; } static void cublas_set_pointer_host(void) { (void)get_handle(); CUBLAS_ERROR(cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_HOST)); } static void cublas_set_pointer_device(void) { (void)get_handle(); CUBLAS_ERROR(cublasSetPointerMode(handle, CUBLAS_POINTER_MODE_DEVICE)); } static cublasOperation_t cublas_trans(char trans) { if (('N' == trans) || ('n'==trans)) return CUBLAS_OP_N; if (('T' == trans) || ('t'==trans)) return CUBLAS_OP_T; if (('C' == trans) || ('c'==trans)) return CUBLAS_OP_C; assert(0); } #endif static void openblas_set_threads(void) { #ifndef USE_OPENBLAS return; #else #ifndef _OPENMP return; #else if (1 != openblas_get_parallel()) return; //pthread version of openblas #pragma omp critical openblas_set_num_threads(omp_in_parallel() ? 1 : omp_get_max_threads()); #endif #endif } void blas2_cgemm(char transa, char transb, long M, long N, long K, const complex float* alpha, long lda, const complex float* A, long ldb, const complex float* B, const complex float* beta, long ldc, complex float* C) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasCgemm(get_handle(), cublas_trans(transa), cublas_trans(transb), M, N, K, (const cuComplex*)alpha, (const cuComplex*)A, lda, (const cuComplex*)B, ldb, (const cuComplex*)beta, (cuComplex*)C, ldc); return; } #endif openblas_set_threads(); cblas_cgemm(CblasColMajor, ('T' == transa) ? CblasTrans : (('C' == transa) ? CblasConjTrans : CblasNoTrans), ('T' == transb) ? CblasTrans : (('C' == transb) ? CblasConjTrans : CblasNoTrans), M, N, K, (void*)alpha, (void*)A, lda, (void*)B, ldb, (void*)beta, (void*)C, ldc); } void blas_cgemm(char transa, char transb, long M, long N, long K, const complex float alpha, long lda, const complex float* A, long ldb, const complex float* B, const complex float beta, long ldc, complex float* C) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasCgemm(get_handle(), cublas_trans(transa), cublas_trans(transb), M, N, K, (const cuComplex*)(&alpha), (const cuComplex*)A, lda, (const cuComplex*)B, ldb, (const cuComplex*)(&beta), (cuComplex*)C, ldc); return; } #endif openblas_set_threads(); cblas_cgemm(CblasColMajor, ('T' == transa) ? CblasTrans : (('C' == transa) ? CblasConjTrans : CblasNoTrans), ('T' == transb) ? CblasTrans : (('C' == transb) ? CblasConjTrans : CblasNoTrans), M, N, K, (void*)(&alpha), (void*)A, lda, (void*)B, ldb, (void*)(&beta), (void*)C, ldc); } void blas2_cgemv(char trans, long M, long N, const complex float* alpha, long lda, const complex float* A, long incx, const complex float* x, complex float* beta, long incy, complex float* y) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasCgemv(get_handle(), cublas_trans(trans), M, N, (const cuComplex*)alpha, (const cuComplex*)A, lda, (const cuComplex*)x, incx, (const cuComplex*)beta, (cuComplex*)y, incy); return; } #endif openblas_set_threads(); cblas_cgemv(CblasColMajor, ('T' == trans) ? CblasTrans : (('C' == trans) ? CblasConjTrans : CblasNoTrans), M, N, (void*)alpha, (void*)A, lda, (void*)x, incx, (void*)beta, (void*)y, incy); } void blas_cgemv(char trans, long M, long N, complex float alpha, long lda, const complex float* A, long incx, const complex float* x, complex float beta, long incy, complex float* y) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasCgemv(get_handle(), cublas_trans(trans), M, N, (const cuComplex*)&alpha, (const cuComplex*)A, lda, (const cuComplex*)x, incx, (const cuComplex*)&beta, (cuComplex*)y, incy); return; } #endif openblas_set_threads(); cblas_cgemv(CblasColMajor, ('T' == trans) ? CblasTrans : (('C' == trans) ? CblasConjTrans : CblasNoTrans), M, N, (void*)&alpha, (void*)A, lda, (void*)x, incx, (void*)&beta, (void*)y, incy); } void blas2_cgeru(long M, long N, const complex float* alpha, long incx, const complex float* x, long incy, const complex float* y, long lda, complex float* A) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasCgeru(get_handle(), M, N, (const cuComplex*)alpha, (const cuComplex*)x, incx, (const cuComplex*)y, incy, (cuComplex*)A, lda); return; } #endif openblas_set_threads(); cblas_cgeru(CblasColMajor, M, N, alpha, x, incx, y, incy, A, lda); } void blas_cgeru(long M, long N, complex float alpha, long incx, const complex float* x, long incy, const complex float* y, long lda, complex float* A) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasCgeru(get_handle(), M, N, (const cuComplex*)&alpha, (const cuComplex*)x, incx, (const cuComplex*)y, incy, (cuComplex*)A, lda); return; } #endif openblas_set_threads(); cblas_cgeru(CblasColMajor, M, N, &alpha, x, incx, y, incy, (float*)A, lda); } void blas2_caxpy(long N, const complex float* alpha, long incx, const complex float* x, long incy, complex float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasCaxpy(get_handle(), N, (const cuComplex*)alpha, (const cuComplex*)x, incx, (cuComplex*)y, incy); return; } #endif openblas_set_threads(); cblas_caxpy(N, alpha, x, incx, y, incy); } void blas_caxpy(long N, const complex float alpha, long incx, const complex float* x, long incy, complex float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_host(); cublasCaxpy(get_handle(), N, (const cuComplex*)&alpha, (const cuComplex*)x, incx, (cuComplex*)y, incy); return; } #endif openblas_set_threads(); cblas_caxpy(N, &alpha, x, incx, y, incy); } void blas2_cscal(long N, const complex float* alpha, long incx, complex float* x) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasCscal(get_handle(), N, (const cuComplex*)alpha, (cuComplex*)x, incx); return; } #endif openblas_set_threads(); cblas_cscal(N, alpha, x, incx); } void blas_cscal(long N, const complex float alpha, long incx, complex float* x) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_host(); cublasCscal(get_handle(), N, (const cuComplex*)&alpha, (cuComplex*)x, incx); return; } #endif openblas_set_threads(); cblas_cscal(N, &alpha, x, incx); } void blas2_cdotu(complex float* result, long N, long incx, const complex float* x, long incy, const complex float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasCdotu(get_handle(), N, (const cuComplex*)x, incx, (const cuComplex*)y, incy, (cuComplex*)result); return; } #endif openblas_set_threads(); cblas_cdotu_sub(N, x, incx, y, incy, (void*)result); } void blas2_sgemm(char transa, char transb, long M, long N, long K, const float* alpha, long lda, const float* A, long ldb, const float* B, const float* beta, long ldc, float* C) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasSgemm(get_handle(), cublas_trans(transa), cublas_trans(transb), M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); return; } #endif openblas_set_threads(); cblas_sgemm(CblasColMajor, ('T' == transa) ? CblasTrans : (('C' == transa) ? CblasConjTrans : CblasNoTrans), ('T' == transb) ? CblasTrans : (('C' == transb) ? CblasConjTrans : CblasNoTrans), M, N, K, *alpha, A, lda, B, ldb, *beta, C, ldc); } void blas_sgemm(char transa, char transb, long M, long N, long K, const float alpha, long lda, const float* A, long ldb, const float* B, const float beta, long ldc, float* C) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasSgemm(get_handle(), cublas_trans(transa), cublas_trans(transb), M, N, K, &alpha, A, lda, B, ldb, &beta, C, ldc); return; } #endif openblas_set_threads(); cblas_sgemm(CblasColMajor, ('T' == transa) ? CblasTrans : (('C' == transa) ? CblasConjTrans : CblasNoTrans), ('T' == transb) ? CblasTrans : (('C' == transb) ? CblasConjTrans : CblasNoTrans), M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } void blas2_sgemv(char trans, long M, long N, const float* alpha, long lda, const float* A, long incx, const float* x, float* beta, long incy, float* y) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasSgemv(get_handle(), cublas_trans(trans), M, N, alpha, (const float*)A, lda, x, incx, beta, y, incy); return; } #endif openblas_set_threads(); cblas_sgemv(CblasColMajor, ('T' == trans) ? CblasTrans : CblasNoTrans, M, N, *alpha, (const float*)A, lda, x, incx, *beta, y, incy); } void blas_sgemv(char trans, long M, long N, const float alpha, long lda, const float* A, long incx, const float* x, float beta, long incy, float* y) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasSgemv(get_handle(), cublas_trans(trans), M, N, &alpha, (const float*)A, lda, x, incx, &beta, y, incy); return; } #endif openblas_set_threads(); cblas_sgemv(CblasColMajor, ('T' == trans) ? CblasTrans : CblasNoTrans, M, N, alpha, (const float*)A, lda, x, incx, beta, y, incy); } void blas2_sger(long M, long N, const float* alpha, long incx, const float* x, long incy, const float* y, long lda, float* A) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_device(); cublasSger(get_handle(), M, N, alpha, x, incx, y, incy, (float*)A, lda); return; } #endif openblas_set_threads(); cblas_sger(CblasColMajor, M, N, *alpha, x, incx, y, incy, (float*)A, lda); } void blas_sger(long M, long N, const float alpha, long incx, const float* x, long incy, const float* y, long lda, float* A) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); cublasSger(get_handle(), M, N, &alpha, x, incx, y, incy, (float*)A, lda); return; } #endif openblas_set_threads(); cblas_sger(CblasColMajor, M, N, alpha, x, incx, y, incy, (float*)A, lda); } void blas2_saxpy(long N, const float* alpha, long incx, const float* x, long incy, float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasSaxpy(get_handle(), N, alpha, x, incx, y, incy); return; } #endif openblas_set_threads(); cblas_saxpy(N, *alpha, x, incx, y, incy); } void blas_saxpy(long N, const float alpha, long incx, const float* x, long incy, float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_host(); cublasSaxpy(get_handle(), N, &alpha, x, incx, y, incy); return; } #endif openblas_set_threads(); cblas_saxpy(N, alpha, x, incx, y, incy); } void blas2_sscal(long N, const float* alpha, long incx, float* x) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasSscal(get_handle(), N, alpha, x, incx); return; } #endif openblas_set_threads(); cblas_sscal(N, *alpha, x, incx); } void blas_sscal(long N, float alpha, long incx, float* x) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_host(); cublasSscal(get_handle(), N, &alpha, x, incx); return; } #endif openblas_set_threads(); cblas_sscal(N, alpha, x, incx); } void blas2_sdot(float* result, long N, long incx, const float* x, long incy, const float* y) { #ifdef USE_CUDA if (cuda_ondevice(x)) { cublas_set_pointer_device(); cublasSdot(get_handle(), N, x, incx, y, incy, result); return; } #endif openblas_set_threads(); *result = cblas_sdot(N, x, incx, y, incy); } void blas_cdgmm(long M, long N, _Bool left_mul, const complex float* A, long lda, const complex float* x, long incx, complex float* C, long ldc) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublasCdgmm(get_handle(), left_mul ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT, M, N, (const cuComplex*)A, lda, (const cuComplex*)x, incx, (cuComplex*)C, ldc); return; } #endif UNUSED(M); UNUSED(N); UNUSED(left_mul); UNUSED(A); UNUSED(lda); UNUSED(x); UNUSED(incx); UNUSED(C); UNUSED(ldc); assert(0); } void blas_sdgmm(long M, long N, _Bool left_mul, const float* A, long lda, const float* x, long incx, float* C, long ldc) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublasSdgmm(get_handle(), left_mul ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT, M, N, A, lda, x, incx, C, ldc); return; } #endif UNUSED(M); UNUSED(N); UNUSED(left_mul); UNUSED(A); UNUSED(lda); UNUSED(x); UNUSED(incx); UNUSED(C); UNUSED(ldc); assert(0); } //B = alpha * op(A) void blas_cmatcopy(char trans, long M, long N, complex float alpha, const complex float* A, long lda, complex float* B, long ldb) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); complex float zero = 0.; cublasCgeam(get_handle(), cublas_trans(trans), cublas_trans('N'), M, N, (const cuComplex*)&alpha, (const cuComplex*)A, lda, (const cuComplex*)&zero, (const cuComplex*)B, ldb, (cuComplex*)B, ldb); return; } #endif UNUSED(trans); UNUSED(M); UNUSED(N); UNUSED(alpha); UNUSED(lda); UNUSED(A); UNUSED(ldb); UNUSED(B); assert(0); } //B = alpha * op(A) void blas2_cmatcopy(char trans, long M, long N, const complex float* alpha, const complex float* A, long lda, complex float* B, long ldb) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); complex float* zero = cuda_malloc(8); cuda_clear(8, zero); cublasCgeam(get_handle(), cublas_trans(trans), cublas_trans('N'), M, N, (const cuComplex*)alpha, (const cuComplex*)A, lda, (const cuComplex*)zero, (const cuComplex*)B, ldb, (cuComplex*)B, ldb); cuda_free(zero); return; } #endif UNUSED(trans); UNUSED(M); UNUSED(N); UNUSED(alpha); UNUSED(lda); UNUSED(A); UNUSED(ldb); UNUSED(B); assert(0); } //B = alpha * op(A) void blas_smatcopy(char trans, long M, long N, float alpha, const float* A, long lda, float* B, long ldb) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); float zero = 0.; cublasSgeam(get_handle(), cublas_trans(trans), cublas_trans('N'), M, N, &alpha, A, lda, &zero, B, ldb, B, ldb); return; } #endif UNUSED(trans); UNUSED(M); UNUSED(N); UNUSED(alpha); UNUSED(lda); UNUSED(A); UNUSED(ldb); UNUSED(B); assert(0); } //B = alpha * op(A) void blas2_smatcopy(char trans, long M, long N, const float* alpha, const float* A, long lda, float* B, long ldb) { #ifdef USE_CUDA if (cuda_ondevice(A)) { cublas_set_pointer_host(); float* zero = cuda_malloc(4); cuda_clear(4, zero); cublasSgeam(get_handle(), cublas_trans(trans), cublas_trans('N'), M, N, alpha, A, lda, zero, B, ldb, B, ldb); cuda_free(zero); return; } #endif UNUSED(trans); UNUSED(M); UNUSED(N); UNUSED(alpha); UNUSED(lda); UNUSED(A); UNUSED(ldb); UNUSED(B); assert(0); } void blas_csyrk(char uplo, char trans, long N, long K, const complex float alpha, long lda, const complex float A[][lda], complex float beta, long ldc, complex float C[][ldc]) { assert('U' == uplo); assert(('T' == trans) || ('N' == trans)); cblas_csyrk(CblasColMajor, CblasUpper, ('T' == trans) ? CblasTrans : CblasNoTrans, N, K, (void*)&alpha, (void*)A, lda, (void*)&beta, (void*)C, ldc); } void blas_sger_fmac(long M, long N, float* A, const float* x, const float* y) { blas_sger(M, N, 1., 1, x, 1, y, M, A); } void blas_gemv_zfmac(long M, long N, complex float* y, const complex float* A, char trans, const complex float* x) { assert((trans == 'N') || (trans == 'T') || (trans == 'C')); blas_cgemv(trans,M, N, 1., M, A, 1, x, 1., 1, y); } void blas_gemv_fmac(long M, long N, float* y, const float* A, char trans, const float* x) { assert((trans == 'N') || (trans == 'T')); blas_sgemv(trans,M, N, 1., M, A, 1, x, 1., 1, y); } void blas_matrix_multiply(long M, long N, long K, complex float C[N][M], const complex float A[K][M], const complex float B[N][K]) { blas_cgemm('N', 'N', M, N, K, 1. , M, (const complex float*)A, K, (const complex float*)B, 0., M, (complex float*)C); } void blas_matrix_zfmac(long M, long N, long K, complex float* C, const complex float* A, char transa, const complex float* B, char transb) { assert((transa == 'N') || (transa == 'T') || (transa == 'C')); assert((transb == 'N') || (transb == 'T') || (transb == 'C')); long lda = (transa == 'N' ? M: K); long ldb = (transb == 'N' ? K: N); blas_cgemm(transa, transb, M, N, K, 1., lda, A, ldb, B, 1., M, C); }
{ "alphanum_fraction": 0.6715787132, "avg_line_length": 22.5068836045, "ext": "c", "hexsha": "37a0cc9e1a805ef6014e226f333de1726e452781", "lang": "C", "max_forks_count": 153, "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:03:34.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-25T02:30:45.000Z", "max_forks_repo_head_hexsha": "924f440abf855bae1b28d66c10ed6b37c3ebb2b0", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ecat/bart", "max_forks_repo_path": "src/num/blas.c", "max_issues_count": 158, "max_issues_repo_head_hexsha": "924f440abf855bae1b28d66c10ed6b37c3ebb2b0", "max_issues_repo_issues_event_max_datetime": "2022-02-15T15:36:44.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-17T18:55:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "ecat/bart", "max_issues_repo_path": "src/num/blas.c", "max_line_length": 217, "max_stars_count": 189, "max_stars_repo_head_hexsha": "924f440abf855bae1b28d66c10ed6b37c3ebb2b0", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ecat/bart", "max_stars_repo_path": "src/num/blas.c", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:30:17.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-28T15:36:23.000Z", "num_tokens": 5782, "size": 17983 }
/* histogram/pdf.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 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. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> #include "find.c" double gsl_histogram_pdf_sample (const gsl_histogram_pdf * p, double r) { size_t i; int status; /* Wrap the exclusive top of the bin down to the inclusive bottom of the bin. Since this is a single point it should not affect the distribution. */ if (r == 1.0) { r = 0.0; } status = find (p->n, p->sum, r, &i); if (status) { GSL_ERROR_VAL ("cannot find r in cumulative pdf", GSL_EDOM, 0); } else { double delta = (r - p->sum[i]) / (p->sum[i + 1] - p->sum[i]); double x = p->range[i] + delta * (p->range[i + 1] - p->range[i]); return x; } } gsl_histogram_pdf * gsl_histogram_pdf_alloc (const size_t n) { gsl_histogram_pdf *p; if (n == 0) { GSL_ERROR_VAL ("histogram pdf length n must be positive integer", GSL_EDOM, 0); } p = (gsl_histogram_pdf *) malloc (sizeof (gsl_histogram_pdf)); if (p == 0) { GSL_ERROR_VAL ("failed to allocate space for histogram pdf struct", GSL_ENOMEM, 0); } p->range = (double *) malloc ((n + 1) * sizeof (double)); if (p->range == 0) { free (p); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for histogram pdf ranges", GSL_ENOMEM, 0); } p->sum = (double *) malloc ((n + 1) * sizeof (double)); if (p->sum == 0) { free (p->range); free (p); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for histogram pdf sums", GSL_ENOMEM, 0); } p->n = n; return p; } int gsl_histogram_pdf_init (gsl_histogram_pdf * p, const gsl_histogram * h) { size_t i; size_t n = p->n; if (n != h->n) { GSL_ERROR ("histogram length must match pdf length", GSL_EINVAL); } for (i = 0; i < n; i++) { if (h->bin[i] < 0) { GSL_ERROR ("histogram bins must be non-negative to compute" "a probability distribution", GSL_EDOM); } } for (i = 0; i < n + 1; i++) { p->range[i] = h->range[i]; } { double mean = 0, sum = 0; for (i = 0; i < n; i++) { mean += (h->bin[i] - mean) / ((double) (i + 1)); } p->sum[0] = 0; for (i = 0; i < n; i++) { sum += (h->bin[i] / mean) / n; p->sum[i + 1] = sum; } } return GSL_SUCCESS; } void gsl_histogram_pdf_free (gsl_histogram_pdf * p) { RETURN_IF_NULL (p); free (p->range); free (p->sum); free (p); }
{ "alphanum_fraction": 0.575191164, "avg_line_length": 22.7806451613, "ext": "c", "hexsha": "529863bbf5c0b1001f1d619937ca7eb08271e5dc", "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/histogram/pdf.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/histogram/pdf.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/histogram/pdf.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": 1030, "size": 3531 }
// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \file sirius_internal.h * * \brief Contains basic definitions and declarations. */ #ifndef __SIRIUS_INTERNAL_H__ #define __SIRIUS_INTERNAL_H__ #include <omp.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_sf_bessel.h> #include <fftw3.h> #include <vector> #include <complex> #include <iostream> #include <algorithm> #include "config.h" #include "communicator.hpp" #include "gpu.h" #include "runtime.h" #ifdef __PLASMA extern "C" void plasma_init(int num_cores); #endif #ifdef __LIBSCI_ACC extern "C" void libsci_acc_init(); extern "C" void libsci_acc_finalize(); #endif /// Namespace of the SIRIUS library. namespace sirius { inline void initialize(bool call_mpi_init__) { if (call_mpi_init__) Communicator::initialize(); #ifdef __GPU cuda_create_streams(omp_get_max_threads() + 1); cublas_create_handles(omp_get_max_threads() + 1); #endif #ifdef __MAGMA magma_init_wrapper(); #endif #ifdef __PLASMA plasma_init(omp_get_max_threads()); #endif #ifdef __LIBSCI_ACC libsci_acc_init(); #endif assert(sizeof(int) == 4); assert(sizeof(double) == 8); } inline void finalize() { Communicator::finalize(); #ifdef __MAGMA magma_finalize_wrapper(); #endif #ifdef __LIBSCI_ACC libsci_acc_finalize(); #endif #ifdef __GPU cublas_destroy_handles(omp_get_max_threads() + 1); cuda_destroy_streams(); cuda_device_reset(); #endif fftw_cleanup(); } }; #define TERMINATE_NO_GPU TERMINATE("not compiled with GPU support"); #define TERMINATE_NO_SCALAPACK TERMINATE("not compiled with ScaLAPACK support"); #define TERMINATE_NOT_IMPLEMENTED TERMINATE("feature is not implemented"); #endif // __SIRIUS_INTERNAL_H__ /** \mainpage Welcome to SIRIUS * \section intro Introduction * SIRIUS is a domain-specific library for electronic structure calculations. It supports full-potential linearized * augmented plane wave (FP-LAPW) and pseudopotential plane wave (PP-PW) methods and is designed to work with codes * such as Exciting, Elk, Quantum ESPRESSO, etc. * \section install Installation * ... */ /** \page stdvarname Standard variable names * * Below is the list of standard names for some of the loop variables: * * l - index of orbital quantum number \n * m - index of azimutal quantum nuber \n * lm - combined index of (l,m) quantum numbers \n * ia - index of atom \n * ic - index of atom class \n * iat - index of atom type \n * ir - index of r-point \n * ig - index of G-vector \n * idxlo - index of local orbital \n * idxrf - index of radial function \n * xi - compbined index of lm and idxrf (product of angular and radial functions) \n * ik - index of k-point \n * itp - index of (theta, phi) spherical angles \n * * The _loc suffix is often added to the variables to indicate that they represent the local fraction of the elements * assigned to the given MPI rank. */ //! \page coding Coding style //! //! Below are some basic style rules that we follow: //! - Page width is approximately 120 characters. Screens are wide nowdays and 80 characters is an //! obsolete restriction. Going slightly over 120 characters is allowed if it is requird for the line continuity. //! - Identation: 4 spaces (no tabs) //! - Coments are inserted before the code with slash-star style starting with the lower case: //! \code{.cpp} //! /* call a very important function */ //! do_something(); //! \endcode //! - Spaces between most operators: //! \code{.cpp} //! if (i < 5) { //! j = 5; //! } //! //! for (int k = 0; k < 3; k++) //! //! int lm = l * l + l + m; //! //! double d = std::abs(e); //! //! int k = idx[3]; //! \endcode //! - Spaces between function arguments: //! \code{.cpp} //! double d = some_func(a, b, c); //! \endcode //! but not //! \code{.cpp} //! double d=some_func(a,b,c); //! \endcode //! or //! \code{.cpp} //! double d = some_func( a, b, c ); //! \endcode //! - Spaces between template arguments, but not between <> brackets: //! \code{.cpp} //! std::vector<std::array<int, 2>> vec; //! \endcode //! but not //! \code{.cpp} //! std::vector< std::array< int, 2 > > vec; //! \endcode //! - Curly braces for classes and functions start form the new line: //! \code{.cpp} //! class A //! { //! .... //! }; //! //! inline int num_points() //! { //! return num_points_; //! } //! \endcode //! - Curly braces for if-statements, for-loops, switch-case statements, etc. start at the end of the line: //! \code{.cpp} //! for (int i: {0, 1, 2}) { //! some_func(i); //! } //! //! if (a == 0) { //! printf("a is zero"); //! } else { //! printf("a is not zero"); //! } //! //! switch (i) { //! case 1: { //! do_something(); //! break; //! case 2: { //! do_something_else(); //! break; //! } //! } //! \endcode //! - Even single line 'if' statements and 'for' loops must have the curly brackes: //! \code{.cpp} //! if (i == 4) { //! some_variable = 5; //! } //! //! for (int k = 0; k < 10; k++) { //! do_something(k); //! } //! \endcode //! - Reference and pointer symbols are part of type: //! \code{.cpp} //! std::vector<double>& vec = make_vector(); //! //! double* ptr = &vec[0]; //! //! auto& atom = unit_cell().atom(ia); //! \endcode //! - Const modifier follows the type declaration: //! \code{.cpp} //! std::vector<int> const& idx() const //! { //! return idx_; //! } //! \endcode //! - Names of class members end with underscore: //! \code{.cpp} //! class A //! { //! private: //! int lmax_; //! }; //! \endcode //! - Setter method starts from set_, getter method is a variable name itself: //! \code{.cpp} //! class A //! { //! private: //! int lmax_; //! public: //! int lmax() const //! { //! return lmax_; //! } //! void set_lmax(int lmax__) //! { //! lmax_ = lmax__; //! } //! }; //! \endcode //! - Single-line functions should not be flattened: //! \code{.cpp} //! struct A //! { //! int lmax() const //! { //! return lmax_; //! } //! }; //! \endcode //! but not //! \code{.cpp} //! struct A //! { //! int lmax() const { return lmax_; } //! }; //! \endcode //! - Header guards have a standard name: double underscore + file name in capital letters + double underscore //! \code{.cpp} //! #ifndef __SIRIUS_INTERNAL_H__ //! #define __SIRIUS_INTERNAL_H__ //! ... //! #endif // __SIRIUS_INTERNAL_H__ //! \endcode //! We use clang-format utility to enforce the basic formatting style. Please have a look at .clang-format config file //! in the source root folder for the definitions. //! //! Class naming convention. //! //! Problem: all 'standard' naming conventions are not satisfactory. For example, we have a class //! which does a DFT ground state. Following the common naming conventions it could be named like this: //! DFTGroundState, DftGroundState, dft_ground_state. Last two are bad, because DFT (and not Dft or dft) //! is a well recognized abbreviation. First one is band because capital G adds to DFT and we automaticaly //! read DFTG round state. //! //! Solution: we can propose the following: DFTgroundState or DFT_ground_state. The first variant still //! doens't look very good because one of the words is captalized (State) and one (ground) - is not. So we pick //! the second variant: DFT_ground_state (by the way, this is close to the Bjarne Stroustrup's naiming convention, //! where he uses first capital letter and underscores, for example class Io_obj). //! //! Some other examples: //! - class Ground_state (composed of two words) //! - class FFT_interface (composed of an abbreviation and a word) //! - class Interface_XC (composed of a word and abbreviation) //! - class Spline (single word) //! //! Exceptions are allowed if it makes sense. For example, low level utility classes like 'mdarray' (multi-dimentional //! array) or 'pstdout' (parallel standard output) are named with small letters. //!
{ "alphanum_fraction": 0.5780555556, "avg_line_length": 34.5047923323, "ext": "h", "hexsha": "15b58c021921db73a70b6904ca815bef9f371a68", "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": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "cocteautwins/SIRIUS-develop", "max_forks_repo_path": "src/sirius_internal.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "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": "cocteautwins/SIRIUS-develop", "max_issues_repo_path": "src/sirius_internal.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "8ab09ca7cc69e9a7dc76475b7b562b20d56deea3", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "cocteautwins/SIRIUS-develop", "max_stars_repo_path": "src/sirius_internal.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2576, "size": 10800 }
#pragma once #include "file_descriptor.h" #include <filesystem> #include <gsl/span> #include <random> namespace dogbox { inline void create_random_file(std::filesystem::path const &file, uint64_t const size) { file_descriptor const created = create_file(file).value(); file_descriptor const random = open_file_for_reading("/dev/urandom").value(); std::array<std::byte, 0x10000> buffer; uint64_t written = 0; while (written < size) { size_t const reading = static_cast<size_t>(std::min<uint64_t>(buffer.size(), (size - written))); ssize_t const read_result = read(random.handle, buffer.data(), reading); if (read_result < 0) { TO_DO(); } ssize_t const write_result = write(created.handle, buffer.data(), reading); if (write_result < 0) { TO_DO(); } written += reading; } } }
{ "alphanum_fraction": 0.5722891566, "avg_line_length": 30.1818181818, "ext": "h", "hexsha": "78d1e465ede97e6cf2d2624a787d4679e36e3c1e", "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_random_file.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_random_file.h", "max_line_length": 108, "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_random_file.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 217, "size": 996 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <string.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include "dnest.h" #include "model3.h" int which_level_update; int num_params; DNestFptrSet *fptrset_thismodel3; void model3() { int i, argc=0, narg=6; char **argv; argv = malloc(narg*sizeof(char *)); for(i=0; i<narg; i++) { argv[i] = malloc(200*sizeof(char)); } strcpy(argv[argc++], "dnest"); strcpy(argv[argc++], "-s"); strcpy(argv[argc++], "restart_dnest3.txt"); strcpy(argv[argc++], "-l"); //level-dependnet sampling strcpy(argv[argc++], "-g"); // tag strcpy(argv[argc++], "3"); /* setup szie of modeltype, which is used for dnest */ num_params = 2; fptrset_thismodel3 = dnest_malloc_fptrset(); /* setup functions used for dnest*/ fptrset_thismodel3->from_prior = from_prior_thismodel3; fptrset_thismodel3->log_likelihoods_cal = log_likelihoods_cal_thismodel3; fptrset_thismodel3->log_likelihoods_cal_initial = log_likelihoods_cal_thismodel3; fptrset_thismodel3->log_likelihoods_cal_restart = log_likelihoods_cal_thismodel3; fptrset_thismodel3->perturb = perturb_thismodel3; fptrset_thismodel3->print_particle = print_particle_thismodel3; fptrset_thismodel3->restart_action = restart_action_model3; /* run dnest */ dnest(argc, argv, fptrset_thismodel3, num_params, NULL, NULL, NULL, "./", "OPTIONS3", NULL, NULL); /* free memory */ dnest_free_fptrset(fptrset_thismodel3); for(i=0; i<narg; i++) free(argv[i]); free(argv); } /*====================================================*/ /* users responsible for following struct definitions */ void from_prior_thismodel3(void *model) { int i; double *params = (double *)model; for(i=0; i<num_params; i++) { params[i] = -6.0 + 12.0 * dnest_rand(); dnest_wrap(&params[i], -6.0, 6.0); } } double log_likelihoods_cal_thismodel3(const void *model) { double *params = (double *)model; double logL; double logl1; double logl2; logl1 = -0.5 * pow( (sqrt((params[0] - 3.0)* (params[0] - 3.0) + params[1]*params[1])- 2.0)/0.1, 2.0) - 0.5 * log(2.0*M_PI * 0.01); logl2 = -0.5 * pow( (sqrt((params[0] + 3.0)* (params[0] + 3.0) + params[1]*params[1])- 2.0)/0.1, 2.0) - 0.5 * log(2.0*M_PI * 0.01); double max = fmax(logl1, logl2); logL = log( exp(logl1-max) + exp(logl2-max) ) + max; return logL; } double perturb_thismodel3(void *model) { double *params = (double *)model; double logH = 0.0, width, limit1, limit2; int which = dnest_rand_int(num_params), which_level; int size_levels; which_level_update = dnest_get_which_level_update(); size_levels = dnest_get_size_levels(); which_level = which_level_update > (size_levels - 20)?(size_levels-20):which_level_update; which_level = 0; if(which_level > 0 ) { limit1 = limits[(which_level_update-1) * num_params *2 + which *2 ]; limit2 = limits[(which_level_update-1) * num_params *2 + which *2 + 1]; } else { limit1 = -6.0; limit2 = 6.0; } width = (limit2 - limit1); params[which] += width * dnest_randh(); dnest_wrap(&params[which], -6.0, 6.0); return logH; } /*=======================================================*/ void print_particle_thismodel3(FILE *fp, const void *model) { int i; double *params = (double *)model; for(i=0; i<num_params; i++) { fprintf(fp, "%f ", params[i]); } fprintf(fp, "\n"); } /*========================================================*/ void restart_action_model3(int iflag) { return; }
{ "alphanum_fraction": 0.6280947255, "avg_line_length": 25.8055555556, "ext": "c", "hexsha": "8525dbf10b1f507343499bde79e2248c97990d0a", "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": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_path": "src/model3.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_path": "src/model3.c", "max_line_length": 104, "max_stars_count": 6, "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_path": "src/model3.c", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "num_tokens": 1187, "size": 3716 }
#pragma once #include <gsl.h> #include <mitkCommon.h> #include <mitkBaseData.h> #include <vtkSmartPointer.h> #include <vtkDataArray.h> #include "SolverSetupServiceExports.h" namespace crimson { /*! \brief A class used for storing the simulation results and materials. */ class SolverSetupService_EXPORT SolutionData : public mitk::BaseData { public: mitkClassMacro(SolutionData, mitk::BaseData); mitkNewMacro1Param(Self, vtkSmartPointer<vtkDataArray>); // itkCloneMacro(Self); // mitkCloneMacro(Self); /*! * \brief Gets the data in form of a vtkDataArray. */ vtkDataArray* getArrayData() const; protected: SolutionData(vtkSmartPointer<vtkDataArray> data); virtual ~SolutionData() {} SolutionData(const Self& other) = delete; private: vtkSmartPointer<vtkDataArray> _data; void SetRequestedRegion(const itk::DataObject*) override {} void SetRequestedRegionToLargestPossibleRegion() override {} bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; } bool VerifyRequestedRegion() override { return true; } }; }
{ "alphanum_fraction": 0.7271914132, "avg_line_length": 24.8444444444, "ext": "h", "hexsha": "1b0b0e121fc61a5568701f3d7f13c0126c4fc386", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "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": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_line_length": 80, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Modules/SolverSetupService/include/SolutionData.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 267, "size": 1118 }
#include <asf_terrcorr.h> #include <stdio.h> #include <assert.h> #include <gsl/gsl_spline.h> #include <asf_raster.h> static float * read_dem(meta_parameters *meta_dem, const char *demImg) { int ns = meta_dem->general->sample_count; int nl = meta_dem->general->line_count; float *demData = MALLOC(sizeof(float)*ns*nl); FILE *fp = FOPEN(demImg, "rb"); int ii; for (ii=0; ii<nl; ++ii) { get_float_line(fp, meta_dem, ii, demData + ii*ns); asfLineMeter(ii,nl); } FCLOSE(fp); return demData; } static void sar_to_dem(meta_parameters *meta_sar, meta_parameters *meta_dem, double line_sar, double samp_sar, double *line_dem, double *samp_dem) { double lat, lon; int ret; ret = meta_get_latLon(meta_sar, line_sar, samp_sar, 0, &lat, &lon); if (ret != 0) { asfPrintError("meta_get_latLon error: line = %f, samp = %f\n", line_sar, samp_sar); } ret = meta_get_lineSamp(meta_dem, lat, lon, 0, line_dem, samp_dem); if (ret != 0) { asfPrintError("meta_get_lineSamp error: lat = %f, lon = %f\n", lat, lon); } } static double bilinear_interp_fn(double y, double x, double p00, double p10, double p01, double p11) { double x1 = 1-x; double y1 = 1-y; return p00*x1*y1 + p10*x*y1 + p01*x1*y + p11*x*y; } static float interp_demData(float *demData, int nl, int ns, double l, double s) { if (l<0 || l>=nl-1 || s<0 || s>=ns-1) { return 0; } int ix = (int)s; int iy = (int)l; int bilinear = l<3 || l>=nl-3 || s<3 || s>=ns-3; //int bilinear = 1; if (bilinear) { float p00 = demData[ix + ns*(iy )]; float p10 = demData[ix+1 + ns*(iy )]; float p01 = demData[ix + ns*(iy+1)]; float p11 = demData[ix+1 + ns*(iy+1)]; return (float)bilinear_interp_fn(s-ix, l-iy, p00, p10, p01, p11); } else { double ret, x[4], y[4], xi[4], yi[4]; int ii; for (ii=0; ii<4; ++ii) { y[0] = demData[ix-1 + ns*(iy+ii-1)]; y[1] = demData[ix + ns*(iy+ii-1)]; y[2] = demData[ix+1 + ns*(iy+ii-1)]; y[3] = demData[ix+2 + ns*(iy+ii-1)]; x[0] = ix - 1; x[1] = ix; x[2] = ix + 1; x[3] = ix + 2; gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 4); gsl_spline_init (spline, x, y, 4); yi[ii] = gsl_spline_eval(spline, s, acc); gsl_spline_free (spline); gsl_interp_accel_free (acc); xi[ii] = iy + ii - 1; } gsl_interp_accel *acc = gsl_interp_accel_alloc (); gsl_spline *spline = gsl_spline_alloc (gsl_interp_cspline, 4); gsl_spline_init (spline, xi, yi, 4); ret = gsl_spline_eval(spline, l, acc); gsl_spline_free (spline); gsl_interp_accel_free (acc); return (float)ret; } asfPrintError("Impossible."); } static void check(int num, double a, double b) { if (a==b || fabs(a-b)<0.0000001) return; asfPrintError("Failed test %d -- %f %f\n", num, a, b); } static void test_interp() { check(1, bilinear_interp_fn(.5,.5,1,1,1,1), 1); check(2, bilinear_interp_fn(.1,.1,1,1,1,1), 1); check(3, bilinear_interp_fn(.5,.5,1,1,2,2), 1.5); check(4, bilinear_interp_fn(.5,.5,1,2,1,2), 1.5); check(5, bilinear_interp_fn(.5,.5,1,2,1,2), 1.5); check(6, bilinear_interp_fn(0,0,1,2,3,4), 1); check(7, bilinear_interp_fn(1,1,1,2,3,4), 4); check(8, bilinear_interp_fn(0,1,1,2,3,4), 2); check(9, bilinear_interp_fn(1,0,1,2,3,4), 3); } static void xy_interp(int line, int samp, int line_lo, int line_hi, int samp_lo, int samp_hi, double *lines, double *samps, double *interp_line, double *interp_samp) { assert(samp>=samp_lo && samp<=samp_hi); assert(line>=line_lo && line<=line_hi); double l = (double)(line - line_lo) / (double)(line_hi - line_lo); double s = (double)(samp - samp_lo) / (double)(samp_hi - samp_lo); *interp_line = bilinear_interp_fn(l, s, lines[0], lines[1], lines[2], lines[3]); *interp_samp = bilinear_interp_fn(l, s, samps[0], samps[1], samps[2], samps[3]); } static double calc_err(meta_parameters *meta_sar, meta_parameters *meta_dem, int line_lo, int line_hi, int samp_lo, int samp_hi, double *lines, double *samps) { int l = (line_lo + line_hi) * .5; int s = (samp_lo + samp_hi) * .5; double interp_line, interp_samp, real_line, real_samp; xy_interp(l, s, line_lo, line_hi, samp_lo, samp_hi, lines, samps, &interp_line, &interp_samp); sar_to_dem(meta_sar, meta_dem, l, s, &real_line, &real_samp); asfPrintStatus(" Interp: (%f,%f)\n", interp_line, interp_samp); asfPrintStatus(" Actual: (%f,%f)\n", real_line, real_samp); return hypot(interp_line - real_line, interp_samp - real_samp); } static void get_interp_params(meta_parameters *meta_sar, meta_parameters *meta_dem, int line_lo, int line_hi, int samp_lo, int samp_hi, double *lines, double *samps) { sar_to_dem(meta_sar, meta_dem, line_lo, samp_lo, &lines[0], &samps[0]); sar_to_dem(meta_sar, meta_dem, line_lo, samp_hi, &lines[1], &samps[1]); sar_to_dem(meta_sar, meta_dem, line_hi, samp_lo, &lines[2], &samps[2]); sar_to_dem(meta_sar, meta_dem, line_hi, samp_hi, &lines[3], &samps[3]); } static int find_grid_size(meta_parameters *meta_sar, meta_parameters *meta_dem, int initial_size, double tolerance) { // pick a square centered on the center of the image // we will start with the biggest square and compare the error at the center // point between using (1) bilinear interp and (2) the real mapping // if the error is larger than the tolerance, shrink square and try again int line = meta_sar->general->line_count / 2; int samp = meta_sar->general->sample_count / 2; int sz = initial_size; double lines[4], samps[4]; while (1) { int sz2 = sz/2; int line_lo = line - sz2; int line_hi = line_lo + sz; int samp_lo = samp - sz2; int samp_hi = samp_lo + sz; get_interp_params(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi, lines, samps); double err = calc_err(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi, lines, samps); if (err < tolerance) { asfPrintStatus("Using square size %d (err %f < %f)\n", sz, err, tolerance); break; } asfPrintStatus("Square size %d, no good (err %f > %f)\n", sz, err, tolerance); sz = sz2; if (sz <= 2) { asfPrintStatus("Proceeding with grid size 1.\n"); sz = 1; break; } } return sz; } int make_gr_dem(meta_parameters *meta_sar, const char *demBase, const char *output_name) { char *demImg = appendExt(demBase, ".img"); char *demMeta = appendExt(demBase, ".meta"); int ret = make_gr_dem_ext(meta_sar, demImg, demMeta, 0, .1, output_name, 0); FREE(demImg); FREE(demMeta); return ret; } // This is the external facing function from this file. // Given the geometry from a sar image (meta_sar), and a DEM (in the files // demImg and demMeta), we write out an image/meta pair with the specified // output_name, which is a subset of the given DEM that covers the given // sar geometry. This function uses interpolations for speed, so there is // a tolerance parameter that specifies how accurate the line/sample mapping // from sar to dem geometry needs to be. // Input: // meta_parameters *meta_sar-- SAR geometry to subset the DEM // const char *demImg -- DEM data filename // const char *demMeta -- DEM metadata filename // int pad -- number of lines to add at the top/bottom/left/right // double tolerance -- how accurate the approximation mapping needs to be, // in units of pixels // const char *output_name -- output filename (basename) // int test_mode -- adds checks for the accuracy of the mapping, and // does some unit testing // Output: // no output parameters, the output is the output_name files (.img and .meta) // Return Value: // return TRUE on success, FALSE on fail // int make_gr_dem_ext(meta_parameters *meta_sar, const char *demImg, const char *demMeta, int pad, double tolerance, const char *output_name, int test_mode) { if (test_mode) test_interp(); asfPrintStatus("Reading DEM...\n"); meta_parameters *meta_dem = meta_read(demMeta); float *demData = read_dem(meta_dem, demImg); int dnl = meta_dem->general->line_count; int dns = meta_dem->general->sample_count; char *outImg = appendExt(output_name, ".img"); char *output_name_tmp, *outImgTmp; // do not do DEM smoothing if the DEM pixel size is better or close to the // SAR image's pixel size. int do_averaging = TRUE; if (meta_dem->general->y_pixel_size - 10 < meta_sar->general->y_pixel_size) do_averaging = FALSE; asfPrintStatus("Averaging: %s (DEM %f, SAR: %f)\n", do_averaging ? "YES" : "NO", meta_dem->general->y_pixel_size, meta_sar->general->y_pixel_size); if (do_averaging) { output_name_tmp = appendStr(output_name, "_unsmoothed"); outImgTmp = appendExt(output_name_tmp, ".img"); } else { output_name_tmp = STRDUP(output_name); outImgTmp = STRDUP(outImg); } // add the padding if requested meta_parameters *meta_out = meta_copy(meta_sar); meta_out->general->line_count += pad*2; meta_out->general->sample_count += pad*2; meta_out->general->start_line -= pad; meta_out->general->start_sample -= pad; // fixing up the output metadata. Note that we must keep the SAR section // intact since that specifies our geometry which is the whole point of // this exercise. strcpy(meta_out->general->basename, meta_dem->general->basename); strcpy(meta_out->general->sensor, MAGIC_UNSET_STRING); strcpy(meta_out->general->processor, MAGIC_UNSET_STRING); strcpy(meta_out->general->mode, MAGIC_UNSET_STRING); strcpy(meta_out->general->sensor_name, MAGIC_UNSET_STRING); meta_out->general->image_data_type = DEM; meta_out->general->radiometry = MAGIC_UNSET_INT; strcpy(meta_out->general->acquisition_date, meta_dem->general->acquisition_date); meta_out->general->orbit = MAGIC_UNSET_INT; meta_out->general->orbit_direction = MAGIC_UNSET_CHAR; meta_out->general->frame = MAGIC_UNSET_INT; meta_out->general->band_count = 1; strcpy(meta_out->general->bands, "DEM"); int nl = meta_out->general->line_count; int ns = meta_out->general->sample_count; // finding the right grid size int size = find_grid_size(meta_sar, meta_dem, 512, .1*tolerance); asfPrintStatus("Creating ground range image...\n"); float *buf = MALLOC(sizeof(float)*ns*size); FILE *fpOut = FOPEN(outImgTmp, "wb"); // these are for tracking the quality of the bilinear interp // not used if test_mode is false int num_out_of_tol = 0; int num_checked = 0; int num_bad = 0; double max_err = 0; double avg_err = 0; int ii, jj; for (ii=0; ii<nl; ii += size) { int line_lo = ii; int line_hi = ii + size; for (jj=0; jj<ns; jj += size) { double lines[4], samps[4]; int samp_lo = jj; int samp_hi = jj + size; get_interp_params(meta_sar, meta_dem, line_lo, line_hi, samp_lo, samp_hi, lines, samps); int iii, jjj; for (iii=0; iii<size; ++iii) { for (jjj=0; jjj<size && jj+jjj<ns; ++jjj) { int index = iii*ns + jj + jjj; assert(index < ns*size); double line_out, samp_out; xy_interp(ii+iii, jj+jjj, line_lo, line_hi, samp_lo, samp_hi, lines, samps, &line_out, &samp_out); // random checking of the quality of our interpolations if (test_mode && iii%11==0 && jjj%13==0) { double real_line, real_samp; sar_to_dem(meta_sar, meta_dem, ii+iii, jj+jjj, &real_line, &real_samp); double err = hypot(real_line - line_out, real_samp - samp_out); avg_err += err; if (err > max_err) max_err = err; if (err > tolerance) { asfPrintStatus("Out of tolerance at %d,%d: (%f,%f) vs (%f,%f) -> %f\n", ii+iii, jj+jjj, line_out, samp_out, real_line, real_samp, err); ++num_out_of_tol; } if (err > .5) { asfPrintStatus("Error is larger than 1 pixel!\n"); ++num_bad; } ++num_checked; } buf[index] = interp_demData(demData, dnl, dns, line_out, samp_out); } } } put_float_lines(fpOut, meta_out, ii, size, buf); asfPrintStatus("Completed %.1f%% \r", 100.*ii/(double)nl); } asfPrintStatus("Completed 100%% \n"); if (test_mode) { asfPrintStatus("Tolerance was %f\n", tolerance); asfPrintStatus("%d/%d checked pixels had error exceeding tolerance. (%.1f%%)\n", num_out_of_tol, num_checked, 100.*num_out_of_tol/(double)num_checked); asfPrintStatus("%d/%d checked pixels had error larger than half a pixel. (%.1f%%)\n", num_bad, num_checked, 100.*num_bad/(double)num_checked); asfPrintStatus("Maximum error: %f pixels\n", max_err); avg_err /= (double)num_checked; asfPrintStatus("Average error: %f pixels\n", avg_err); } FCLOSE(fpOut); meta_write(meta_out, outImgTmp); meta_free(meta_out); meta_free(meta_dem); FREE(buf); FREE(demData); // now apply 3x3 filter if (do_averaging) { asfPrintStatus("Smoothing with 3x3 kernel ...\n"); smooth(outImgTmp, outImg, 3, EDGE_TRUNCATE); } FREE(outImg); FREE(outImgTmp); FREE(output_name_tmp); return FALSE; }
{ "alphanum_fraction": 0.6291711907, "avg_line_length": 33.0502392344, "ext": "c", "hexsha": "50524353d8b51efbc6a1d4d649b3277854c9ee16", "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_terrcorr/make_gr_dem.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_terrcorr/make_gr_dem.c", "max_line_length": 89, "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_terrcorr/make_gr_dem.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": 4200, "size": 13815 }
/* ode-initval2/rk2imp.c * * Copyright (C) 2009, 2010 Tuomo Keskitalo * * 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. */ /* Based on rk2imp.c by Gerard Jungman */ /* Runge-Kutta 2, Gaussian implicit. Also known as implicit midpoint rule. Error estimation is carried out by the step doubling method. */ /* Reference: Ascher, U.M., Petzold, L.R., Computer methods for ordinary differential and differential-algebraic equations, SIAM, Philadelphia, 1998. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv2.h> #include "odeiv_util.h" #include "rksubs.c" #include "modnewton1.c" /* Stage of method */ #define RK2IMP_STAGE 1 typedef struct { gsl_matrix *A; /* Runge-Kutta coefficients */ double *y_onestep; /* Result with one step */ double *y_twostep; /* Result with two half steps */ double *ytmp; /* Temporary work space */ double *y_save; /* Backup space */ double *YZ; /* Runge-Kutta points */ double *fYZ; /* Derivatives at YZ */ gsl_matrix *dfdy; /* Jacobian matrix */ double *dfdt; /* time derivative of f */ modnewton1_state_t *esol; /* nonlinear equation solver */ double *errlev; /* desired error level of y */ const gsl_odeiv2_driver *driver; /* pointer to driver object */ } rk2imp_state_t; static void * rk2imp_alloc (size_t dim) { rk2imp_state_t *state = (rk2imp_state_t *) malloc (sizeof (rk2imp_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for rk2imp_state", GSL_ENOMEM); } state->A = gsl_matrix_alloc (RK2IMP_STAGE, RK2IMP_STAGE); if (state->A == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for A", GSL_ENOMEM); } state->y_onestep = (double *) malloc (dim * sizeof (double)); if (state->y_onestep == 0) { gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM); } state->y_twostep = (double *) malloc (dim * sizeof (double)); if (state->y_twostep == 0) { free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM); } state->ytmp = (double *) malloc (dim * sizeof (double)); if (state->ytmp == 0) { free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM); } state->y_save = (double *) malloc (dim * sizeof (double)); if (state->y_save == 0) { free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for y_save", GSL_ENOMEM); } state->YZ = (double *) malloc (dim * RK2IMP_STAGE * sizeof (double)); if (state->YZ == 0) { free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for YZ", GSL_ENOMEM); } state->fYZ = (double *) malloc (dim * RK2IMP_STAGE * sizeof (double)); if (state->fYZ == 0) { free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for fYZ", GSL_ENOMEM); } state->dfdt = (double *) malloc (dim * sizeof (double)); if (state->dfdt == 0) { free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for dfdt", GSL_ENOMEM); } state->dfdy = gsl_matrix_alloc (dim, dim); if (state->dfdy == 0) { free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for dfdy", GSL_ENOMEM); } state->esol = modnewton1_alloc (dim, RK2IMP_STAGE); if (state->esol == 0) { gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for esol", GSL_ENOMEM); } state->errlev = (double *) malloc (dim * sizeof (double)); if (state->errlev == 0) { modnewton1_free (state->esol); gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); GSL_ERROR_NULL ("failed to allocate space for errlev", GSL_ENOMEM); } state->driver = NULL; return state; } static int rk2imp_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv2_system * sys) { /* Makes a Gaussian implicit 4th order Runge-Kutta step with size h and estimates the local error of the step by step doubling. */ rk2imp_state_t *state = (rk2imp_state_t *) vstate; double *const y_onestep = state->y_onestep; double *const y_twostep = state->y_twostep; double *const ytmp = state->ytmp; double *const y_save = state->y_save; double *const YZ = state->YZ; double *const fYZ = state->fYZ; gsl_matrix *const dfdy = state->dfdy; double *const dfdt = state->dfdt; double *const errlev = state->errlev; const modnewton1_state_t *esol = state->esol; /* Runge-Kutta coefficients */ gsl_matrix *A = state->A; const double b[] = { 1.0 }; const double c[] = { 0.5 }; gsl_matrix_set (A, 0, 0, 0.5); if (esol == NULL) { GSL_ERROR ("no non-linear equation solver speficied", GSL_EINVAL); } /* Get desired error levels via gsl_odeiv2_control object through driver object, which is a requirement for this stepper. */ if (state->driver == NULL) { return GSL_EFAULT; } else { size_t i; for (i = 0; i < dim; i++) { if (dydt_in != NULL) { gsl_odeiv2_control_errlevel (state->driver->c, y[i], dydt_in[i], h, i, &errlev[i]); } else { gsl_odeiv2_control_errlevel (state->driver->c, y[i], 0.0, h, i, &errlev[i]); } } } /* Evaluate Jacobian for modnewton1 */ { int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt); if (s != GSL_SUCCESS) { return s; } } /* Calculate a single step with size h */ { int s = modnewton1_init ((void *) esol, A, h, dfdy, sys); if (s != GSL_SUCCESS) { return s; } } { int s = modnewton1_solve ((void *) esol, A, c, t, h, y, sys, YZ, errlev); if (s != GSL_SUCCESS) { return s; } } { int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { int s = rksubs (y_onestep, h, y, fYZ, b, RK2IMP_STAGE, dim); if (s != GSL_SUCCESS) { return s; } } /* Error estimation by step doubling */ { int s = modnewton1_init ((void *) esol, A, h / 2.0, dfdy, sys); if (s != GSL_SUCCESS) { return s; } } /* 1st half step */ { int s = modnewton1_solve ((void *) esol, A, c, t, h / 2.0, y, sys, YZ, errlev); if (s != GSL_SUCCESS) return s; } { int s = GSL_ODEIV_FN_EVAL (sys, t + c[0] * h / 2.0, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { int s = rksubs (ytmp, h / 2.0, y, fYZ, b, RK2IMP_STAGE, dim); if (s != GSL_SUCCESS) { return s; } } /* Save original y values in case of error */ DBL_MEMCPY (y_save, y, dim); /* 2nd half step */ { int s = modnewton1_solve ((void *) esol, A, c, t + h / 2.0, h / 2.0, ytmp, sys, YZ, errlev); if (s != GSL_SUCCESS) { return s; } } { int s = GSL_ODEIV_FN_EVAL (sys, t + h / 2.0 + c[0] * h / 2.0, YZ, fYZ); if (s != GSL_SUCCESS) { return s; } } { /* Note: rk2imp returns y using the results from two half steps instead of the single step since the results are freely available and more precise. */ int s = rksubs (y_twostep, h / 2.0, ytmp, fYZ, b, RK2IMP_STAGE, dim); if (s != GSL_SUCCESS) { DBL_MEMCPY (y, y_save, dim); return s; } } DBL_MEMCPY (y, y_twostep, dim); /* Error estimation */ { size_t i; for (i = 0; i < dim; i++) { yerr[i] = ODEIV_ERR_SAFETY * 0.5 * fabs (y_twostep[i] - y_onestep[i]) / 3.0; } } /* Derivatives at output */ if (dydt_out != NULL) { int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out); if (s != GSL_SUCCESS) { /* Restore original values */ DBL_MEMCPY (y, y_save, dim); return s; } } return GSL_SUCCESS; } static int rk2imp_set_driver (void *vstate, const gsl_odeiv2_driver * d) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; state->driver = d; return GSL_SUCCESS; } static int rk2imp_reset (void *vstate, size_t dim) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; DBL_ZERO_MEMSET (state->y_onestep, dim); DBL_ZERO_MEMSET (state->y_twostep, dim); DBL_ZERO_MEMSET (state->ytmp, dim); DBL_ZERO_MEMSET (state->y_save, dim); DBL_ZERO_MEMSET (state->YZ, dim); DBL_ZERO_MEMSET (state->fYZ, dim); return GSL_SUCCESS; } static unsigned int rk2imp_order (void *vstate) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 2; } static void rk2imp_free (void *vstate) { rk2imp_state_t *state = (rk2imp_state_t *) vstate; free (state->errlev); modnewton1_free (state->esol); gsl_matrix_free (state->dfdy); free (state->dfdt); free (state->fYZ); free (state->YZ); free (state->y_save); free (state->ytmp); free (state->y_twostep); free (state->y_onestep); gsl_matrix_free (state->A); free (state); } static const gsl_odeiv2_step_type rk2imp_type = { "rk2imp", /* name */ 1, /* can use dydt_in? */ 1, /* gives exact dydt_out? */ &rk2imp_alloc, &rk2imp_apply, &rk2imp_set_driver, &rk2imp_reset, &rk2imp_order, &rk2imp_free }; const gsl_odeiv2_step_type *gsl_odeiv2_step_rk2imp = &rk2imp_type;
{ "alphanum_fraction": 0.5766465109, "avg_line_length": 24.0905511811, "ext": "c", "hexsha": "9abac5dc9ce3112615b85b20740d9c1a71f85b5b", "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": "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/ode-initval2/rk2imp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval2/rk2imp.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/ode-initval2/rk2imp.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": 3652, "size": 12238 }
#ifndef SYSTEM_H_ #define SYSTEM_H_ #pragma once //#include <gsl/gsl_matrix.h> #include <fstream> //#include <gsl/gsl_vector.h> //#include <gsl/gsl_math.h> //#include <gsl/gsl_multimin.h> //#include <gsl/gsl_errno.h> #include <memory> #include <math.h> #include <thrust/extrema.h> #include <thrust/sort.h> #include <thrust/copy.h> #include <thrust/for_each.h> #include <thrust/transform.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/tuple.h> #include <thrust/device_vector.h> #include <thrust/device_ptr.h> #include <thrust/remove.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/copy.h> #include <thrust/execution_policy.h> #include <thrust/pair.h> #include <stdint.h> // struct CapsidInfoVecs { thrust::device_vector<int> id_bucket; //bucket id // bucket value means global rank of a certain point thrust::device_vector<int> id_value;//node id thrust::device_vector<double> nodeLocX; thrust::device_vector<double> nodeLocY; thrust::device_vector<double> nodeLocZ; //used for capside linear springs binding to membrane thrust::device_vector<int> tempMembraneId; thrust::device_vector<int> tempCapsideId; thrust::device_vector<double> tempLengthsPairs; thrust::device_vector<double> tempNodeForceX; thrust::device_vector<double> tempNodeForceY; thrust::device_vector<double> tempNodeForceZ; //used for capside repulsion int factor = 10;//number of default nodes repulsion can interact with. thrust::device_vector<int> tempNodeIdUnreduced; thrust::device_vector<double> tempNodeForceXUnreduced; thrust::device_vector<double> tempNodeForceYUnreduced; thrust::device_vector<double> tempNodeForceZUnreduced; thrust::device_vector<int> tempNodeIdReduced; thrust::device_vector<double> tempNodeForceXReduced; thrust::device_vector<double> tempNodeForceYReduced; thrust::device_vector<double> tempNodeForceZReduced; double spring_constant = 10.0; double length_zero = 0.97; double length_cutoff = 1.63; int maxNodeCount; double viscosity = 1.0; double forceX = 0.0; double forceY = 0.0; double forceZ = 0.0; int num_connections=0; }; //Data Structure for node location. velocity and force struct CoordInfoVecs { thrust::device_vector<double> scaling_per_edge; thrust::device_vector<int> nodes2Triangles_1; thrust::device_vector<int> nodes2Triangles_2; thrust::device_vector<int> nodes2Triangles_3; thrust::device_vector<int> nodes2Triangles_4; thrust::device_vector<int> nodes2Triangles_5; thrust::device_vector<int> nodes2Triangles_6; thrust::device_vector<int> nodes2Triangles_7; thrust::device_vector<int> nodes2Triangles_8; thrust::device_vector<int> nodes2Triangles_9; // thrust::device_vector<int> nodes2Triangles_10; // thrust::device_vector<int> nodes2Triangles_11; // thrust::device_vector<int> nodes2Triangles_12; thrust::device_vector<double> SurfaceNormalX; thrust::device_vector<double> SurfaceNormalY; thrust::device_vector<double> SurfaceNormalZ; thrust::device_vector<int> nndata1; thrust::device_vector<int> nndata2; thrust::device_vector<int> nndata3; thrust::device_vector<int> nndata4; thrust::device_vector<int> nndata5; thrust::device_vector<int> nndata6; thrust::device_vector<int> nndata7; thrust::device_vector<int> nndata8; thrust::device_vector<int> nndata9; // thrust::device_vector<int> nndata10; // thrust::device_vector<int> nndata11; // thrust::device_vector<int> nndata12; thrust::device_vector<bool> isNodeFixed; //GLOBAL COORDS // X,Y,Z, location, velocity and force of all nodes thrust::device_vector<double> prevNodeLocX; thrust::device_vector<double> prevNodeLocY; thrust::device_vector<double> prevNodeLocZ; thrust::device_vector<double> prevNodeForceX; thrust::device_vector<double> prevNodeForceY; thrust::device_vector<double> prevNodeForceZ; thrust::device_vector<double> nodeLocX; thrust::device_vector<double> nodeLocY; thrust::device_vector<double> nodeLocZ; thrust::device_vector<double> nodeForceX; thrust::device_vector<double> nodeForceY; thrust::device_vector<double> nodeForceZ; thrust::device_vector<double> tempNodeForceXReduced; thrust::device_vector<double> tempNodeForceYReduced; thrust::device_vector<double> tempNodeForceZReduced; thrust::device_vector<double> tempNodeForceXUnreduced; thrust::device_vector<double> tempNodeForceYUnreduced; thrust::device_vector<double> tempNodeForceZUnreduced; //LOCAL COORDS //indices of each triangle int num_triangles; thrust::device_vector<int> triangles2Nodes_1; thrust::device_vector<int> triangles2Nodes_2; thrust::device_vector<int> triangles2Nodes_3; //indices of each edge int num_edges; thrust::device_vector<int> edges2Nodes_1; thrust::device_vector<int> edges2Nodes_2; //indices of 2 triangle on each edge thrust::device_vector<int> edges2Triangles_1; thrust::device_vector<int> edges2Triangles_2; //indices of edges on each triangle. thrust::device_vector<int> triangles2Edges_1; thrust::device_vector<int> triangles2Edges_2; thrust::device_vector<int> triangles2Edges_3; }; //struct used for linking of nodes in network struct AuxVecs { // bucket key means which bucket ID does a certain point fit into thrust::device_vector<int> id_bucket; //bucket id // bucket value means global rank of a certain point thrust::device_vector<int> id_value;//node id // bucket key expanded means what are the bucket IDs are the neighbors of a certain point thrust::device_vector<int> id_bucket_expanded; // bucket value expanded means each point ( represented by its global rank) will have multiple copies thrust::device_vector<int> id_value_expanded; // begin position of a keys in id_bucket_expanded and id_value_expanded //entry keyBegin[bucketKey] returns start of indices to link thrust::device_vector<int> keyBegin; // end position of a keys in id_bucket_expanded and id_value_expanded thrust::device_vector<int> keyEnd; int endIndexid_bucket; }; struct DomainParams { double minX; double maxX; double minY; double maxY; double minZ; double maxZ; double originMinX; double originMaxX; double originMinY; double originMaxY; double originMinZ; double originMaxZ; double gridSpacing = 1.5;//bucket scheme search distance, must be larger than cutoff for capsid int XBucketCount; int YBucketCount; int ZBucketCount; int totalBucketCount = 0; }; struct LJInfoVecs{ double LJ_PosX; double LJ_PosY; double LJ_PosZ; thrust::device_vector<double> LJ_PosX_all; thrust::device_vector<double> LJ_PosY_all; thrust::device_vector<double> LJ_PosZ_all; double Rmin_M=0.97;//1.0; double Rcutoff_M=0.97;//1.0; double Rmin_LJ; double Rcutoff_LJ; double epsilon_M=1.0; double epsilon_M_att1; double epsilon_M_att2; double epsilon_M_rep1; double epsilon_M_rep2; double epsilon_LJ; double epsilon_LJ_rep1; double epsilon_LJ_rep2; double spring_constant; thrust::device_vector<int> node_id_close; double lj_energy_M; double lj_energy_LJ; double forceX; double forceY; double forceZ; thrust::device_vector<double> forceX_all; thrust::device_vector<double> forceY_all; thrust::device_vector<double> forceZ_all; }; struct AreaTriangleInfoVecs { int factor = 3;//used for reduction double initial_area = 0.0048013; double spring_constant; double spring_constant_weak; double area_triangle_energy; thrust::device_vector<int> tempNodeIdUnreduced; thrust::device_vector<double> tempNodeForceXUnreduced; thrust::device_vector<double> tempNodeForceYUnreduced; thrust::device_vector<double> tempNodeForceZUnreduced; thrust::device_vector<int> tempNodeIdReduced; thrust::device_vector<double> tempNodeForceXReduced; thrust::device_vector<double> tempNodeForceYReduced; thrust::device_vector<double> tempNodeForceZReduced; }; struct BendingTriangleInfoVecs { int numBendingSprings=0; int factor = 4;//used for reduction double spring_constant; double spring_constant_weak; double spring_constant_raft; double spring_constant_coat; double initial_angle = 0.0;//radians double initial_angle_raft; double initial_angle_coat; double bending_triangle_energy; thrust::device_vector<int> tempNodeIdUnreduced; thrust::device_vector<double> tempNodeForceXUnreduced; thrust::device_vector<double> tempNodeForceYUnreduced; thrust::device_vector<double> tempNodeForceZUnreduced; thrust::device_vector<int> tempNodeIdReduced; thrust::device_vector<double> tempNodeForceXReduced; thrust::device_vector<double> tempNodeForceYReduced; thrust::device_vector<double> tempNodeForceZReduced; }; struct LinearSpringInfoVecs { int factor = 2;//used for reduction double spring_constant; double spring_constant_weak; double spring_constant_att1; double spring_constant_att2; double spring_constant_rep1; //This is the "D" in Morse potential double spring_constant_rep2; //This is the "a" in Morse potential double linear_spring_energy; double memrepulsion_energy; double scalar_edge_length; thrust::device_vector<double> edge_initial_length; thrust::device_vector<int> tempNodeIdUnreduced; thrust::device_vector<double> tempNodeForceXUnreduced; thrust::device_vector<double> tempNodeForceYUnreduced; thrust::device_vector<double> tempNodeForceZUnreduced; thrust::device_vector<int> tempNodeIdReduced; thrust::device_vector<double> tempNodeForceXReduced; thrust::device_vector<double> tempNodeForceYReduced; thrust::device_vector<double> tempNodeForceZReduced; }; struct GeneralParams{ double kT; double kT_growth; double tau; int solve_time=100; double Rmin = 1.0; //Current mesh minimum edge length, subject to change. double abs_Rmin; int iteration = 0; int maxNodeCount; int maxNodeCountLJ; double length_scale; //parameters for advancing timestep and determining equilibrium double dt; double nodeMass = 1.0; int edges_in_upperhem_list_length; double growth_energy_scaling; thrust::device_vector<int> edge_to_ljparticle; thrust::device_vector<int> nodes_in_upperhem; thrust::device_vector<int> edges_in_upperhem; thrust::device_vector<int> edges_in_upperhem_list; thrust::device_vector<int> triangles_in_upperhem; thrust::device_vector<int> boundaries_in_upperhem; thrust::device_vector<double> angle_per_edge; double centerX = 0.0; double centerY = 0.0; double centerZ = 0.0; double current_total_volume; double true_current_total_volume; double eq_total_volume; double volume_spring_constant; double volume_energy; double eq_total_boundary_length; double line_tension_energy; double line_tension_constant; double safeguardthreshold; //int num_of_triangles; //int num_of_edges; int true_num_edges; double insertion_energy_cost; double strain_threshold; int SCALE_TYPE; double scaling_pow; double gausssigma; double hilleqnconst; double hilleqnpow; thrust::device_vector<int> no_weakening; double septin_ring_z; double boundary_z; }; class Storage; class SystemBuilder; struct HostSetInfoVecs; class System { public: std::weak_ptr<SystemBuilder> weak_bld_ptr; GeneralParams generalParams; DomainParams domainParams; AuxVecs auxVecs; CoordInfoVecs coordInfoVecs; CapsidInfoVecs capsidInfoVecs; LinearSpringInfoVecs linearSpringInfoVecs; BendingTriangleInfoVecs bendingTriangleInfoVecs; AreaTriangleInfoVecs areaTriangleInfoVecs; LJInfoVecs ljInfoVecs; std::shared_ptr<Storage> storage; //gsl_vector* df; //gsl_vector* locations; public: System(); void set_weak_builder(std::weak_ptr<SystemBuilder> _weak_bld_ptr); void PrintForce(); void initializeSystem(HostSetInfoVecs& hostSetInfoVecs); void assignStorage(std::shared_ptr<Storage> _storage); void solveSystem(); void setExtras(); void setBucketScheme(); //void Solve_Forces(const gsl_vector* temp_locations); void Solve_Forces(); //double Solve_Energy(const gsl_vector* temp_locations); //void dev_to_gsl_loc_update(gsl_vector* temp_locations); //void gsl_to_dev_loc_update(const gsl_vector* temp_locations); }; #endif /*POLYMERSYSTEM_H_*/
{ "alphanum_fraction": 0.770698577, "avg_line_length": 28.6960556845, "ext": "h", "hexsha": "87df4c3e000c678d80aba5694a722959d284409e", "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": "cfdd434f4643b0ac0800d00ec56d53a888bec990", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "librastar1985/Yeast_Budding_20200214", "max_forks_repo_path": "System.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cfdd434f4643b0ac0800d00ec56d53a888bec990", "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": "librastar1985/Yeast_Budding_20200214", "max_issues_repo_path": "System.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "cfdd434f4643b0ac0800d00ec56d53a888bec990", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "librastar1985/Yeast_Budding_20200214", "max_stars_repo_path": "System.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3090, "size": 12368 }
#ifndef __GSL_PERMUTE_MATRIX_H__ #define __GSL_PERMUTE_MATRIX_H__ #include <gsl/gsl_permute_matrix_complex_long_double.h> #include <gsl/gsl_permute_matrix_complex_double.h> #include <gsl/gsl_permute_matrix_complex_float.h> #include <gsl/gsl_permute_matrix_long_double.h> #include <gsl/gsl_permute_matrix_double.h> #include <gsl/gsl_permute_matrix_float.h> #include <gsl/gsl_permute_matrix_ulong.h> #include <gsl/gsl_permute_matrix_long.h> #include <gsl/gsl_permute_matrix_uint.h> #include <gsl/gsl_permute_matrix_int.h> #include <gsl/gsl_permute_matrix_ushort.h> #include <gsl/gsl_permute_matrix_short.h> #include <gsl/gsl_permute_matrix_uchar.h> #include <gsl/gsl_permute_matrix_char.h> #endif /* __GSL_PERMUTE_MATRIX_H__ */
{ "alphanum_fraction": 0.8362892224, "avg_line_length": 29.32, "ext": "h", "hexsha": "aa8e67211e3a6c7a29b7dff93e5b509ee133df8b", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.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/permutation/gsl_permute_matrix.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/permutation/gsl_permute_matrix.h", "max_line_length": 55, "max_stars_count": 7, "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_permute_matrix.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 207, "size": 733 }
#ifndef DEPTH_TO_BEARING_H_ZXFA9HGG #define DEPTH_TO_BEARING_H_ZXFA9HGG #include <cmath> #include <gsl/gsl> #include <limits> #include <sens_loc/camera_models/concepts.h> #include <sens_loc/camera_models/utility.h> #include <sens_loc/conversion/util.h> #include <sens_loc/math/constants.h> #include <sens_loc/math/coordinate.h> #include <sens_loc/math/image.h> #include <sens_loc/math/triangles.h> #include <sens_loc/util/correctness_util.h> #include <taskflow/taskflow.hpp> namespace sens_loc::conversion { /// Convert the image \p depth_image to an bearing angle image. /// This function returns a new image with the same dimension as \p depth_image. /// /// \tparam Direction the direction for neighbourhood-relationship between /// pixels that form the bearing angle /// \tparam Real precision to calculate in, needs to be floating-point /// \tparam Intrinsic camera model that projects pixel to the unit sphere /// \param depth_image range image that was taken by a sensor with the /// calibration from \p intrinsic /// \param intrinsic camera model to calculate the angle between light /// rays that correspond to pixels /// \returns cv::Mat<Real> with each pixel the bearing angle (radians) in /// \p Direction. Invalid depth values result in 0 as result. // /// \note Depth images are orthografic and require conversion first! /// \sa conversion::depth_to_laserscan /// \sa camera_models::is_intrinsic_v /// /// \pre \p depth_image to have 1 channel /// \pre \p depth_image == laser-scan like image! /// \pre \p depth_image is not empty /// \pre \p the underlying type of \p depth_image matches \p PixelType /// \pre \p intrinsic matches sensor that took the image, prior preprocessing /// \post each bearing angle is in the range \f$[0, \pi)\f$ /// is of course possible with matching changes in the \p depth_image. template <direction Direction, template <typename> typename Intrinsic, typename Real = float> math::image<Real> depth_to_bearing(const math::image<Real>& depth_image, const Intrinsic<Real>& intrinsic) noexcept; /// This function provides are parallelized version of the conversion /// functionality. /// /// This function creates a taskflow for the row-wise parallel calculation /// of the bearing angle image. /// Only differences are documented here. /// \param[in] depth_image,intrinsic the same /// \param[out] ba_image result image that will be created with parallel /// processing /// \param[inout] flow parallel flow type that is used to parallelize the outer /// for loop over all rows. /// \returns synchronization points before and after the calculation of the /// bearing angle image. /// \sa depth_to_bearing template <direction Direction, template <typename> typename Intrinsic, typename Real = float> std::pair<tf::Task, tf::Task> par_depth_to_bearing(const math::image<Real>& depth_image, const Intrinsic<Real>& intrinsic, math::image<Real>& ba_image, tf::Taskflow& flow) noexcept; /// Convert a bearing angle image to an image with integer types. /// This function scales the bearing angles between /// [PixelType::min, PixelType::max] for the angles in range (0, PI). /// /// \tparam Real underyling type of the \p bearing_image, floating-point /// \tparam PixelType target type for the converted image that is returned, /// arithmetic type (integer or floating-point) /// \param bearing_image calculated /// bearing angle image /// \returns the bearing angle image is converted to a "normal" image that can /// be displayed and stored with normal image visualization tools. /// \pre the underlying type of \p bearing_image is \p Real /// \pre range of pixel is in \p bearinge_image \f$[0, \pi)\f$ /// \post the underlying type of the result is \p PixelType /// \post range of pixel in result is \f$[PixelType_{min}, PixelType_{max}]\f$ /// \sa conversion::depth_to_bearing template <typename Real = float, typename PixelType = ushort> math::image<PixelType> convert_bearing(const math::image<Real>& bearing_image) noexcept; namespace detail { inline int get_du(direction dir) { switch (dir) { case direction::antidiagonal: case direction::diagonal: case direction::horizontal: return -1; case direction::vertical: return 0; } UNREACHABLE("Only 4 directions are possible"); // LCOV_EXCL_LINE } inline int get_dv(direction dir) { switch (dir) { case direction::diagonal: case direction::vertical: return -1; case direction::horizontal: return 0; case direction::antidiagonal: return 1; } UNREACHABLE("Only 4 directions are possible"); // LCOV_EXCL_LINE } /// Provide a general accessor for the pixels that provide depth information /// to calculate the bearing angle. template <typename Real, direction Direction> class pixel { public: pixel() : _du{get_du(Direction)} , _dv{get_dv(Direction)} {} /// \returns (u, v) for the prior point depending on the direction. math::pixel_coord<int> operator()(const math::pixel_coord<int>& p) const noexcept { return {p.u() + _du, p.v() + _dv}; } private: const int _du = 0; const int _dv = 0; }; inline int get_x_start(direction dir) { switch (dir) { case direction::horizontal: case direction::antidiagonal: case direction::diagonal: return 1; case direction::vertical: return 0; } UNREACHABLE("Only 4 directions are possible"); // LCOV_EXCL_LINE } inline int get_y_start(direction dir) { switch (dir) { case direction::horizontal: case direction::antidiagonal: return 0; case direction::diagonal: case direction::vertical: return 1; } UNREACHABLE("Only 4 directions are possible"); // LCOV_EXCL_LINE } inline int get_dy_end(direction dir) { switch (dir) { case direction::antidiagonal: return 1; case direction::horizontal: case direction::diagonal: case direction::vertical: return 0; } UNREACHABLE("Only 4 directions are possible"); // LCOV_EXCL_LINE } /// Define the start and end iterator for each bearing angle direction. template <direction Direction> struct pixel_range { pixel_range(const cv::Mat& depth_image) noexcept : x_start{get_x_start(Direction)} , x_end{depth_image.cols} , y_start{get_y_start(Direction)} , y_end{depth_image.rows - get_dy_end(Direction)} {} const int x_start; const int x_end; const int y_start; const int y_end; }; template <typename Real, typename RangeLimits, typename PriorAccess, template <typename> typename Intrinsic> inline void bearing_inner(const RangeLimits& r, const PriorAccess& prior_accessor, const int v, const math::image<Real>& depth_image, const Intrinsic<Real>& intrinsic, math::image<Real>& ba_image) { for (int u = r.x_start; u < r.x_end; ++u) { const math::pixel_coord<int> central(u, v); const math::pixel_coord<int> prior = prior_accessor(central); const auto d_i = depth_image.at(central); const auto d_j = depth_image.at(prior); Expects(d_i >= Real(0.)); Expects(d_j >= Real(0.)); const Real d_phi = camera_models::phi(intrinsic, central, prior); // A depth==0 means there is no measurement at this pixel. const Real angle = (d_i == Real(0.) || d_j == Real(0.)) ? Real(0.) : math::bearing_angle<Real>(d_i, d_j, std::cos(d_phi)); Ensures(angle >= Real(0.)); Ensures(angle < math::pi<Real>); ba_image.at(central) = angle; } } } // namespace detail template <direction Direction, template <typename> typename Intrinsic, typename Real> inline math::image<Real> depth_to_bearing(const math::image<Real>& depth_image, const Intrinsic<Real>& intrinsic) noexcept { static_assert(camera_models::is_intrinsic_v<Intrinsic, Real>); static_assert(std::is_floating_point_v<Real>); Expects(depth_image.w() == intrinsic.w()); Expects(depth_image.h() == intrinsic.h()); using namespace detail; const pixel<Real, Direction> prior_accessor; const pixel_range<Direction> r{depth_image.data()}; // Image of Reals, that will be converted after the full calculation. cv::Mat ba(depth_image.h(), depth_image.w(), math::detail::get_opencv_type<Real>()); ba = Real(0.); math::image<Real> ba_image(std::move(ba)); for (int v = r.y_start; v < r.y_end; ++v) detail::bearing_inner(r, prior_accessor, v, depth_image, intrinsic, ba_image); Ensures(ba_image.h() == depth_image.h()); Ensures(ba_image.w() == depth_image.w()); return ba_image; } template <direction Direction, template <typename> typename Intrinsic, typename Real> inline std::pair<tf::Task, tf::Task> par_depth_to_bearing(const math::image<Real>& depth_image, const Intrinsic<Real>& intrinsic, math::image<Real>& ba_image, tf::Taskflow& flow) noexcept { static_assert(camera_models::is_intrinsic_v<Intrinsic, Real>); static_assert(std::is_floating_point_v<Real>); using namespace detail; Expects(depth_image.w() == intrinsic.w()); Expects(depth_image.h() == intrinsic.h()); Expects(ba_image.w() == depth_image.w()); Expects(ba_image.h() == depth_image.h()); const pixel<Real, Direction> prior_accessor; const pixel_range<Direction> r{depth_image.data()}; auto sync_points = flow.parallel_for( r.y_start, r.y_end, 1, [prior_accessor, r, &depth_image, &intrinsic, &ba_image](int v) { detail::bearing_inner(r, prior_accessor, v, depth_image, intrinsic, ba_image); }); return sync_points; } template <typename Real, typename PixelType> inline math::image<PixelType> convert_bearing(const math::image<Real>& bearing_image) noexcept { static_assert(std::is_floating_point_v<Real>); static_assert(std::is_arithmetic_v<PixelType>); using detail::scaling_factor; cv::Mat img(bearing_image.h(), bearing_image.w(), math::detail::get_opencv_type<PixelType>()); auto [scale, offset] = scaling_factor<Real, PixelType>(/*max_angle = */ math::pi<Real>); bearing_image.data().convertTo( img, math::detail::get_opencv_type<PixelType>(), scale, offset); Ensures(img.cols == bearing_image.w()); Ensures(img.rows == bearing_image.h()); Ensures(img.type() == math::detail::get_opencv_type<PixelType>()); Ensures(img.channels() == 1); return math::image<PixelType>(std::move(img)); } } // namespace sens_loc::conversion #endif /* end of include guard: DEPTH_TO_BEARING_H_ZXFA9HGG */
{ "alphanum_fraction": 0.6647798742, "avg_line_length": 36.4918032787, "ext": "h", "hexsha": "e9ff05662c2a5377fcdeb2695b1892a81d67f418", "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/include/sens_loc/conversion/depth_to_bearing.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/include/sens_loc/conversion/depth_to_bearing.h", "max_line_length": 80, "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/include/sens_loc/conversion/depth_to_bearing.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": 2634, "size": 11130 }
/* Copyright (C) 2021 Barcelona Supercomputing Center and University of * Illinois at Urbana-Champaign * SPDX-License-Identifier: MIT * * This is the c ODE solver for the chemistry module * It is currently set up to use the SUNDIALS BDF method, Newton * iteration with the KLU sparse linear solver. * * It uses a scalar relative tolerance and a vector absolute tolerance. * */ /** \file * \brief Interface to c solvers for chemistry */ #include "camp_solver.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "aero_rep_solver.h" #include "rxn_solver.h" #include "sub_model_solver.h" #ifdef CAMP_USE_GPU #include "cuda/camp_gpu_solver.h" #endif #ifdef CAMP_USE_GSL #include <gsl/gsl_deriv.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #endif #include "camp_debug.h" // Default solver initial time step relative to total integration time #define DEFAULT_TIME_STEP 1.0 // State advancement factor for Jacobian element evaluation #define JAC_CHECK_ADV_MAX 1.0E-00 #define JAC_CHECK_ADV_MIN 1.0E-12 // Relative tolerance for Jacobian element evaluation against GSL absolute // errors #define JAC_CHECK_GSL_REL_TOL 1.0e-4 // Absolute Jacobian error tolerance #define JAC_CHECK_GSL_ABS_TOL 1.0e-9 // Set MAX_TIMESTEP_WARNINGS to a negative number to prevent output #define MAX_TIMESTEP_WARNINGS -1 // Maximum number of steps in discreet addition guess helper #define GUESS_MAX_ITER 5 // Status codes for calls to camp_solver functions #define CAMP_SOLVER_SUCCESS 0 #define CAMP_SOLVER_FAIL 1 /** \brief Get a new solver object * * Return a pointer to a new SolverData object * * \param n_state_var Number of variables on the state array per grid cell * \param n_cells Number of grid cells to solve simultaneously * \param var_type Pointer to array of state variable types (solver, constant, * PSSA) * \param n_rxn Number of reactions to include * \param n_rxn_int_param Total number of integer reaction parameters * \param n_rxn_float_param Total number of floating-point reaction parameters * \param n_rxn_env_param Total number of environment-dependent reaction * parameters \param n_aero_phase Number of aerosol phases \param * n_aero_phase_int_param Total number of integer aerosol phase parameters * \param n_aero_phase_float_param Total number of floating-point aerosol phase * parameters * \param n_aero_rep Number of aerosol representations * \param n_aero_rep_int_param Total number of integer aerosol representation * parameters * \param n_aero_rep_float_param Total number of floating-point aerosol * representation parameters * \param n_aero_rep_env_param Total number of environment-dependent aerosol * representation parameters * \param n_sub_model Number of sub models * \param n_sub_model_int_param Total number of integer sub model parameters * \param n_sub_model_float_param Total number of floating-point sub model * parameters * \param n_sub_model_env_param Total number of environment-dependent sub model * parameters * \return Pointer to the new SolverData object */ void *solver_new(int n_state_var, int n_cells, int *var_type, int n_rxn, int n_rxn_int_param, int n_rxn_float_param, int n_rxn_env_param, int n_aero_phase, int n_aero_phase_int_param, int n_aero_phase_float_param, int n_aero_rep, int n_aero_rep_int_param, int n_aero_rep_float_param, int n_aero_rep_env_param, int n_sub_model, int n_sub_model_int_param, int n_sub_model_float_param, int n_sub_model_env_param) { // Create the SolverData object SolverData *sd = (SolverData *)malloc(sizeof(SolverData)); if (sd == NULL) { printf("\n\nERROR allocating space for SolverData\n\n"); exit(EXIT_FAILURE); } #ifdef CAMP_USE_SUNDIALS #ifdef CAMP_DEBUG // Default to no debugging output sd->debug_out = SUNFALSE; // Initialize the Jac solver flag sd->eval_Jac = SUNFALSE; #endif #endif // Do not output precision loss by default sd->output_precision = 0; // Use the Jacobian estimated derivative in f() by default sd->use_deriv_est = 1; // Save the number of state variables per grid cell sd->model_data.n_per_cell_state_var = n_state_var; // Set number of cells to compute simultaneously sd->model_data.n_cells = n_cells; // Add the variable types to the solver data sd->model_data.var_type = (int *)malloc(n_state_var * sizeof(int)); if (sd->model_data.var_type == NULL) { printf("\n\nERROR allocating space for variable types\n\n"); exit(EXIT_FAILURE); } for (int i = 0; i < n_state_var; i++) sd->model_data.var_type[i] = var_type[i]; // Get the number of solver variables per grid cell int n_dep_var = 0; for (int i = 0; i < n_state_var; i++) if (var_type[i] == CHEM_SPEC_VARIABLE) n_dep_var++; // Save the number of solver variables per grid cell sd->model_data.n_per_cell_dep_var = n_dep_var; #ifdef CAMP_USE_SUNDIALS // Set up a TimeDerivative object to use during solving if (time_derivative_initialize(&(sd->time_deriv), n_dep_var) != 1) { printf("\n\nERROR initializing the TimeDerivative\n\n"); exit(EXIT_FAILURE); } // Set up the solver variable array and helper derivative array sd->y = N_VNew_Serial(n_dep_var * n_cells); sd->deriv = N_VNew_Serial(n_dep_var * n_cells); #endif // Allocate space for the reaction data and set the number // of reactions (including one int for the number of reactions // and one int per reaction to store the reaction type) sd->model_data.rxn_int_data = (int *)malloc((n_rxn_int_param + n_rxn) * sizeof(int)); if (sd->model_data.rxn_int_data == NULL) { printf("\n\nERROR allocating space for reaction integer data\n\n"); exit(EXIT_FAILURE); } sd->model_data.rxn_float_data = (double *)malloc(n_rxn_float_param * sizeof(double)); if (sd->model_data.rxn_float_data == NULL) { printf("\n\nERROR allocating space for reaction float data\n\n"); exit(EXIT_FAILURE); } sd->model_data.rxn_env_data = (double *)calloc(n_cells * n_rxn_env_param, sizeof(double)); if (sd->model_data.rxn_env_data == NULL) { printf( "\n\nERROR allocating space for environment-dependent " "data\n\n"); exit(EXIT_FAILURE); } // Allocate space for the reaction data pointers sd->model_data.rxn_int_indices = (int *)malloc((n_rxn + 1) * sizeof(int *)); if (sd->model_data.rxn_int_indices == NULL) { printf("\n\nERROR allocating space for reaction integer indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.rxn_float_indices = (int *)malloc((n_rxn + 1) * sizeof(int *)); if (sd->model_data.rxn_float_indices == NULL) { printf("\n\nERROR allocating space for reaction float indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.rxn_env_idx = (int *)malloc((n_rxn + 1) * sizeof(int)); if (sd->model_data.rxn_env_idx == NULL) { printf( "\n\nERROR allocating space for reaction environment-dependent " "data pointers\n\n"); exit(EXIT_FAILURE); } sd->model_data.n_rxn = n_rxn; sd->model_data.n_added_rxns = 0; sd->model_data.n_rxn_env_data = 0; sd->model_data.rxn_int_indices[0] = 0; sd->model_data.rxn_float_indices[0] = 0; sd->model_data.rxn_env_idx[0] = 0; // If there are no reactions, flag the solver not to run sd->no_solve = (n_rxn == 0); // Allocate space for the aerosol phase data and st the number // of aerosol phases (including one int for the number of // phases) sd->model_data.aero_phase_int_data = (int *)malloc(n_aero_phase_int_param * sizeof(int)); if (sd->model_data.aero_phase_int_data == NULL) { printf("\n\nERROR allocating space for aerosol phase integer data\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_phase_float_data = (double *)malloc(n_aero_phase_float_param * sizeof(double)); if (sd->model_data.aero_phase_float_data == NULL) { printf( "\n\nERROR allocating space for aerosol phase floating-point " "data\n\n"); exit(EXIT_FAILURE); } // Allocate space for the aerosol phase data pointers sd->model_data.aero_phase_int_indices = (int *)malloc((n_aero_phase + 1) * sizeof(int *)); if (sd->model_data.aero_phase_int_indices == NULL) { printf("\n\nERROR allocating space for reaction integer indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_phase_float_indices = (int *)malloc((n_aero_phase + 1) * sizeof(int *)); if (sd->model_data.aero_phase_float_indices == NULL) { printf("\n\nERROR allocating space for reaction float indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.n_aero_phase = n_aero_phase; sd->model_data.n_added_aero_phases = 0; sd->model_data.aero_phase_int_indices[0] = 0; sd->model_data.aero_phase_float_indices[0] = 0; // Allocate space for the aerosol representation data and set // the number of aerosol representations (including one int // for the number of aerosol representations and one int per // aerosol representation to store the aerosol representation // type) sd->model_data.aero_rep_int_data = (int *)malloc((n_aero_rep_int_param + n_aero_rep) * sizeof(int)); if (sd->model_data.aero_rep_int_data == NULL) { printf( "\n\nERROR allocating space for aerosol representation integer " "data\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_rep_float_data = (double *)malloc(n_aero_rep_float_param * sizeof(double)); if (sd->model_data.aero_rep_float_data == NULL) { printf( "\n\nERROR allocating space for aerosol representation " "floating-point data\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_rep_env_data = (double *)calloc(n_cells * n_aero_rep_env_param, sizeof(double)); if (sd->model_data.aero_rep_env_data == NULL) { printf( "\n\nERROR allocating space for aerosol representation " "environmental parameters\n\n"); exit(EXIT_FAILURE); } // Allocate space for the aerosol representation data pointers sd->model_data.aero_rep_int_indices = (int *)malloc((n_aero_rep + 1) * sizeof(int *)); if (sd->model_data.aero_rep_int_indices == NULL) { printf("\n\nERROR allocating space for reaction integer indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_rep_float_indices = (int *)malloc((n_aero_rep + 1) * sizeof(int *)); if (sd->model_data.aero_rep_float_indices == NULL) { printf("\n\nERROR allocating space for reaction float indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.aero_rep_env_idx = (int *)malloc((n_aero_rep + 1) * sizeof(int)); if (sd->model_data.aero_rep_env_idx == NULL) { printf( "\n\nERROR allocating space for aerosol representation " "environment-dependent data pointers\n\n"); exit(EXIT_FAILURE); } sd->model_data.n_aero_rep = n_aero_rep; sd->model_data.n_added_aero_reps = 0; sd->model_data.n_aero_rep_env_data = 0; sd->model_data.aero_rep_int_indices[0] = 0; sd->model_data.aero_rep_float_indices[0] = 0; sd->model_data.aero_rep_env_idx[0] = 0; // Allocate space for the sub model data and set the number of sub models // (including one int for the number of sub models and one int per sub // model to store the sub model type) sd->model_data.sub_model_int_data = (int *)malloc((n_sub_model_int_param + n_sub_model) * sizeof(int)); if (sd->model_data.sub_model_int_data == NULL) { printf("\n\nERROR allocating space for sub model integer data\n\n"); exit(EXIT_FAILURE); } sd->model_data.sub_model_float_data = (double *)malloc(n_sub_model_float_param * sizeof(double)); if (sd->model_data.sub_model_float_data == NULL) { printf("\n\nERROR allocating space for sub model floating-point data\n\n"); exit(EXIT_FAILURE); } sd->model_data.sub_model_env_data = (double *)calloc(n_cells * n_sub_model_env_param, sizeof(double)); if (sd->model_data.sub_model_env_data == NULL) { printf( "\n\nERROR allocating space for sub model environment-dependent " "data\n\n"); exit(EXIT_FAILURE); } // Allocate space for the sub-model data pointers sd->model_data.sub_model_int_indices = (int *)malloc((n_sub_model + 1) * sizeof(int *)); if (sd->model_data.sub_model_int_indices == NULL) { printf("\n\nERROR allocating space for reaction integer indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.sub_model_float_indices = (int *)malloc((n_sub_model + 1) * sizeof(int *)); if (sd->model_data.sub_model_float_indices == NULL) { printf("\n\nERROR allocating space for reaction float indices\n\n"); exit(EXIT_FAILURE); } sd->model_data.sub_model_env_idx = (int *)malloc((n_sub_model + 1) * sizeof(int)); if (sd->model_data.sub_model_env_idx == NULL) { printf( "\n\nERROR allocating space for sub model environment-dependent " "data pointers\n\n"); exit(EXIT_FAILURE); } sd->model_data.n_sub_model = n_sub_model; sd->model_data.n_added_sub_models = 0; sd->model_data.n_sub_model_env_data = 0; sd->model_data.sub_model_int_indices[0] = 0; sd->model_data.sub_model_float_indices[0] = 0; sd->model_data.sub_model_env_idx[0] = 0; #ifdef CAMP_USE_GPU solver_new_gpu_cu(n_dep_var, n_state_var, n_rxn, n_rxn_int_param, n_rxn_float_param, n_rxn_env_param, n_cells); #endif #ifdef CAMP_DEBUG if (sd->debug_out) print_data_sizes(&(sd->model_data)); #endif // Return a pointer to the new SolverData object return (void *)sd; } /** \brief Solver initialization * * Allocate and initialize solver objects * * \param solver_data Pointer to a SolverData object * \param abs_tol Pointer to array of absolute tolerances * \param rel_tol Relative integration tolerance * \param max_steps Maximum number of internal integration steps * \param max_conv_fails Maximum number of convergence failures */ void solver_initialize(void *solver_data, double *abs_tol, double rel_tol, int max_steps, int max_conv_fails) { #ifdef CAMP_USE_SUNDIALS SolverData *sd; // SolverData object int flag; // return code from SUNDIALS functions int n_dep_var; // number of dependent variables per grid cell int i_dep_var; // index of dependent variables in loops int n_state_var; // number of variables on the state array per // grid cell int n_cells; // number of cells to solve simultaneously int *var_type; // state variable types // Seed the random number generator srand((unsigned int)100); // Get a pointer to the SolverData sd = (SolverData *)solver_data; // Create a new solver object sd->cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON); check_flag_fail((void *)sd->cvode_mem, "CVodeCreate", 0); // Get the number of total and dependent variables on the state array, // and the type of each state variable. All values are per-grid-cell. n_state_var = sd->model_data.n_per_cell_state_var; n_dep_var = sd->model_data.n_per_cell_dep_var; var_type = sd->model_data.var_type; n_cells = sd->model_data.n_cells; // Set the solver data flag = CVodeSetUserData(sd->cvode_mem, sd); check_flag_fail(&flag, "CVodeSetUserData", 1); /* Call CVodeInit to initialize the integrator memory and specify the * right-hand side function in y'=f(t,y), the initial time t0, and * the initial dependent variable vector y. */ flag = CVodeInit(sd->cvode_mem, f, (realtype)0.0, sd->y); check_flag_fail(&flag, "CVodeInit", 1); // Set the relative and absolute tolerances sd->abs_tol_nv = N_VNew_Serial(n_dep_var * n_cells); i_dep_var = 0; for (int i_cell = 0; i_cell < n_cells; ++i_cell) for (int i_spec = 0; i_spec < n_state_var; ++i_spec) if (var_type[i_spec] == CHEM_SPEC_VARIABLE) NV_Ith_S(sd->abs_tol_nv, i_dep_var++) = (realtype)abs_tol[i_spec]; flag = CVodeSVtolerances(sd->cvode_mem, (realtype)rel_tol, sd->abs_tol_nv); check_flag_fail(&flag, "CVodeSVtolerances", 1); // Add a pointer in the model data to the absolute tolerances for use during // solving. TODO find a better way to do this sd->model_data.abs_tol = abs_tol; // Set the maximum number of iterations flag = CVodeSetMaxNumSteps(sd->cvode_mem, max_steps); check_flag_fail(&flag, "CVodeSetMaxNumSteps", 1); // Set the maximum number of convergence failures flag = CVodeSetMaxConvFails(sd->cvode_mem, max_conv_fails); check_flag_fail(&flag, "CVodeSetMaxConvFails", 1); // Set the maximum number of error test failures (TODO make separate input?) flag = CVodeSetMaxErrTestFails(sd->cvode_mem, max_conv_fails); check_flag_fail(&flag, "CVodeSetMaxErrTestFails", 1); // Set the maximum number of warnings about a too-small time step flag = CVodeSetMaxHnilWarns(sd->cvode_mem, MAX_TIMESTEP_WARNINGS); check_flag_fail(&flag, "CVodeSetMaxHnilWarns", 1); // Get the structure of the Jacobian matrix sd->J = get_jac_init(sd); sd->model_data.J_init = SUNMatClone(sd->J); SUNMatCopy(sd->J, sd->model_data.J_init); // Create a Jacobian matrix for correcting negative predicted concentrations // during solving sd->J_guess = SUNMatClone(sd->J); SUNMatCopy(sd->J, sd->J_guess); // Create a KLU SUNLinearSolver sd->ls = SUNKLU(sd->y, sd->J); check_flag_fail((void *)sd->ls, "SUNKLU", 0); // Attach the linear solver and Jacobian to the CVodeMem object flag = CVDlsSetLinearSolver(sd->cvode_mem, sd->ls, sd->J); check_flag_fail(&flag, "CVDlsSetLinearSolver", 1); // Set the Jacobian function to Jac flag = CVDlsSetJacFn(sd->cvode_mem, Jac); check_flag_fail(&flag, "CVDlsSetJacFn", 1); // Set a function to improve guesses for y sent to the linear solver flag = CVodeSetDlsGuessHelper(sd->cvode_mem, guess_helper); check_flag_fail(&flag, "CVodeSetDlsGuessHelper", 1); // Allocate Jacobian on GPU #ifdef CAMP_USE_GPU allocate_jac_gpu(sd->model_data.n_per_cell_solver_jac_elem, n_cells); #endif // Set gpu rxn values #ifdef CAMP_USE_GPU solver_set_rxn_data_gpu(&(sd->model_data)); #endif #ifndef FAILURE_DETAIL // Set a custom error handling function flag = CVodeSetErrHandlerFn(sd->cvode_mem, error_handler, (void *)sd); check_flag_fail(&flag, "CVodeSetErrHandlerFn", 0); #endif #endif } #ifdef CAMP_DEBUG /** \brief Set the flag indicating whether to output debugging information * * \param solver_data A pointer to the solver data * \param do_output Whether to output debugging information during solving */ int solver_set_debug_out(void *solver_data, bool do_output) { #ifdef CAMP_USE_SUNDIALS SolverData *sd = (SolverData *)solver_data; sd->debug_out = do_output == true ? SUNTRUE : SUNFALSE; return CAMP_SOLVER_SUCCESS; #else return 0; #endif } #endif #ifdef CAMP_DEBUG /** \brief Set the flag indicating whether to evalute the Jacobian during ** solving * * \param solver_data A pointer to the solver data * \param eval_Jac Flag indicating whether to evaluate the Jacobian during * solving */ int solver_set_eval_jac(void *solver_data, bool eval_Jac) { #ifdef CAMP_USE_SUNDIALS SolverData *sd = (SolverData *)solver_data; sd->eval_Jac = eval_Jac == true ? SUNTRUE : SUNFALSE; return CAMP_SOLVER_SUCCESS; #else return 0; #endif } #endif /** \brief Solve for a given timestep * * \param solver_data A pointer to the initialized solver data * \param state A pointer to the full state array (all grid cells) * \param env A pointer to the full array of environmental conditions * (all grid cells) * \param t_initial Initial time (s) * \param t_final (s) * \return Flag indicating CAMP_SOLVER_SUCCESS or CAMP_SOLVER_FAIL */ int solver_run(void *solver_data, double *state, double *env, double t_initial, double t_final) { #ifdef CAMP_USE_SUNDIALS SolverData *sd = (SolverData *)solver_data; ModelData *md = &(sd->model_data); int n_state_var = sd->model_data.n_per_cell_state_var; int n_cells = sd->model_data.n_cells; int flag; // Update the dependent variables int i_dep_var = 0; for (int i_cell = 0; i_cell < n_cells; i_cell++) for (int i_spec = 0; i_spec < n_state_var; i_spec++) if (sd->model_data.var_type[i_spec] == CHEM_SPEC_VARIABLE) { NV_Ith_S(sd->y, i_dep_var++) = state[i_spec + i_cell * n_state_var] > TINY ? (realtype)state[i_spec + i_cell * n_state_var] : TINY; } else if (md->var_type[i_spec] == CHEM_SPEC_CONSTANT) { state[i_spec + i_cell * n_state_var] = state[i_spec + i_cell * n_state_var] > TINY ? state[i_spec + i_cell * n_state_var] : TINY; } // Update model data pointers sd->model_data.total_state = state; sd->model_data.total_env = env; #ifdef CAMP_DEBUG // Update the debug output flag in CVODES and the linear solver flag = CVodeSetDebugOut(sd->cvode_mem, sd->debug_out); check_flag_fail(&flag, "CVodeSetDebugOut", 1); flag = SUNKLUSetDebugOut(sd->ls, sd->debug_out); check_flag_fail(&flag, "SUNKLUSetDebugOut", 1); #endif // Reset the counter of Jacobian evaluation failures sd->Jac_eval_fails = 0; // Update data for new environmental state // (This is set up to assume the environmental variables do not change during // solving. This can be changed in the future if necessary.) for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) { // Set the grid cell state pointers md->grid_cell_id = i_cell; md->grid_cell_state = &(md->total_state[i_cell * md->n_per_cell_state_var]); md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]); md->grid_cell_rxn_env_data = &(md->rxn_env_data[i_cell * md->n_rxn_env_data]); md->grid_cell_aero_rep_env_data = &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]); md->grid_cell_sub_model_env_data = &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]); // Update the model for the current environmental state aero_rep_update_env_state(md); sub_model_update_env_state(md); rxn_update_env_state(md); } CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_init, "Begin solving"); // Reset the flag indicating a current J_guess sd->curr_J_guess = false; // Set the initial time step sd->init_time_step = (t_final - t_initial) * DEFAULT_TIME_STEP; // Check whether there is anything to solve (filters empty air masses with no // emissions) if (is_anything_going_on_here(sd, t_initial, t_final) == false) return CAMP_SOLVER_SUCCESS; // Reinitialize the solver flag = CVodeReInit(sd->cvode_mem, t_initial, sd->y); check_flag_fail(&flag, "CVodeReInit", 1); // Reinitialize the linear solver flag = SUNKLUReInit(sd->ls, sd->J, SM_NNZ_S(sd->J), SUNKLU_REINIT_PARTIAL); check_flag_fail(&flag, "SUNKLUReInit", 1); // Set the inital time step flag = CVodeSetInitStep(sd->cvode_mem, sd->init_time_step); check_flag_fail(&flag, "CVodeSetInitStep", 1); // Run the solver realtype t_rt = (realtype)t_initial; if (!sd->no_solve) { flag = CVode(sd->cvode_mem, (realtype)t_final, sd->y, &t_rt, CV_NORMAL); sd->solver_flag = flag; #ifndef FAILURE_DETAIL if (flag < 0) { #else if (check_flag(&flag, "CVode", 1) == CAMP_SOLVER_FAIL) { if (flag == -6) { long int lsflag; int lastflag = CVDlsGetLastFlag(sd->cvode_mem, &lsflag); printf("\nLinear Solver Setup Fail: %d %ld", lastflag, lsflag); } N_Vector deriv = N_VClone(sd->y); flag = f(t_initial, sd->y, deriv, sd); if (flag != 0) printf("\nCall to f() at failed state failed with flag %d\n", flag); for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) { printf("\n Cell: %d ", i_cell); printf("temp = %le pressure = %le\n", env[i_cell * CAMP_NUM_ENV_PARAM_], env[i_cell * CAMP_NUM_ENV_PARAM_ + 1]); for (int i_spec = 0, i_dep_var = 0; i_spec < md->n_per_cell_state_var; i_spec++) if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) { printf( "spec %d = %le deriv = %le\n", i_spec, NV_Ith_S(sd->y, i_cell * md->n_per_cell_dep_var + i_dep_var), NV_Ith_S(deriv, i_cell * md->n_per_cell_dep_var + i_dep_var)); i_dep_var++; } else { printf("spec %d = %le\n", i_spec, state[i_cell * md->n_per_cell_state_var + i_spec]); } } solver_print_stats(sd->cvode_mem); #endif return CAMP_SOLVER_FAIL; } } // Update the species concentrations on the state array i_dep_var = 0; for (int i_cell = 0; i_cell < n_cells; i_cell++) { for (int i_spec = 0; i_spec < n_state_var; i_spec++) { if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) { state[i_spec + i_cell * n_state_var] = (double)(NV_Ith_S(sd->y, i_dep_var) > 0.0 ? NV_Ith_S(sd->y, i_dep_var) : 0.0); i_dep_var++; } } } // Re-run the pre-derivative calculations to update equilibrium species // and apply adjustments to final state sub_model_calculate(md); return CAMP_SOLVER_SUCCESS; #else return CAMP_SOLVER_FAIL; #endif } /** \brief Get solver statistics after an integration attempt * * \param solver_data Pointer to the solver data * \param solver_flag Last flag returned by the solver * \param num_steps Pointer to set to the number of integration * steps * \param RHS_evals Pointer to set to the number of right-hand side * evaluations * \param LS_setups Pointer to set to the number of linear solver * setups * \param error_test_fails Pointer to set to the number of error test * failures * \param NLS_iters Pointer to set to the non-linear solver * iterations * \param NLS_convergence_fails Pointer to set to the non-linear solver * convergence failures * \param DLS_Jac_evals Pointer to set to the direct linear solver * Jacobian evaluations * \param DLS_RHS_evals Pointer to set to the direct linear solver * right-hand side evaluations * \param last_time_step__s Pointer to set to the last time step size [s] * \param next_time_step__s Pointer to set to the next time step size [s] * \param Jac_eval_fails Number of Jacobian evaluation failures * \param RHS_evals_total Total calls to `f()` * \param Jac_evals_total Total calls to `Jac()` * \param RHS_time__s Compute time for calls to f() [s] * \param Jac_time__s Compute time for calls to Jac() [s] * \param max_loss_precision Indicators of loss of precision in derivative * calculation for each species */ void solver_get_statistics(void *solver_data, int *solver_flag, int *num_steps, int *RHS_evals, int *LS_setups, int *error_test_fails, int *NLS_iters, int *NLS_convergence_fails, int *DLS_Jac_evals, int *DLS_RHS_evals, double *last_time_step__s, double *next_time_step__s, int *Jac_eval_fails, int *RHS_evals_total, int *Jac_evals_total, double *RHS_time__s, double *Jac_time__s, double *max_loss_precision) { #ifdef CAMP_USE_SUNDIALS SolverData *sd = (SolverData *)solver_data; long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge; realtype last_h, curr_h; int flag; *solver_flag = sd->solver_flag; flag = CVodeGetNumSteps(sd->cvode_mem, &nst); if (check_flag(&flag, "CVodeGetNumSteps", 1) == CAMP_SOLVER_FAIL) return; *num_steps = (int)nst; flag = CVodeGetNumRhsEvals(sd->cvode_mem, &nfe); if (check_flag(&flag, "CVodeGetNumRhsEvals", 1) == CAMP_SOLVER_FAIL) return; *RHS_evals = (int)nfe; flag = CVodeGetNumLinSolvSetups(sd->cvode_mem, &nsetups); if (check_flag(&flag, "CVodeGetNumLinSolveSetups", 1) == CAMP_SOLVER_FAIL) return; *LS_setups = (int)nsetups; flag = CVodeGetNumErrTestFails(sd->cvode_mem, &netf); if (check_flag(&flag, "CVodeGetNumErrTestFails", 1) == CAMP_SOLVER_FAIL) return; *error_test_fails = (int)netf; flag = CVodeGetNumNonlinSolvIters(sd->cvode_mem, &nni); if (check_flag(&flag, "CVodeGetNonlinSolvIters", 1) == CAMP_SOLVER_FAIL) return; *NLS_iters = (int)nni; flag = CVodeGetNumNonlinSolvConvFails(sd->cvode_mem, &ncfn); if (check_flag(&flag, "CVodeGetNumNonlinSolvConvFails", 1) == CAMP_SOLVER_FAIL) return; *NLS_convergence_fails = ncfn; flag = CVDlsGetNumJacEvals(sd->cvode_mem, &nje); if (check_flag(&flag, "CVDlsGetNumJacEvals", 1) == CAMP_SOLVER_FAIL) return; *DLS_Jac_evals = (int)nje; flag = CVDlsGetNumRhsEvals(sd->cvode_mem, &nfeLS); if (check_flag(&flag, "CVDlsGetNumRhsEvals", 1) == CAMP_SOLVER_FAIL) return; *DLS_RHS_evals = (int)nfeLS; flag = CVodeGetLastStep(sd->cvode_mem, &last_h); if (check_flag(&flag, "CVodeGetLastStep", 1) == CAMP_SOLVER_FAIL) return; *last_time_step__s = (double)last_h; flag = CVodeGetCurrentStep(sd->cvode_mem, &curr_h); if (check_flag(&flag, "CVodeGetCurrentStep", 1) == CAMP_SOLVER_FAIL) return; *next_time_step__s = (double)curr_h; *Jac_eval_fails = sd->Jac_eval_fails; #ifdef CAMP_DEBUG *RHS_evals_total = sd->counterDeriv; *Jac_evals_total = sd->counterJac; *RHS_time__s = ((double)sd->timeDeriv) / CLOCKS_PER_SEC; *Jac_time__s = ((double)sd->timeJac) / CLOCKS_PER_SEC; *max_loss_precision = sd->max_loss_precision; #else *RHS_evals_total = -1; *Jac_evals_total = -1; *RHS_time__s = 0.0; *Jac_time__s = 0.0; *max_loss_precision = 0.0; #endif #endif } #ifdef CAMP_USE_SUNDIALS /** \brief Update the model state from the current solver state * * \param solver_state Solver state vector * \param model_data Pointer to the model data (including the state array) * \param threshhold A lower limit for model concentrations below which the * solver value is replaced with a replacement value * \param replacement_value Replacement value for low concentrations * \return CAMP_SOLVER_SUCCESS for successful update or * CAMP_SOLVER_FAIL for negative concentration */ int camp_solver_update_model_state(N_Vector solver_state, ModelData *model_data, realtype threshhold, realtype replacement_value) { int n_state_var = model_data->n_per_cell_state_var; int n_dep_var = model_data->n_per_cell_dep_var; int n_cells = model_data->n_cells; int i_dep_var = 0; for (int i_cell = 0; i_cell < n_cells; i_cell++) { for (int i_spec = 0; i_spec < n_state_var; ++i_spec) { if (model_data->var_type[i_spec] == CHEM_SPEC_VARIABLE) { if (NV_DATA_S(solver_state)[i_dep_var] < -SMALL) { #ifdef FAILURE_DETAIL printf("\nFailed model state update: [spec %d] = %le", i_spec, NV_DATA_S(solver_state)[i_dep_var]); #endif return CAMP_SOLVER_FAIL; } // Assign model state to solver_state model_data->total_state[i_spec + i_cell * n_state_var] = NV_DATA_S(solver_state)[i_dep_var] > threshhold ? NV_DATA_S(solver_state)[i_dep_var] : replacement_value; i_dep_var++; } } } return CAMP_SOLVER_SUCCESS; } /** \brief Compute the time derivative f(t,y) * * \param t Current model time (s) * \param y Dependent variable array * \param deriv Time derivative vector f(t,y) to calculate * \param solver_data Pointer to the solver data * \return Status code */ int f(realtype t, N_Vector y, N_Vector deriv, void *solver_data) { SolverData *sd = (SolverData *)solver_data; ModelData *md = &(sd->model_data); realtype time_step; #ifdef CAMP_DEBUG sd->counterDeriv++; #endif // Get a pointer to the derivative data double *deriv_data = N_VGetArrayPointer(deriv); // Get a pointer to the Jacobian estimated derivative data double *jac_deriv_data = N_VGetArrayPointer(md->J_tmp); // Get the grid cell dimensions int n_cells = md->n_cells; int n_state_var = md->n_per_cell_state_var; int n_dep_var = md->n_per_cell_dep_var; // Get the current integrator time step (s) CVodeGetCurrentStep(sd->cvode_mem, &time_step); // On the first call to f(), the time step hasn't been set yet, so use the // default value time_step = time_step > ZERO ? time_step : sd->init_time_step; // Update the state array with the current dependent variable values. // Signal a recoverable error (positive return value) for negative // concentrations. if (camp_solver_update_model_state(y, md, -SMALL, TINY) != CAMP_SOLVER_SUCCESS) return 1; // Get the Jacobian-estimated derivative N_VLinearSum(1.0, y, -1.0, md->J_state, md->J_tmp); SUNMatMatvec(md->J_solver, md->J_tmp, md->J_tmp2); N_VLinearSum(1.0, md->J_deriv, 1.0, md->J_tmp2, md->J_tmp); #ifdef CAMP_DEBUG // Measure calc_deriv time execution clock_t start = clock(); #endif #ifdef CAMP_USE_GPU // Reset the derivative vector N_VConst(ZERO, deriv); // Calculate the time derivative f(t,y) // (this is for all grid cells at once) rxn_calc_deriv_gpu(md, deriv, (double)time_step); #endif #ifdef CAMP_DEBUG clock_t end = clock(); sd->timeDeriv += (end - start); #endif // Loop through the grid cells and update the derivative array for (int i_cell = 0; i_cell < n_cells; ++i_cell) { // Set the grid cell state pointers md->grid_cell_id = i_cell; md->grid_cell_state = &(md->total_state[i_cell * n_state_var]); md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]); md->grid_cell_rxn_env_data = &(md->rxn_env_data[i_cell * md->n_rxn_env_data]); md->grid_cell_aero_rep_env_data = &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]); md->grid_cell_sub_model_env_data = &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]); // Update the aerosol representations aero_rep_update_state(md); // Run the sub models sub_model_calculate(md); #ifdef CAMP_DEBUG // Measure calc_deriv time execution clock_t start2 = clock(); #endif #ifndef CAMP_USE_GPU // Reset the TimeDerivative time_derivative_reset(sd->time_deriv); // Calculate the time derivative f(t,y) rxn_calc_deriv(md, sd->time_deriv, (double)time_step); // Update the deriv array if (sd->use_deriv_est == 1) { time_derivative_output(sd->time_deriv, deriv_data, jac_deriv_data, sd->output_precision); } else { time_derivative_output(sd->time_deriv, deriv_data, NULL, sd->output_precision); } #else // Add contributions from reactions not implemented on GPU // FIXME need to fix this to use TimeDerivative rxn_calc_deriv_specific_types(md, sd->time_deriv, (double)time_step); #endif #ifdef CAMP_DEBUG clock_t end2 = clock(); sd->timeDeriv += (end2 - start2); sd->max_loss_precision = time_derivative_max_loss_precision(sd->time_deriv); #endif // Advance the derivative for the next cell deriv_data += n_dep_var; jac_deriv_data += n_dep_var; } // Return 0 if success return (0); } /** \brief Compute the Jacobian * * \param t Current model time (s) * \param y Dependent variable array * \param deriv Time derivative vector f(t,y) * \param J Jacobian to calculate * \param solver_data Pointer to the solver data * \param tmp1 Unused vector * \param tmp2 Unused vector * \param tmp3 Unused vector * \return Status code */ int Jac(realtype t, N_Vector y, N_Vector deriv, SUNMatrix J, void *solver_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) { SolverData *sd = (SolverData *)solver_data; ModelData *md = &(sd->model_data); realtype time_step; #ifdef CAMP_DEBUG sd->counterJac++; #endif // Get the grid cell dimensions int n_state_var = md->n_per_cell_state_var; int n_dep_var = md->n_per_cell_dep_var; int n_cells = md->n_cells; // Get pointers to the rxn and parameter Jacobian arrays double *J_param_data = SM_DATA_S(md->J_params); double *J_rxn_data = SM_DATA_S(md->J_rxn); // Initialize the sparse matrix (sized for one grid cell) // solver_data->model_data.J_rxn = // SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_rxn, CSC_MAT); // TODO: use this instead of saving all this jacs // double J_rxn_data[md->n_per_cell_dep_var]; // memset(J_rxn_data, 0, md->n_per_cell_dep_var * sizeof(double)); // double *J_rxn_data = (double*)calloc(md->n_per_cell_state_var, // sizeof(double)); // !!!! Do not use tmp2 - it is the same as y !!!! // // FIXME Find out why cvode is sending tmp2 as y // Calculate the the derivative for the current state y without // the estimated derivative from the last Jacobian calculation sd->use_deriv_est = 0; if (f(t, y, deriv, solver_data) != 0) { printf("\n Derivative calculation failed.\n"); sd->use_deriv_est = 1; return 1; } sd->use_deriv_est = 1; // Update the state array with the current dependent variable values // Signal a recoverable error (positive return value) for negative // concentrations. if (camp_solver_update_model_state(y, md, -SMALL, TINY) != CAMP_SOLVER_SUCCESS) return 1; // Get the current integrator time step (s) CVodeGetCurrentStep(sd->cvode_mem, &time_step); // Reset the primary Jacobian /// \todo #83 Figure out how to stop CVODE from resizing the Jacobian /// during solving SM_NNZ_S(J) = SM_NNZ_S(md->J_init); for (int i = 0; i <= SM_NP_S(J); i++) { (SM_INDEXPTRS_S(J))[i] = (SM_INDEXPTRS_S(md->J_init))[i]; } for (int i = 0; i < SM_NNZ_S(J); i++) { (SM_INDEXVALS_S(J))[i] = (SM_INDEXVALS_S(md->J_init))[i]; (SM_DATA_S(J))[i] = (realtype)0.0; } #ifdef CAMP_DEBUG clock_t start2 = clock(); #endif #ifdef CAMP_USE_GPU // Calculate the Jacobian rxn_calc_jac_gpu(md, J, time_step); #endif #ifdef CAMP_DEBUG clock_t end2 = clock(); sd->timeJac += (end2 - start2); #endif // Solving on CPU only // Loop over the grid cells to calculate sub-model and rxn Jacobians for (int i_cell = 0; i_cell < n_cells; ++i_cell) { // Set the grid cell state pointers md->grid_cell_id = i_cell; md->grid_cell_state = &(md->total_state[i_cell * n_state_var]); md->grid_cell_env = &(md->total_env[i_cell * CAMP_NUM_ENV_PARAM_]); md->grid_cell_rxn_env_data = &(md->rxn_env_data[i_cell * md->n_rxn_env_data]); md->grid_cell_aero_rep_env_data = &(md->aero_rep_env_data[i_cell * md->n_aero_rep_env_data]); md->grid_cell_sub_model_env_data = &(md->sub_model_env_data[i_cell * md->n_sub_model_env_data]); // Reset the sub-model and reaction Jacobians for (int i = 0; i < SM_NNZ_S(md->J_params); ++i) SM_DATA_S(md->J_params)[i] = 0.0; jacobian_reset(sd->jac); // Update the aerosol representations aero_rep_update_state(md); // Run the sub models and get the sub-model Jacobian sub_model_calculate(md); sub_model_get_jac_contrib(md, J_param_data, time_step); CAMP_DEBUG_JAC(md->J_params, "sub-model Jacobian"); #ifdef CAMP_DEBUG clock_t start = clock(); #endif #ifndef CAMP_USE_GPU // Calculate the reaction Jacobian rxn_calc_jac(md, sd->jac, time_step); #else // Add contributions from reactions not implemented on GPU rxn_calc_jac_specific_types(md, sd->jac, time_step); #endif // rxn_calc_jac_specific_types(md, J_rxn_data, time_step); #ifdef CAMP_DEBUG clock_t end = clock(); sd->timeJac += (end - start); #endif // Output the Jacobian to the SUNDIALS J_rxn jacobian_output(sd->jac, SM_DATA_S(md->J_rxn)); CAMP_DEBUG_JAC(md->J_rxn, "reaction Jacobian"); // Set the solver Jacobian using the reaction and sub-model Jacobians JacMap *jac_map = md->jac_map; SM_DATA_S(md->J_params)[0] = 1.0; // dummy value for non-sub model calcs for (int i_map = 0; i_map < md->n_mapped_values; ++i_map) SM_DATA_S(J) [i_cell * md->n_per_cell_solver_jac_elem + jac_map[i_map].solver_id] += SM_DATA_S(md->J_rxn)[jac_map[i_map].rxn_id] * SM_DATA_S(md->J_params)[jac_map[i_map].param_id]; CAMP_DEBUG_JAC(J, "solver Jacobian"); } // Save the Jacobian for use with derivative calculations for (int i_elem = 0; i_elem < SM_NNZ_S(J); ++i_elem) SM_DATA_S(md->J_solver)[i_elem] = SM_DATA_S(J)[i_elem]; N_VScale(1.0, y, md->J_state); N_VScale(1.0, deriv, md->J_deriv); #ifdef CAMP_DEBUG // Evaluate the Jacobian if flagged to do so if (sd->eval_Jac == SUNTRUE) { if (!check_Jac(t, y, J, deriv, tmp1, tmp3, solver_data)) { ++(sd->Jac_eval_fails); } } #endif return (0); } /** \brief Check a Jacobian for accuracy * * This function compares Jacobian elements against differences in derivative * calculations for small changes to the state array: * \f[ * J_{ij}(x) = \frac{f_i(x+\sum_j e_j) - f_i(x)}{\epsilon} * \f] * where \f$\epsilon_j = 10^{-8} \left|x_j\right|\f$ * * \param t Current time [s] * \param y Current state array * \param J Jacobian matrix to evaluate * \param deriv Current derivative \f$f(y)\f$ * \param tmp Working array the size of \f$y\f$ * \param tmp1 Working array the size of \f$y\f$ * \param solver_data Solver data * \return True if Jacobian values are accurate, false otherwise */ bool check_Jac(realtype t, N_Vector y, SUNMatrix J, N_Vector deriv, N_Vector tmp, N_Vector tmp1, void *solver_data) { realtype *d_state = NV_DATA_S(y); realtype *d_deriv = NV_DATA_S(deriv); bool retval = true; #ifdef CAMP_USE_GSL GSLParam gsl_param; gsl_function gsl_func; // Set up gsl parameters needed during numerical differentiation gsl_param.t = t; gsl_param.y = tmp; gsl_param.deriv = tmp1; gsl_param.solver_data = (SolverData *)solver_data; // Set up the gsl function gsl_func.function = &gsl_f; gsl_func.params = &gsl_param; #endif // Calculate the the derivative for the current state y if (f(t, y, deriv, solver_data) != 0) { printf("\n Derivative calculation failed.\n"); return false; } // Loop through the independent variables, numerically calculating // the partial derivatives d_fy/d_x for (int i_ind = 0; i_ind < NV_LENGTH_S(y); ++i_ind) { // If GSL is available, use their numerical differentiation to // calculate the partial derivatives. Otherwise, estimate them by // advancing the state. #ifdef CAMP_USE_GSL // Reset tmp to the initial state N_VScale(ONE, y, tmp); // Save the independent species concentration and index double x = d_state[i_ind]; gsl_param.ind_var = i_ind; // Skip small concentrations if (x < SMALL) continue; // Do the numerical differentiation for each potentially non-zero // Jacobian element for (int i_elem = SM_INDEXPTRS_S(J)[i_ind]; i_elem < SM_INDEXPTRS_S(J)[i_ind + 1]; ++i_elem) { int i_dep = SM_INDEXVALS_S(J)[i_elem]; double abs_err; double partial_deriv; gsl_param.dep_var = i_dep; bool test_pass = false; double h, abs_tol, rel_diff, scaling; // Evaluate the Jacobian element over a range of initial step sizes for (scaling = JAC_CHECK_ADV_MIN; scaling <= JAC_CHECK_ADV_MAX && test_pass == false; scaling *= 10.0) { // Get the current initial step size h = x * scaling; // Get the partial derivative d_fy/dx if (gsl_deriv_forward(&gsl_func, x, h, &partial_deriv, &abs_err) == 1) { printf("\nERROR in numerical differentiation for J[%d][%d]", i_ind, i_dep); } // Evaluate the results abs_tol = 1.2 * fabs(abs_err); abs_tol = abs_tol > JAC_CHECK_GSL_ABS_TOL ? abs_tol : JAC_CHECK_GSL_ABS_TOL; rel_diff = 1.0; if (partial_deriv != 0.0) rel_diff = fabs((SM_DATA_S(J)[i_elem] - partial_deriv) / partial_deriv); if (fabs(SM_DATA_S(J)[i_elem] - partial_deriv) < abs_tol || rel_diff < JAC_CHECK_GSL_REL_TOL) test_pass = true; } // If the test does not pass with any initial step size, print out the // failure, output the local derivative state and return false if (test_pass == false) { printf( "\nError in Jacobian[%d][%d]: Got %le; expected %le" "\n difference %le is greater than error %le", i_ind, i_dep, SM_DATA_S(J)[i_elem], partial_deriv, fabs(SM_DATA_S(J)[i_elem] - partial_deriv), abs_tol); printf("\n relative error %le intial step size %le", rel_diff, h); printf("\n initial rate %le initial state %le", d_deriv[i_dep], d_state[i_ind]); printf(" scaling %le", scaling); ModelData *md = &(((SolverData *)solver_data)->model_data); for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) for (int i_spec = 0; i_spec < md->n_per_cell_state_var; ++i_spec) printf("\n cell: %d species %d state_id %d conc: %le", i_cell, i_spec, i_cell * md->n_per_cell_state_var + i_spec, md->total_state[i_cell * md->n_per_cell_state_var + i_spec]); retval = false; output_deriv_local_state(t, y, deriv, solver_data, &f, i_dep, i_ind, SM_DATA_S(J)[i_elem], h / 10.0); } } #endif } return retval; } #ifdef CAMP_USE_GSL /** \brief Wrapper function for derivative calculations for numerical solving * * Wraps the f(t,y) function for use by the GSL numerical differentiation * functions. * * \param x Independent variable \f$x\f$ for calculations of \f$df_y/dx\f$ * \param param Differentiation parameters * \return Partial derivative \f$df_y/dx\f$ */ double gsl_f(double x, void *param) { GSLParam *gsl_param = (GSLParam *)param; N_Vector y = gsl_param->y; N_Vector deriv = gsl_param->deriv; // Set the independent variable NV_DATA_S(y)[gsl_param->ind_var] = x; // Calculate the derivative if (f(gsl_param->t, y, deriv, (void *)gsl_param->solver_data) != 0) { printf("\nDerivative calculation failed!"); for (int i_spec = 0; i_spec < NV_LENGTH_S(y); ++i_spec) printf("\n species %d conc: %le", i_spec, NV_DATA_S(y)[i_spec]); return 0.0 / 0.0; } // Return the calculated derivative for the dependent variable return NV_DATA_S(deriv)[gsl_param->dep_var]; } #endif /** \brief Try to improve guesses of y sent to the linear solver * * This function checks if there are any negative guessed concentrations, * and if there are it calculates a set of initial corrections to the * guessed state using the state at time \f$t_{n-1}\f$ and the derivative * \f$f_{n-1}\f$ and advancing the state according to: * \f[ * y_n = y_{n-1} + \sum_{j=1}^m h_j * f_j * \f] * where \f$h_j\f$ is the largest timestep possible where * \f[ * y_{j-1} + h_j * f_j > 0 * \f] * and * \f[ * t_n = t_{n-1} + \sum_{j=1}^m h_j * \f] * * \param t_n Current time [s] * \param h_n Current time step size [s] If this is set to zero, the change hf * is assumed to be an adjustment where y_n = y_n1 + hf * \param y_n Current guess for \f$y(t_n)\f$ * \param y_n1 \f$y(t_{n-1})\f$ * \param hf Current guess for change in \f$y\f$ from \f$t_{n-1}\f$ to * \f$t_n\f$ [input/output] * \param solver_data Solver data * \param tmp1 Temporary vector for calculations * \param corr Vector of calculated adjustments to \f$y(t_n)\f$ [output] * \return 1 if corrections were calculated, 0 if not */ int guess_helper(const realtype t_n, const realtype h_n, N_Vector y_n, N_Vector y_n1, N_Vector hf, void *solver_data, N_Vector tmp1, N_Vector corr) { SolverData *sd = (SolverData *)solver_data; realtype *ay_n = NV_DATA_S(y_n); realtype *ay_n1 = NV_DATA_S(y_n1); realtype *atmp1 = NV_DATA_S(tmp1); realtype *acorr = NV_DATA_S(corr); realtype *ahf = NV_DATA_S(hf); int n_elem = NV_LENGTH_S(y_n); // Only try improvements when negative concentrations are predicted if (N_VMin(y_n) > -SMALL) return 0; CAMP_DEBUG_PRINT_FULL("Trying to improve guess"); // Copy \f$y(t_{n-1})\f$ to working array N_VScale(ONE, y_n1, tmp1); // Get \f$f(t_{n-1})\f$ if (h_n > ZERO) { N_VScale(ONE / h_n, hf, corr); } else { N_VScale(ONE, hf, corr); } CAMP_DEBUG_PRINT("Got f0"); // Advance state interatively realtype t_0 = h_n > ZERO ? t_n - h_n : t_n - ONE; realtype t_j = ZERO; int iter = 0; for (; iter < GUESS_MAX_ITER && t_0 + t_j < t_n; iter++) { // Calculate \f$h_j\f$ realtype h_j = t_n - (t_0 + t_j); int i_fast = -1; for (int i = 0; i < n_elem; i++) { realtype t_star = -atmp1[i] / acorr[i]; if ((t_star > ZERO || (t_star == ZERO && acorr[i] < ZERO)) && t_star < h_j) { h_j = t_star; i_fast = i; } } // Scale incomplete jumps if (i_fast >= 0 && h_n > ZERO) h_j *= 0.95 + 0.1 * rand() / (double)RAND_MAX; h_j = t_n < t_0 + t_j + h_j ? t_n - (t_0 + t_j) : h_j; // Only make small changes to adjustment vectors used in Newton iteration if (h_n == ZERO && t_n - (h_j + t_j + t_0) > ((CVodeMem)sd->cvode_mem)->cv_reltol) return -1; // Advance the state N_VLinearSum(ONE, tmp1, h_j, corr, tmp1); CAMP_DEBUG_PRINT_FULL("Advanced state"); // Advance t_j t_j += h_j; // Recalculate the time derivative \f$f(t_j)\f$ if (f(t_0 + t_j, tmp1, corr, solver_data) != 0) { CAMP_DEBUG_PRINT("Unexpected failure in guess helper!"); N_VConst(ZERO, corr); return -1; } ((CVodeMem)sd->cvode_mem)->cv_nfe++; if (iter == GUESS_MAX_ITER - 1 && t_0 + t_j < t_n) { CAMP_DEBUG_PRINT("Max guess iterations reached!"); if (h_n == ZERO) return -1; } } CAMP_DEBUG_PRINT_INT("Guessed y_h in steps:", iter); // Set the correction vector N_VLinearSum(ONE, tmp1, -ONE, y_n, corr); // Scale the initial corrections if (h_n > ZERO) N_VScale(0.999, corr, corr); // Update the hf vector N_VLinearSum(ONE, tmp1, -ONE, y_n1, hf); return 1; } /** \brief Create a sparse Jacobian matrix based on model data * * \param solver_data A pointer to the SolverData * \return Sparse Jacobian matrix with all possible non-zero elements intialize * to 1.0 */ SUNMatrix get_jac_init(SolverData *solver_data) { int n_rxn; /* number of reactions in the mechanism * (stored in first position in *rxn_data) */ sunindextype n_jac_elem_rxn; /* number of potentially non-zero Jacobian elements in the reaction matrix*/ sunindextype n_jac_elem_param; /* number of potentially non-zero Jacobian elements in the reaction matrix*/ sunindextype n_jac_elem_solver; /* number of potentially non-zero Jacobian elements in the reaction matrix*/ // Number of grid cells int n_cells = solver_data->model_data.n_cells; // Number of variables on the state array per grid cell // (these are the ids the reactions are initialized with) int n_state_var = solver_data->model_data.n_per_cell_state_var; // Number of total state variables int n_state_var_total = n_state_var * n_cells; // Number of solver variables per grid cell (excludes constants, parameters, // etc.) int n_dep_var = solver_data->model_data.n_per_cell_dep_var; // Number of total solver variables int n_dep_var_total = n_dep_var * n_cells; // Initialize the Jacobian for reactions if (jacobian_initialize_empty(&(solver_data->jac), (unsigned int)n_state_var) != 1) { printf("\n\nERROR allocating Jacobian structure\n\n"); exit(EXIT_FAILURE); } // Add diagonal elements by default for (unsigned int i_spec = 0; i_spec < n_state_var; ++i_spec) { jacobian_register_element(&(solver_data->jac), i_spec, i_spec); } // Fill in the 2D array of flags with Jacobian elements used by the // mechanism reactions for a single grid cell rxn_get_used_jac_elem(&(solver_data->model_data), &(solver_data->jac)); // Build the sparse Jacobian if (jacobian_build_matrix(&(solver_data->jac)) != 1) { printf("\n\nERROR building sparse full-state Jacobian\n\n"); exit(EXIT_FAILURE); } // Determine the number of non-zero Jacobian elements per grid cell n_jac_elem_rxn = jacobian_number_of_elements(solver_data->jac); // Save number of reaction jacobian elements per grid cell solver_data->model_data.n_per_cell_rxn_jac_elem = (int)n_jac_elem_rxn; // Initialize the sparse matrix (sized for one grid cell) solver_data->model_data.J_rxn = SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_rxn, CSC_MAT); // Set the column and row indices for (unsigned int i_col = 0; i_col <= n_state_var; ++i_col) { (SM_INDEXPTRS_S(solver_data->model_data.J_rxn))[i_col] = jacobian_column_pointer_value(solver_data->jac, i_col); } for (unsigned int i_elem = 0; i_elem < n_jac_elem_rxn; ++i_elem) { (SM_DATA_S(solver_data->model_data.J_rxn))[i_elem] = (realtype)0.0; (SM_INDEXVALS_S(solver_data->model_data.J_rxn))[i_elem] = jacobian_row_index(solver_data->jac, i_elem); } // Build the set of time derivative ids int *deriv_ids = (int *)malloc(sizeof(int) * n_state_var); if (deriv_ids == NULL) { printf("\n\nERROR allocating space for derivative ids\n\n"); exit(EXIT_FAILURE); } int i_dep_var = 0; for (int i_spec = 0; i_spec < n_state_var; i_spec++) { if (solver_data->model_data.var_type[i_spec] == CHEM_SPEC_VARIABLE) { deriv_ids[i_spec] = i_dep_var++; } else { deriv_ids[i_spec] = -1; } } // Update the ids in the reaction data rxn_update_ids(&(solver_data->model_data), deriv_ids, solver_data->jac); //////////////////////////////////////////////////////////////////////// // Get the Jacobian elements used in sub model parameter calculations // //////////////////////////////////////////////////////////////////////// // Initialize the Jacobian for sub-model parameters Jacobian param_jac; if (jacobian_initialize_empty(&param_jac, (unsigned int)n_state_var) != 1) { printf("\n\nERROR allocating sub-model Jacobian structure\n\n"); exit(EXIT_FAILURE); } // Set up a dummy element at the first position jacobian_register_element(&param_jac, 0, 0); // Fill in the 2D array of flags with Jacobian elements used by the // mechanism sub models sub_model_get_used_jac_elem(&(solver_data->model_data), &param_jac); // Build the sparse Jacobian for sub-model parameters if (jacobian_build_matrix(&param_jac) != 1) { printf("\n\nERROR building sparse Jacobian for sub-model parameters\n\n"); exit(EXIT_FAILURE); } // Save the number of sub model Jacobian elements per grid cell n_jac_elem_param = jacobian_number_of_elements(param_jac); solver_data->model_data.n_per_cell_param_jac_elem = (int)n_jac_elem_param; // Set up the parameter Jacobian (sized for one grid cell) // Initialize the sparse matrix with one extra element (at the first position) // for use in mapping that is set to 1.0. (This is safe because there can be // no elements on the diagonal in the sub model Jacobian.) solver_data->model_data.J_params = SUNSparseMatrix(n_state_var, n_state_var, n_jac_elem_param, CSC_MAT); // Set the column and row indices for (unsigned int i_col = 0; i_col <= n_state_var; ++i_col) { (SM_INDEXPTRS_S(solver_data->model_data.J_params))[i_col] = jacobian_column_pointer_value(param_jac, i_col); } for (unsigned int i_elem = 0; i_elem < n_jac_elem_param; ++i_elem) { (SM_DATA_S(solver_data->model_data.J_params))[i_elem] = (realtype)0.0; (SM_INDEXVALS_S(solver_data->model_data.J_params))[i_elem] = jacobian_row_index(param_jac, i_elem); } // Update the ids in the sub model data sub_model_update_ids(&(solver_data->model_data), deriv_ids, param_jac); //////////////////////////////// // Set up the solver Jacobian // //////////////////////////////// // Initialize the Jacobian for sub-model parameters Jacobian solver_jac; if (jacobian_initialize_empty(&solver_jac, (unsigned int)n_state_var) != 1) { printf("\n\nERROR allocating solver Jacobian structure\n\n"); exit(EXIT_FAILURE); } // Determine the structure of the solver Jacobian and number of mapped values int n_mapped_values = 0; for (int i_ind = 0; i_ind < n_state_var; ++i_ind) { for (int i_dep = 0; i_dep < n_state_var; ++i_dep) { // skip dependent species that are not solver variables and // depenedent species that aren't used by any reaction if (solver_data->model_data.var_type[i_dep] != CHEM_SPEC_VARIABLE || jacobian_get_element_id(solver_data->jac, i_dep, i_ind) == -1) continue; // If both elements are variable, use the rxn Jacobian only if (solver_data->model_data.var_type[i_ind] == CHEM_SPEC_VARIABLE && solver_data->model_data.var_type[i_dep] == CHEM_SPEC_VARIABLE) { jacobian_register_element(&solver_jac, i_dep, i_ind); ++n_mapped_values; continue; } // Check the sub model Jacobian for remaining conditions /// \todo Make the Jacobian mapping recursive for sub model parameters /// that depend on other sub model parameters for (int j_ind = 0; j_ind < n_state_var; ++j_ind) { if (jacobian_get_element_id(param_jac, i_ind, j_ind) != -1 && solver_data->model_data.var_type[j_ind] == CHEM_SPEC_VARIABLE) { jacobian_register_element(&solver_jac, i_dep, j_ind); ++n_mapped_values; } } } } // Build the sparse solver Jacobian if (jacobian_build_matrix(&solver_jac) != 1) { printf("\n\nERROR building sparse Jacobian for the solver\n\n"); exit(EXIT_FAILURE); } // Save the number of non-zero Jacobian elements n_jac_elem_solver = jacobian_number_of_elements(solver_jac); solver_data->model_data.n_per_cell_solver_jac_elem = (int)n_jac_elem_solver; // Initialize the sparse matrix (for solver state array including all cells) SUNMatrix M = SUNSparseMatrix(n_dep_var_total, n_dep_var_total, n_jac_elem_solver * n_cells, CSC_MAT); solver_data->model_data.J_solver = SUNSparseMatrix( n_dep_var_total, n_dep_var_total, n_jac_elem_solver * n_cells, CSC_MAT); // Set the column and row indices for (unsigned int i_cell = 0; i_cell < n_cells; ++i_cell) { for (unsigned int cell_col = 0; cell_col < n_state_var; ++cell_col) { if (deriv_ids[cell_col] == -1) continue; unsigned int i_col = deriv_ids[cell_col] + i_cell * n_dep_var; (SM_INDEXPTRS_S(M))[i_col] = (SM_INDEXPTRS_S(solver_data->model_data.J_solver))[i_col] = jacobian_column_pointer_value(solver_jac, cell_col) + i_cell * n_jac_elem_solver; } for (unsigned int cell_elem = 0; cell_elem < n_jac_elem_solver; ++cell_elem) { unsigned int i_elem = cell_elem + i_cell * n_jac_elem_solver; (SM_DATA_S(M))[i_elem] = (SM_DATA_S(solver_data->model_data.J_solver))[i_elem] = (realtype)0.0; (SM_INDEXVALS_S(M))[i_elem] = (SM_INDEXVALS_S(solver_data->model_data.J_solver))[i_elem] = deriv_ids[jacobian_row_index(solver_jac, cell_elem)] + i_cell * n_dep_var; } } (SM_INDEXPTRS_S(M))[n_cells * n_dep_var] = (SM_INDEXPTRS_S(solver_data->model_data.J_solver))[n_cells * n_dep_var] = n_cells * n_jac_elem_solver; // Allocate space for the map solver_data->model_data.n_mapped_values = n_mapped_values; solver_data->model_data.jac_map = (JacMap *)malloc(sizeof(JacMap) * n_mapped_values); if (solver_data->model_data.jac_map == NULL) { printf("\n\nERROR allocating space for jacobian map\n\n"); exit(EXIT_FAILURE); } JacMap *map = solver_data->model_data.jac_map; // Set map indices (when no sub-model value is used, the param_id is // set to 0 which maps to a fixed value of 1.0 int i_mapped_value = 0; for (unsigned int i_ind = 0; i_ind < n_state_var; ++i_ind) { for (unsigned int i_elem = jacobian_column_pointer_value(solver_data->jac, i_ind); i_elem < jacobian_column_pointer_value(solver_data->jac, i_ind + 1); ++i_elem) { unsigned int i_dep = jacobian_row_index(solver_data->jac, i_elem); // skip dependent species that are not solver variables and // depenedent species that aren't used by any reaction if (solver_data->model_data.var_type[i_dep] != CHEM_SPEC_VARIABLE || jacobian_get_element_id(solver_data->jac, i_dep, i_ind) == -1) continue; // If both elements are variable, use the rxn Jacobian only if (solver_data->model_data.var_type[i_ind] == CHEM_SPEC_VARIABLE && solver_data->model_data.var_type[i_dep] == CHEM_SPEC_VARIABLE) { map[i_mapped_value].solver_id = jacobian_get_element_id(solver_jac, i_dep, i_ind); map[i_mapped_value].rxn_id = i_elem; map[i_mapped_value].param_id = 0; ++i_mapped_value; continue; } // Check the sub model Jacobian for remaining conditions // (variable dependent species; independent parameter from sub model) for (int j_ind = 0; j_ind < n_state_var; ++j_ind) { if (jacobian_get_element_id(param_jac, i_ind, j_ind) != -1 && solver_data->model_data.var_type[j_ind] == CHEM_SPEC_VARIABLE) { map[i_mapped_value].solver_id = jacobian_get_element_id(solver_jac, i_dep, j_ind); map[i_mapped_value].rxn_id = i_elem; map[i_mapped_value].param_id = jacobian_get_element_id(param_jac, i_ind, j_ind); ++i_mapped_value; } } } } SolverData *sd = solver_data; CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_params, "Param struct"); CAMP_DEBUG_JAC_STRUCT(sd->model_data.J_rxn, "Reaction struct"); CAMP_DEBUG_JAC_STRUCT(M, "Solver struct"); if (i_mapped_value != n_mapped_values) { printf("[ERROR-340355266] Internal error"); exit(EXIT_FAILURE); } // Create vectors to store Jacobian state and derivative data solver_data->model_data.J_state = N_VClone(solver_data->y); solver_data->model_data.J_deriv = N_VClone(solver_data->y); solver_data->model_data.J_tmp = N_VClone(solver_data->y); solver_data->model_data.J_tmp2 = N_VClone(solver_data->y); // Initialize the Jacobian state and derivative arrays to zero // for use before the first call to Jac() N_VConst(0.0, solver_data->model_data.J_state); N_VConst(0.0, solver_data->model_data.J_deriv); // Free the memory used jacobian_free(&param_jac); jacobian_free(&solver_jac); free(deriv_ids); return M; } /** \brief Check the return value of a SUNDIALS function * * \param flag_value A pointer to check (either for NULL, or as an int pointer * giving the flag value * \param func_name A string giving the function name returning this result code * \param opt A flag indicating the type of check to perform (0 for NULL * pointer check; 1 for integer flag check) * \return Flag indicating CAMP_SOLVER_SUCCESS or CAMP_SOLVER_FAIL */ int check_flag(void *flag_value, char *func_name, int opt) { int *err_flag; /* Check for a NULL pointer */ if (opt == 0 && flag_value == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", func_name); return CAMP_SOLVER_FAIL; } /* Check if flag < 0 */ else if (opt == 1) { err_flag = (int *)flag_value; if (*err_flag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", func_name, *err_flag); return CAMP_SOLVER_FAIL; } } return CAMP_SOLVER_SUCCESS; } /** \brief Check the return value of a SUNDIALS function and exit on failure * * \param flag_value A pointer to check (either for NULL, or as an int pointer * giving the flag value * \param func_name A string giving the function name returning this result code * \param opt A flag indicating the type of check to perform (0 for NULL * pointer check; 1 for integer flag check) */ void check_flag_fail(void *flag_value, char *func_name, int opt) { if (check_flag(flag_value, func_name, opt) == CAMP_SOLVER_FAIL) { exit(EXIT_FAILURE); } } /** \brief Reset the timers for solver functions * * \param solver_data Pointer to the SolverData object with timers to reset */ #ifdef CAMP_USE_SUNDIALS void solver_reset_timers(void *solver_data) { SolverData *sd = (SolverData *)solver_data; #ifdef CAMP_DEBUG sd->counterDeriv = 0; sd->counterJac = 0; sd->timeDeriv = 0; sd->timeJac = 0; #endif } #endif /** \brief Print solver statistics * * \param cvode_mem Solver object */ static void solver_print_stats(void *cvode_mem) { long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge; realtype last_h, curr_h; int flag; flag = CVodeGetNumSteps(cvode_mem, &nst); if (check_flag(&flag, "CVodeGetNumSteps", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumRhsEvals(cvode_mem, &nfe); if (check_flag(&flag, "CVodeGetNumRhsEvals", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups); if (check_flag(&flag, "CVodeGetNumLinSolveSetups", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumErrTestFails(cvode_mem, &netf); if (check_flag(&flag, "CVodeGetNumErrTestFails", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni); if (check_flag(&flag, "CVodeGetNonlinSolvIters", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn); if (check_flag(&flag, "CVodeGetNumNonlinSolvConvFails", 1) == CAMP_SOLVER_FAIL) return; flag = CVDlsGetNumJacEvals(cvode_mem, &nje); if (check_flag(&flag, "CVDlsGetNumJacEvals", 1) == CAMP_SOLVER_FAIL) return; flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS); if (check_flag(&flag, "CVDlsGetNumRhsEvals", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetNumGEvals(cvode_mem, &nge); if (check_flag(&flag, "CVodeGetNumGEvals", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetLastStep(cvode_mem, &last_h); if (check_flag(&flag, "CVodeGetLastStep", 1) == CAMP_SOLVER_FAIL) return; flag = CVodeGetCurrentStep(cvode_mem, &curr_h); if (check_flag(&flag, "CVodeGetCurrentStep", 1) == CAMP_SOLVER_FAIL) return; printf("\nSUNDIALS Solver Statistics:\n"); printf("number of steps = %-6ld RHS evals = %-6ld LS setups = %-6ld\n", nst, nfe, nsetups); printf("error test fails = %-6ld LS iters = %-6ld NLS iters = %-6ld\n", netf, nni, ncfn); printf( "NL conv fails = %-6ld Dls Jac evals = %-6ld Dls RHS evals = %-6ld G " "evals =" " %-6ld\n", ncfn, nje, nfeLS, nge); printf("Last time step = %le Next time step = %le\n", last_h, curr_h); } #endif // CAMP_USE_SUNDIALS /** \brief Free a SolverData object * * \param solver_data Pointer to the SolverData object to free */ void solver_free(void *solver_data) { SolverData *sd = (SolverData *)solver_data; #ifdef CAMP_USE_SUNDIALS // free the SUNDIALS solver CVodeFree(&(sd->cvode_mem)); // free the absolute tolerance vector N_VDestroy(sd->abs_tol_nv); // free the TimeDerivative time_derivative_free(sd->time_deriv); // free the Jacobian jacobian_free(&(sd->jac)); // free the derivative vectors N_VDestroy(sd->y); N_VDestroy(sd->deriv); // destroy the Jacobian marix SUNMatDestroy(sd->J); // destroy Jacobian matrix for guessing state SUNMatDestroy(sd->J_guess); // free the linear solver SUNLinSolFree(sd->ls); #endif // Free the allocated ModelData model_free(sd->model_data); // free the SolverData object free(sd); } #ifdef CAMP_USE_SUNDIALS /** \brief Determine if there is anything to solve * * If the solver state concentrations and the derivative vector are very small, * there is no point running the solver */ bool is_anything_going_on_here(SolverData *sd, realtype t_initial, realtype t_final) { ModelData *md = &(sd->model_data); if (f(t_initial, sd->y, sd->deriv, sd)) { int i_dep_var = 0; for (int i_cell = 0; i_cell < md->n_cells; ++i_cell) { for (int i_spec = 0; i_spec < md->n_per_cell_state_var; ++i_spec) { if (md->var_type[i_spec] == CHEM_SPEC_VARIABLE) { if (NV_Ith_S(sd->y, i_dep_var) > NV_Ith_S(sd->abs_tol_nv, i_dep_var) * 1.0e-10) return true; if (NV_Ith_S(sd->deriv, i_dep_var) * (t_final - t_initial) > NV_Ith_S(sd->abs_tol_nv, i_dep_var) * 1.0e-10) return true; i_dep_var++; } } } return false; } return true; } #endif /** \brief Custom error handling function * * This is used for quiet operation. Solver failures are returned with a flag * from the solver_run() function. */ void error_handler(int error_code, const char *module, const char *function, char *msg, void *sd) { // Do nothing } /** \brief Free a ModelData object * * \param model_data Pointer to the ModelData object to free */ void model_free(ModelData model_data) { #ifdef CAMP_USE_GPU // free_gpu_cu(); #endif #ifdef CAMP_USE_SUNDIALS // Destroy the initialized Jacbobian matrix SUNMatDestroy(model_data.J_init); SUNMatDestroy(model_data.J_rxn); SUNMatDestroy(model_data.J_params); SUNMatDestroy(model_data.J_solver); N_VDestroy(model_data.J_state); N_VDestroy(model_data.J_deriv); N_VDestroy(model_data.J_tmp); N_VDestroy(model_data.J_tmp2); #endif free(model_data.jac_map); free(model_data.jac_map_params); free(model_data.var_type); free(model_data.rxn_int_data); free(model_data.rxn_float_data); free(model_data.rxn_env_data); free(model_data.rxn_int_indices); free(model_data.rxn_float_indices); free(model_data.rxn_env_idx); free(model_data.aero_phase_int_data); free(model_data.aero_phase_float_data); free(model_data.aero_phase_int_indices); free(model_data.aero_phase_float_indices); free(model_data.aero_rep_int_data); free(model_data.aero_rep_float_data); free(model_data.aero_rep_env_data); free(model_data.aero_rep_int_indices); free(model_data.aero_rep_float_indices); free(model_data.aero_rep_env_idx); free(model_data.sub_model_int_data); free(model_data.sub_model_float_data); free(model_data.sub_model_env_data); free(model_data.sub_model_int_indices); free(model_data.sub_model_float_indices); free(model_data.sub_model_env_idx); } /** \brief Free update data * * \param update_data Object to free */ void solver_free_update_data(void *update_data) { free(update_data); }
{ "alphanum_fraction": 0.67878754, "avg_line_length": 36.6395289299, "ext": "c", "hexsha": "1b7454e894ace9fabcabec04735eda92f961f28d", "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": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "open-atmos/camp", "max_forks_repo_path": "src/camp_solver.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_issues_repo_issues_event_max_datetime": "2022-01-22T11:42:07.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-06T18:14:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "open-atmos/camp", "max_issues_repo_path": "src/camp_solver.c", "max_line_length": 81, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4c77145ac43ae3dcfce71f49a9709bb62f80b8c3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "open-atmos/camp", "max_stars_repo_path": "src/camp_solver.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T05:32:29.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-05T21:35:20.000Z", "num_tokens": 19821, "size": 71557 }
/* $Id$ */ /* * Copyright (c) 2014--2016 Kristaps Dzonsons <kristaps@kcons.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <errno.h> #include <math.h> #include <stdint.h> #include <stdlib.h> #ifdef __linux__ #include <bsd/stdlib.h> /* arc4random() */ #endif #include <string.h> #include <gtk/gtk.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <kplot.h> #include "extern.h" /* * For a given point "x" in the domain, fit ourselves to the polynomial * coefficients of degree "fitpoly + 1". */ static double fitpoly(const double *fits, size_t poly, double x) { double y, v; size_t i, j; for (y = 0.0, i = 0; i < poly; i++) { v = fits[i]; for (j = 0; j < i; j++) v *= x; y += v; } return(y); } /* * Copy the "hotlsb" data into "warm" holding. * While here, set our simulation's "work" parameter (if "fitpoly" is * set) to contain the necessary dependent variable. * We're guaranteed to be the only ones in here, and the only ones with * a lock on the LBS data. */ static void snapshot(struct sim *sim, struct simwarm *warm, uint64_t truns, uint64_t tgens) { double v, chisq, x, y; struct kpair kp; int rc; size_t i, j, k; /* Warm copy is already up to date. */ if (warm->truns == truns) { g_assert(warm->tgens == tgens); return; } /* Copy out: we have a lock. */ simbuf_copy_warm(sim->bufs.times); simbuf_copy_warm(sim->bufs.imeans); simbuf_copy_warm(sim->bufs.istddevs); simbuf_copy_warm(sim->bufs.islandmeans); simbuf_copy_warm(sim->bufs.islandstddevs); simbuf_copy_warm(sim->bufs.means); simbuf_copy_warm(sim->bufs.stddevs); simbuf_copy_warm(sim->bufs.mextinct); simbuf_copy_warm(sim->bufs.iextinct); warm->truns = truns; warm->tgens = tgens; /* * If we're going to fit to a polynomial, set the dependent * variable within the conditional. */ if (sim->fitpoly) for (i = 0; i < sim->dims; i++) { rc = kdata_get(sim->bufs.means->warm, i, &kp); g_assert(0 != rc); gsl_vector_set(sim->work.y, i, kp.y); } /* * If we're going to run a weighted polynomial multifit, then * use the variance as the weight. */ if (sim->fitpoly && sim->weighted) for (i = 0; i < sim->dims; i++) { rc = kdata_get(sim->bufs.stddevs->warm, i, &kp); g_assert(0 != rc); gsl_vector_set(sim->work.w, i, kp.y); } /* * If we're not fitting to a polynomial, simply notify that * we've copied out and continue on our way. */ if (0 == sim->fitpoly) return; /* * If we're fitting to a polynomial, initialise our independent * variables now. */ for (i = 0; i < sim->dims; i++) { gsl_matrix_set(sim->work.X, i, 0, 1.0); for (j = 0; j < sim->fitpoly; j++) { v = sim->xmin + (sim->xmax - sim->xmin) * (i / (double)sim->dims); for (k = 0; k < j; k++) v *= v; gsl_matrix_set(sim->work.X, i, j + 1, v); } } /* * Now perform the actual fitting. * We either use weighted (weighted with the variance) or * non-weighted fitting algorithms. */ if (sim->weighted) gsl_multifit_wlinear(sim->work.X, sim->work.w, sim->work.y, sim->work.c, sim->work.cov, &chisq, sim->work.work); else gsl_multifit_linear(sim->work.X, sim->work.y, sim->work.c, sim->work.cov, &chisq, sim->work.work); /* * Now snapshot the fitted polynomial coefficients and compute * the fitted approximation for all incumbents (along with the * minimum value). */ for (i = 0; i < sim->fitpoly + 1; i++) sim->work.coeffs[i] = gsl_vector_get(sim->work.c, i); for (i = 0; i < sim->dims; i++) { x = sim->xmin + (sim->xmax - sim->xmin) * i / (double)sim->dims; y = fitpoly(sim->work.coeffs, sim->fitpoly + 1, x); kdata_array_set(sim->bufs.fitpoly, i, x, y); } } /* * In a given simulation, compute the next mutant/incumbent pair. * We make sure that incumbents are striped evenly in any given * simulation but that mutants are randomly selected from within the * strategy domain. */ static int on_sim_next(struct sim *sim, const gsl_rng *rng, size_t *islandidx, double *mutantp, double *incumbentp, size_t *incumbentidx, double *vp, const size_t *islands, size_t gen) { int dosnap, rc; size_t mutant; uint64_t truns, tgens; if (sim->terminate) return(0); truns = tgens = 0; /* Silence compiler. */ /* This is set if we "own" the LSB->warm process. */ dosnap = 0; g_assert(*incumbentidx < sim->dims); g_assert(*islandidx < sim->islands); g_mutex_lock(&sim->hot.mux); /* * If we're entering this with a result value, then plug it into * the index associated with the run and increment our count. * This prevents us from overwriting others' results. */ if (NULL != vp) { rc = kdata_array_add (sim->bufs.times->hot, gen, 1.0); g_assert(0 != rc); rc = kdata_array_fill_ysizes (sim->bufs.islands, islands); g_assert(0 != rc); rc = kdata_array_set(sim->bufs.fractions, *incumbentidx, *incumbentp, *vp); g_assert(0 != rc); rc = kdata_array_set(sim->bufs.ifractions, *islandidx, *islandidx, *vp); g_assert(0 != rc); rc = kdata_array_set(sim->bufs.mutants, *incumbentidx, *incumbentp, 0.0 == *vp); g_assert(0 != rc); rc = kdata_array_set(sim->bufs.incumbents, *incumbentidx, *incumbentp, 1.0 == *vp); g_assert(0 != rc); sim->hot.tgens += gen; sim->hot.truns++; } /* * Check if we've been requested to pause. * If so, wait for a broadcast on our condition. * This will unlock the mutex for others to process. */ if (1 == sim->hot.pause) g_cond_wait(&sim->hot.cond, &sim->hot.mux); /* * Check if we've been instructed by the main thread of * execution to snapshot hot data into warm storage. * We do this in two parts: first, we register that we're in a * copyout (it's now 2) and then actually do the copyout outside * of the hot mutex. */ if (1 == sim->hot.copyout) { simbuf_copy_hotlsb(sim->bufs.times); simbuf_copy_hotlsb(sim->bufs.islandmeans); simbuf_copy_hotlsb(sim->bufs.islandstddevs); simbuf_copy_hotlsb(sim->bufs.imeans); simbuf_copy_hotlsb(sim->bufs.istddevs); simbuf_copy_hotlsb(sim->bufs.means); simbuf_copy_hotlsb(sim->bufs.stddevs); simbuf_copy_hotlsb(sim->bufs.mextinct); simbuf_copy_hotlsb(sim->bufs.iextinct); truns = sim->hot.truns; tgens = sim->hot.tgens; sim->hot.copyout = dosnap = 2; } /* * Reassign our mutant and incumbent from the ring sized by the * configured lattice dimensions. * These both increment in single movements until the end of the * lattice, then wrap around. */ *islandidx = sim->hot.island; mutant = sim->hot.mutant; *incumbentidx = sim->hot.incumbent; sim->hot.mutant++; if (sim->hot.mutant == sim->dims) { sim->hot.incumbent++; if (sim->hot.incumbent == sim->dims) { sim->hot.incumbent = 0; if (MAPINDEX_STRIPED == sim->mapindex) sim->hot.island = (sim->hot.island + 1) % sim->islands; } sim->hot.mutant = 0; } g_mutex_unlock(&sim->hot.mux); /* * Assign our incumbent and mutant. * The incumbent just gets the current lattice position, * ensuring an even propogation. * The mutant is either assigned the same way or from a Gaussian * distribution around the current incumbent. */ *incumbentp = sim->xmin + (sim->xmax - sim->xmin) * (*incumbentidx / (double)sim->dims); if (MUTANTS_GAUSSIAN == sim->mutants) { do { *mutantp = *incumbentp + gsl_ran_gaussian (rng, sim->mutantsigma); } while (*mutantp < sim->ymin || *mutantp >= sim->ymax); } else *mutantp = sim->xmin + (sim->xmax - sim->xmin) * (mutant / (double)sim->dims); /* * If we were the ones to set the copyout bit, then do the * copyout right now. * When we're finished, lower the copyout semaphor. */ if (dosnap) { snapshot(sim, &sim->warm, truns, tgens); g_mutex_lock(&sim->hot.mux); g_assert(2 == sim->hot.copyout); sim->hot.copyout = 0; g_mutex_unlock(&sim->hot.mux); } return(1); } /* * For a given island (size "pop") player's strategy "x" where mutants * (numbering "mutants") have strategy "mutant" and incumbents * (numbering "incumbents") have strategy "incumbent", compute the * a(1 + delta(pi(x, X)) function. */ static double reproduce(const struct sim *sim, double x, double mutant, double incumbent, size_t mutants, size_t pop) { double v; if (0 == pop) return(0.0); v = hnode_exec ((const struct hnode *const *) sim->exp, x, (mutants * mutant) + ((pop - mutants) * incumbent), pop); g_assert( ! (isnan(v) || isinf(v))); return(sim->alpha * (1.0 + sim->delta * v)); } static size_t migrate(const struct sim *sim, const gsl_rng *rng, size_t cur) { double v; size_t i; again: while (0.0 == (v = gsl_rng_uniform(rng))) /* Loop. */ ; for (i = 0; i < sim->islands - 1; i++) if ((v -= sim->ms[cur][i]) <= 0.0) break; /* * This can occur due to floating-point rounding. * If it does, re-run the algorithm. */ if (i == sim->islands - 1 && i == cur) { g_debug("Degenerate probability: re-running"); goto again; } g_assert(cur != i); return(i); } /* * Run a simulation. * This can be one thread of many within the same simulation. */ void * simulation(void *arg) { struct simthr *thr = arg; struct sim *sim = thr->sim; double mutant, incumbent, v, lambda, prob; unsigned int offs; unsigned long seed; double *vp, *icache, *mcache; double ***icaches, ***mcaches; size_t *kids[2], *migrants[2], *imutants, *npops, *ndeaths; size_t t, i, j, k, new, mutants, incumbents, len1, len2, incumbentidx, islandidx, ntotalpop; int mutant_old, mutant_new; gsl_rng *rng; rng = gsl_rng_alloc(gsl_rng_default); seed = arc4random(); gsl_rng_set(rng, seed); g_debug("%p: Thread (simulation %p) " "start", g_thread_self(), sim); icache = mcache = NULL; icaches = mcaches = NULL; kids[0] = g_malloc0_n(sim->islands, sizeof(size_t)); kids[1] = g_malloc0_n(sim->islands, sizeof(size_t)); ndeaths = g_malloc0_n(sim->islands, sizeof(size_t)); migrants[0] = g_malloc0_n(sim->islands, sizeof(size_t)); migrants[1] = g_malloc0_n(sim->islands, sizeof(size_t)); imutants = g_malloc0_n(sim->islands, sizeof(size_t)); vp = NULL; npops = NULL; incumbentidx = 0; islandidx = MAPINDEX_FIXED == sim->mapindex ? sim->mapindexfix : 0; mutant = incumbent = 0.0; t = 0; /* * Set up our mutant and incumbent payoff caches. * These consist of all possible payoffs with a given number of * mutants and incumbents on an island. * We have two ways of doing this: with non-uniform island sizes * (icaches and mcaches) and uniform sizes (icache and mcache, * notice the singular). * The non-uniform island size can also change, so we precompute * for all possible populations as well. */ if (NULL != sim->pops) { g_assert(0 == sim->pop); npops = g_malloc0_n(sim->islands, sizeof(size_t)); for (i = 0; i < sim->islands; i++) npops[i] = sim->pops[i]; icaches = g_malloc0_n(sim->islands, sizeof(double **)); mcaches = g_malloc0_n(sim->islands, sizeof(double **)); for (i = 0; i < sim->islands; i++) { icaches[i] = g_malloc0_n (sim->pops[i] + 1, sizeof(double *)); mcaches[i] = g_malloc0_n (sim->pops[i] + 1, sizeof(double *)); for (j = 0; j <= sim->pops[i]; j++) { icaches[i][j] = g_malloc0_n(j + 1, sizeof(double)); mcaches[i][j] = g_malloc0_n(j + 1, sizeof(double)); } } } else { g_assert(sim->pop > 0); icache = g_malloc0_n(sim->pop + 1, sizeof(double)); mcache = g_malloc0_n(sim->pop + 1, sizeof(double)); } again: /* * Repeat til we're instructed to terminate. * We also pass in our last result for processing. */ if ( ! on_sim_next(sim, rng, &islandidx, &mutant, &incumbent, &incumbentidx, vp, imutants, t)) { g_debug("%p: Thread (simulation %p) exiting", g_thread_self(), sim); /* * Upon termination, free up all of the memory * associated with our simulation. */ g_free(ndeaths); g_free(imutants); g_free(kids[0]); g_free(kids[1]); g_free(migrants[0]); g_free(migrants[1]); if (NULL != sim->pops) for (i = 0; i < sim->islands; i++) { for (j = 0; j <= sim->pops[i]; j++) { g_free(icaches[i][j]); g_free(mcaches[i][j]); } g_free(icaches[i]); g_free(mcaches[i]); } g_free(icaches); g_free(mcaches); g_free(icache); g_free(mcache); return(NULL); } /* * Initialise a random island to have one mutant. * The rest are all incumbents. */ memset(imutants, 0, sim->islands * sizeof(size_t)); imutants[islandidx] = 1; mutants = 1; incumbents = sim->totalpop - mutants; ntotalpop = sim->totalpop; /* * Precompute all possible payoffs. * This allows us not to re-run the lambda calculation for each * individual. * If we have only a single island size, then avoid allocating * for each island by using only the first mcaches index. */ if (NULL != sim->pops) for (i = 0; i < sim->islands; i++) { for (j = 0; j <= sim->pops[i]; j++) { for (k = 0; k <= j; k++) { mcaches[i][j][k] = reproduce (sim, mutant, mutant, incumbent, k, j); icaches[i][j][k] = reproduce (sim, incumbent, mutant, incumbent, k, j); } } } else for (i = 0; i <= sim->pop; i++) { mcache[i] = reproduce(sim, mutant, mutant, incumbent, i, sim->pop); icache[i] = reproduce(sim, incumbent, mutant, incumbent, i, sim->pop); } for (t = 0; t < sim->stop; t++) { if (NULL != sim->pops && sim->ideathmean > 0) { /* * If we're a non-uniform population and have an * island death mean, then see if we're supposed * to kill off islands, then re-set the shot * clock. */ for (i = 0; i < sim->islands; i++) { /* * If the shot-clock has not been * started OR the island is already * dead, set it again. */ if (0 == ndeaths[i] || 0 == npops[i]) { ndeaths[i] = t + 1 + gsl_ran_poisson (rng, sim->ideathmean); continue; } else if (t != ndeaths[i]) continue; ndeaths[i] = t + 1 + gsl_ran_poisson (rng, sim->ideathmean); /* * What's the sum of our payoffs? * Compute the probability that we're * going to be killed from that and our * coefficient. */ g_assert(npops[i] > 0); v = mcaches[i][npops[i]][imutants[i]] * imutants[i] + icaches[i][npops[i]][imutants[i]] * (npops[i] - imutants[i]); prob = sim->ideathcoef * exp(-v); if (gsl_rng_uniform(rng) >= prob) continue; mutants -= imutants[i]; incumbents -= (npops[i] - imutants[i]); ntotalpop -= npops[i]; npops[i] = 0; imutants[i] = 0; } } /* * Birth process: have each individual (first mutants, * then incumbents) give birth. * Use a Poisson process with the given mean in order to * properly compute this. * We need two separate versions for whichever type of * mcache we decide to use. */ if (NULL != sim->pops) for (j = 0; j < sim->islands; j++) { if (0 == npops[j]) continue; g_assert(0 == kids[0][j]); g_assert(0 == kids[1][j]); g_assert(0 == migrants[0][j]); g_assert(0 == migrants[1][j]); g_assert(imutants[j] <= npops[j]); lambda = mcaches[j] [npops[j]][imutants[j]]; for (k = 0; k < imutants[j]; k++) { offs = gsl_ran_poisson (rng, lambda); kids[0][j] += offs; } lambda = icaches[j] [npops[j]][imutants[j]]; for ( ; k < npops[j]; k++) { offs = gsl_ran_poisson (rng, lambda); kids[1][j] += offs; } } else for (j = 0; j < sim->islands; j++) { g_assert(0 == kids[0][j]); g_assert(0 == kids[1][j]); g_assert(0 == migrants[0][j]); g_assert(0 == migrants[1][j]); lambda = mcache[imutants[j]]; for (k = 0; k < imutants[j]; k++) { offs = gsl_ran_poisson (rng, lambda); kids[0][j] += offs; } lambda = icache[imutants[j]]; for ( ; k < sim->pop; k++) { offs = gsl_ran_poisson (rng, lambda); kids[1][j] += offs; } } /* * Determine whether we're going to migrate and, if * migration is stipulated, to where. */ if (NULL != sim->ms) for (j = 0; j < sim->islands; j++) { for (k = 0; k < kids[0][j]; k++) { new = j; if (gsl_rng_uniform(rng) < sim->m) new = migrate(sim, rng, j); migrants[0][new]++; } for (k = 0; k < kids[1][j]; k++) { new = j; if (gsl_rng_uniform(rng) < sim->m) new = migrate(sim, rng, j); migrants[1][new]++; } kids[0][j] = kids[1][j] = 0; } else for (j = 0; j < sim->islands; j++) { for (k = 0; k < kids[0][j]; k++) { new = j; if (gsl_rng_uniform(rng) < sim->m) do new = gsl_rng_uniform_int (rng, sim->islands); while (new == j); migrants[0][new]++; } for (k = 0; k < kids[1][j]; k++) { new = j; if (gsl_rng_uniform(rng) < sim->m) do new = gsl_rng_uniform_int (rng, sim->islands); while (new == j); migrants[1][new]++; } kids[0][j] = kids[1][j] = 0; } /* * Perform the migration itself. * We randomly select an individual on the destination * island as well as one from the migrant queue. * We then replace one with the other. */ if (NULL != sim->pops) for (j = 0; j < sim->islands; j++) { if (npops[j] < sim->pops[j]) { /* * This is the case where a * given island has had its * population killed off. * Try to fill it up: don't * replace anybody. */ while (npops[j] < sim->pops[j]) { len1 = migrants[0][j] + migrants[1][j]; if (0 == len1) break; len2 = gsl_rng_uniform_int (rng, len1); if (len2 < migrants[0][j]) { migrants[0][j]--; imutants[j]++; mutants++; } else { migrants[1][j]--; incumbents++; } npops[j]++; ntotalpop++; } } else { len1 = migrants[0][j] + migrants[1][j]; if (0 == len1) continue; len2 = gsl_rng_uniform_int (rng, npops[j]); mutant_old = len2 < imutants[j]; len2 = gsl_rng_uniform_int(rng, len1); mutant_new = len2 < migrants[0][j]; if (mutant_old && ! mutant_new) { imutants[j]--; mutants--; incumbents++; } else if ( ! mutant_old && mutant_new) { imutants[j]++; mutants++; incumbents--; } } migrants[0][j] = migrants[1][j] = 0; } else for (j = 0; j < sim->islands; j++) { len1 = migrants[0][j] + migrants[1][j]; if (0 == len1) continue; len2 = gsl_rng_uniform_int(rng, sim->pop); mutant_old = len2 < imutants[j]; len2 = gsl_rng_uniform_int(rng, len1); mutant_new = len2 < migrants[0][j]; if (mutant_old && ! mutant_new) { imutants[j]--; mutants--; incumbents++; } else if ( ! mutant_old && mutant_new) { imutants[j]++; mutants++; incumbents--; } migrants[0][j] = migrants[1][j] = 0; } /* Stop when a population goes extinct. */ if (0 == mutants || 0 == incumbents) break; } /* * Assign the result pointer to the last population fraction. * This will be processed by on_sim_next(). */ if (incumbents == 0) { g_assert(mutants == ntotalpop); v = 1.0; } else if (mutants == 0) { g_assert(incumbents == ntotalpop); v = 0.0; } else v = mutants / (double)ntotalpop; vp = &v; goto again; }
{ "alphanum_fraction": 0.6063027295, "avg_line_length": 26.5831134565, "ext": "c", "hexsha": "015892ec93e7cb6a80d10215865e5ed4bc2d456c", "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": "0280a899564031a5a14af87d9264cd239a89851f", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "kristapsdz/bmigrate", "max_forks_repo_path": "simulation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "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": "kristapsdz/bmigrate", "max_issues_repo_path": "simulation.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "kristapsdz/bmigrate", "max_stars_repo_path": "simulation.c", "max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z", "num_tokens": 6695, "size": 20150 }
#include <math.h> #include "2d_array.h" #include "const.h" #include "misc.h" #include "utilities.h" #include <gsl/gsl_multifit.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_fit.h> /****************************************************************************** MODULE: rmse_from_square_root_mean PURPOSE: simulate matlab calculate rmse from square root mean RETURN VALUE: Type = void Value Description ----- ----------- HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 5/28/2019 Su Ye Original Development ******************************************************************************/ void rmse_from_square_root_mean ( float **array, /* I: input array */ float fit_cft, /* I: input fit_cft value */ int dim1_index, /* I: dimension 1 index in input array */ int dim2_len, /* I: dimension 2 length */ float *rmse /* O: output rmse */ ) { int i; float sum = 0.0; for (i = 0; i < dim2_len; i++) { sum += (array[dim1_index][i] - fit_cft) * (array[dim1_index][i] - fit_cft); } *rmse = sqrt(sum / dim2_len); } /****************************************************************************** MODULE: dofit PURPOSE: Declare data type and allocate memory and do multiple linear robust fit used for auto_robust_fit RETURN VALUE: None HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 5/28/2019 Su Ye Original Development NOTES: ******************************************************************************/ void dofit(const gsl_multifit_robust_type *T, const gsl_matrix *X, const gsl_vector *y, gsl_vector *c, gsl_matrix *cov) { gsl_multifit_robust_workspace * work = gsl_multifit_robust_alloc (T, X->size1, X->size2); gsl_multifit_robust (X, y, c, cov, work); gsl_multifit_robust_free (work); work = NULL; } void dofit_linear(const gsl_matrix *X, const gsl_vector *y, gsl_vector *c, gsl_matrix *cov) { double chisq; gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc ( X->size1, X->size2); gsl_multifit_linear(X, y, c, cov, &chisq,work); gsl_multifit_linear_free (work); // work = NULL; // SY 03242019 } /****************************************************************************** MODULE: auto_robust_fit PURPOSE: Robust fit for one band RETURN VALUE: None HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 5/28/2019 Su Ye Original Development NOTES: ******************************************************************************/ void auto_robust_fit ( float **clrx, float **clry, int nums, int start, int band_index, float *coefs ) { int i, j; const int p = 2; /* linear fit */ gsl_matrix *x, *cov; gsl_vector *y, *c; /******************************************************************/ /* */ /* Defines the inputs/outputs for robust fitting */ /* */ /******************************************************************/ x = gsl_matrix_alloc (nums, p); y = gsl_vector_alloc (nums); c = gsl_vector_alloc (p); cov = gsl_matrix_alloc (p, p); /******************************************************************/ /* */ /* construct design matrix x for linear fit */ /* */ /******************************************************************/ for (i = 0; i < nums; ++i) { for (j = 0; j < p; j++) { if (j == 0) { gsl_matrix_set (x, i, j, 1.0); } else { gsl_matrix_set (x, i, j, (double)clrx[i][j-1]); } } gsl_vector_set(y,i,(double)clry[band_index][i+start]); } /******************************************************************/ /* */ /* perform robust fit */ /* */ /******************************************************************/ dofit(gsl_multifit_robust_bisquare, x, y, c, cov); for (j = 0; j < (int)c->size; j++) { coefs[j] = gsl_vector_get(c, j); } /******************************************************************/ /* */ /* Free the memories */ /* */ /******************************************************************/ gsl_matrix_free (x); x = NULL; gsl_vector_free (y); y = NULL; gsl_vector_free (c); c = NULL; gsl_matrix_free (cov); cov = NULL; } /****************************************************************************** MODULE: auto_mask PURPOSE: Multitemporal cloud, cloud shadow, & snow masks (global version) RETURN VALUE: Type = int ERROR error out due to memory allocation SUCCESS no error encounted HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 05282019 Su Ye NOTES: ******************************************************************************/ int auto_mask ( int *clrx, float **clry, int start, int end, float years, float t_b1, float t_b2, float n_t, int *bl_ids ) { char FUNC_NAME[] = "auto_mask"; int i; float **x; float pred_b2, pred_b4; int nums; float coefs[ROBUST_COEFFS]; float coefs2[ROBUST_COEFFS]; nums = end - start + 1; /* Allocate memory */ x = (float **)allocate_2d_array(nums, ROBUST_COEFFS - 1, sizeof(float)); if (x == NULL) { RETURN_ERROR("ERROR allocating x memory", FUNC_NAME, ERROR); } for (i = 0; i < nums; i++) { x[i][0] = (float)clrx[i+start]; } /******************************************************************/ /* */ /* Do robust fitting for band 2 */ /* */ /******************************************************************/ auto_robust_fit(x, clry, nums, start, 1, coefs); /******************************************************************/ /* */ /* Do robust fitting for band 4 */ /* */ /******************************************************************/ auto_robust_fit(x, clry, nums, start, 3, coefs2); /******************************************************************/ /* */ /* predict band 2 and band 4 refs, bl_ids value of 0 is clear and */ /* 1 otherwise */ /* */ /******************************************************************/ for (i = 0; i < nums; i++) { pred_b2 = coefs[0] + coefs[1] * (float)clrx[i+start]; pred_b4 = coefs2[0] + coefs2[1] * (float)clrx[i+start]; if (((clry[1][i+start]-pred_b2) > (n_t * t_b1)) || ((clry[3][i+start]-pred_b4) < -(n_t * t_b2))) { bl_ids[i] = 1; } else { bl_ids[i] = 0; } } /* Free allocated memory */ if (free_2d_array ((void **) x) != SUCCESS) { RETURN_ERROR ("Freeing memory: x\n", FUNC_NAME, ERROR); } return (SUCCESS); } /****************************************************************************** MODULE: adjust_median_variogram PURPOSE: calculate absolute variogram for auto_mask RETURN VALUE: Type = void Value Description ----- ----------- HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 28/05/2019 Su Ye Original Development NOTES: ******************************************************************************/ int adjust_median_variogram ( int *clrx, /* I: dates */ float **array, /* I: input array */ int dim1_len, /* I: dimension 1 length in input array */ int dim2_start, /* I: dimension 2 start index */ int dim2_end, /* I: dimension 2 end index */ float *date_vario, /* O: outputted median variogran for dates */ float *max_neighdate_diff, /* O: maximum difference for two neighbor times */ float *output_array /* O: output array */ ) { int i, j; /* loop indecies */ float *var; /* pointer for allocation variable memory */ int dim2_len = dim2_end - dim2_start + 1; /* perhaps should get defined */ char FUNC_NAME[] = "adjust_median_variogram"; /* for error messages */ int max_freq; int m; // for (i = 0; i < dim2_len; i++) // { // for (j = 0; j < TOTAL_IMAGE_BANDS; j++) // { // printf("%f\n", (float)array[j][i]); // } // } if (dim2_len == 1) { for (i = 0; i < dim1_len; i++) { output_array[i] = array[i][dim2_start]; *date_vario = clrx[dim2_start]; return (SUCCESS); } } var = malloc((dim2_len-1) * sizeof(float)); if (var == NULL) { RETURN_ERROR ("Allocating var memory", FUNC_NAME, ERROR); } for (j = dim2_start; j < dim2_end; j++) { var[j] = abs(clrx[j+1] - clrx[j]); } quick_sort_float(var, dim2_start, dim2_end-1); m = (dim2_len-1) / 2; if ((dim2_len-1) % 2 == 0) { *date_vario = (var[m-1] + var[m]) / 2.0; } else *date_vario = var[m]; *max_neighdate_diff = var[dim2_len-2]; for (i = 0; i < dim1_len; i++) { for (j = dim2_start; j < dim2_end; j++) { var[j] = abs(array[i][j+1] - array[i][j]); //printf("%d var for band %d: %f\n", j, i+1, (float)var[j]); } quick_sort_float(var, dim2_start, dim2_end-1); // for (j = 0; j < dim2_end; j++) // { // printf("%f\n", var[j]); // } m = (dim2_len-1) / 2; if ((dim2_len-1) % 2 == 0) { //printf("%f\n", var[m-1]); //printf("%f\n", var[m]); output_array[i] = (var[m-1] + var[m]) / 2.0; } else output_array[i] = var[m]; } free(var); return (SUCCESS); } /****************************************************************************** * MODULE: single_median_variogram PURPOSE: calculate absolute variogram for a single band RETURN VALUE: Type = void Value Description ----- ----------- HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 22/06/2019 Su Ye Original Development NOTES: ******************************************************************************/ int single_median_variogram ( short int *array, /* I: input array */ int i_start, int i_end, short int *variogram, short int *mediam_value /* O: outputted mediam value */ ) { int j, m; /* loop indecies */ char FUNC_NAME[] = "single_median_variogram"; /* for error messages */ short int *var; /* pointer for allocation variable memory */ int obs_num; int var_count = 0; short int *array_cpy; obs_num = i_end - i_start + 1; // for (j = 0; j < obs_num; j++) // { // printf("%i\n", array[j]); // } if (obs_num == 1) { *variogram = 0; *mediam_value = array[0]; return (SUCCESS); } var = malloc((obs_num-1) * sizeof(short int)); if (var == NULL) { RETURN_ERROR ("Allocating var memory", FUNC_NAME, ERROR); } array_cpy = malloc(obs_num * sizeof(short int)); if (array_cpy == NULL) { RETURN_ERROR ("Allocating array_cpy memory", FUNC_NAME, ERROR); } for (j = i_start; j < i_end; j++) { var[j] = (short int)abs(array[j+1] - array[j]); //printf("%d var for band %d: %f\n", j, i+1, (float)var[j]); } for (j = i_start; j < i_end+1; j++) { array_cpy[j] = array[j]; //printf("%d var for band %d: %f\n", j, i+1, (float)var[j]); } quick_sort_shortint(var, 0, obs_num-2); // for (j = 0; j < obs_num-1; j++) // { // printf("%d\n", var[j]); // } /* compute variogram */ m = (obs_num-1) / 2; if ((obs_num-1) % 2 == 0) { *variogram = (short int) ((var[m-1] + var[m]) / 2.0); } else *variogram = var[m]; /* compute mediam value */ quick_sort_shortint(array_cpy, i_start, i_end); // for (j = 0; j < obs_num; j++) // { // printf("%d\n", array_cpy[j]); // } m = obs_num / 2; if (obs_num % 2 == 0) { *mediam_value = (short int)((array_cpy[m-1] + array_cpy[m]) / 2.0); } else *mediam_value = array_cpy[m]; free(var); free(array_cpy); return (SUCCESS); } /****************************************************************************** * MODULE: single_median_variogram PURPOSE: calculate absolute variogram for a single band RETURN VALUE: Type = void Value Description ----- ----------- HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 22/06/2019 Su Ye Original Development NOTES: ******************************************************************************/ int single_median_quantile ( short int *array, /* I: input array */ int i_start, int i_end, short int *quantile, /* O: outputted quantile value */ short int *mediam_value ) { int j, m; /* loop indecies */ char FUNC_NAME[] = "single_median_quantile"; /* for error messages */ short int *var; /* pointer for allocation variable memory */ int obs_num; int var_count = 0; short int *array_cpy; obs_num = i_end - i_start + 1; // for (j = 0; j < obs_num; j++) // { // printf("%i\n", array[j]); // } if (obs_num == 1) { *mediam_value = array[0]; *quantile = array[0]; return (SUCCESS); } var = malloc((obs_num-1) * sizeof(short int)); if (var == NULL) { RETURN_ERROR ("Allocating var memory", FUNC_NAME, ERROR); } array_cpy = malloc(obs_num * sizeof(short int)); if (array_cpy == NULL) { RETURN_ERROR ("Allocating array_cpy memory", FUNC_NAME, ERROR); } for (j = i_start; j < i_end+1; j++) { array_cpy[j] = array[j]; //printf("%d var for band %d: %f\n", j, i+1, (float)var[j]); } /* compute mediam value */ quick_sort_shortint(array_cpy, i_start, i_end); // for (j = 0; j < obs_num; j++) // { // printf("%d\n", array_cpy[j]); // } m = obs_num / 2; if (obs_num % 2 == 0) { *mediam_value = (short int)((array_cpy[m-1] + array_cpy[m]) / 2.0); } else *mediam_value = array_cpy[m]; *quantile = array_cpy[obs_num / 4]; free(var); free(array_cpy); return (SUCCESS); } /****************************************************************************** * MODULE: single_mean_rmse PURPOSE: calculate absolute variogram for a single band RETURN VALUE: Type = void Value Description ----- ----------- HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 22/06/2019 Su Ye Original Development NOTES: ******************************************************************************/ int single_mean_rmse ( short int *array, /* I: input array */ int i_start, int i_end, float *rmse, float *mean /* O: outputted mediam value */ ) { int j, m; /* loop indecies */ char FUNC_NAME[] = "single_mean_rse"; /* for error messages */ short int *var; /* pointer for allocation variable memory */ int obs_num; int sum = 0; int rmse_sum = 0; obs_num = i_end - i_start + 1; // for (j = 0; j < obs_num; j++) // { // printf("%i\n", array[j]); // } if (obs_num == 1) { *rmse = 0; *mean = array[0]; return (SUCCESS); } var = malloc((obs_num-1) * sizeof(short int)); if (var == NULL) { RETURN_ERROR ("Allocating var memory", FUNC_NAME, ERROR); } for (j = i_start; j < i_end + 1; j++) { sum = sum + (int)array[j]; } *mean = (float)((float)sum / (float)obs_num); for (j = i_start; j < i_end + 1; j++) { rmse_sum = rmse_sum + (array[j] - *mean) * (array[j] - *mean); } *rmse = (float)sqrt((double)rmse_sum/(double)obs_num); return (SUCCESS); } /****************************************************************************** MODULE: linear_fit_centerdate PURPOSE: Robust fit for one band RETURN VALUE: None HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 5/31/2019 Su Ye Original Development NOTES: ******************************************************************************/ void linear_fit_centerdate ( int *clrx, float **clry, int nums, int start, int center_date, int i_col, short int **composites, int bweighted, float *C0, float *C1 ) { char FUNC_NAME[] = "linear_fit_centerdate"; double c0; double c1; double cov00; double cov01; double cov11; double sumsq; int i; double* x; double* y_b1; double* y_b2; double* y_b3; double* y_b4; double* w; float coefs[ROBUST_COEFFS]; float** x_t; x = (double*)malloc(nums * sizeof(double)); if (x == NULL) { RETURN_ERROR("ERROR allocating x memory", FUNC_NAME, FAILURE); } y_b1 = (double*)malloc(nums * sizeof(double)); if (y_b1 == NULL) { RETURN_ERROR("ERROR allocating y_b1 memory", FUNC_NAME, FAILURE); } y_b2 = (double*)malloc(nums * sizeof(double)); if (y_b2 == NULL) { RETURN_ERROR("ERROR allocating y_b2 memory", FUNC_NAME, FAILURE); } y_b3 = (double*)malloc(nums * sizeof(double)); if (y_b3 == NULL) { RETURN_ERROR("ERROR allocating y_b3 memory", FUNC_NAME, FAILURE); } y_b4 = (double*)malloc(nums * sizeof(double)); if (y_b4 == NULL) { RETURN_ERROR("ERROR allocating y_b4 memory", FUNC_NAME, FAILURE); } w = (double*)malloc(nums * sizeof(double)); if (w == NULL) { RETURN_ERROR("ERROR allocating y_b4 memory", FUNC_NAME, FAILURE); } x_t = (float **)allocate_2d_array(nums, ROBUST_COEFFS - 1, sizeof(float)); if (x_t == NULL) { RETURN_ERROR("ERROR allocating x_t memory", FUNC_NAME, ERROR); } for (i = 0; i < nums; i++) { x_t[i][0] = (float)clrx[i+start]; } /******************************************************************/ /* */ /* Defines the inputs/outputs for robust fitting */ /* */ /******************************************************************/ /******************************************************************/ /* */ /* construct design matrix x for linear fit */ /* */ /******************************************************************/ for (i = 0; i < nums; ++i) { x[i] = (double)clrx[i]; y_b1[i] = (double)clry[0][i]; y_b2[i] = (double)clry[1][i]; y_b3[i] = (double)clry[2][i]; y_b4[i] = (double)clry[3][i]; } /******************************************************************/ /* */ /* perform robust fit */ /* */ /******************************************************************/ if (bweighted == TRUE) { /* create hot weights */ for (i = 0; i < nums; ++i) { w[i] = (double)1/(abs(y_b1[i] - 0.5 * y_b3[i])); } gsl_fit_wlinear (x, 1, w, 1, y_b1, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); composites[0][i_col] = (short int)(c0 + c1 * center_date); C0[0] = (float)c0; C1[0] = (float)c1; gsl_fit_wlinear (x, 1, w, 1, y_b2, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); composites[1][i_col] = (short int)(c0 + c1 * center_date); C0[1] = (float)c0; C1[1] = (float)c1; gsl_fit_wlinear (x, 1, w, 1, y_b3, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); composites[2][i_col] = (short int)(c0 + c1 * center_date); C0[2] = (float)c0; C1[2] = (float)c1; gsl_fit_wlinear (x, 1, w, 1, y_b4, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); composites[3][i_col] = (short int)(c0 + c1 * center_date); C0[3] = (float)c0; C1[3] = (float)c1; } else { /* OLS*/ // gsl_fit_linear (x, 1, y_b1, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); // composites[0][i_col] = (short int)(c0 + c1 * center_date); // C0[0] = (float)c0; // C1[0] = (float)c1; // gsl_fit_linear (x, 1, y_b2, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); // composites[1][i_col] = (short int)(c0 + c1 * center_date); // C0[1] = (float)c0; // C1[1] = (float)c1; // gsl_fit_linear (x, 1, y_b3, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); // composites[2][i_col] = (short int)(c0 + c1 * center_date); // C0[2] = (float)c0; // C1[2] = (float)c1; // gsl_fit_linear (x, 1, y_b4, 1, nums, &c0, &c1, &cov00, &cov01, &cov11, &sumsq); // composites[3][i_col] = (short int)(c0 + c1 * center_date); // C0[3] = (float)c0; // C1[3] = (float)c1; /* robust regression */ for(i = 0; i < TOTAL_IMAGE_BANDS; i++) { auto_robust_fit(x_t, clry, nums, start, i, coefs); composites[i][i_col] = (short int)(coefs[0] + coefs[1] * center_date); C0[i] = (float)coefs[0]; C1[i] = (float)coefs[1]; } } /******************************************************************/ /* */ /* Free the memories */ /* */ /******************************************************************/ free (x); free (y_b1); free (y_b2); free (y_b3); free (y_b4); free (w); /* Free allocated memory */ if (free_2d_array ((void **) x_t) != SUCCESS) { RETURN_ERROR ("Freeing memory: x_t\n", FUNC_NAME, ERROR); } } /****************************************************************************** MODULE: median_filter PURPOSE: calculate mediam filtering for three buf scanline RETURN VALUE: None HISTORY: Date Programmer Reason -------- --------------- ------------------------------------- 6/12/2019 Su Ye Original Development NOTES: ******************************************************************************/ int median_filter ( short int **buf1, short int **buf2, short int **buf3, short int **buf, int *valid_datecount_scanline, /* I: the number of valid dates */ int num_scenes, int n_cols ) { int i, b, j; short int window[9]; for(i = 0; i < n_cols; i++) { for(j = 0; j < valid_datecount_scanline[i]; j++) { if(i==0) { for(b = 0; b < TOTAL_IMAGE_BANDS; b++) { window[0] = buf1[b][i * num_scenes + j]; window[1] = buf1[b][i * num_scenes + j]; window[2] = buf1[b][(i+1) * num_scenes + j]; window[3] = buf2[b][i * num_scenes + j]; window[4] = buf2[b][i * num_scenes + j]; window[5] = buf2[b][(i+1) * num_scenes + j]; window[6] = buf3[b][i * num_scenes + j]; window[7] = buf3[b][i * num_scenes + j]; window[8] = buf3[b][(i+1) * num_scenes + j]; quick_sort_shortint(window, 0, 8); buf[b][i * num_scenes + j] = window[4]; } } else if (i == n_cols - 1) { for(b = 0; b < TOTAL_IMAGE_BANDS; b++) { window[0] = buf1[b][(i-1) * num_scenes + j]; window[1] = buf1[b][i * num_scenes + j]; window[2] = buf1[b][i * num_scenes + j]; window[3] = buf2[b][(i-1) * num_scenes + j]; window[4] = buf2[b][i * num_scenes + j]; window[5] = buf2[b][i * num_scenes + j]; window[6] = buf3[b][(i-1) * num_scenes + j]; window[7] = buf3[b][i * num_scenes + j]; window[8] = buf3[b][i * num_scenes + j]; quick_sort_shortint(window, 0, 8); buf[b][i * num_scenes + j] = window[4]; } } else { for(b = 0; b < TOTAL_IMAGE_BANDS; b++) { window[0] = buf1[b][(i-1) * num_scenes + j]; window[1] = buf1[b][i * num_scenes + j]; window[2] = buf1[b][(i+1) * num_scenes + j]; window[3] = buf2[b][(i-1) * num_scenes + j]; window[4] = buf2[b][i * num_scenes + j]; window[5] = buf2[b][(i+1) * num_scenes + j]; window[6] = buf3[b][(i-1) * num_scenes + j]; window[7] = buf3[b][i * num_scenes + j]; window[8] = buf3[b][(i+1) * num_scenes + j]; quick_sort_shortint(window, 0, 8); buf[b][i * num_scenes + j] = window[4]; } } } } }
{ "alphanum_fraction": 0.3956377396, "avg_line_length": 28.5555555556, "ext": "c", "hexsha": "86d7e538d4942d6e30588011910625cb03fe0249", "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": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "agroimpacts/imager", "max_forks_repo_path": "C/AFMapTSComposite/misc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "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": "agroimpacts/imager", "max_issues_repo_path": "C/AFMapTSComposite/misc.c", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "agroimpacts/imager", "max_stars_repo_path": "C/AFMapTSComposite/misc.c", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:48:12.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:48:12.000Z", "num_tokens": 6952, "size": 28013 }
#ifndef _read_h_included_ #define _read_h_included_ #include <assert.h> #include <stdlib.h> #include <algorithm> #include <cctype> #include <fstream> #include <functional> #include <iostream> #include <map> #include <numeric> #include <set> #include <sstream> #include <vector> #include <sstream> #include <string> #include <boost/config.hpp> #include <boost/foreach.hpp> #include <boost/random.hpp> #include <boost/shared_ptr.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/io.hpp> #include <jsc/bioinfo/gene_anno.hpp> #include <jsc/util/log.hpp> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "splicing_graph.h" #include "accessible_read_starts.h" using namespace std; using namespace boost; using namespace boost::numeric; using namespace jsc::bioinfo; using namespace jsc::util; using boost::shared_ptr; // returns the index (in the isoform) of the first matching exon in the isoform long is_connected_exons_compatible_with_isoform( vector<unsigned long> const & exon_indices, vector<unsigned long> const & iso_exon_indices) { vector<unsigned long>::const_iterator itr, itr2; itr = exon_indices.begin(); itr2 = iso_exon_indices.begin(); bool is_compatible = false; bool found_first_match = false; long first_match_idx = 0; while (itr != exon_indices.end()) { if (itr2 == iso_exon_indices.end()) { is_compatible = false; break; } if (*itr != *itr2) { if (!found_first_match) { itr2++; first_match_idx++; } else { is_compatible = false; break; } } else { if (!found_first_match) { found_first_match = true; is_compatible = true; itr++; itr2++; } else { itr++; itr2++; } } } return (is_compatible ? first_match_idx : -1); } class ReadType { public: static const int LONG_READ = 0; static const int MEDIUM_READ = 1; static const int SHORT_READ = 2; static const int SHORT_CONTIG = 3; static const int CONTIG = 4; static const int LONG_READ_PE = 5; static const int MEDIUM_READ_PE = 6; static const int SHORT_READ_PE = 7; static const string TYPES[]; }; const string ReadType::TYPES[] = {"LONG_READ", "MEDIUM_READ", "SHORT_READ", "SHORT_CONTIG", "CONTIG", "LONG_READ_PE", "MEDIUM_READ_PE", "SHORT_READ_PE"}; class Read { public: string read_type; vector<unsigned long> exon_indices; unsigned long start_at_first_exon; unsigned long end_at_last_exon; Read(shared_ptr<AccessibleReadStarts> const & ars = shared_ptr<AccessibleReadStarts>()) : ars(ars) { read_length = 0; expected_read_length = 0; read_type = "General read"; } unsigned long get_num_isoforms() const { return ars->get_num_isoforms(); } unsigned long get_read_length() const { return read_length; } shared_ptr<AccessibleReadStarts> get_ARS() const { return ars; } virtual unsigned long get_read_span() const { return read_length; } unsigned long get_expected_read_length() const { return expected_read_length; } virtual unsigned long get_expected_read_span() const { return expected_read_length; } virtual bool is_compatible_with_iso( unsigned long const & iso_idx) const = 0; virtual void build( interval_list<long> const & read_il, SetExonp const & exonps, interval_list<long> const & read_il2 = interval_list<long>()) = 0; /// Generates a read from an isoform. // /// The start position of the read in the isoform is either /// determined by \a fixed_read_start or chosen randomly /// according to the actual type of the read. // /// \param[in] iso_idx index of the isoform from which /// the read will be generated. /// exons in the corresponding gene. /// \param[in] fixed_read_start When >= 0, specifies the start /// position (in the isoform) of the /// read to be generated. /// \returns The actual start position (in the isoform) /// of the generated read. virtual unsigned long generate_read( unsigned long const & iso_idx, long fixed_read_start = -1) = 0; virtual double prob_generated_by_iso( unsigned long const & iso_idx) const = 0; virtual string to_string() const = 0; virtual ~Read() {} protected: shared_ptr<AccessibleReadStarts> ars; unsigned long read_length; unsigned long expected_read_length; }; ostream& operator << (ostream& os, Read const & r) { os << r.to_string(); return os; }; typedef shared_ptr<Read> Read_ptr; class Read_stats { public: static const unsigned long medium_single_expected_read_length = 250; static const double medium_cost_per_bp = 7E-5; static const unsigned long short_single_expected_read_length = 30; static const unsigned long short_paired_expected_insert_size = 300; static const double short_cost_per_bp = 7E-6; }; class Read_single : public Read { public: Read_single(shared_ptr<AccessibleReadStarts> ars = shared_ptr<AccessibleReadStarts>()) : Read(ars) { rng = NULL; read_type = "General single read"; } virtual bool is_compatible_with_iso( unsigned long const & iso_idx) const { return (is_connected_exons_compatible_with_isoform( exon_indices, ars->iso_exon_indices[iso_idx]) >= 0); } virtual void build( interval_list<long> const & read_il, SetExonp const & exonps, interval_list<long> const & read_il2 = interval_list<long>()) { L_(debug2) << "Read::build"; unsigned long matching_length = 0; set<unsigned long> index_set; exon_indices.clear(); start_at_first_exon = end_at_last_exon = 0; bool found_start = false; unsigned long il_idx = 0; SetExonp::const_iterator itr = exonps.begin(); long cur_start, cur_end, cur_exon_start; cur_exon_start = 0; L_(debug2) << "Read: " << read_il; L_(debug2) << "Exons: " << exonps; while (il_idx < read_il.get_num_intervals()) { cur_start = read_il.get_starts()[il_idx]; cur_end = read_il.get_ends()[il_idx]; L_(debug2) << "Current interval: [" << cur_start << "," << cur_end << ")"; // find all the exons that overlap with/contain the interval while (itr != exonps.end() && (*itr)->start < cur_end) { L_(debug2) << "Current exon: [" << (*itr)->start << "," << (*itr)->end << ")"; cur_exon_start = max(cur_exon_start, (*itr)->start); if (cur_start >= cur_exon_start && cur_start < (*itr)->end) { if (!found_start) { L_(debug2) << "Found start"; found_start = true; start_at_first_exon = cur_start - (*itr)->start; } else if (cur_start > cur_exon_start) { break; } L_(debug2) << "Add exon #" << distance(exonps.begin(), itr); index_set.insert(distance(exonps.begin(), itr)); cur_exon_start = min((*itr)->end, cur_end); matching_length += cur_exon_start - cur_start; if (cur_end < (*itr)->end) { cur_start = cur_end; end_at_last_exon = cur_end - (*itr)->start; ++il_idx; break; } else if (cur_end == (*itr)->end) { cur_start = cur_end; end_at_last_exon = cur_end - (*itr)->start; ++il_idx; } else { cur_start = (*itr)->end; end_at_last_exon = (*itr)->end - (*itr)->start; } } else if (cur_exon_start > (*itr)->start && cur_exon_start < (*itr)->end) { break; } itr++; } if (cur_start == cur_end) { continue; } else { break; } } BOOST_FOREACH (unsigned long i, index_set) { exon_indices.push_back(i); } read_length = matching_length; } virtual unsigned long generate_read( unsigned long const & iso_idx, long fixed_read_start = -1) { assert(rng != NULL || fixed_read_start >= 0); vector<unsigned long> const & iso_exon_indices = ars->iso_exon_indices[iso_idx]; vector<unsigned long> const & iso_exon_total_lengths = ars->iso_exon_total_lengths[iso_idx]; exon_indices.clear(); unsigned long read_start; if (fixed_read_start < 0) { // randomly generate a read start read_start = (unsigned long)( gsl_ran_flat(rng, 0, ars->get_iso_ARS_total_length(iso_idx))); read_start = ars->ARStart2IsoStart(iso_idx, read_start); } else { read_start = fixed_read_start; } unsigned long read_end = read_start + get_expected_read_length(); read_length = read_end - read_start; L_(debug2) << "Generating read [" << read_start << ", " << read_end << ") length=" << read_length << "bp"; vector<unsigned long>::const_iterator itr = upper_bound(iso_exon_total_lengths.begin(), iso_exon_total_lengths.end(), read_start); assert(itr != iso_exon_total_lengths.end()); unsigned long start_exon_idx = distance( iso_exon_total_lengths.begin(), itr); itr = lower_bound(iso_exon_total_lengths.begin(), iso_exon_total_lengths.end(), read_end); assert(itr != iso_exon_total_lengths.end()); unsigned long end_exon_idx = distance( iso_exon_total_lengths.begin(), itr); L_(debug2) << "Start exon: " << iso_exon_indices[start_exon_idx] << ", end exon: " << iso_exon_indices[end_exon_idx]; for (unsigned long i = start_exon_idx; i <= end_exon_idx; ++i) { exon_indices.push_back(iso_exon_indices[i]); } start_at_first_exon = read_start - (start_exon_idx == 0 ? 0 : iso_exon_total_lengths[start_exon_idx - 1]); end_at_last_exon = read_end - (end_exon_idx == 0 ? 0 : iso_exon_total_lengths[end_exon_idx - 1]); return read_start; } virtual double prob_generated_by_iso( unsigned long const & iso_idx) const { double num_diff_reads = ars->get_iso_ARS_total_length(iso_idx); if (num_diff_reads <= 0) { L_(warning) << read_type << ": supported read length > isoform length" << endl; return 0; } double prob = (double)1.0 / num_diff_reads; return prob; } virtual string to_string() const { std::ostringstream os; os << "[" << read_type << "] " << "(Exons) "; BOOST_FOREACH(unsigned long const & idx, exon_indices) { os << idx << ","; } os << " (Start at first exon) " << start_at_first_exon << " "; os << "(End at last exon) " << end_at_last_exon; return os.str(); } protected: gsl_rng * rng; }; class Read_medium_single : public Read_single { public: Read_medium_single(shared_ptr<AccessibleReadStarts> const & ars = shared_ptr<AccessibleReadStarts>(), gsl_rng * r = NULL, unsigned long expected_length = Read_stats::medium_single_expected_read_length) : Read_single(ars) { rng = r; expected_read_length = expected_length; read_type = "Medium single read"; } }; class Read_short_single : public Read_single { public: Read_short_single(shared_ptr<AccessibleReadStarts> const & ars = shared_ptr<AccessibleReadStarts>(), gsl_rng * r = NULL, unsigned long expected_length = Read_stats::short_single_expected_read_length) : Read_single(ars) { rng = r; expected_read_length = expected_length; read_type = "Short single read"; } }; class Read_paired: public Read { public: Read_single end1; Read_single end2; Read_single span; Read_paired(shared_ptr<AccessibleReadStarts> ars = shared_ptr<AccessibleReadStarts>(), double tolerance = 0) : Read(ars), tolerance(tolerance) { insert_size = expected_insert_size = 0; read_type = "General paired-end read"; end1 = Read_single(ars); end2 = Read_single(ars); span = Read_single(ars); } unsigned long get_expected_insert_size() const { return expected_insert_size; } virtual unsigned long get_read_span() const { return read_length + insert_size; } virtual unsigned long get_expected_read_span() const { return (end1.get_expected_read_length() + end2.get_expected_read_length() + expected_insert_size); } virtual bool is_compatible_with_iso( unsigned long const & iso_idx) const { assert(end1.exon_indices.size() > 0 && end2.exon_indices.size() > 0); if (end1.is_compatible_with_iso(iso_idx) && end2.is_compatible_with_iso(iso_idx)) { if (expected_insert_size == 0) { return true; } vector<unsigned long> const & iso_exon_indices = ars->iso_exon_indices[iso_idx]; vector<unsigned long> const & exon_total_lengths = ars->iso_exon_total_lengths[iso_idx]; vector<unsigned long>::const_iterator itr; unsigned long end1_last_exon_idx = end1.exon_indices [end1.exon_indices.size() - 1]; itr = lower_bound(iso_exon_indices.begin(), iso_exon_indices.end(), end1_last_exon_idx); unsigned long exon_idx = distance( iso_exon_indices.begin(), itr); unsigned long end1_end = (exon_idx > 0 ? exon_total_lengths[exon_idx - 1] : 0) + end1.end_at_last_exon; unsigned long end2_first_exon_idx = end2.exon_indices[0]; itr = lower_bound(iso_exon_indices.begin(), iso_exon_indices.end(), end2_first_exon_idx); exon_idx = distance(iso_exon_indices.begin(), itr); unsigned long end2_start = (exon_idx > 0 ? exon_total_lengths[exon_idx - 1] : 0) + end2.start_at_first_exon; double gap = end2_start - end1_end; double diff = gap / (double)(expected_insert_size); if (diff <= (1.0 + tolerance + epsilon) && diff >= (1.0 - tolerance - epsilon)) { return true; } } return false; } virtual double prob_generated_by_iso( unsigned long const & iso_idx) const { double num_diff_reads = ars->get_iso_ARS_total_length(iso_idx); if (num_diff_reads <= 0) { L_(warning) << read_type << ": supported paired-end read length (including insert) > isoform length" << endl; return 0; } double prob = (double)1.0 / num_diff_reads; return prob; } virtual string to_string() const { std::ostringstream os; os << "[" << read_type << "]" << " End #1: " << end1.to_string() << "; End #2: " << end2.to_string(); return os.str(); } virtual void build( interval_list<long> const & read_il, SetExonp const & exonps, interval_list<long> const & read_il2 = interval_list<long>()) { L_(debug2) << "Read::build"; end1.build(read_il, exonps); end2.build(read_il2, exonps); read_length = end1.get_read_length() + end2.get_read_length(); /// \todo compute insert size and construct span, exon_indices, etc. } virtual unsigned long generate_read( unsigned long const & iso_idx, long fixed_read_start = -1) { assert(rng != NULL || fixed_read_start >= 0); unsigned long read_start; if (fixed_read_start < 0) { // randomly generate a read start read_start = (unsigned long)( gsl_ran_flat(rng, 0, ars->get_iso_ARS_total_length(iso_idx))); read_start = ars->ARStart2IsoStart(iso_idx, read_start); } else { read_start = fixed_read_start; } unsigned long end1_start = end1.generate_read(iso_idx, read_start); unsigned long end2_start = end1_start + end1.get_read_length() + expected_insert_size; end2.generate_read(iso_idx, end2_start); read_length = end1.get_read_length() + end2.get_read_length(); span.generate_read(iso_idx, read_start); exon_indices = span.exon_indices; start_at_first_exon = span.start_at_first_exon; end_at_last_exon = span.end_at_last_exon; return end1_start; } protected: unsigned long insert_size; unsigned long expected_insert_size; double tolerance; static const double epsilon = 1E-5; gsl_rng * rng; }; void generate_reads(unsigned long const & num_reads, Isoforms const & iso, shared_ptr<Read> readp, gsl_rng * rng, ublas::matrix<double> & m_delta_G, bool known_isoforms_only = false) { gsl_ran_discrete_t * discrete_g = gsl_ran_discrete_preproc( iso.num_known_isoforms, iso.known_iso_probs); for (unsigned long i = 0; i < num_reads; ++i) { unsigned long iso_idx = gsl_ran_discrete(rng, discrete_g); L_(debug2) << "Selected known isoform " << iso_idx; if (!known_isoforms_only) { iso_idx = iso.known_iso_indices[iso_idx]; } readp->generate_read(iso_idx); L_(debug2) << *readp; if (known_isoforms_only) { for (unsigned long j = 0; j < iso.num_known_isoforms; ++j) { if (readp->is_compatible_with_iso(j)) { m_delta_G(i,j) = readp->prob_generated_by_iso(j); } } } else { for (unsigned long j = 0; j < iso.num_possible_isoforms; ++j) { if (readp->is_compatible_with_iso(j)) { m_delta_G(i,j) = readp->prob_generated_by_iso(j); } } } } gsl_ran_discrete_free(discrete_g); } class Read_short_paired: public Read_paired { public: Read_short_paired(shared_ptr<AccessibleReadStarts> ars = shared_ptr<AccessibleReadStarts>(), gsl_rng * r = NULL, unsigned long expected_length = 2 * Read_stats::short_single_expected_read_length, unsigned long expected_insert = Read_stats::short_paired_expected_insert_size, double tolerance = 0) : Read_paired(ars, tolerance) { rng = r; expected_read_length = expected_length; insert_size = expected_insert_size = expected_insert; read_type = "Short paired-end read"; shared_ptr<AccessibleReadStarts> end_ars( new AccessibleReadStarts( ars->iso_exon_indices, ars->iso_exon_total_lengths, ars->exon_lengths, expected_length / 2)); end1 = Read_short_single(end_ars, r, expected_length / 2); end2 = Read_short_single(end_ars, r, expected_length / 2); span = Read_medium_single(ars, r, expected_length + expected_insert); } }; void compute_iso_probs_EM_step( unsigned long num_possible_isoforms, vector<ublas::matrix<double> > const & m_delta_Gs, vector<double> const & old_theta, vector<double> & new_theta) { for (unsigned k = 0; k < num_possible_isoforms; ++k) { double sum_zeta = 0; double num_total_reads = 0; BOOST_FOREACH (ublas::matrix<double> const & m_delta_G, m_delta_Gs) { unsigned long num_reads = m_delta_G.size1(); num_total_reads += (double)num_reads; for (unsigned long i = 0; i < num_reads; ++i) { double sum_local_probs = 0; for (unsigned k2 = 0; k2 < num_possible_isoforms; ++k2) { sum_local_probs += old_theta[k2] * m_delta_G(i, k2); } if (sum_local_probs > 0) { double local_prob = old_theta[k] * m_delta_G(i, k); if (local_prob > 0) { sum_zeta += local_prob / sum_local_probs; } } } } new_theta[k] = sum_zeta / num_total_reads; } } double reads_log_likelihood( unsigned long num_possible_isoforms, vector<ublas::matrix<double> > const & m_delta_Gs, vector<double> const & theta) { double ll = 0; BOOST_FOREACH (ublas::matrix<double> const & m_delta_G, m_delta_Gs) { unsigned long num_reads = m_delta_G.size1(); for (unsigned long i = 0; i < num_reads; ++i) { double sum_local_probs = 0; for (unsigned k = 0; k < num_possible_isoforms; ++k) { sum_local_probs += theta[k] * m_delta_G(i, k); } ll += log(sum_local_probs); } } return ll; } void compute_iso_probs_EM( unsigned long num_possible_isoforms, vector<ublas::matrix<double> > const & m_delta_Gs, vector<double> & theta) { theta.resize(num_possible_isoforms, (double)1.0 / (double)num_possible_isoforms); double ll, old_ll; vector<double> old_theta; unsigned long count = 0; do { old_theta = theta; old_ll = reads_log_likelihood( num_possible_isoforms, m_delta_Gs, old_theta); compute_iso_probs_EM_step(num_possible_isoforms, m_delta_Gs, old_theta, theta); ll = reads_log_likelihood( num_possible_isoforms, m_delta_Gs, theta); if (++count == 100) { L_(debug) << "log likelihood: " << old_ll << " -> " << ll; count = 0; } } while (abs(1.0 - old_ll / ll) > 1E-6); } void err_known_iso_probs(Isoforms const & iso, vector<double> const & theta, double & abs_err, double & sse) { abs_err = sse = 0; for (unsigned long i = 0; i < iso.num_known_isoforms; ++i) { abs_err += abs(iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]); sse += (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]) * (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]); } } void err_possible_iso_probs(Isoforms const & iso, vector<double> const & theta, double & abs_err, double & sse) { abs_err = sse = 0; for (unsigned long i = 0; i < iso.num_possible_isoforms; ++i) { abs_err += theta[i]; sse += theta[i] * theta[i]; } for (unsigned long i = 0; i < iso.num_known_isoforms; ++i) { abs_err -= theta[iso.known_iso_indices[i]]; abs_err += abs(iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]); sse -= theta[iso.known_iso_indices[i]] * theta[iso.known_iso_indices[i]]; sse += (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]) * (iso.known_iso_probs[i] - theta[iso.known_iso_indices[i]]); } } #endif
{ "alphanum_fraction": 0.6779188305, "avg_line_length": 30.0086580087, "ext": "h", "hexsha": "a33b20e555e31e9ad4465f5bd4ebdbf1963065f7", "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": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_path": "common/read.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_path": "common/read.h", "max_line_length": 153, "max_stars_count": 7, "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_path": "common/read.h", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "num_tokens": 5866, "size": 20796 }
/* * mvdens.h * likely * * Created by Karim Benabed on 10/03/08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ #ifndef __MVDENS_H #define __MVDENS_H #ifdef __PLANCK__ #include "HL2_likely/tools/errorlist.h" #include "HL2_likely/tools/io.h" #include "HL2_likely/tools/maths_base.h" #else #include "errorlist.h" #include "io.h" #include "maths_base.h" #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_vector_int.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_gamma.h> /*#ifdef HAS_LAPACK #ifdef HAS_MKL #include "mkl_blas.h" #include "mkl_lapack.h" #else #include "blas.h" #include "lapack.h" #endif #endif */ #define __MVDENS_PARANOID_DEBUG__ /* errors */ #define mv_base -700 #define mv_allocate -1 + mv_base #define mv_serialize -2 + mv_base #define mv_outOfBound -3 + mv_base #define mv_badComm -4 + mv_base #define mv_negWeight -5 + mv_base #define mv_cholesky -6 + mv_base #define mv_negative -7 + mv_base #define mv_undef -8 + mv_base #define mv_file -9 + mv_base #define mv_io -10 + mv_base #define mv_tooManySteps -11 + mv_base #define mv_dimension -12 + mv_base #define mv_type -13 + mv_base #define mv_negHatCl -14 + mv_base #define PI 3.141592653589793 #define LOGSQRT2PI 0.918938533204673 #ifndef DYNMAX #define DYNMAX 500.0 #endif #define mv_INF 1e99 #define mv_EXP 2 #define mv_NORM 1 #define mv_UNORM 0 #define MVT_DF 3 typedef struct { size_t ndim; void *buf; int own_buf; double *mean; double *std; double *x_tmp; gsl_vector_view mean_view_container; gsl_vector *mean_view; gsl_vector_view x_tmp_view_container; gsl_vector *x_tmp_view; gsl_matrix_view std_view_container; gsl_matrix *std_view; size_t band_limit; int chol; int df; double detL; /* Determinant of L, where L^t L = Covariance matrix */ } mvdens; typedef struct { size_t ncomp, ndim; int init_cwght; double *wght, *cwght; gsl_vector_view wght_view_container, cwght_view_container; gsl_vector *wght_view, *cwght_view; mvdens **comp; void *buf_comp; } mix_mvdens; // init and stuff mvdens * mvdens_alloc(size_t ndim, error **err); mvdens * mvdens_init(mvdens *g, size_t nndim, double* mn, double* std, error **err); void mvdens_empty(mvdens *g); void mvdens_free(mvdens ** g); void mvdens_free_void(void **g); void mvdens_print(FILE* where, mvdens* what); mvdens *mvdens_dwnp(FILE* where, error **err); mvdens *mvdens_read_and_chol(FILE *where, error **err); void mvdens_dump(FILE* where, mvdens* what); void mvdens_chdump(const char *name, mvdens* what, error **err); void mvdens_set_band_limit(mvdens *self, size_t value); void mvdens_from_meanvar(mvdens *m, const double *pmean, const double *pvar, double correct); //computations double determinant(const double *L, size_t ndim); void mvdens_cholesky_decomp(mvdens* self, error **err); double* mvdens_ran(double* dest, mvdens * g, gsl_rng * r,error **err); double scalar_product(mvdens *g, const double *x, error **err); double mvdens_log_pdf(mvdens *g, const double * x, error ** err); double mvdens_log_pdf_void(void *g, const double *x, error **err); double mvdens_inverse(mvdens *m, error **err); /* mix_mvdens functions */ mix_mvdens *mix_mvdens_alloc(size_t ncomp, size_t size,error **err); void mix_mvdens_copy(mix_mvdens *target, const mix_mvdens *source, error **err); void mix_mvdens_free_void(void **m); void mix_mvdens_free(mix_mvdens **m); void mix_mvdens_print(FILE* where,mix_mvdens* what); void mix_mvdens_dump(FILE* where,mix_mvdens* what); mix_mvdens * mix_mvdens_dwnp(FILE* where,error **err); void mix_mvdens_set_band_limit(mix_mvdens *self, size_t value); double effective_number_of_components(const mix_mvdens *self, error **err); size_t mix_mvdens_size(size_t ncomp,size_t ndim); void* serialize_mix_mvdens(mix_mvdens* self, size_t *sz,error** err); mix_mvdens* deserialize_mix_mvdens(void* serialized, size_t sz,error **err); void mix_mvdens_cholesky_decomp(mix_mvdens* self, error **err); double* mix_mvdens_ran(double* dest,size_t *index, mix_mvdens *m, gsl_rng * r, error **err); size_t ranindx(double *cw, size_t nE, gsl_rng * r, error ** err); double mix_mvdens_log_pdf(mix_mvdens *m, const double *x, error **err); double mix_mvdens_log_pdf_void(void *m, const double *x, error **err); #define MALLOC_IF_NEEDED(ret,dest,size,err) { \ if (dest==NULL) { \ ret= (double*) malloc_err(size,err); \ } else { \ ret=dest; \ } \ } #ifdef HAS_HDF5 #include "hdf5.h" #define hdf5_base mv_io void mvdens_hdfdump_infile(mvdens* mv,hid_t loc_id,error **err); void mvdens_hdfdump(mvdens* mv,char *fname,error **err); void mix_mvdens_hdfdump(mix_mvdens* mmv,char *fname,error **err); mvdens* mvdens_hdfdwnp_infile(mvdens* mv,hid_t loc_id,error **err); mvdens* mvdens_hdfdwnp(char *fname,error **err); mix_mvdens* mix_mvdens_hdfdwnp(char *fname,error **err); #endif #endif
{ "alphanum_fraction": 0.7394200627, "avg_line_length": 28.8361581921, "ext": "h", "hexsha": "1e2c45f8049571d289a4d8d741bdec13e3a1dabe", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_path": "cosmosis-standard-library/likelihood/planck2015/plc-2.0/src/minipmc/mvdens.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "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": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_path": "cosmosis-standard-library/likelihood/planck2015/plc-2.0/src/minipmc/mvdens.h", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_path": "cosmosis-standard-library/likelihood/planck2015/plc-2.0/src/minipmc/mvdens.h", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "num_tokens": 1635, "size": 5104 }
/* Copyright [2017-2021] [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_POOL_SESSION_H_ #define _MCAS_POOL_SESSION_H_ #include <gsl/pointers> #include <memory> class Pool_instance; struct pool_session { pool_session(gsl::not_null<std::shared_ptr<Pool_instance>> ph) : pool(ph), canary(0x45450101) { } ~pool_session() { } bool check() const { return canary == 0x45450101; } gsl::not_null<std::shared_ptr<Pool_instance>> pool; const unsigned canary; }; #endif
{ "alphanum_fraction": 0.7502487562, "avg_line_length": 28.7142857143, "ext": "h", "hexsha": "b5cb07faf0df9aee18e0f604641b24cd8d57df20", "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": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "IBM/artemis", "max_forks_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "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": "IBM/artemis", "max_issues_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "IBM/artemis", "max_stars_repo_path": "src/components/store/mapstore/src/pool_session.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 251, "size": 1005 }
#ifndef __SAMPLE_H__ #define __SAMPLE_H__ #include <gsl/gsl_rng.h> #include <pthread.h> #include <stdint.h> #include "parse_mmaps.h" #define NUM_USER_LOCKS 2000 struct sample_thread_info; struct index_update; struct sample_threads; /* Thread utility functions */ void initialize_threads(struct sample_threads* sample_threads, int num_threads, const struct mmap_info* mmap_info); void destroy_threads(struct sample_threads* sample_threads); /* Resampling functions */ /* Set all topic and POV assignments to -1, not doing any index updates. Used before initializing topics and POVs.*/ void resample_null(struct sample_threads* sample_threads); /* Initialize topic and POV assignments by sampling them uniformly at random and performing index updates. */ void resample_uniform(struct sample_threads* sample_threads); /* Re-sample topics and POVs. One iteration of Gibbs sampling. */ void resample(struct sample_threads* sample_threads); /* Re-sample assignments, but (approximately) in the opposite order as resample(). Used during model selection. */ void resample_reverse(struct sample_threads* sample_threads); /* Rather than re-sampling randomly, always choose the maximum probability assignment. Useful for finding a high probability assignment of topics and POVs after random sampling. */ void resample_maximize(struct sample_threads* sample_threads); /* Restore a set of assignments, updating indexes as necessary */ void resample_restore(struct sample_threads* sample_threads, const struct revision_assignment* revision_assignments); /* Set all topic and POV assignments to -1, subtracting the assignments from indexes. Primarily useful for verifying that indexes were correct. */ void resample_zero(struct sample_threads* sample_threads); /* Parallel probability computations */ /* Compute the log probability of transitioning to the specified assignments from the current assignments (don't actually transition to them). */ double transition_probability(struct sample_threads* sample_threads, const struct revision_assignment* revision_assignments); /* Compute the likelihood of the current model and topic/POV assignments */ double parallel_log_likelihood(struct sample_threads* sample_threads); /* Other miscellaneous parallel utility routines */ /* Set all of the user topic/POV distributions to alpha. Used during initialization. */ void parallel_initialize_user_topics(struct sample_threads* sample_threads); /* Structs to hold synchronization and thread information. */ struct sample_thread_info { /* Each thread gets its own random number generator, initialized with a different seed. */ gsl_rng* rand_gen; /* A num_topics * num_povs_per_topic array which threads use to sample new topic and POV assignments. */ double* sampling_array; /* Each thread gets its own copy of mmap_info, allowing us to replace topic_index_mmap with a private copy which is manually synchronized. */ struct mmap_info mmap_info; // Sample only pages numbered (page# % mod_n) == sample_pages int sample_pages; int mod_n; // Information about the current thread. pthread_t thread; /* An array of locks to synchronize access and updates to user topic/POV distributions. For a given user's topic and POV distribution, the lock to use is userid % NUM_USER_LOCKS. */ pthread_rwlock_t* user_locks; /* Memory accounting for the topic_index_mmap copy, if any. One thread updates the original, and so does not have a specially allocated topic index, in which case allocated_topic_dist will be NULL. */ char* allocated_topic_dist; /* The index of the first position in the topic index update queue that we have not read. */ int64_t last_queue_position; /* Pointers to the global topic index update queue, and the global position of the first empty slot in the queue. Access to the queue location is synchronized with queue_lock. */ struct index_update* index_update_queue; int64_t* queue_location; pthread_mutex_t* queue_lock; /* Generally +1 or -1, indicating whether sampling is forward or backward. */ int increment; /* Helper functions to specify sampling behavior, replacing small or large parts of the sampling routine. */ void (*revision_callback) (struct sample_thread_info*, int64_t); void (*index_update_function) (const struct mmap_info* mmap_info, const struct index_update* patch); void (*sample_function) (const double* sampling_array, double probability_sum, int num_topics, int pov_per_topic, int* chosen_topic, int* chosen_pov, gsl_rng* rand_gen); /* When computing transition probabilities, these assignments specify which assignments the transition is to. */ const struct revision_assignment* reference_assignments; double output; }; struct sample_threads { struct sample_thread_info* thread_info; pthread_mutex_t queue_lock; pthread_rwlock_t user_locks[NUM_USER_LOCKS]; int num_threads; struct index_update* index_update_queue; // One past the last value in the queue int64_t queue_location; }; #endif
{ "alphanum_fraction": 0.7673698471, "avg_line_length": 35.6344827586, "ext": "h", "hexsha": "590b9832bae0aad642f034e816108be8367aa4ae", "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": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "allenlavoie/topic-pov", "max_forks_repo_path": "src/sample.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "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": "allenlavoie/topic-pov", "max_issues_repo_path": "src/sample.h", "max_line_length": 79, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "allenlavoie/topic-pov", "max_stars_repo_path": "src/sample.h", "max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z", "num_tokens": 1079, "size": 5167 }
#pragma once #include <autograph/Core/Types.h> #include <gsl/span> #include <gsl/string_span> namespace ag { // until a standard solution appears using gsl::span; using gsl::string_span; }
{ "alphanum_fraction": 0.7357512953, "avg_line_length": 17.5454545455, "ext": "h", "hexsha": "2db8ff63df5157164debaeeddddc243a293d4a92", "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": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ennis/autograph-pipelines", "max_forks_repo_path": "include/autograph/Core/Support/Span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "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": "ennis/autograph-pipelines", "max_issues_repo_path": "include/autograph/Core/Support/Span.h", "max_line_length": 37, "max_stars_count": 1, "max_stars_repo_head_hexsha": "afc66ef60bf99fca26d200bd7739528e1bf3ed8c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ennis/autograph-pipelines", "max_stars_repo_path": "include/autograph/Core/Support/Span.h", "max_stars_repo_stars_event_max_datetime": "2021-04-24T12:29:42.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-24T12:29:42.000Z", "num_tokens": 49, "size": 193 }
#pragma once #include <gsl\gsl> #include "Texture.h" #include "Rectangle.h" namespace Library { class Texture2D final : public Texture { RTTI_DECLARATIONS(Texture2D, Texture) public: Texture2D(const winrt::com_ptr<ID3D11ShaderResourceView>& shaderResourceView, std::uint32_t width, std::uint32_t height); Texture2D(const Texture2D&) = default; Texture2D& operator=(const Texture2D&) = default; Texture2D(Texture2D&&) = default; Texture2D& operator=(Texture2D&&) = default; ~Texture2D() = default; static std::shared_ptr<Texture2D> CreateTexture2D(gsl::not_null<ID3D11Device*> device, const D3D11_TEXTURE2D_DESC& textureDesc); static std::shared_ptr<Texture2D> CreateTexture2D(gsl::not_null<ID3D11Device*> device, std::uint32_t width, std::uint32_t height, std::uint32_t mipLevels = 1, std::uint32_t arraySize = 1, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC sampleDesc = { 1, 0 }, std::uint32_t bindFlags = D3D11_BIND_UNORDERED_ACCESS | D3D11_BIND_SHADER_RESOURCE, std::uint32_t cpuAccessFlags = 0); std::uint32_t Width() const; std::uint32_t Height() const; Rectangle Bounds() const; private: std::uint32_t mWidth; std::uint32_t mHeight; }; }
{ "alphanum_fraction": 0.7599667774, "avg_line_length": 37.625, "ext": "h", "hexsha": "5d472f0eba5306e42dca6985b7d72803e4a8f852", "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": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/Library.Shared/Texture2D.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "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": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/Library.Shared/Texture2D.h", "max_line_length": 397, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/Library.Shared/Texture2D.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 371, "size": 1204 }
/* Copyright (c) 2014, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BLAS_WRAPPER_H #define BLAS_WRAPPER_H #include <cblas.h> namespace blas { inline void gemm(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* B, bool transposeB, int rowsB, int colsB, double alpha = 1.0, double beta = 0.0) { cblas_dgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB); } inline void gemm(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* B, bool transposeB, int rowsB, int colsB, float alpha = 1.0f, float beta = 0.0f) { cblas_sgemm(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, transposeB ? CblasTrans : CblasNoTrans, transposeA ? colsA : rowsA, transposeB ? rowsB : colsB, transposeB ? colsB : rowsB, alpha, A, colsA, B, colsB, beta, Y, transposeB ? rowsB : colsB); } inline void gemv(double* Y, const double* A, bool transposeA, int rowsA, int colsA, const double* x, double alpha = 1.0, double beta = 0.0) { cblas_dgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1); } inline void gemv(float* Y, const float* A, bool transposeA, int rowsA, int colsA, const float* x, float alpha = 1.0, float beta = 0.0) { cblas_sgemv(CblasRowMajor, transposeA ? CblasTrans : CblasNoTrans, rowsA, colsA, alpha, A, colsA, x, 1, beta, Y, 1); } inline void ger(double* Y, const double * A, int rowsA, const double* X, int rowsX, double alpha = 1.0) { cblas_dger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX); } inline void ger(float* Y, const float * A, int rowsA, const float* X, int rowsX, float alpha = 1.0) { cblas_sger(CblasRowMajor, rowsA, rowsX, alpha, A, 1, X, 1, Y, rowsX); } inline double norm2(double* X, int n, int stride = 1) { return cblas_dnrm2(n, X, stride); } inline float norm2(float* X, int n, int stride = 1) { return cblas_snrm2(n, X, stride); } inline void scale(float alpha, float* X, int n, int stride = 1) { return cblas_sscal(n, alpha, X, stride); } inline void scale(double alpha, double* X, int n, int stride = 1) { return cblas_dscal(n, alpha, X, stride); } } #endif
{ "alphanum_fraction": 0.740470852, "avg_line_length": 41.488372093, "ext": "h", "hexsha": "802ab2e719c1a7366b3a29fbdb7b2378ff18110f", "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": "74759d35f7635ff725629a1ae555d313f3e9fb29", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "klindworth/disparity_estimation", "max_forks_repo_path": "neural_network/blas_wrapper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "74759d35f7635ff725629a1ae555d313f3e9fb29", "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": "klindworth/disparity_estimation", "max_issues_repo_path": "neural_network/blas_wrapper.h", "max_line_length": 256, "max_stars_count": null, "max_stars_repo_head_hexsha": "74759d35f7635ff725629a1ae555d313f3e9fb29", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "klindworth/disparity_estimation", "max_stars_repo_path": "neural_network/blas_wrapper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1031, "size": 3568 }
/* specfunc/mathieu_angfunc.c * * Copyright (C) 2002 Lowell Johnson * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: L. Johnson */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_mathieu.h> int gsl_sf_mathieu_ce_e(int order, double qq, double zz, gsl_sf_result *result) { int even_odd, ii, status; double coeff[GSL_SF_MATHIEU_COEFF], norm, fn, factor; gsl_sf_result aa; norm = 0.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* Handle the trivial case where q = 0. */ if (qq == 0.0) { norm = 1.0; if (order == 0) norm = sqrt(2.0); fn = cos(order*zz)/norm; result->val = fn; result->err = 2.0*GSL_DBL_EPSILON; factor = fabs(fn); if (factor > 1.0) result->err *= factor; return GSL_SUCCESS; } /* Use symmetry characteristics of the functions to handle cases with negative order. */ if (order < 0) order *= -1; /* Compute the characteristic value. */ status = gsl_sf_mathieu_a_e(order, qq, &aa); if (status != GSL_SUCCESS) { return status; } /* Compute the series coefficients. */ status = gsl_sf_mathieu_a_coeff(order, qq, aa.val, coeff); if (status != GSL_SUCCESS) { return status; } if (even_odd == 0) { fn = 0.0; norm = coeff[0]*coeff[0]; for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) { fn += coeff[ii]*cos(2.0*ii*zz); norm += coeff[ii]*coeff[ii]; } } else { fn = 0.0; for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) { fn += coeff[ii]*cos((2.0*ii + 1.0)*zz); norm += coeff[ii]*coeff[ii]; } } norm = sqrt(norm); fn /= norm; result->val = fn; result->err = 2.0*GSL_DBL_EPSILON; factor = fabs(fn); if (factor > 1.0) result->err *= factor; return GSL_SUCCESS; } int gsl_sf_mathieu_se_e(int order, double qq, double zz, gsl_sf_result *result) { int even_odd, ii, status; double coeff[GSL_SF_MATHIEU_COEFF], norm, fn, factor; gsl_sf_result aa; norm = 0.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* Handle the trivial cases where order = 0 and/or q = 0. */ if (order == 0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } if (qq == 0.0) { norm = 1.0; fn = sin(order*zz); result->val = fn; result->err = 2.0*GSL_DBL_EPSILON; factor = fabs(fn); if (factor > 1.0) result->err *= factor; return GSL_SUCCESS; } /* Use symmetry characteristics of the functions to handle cases with negative order. */ if (order < 0) order *= -1; /* Compute the characteristic value. */ status = gsl_sf_mathieu_b_e(order, qq, &aa); if (status != GSL_SUCCESS) { return status; } /* Compute the series coefficients. */ status = gsl_sf_mathieu_b_coeff(order, qq, aa.val, coeff); if (status != GSL_SUCCESS) { return status; } if (even_odd == 0) { fn = 0.0; for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) { norm += coeff[ii]*coeff[ii]; fn += coeff[ii]*sin(2.0*(ii + 1)*zz); } } else { fn = 0.0; for (ii=0; ii<GSL_SF_MATHIEU_COEFF; ii++) { norm += coeff[ii]*coeff[ii]; fn += coeff[ii]*sin((2.0*ii + 1)*zz); } } norm = sqrt(norm); fn /= norm; result->val = fn; result->err = 2.0*GSL_DBL_EPSILON; factor = fabs(fn); if (factor > 1.0) result->err *= factor; return GSL_SUCCESS; } int gsl_sf_mathieu_ce_array(int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]) { int even_odd, order, ii, jj, status; double coeff[GSL_SF_MATHIEU_COEFF], *aa = work->aa, norm; /* Initialize the result array to zeroes. */ for (ii=0; ii<nmax-nmin+1; ii++) result_array[ii] = 0.0; /* Ensure that the workspace is large enough to accomodate. */ if (work->size < (unsigned int)nmax) { GSL_ERROR("Work space not large enough", GSL_EINVAL); } if (nmin < 0 || nmax < nmin) { GSL_ERROR("domain error", GSL_EDOM); } /* Compute all of the eigenvalues up to nmax. */ gsl_sf_mathieu_a_array(0, nmax, qq, work, aa); for (ii=0, order=nmin; order<=nmax; ii++, order++) { norm = 0.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* Handle the trivial case where q = 0. */ if (qq == 0.0) { norm = 1.0; if (order == 0) norm = sqrt(2.0); result_array[ii] = cos(order*zz)/norm; continue; } /* Compute the series coefficients. */ status = gsl_sf_mathieu_a_coeff(order, qq, aa[order], coeff); if (status != GSL_SUCCESS) return status; if (even_odd == 0) { norm = coeff[0]*coeff[0]; for (jj=0; jj<GSL_SF_MATHIEU_COEFF; jj++) { result_array[ii] += coeff[jj]*cos(2.0*jj*zz); norm += coeff[jj]*coeff[jj]; } } else { for (jj=0; jj<GSL_SF_MATHIEU_COEFF; jj++) { result_array[ii] += coeff[jj]*cos((2.0*jj + 1.0)*zz); norm += coeff[jj]*coeff[jj]; } } norm = sqrt(norm); result_array[ii] /= norm; } return GSL_SUCCESS; } int gsl_sf_mathieu_se_array(int nmin, int nmax, double qq, double zz, gsl_sf_mathieu_workspace *work, double result_array[]) { int even_odd, order, ii, jj, status; double coeff[GSL_SF_MATHIEU_COEFF], *bb = work->bb, norm; /* Initialize the result array to zeroes. */ for (ii=0; ii<nmax-nmin+1; ii++) result_array[ii] = 0.0; /* Ensure that the workspace is large enough to accomodate. */ if (work->size < (unsigned int)nmax) { GSL_ERROR("Work space not large enough", GSL_EINVAL); } if (nmin < 0 || nmax < nmin) { GSL_ERROR("domain error", GSL_EDOM); } /* Compute all of the eigenvalues up to nmax. */ gsl_sf_mathieu_b_array(0, nmax, qq, work, bb); for (ii=0, order=nmin; order<=nmax; ii++, order++) { norm = 0.0; even_odd = 0; if (order % 2 != 0) even_odd = 1; /* Handle the trivial cases where order = 0 and/or q = 0. */ if (order == 0) { norm = 1.0; result_array[ii] = 0.0; continue; } if (qq == 0.0) { norm = 1.0; result_array[ii] = sin(order*zz); continue; } /* Compute the series coefficients. */ status = gsl_sf_mathieu_b_coeff(order, qq, bb[order], coeff); if (status != GSL_SUCCESS) { return status; } if (even_odd == 0) { for (jj=0; jj<GSL_SF_MATHIEU_COEFF; jj++) { result_array[ii] += coeff[jj]*sin(2.0*(jj + 1)*zz); norm += coeff[jj]*coeff[jj]; } } else { for (jj=0; jj<GSL_SF_MATHIEU_COEFF; jj++) { result_array[ii] += coeff[jj]*sin((2.0*jj + 1.0)*zz); norm += coeff[jj]*coeff[jj]; } } norm = sqrt(norm); result_array[ii] /= norm; } return GSL_SUCCESS; } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_mathieu_ce(int order, double qq, double zz) { EVAL_RESULT(gsl_sf_mathieu_ce_e(order, qq, zz, &result)); } double gsl_sf_mathieu_se(int order, double qq, double zz) { EVAL_RESULT(gsl_sf_mathieu_se_e(order, qq, zz, &result)); }
{ "alphanum_fraction": 0.5474238876, "avg_line_length": 23.3333333333, "ext": "c", "hexsha": "10727e111afcc99174c4e7c9451b5ce5aa3bf596", "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/specfunc/mathieu_angfunc.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/mathieu_angfunc.c", "max_line_length": 79, "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/specfunc/mathieu_angfunc.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": 2533, "size": 8540 }
/* ** ECM - eigenvector centrality mapping ** ** G.Lohmann, MPI-KYB, updated Oct 2018 */ #include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif /*_OPENMP*/ #define SQR(x) ((x) * (x)) #define ReLU(x) ((x) > 0 ? (x) : 0) extern void VMatrixECM(gsl_matrix_float *,float *,int,int,VImage); extern void VMatrixProjection(gsl_matrix_float *X,float *ev,int,int seed); extern VImage VoxelMap(VAttrList list,VImage mask,size_t nvox); extern size_t NumVoxels(VImage); extern gsl_matrix_float *ReadDataECM(VAttrList,VImage,VImage,VShort,VShort,int,size_t); extern VImage WriteOutput(VAttrList,VImage,float *,size_t); extern int Irreducible(gsl_matrix_float *X,int type); void NormVec(float *x,size_t nvox) { size_t i; float sum=0; sum = 0; for (i=0; i<nvox; i++) sum += (x[i]*x[i]); sum = sqrt(sum); for (i=0; i<nvox; i++) x[i] /= sum; } /* needed for ECM-RLC, negative */ void SignFlip(gsl_matrix_float *X) { float u=0; size_t nt = X->size2; size_t i,j,n=nt/2; for (i=0; i<X->size1; i++) { for (j=n; j<nt; j++) { u = gsl_matrix_float_get(X,i,j); gsl_matrix_float_set(X,i,j,-u); } } } /* fast, memory efficient power iteration, used in ECM-RLC, ECM-Add1 */ void PowerIteration(gsl_matrix_float *X,float *ev,int type,int maxiter) { int iter; float vsum=0,d=0; size_t i; size_t nvox = X->size1; size_t nt = X->size2; float scale = 1.0/(float)nt; fprintf(stderr," power iteration...\n"); gsl_vector_float *y = gsl_vector_float_calloc(nvox); gsl_vector_float *z = gsl_vector_float_calloc(nt); Irreducible(X,type); /* check if corr matrix is irreducible */ NormVec(ev,nvox); for (i=0; i<nvox; i++) y->data[i] = ev[i]; /* power iterations */ for (iter=0; iter<maxiter; iter++) { /* R = (X^t X)/n */ gsl_blas_sgemv (CblasTrans,1.0,X,y,0.0,z); if (type == 7) SignFlip(X); gsl_blas_sgemv (CblasNoTrans,1.0,X,z,0.0,y); if (type == 7) SignFlip(X); gsl_vector_float_scale(y,scale); /* ECM-Add1, (R+E)v = Rv + Ev */ if (type == 1) { vsum = 0; for (i=0; i<nvox; i++) vsum += ev[i]; for (i=0; i<nvox; i++) y->data[i] += vsum; } /* normalize */ NormVec(y->data,nvox); /* check convergence */ d = 0; for (i=0; i<nvox; i++) { d += SQR(ev[i] - y->data[i]); ev[i] = y->data[i]; } fprintf(stderr," %5d %.6f\n",(int)iter,d); if (iter > 2 && d < 1.0e-6) break; } gsl_vector_float_free(y); gsl_vector_float_free(z); } float *VECM(gsl_matrix_float *X,int type,VBoolean project,int seed,int maxiter,VImage map) { size_t i,j; size_t nvox = X->size1; size_t nt = X->size2; if (type == 0 || type == 7) nt /= 2; /* ini eigenvector */ float u=0; float *eigvec = (float *) VCalloc(nvox,sizeof(float)); for (i=0; i<nvox; i++) eigvec[i] = 1.0/(float)nt; /* no matrix projection */ if (!project) { switch (type) { case 0: /* ECM-RLC positive */ for (i=0; i<X->size1; i++) { for (j=0; j<nt; j++) { u = gsl_matrix_float_get(X,i,j); gsl_matrix_float_set(X,i,j+nt,fabs(u)); } } PowerIteration(X,eigvec,type,maxiter); break; case 1: /* ECM-Add1 */ PowerIteration(X,eigvec,type,maxiter); break; case 6: /* no filter, risky */ PowerIteration(X,eigvec,1,maxiter); /* initialize using ecm-add1 */ PowerIteration(X,eigvec,0,maxiter); break; /* ECM-RLC negative */ case 7: for (i=0; i<X->size1; i++) { for (j=0; j<nt; j++) { u = gsl_matrix_float_get(X,i,j); gsl_matrix_float_set(X,i,j,fabs(u)); gsl_matrix_float_set(X,i,j+nt,u); } } PowerIteration(X,eigvec,type,maxiter); break; default: /* dense matrix representation */ VMatrixECM(X,eigvec,type,maxiter,map); break; } } /* Matrix projection, ECM-project */ else { VMatrixProjection(X,eigvec,type,seed); } /* rescale for better visualization */ float nx = (float)nvox; nx = sqrt(nx); for (i=0; i<nvox; i++) eigvec[i] *= nx; return eigvec; } VDictEntry TYPDict[] = { { "rlc", 0, 0,0,0,0 }, { "add", 1, 0,0,0,0 }, { "pos", 2, 0,0,0,0 }, { "abs", 3, 0,0,0,0 }, { "neg", 4, 0,0,0,0 }, { "gauss", 5, 0,0,0,0 }, { NULL, 0,0,0,0,0 } }; int main (int argc,char *argv[]) { static VString mask_filename = ""; static VShort first = 0; static VShort length = 0; static VShort type = 0; static VShort maxiter= 20; static VBoolean project = FALSE; static VInteger seed = 99402622; static VShort nproc = 0; static VOptionDescRec options[] = { {"mask",VStringRepn,1,(VPointer) &mask_filename,VRequiredOpt,NULL,"Region of interest mask"}, {"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"First timestep to use"}, {"length",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,"Length of time series to use, '0' to use full length"}, {"metric",VShortRepn,1,(VPointer) &type,VOptionalOpt,TYPDict,"Type of correlation metric"}, {"iterations",VShortRepn,1,(VPointer) &maxiter,VOptionalOpt,NULL,"Maximum number of power iterations"}, {"project",VBooleanRepn,1,(VPointer) &project,VOptionalOpt,NULL,"Whether to do matrix projection"}, {"seed",VIntegerRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generation (only for ECM-project)"}, {"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"} }; FILE *in_file=NULL,*out_file=NULL; VString in_filename=NULL; char *prg_name=GetLipsiaName("vecm"); fprintf(stderr, "%s\n", prg_name); /* parse command line */ VParseFilterCmdZ (VNumber (options),options,argc,argv,&in_file,&out_file,&in_filename); if (type < 0 || type > 8) VError(" unknown metric"); if (type < 6) fprintf(stderr," Correlation metric %d: %s\n",type,TYPDict[type].keyword); if (project && (type < 2 || type == 7)) VError(" matrix projection not needed for metric %d (%s)\n",type,TYPDict[type].keyword); /* omp-stuff */ #ifdef _OPENMP int num_procs=omp_get_num_procs(); if (nproc > 0 && nproc < num_procs) num_procs = nproc; if (type > 3 || project == TRUE) fprintf(stderr,"using %d cores\n",(int)num_procs); omp_set_num_threads(num_procs); #endif /* _OPENMP */ /* read functional data */ VAttrList list = VReadAttrListZ(in_file,in_filename,0L,TRUE,FALSE); if (list == NULL) VError(" error reading input file %s",in_file); VAttrList geolist = VGetGeoInfo(list); /* read mask */ VAttrList listm = VReadAttrList(mask_filename,0L,TRUE,FALSE); VImage mask = VReadImage(listm); if (mask == NULL) VError(" no mask found"); size_t nvox = NumVoxels(mask); /* voxel map */ VImage map = VoxelMap(list,mask,nvox); /* read data into X */ gsl_matrix_float *X = ReadDataECM(list,mask,map,first,length,type,nvox); /* main process */ float *eigvec = VECM(X,(int)type,project,(VLong)seed,(int)maxiter,map); /* create output image */ VImage dest = WriteOutput(list,map,eigvec,nvox); VSetAttr(VImageAttrList(dest),"name",NULL,VStringRepn,"ECM"); VAttrList out_list = VCreateAttrList(); VAppendAttr(out_list,"image",NULL,VImageRepn,dest); /* update geoinfo, 4D to 3D */ if (geolist != NULL) { double *D = VGetGeoDim(geolist,NULL); D[0] = 3; /* 3D */ D[4] = 1; /* just one timestep */ VSetGeoDim(geolist,D); VSetGeoInfo(geolist,out_list); } /* write to disk */ VHistory(VNumber(options),options,prg_name,&list,&out_list); if (! VWriteFile (out_file, out_list)) exit (1); fprintf (stderr, "%s: done.\n", argv[0]); return 0; }
{ "alphanum_fraction": 0.6235693623, "avg_line_length": 26.5919732441, "ext": "c", "hexsha": "86de44666a70c2201c008dc315b643c76db38c04", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/nets/vecm/vecm.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/nets/vecm/vecm.c", "max_line_length": 125, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/nets/vecm/vecm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 2639, "size": 7951 }
#ifndef __GSL_VERSION_H__ #define __GSL_VERSION_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 <gsl/gsl_types.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 #define GSL_VERSION "2.4" #define GSL_MAJOR_VERSION 2 #define GSL_MINOR_VERSION 4 GSL_VAR const char * gsl_version; __END_DECLS #endif /* __GSL_VERSION_H__ */
{ "alphanum_fraction": 0.7138927098, "avg_line_length": 19.6486486486, "ext": "h", "hexsha": "56f1556fc918e37a2c05d0786f7ab5643447084b", "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_version.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_version.h", "max_line_length": 49, "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_version.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": 187, "size": 727 }
/* movstat/qnacc.c * * Moving window Q_n accumulator * * 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> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> typedef double qnacc_type_t; typedef qnacc_type_t ringbuf_type_t; #include "ringbuf.c" typedef struct { qnacc_type_t *window; /* linear array for current window */ qnacc_type_t *work; /* workspace, length 3*n */ int *work_int; /* integer workspace, length 5*n */ ringbuf *rbuf; /* ring buffer storing current window */ } qnacc_state_t; static size_t qnacc_size(const size_t n) { size_t size = 0; size += sizeof(qnacc_state_t); size += n * sizeof(qnacc_type_t); /* window */ size += 3 * n * sizeof(qnacc_type_t); /* work */ size += 5 * n * sizeof(int); /* work_int */ size += ringbuf_size(n); return size; } static int qnacc_init(const size_t n, void * vstate) { qnacc_state_t * state = (qnacc_state_t *) vstate; state->window = (qnacc_type_t *) ((unsigned char *) vstate + sizeof(qnacc_state_t)); state->work = (qnacc_type_t *) ((unsigned char *) state->window + n * sizeof(qnacc_type_t)); state->work_int = (int *) ((unsigned char *) state->work + 3 * n * sizeof(qnacc_type_t)); state->rbuf = (ringbuf *) ((unsigned char *) state->work_int + 5 * n * sizeof(int)); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int qnacc_insert(const qnacc_type_t x, void * vstate) { qnacc_state_t * state = (qnacc_state_t *) vstate; /* add new element to ring buffer */ ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int qnacc_delete(void * vstate) { qnacc_state_t * state = (qnacc_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) ringbuf_pop_back(state->rbuf); return GSL_SUCCESS; } /* FIXME XXX: this is inefficient - could be improved by maintaining a sorted ring buffer */ static int qnacc_get(void * params, qnacc_type_t * result, const void * vstate) { const qnacc_state_t * state = (const qnacc_state_t *) vstate; size_t n = ringbuf_copy(state->window, state->rbuf); (void) params; gsl_sort(state->window, 1, n); *result = gsl_stats_Qn_from_sorted_data(state->window, 1, n, state->work, state->work_int); return GSL_SUCCESS; } static const gsl_movstat_accum qn_accum_type = { qnacc_size, qnacc_init, qnacc_insert, qnacc_delete, qnacc_get }; const gsl_movstat_accum *gsl_movstat_accum_Qn = &qn_accum_type;
{ "alphanum_fraction": 0.7031823745, "avg_line_length": 27.4621848739, "ext": "c", "hexsha": "57c60d64475228dad1b147f4f4b3e86c2b7d7ff7", "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/qnacc.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/qnacc.c", "max_line_length": 94, "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/qnacc.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": 931, "size": 3268 }
#pragma once #include <string> #include <utility> #include <vector> #include <unordered_map> #include <gsl/span> #include <lmdb.h> #include <functional> #include "Transaction.h" #include "LmdbExceptions.h" namespace DeepestScatter { class Dataset { public: struct Settings; class Example; explicit Dataset(std::shared_ptr<Settings> settings); ~Dataset(); template<class T> size_t getRecordsCount(); template<class T> T getRecord(int32_t recordId); template<class T> void dropTable(); template<class T> void append(const T& example); template<class T> void batchAppend(const gsl::span<T>& examples, int32_t startId); struct Settings { Settings(std::string path) : path(std::move(path)) {} std::string path; }; private: using TableName = std::string; template<class T> void tryAppend(const T& example, int entryId); template<class T> void tryBatchAppend(const gsl::span<T>& examples, int nextExampleId); void increaseSizeIfNeededWhile(const std::function<void(void)>& action); void increaseSize(); MDB_dbi getTable(const TableName& name); MDB_dbi openTable(const TableName& name); void closeTable(const TableName& name); std::unordered_map<TableName, MDB_dbi> openedTables; std::unordered_map<TableName, int32_t> nextIds; MDB_env* mdbEnv = nullptr; }; template <class T> size_t Dataset::getRecordsCount() { const TableName tableName = T::descriptor()->name(); MDB_dbi dbi = getTable(tableName); return Transaction::withTransaction<size_t>(mdbEnv, nullptr, 0, [&](Transaction& transaction) { MDB_stat stats; LmdbExceptions::checkError(mdb_stat(transaction, dbi, &stats)); return stats.ms_entries; }); } template <class T> T Dataset::getRecord(int32_t recordId) { const TableName tableName = T::descriptor()->name(); MDB_dbi dbi = getTable(tableName); return Transaction::withTransaction<T>(mdbEnv, nullptr, 0, [&](Transaction& transaction) { MDB_val mdbKey { sizeof(int32_t), &recordId }; MDB_val mdbVal; LmdbExceptions::checkError(mdb_get(transaction, dbi, &mdbKey, &mdbVal)); T record{}; record.ParseFromArray(mdbVal.mv_data, mdbVal.mv_size); return record; }); } template <class T> void Dataset::dropTable() { const TableName tableName = T::descriptor()->name(); MDB_dbi dbi = getTable(tableName); if (getRecordsCount<T>() == 0) { return; } while (true) { std::string tableConfirmation; std::cout << "YOU ARE GOING TO DELETE " << getRecordsCount<T>() << " RECORDS!!!" << std::endl; std::cout << "Type table name: \"" << T::descriptor()->name() << "\" to drop it" << std::endl; std::cin >> tableConfirmation; if (tableConfirmation == T::descriptor()->name()) { break; } std::cout << "Mismatched table name. Try again."; } Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction) { mdb_drop(transaction, dbi, 0); nextIds[tableName] = 0; }); } template <class T> void Dataset::append(const T& example) { const TableName tableName = T::descriptor()->name(); // Returns zero if not initialized; int entryId = nextIds[tableName]; increaseSizeIfNeededWhile([&]() { return tryAppend(example, entryId); }); nextIds[tableName] = entryId + 1; } template <class T> void Dataset::batchAppend(const gsl::span<T>& examples, int32_t startId) { const TableName tableName = T::descriptor()->name(); increaseSizeIfNeededWhile([&]() { return tryBatchAppend(examples, startId); }); nextIds[tableName] = startId + examples.size(); } template <class T> void Dataset::tryAppend(const T& example, int entryId) { const TableName tableName = T::descriptor()->name(); MDB_dbi dbi = getTable(tableName); Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction) { MDB_val mdbKey { sizeof(int32_t), &entryId }; const size_t length = example.ByteSizeLong(); std::vector<uint8_t> serialized(length); example.SerializeWithCachedSizesToArray(&serialized[0]); MDB_val mdbVal { length * sizeof(uint8_t), static_cast<void*>(&serialized[0]) }; LmdbExceptions::checkError(mdb_put(transaction, dbi, &mdbKey, &mdbVal, 0)); }); } template <class T> void Dataset::tryBatchAppend(const gsl::span<T>& examples, int nextExampleId) { const TableName tableName = T::descriptor()->name(); MDB_dbi dbi = getTable(tableName); Transaction::withTransaction<void>(mdbEnv, nullptr, 0, [&](Transaction& transaction) { for (const auto& example : examples) { MDB_val mdbKey { sizeof(int32_t), &nextExampleId }; const size_t length = example.ByteSizeLong(); std::vector<uint8_t> serialized(length); example.SerializeWithCachedSizesToArray(&serialized[0]); MDB_val mdbVal { length * sizeof(uint8_t), static_cast<void*>(&serialized[0]) }; LmdbExceptions::checkError(mdb_put(transaction, dbi, &mdbKey, &mdbVal, 0)); nextExampleId++; } }); } }
{ "alphanum_fraction": 0.5480216975, "avg_line_length": 26.7863247863, "ext": "h", "hexsha": "833cb40bcd0d1ae87372f1208896b199b1256320", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:10:36.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-07T01:20:07.000Z", "max_forks_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "marsermd/DeepestScatter", "max_forks_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_issues_count": 18, "max_issues_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_issues_repo_issues_event_max_datetime": "2022-03-11T23:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:39:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "marsermd/DeepestScatter", "max_issues_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_line_length": 106, "max_stars_count": 13, "max_stars_repo_head_hexsha": "eeb490b5e6afd7f05049c8aca90a5c2e6f253726", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "marsermd/DeepestScatter", "max_stars_repo_path": "DeepestScatter_DataGen/DeepestScatter_DataGen/src/Util/Dataset/Dataset.h", "max_stars_repo_stars_event_max_datetime": "2021-08-17T13:15:14.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-02T05:39:28.000Z", "num_tokens": 1339, "size": 6268 }
#include <stdlib.h> #include <stdio.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlinear.h> int func_f (const gsl_vector * x, void *params, gsl_vector * f) { double x1 = gsl_vector_get(x, 0); double x2 = gsl_vector_get(x, 1); gsl_vector_set(f, 0, 100.0 * (x2 - x1*x1)); gsl_vector_set(f, 1, 1.0 - x1); return GSL_SUCCESS; } int func_df (const gsl_vector * x, void *params, gsl_matrix * J) { double x1 = gsl_vector_get(x, 0); gsl_matrix_set(J, 0, 0, -200.0*x1); gsl_matrix_set(J, 0, 1, 100.0); gsl_matrix_set(J, 1, 0, -1.0); gsl_matrix_set(J, 1, 1, 0.0); return GSL_SUCCESS; } int func_fvv (const gsl_vector * x, const gsl_vector * v, void *params, gsl_vector * fvv) { double v1 = gsl_vector_get(v, 0); gsl_vector_set(fvv, 0, -200.0 * v1 * v1); gsl_vector_set(fvv, 1, 0.0); return GSL_SUCCESS; } void callback(const size_t iter, void *params, const gsl_multifit_nlinear_workspace *w) { gsl_vector * x = gsl_multifit_nlinear_position(w); /* print out current location */ printf("%f %f\n", gsl_vector_get(x, 0), gsl_vector_get(x, 1)); } void solve_system(gsl_vector *x0, gsl_multifit_nlinear_fdf *fdf, gsl_multifit_nlinear_parameters *params) { const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; const size_t max_iter = 200; const double xtol = 1.0e-8; const double gtol = 1.0e-8; const double ftol = 1.0e-8; const size_t n = fdf->n; const size_t p = fdf->p; gsl_multifit_nlinear_workspace *work = gsl_multifit_nlinear_alloc(T, params, n, p); gsl_vector * f = gsl_multifit_nlinear_residual(work); gsl_vector * x = gsl_multifit_nlinear_position(work); int info; double chisq0, chisq, rcond; /* initialize solver */ gsl_multifit_nlinear_init(x0, fdf, work); /* store initial cost */ gsl_blas_ddot(f, f, &chisq0); /* iterate until convergence */ gsl_multifit_nlinear_driver(max_iter, xtol, gtol, ftol, callback, NULL, &info, work); /* store final cost */ gsl_blas_ddot(f, f, &chisq); /* store cond(J(x)) */ gsl_multifit_nlinear_rcond(&rcond, work); /* print summary */ fprintf(stderr, "NITER = %zu\n", gsl_multifit_nlinear_niter(work)); fprintf(stderr, "NFEV = %zu\n", fdf->nevalf); fprintf(stderr, "NJEV = %zu\n", fdf->nevaldf); fprintf(stderr, "NAEV = %zu\n", fdf->nevalfvv); fprintf(stderr, "initial cost = %.12e\n", chisq0); fprintf(stderr, "final cost = %.12e\n", chisq); fprintf(stderr, "final x = (%.12e, %.12e)\n", gsl_vector_get(x, 0), gsl_vector_get(x, 1)); fprintf(stderr, "final cond(J) = %.12e\n", 1.0 / rcond); printf("\n\n"); gsl_multifit_nlinear_free(work); } int main (void) { const size_t n = 2; const size_t p = 2; gsl_vector *f = gsl_vector_alloc(n); gsl_vector *x = gsl_vector_alloc(p); gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params = gsl_multifit_nlinear_default_parameters(); /* print map of Phi(x1, x2) */ { double x1, x2, chisq; double *f1 = gsl_vector_ptr(f, 0); double *f2 = gsl_vector_ptr(f, 1); for (x1 = -1.2; x1 < 1.3; x1 += 0.1) { for (x2 = -0.5; x2 < 2.1; x2 += 0.1) { gsl_vector_set(x, 0, x1); gsl_vector_set(x, 1, x2); func_f(x, NULL, f); chisq = (*f1) * (*f1) + (*f2) * (*f2); printf("%f %f %f\n", x1, x2, chisq); } printf("\n"); } printf("\n\n"); } /* define function to be minimized */ fdf.f = func_f; fdf.df = func_df; fdf.fvv = func_fvv; fdf.n = n; fdf.p = p; fdf.params = NULL; /* starting point */ gsl_vector_set(x, 0, -0.5); gsl_vector_set(x, 1, 1.75); fprintf(stderr, "=== Solving system without acceleration ===\n"); fdf_params.trs = gsl_multifit_nlinear_trs_lm; solve_system(x, &fdf, &fdf_params); fprintf(stderr, "=== Solving system with acceleration ===\n"); fdf_params.trs = gsl_multifit_nlinear_trs_lmaccel; solve_system(x, &fdf, &fdf_params); gsl_vector_free(f); gsl_vector_free(x); return 0; }
{ "alphanum_fraction": 0.6257129278, "avg_line_length": 25.3493975904, "ext": "c", "hexsha": "f9ff23573f9bd31d21d2af3170ef5872a29bd701", "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/doc/examples/nlfit2.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/doc/examples/nlfit2.c", "max_line_length": 77, "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/nlfit2.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": 1429, "size": 4208 }
/* spio.c * * Copyright (C) 2016 Patrick Alken * Copyright (C) 2016 Alexis Tantet * * 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 <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spmatrix.h> /* gsl_spmatrix_fprintf() Print sparse matrix to file in MatrixMarket format: M N NNZ I1 J1 A(I1,J1) ... Note that indices start at 1 and not 0 */ int gsl_spmatrix_fprintf(FILE *stream, const gsl_spmatrix *m, const char *format) { int status; /* print header */ status = fprintf(stream, "%%%%MatrixMarket matrix coordinate real general\n"); if (status < 0) { GSL_ERROR("fprintf failed for header", GSL_EFAILED); } /* print rows,columns,nnz */ status = fprintf(stream, "%u\t%u\t%u\n", (unsigned int) m->size1, (unsigned int) m->size2, (unsigned int) m->nz); if (status < 0) { GSL_ERROR("fprintf failed for dimension header", GSL_EFAILED); } if (GSL_SPMATRIX_ISTRIPLET(m)) { size_t n; for (n = 0; n < m->nz; ++n) { status = fprintf(stream, "%u\t%u\t", (unsigned int) m->i[n] + 1, (unsigned int) m->p[n] + 1); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = fprintf(stream, format, m->data[n]); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = putc('\n', stream); if (status == EOF) { GSL_ERROR("putc failed", GSL_EFAILED); } } } else if (GSL_SPMATRIX_ISCCS(m)) { size_t j, p; for (j = 0; j < m->size2; ++j) { for (p = m->p[j]; p < m->p[j + 1]; ++p) { status = fprintf(stream, "%u\t%u\t", (unsigned int) m->i[p] + 1, (unsigned int) j + 1); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = fprintf(stream, format, m->data[p]); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = putc('\n', stream); if (status == EOF) { GSL_ERROR("putc failed", GSL_EFAILED); } } } } else if (GSL_SPMATRIX_ISCRS(m)) { size_t i, p; for (i = 0; i < m->size1; ++i) { for (p = m->p[i]; p < m->p[i + 1]; ++p) { status = fprintf(stream, "%u\t%u\t", (unsigned int) i + 1, (unsigned int) m->i[p] + 1); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = fprintf(stream, format, m->data[p]); if (status < 0) { GSL_ERROR("fprintf failed", GSL_EFAILED); } status = putc('\n', stream); if (status == EOF) { GSL_ERROR("putc failed", GSL_EFAILED); } } } } else { GSL_ERROR("unknown sparse matrix type", GSL_EINVAL); } return GSL_SUCCESS; } gsl_spmatrix * gsl_spmatrix_fscanf(FILE *stream) { gsl_spmatrix *m; unsigned int size1, size2, nz; char buf[1024]; int found_header = 0; /* read file until we find rows,cols,nz header */ while (fgets(buf, 1024, stream) != NULL) { int c; /* skip comments */ if (*buf == '%') continue; c = sscanf(buf, "%u %u %u", &size1, &size2, &nz); if (c == 3) { found_header = 1; break; } } if (!found_header) { GSL_ERROR_NULL ("fscanf failed reading header", GSL_EFAILED); } m = gsl_spmatrix_alloc_nzmax((size_t) size1, (size_t) size2, (size_t) nz, GSL_SPMATRIX_TRIPLET); if (!m) { GSL_ERROR_NULL ("error allocating m", GSL_ENOMEM); } { unsigned int i, j; double val; while (fgets(buf, 1024, stream) != NULL) { int c = sscanf(buf, "%u %u %lg", &i, &j, &val); if (c < 3 || (i == 0) || (j == 0)) { GSL_ERROR_NULL ("error in input file format", GSL_EFAILED); } else if ((i > size1) || (j > size2)) { GSL_ERROR_NULL ("element exceeds matrix dimensions", GSL_EBADLEN); } else { /* subtract 1 from (i,j) since indexing starts at 1 */ gsl_spmatrix_set(m, i - 1, j - 1, val); } } } return m; } int gsl_spmatrix_fwrite(FILE *stream, const gsl_spmatrix *m) { size_t items; /* write header: size1, size2, nz */ items = fwrite(&(m->size1), sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fwrite failed on size1", GSL_EFAILED); } items = fwrite(&(m->size2), sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fwrite failed on size2", GSL_EFAILED); } items = fwrite(&(m->nz), sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fwrite failed on nz", GSL_EFAILED); } /* write m->i and m->data which are size nz in all storage formats */ items = fwrite(m->i, sizeof(size_t), m->nz, stream); if (items != m->nz) { GSL_ERROR("fwrite failed on row indices", GSL_EFAILED); } items = fwrite(m->data, sizeof(double), m->nz, stream); if (items != m->nz) { GSL_ERROR("fwrite failed on data", GSL_EFAILED); } if (GSL_SPMATRIX_ISTRIPLET(m)) { items = fwrite(m->p, sizeof(size_t), m->nz, stream); if (items != m->nz) { GSL_ERROR("fwrite failed on column indices", GSL_EFAILED); } } else if (GSL_SPMATRIX_ISCCS(m)) { items = fwrite(m->p, sizeof(size_t), m->size2 + 1, stream); if (items != m->size2 + 1) { GSL_ERROR("fwrite failed on column indices", GSL_EFAILED); } } else if (GSL_SPMATRIX_ISCRS(m)) { items = fwrite(m->p, sizeof(size_t), m->size1 + 1, stream); if (items != m->size1 + 1) { GSL_ERROR("fwrite failed on column indices", GSL_EFAILED); } } return GSL_SUCCESS; } int gsl_spmatrix_fread(FILE *stream, gsl_spmatrix *m) { size_t size1, size2, nz; size_t items; /* read header: size1, size2, nz */ items = fread(&size1, sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fread failed on size1", GSL_EFAILED); } items = fread(&size2, sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fread failed on size2", GSL_EFAILED); } items = fread(&nz, sizeof(size_t), 1, stream); if (items != 1) { GSL_ERROR("fread failed on nz", GSL_EFAILED); } if (m->size1 != size1) { GSL_ERROR("matrix has wrong size1", GSL_EBADLEN); } else if (m->size2 != size2) { GSL_ERROR("matrix has wrong size2", GSL_EBADLEN); } else if (nz > m->nzmax) { GSL_ERROR("matrix nzmax is too small", GSL_EBADLEN); } else { /* read m->i and m->data arrays, which are size nz for all formats */ items = fread(m->i, sizeof(size_t), nz, stream); if (items != nz) { GSL_ERROR("fread failed on row indices", GSL_EFAILED); } items = fread(m->data, sizeof(double), nz, stream); if (items != nz) { GSL_ERROR("fread failed on data", GSL_EFAILED); } m->nz = nz; if (GSL_SPMATRIX_ISTRIPLET(m)) { items = fread(m->p, sizeof(size_t), nz, stream); if (items != nz) { GSL_ERROR("fread failed on column indices", GSL_EFAILED); } /* build binary search tree for m */ gsl_spmatrix_tree_rebuild(m); } else if (GSL_SPMATRIX_ISCCS(m)) { items = fread(m->p, sizeof(size_t), size2 + 1, stream); if (items != size2 + 1) { GSL_ERROR("fread failed on row pointers", GSL_EFAILED); } } else if (GSL_SPMATRIX_ISCRS(m)) { items = fread(m->p, sizeof(size_t), size1 + 1, stream); if (items != size1 + 1) { GSL_ERROR("fread failed on column pointers", GSL_EFAILED); } } } return GSL_SUCCESS; }
{ "alphanum_fraction": 0.5212397052, "avg_line_length": 25.0081300813, "ext": "c", "hexsha": "a276ec0a884e647aa5565f295e70dccf1aa4e1d4", "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": "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/spmatrix/spio.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "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": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spmatrix/spio.c", "max_line_length": 103, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/spmatrix/spio.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 2571, "size": 9228 }
#pragma once #include "BgfxCallback.h" #include "FrameBuffer.h" #include "ShaderCompiler.h" #include <Babylon/JsRuntime.h> #include <Babylon/JsRuntimeScheduler.h> #include <GraphicsImpl.h> #include <napi/napi.h> #include <bgfx/bgfx.h> #include <bgfx/platform.h> #include <bimg/bimg.h> #include <bx/allocator.h> #include <gsl/gsl> #include <assert.h> #include <arcana/containers/weak_table.h> #include <arcana/threading/cancellation.h> #include <unordered_map> namespace Babylon { struct TextureData final { ~TextureData() { if (OwnsHandle && bgfx::isValid(Handle)) { bgfx::destroy(Handle); } } bgfx::TextureHandle Handle{bgfx::kInvalidHandle}; bool OwnsHandle{true}; uint32_t Width{0}; uint32_t Height{0}; uint32_t Flags{0}; uint8_t AnisotropicLevel{0}; }; struct UniformInfo final { uint8_t Stage{}; bgfx::UniformHandle Handle{bgfx::kInvalidHandle}; bool YFlip{false}; }; struct ProgramData final { ProgramData() = default; ProgramData(const ProgramData&) = delete; ProgramData(ProgramData&&) = delete; ~ProgramData() { if (bgfx::isValid(Handle)) { bgfx::destroy(Handle); } } std::unordered_map<std::string, uint32_t> VertexAttributeLocations{}; std::unordered_map<std::string, UniformInfo> VertexUniformInfos{}; std::unordered_map<std::string, UniformInfo> FragmentUniformInfos{}; bgfx::ProgramHandle Handle{bgfx::kInvalidHandle}; struct UniformValue { std::vector<float> Data{}; uint16_t ElementLength{}; bool YFlip{false}; }; std::unordered_map<uint16_t, UniformValue> Uniforms{}; void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, bool YFlip, size_t elementLength = 1) { UniformValue& value = Uniforms[handle.idx]; value.Data.assign(data.begin(), data.end()); value.ElementLength = static_cast<uint16_t>(elementLength); value.YFlip = YFlip; } }; class IndexBufferData; class VertexBufferData; struct VertexArray final { ~VertexArray() { for (auto& vertexBufferPair : VertexBuffers) { bgfx::destroy(vertexBufferPair.second.VertexLayoutHandle); } } struct IndexBuffer { const IndexBufferData* Data{}; }; IndexBuffer indexBuffer{}; struct VertexBuffer { const VertexBufferData* Data{}; uint32_t StartVertex{}; bgfx::VertexLayoutHandle VertexLayoutHandle{}; }; std::unordered_map<uint32_t, VertexBuffer> VertexBuffers; }; class NativeEngine final : public Napi::ObjectWrap<NativeEngine> { static constexpr auto JS_CLASS_NAME = "_NativeEngine"; static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = "Engine"; public: NativeEngine(const Napi::CallbackInfo& info); NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime); ~NativeEngine(); static void Initialize(Napi::Env env); private: void Dispose(); void Dispose(const Napi::CallbackInfo& info); Napi::Value HomogeneousDepth(const Napi::CallbackInfo& info); void RequestAnimationFrame(const Napi::CallbackInfo& info); Napi::Value CreateVertexArray(const Napi::CallbackInfo& info); void DeleteVertexArray(const Napi::CallbackInfo& info); void BindVertexArray(const Napi::CallbackInfo& info); Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info); void DeleteIndexBuffer(const Napi::CallbackInfo& info); void RecordIndexBuffer(const Napi::CallbackInfo& info); void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info); Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info); void DeleteVertexBuffer(const Napi::CallbackInfo& info); void RecordVertexBuffer(const Napi::CallbackInfo& info); void UpdateDynamicVertexBuffer(const Napi::CallbackInfo& info); Napi::Value CreateProgram(const Napi::CallbackInfo& info); Napi::Value GetUniforms(const Napi::CallbackInfo& info); Napi::Value GetAttributes(const Napi::CallbackInfo& info); void SetProgram(const Napi::CallbackInfo& info); void SetState(const Napi::CallbackInfo& info); void SetZOffset(const Napi::CallbackInfo& info); Napi::Value GetZOffset(const Napi::CallbackInfo& info); void SetDepthTest(const Napi::CallbackInfo& info); Napi::Value GetDepthWrite(const Napi::CallbackInfo& info); void SetDepthWrite(const Napi::CallbackInfo& info); void SetColorWrite(const Napi::CallbackInfo& info); void SetBlendMode(const Napi::CallbackInfo& info); void SetMatrix(const Napi::CallbackInfo& info); void SetInt(const Napi::CallbackInfo& info); void SetIntArray(const Napi::CallbackInfo& info); void SetIntArray2(const Napi::CallbackInfo& info); void SetIntArray3(const Napi::CallbackInfo& info); void SetIntArray4(const Napi::CallbackInfo& info); void SetFloatArray(const Napi::CallbackInfo& info); void SetFloatArray2(const Napi::CallbackInfo& info); void SetFloatArray3(const Napi::CallbackInfo& info); void SetFloatArray4(const Napi::CallbackInfo& info); void SetMatrices(const Napi::CallbackInfo& info); void SetMatrix3x3(const Napi::CallbackInfo& info); void SetMatrix2x2(const Napi::CallbackInfo& info); void SetFloat(const Napi::CallbackInfo& info); void SetFloat2(const Napi::CallbackInfo& info); void SetFloat3(const Napi::CallbackInfo& info); void SetFloat4(const Napi::CallbackInfo& info); Napi::Value CreateTexture(const Napi::CallbackInfo& info); void LoadTexture(const Napi::CallbackInfo& info); void LoadRawTexture(const Napi::CallbackInfo& info); void LoadCubeTexture(const Napi::CallbackInfo& info); void LoadCubeTextureWithMips(const Napi::CallbackInfo& info); Napi::Value GetTextureWidth(const Napi::CallbackInfo& info); Napi::Value GetTextureHeight(const Napi::CallbackInfo& info); void SetTextureSampling(const Napi::CallbackInfo& info); void SetTextureWrapMode(const Napi::CallbackInfo& info); void SetTextureAnisotropicLevel(const Napi::CallbackInfo& info); void SetTexture(const Napi::CallbackInfo& info); void DeleteTexture(const Napi::CallbackInfo& info); Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info); void DeleteFrameBuffer(const Napi::CallbackInfo& info); void BindFrameBuffer(const Napi::CallbackInfo& info); void UnbindFrameBuffer(const Napi::CallbackInfo& info); void DrawIndexed(const Napi::CallbackInfo& info); void Draw(const Napi::CallbackInfo& info); void Clear(const Napi::CallbackInfo& info); Napi::Value GetRenderWidth(const Napi::CallbackInfo& info); Napi::Value GetRenderHeight(const Napi::CallbackInfo& info); void SetViewPort(const Napi::CallbackInfo& info); Napi::Value GetHardwareScalingLevel(const Napi::CallbackInfo& info); void SetHardwareScalingLevel(const Napi::CallbackInfo& info); Napi::Value CreateImageBitmap(const Napi::CallbackInfo& info); Napi::Value ResizeImageBitmap(const Napi::CallbackInfo& info); void GetFrameBufferData(const Napi::CallbackInfo& info); void Draw(bgfx::Encoder* encoder, int fillMode); GraphicsImpl::UpdateToken& GetUpdateToken(); std::shared_ptr<arcana::cancellation_source> m_cancellationSource{}; ShaderCompiler m_shaderCompiler{}; ProgramData* m_currentProgram{nullptr}; arcana::weak_table<std::unique_ptr<ProgramData>> m_programDataCollection{}; JsRuntime& m_runtime; GraphicsImpl& m_graphicsImpl; JsRuntimeScheduler m_runtimeScheduler; std::optional<GraphicsImpl::UpdateToken> m_updateToken{}; void ScheduleRequestAnimationFrameCallbacks(); bool m_requestAnimationFrameCallbacksScheduled{}; bx::DefaultAllocator m_allocator{}; uint64_t m_engineState{BGFX_STATE_DEFAULT}; template<int size, typename arrayType> void SetTypeArrayN(const Napi::CallbackInfo& info); template<int size> void SetFloatN(const Napi::CallbackInfo& info); template<int size> void SetMatrixN(const Napi::CallbackInfo& info); // Scratch vector used for data alignment. std::vector<float> m_scratch{}; std::vector<Napi::FunctionReference> m_requestAnimationFrameCallbacks{}; const VertexArray* m_boundVertexArray{}; FrameBuffer* m_boundFrameBuffer{}; }; }
{ "alphanum_fraction": 0.6628991551, "avg_line_length": 36.452, "ext": "h", "hexsha": "5c592992d499538c46b314e2ceaf1ce3f0a4b043", "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": "cfbea50839e10cd53576b4382b191f5213a634f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lupin4/BabylonNative", "max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "cfbea50839e10cd53576b4382b191f5213a634f2", "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": "lupin4/BabylonNative", "max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "cfbea50839e10cd53576b4382b191f5213a634f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lupin4/BabylonNative", "max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2054, "size": 9113 }
#pragma once #include <gsl/string_span> #include <string> #include "params.h" namespace particles { class ParserParams { public: static PartSysParam* Parse(PartSysParamId id, gsl::cstring_span<> value, float emitterLifespan, float particleLifespan, bool& success); static PartSysParam* Parse(gsl::cstring_span<> value, float defaultValue, float parentLifespan, bool& success); static PartSysParamKeyframes* ParseKeyframes(gsl::cstring_span<> value, float parentLifespan); static PartSysParamRandom* ParseRandom(gsl::cstring_span<> value); static PartSysParamSpecial* ParseSpecial(gsl::cstring_span<> value); static PartSysParamConstant* ParseConstant(gsl::cstring_span<> value, float defaultValue, bool& success); }; }
{ "alphanum_fraction": 0.6327868852, "avg_line_length": 26.1428571429, "ext": "h", "hexsha": "b093f03202cd20000f3fc32f12f18d1f3b7334af", "lang": "C", "max_forks_count": 25, "max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z", "max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "edoipi/TemplePlus", "max_forks_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_issues_count": 457, "max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "edoipi/TemplePlus", "max_issues_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_line_length": 106, "max_stars_count": 69, "max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "edoipi/TemplePlus", "max_stars_repo_path": "ParticleSystems/include/particles/parser_params.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z", "num_tokens": 185, "size": 915 }
/* * Copyright 2021 The DAPHNE Consortium * * 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 <runtime/local/context/DaphneContext.h> #include <runtime/local/datastructures/DataObjectFactory.h> #include <runtime/local/datastructures/DenseMatrix.h> #include <cblas.h> #include <cassert> #include <cstddef> // **************************************************************************** // Struct for partial template specialization // **************************************************************************** template<class DTRes, class DTLhs, class DTRhs> struct MatMul { static void apply(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) = delete; }; // **************************************************************************** // Convenience function // **************************************************************************** template<class DTRes, class DTLhs, class DTRhs> void matMul(DTRes *& res, const DTLhs * lhs, const DTRhs * rhs, DCTX(ctx)) { MatMul<DTRes, DTLhs, DTRhs>::apply(res, lhs, rhs, ctx); } // **************************************************************************** // (Partial) template specializations for different data/value types // **************************************************************************** // ---------------------------------------------------------------------------- // DenseMatrix <- DenseMatrix, DenseMatrix // ---------------------------------------------------------------------------- template<> struct MatMul<DenseMatrix<float>, DenseMatrix<float>, DenseMatrix<float>> { static void apply(DenseMatrix<float> *& res, const DenseMatrix<float> * lhs, const DenseMatrix<float> * rhs, DCTX(ctx)) { const auto nr1 = static_cast<int>(lhs->getNumRows()); const auto nc1 = static_cast<int>(lhs->getNumCols()); const auto nc2 = static_cast<int>(rhs->getNumCols()); assert((nc1 == static_cast<int>(rhs->getNumRows())) && "#cols of lhs and #rows of rhs must be the same"); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<float>>(nr1, nc2, false); if(nr1 == 1 && nc2 == 1) // Vector-Vector res->set(0, 0, cblas_sdot(nc1, lhs->getValues(), 1, rhs->getValues(), static_cast<int>(rhs->getRowSkip()))); else if(nc2 == 1) // Matrix-Vector cblas_sgemv(CblasRowMajor, CblasNoTrans, nr1, nc1, 1, lhs->getValues(), static_cast<int>(lhs->getRowSkip()), rhs->getValues(), static_cast<int>(rhs->getRowSkip()), 0,res->getValues(), static_cast<int>(res->getRowSkip())); else // Matrix-Matrix cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, nr1, nc2, nc1, 1, lhs->getValues(), static_cast<int>(lhs->getRowSkip()), rhs->getValues(), static_cast<int>(rhs->getRowSkip()), 0, res->getValues(), static_cast<int>(res->getRowSkip())); } }; template<> struct MatMul<DenseMatrix<double>, DenseMatrix<double>, DenseMatrix<double>> { static void apply(DenseMatrix<double> *& res, const DenseMatrix<double> * lhs, const DenseMatrix<double> * rhs, DCTX(ctx)) { const auto nr1 = static_cast<int>(lhs->getNumRows()); const auto nc1 = static_cast<int>(lhs->getNumCols()); const auto nc2 = static_cast<int>(rhs->getNumCols()); assert((nc1 == static_cast<int>(rhs->getNumRows())) && "#cols of lhs and #rows of rhs must be the same"); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<double>>(nr1, nc2, false); if(nr1 == 1 && nc2 == 1) // Vector-Vector res->set(0, 0, cblas_ddot(nc1, lhs->getValues(), 1, rhs->getValues(), static_cast<int>(rhs->getRowSkip()))); else if(nc2 == 1) // Matrix-Vector cblas_dgemv(CblasRowMajor, CblasNoTrans, nr1, nc1, 1, lhs->getValues(), static_cast<int>(lhs->getRowSkip()), rhs->getValues(),static_cast<int>(rhs->getRowSkip()), 0, res->getValues(), static_cast<int>(res->getRowSkip())); else // Matrix-Matrix cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, nr1, nc2, nc1, 1, lhs->getValues(), static_cast<int>(lhs->getRowSkip()), rhs->getValues(), static_cast<int>(rhs->getRowSkip()), 0, res->getValues(), static_cast<int>(res->getRowSkip())); } };
{ "alphanum_fraction": 0.5556664006, "avg_line_length": 48.1923076923, "ext": "h", "hexsha": "ef94e7af150c1908bf1cb33e8789f449b15ec066", "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": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "daphne-eu/daphne", "max_forks_repo_path": "src/runtime/local/kernels/MatMul.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:46:30.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-31T22:10:10.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "daphne-eu/daphne", "max_issues_repo_path": "src/runtime/local/kernels/MatMul.h", "max_line_length": 128, "max_stars_count": 10, "max_stars_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "daphne-eu/daphne", "max_stars_repo_path": "src/runtime/local/kernels/MatMul.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:37:06.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-31T21:49:35.000Z", "num_tokens": 1140, "size": 5012 }
/* Project 2: A Simple Ocean Model This code models a set of equations for a 2-layer model of Ekman heat transport defined by F. Codron 2012: Ekman Heat Transport for Slab Oceans The model is designed to take input from the Met Office Unified Model (UM) in .dat file form. As a result, this model uses the same spatial horizontal resolution as the UM (90 latitude grid points and 144 longitude points, using spacing of 2.0 and 2.5 degrees respectively). The code solves the heat transport using a finite difference method, and a sparse linear algebra GSL solver. Model can be ran on an Ubuntu terminal using the following set of commands: gcc -Wall -I/GSL_PATH/gsl/include -c pr2_ocean_transport_v7.c gcc -L/GSL_PATH/gsl/lib pr2_ocean_transport_v7.o -lgsl -lgslcblas -lm ./a.out [-v {NO_TRANSPORT, DIFUSION_ONLY, DIFUSION_EKMAN}] where the options for -v are integers defined in enum Transport. Created by Jake K. Eager */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits.h> #include <unistd.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_splinalg.h> #define C_D 0.0013 // drag coefficient, dimensionless #define C_V 4000.0 // specific heat capacity of water J/kg/K #define EMISSIVITY 0.985 // effective blackbody emissivity of ocean water #define HEAT_TRANSFER_COEFFICIENT 3000. /* heat transfer coefficient for water W/m2/K 50-3000*/ #define RHO_AIR 1.22 // air density kg/m3 #define RHO_WATER 1027 // km/m3 #define R_PLANET (1.12384*6.371e6) // radius of planet in m (as fraction of Earth radius) #define EPSILON (0.00001) // 0.00001 pretty good need to find appropriate value #define OMEGA (6.501e-6) // angular frequency planet, about its central axis // #define OMEGA (7.272e-5) // Earth value for omega #define SIGMA (5.67e-8) // stefan boltzman constant #define H_S 50.0 // thickness of surface layer in m #define H_D 150.0 // thickness of deep layer below #define D (25000.0) // horizontal diffusion coefficient m2/s // #define D (25000.0*50.0/(H_S+H_D)) // horizontal diffusion coefficient m2/s MIGHT NEED THIS FIX, UNSURE... #define N_LATS 90 /* number of latitude points */ #define N_LONS 144 /* number of longitude points */ #define LAT_MIN -89.0 #define DELTA_LAT 2.0 #define LON_MIN 1.25 #define DELTA_LON 2.5 #define HOURS_PER_DAY 24. #define MINUTES_PER_HOUR 60. #define SECONDS_PER_MINUTE 60. #define DELTA_T (12.0*MINUTES_PER_HOUR*SECONDS_PER_MINUTE) // time step of 1 hours #define TIME_STEPS (20000*2) // for time step of 12 hours, 20,000 time steps needed for 10,000 day run #define TIME_OUTPUT_FREQ (25.0*HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MINUTE) // print update frequency in seconds, but first term is number of days #define DATA_OUTPUT_FREQ (100.0*HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MINUTE) // output frequency in seconds, but first term is number of days #define TIME_OUTPUT_TOL (1e-6) // days #define T_OFFSET 0.0 // IF you want to restart run, specify start time here, so it doesn't save over stuff, and change input temp files to output ones #define TOL (1e-6) #define MAX_ITER 100 // input data files // #define LAND_MASK_DATA "input_data/land_mask_day_cont_100_180.dat" #define LAND_MASK_DATA "input_data/land_mask_no_land.dat" #define MAX_FILE_LINE_SIZE 4000 #define SW_FLUX_NET_DOWN_DATA "input_data/ProCb/surface_net_downward_shortwave_flux.dat" #define LW_FLUX_DOWN_DATA "input_data/ProCb/surface_downwelling_longwave_flux_in_air.dat" // #define LW_FLUX_DOWN_DATA "input_data/ProCb/surface_net_downward_longwave_flux.dat" #define LATENT_UP_FLUX_DATA "input_data/ProCb/surface_upward_latent_heat_flux.dat" #define SENSIBLE_UP_FLUX_DATA "input_data/ProCb/surface_upward_sensible_heat_flux.dat" // #define INITIAL_SURFACE_TEMP_DATA "output_data/ProCb/T_surf_1000_days.dat" // #define INITIAL_DEEP_TEMP_DATA "output_data/ProCb/T_deep_1000_days.dat" #define INITIAL_SURFACE_TEMP_DATA "input_data/ProCb/surface_temperature.dat" #define INITIAL_DEEP_TEMP_DATA "input_data/ProCb/surface_temperature.dat" #define U_WIND_DATA "input_data/ProCb/x_wind.dat" #define V_WIND_DATA "input_data/ProCb/y_wind.dat" #define X_STRESS_DATA "input_data/ProCb/surface_downward_eastward_stress.dat" #define Y_STRESS_DATA "input_data/ProCb/surface_downward_northward_stress.dat" #define LATS_FILE "input_data/lats.dat" #define LONS_FILE "input_data/lons.dat" // output data files #define MAX_FNAME_CHAR 100 // #define PYTHON_EXE "python" // #define PYTHON_SCRIPT "plotting_scripts/temperature_contour_plot.py" #define OUTPUT_UPWARD_Q_FLUX "output_data/ProCb/upward_surface_Q_flux_" #define OUTPUT_SURFACE_TEMP_DATA "output_data/ProCb/T_surf_" #define OUTPUT_DEEP_TEMP_DATA "output_data/ProCb/T_deep_" #define OUTPUT_X_MASS_FLUX_DATA "output_data/ProCb/eastward_flow_" #define OUTPUT_Y_MASS_FLUX_DATA "output_data/ProCb/northward_flow_" #define OUTPUT_VERITCAL_FLUX_DATA "output_data/ProCb/vertical_mass_flux_" #define OUTPUT_DATA_EXT "_days.dat" typedef enum coords { THETA, PHI, N_COORDS } Coords; typedef enum depths { SURFACE, DEEP, N_DEPTHS } Depths; typedef enum transport {NO_TRANSPORT, DIFUSION_ONLY, DIFUSION_EKMAN} Transport; typedef enum errors { MALLOC_ERR, FREE_ERR, FOPEN_ERR, DEPTH_ERR, DERIVATIVE_ERR, READ_DATA_ERR, SOLVER_ERR, VERSION_ERR } Errors; typedef struct grid_vals { // values of latitude and longitude double lat[N_LATS]; double lon[N_LONS]; } Grid_vals; static int select_version(int argc, char **argv); static void time_stepper(int n_times, int n_lats, int n_lons, int version); int main(int argc, char **argv) { int version = select_version(argc, argv); time_stepper(TIME_STEPS,N_LATS,N_LONS,version); return 0; } /* Selects the whether to solve using no horizontal transport, diffusion only or diffusion and Ekman transport. */ static int select_version(int argc, char **argv) { extern char *optarg; int c, err = 0; // char *case_number=NULL; int version=DIFUSION_EKMAN; // default case is the step function test case static char usage[] = "usage: %s [-v version_number] [name ...]\n"; while ((c = getopt(argc, argv, "v:")) != -1) switch (c) { case 'v': version=atoi(optarg); if(version!=NO_TRANSPORT && version!=DIFUSION_EKMAN && version!=DIFUSION_ONLY){ fprintf(stderr, "Version selected not valid, please enter [-v {%i, %i, %i}]\n", NO_TRANSPORT, DIFUSION_ONLY, DIFUSION_EKMAN); exit(VERSION_ERR); } break; case '?': err = 1; break; } if (err) { fprintf(stderr, usage, argv[0]); exit(1); } return version; } /* Checks memory allocation has been successful */ static void *xmalloc(size_t n) { void *p = malloc(n); if(p == NULL) { fprintf(stderr,"Out of memory.\n"); exit(MALLOC_ERR); } return p; } /* checks pointer being freed is not NULL */ static void xfree(void *p) { if(p == NULL) { fprintf(stderr,"Pointer is NULL, so cannot free.\n"); exit(FREE_ERR); } free(p); } /* allocates a 2d array of pointers */ static int **create_2d_int_pointer(int n, int m) { int **p = (int **)xmalloc(n*sizeof(int*)); for(int i=0;i<n;i++){ p[i]=(int *)xmalloc(m*sizeof(int)); } return p; } /* frees a 2d array of pointers */ static void destroy_2d_int_pointer(int **p, int n) { for(int i=0;i<n;i++){ xfree(p[i]); } xfree(p); } /* allocates a 2d array of pointers */ static double **create_2d_pointer(int n, int m) { double **p = (double **)xmalloc(n*sizeof(double*)); for(int i=0;i<n;i++){ p[i]=(double *)xmalloc(m*sizeof(double)); } return p; } /* frees a 2d array of pointers */ static void destroy_2d_pointer(double **p, int n) { for(int i=0;i<n;i++){ xfree(p[i]); } xfree(p); } /* allocates a 3d array of pointers */ static double ***create_3d_pointer(int n, int m, int l) { double ***p = (double ***)xmalloc(n*sizeof(double**)); for(int i=0;i<n;i++){ p[i]=(double **)xmalloc(m*sizeof(double*)); for(int j=0;j<m;j++){ p[i][j]=(double *)xmalloc(l*sizeof(double)); } } return p; } /* frees a 3d array of pointers */ static void destroy_3d_pointer(double ***p, int n, int m) { for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ xfree(p[i][j]); } xfree(p[i]); } xfree(p); } /* checks file opened correctly */ static void *xfopen(char *filename, char *command) { FILE *outfile; outfile = fopen(filename,command); if(outfile==NULL){ fprintf(stderr, "%s could not be opened.\n", filename); exit(FOPEN_ERR); } return outfile; } static void construct_fname(char* fname, size_t fname_length, const char* base, const char* time, const char* ext) { // construct filename from base, time of run and appropriate extention strcpy(fname, base); strcat(fname,time); strcat(fname,ext); } /* reads in a .dat files called filename, that contains data with n_lats rows and n_lons collumns, ie UM output data */ static void read_input_data(double **var, char *filename, int n_lats, int n_lons) { char line[MAX_FILE_LINE_SIZE]; char *data = line; FILE *input; input = xfopen(filename, "r" ); int offset; for(int i=0;i<n_lats;i++){ fgets(line, MAX_FILE_LINE_SIZE, input); for(int j=0;j<n_lons;j++){ int found = sscanf(data, " %le%n", &var[i][j], &offset); if(found!=1){ fprintf(stderr, "%s does not contain enough longitudinal points.\n", filename); exit(READ_DATA_ERR); } data+=offset; } data=line; } fclose(input); } /* reads in a .dat files called filename, that contains integer data with n_lats rows and n_lons collumns, ie UM output data */ static void read_input_int_data(int **var, char *filename, int n_lats, int n_lons) { char line[MAX_FILE_LINE_SIZE]; char *data = line; FILE *input; input = xfopen(filename, "r" ); int offset; for(int i=0;i<n_lats;i++){ fgets(line, MAX_FILE_LINE_SIZE, input); for(int j=0;j<n_lons;j++){ int found = sscanf(data, " %d%n", &var[i][j], &offset); if(found!=1){ fprintf(stderr, "%s does not contain enough longitudinal points.\n", filename); exit(READ_DATA_ERR); } data+=offset; } data=line; } fclose(input); } /* writes out put data to filename on a grid of n_lats by n_lons. */ static void write_data(double **var, char *fbasename, char *time_str, Grid_vals *grid, int n_lats, int n_lons) { char *fname = (char*) xmalloc((MAX_FNAME_CHAR)*sizeof(char)); construct_fname(fname, MAX_FNAME_CHAR, fbasename, time_str, OUTPUT_DATA_EXT); FILE *output; output = xfopen(fname, "w" ); for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ fprintf(output, "%lg\t", var[i][j]); } fprintf(output, "\n"); } fclose(output); xfree(fname); } static void calc_Q_flux(double **upward_Q_flux, double **T_surf, Grid_vals *grid, int n_lats, int n_lons) { double **F_net_sw_down = create_2d_pointer(n_lats,n_lons); double **F_lw_down = create_2d_pointer(n_lats,n_lons); double **F_latent_up = create_2d_pointer(n_lats,n_lons); double **F_sensible_up = create_2d_pointer(n_lats,n_lons); read_input_data(F_net_sw_down,SW_FLUX_NET_DOWN_DATA,n_lats,n_lons); read_input_data(F_lw_down,LW_FLUX_DOWN_DATA,n_lats,n_lons); read_input_data(F_latent_up,LATENT_UP_FLUX_DATA,n_lats,n_lons); read_input_data(F_sensible_up,SENSIBLE_UP_FLUX_DATA,n_lats,n_lons); for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ upward_Q_flux[i][j] = F_latent_up[i][j] + F_sensible_up[i][j] + EMISSIVITY*SIGMA*pow(T_surf[i][j],4) - (F_net_sw_down[i][j] + F_lw_down[i][j]); } } destroy_2d_pointer(F_net_sw_down,n_lats); destroy_2d_pointer(F_lw_down,n_lats); destroy_2d_pointer(F_latent_up,n_lats); destroy_2d_pointer(F_sensible_up,n_lats); } /* convert angle in degrees to radians for evaluating trigonometric functions in calculus */ static double deg_to_rad(double theta) { return theta*M_PI/180.0; } /* calculates the first spatial derivative of A with respect to a (which may be theta or phi), on a spherical surface. Used mainly to calculate derivative of mass transport components M_theta and M_phi. Boundary conditions are used for a spherical geometry, using A[i][0] to be adjacent to A[i][n_lons-1], and also A[0][j] is adjacent to the opposite point in longitude (j+-n_lats/2) at the same latitude. */ static double dA_da(double **A, int i, int j, int a, int n_lats, int n_lons) { double d_theta=deg_to_rad(DELTA_LAT); double d_phi=deg_to_rad(DELTA_LON); if(a==THETA){ if(i==n_lats-1){ int j_temp = j+n_lons/2; if(j_temp>=n_lons){ j_temp -=n_lons; } return (A[i][j_temp]-A[i-1][j])/(2*d_theta); } else if(i==0){ int j_temp = j+n_lons/2; if(j_temp>=n_lons){ j_temp -=n_lons; } return (A[i+1][j]-A[i][j_temp])/(2*d_theta); } else{ return (A[i+1][j]-A[i-1][j])/(2*d_theta); } } else if(a==PHI){ if(j==n_lons-1){ return (A[i][0]-A[i][j-1])/(2*d_phi); } else if(j==0){ return (A[i][j+1]-A[i][n_lons-1])/(2*d_phi); } else{ return (A[i][j+1]-A[i][j-1])/(2*d_phi); } } else{ fprintf(stderr, "Specified derivative is not respect to either theta or phi\n"); exit(DERIVATIVE_ERR); } } /* Returns the horizontal divergence of quanitity M. determines whether there is an up or downward flow between the ocean layers */ static double calculate_div_M(double ***M, Grid_vals *grid, int i, int j, int n_lats, int n_lons) { double theta=deg_to_rad(grid->lat[i]); double dM_theta_dtheta = dA_da(M[THETA],i,j,THETA,n_lats,n_lons); double dM_phi_dphi = dA_da(M[PHI],i,j,PHI,n_lats,n_lons); double div_M=1./R_PLANET*(dM_theta_dtheta-tan(theta)*M[THETA][i][j]+1./cos(theta)*dM_phi_dphi); return div_M; } static void calc_flow_Sv(double ***Sv_flow, double ***M, Grid_vals *grid, int n_lats, int n_lons) { for(int i=0;i<n_lats;i++){ double theta=deg_to_rad(grid->lat[i]); for(int j=0;j<n_lons;j++){ Sv_flow[PHI][i][j] = M[PHI][i][j] * R_PLANET * DELTA_LAT * M_PI / 180. / RHO_WATER / 1.0e6; Sv_flow[THETA][i][j] = M[THETA][i][j] * R_PLANET * cos(theta) * deg_to_rad(DELTA_LON) / RHO_WATER / 1.0e6; } } } static void process_output_data(double ***T, double ***M, Grid_vals *grid, int n_lats, int n_lons, double time) { // processes output data double days = T_OFFSET+time/(HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MINUTE); days=round(days); printf("Data outputted at %lg\n", days); int day_int = days+TIME_OUTPUT_TOL; char time_str[10]; sprintf(time_str, "%d", day_int); // char *fname = (char*) xmalloc((MAX_FNAME_CHAR)*sizeof(char)); double **upward_Q_flux= create_2d_pointer(n_lats,n_lons); calc_Q_flux(upward_Q_flux,T[SURFACE],grid,n_lats,n_lons); // construct_fname(fname, MAX_FNAME_CHAR, OUTPUT_UPWARD_LW_SURFACE_FLUX, time_str, OUTPUT_DATA_EXT); write_data(upward_Q_flux, OUTPUT_UPWARD_Q_FLUX, time_str, grid, n_lats, n_lons); destroy_2d_pointer(upward_Q_flux,n_lats); double ***Sv_flow = create_3d_pointer(N_COORDS,N_LATS,N_LONS); calc_flow_Sv(Sv_flow,M,grid,n_lats,n_lons); write_data(Sv_flow[PHI], OUTPUT_X_MASS_FLUX_DATA, time_str, grid, n_lats, n_lons); write_data(Sv_flow[THETA], OUTPUT_Y_MASS_FLUX_DATA, time_str, grid, n_lats, n_lons); destroy_3d_pointer(Sv_flow,N_COORDS,N_LATS); double **div_M= create_2d_pointer(n_lats,n_lons); for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ div_M[i][j] = calculate_div_M(M,grid,i,j,n_lats,n_lons); } } write_data(div_M, OUTPUT_VERITCAL_FLUX_DATA, time_str, grid, n_lats, n_lons); destroy_2d_pointer(div_M,n_lats); // construct_fname(fname, MAX_FNAME_CHAR, OUTPUT_SURFACE_TEMP_DATA, time_str, OUTPUT_DATA_EXT); write_data(T[SURFACE], OUTPUT_SURFACE_TEMP_DATA, time_str, grid, n_lats, n_lons); // construct_fname(fname, MAX_FNAME_CHAR, OUTPUT_DEEP_TEMP_DATA, time_str, OUTPUT_DATA_EXT); write_data(T[DEEP], OUTPUT_DEEP_TEMP_DATA, time_str, grid, n_lats, n_lons); // xfree(fname); } /* returns height of layer given index h, from enum heights. */ static double height_of_slab(int h) { if(h==SURFACE){ return H_S; } else if(h==DEEP){ return H_D; } else{ fprintf(stderr, "Index for depth is out of range.\n"); exit(DEPTH_ERR); } } /* Constructs a grid with latitude and longitude points on the sphere, starting at LAT_MIN and LON_MIN, increasing in increments of DELTA_LAT and DELTA_LON */ static void construct_grid(Grid_vals *grid, int n_lats, int n_lons, char *lats_file, char *lons_file) { FILE *lats_out; lats_out = xfopen(lats_file, "w" ); for(int i=0;i<n_lats;i++){ grid->lat[i]=LAT_MIN+(i*DELTA_LAT); fprintf(lats_out, "%i\t%lg\n", i, grid->lat[i]); } fclose(lats_out); FILE *lons_out; lons_out = xfopen(lons_file, "w" ); for(int j=0;j<n_lons;j++){ grid->lon[j]=LON_MIN+(j*DELTA_LON); fprintf(lons_out, "%i\t%lg\n", j, grid->lon[j]); } fclose(lons_out); } /* Calculates the surface stress on the ocean surface as a result of the atmospheric winds near the surface. Reads in velocity data from .dat files */ static void calculate_surface_stress(double ***tau, Grid_vals *grid, int n_lats, int n_lons) { double ***v = create_3d_pointer(N_COORDS,N_LATS,N_LONS); read_input_data(v[THETA],V_WIND_DATA,n_lats,n_lons); read_input_data(v[PHI],U_WIND_DATA,n_lats,n_lons); for(int coord=THETA;coord<N_COORDS;coord++){ for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ tau[coord][i][j]=C_D*RHO_AIR*v[coord][i][j]*fabs(v[coord][i][j]); // retains sign of velocity } } } destroy_3d_pointer(v,N_COORDS,N_LATS); } /* Returns the coriolis parameter at an latitude theta */ static double calculate_coriolis_parameter(double theta) { // f=2*Omega*sin(theta) return 2*OMEGA*sin(deg_to_rad(theta)); } /* calculates the mass flux due to Ekman transport */ static void calculate_mass_flux(double ***M, int **land_mask, Grid_vals *grid, int n_lats, int n_lons) { double ***tau = create_3d_pointer(N_COORDS,N_LATS,N_LONS); // read_input_data(tau[THETA],Y_STRESS_DATA,n_lats,n_lons); // read_input_data(tau[PHI],X_STRESS_DATA,n_lats,n_lons); calculate_surface_stress(tau, grid, n_lats, n_lons); for(int i=0;i<n_lats;i++){ double f = calculate_coriolis_parameter(grid->lat[i]); for(int j=0;j<n_lons;j++){ if(land_mask[i][j]==1){ M[THETA][i][j]=0.; M[PHI][i][j]=0.; } else{ M[THETA][i][j]=(EPSILON*tau[THETA][i][j]+f*tau[PHI][i][j])/(pow(EPSILON,2)+pow(f,2)); M[PHI][i][j]=(EPSILON*tau[PHI][i][j]-f*tau[THETA][i][j])/(pow(EPSILON,2)+pow(f,2)); } } } destroy_3d_pointer(tau,N_COORDS,N_LATS); } /* Plots the script called filename in python */ // static void plot_data(char *filename) // { // char command[PATH_MAX]; // snprintf(command, sizeof(command), "%s %s", PYTHON_EXE, filename); // system( command ); // } /* Calculates the index for the matrix used in the solver, before being compressed */ static int calculate_matrix_index(int height, int lat, int lon, int n_lats, int n_lons) { return height*n_lats*n_lons+lat*n_lons+lon; } /* At maximum or minimum latitutde, the adjacent latitude point above or bellow, respectively, is located at the same latitude, but at the new longitudinal point (from lon to new_lon) */ static int calculate_new_lon(int lon, int n_lons) { int new_lon = lon+n_lons/2; if(new_lon>=n_lons){ new_lon -= n_lons; } return new_lon; } /* calculates and sets the matrix elements for a 2 layer ocean with 144 longitude points and 90 latitude points. version determines whether the matrix is calculated for a no horizontal transport model, diffusion only model or the full Ekman model. */ static void calculate_matrix(gsl_spmatrix *A, double ***M, int **land_mask, Grid_vals *grid, int n_lats, int n_lons, int version) { double d_theta=deg_to_rad(DELTA_LAT); double d_phi=deg_to_rad(DELTA_LON); double s_dfsn = DELTA_T*D/pow(R_PLANET,2); for(int height=SURFACE; height<N_DEPTHS; height++){ double thickness = height_of_slab(height); double s_ekmn = DELTA_T/(RHO_WATER*thickness*R_PLANET); for(int lat=0; lat<n_lats; lat++){ double theta = deg_to_rad(grid->lat[lat]); for(int lon=0; lon<n_lons; lon++){ double Aii=0.0; int i; i = calculate_matrix_index(height,lat,lon,n_lats,n_lons); /* central point - check if land */ if(land_mask[lat][lon]==1){ Aii=1.; gsl_spmatrix_set(A, i, i, Aii); continue; } double dM_theta_dtheta = dA_da(M[THETA],lat,lon,THETA,n_lats,n_lons); double dM_phi_dphi = dA_da(M[PHI],lat,lon,PHI,n_lats,n_lons); double M_theta = M[THETA][lat][lon]; double M_phi = M[PHI][lat][lon]; double div_M = calculate_div_M(M,grid,lat,lon,n_lats,n_lons); double Aij=0.0; int j; /* central point */ Aii=1.; if(version != NO_TRANSPORT){ // if(height==SURFACE){ Aii+= 2.*s_dfsn*(1./pow(d_theta,2)+1./pow(cos(theta)*d_phi,2)); // } if(version==DIFUSION_EKMAN){ if(height==SURFACE){ Aii+= s_ekmn*(dM_theta_dtheta-M_theta*tan(theta)+1./cos(theta)*dM_phi_dphi); if(div_M<0.0){ Aii+=(-DELTA_T/(RHO_WATER*thickness)*div_M); } } else if(height==DEEP){ Aii+= -s_ekmn*(dM_theta_dtheta-M_theta*tan(theta)+1./cos(theta)*dM_phi_dphi); if(div_M>0.0){ Aii+=(+DELTA_T/(RHO_WATER*thickness)*div_M); } } } } gsl_spmatrix_set(A, i, i, Aii); /* Neigbouring points */ int lon_j, lat_j; if(version != NO_TRANSPORT){ /* neighbouring latitude - below */ if(lat==0){ lon_j = calculate_new_lon(lon,n_lons); lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } else{ lon_j = lon; lat_j = lat-1; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } Aij=-s_dfsn*(1./pow(d_theta,2)+tan(theta)/(2*d_theta)); if(version==DIFUSION_EKMAN){ if(height==SURFACE){ Aij+= s_ekmn*(-M_theta/(2.*d_theta)); } else{ Aij+= -s_ekmn*(-M_theta/(2.*d_theta)); } } if(land_mask[lat_j][lon_j]==1){ Aii+=Aij; Aij=0.; } gsl_spmatrix_set(A, i, j, Aij); /* neighbouring latitude - above */ if(lat==n_lats-1){ lon_j = calculate_new_lon(lon,n_lons); lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } else{ lon_j = lon; lat_j = lat+1; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } Aij=-s_dfsn*(1./pow(d_theta,2)-tan(theta)/(2*d_theta)); if(version==DIFUSION_EKMAN){ if(height==SURFACE){ Aij+= s_ekmn*(M_theta/(2.*d_theta)); } else{ Aij+= -s_ekmn*(M_theta/(2.*d_theta)); } } if(land_mask[lat_j][lon_j]==1){ Aii+=Aij; Aij=0.; } gsl_spmatrix_set(A, i, j, Aij); /* neighbouring longitude - left */ if(lon==0){ lon_j = n_lons-1; lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } else{ lon_j = lon-1; lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } Aij=-s_dfsn*1./pow(cos(theta)*d_phi,2); if(version==DIFUSION_EKMAN){ if(height==SURFACE){ Aij+= s_ekmn*(-M_phi/(2.*d_phi*cos(theta))); } else{ Aij+= -s_ekmn*(-M_phi/(2.*d_phi*cos(theta))); } } if(land_mask[lat_j][lon_j]==1){ Aii+=Aij; Aij=0.; } gsl_spmatrix_set(A, i, j, Aij); /* neighbouring longitude - right */ if(lon==n_lons-1){ lon_j = 0; lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } else{ lon_j = lon+1; lat_j = lat; j = calculate_matrix_index(height,lat_j,lon_j,n_lats,n_lons); } Aij=-s_dfsn*1./pow(cos(theta)*d_phi,2); if(version==DIFUSION_EKMAN){ if(height==SURFACE){ Aij+= s_ekmn*(M_phi/(2.*d_phi*cos(theta))); } else{ Aij+= -s_ekmn*(M_phi/(2.*d_phi*cos(theta))); } } if(land_mask[lat_j][lon_j]==1){ Aii+=Aij; Aij=0.; } gsl_spmatrix_set(A, i, j, Aij); gsl_spmatrix_set(A, i, i, Aii); /* interaction between deep and surface layer */ if(version==DIFUSION_EKMAN){ if(height==SURFACE && div_M>0.0){ Aij=(-DELTA_T/(RHO_WATER*thickness)*div_M); j = calculate_matrix_index(DEEP,lat,lon,n_lats,n_lons); gsl_spmatrix_set(A, i, j, Aij); } else if(height==DEEP && div_M<0.0){ Aij=(+DELTA_T/(RHO_WATER*thickness)*div_M); j = calculate_matrix_index(SURFACE,lat,lon,n_lats,n_lons); gsl_spmatrix_set(A, i, j, Aij); } } } } } } } /* Reads in atmospheric fluxes, net stellar sw flux (subrtracts reflected sw radiation from the incident) and incoming lw flux from atmospheric emission */ static void calculate_F_a(double **F_a, int n_lats, int n_lons) { double **F_net_sw_down = create_2d_pointer(n_lats,n_lons); double **F_lw_down = create_2d_pointer(n_lats,n_lons); double **F_latent_up = create_2d_pointer(n_lats,n_lons); double **F_sensible_up = create_2d_pointer(n_lats,n_lons); read_input_data(F_net_sw_down,SW_FLUX_NET_DOWN_DATA,n_lats,n_lons); read_input_data(F_lw_down,LW_FLUX_DOWN_DATA,n_lats,n_lons); read_input_data(F_latent_up,LATENT_UP_FLUX_DATA,n_lats,n_lons); read_input_data(F_sensible_up,SENSIBLE_UP_FLUX_DATA,n_lats,n_lons); for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ F_a[i][j] = (F_net_sw_down[i][j] + F_lw_down[i][j]) - (F_latent_up[i][j] + F_sensible_up[i][j]); } } destroy_2d_pointer(F_net_sw_down,n_lats); destroy_2d_pointer(F_lw_down,n_lats); destroy_2d_pointer(F_latent_up,n_lats); destroy_2d_pointer(F_sensible_up,n_lats); } /* Checks if convetion condition is met, then calculates the associated flux. */ static void calculate_F_c(double **F_c, double ***T, int n_lats, int n_lons) { for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ if(T[DEEP][i][j]>T[SURFACE][i][j]){ /* convection condition */ F_c[i][j] = HEAT_TRANSFER_COEFFICIENT*(T[DEEP][i][j]-T[SURFACE][i][j]); } else{ F_c[i][j] = 0.0; } } } } /* calculated and sets the vector b in matrix Ax=b. EMISSIVITY*SIGMA*T^4 is a blackbody emission from one of the layers, to ensure an energy exchange between the layers. 1.0/(RHO_WATER*C_V*H_S) prefactor converts a flux in W/m2 to K/s */ static void calculate_vector_b(double ***T, int **land_mask, gsl_vector *b, int n_lats, int n_lons) { // calculates b from matrix equation Ax=b double **F_a = create_2d_pointer(n_lats,n_lons); calculate_F_a(F_a,n_lats,n_lons); double **F_c = create_2d_pointer(n_lats,n_lons); calculate_F_c(F_c,T,n_lats,n_lons); double b_hij = 0.0; for(int h=0;h<N_DEPTHS;h++){ for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ if(land_mask[i][j]==1){ b_hij = T[h][i][j]; } else{ double depth = height_of_slab(h); if(h==SURFACE){ b_hij = DELTA_T/(RHO_WATER*C_V*depth)*(F_c[i][j]+F_a[i][j]-EMISSIVITY*SIGMA*pow(T[SURFACE][i][j],4))+ T[h][i][j]; // b_hij = DELTA_T/(RHO_WATER*C_V*depth)*(F_c[i][j]+F_a[i][j]) + T[h][i][j]; } else{ b_hij = DELTA_T/(RHO_WATER*C_V*depth)*(-F_c[i][j]) + T[h][i][j]; } } gsl_vector_set(b, (h*n_lats*n_lons+(i*n_lons+j)), b_hij); } } } destroy_2d_pointer(F_a,n_lats); destroy_2d_pointer(F_c,n_lats); } /* Uses GSL sparse linear algebra to solve Ax=b */ static void calculate_new_T(double ***T, double ***M, int **land_mask, Grid_vals *grid, int n_lats, int n_lons, int version) { int n = N_DEPTHS*n_lats*n_lons; gsl_spmatrix *A = gsl_spmatrix_alloc(n ,n); gsl_spmatrix *C; gsl_vector *b = gsl_vector_alloc(n); gsl_vector *x = gsl_vector_alloc(n); calculate_matrix(A,M,land_mask,grid,n_lats,n_lons,version); calculate_vector_b(T,land_mask,b,n_lats,n_lons); C = gsl_spmatrix_ccs(A); /* now solve the system with the GMRES iterative solver */ const double tol = TOL; /* solution relative tolerance */ const size_t max_iter = MAX_ITER; /* maximum iterations */ const gsl_splinalg_itersolve_type *S = gsl_splinalg_itersolve_gmres; gsl_splinalg_itersolve *work = gsl_splinalg_itersolve_alloc(S, n, 0); size_t iter = 0; double residual; int status; /* initial guess x = 0 */ gsl_vector_set_zero(x); // for(int h=0;h<N_DEPTHS;h++){ // for(int i=0;i<n_lats;i++){ // for(int j=0;j<n_lons;j++){ // gsl_vector_set(x, (h*n_lats*n_lons+(i*n_lons+j)), T[h][i][j]); // } // } // } /* solve the system A x = b */ do{ status = gsl_splinalg_itersolve_iterate(C, b, tol, x, work); if (status != GSL_SUCCESS && iter==max_iter-1){ /* Solver exits if solution diverges */ residual = gsl_splinalg_itersolve_normr(work); fprintf(stderr, "iter %zu residual = %.12e\n", iter, residual); fprintf(stderr, "Diverged\n"); exit(SOLVER_ERR); } } while (status == GSL_CONTINUE && ++iter < max_iter); /* output solution */ for(int h=0;h<N_DEPTHS;h++){ /* sets the new temperature from the gsl vector */ for(int i=0;i<n_lats;i++){ for(int j=0;j<n_lons;j++){ T[h][i][j]=gsl_vector_get(x,h*n_lats*n_lons+(i*n_lons+j)); } } } gsl_splinalg_itersolve_free(work); gsl_spmatrix_free(A); gsl_spmatrix_free(C); gsl_vector_free(b); gsl_vector_free(x); } /* Function that steps through selected time. First creates the horizontal grid, then read in temperatures, and steps through n_times time steps. Writes the final Temperature data to files, and plots a selected plotting script. */ static void time_stepper(int n_times, int n_lats, int n_lons, int version) { Grid_vals *grid = xmalloc(sizeof(Grid_vals)); construct_grid(grid,n_lats,n_lons,LATS_FILE,LONS_FILE); double ***T=create_3d_pointer(N_DEPTHS,N_LATS,N_LONS); read_input_data(T[SURFACE],INITIAL_SURFACE_TEMP_DATA,n_lats,n_lons); read_input_data(T[DEEP],INITIAL_DEEP_TEMP_DATA,n_lats,n_lons); int **land_mask = create_2d_int_pointer(n_lats,n_lons); read_input_int_data(land_mask,LAND_MASK_DATA,n_lats,n_lons); double ***M=create_3d_pointer(N_COORDS,N_LATS,N_LONS); double time = 0.; double days = 0.; for(int t=0;t<n_times;t++){ time = ((double)t+1.)*DELTA_T; calculate_mass_flux(M,land_mask,grid,n_lats,n_lons); calculate_new_T(T,M,land_mask,grid,n_lats,n_lons,version); if (fmod(time,TIME_OUTPUT_FREQ)<TIME_OUTPUT_TOL){ days = T_OFFSET+time/(HOURS_PER_DAY*MINUTES_PER_HOUR*SECONDS_PER_MINUTE); printf("Days passed = %lg\n", days); } if (fmod(time,DATA_OUTPUT_FREQ)<TIME_OUTPUT_TOL){ process_output_data(T, M, grid, n_lats, n_lons, time); } } destroy_2d_int_pointer(land_mask,n_lats); process_output_data(T, M, grid, n_lats, n_lons, time); // plot_data(PYTHON_SCRIPT); destroy_3d_pointer(M,N_COORDS,N_LATS); destroy_3d_pointer(T,N_DEPTHS,N_LATS); xfree(grid); }
{ "alphanum_fraction": 0.692975301, "avg_line_length": 34.8680318544, "ext": "c", "hexsha": "991168a9f3ad50f200b9db9cacde349badd8af5f", "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": "d145b5786bdeb6f108e5f4a0e80830316b0e095f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Kazu1886/ekman_ocean", "max_forks_repo_path": "Ocean_model.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d145b5786bdeb6f108e5f4a0e80830316b0e095f", "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": "Kazu1886/ekman_ocean", "max_issues_repo_path": "Ocean_model.c", "max_line_length": 152, "max_stars_count": null, "max_stars_repo_head_hexsha": "d145b5786bdeb6f108e5f4a0e80830316b0e095f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Kazu1886/ekman_ocean", "max_stars_repo_path": "Ocean_model.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9711, "size": 30649 }
#ifndef cgsl_shim_h #define cgsl_shim_h #include <gsl/gsl_math.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_rng.h> #endif
{ "alphanum_fraction": 0.7709923664, "avg_line_length": 16.375, "ext": "h", "hexsha": "e78c9a5984789992f87feb73766d3acfc48958e7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-04-18T08:59:56.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-18T08:59:56.000Z", "max_forks_repo_head_hexsha": "c96ce3ee34b3c0b16d01c1095f600cd4d996e50d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "kongzii/SGSL", "max_forks_repo_path": "Sources/CGSL/shim.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c96ce3ee34b3c0b16d01c1095f600cd4d996e50d", "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": "kongzii/SGSL", "max_issues_repo_path": "Sources/CGSL/shim.h", "max_line_length": 31, "max_stars_count": 13, "max_stars_repo_head_hexsha": "c96ce3ee34b3c0b16d01c1095f600cd4d996e50d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "kongzii/SGSL", "max_stars_repo_path": "Sources/CGSL/shim.h", "max_stars_repo_stars_event_max_datetime": "2021-06-23T18:37:42.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-10T08:26:42.000Z", "num_tokens": 42, "size": 131 }
#pragma once #include <map> #include <set> #ifdef _NOGSL class gsl_vector; #else #include <gsl/gsl_vector.h> #endif class Interface; class SymbolicEvaluator { double otherError = 1; public: virtual void setInputs(Interface* inputValues_p) = 0; virtual void run(const gsl_vector* ctrls_p, const set<int>& nodesSubset) = 0; virtual void run(const gsl_vector* ctrls_p) = 0; virtual double getErrorOnConstraint(int nodeid, gsl_vector* grad) = 0; virtual double getErrorOnConstraint(int nodeid) = 0; virtual double getErrorForAsserts(const set<int>& nodeid, gsl_vector* grad) = 0; virtual double getErrorForAssert(int assertId, gsl_vector* grad)=0; virtual double dist(int nid) = 0; virtual double dist(int nid, gsl_vector* grad) = 0; virtual void print() = 0; virtual void printFull() = 0; void resetOtherError() { otherError = 1; } void setOtherError(double error) { otherError = error; } double getOtherError() { return otherError; } bool isSetOtherError() { return otherError != 1; } };
{ "alphanum_fraction": 0.7014084507, "avg_line_length": 19.3636363636, "ext": "h", "hexsha": "e0bdf6f32cb3c45d2f603f07fcfd64ec840f4354", "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/SymbolicEvaluator.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/SymbolicEvaluator.h", "max_line_length": 84, "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/SymbolicEvaluator.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": 292, "size": 1065 }
#pragma once #include <gsl/gsl_complex.h> int compare(double n1, double n2, double precision = 1e-15); int compare(const gsl_complex& c1, const gsl_complex& c2, double precision = 1e-15); bool operator==(const gsl_complex& c1, const gsl_complex& c2); bool operator!=(const gsl_complex& c1, const gsl_complex& c2);
{ "alphanum_fraction": 0.7300613497, "avg_line_length": 32.6, "ext": "h", "hexsha": "9661176afc4a65d2203d5b16988875d0f6d1f239", "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/Numeric.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/Numeric.h", "max_line_length": 85, "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/Numeric.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 90, "size": 326 }
#ifndef _PKMCMC_H_ #define _PKMCMC_H_ #include <vector> #include <string> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_matrix.h> class pkmcmc{ int num_data, num_pars, workspace_size; std::vector<double> data, model, k; std::vector<double> theta_0, theta_i, param_vars, min, max; std::vector<std::vector<double>> cov, Psi; std::vector<bool> limit_pars; gsl_spline *Pk_bao, *Pk_nw; gsl_interp_accel *acc_bao, *acc_nw; double chisq_0, chisq_i, abs_err, rel_err, k_min, k_max; // The function to be integrated by GSL double model_func(std::vector<double> &pars, int j); //done // Performs the integral needed for the model value at each data point void model_calc(std::vector<double> &pars); //done // Randomly selects a new parameter realization for a trial void get_param_real(); //done // Compute the chi^2 value of the current model with the data double calc_chi_squared(); //done // Perform one Metropolis-Hastings trial bool trial(); //done // Write the current accepted parameter realization to the screen void write_theta_screen(); //done // Perform a number of trials to move from the initial parameter guess to a higher likelihood region void burn_in(int num_burn); //done // Tune the acceptance ratio to be about 0.234 void tune_vars(); //done public: // Initialization function pkmcmc(std::string data_file, std::string cov_file, std::string pk_bao_file, std::string pk_nw_file, std::vector<double> &pars, std::vector<double> &vars, bool mock_avg); //done // Check that the vectors have the expected sizes void check_init(); //done // Set which parameters have priors and what those priors are. void set_param_limits(std::vector<bool> &lim_pars, std::vector<double> &min_in, std::vector<double> &max_in); //done // Run a number of Metropolis-Hastings trials to form the MCMC chain void run_chain(int num_draws, std::string reals_file, bool new_chain); // Free the memory with various GSL class members void clean_up_gsl(); }; #endif
{ "alphanum_fraction": 0.6569311247, "avg_line_length": 35.2923076923, "ext": "h", "hexsha": "8eb743a7f60084dcd4e7991d57c013b0430dcf68", "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": "aa8af7c8daa4c6ac4c5fa118e4d6584c8698a392", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dpearson1983/pkMCMC2", "max_forks_repo_path": "include/pkmcmc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "aa8af7c8daa4c6ac4c5fa118e4d6584c8698a392", "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": "dpearson1983/pkMCMC2", "max_issues_repo_path": "include/pkmcmc.h", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "aa8af7c8daa4c6ac4c5fa118e4d6584c8698a392", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dpearson1983/pkMCMC2", "max_stars_repo_path": "include/pkmcmc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 572, "size": 2294 }
/* Copyright 2017 International Business Machines 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. */ #pragma once #include "kernelpp/types.h" #include <gsl.h> namespace mwe { using kernelpp::maybe; using kernelpp::status; /* Operations --------------------------------------------------------- */ maybe<int> add(int a, int b); status add(const gsl::span<int> a, const gsl::span<int> b, gsl::span<int> result ); }
{ "alphanum_fraction": 0.6591836735, "avg_line_length": 29.696969697, "ext": "h", "hexsha": "72274bfdd23be1bc5e0d96a883f872ce447f8c13", "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": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rayglover-ibm/cuda-bindings", "max_forks_repo_path": "include/mwe.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "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": "rayglover-ibm/cuda-bindings", "max_issues_repo_path": "include/mwe.h", "max_line_length": 79, "max_stars_count": 7, "max_stars_repo_head_hexsha": "7d9f2f1f2f15cec7ec7b1d5882dc2a2cbfb646cd", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rayglover-ibm/cuda-bindings", "max_stars_repo_path": "include/mwe.h", "max_stars_repo_stars_event_max_datetime": "2021-05-25T10:01:56.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-18T02:56:15.000Z", "num_tokens": 205, "size": 980 }
/* * Take the input stream and tally the distribution of 8-bit bytes. * Calculate the entropy. */ #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_sf_log.h> #include <gsl/gsl_math.h> int main(int argc, char **argv) { int tally[256]; int ch; int n = 0; double h = 0; for (int i=0; i<256; i++) tally[i] = 0; FILE *in; printf ("argc = %d\n", argc); if (argc < 2) { printf ("Input from stdin.\n"); in = stdin; } else { printf ("Input file: %s\n", argv[1]); in = fopen(argv[1], "r"); if (in == NULL) { printf("BAD file: Usage: %s <random_file>\n", argv[0]); return 1; } } while ((ch = fgetc(in)) != EOF) { tally[ch] ++; n ++; } fclose(in); printf("Frequency by byte:"); for (int i=0; i<256; i++) { printf(" %d", tally[i]); } printf("\n"); printf("Input length = %d\n", n); for (int i=0; i<256; i++) { double p = (double)(tally[i])/n; if (p>0) { h = h - p*gsl_sf_log(p); } } // Divide by ln(2) to produce base 2 logarithms to calculate bits of entropy. h = h/M_LN2; printf("Entropy (h) = %1.10f\n", h); // Maximum entropy on bytes is 8 bits. Efficiency is calculated by dividing by the max. double eta = h/8; printf("Efficiency (eta) = %1.10f\n", eta); printf("ln(1-eta) = %1.10f\n", gsl_sf_log(1-eta)); // This prediction is based on the regression from test5. printf("Predicted value = %1.10f\n", -1.035*gsl_sf_log(n) + 3.562); return 0; }
{ "alphanum_fraction": 0.5857946554, "avg_line_length": 20.9117647059, "ext": "c", "hexsha": "e722a40edfe932807cc5164bc77428b0005b5c2e", "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": "dc103a67d0826f09b07196217f00a454441d5011", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonkanderson/BitBalancedTableHash", "max_forks_repo_path": "tests/entropy_tests/exp01.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "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": "jonkanderson/BitBalancedTableHash", "max_issues_repo_path": "tests/entropy_tests/exp01.c", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc103a67d0826f09b07196217f00a454441d5011", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonkanderson/BitBalancedTableHash", "max_stars_repo_path": "tests/entropy_tests/exp01.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 488, "size": 1422 }
#ifndef GLOTTAL_PHASES_H #define GLOTTAL_PHASES_H #include <array> #include <vector> #include <cstring> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_complex.h> #include "constants.h" void estimatePhases(gsl_vector *dEGG, double T0, double *Oq, double *Cq); #endif // GLOTTAL_PHASES_H
{ "alphanum_fraction": 0.7647058824, "avg_line_length": 19.125, "ext": "h", "hexsha": "d66370c9663deab1cd246a8a6c5845ba48258877", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_path": "inc/glottal_phases.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "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": "ichi-rika/glottal-inverse", "max_issues_repo_path": "inc/glottal_phases.h", "max_line_length": 73, "max_stars_count": 6, "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_path": "inc/glottal_phases.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "num_tokens": 139, "size": 459 }
#pragma once #include <variant> #include <gsl/gsl-lite.hpp> #include <clrie/instruction_factory.h> namespace appmap { namespace cil { struct op { ILOrdinalOpcode op; }; struct token_op { ILOrdinalOpcode op; mdToken token; }; struct long_op { ILOrdinalOpcode op; uint64_t value; }; template <ILOrdinalOpcode Op> struct token_opcode: token_op { token_opcode(mdToken token): token_op{Op, token} {} }; namespace ops { struct ldarg { int index; }; struct ldloc { int index; }; struct stloc { int index; }; using ldfld = token_opcode<Cee_Ldfld>; using stfld = token_opcode<Cee_Stfld>; using ldftn = token_opcode<Cee_Ldftn>; using call = token_opcode<Cee_Call>; using calli = token_opcode<Cee_Calli>; using callvirt = token_opcode<Cee_Callvirt>; using newobj = token_opcode<Cee_Newobj>; constexpr inline auto ldnull = op{Cee_Ldnull}; constexpr inline auto pop = op{Cee_Pop}; constexpr inline auto dup = op{Cee_Dup}; struct ldc: long_op { ldc(uint64_t val): long_op{Cee_Ldc_I8, val} {} template <typename Ret, typename... Args> ldc(Ret(*fn)(Args...)): ldc(reinterpret_cast<uint64_t>(fn)) {} }; } using instruction = std::variant<ops::ldarg, ops::ldloc, ops::stloc, op, token_op, long_op>; clrie::instruction_factory::instruction_sequence compile(const gsl::span<const instruction> code, const clrie::instruction_factory &factory); clrie::instruction_factory::instruction_sequence compile(std::initializer_list<const instruction> code, const clrie::instruction_factory &factory); }}
{ "alphanum_fraction": 0.7060662914, "avg_line_length": 25.7903225806, "ext": "h", "hexsha": "94ccc43186adaa8604409b3192cdc72b3797efc3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-06-24T02:05:16.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-24T02:05:16.000Z", "max_forks_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "applandinc/appmap-dotnet", "max_forks_repo_path": "source/cil.h", "max_issues_count": 18, "max_issues_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_issues_repo_issues_event_max_datetime": "2021-08-22T16:45:26.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-28T22:32:05.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "applandinc/appmap-dotnet", "max_issues_repo_path": "source/cil.h", "max_line_length": 147, "max_stars_count": 5, "max_stars_repo_head_hexsha": "f62bf237493472a61701c82ddf8d6f3491707307", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "applandinc/appmap-dotnet", "max_stars_repo_path": "source/cil.h", "max_stars_repo_stars_event_max_datetime": "2021-06-24T02:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-11T04:59:58.000Z", "num_tokens": 416, "size": 1599 }
/* multimin/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi * * 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. */ /* Modified by Tuomo Keskitalo to add Nelder Mead Simplex test suite */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_test.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_ieee_utils.h> #include "test_funcs.h" unsigned int fcount, gcount; int test_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T); int test_f(const char * desc, gsl_multimin_function *f, initpt_function initpt, const gsl_multimin_fminimizer_type *T); int main (void) { gsl_ieee_env_setup (); { const gsl_multimin_fdfminimizer_type *fdfminimizers[6]; const gsl_multimin_fdfminimizer_type ** T; fdfminimizers[0] = gsl_multimin_fdfminimizer_steepest_descent; fdfminimizers[1] = gsl_multimin_fdfminimizer_conjugate_pr; fdfminimizers[2] = gsl_multimin_fdfminimizer_conjugate_fr; fdfminimizers[3] = gsl_multimin_fdfminimizer_vector_bfgs; fdfminimizers[4] = gsl_multimin_fdfminimizer_vector_bfgs2; fdfminimizers[5] = 0; T = fdfminimizers; while (*T != 0) { test_fdf("Roth", &roth, roth_initpt,*T); test_fdf("Wood", &wood, wood_initpt,*T); test_fdf("Rosenbrock", &rosenbrock, rosenbrock_initpt,*T); T++; } T = fdfminimizers; while (*T != 0) { test_fdf("NRoth", &Nroth, roth_initpt,*T); test_fdf("NWood", &Nwood, wood_initpt,*T); test_fdf("NRosenbrock", &Nrosenbrock, rosenbrock_initpt,*T); T++; } } { const gsl_multimin_fminimizer_type *fminimizers[4]; const gsl_multimin_fminimizer_type ** T; fminimizers[0] = gsl_multimin_fminimizer_nmsimplex; fminimizers[1] = gsl_multimin_fminimizer_nmsimplex2; fminimizers[2] = gsl_multimin_fminimizer_nmsimplex2rand; fminimizers[3] = 0; T = fminimizers; while (*T != 0) { test_f("Roth", &roth_fmin, roth_initpt,*T); test_f("Wood", &wood_fmin, wood_initpt,*T); test_f("Rosenbrock", &rosenbrock_fmin, rosenbrock_initpt,*T); test_f("Spring", &spring_fmin, spring_initpt,*T); T++; } } exit (gsl_test_summary()); } int test_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T) { int status; size_t iter = 0; double step_size; gsl_vector *x = gsl_vector_alloc (f->n); gsl_multimin_fdfminimizer *s; fcount = 0; gcount = 0; (*initpt) (x); step_size = 0.1 * gsl_blas_dnrm2 (x); s = gsl_multimin_fdfminimizer_alloc(T, f->n); gsl_multimin_fdfminimizer_set (s, f, x, step_size, 0.1); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); #endif do { iter++; status = gsl_multimin_fdfminimizer_iterate(s); #ifdef DEBUG printf("%i: \n",iter); printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); printf("f(x) %g\n",s->f); printf("dx %g\n",gsl_blas_dnrm2(s->dx)); printf("\n"); #endif status = gsl_multimin_test_gradient(s->gradient,1e-3); } while (iter < 5000 && status == GSL_CONTINUE); status |= (fabs(s->f) > 1e-5); gsl_test(status, "%s, on %s: %i iters (fn+g=%d+%d), f(x)=%g", gsl_multimin_fdfminimizer_name(s),desc, iter, fcount, gcount, s->f); gsl_multimin_fdfminimizer_free(s); gsl_vector_free(x); return status; } int test_f(const char * desc, gsl_multimin_function *f, initpt_function initpt, const gsl_multimin_fminimizer_type *T) { int status; size_t i, iter = 0; gsl_vector *x = gsl_vector_alloc (f->n); gsl_vector *step_size = gsl_vector_alloc (f->n); gsl_multimin_fminimizer *s; fcount = 0; gcount = 0; (*initpt) (x); for (i = 0; i < f->n; i++) gsl_vector_set (step_size, i, 1); s = gsl_multimin_fminimizer_alloc(T, f->n); gsl_multimin_fminimizer_set (s, f, x, step_size); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); #endif do { iter++; status = gsl_multimin_fminimizer_iterate(s); #ifdef DEBUG printf("%i: \n",iter); printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("f(x) %g\n", gsl_multimin_fminimizer_minimum (s)); printf("size: %g\n", gsl_multimin_fminimizer_size (s)); printf("\n"); #endif status = gsl_multimin_test_size (gsl_multimin_fminimizer_size (s), 1e-3); } while (iter < 5000 && status == GSL_CONTINUE); status |= (fabs(s->fval) > 1e-5); gsl_test(status, "%s, on %s: %d iter (fn=%d), f(x)=%g", gsl_multimin_fminimizer_name(s),desc, iter, fcount, s->fval); gsl_multimin_fminimizer_free(s); gsl_vector_free(x); gsl_vector_free(step_size); return status; }
{ "alphanum_fraction": 0.6543402778, "avg_line_length": 26.5437788018, "ext": "c", "hexsha": "74827fa959ac2071905fdfdde326e8a8c80a2330", "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/multimin/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/multimin/test.c", "max_line_length": 81, "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/multimin/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": 1821, "size": 5760 }
/** * * @file qwrapper_slansy.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 Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @generated s Tue Jan 7 11:44:57 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_slansy(Quark *quark, Quark_Task_Flags *task_flags, int norm, PLASMA_enum uplo, int N, const float *A, int LDA, int szeA, int szeW, float *result) { szeW = max(1, szeW); DAG_CORE_LANSY; QUARK_Insert_Task(quark, CORE_slansy_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, 0); } /***************************************************************************//** * **/ void QUARK_CORE_slansy_f1(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum norm, PLASMA_enum uplo, int N, const float *A, int LDA, int szeA, int szeW, float *result, float *fake, int szeF) { szeW = max(1, szeW); DAG_CORE_LANSY; if ( result == fake ) { QUARK_Insert_Task(quark, CORE_slansy_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float)*szeF, result, OUTPUT | GATHERV, 0); } else { QUARK_Insert_Task(quark, CORE_slansy_f1_quark, task_flags, sizeof(PLASMA_enum), &norm, VALUE, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(int), &N, VALUE, sizeof(float)*szeA, A, INPUT, sizeof(int), &LDA, VALUE, sizeof(float)*szeW, NULL, SCRATCH, sizeof(float), result, OUTPUT, sizeof(float)*szeF, fake, OUTPUT | GATHERV, 0); } } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slansy_quark = PCORE_slansy_quark #define CORE_slansy_quark PCORE_slansy_quark #endif void CORE_slansy_quark(Quark *quark) { float *normA; int norm; PLASMA_enum uplo; int N; float *A; int LDA; float *work; quark_unpack_args_7(quark, norm, uplo, N, A, LDA, work, normA); *normA = LAPACKE_slansy_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), N, A, LDA, work); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_slansy_f1_quark = PCORE_slansy_f1_quark #define CORE_slansy_f1_quark PCORE_slansy_f1_quark #endif void CORE_slansy_f1_quark(Quark *quark) { float *normA; int norm; PLASMA_enum uplo; int N; float *A; int LDA; float *work; float *fake; quark_unpack_args_8(quark, norm, uplo, N, A, LDA, work, normA, fake); *normA = LAPACKE_slansy_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), N, A, LDA, work); }
{ "alphanum_fraction": 0.4789244186, "avg_line_length": 32.7619047619, "ext": "c", "hexsha": "d99fe0eda1d9ed6ce48748b58aa1876c3032526b", "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_slansy.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_slansy.c", "max_line_length": 80, "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_slansy.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1075, "size": 4128 }
/* ----------------------------------------------------------------- ** Top contributors: ** Shiqi Wang and Suman Jana ** This file is part of the ReluVal project. ** Copyright (c) 2018-2019 by the authors listed in the file LICENSE ** and their institutional affiliations. ** All rights reserved. ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <cblas.h> #ifndef MATRIX_H #define MATRIX_H /* Define the structure of Matrix */ struct Matrix { float* data; int row, col; }; /* add the constant to matrix */ void add_constant(struct Matrix* A, float alpha); /*matrix multiplication with factors */ void matmul_with_factor(struct Matrix* A,\ struct Matrix* B,\ struct Matrix* C,\ float alpha,\ float beta); /* matrix multiplication */ void matmul(struct Matrix* A,\ struct Matrix* B,\ struct Matrix* C); /* matrix multiplication with bias */ void matmul_with_bias(struct Matrix* A,\ struct Matrix* B,\ struct Matrix* C); /* element-wise multiplication */ void multiply(struct Matrix* A, struct Matrix* B); /* print matrix */ void printMatrix(struct Matrix* A); /* print matrix to the file */ void fprintMatrix(FILE *fp, struct Matrix* A); /* takes the relu of the matrix */ void relu(struct Matrix* A); #endif
{ "alphanum_fraction": 0.5635286373, "avg_line_length": 22.0144927536, "ext": "h", "hexsha": "521da55b033be28de34fe0b81f9c40c14a11fac9", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2022-01-04T07:34:23.000Z", "max_forks_repo_forks_event_min_datetime": "2018-08-20T09:26:21.000Z", "max_forks_repo_head_hexsha": "03f7e2139547a568c20ce27a3dd36b3261463ca4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ahmed-irfan/HorizontalCAS", "max_forks_repo_path": "ReluVal/matrix.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "03f7e2139547a568c20ce27a3dd36b3261463ca4", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:44:12.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-16T20:38:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ahmed-irfan/HorizontalCAS", "max_issues_repo_path": "ReluVal/matrix.h", "max_line_length": 69, "max_stars_count": 47, "max_stars_repo_head_hexsha": "a0dea06f3e8875007d422082603dbdc1e881b572", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cherrywoods/HorizontalCAS", "max_stars_repo_path": "ReluVal/matrix.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T14:19:55.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-01T02:07:51.000Z", "num_tokens": 295, "size": 1519 }
#pragma once #define NOMINMAX #ifndef _WIN32 #include <wsl/winadapter.h> #include "directml_guids.h" #endif #include <unordered_map> #include <vector> #include <iostream> #include <filesystem> #include <variant> #include <fstream> #include <deque> #include <optional> #include <set> #include <string_view> #include <wrl/client.h> #include <wil/result.h> #include <gsl/gsl> #include <DirectML.h> #include "DirectMLX.h" #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #include <fmt/format.h> #include <half.hpp> template<class... Ts> struct overload : Ts... { using Ts::operator()...; }; template<class... Ts> overload(Ts...) -> overload<Ts...>;
{ "alphanum_fraction": 0.7174887892, "avg_line_length": 21.5806451613, "ext": "h", "hexsha": "b1424734a67c7a8dd78ec5339e3ff9ac893b8136", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z", "max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "miaobin/DirectML", "max_forks_repo_path": "DxDispatch/src/model/pch.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "miaobin/DirectML", "max_issues_repo_path": "DxDispatch/src/model/pch.h", "max_line_length": 75, "max_stars_count": 61, "max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "miaobin/DirectML", "max_stars_repo_path": "DxDispatch/src/model/pch.h", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z", "num_tokens": 167, "size": 669 }
#ifndef CPP_MICROBENCH_BENCH_OUTPUT_H #define CPP_MICROBENCH_BENCH_OUTPUT_H #include <string> #include <chrono> #include <fstream> #include <iomanip> #include <fmt/os.h> #include <fmt/ostream.h> #include <fmt/chrono.h> #include <gsl/util> #include "util/aligned_vector.hpp" #include "util/alloc_array.hpp" #include "util/trivial_aligned_array.hpp" #include "util/plain_array.hpp" template <typename array_type> auto generate_array(std::size_t max) { using namespace std::chrono; auto t1 = high_resolution_clock::now(); array_type v(max); auto t2 = high_resolution_clock::now(); for (std::size_t i = 0; i < max; ++i) { v[i] = 1.0F / gsl::narrow_cast<float>(i+1); } auto t3 = high_resolution_clock::now(); fmt::print("Create: {}\n", duration_cast<microseconds>(t2-t1)); fmt::print("Fill: {}\n", duration_cast<microseconds>(t3-t2)); return v; } template <typename vector_type> auto generate_vector(std::size_t max) { using namespace std::chrono; auto t1 = high_resolution_clock::now(); vector_type v; v.reserve(max); auto t2 = high_resolution_clock::now(); for (std::size_t i = 0; i < max; ++i) { v.push_back(1.0F / gsl::narrow_cast<float>(i+1)); } auto t3 = high_resolution_clock::now(); fmt::print("Create: {}\n", duration_cast<microseconds>(t2-t1)); fmt::print("Fill: {}\n", duration_cast<microseconds>(t3-t2)); return v; } void fmt_output_vector(const auto & v) { auto file_name = std::string(static_cast<const char *>(__func__)) + ".txt"; auto file = fmt::output_file(file_name); file.print("{}\n", v.size()); for (const auto & x : v) { file.print("{:.18f}\n", x); } } void stream_output_vector(const auto & v) { auto file_name = std::string(static_cast<const char *>(__func__)) + ".txt"; std::ofstream file{file_name}; file << v.size() << '\n'; for (const auto & x : v) { file << std::setprecision(18) << x << '\n'; } } template <typename array_type> auto bench_fmt_output_array(std::size_t n) { using namespace std::chrono; auto t1 = high_resolution_clock::now(); auto v = generate_array<array_type>(n); auto t2 = high_resolution_clock::now(); fmt_output_vector(v); auto t3 = high_resolution_clock::now(); return std::tuple {__func__, t2 - t1, t3 - t2}; } template <typename vector_type> auto bench_fmt_output_vector(std::size_t n) { using namespace std::chrono; auto t1 = high_resolution_clock::now(); auto v = generate_vector<vector_type>(n); auto t2 = high_resolution_clock::now(); fmt_output_vector(v); auto t3 = high_resolution_clock::now(); return std::tuple {__func__, t2 - t1, t3 - t2}; } template <typename vector_type> auto bench_stream_vector(std::size_t n) { using namespace std::chrono; auto t1 = high_resolution_clock::now(); auto v = generate_vector<vector_type>(n); auto t2 = high_resolution_clock::now(); stream_output_vector(v); auto t3 = high_resolution_clock::now(); return std::tuple {__func__, t2 - t1, t3 - t2}; } void print_bench(auto t) { using namespace std::chrono; auto d1 = duration_cast<microseconds>(std::get<1>(t)); auto d2 = duration_cast<microseconds>(std::get<2>(t)); fmt::print("\nVersion: {}\n", std::get<0>(t)); fmt::print("Generation {} us\n", d1.count()); fmt::print("Writing {} us\n", d2.count()); } #endif//CPP_MICROBENCH_BENCH_OUTPUT_H
{ "alphanum_fraction": 0.6817500749, "avg_line_length": 27.5785123967, "ext": "h", "hexsha": "f8c1734452602881814a119e8b20bc9494329201", "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": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jdgarciauc3m/cpp-microbench", "max_forks_repo_path": "gen-floats/bench_output.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "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": "jdgarciauc3m/cpp-microbench", "max_issues_repo_path": "gen-floats/bench_output.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "c764d5fe5d376324e9c0074e88f79c288fc4afc8", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jdgarciauc3m/cpp-microbench", "max_stars_repo_path": "gen-floats/bench_output.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 965, "size": 3337 }
#ifndef PCA_H #define PCA_H #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_eigen.h> typedef struct { float** matrix; int l; int c; } pca_matrix; pca_matrix empirical_mean(pca_matrix X); pca_matrix mean_deviations(pca_matrix X, pca_matrix U); pca_matrix matrix_multiplication(pca_matrix A, pca_matrix B); pca_matrix transposed_matrix(pca_matrix A); pca_matrix covariance_matrix(pca_matrix B); void eigenvectors_and_eigenvalues(pca_matrix C, gsl_vector *eval, gsl_matrix *evec); void pca_matrix_free(pca_matrix M); #endif /* PCA_H */
{ "alphanum_fraction": 0.7631578947, "avg_line_length": 18.4242424242, "ext": "h", "hexsha": "0cf0961a9537072d17658cf8299d81f4ce013ba6", "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": "8b3b799851a4612c06d1324b1dda8aebf41475a5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gh-duarteljd/faceBIT", "max_forks_repo_path": "VISION/pca/pca.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8b3b799851a4612c06d1324b1dda8aebf41475a5", "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": "gh-duarteljd/faceBIT", "max_issues_repo_path": "VISION/pca/pca.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "8b3b799851a4612c06d1324b1dda8aebf41475a5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gh-duarteljd/faceBIT", "max_stars_repo_path": "VISION/pca/pca.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 164, "size": 608 }
/** * * @file qwrapper_dtrtri.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 Julien Langou * @author Henricus Bouwmeester * @author Mathieu Faverge * @date 2010-11-15 * @generated d Tue Jan 7 11:44:56 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_dtrtri(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum uplo, PLASMA_enum diag, int n, int nb, double *A, int lda, PLASMA_sequence *sequence, PLASMA_request *request, int iinfo) { QUARK_Insert_Task( quark, CORE_dtrtri_quark, task_flags, sizeof(PLASMA_enum), &uplo, VALUE, sizeof(PLASMA_enum), &diag, VALUE, sizeof(int), &n, VALUE, sizeof(double)*nb*nb, A, INOUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_sequence*), &sequence, VALUE, sizeof(PLASMA_request*), &request, VALUE, sizeof(int), &iinfo, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dtrtri_quark = PCORE_dtrtri_quark #define CORE_dtrtri_quark PCORE_dtrtri_quark #endif void CORE_dtrtri_quark(Quark *quark) { PLASMA_enum uplo; PLASMA_enum diag; int N; double *A; int LDA; PLASMA_sequence *sequence; PLASMA_request *request; int iinfo; int info; quark_unpack_args_8(quark, uplo, diag, N, A, LDA, sequence, request, iinfo); info = LAPACKE_dtrtri_work( LAPACK_COL_MAJOR, lapack_const(uplo), lapack_const(diag), N, A, LDA); if ((sequence->status == PLASMA_SUCCESS) && (info > 0)) plasma_sequence_flush(quark, sequence, request, iinfo + info); }
{ "alphanum_fraction": 0.5302474794, "avg_line_length": 30.7323943662, "ext": "c", "hexsha": "6f3f5ddb1d6eb7535850a2c2bf9386159039c656", "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_dtrtri.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_dtrtri.c", "max_line_length": 80, "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_dtrtri.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 573, "size": 2182 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_blas.h> #define m(i,j) m[i*l+j] double* calcMys(char m[],int n,int l) { int i,j,k,k1,k2,k3,k4; char reslist[]={ 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}; int resnum=sizeof(reslist)/sizeof(char); double *simi; simi=malloc(n*n*sizeof(double)); for (i=0;i<n;i++) { simi[i*n+i]=0.0; for (j=i+1;j<n;j++) { double allcount=0,same=0; for (k=0;k<l;k++) { if (m(i,k)!='-' || m(j,k)!='-') { allcount++; if (m(i,k)==m(j,k)) same++; } } simi[i*n+j]=same/allcount; simi[j*n+i]=simi[i*n+j]; } } int *edge,edgenow=0; edge=malloc(5*n*2*sizeof(int)); for (i=0;i<5*n*2;i++) { edge[i]=-1; } for (i=0;i<n;i++) { int has=0,now=0,maxn[5],max5=-1; while (has<5) { if (now!=i) { maxn[has]=now; has++; } now++; } for(j=0;j<5;j++) if (max5==-1||simi[i*n+maxn[max5]]>simi[i*n+maxn[j]]) max5=j; for (j=now;j<n;j++) { if (simi[i*n+j]>simi[i*n+maxn[max5]]) { maxn[max5]=j; max5=-1; for(k=0;k<5;k++) if (max5==-1||simi[i*n+maxn[max5]]>simi[i*n+maxn[k]]) max5=k; } } for (j=0;j<5;j++) { edge[edgenow*2+0]=i; edge[edgenow*2+1]=maxn[j]; edgenow++; } } free(simi); double *mys; int n1=0,n2=0; mys=malloc(l*l*sizeof(double)); for (i=0;i<l*l;i++) mys[i]=0.0; for (i=0;i<l;i++) { for (j=i+1;j<l;j++) { double *prop,*pro1,*pro2,allnumber=0,add=0; prop=malloc(20*20*20*20*sizeof(double)); pro1=malloc(20*20*sizeof(double)); pro2=malloc(20*20*sizeof(double)); int count1=0,count2=0,count3=0,count4=0; for (k=0;k<160000;k++) prop[k]=0.0; for (k=0;k<400;k++) { pro1[k]=0; pro2[k]=0; } for (k=0;k<5*n;k++) { n1=edge[k*2]; n2=edge[k*2+1]; if (m(n1,i)!='-' && m(n1,j)!='-' && m(n2,i)!='-' && m(n2,j)!='-') { count1=0; count2=0; count3=0; count4=0; for (k1 = 0; k1 < 20; k1++) { if (reslist[k1]==m(n1,i)) { count1=k1; break; } } for (k1 = 0; k1 < 20; k1++) { if (reslist[k1]==m(n2,i)) { count2=k1; break; } } for (k1 = 0; k1 < 20; k1++) { if (reslist[k1]==m(n1,j)) { count3=k1; break; } } for (k1 = 0; k1 < 20; k1++) { if (reslist[k1]==m(n2,j)) { count4=k1; break; } } prop[(count1*20+count3)*400+(count2*20+count4)]+=1; prop[(count2*20+count4)*400+(count1*20+count3)]+=1; allnumber+=2; } } gsl_matrix_view m = gsl_matrix_view_array (prop, 400, 400); gsl_vector *eval = gsl_vector_alloc (400); gsl_matrix *evec = gsl_matrix_alloc (400, 400); gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (400); gsl_eigen_symmv (&m.matrix, eval, evec, w); gsl_eigen_symmv_free (w); gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_ASC); gsl_matrix *mid = gsl_matrix_alloc (400, 400); gsl_matrix *right = gsl_matrix_alloc (400, 400); for (k1 = 0; k1 < 400; k1++) { double ser=gsl_vector_get(eval,k1); for (k2=0;k2<400;k2++) { gsl_matrix_set(mid,k1,k2,0); gsl_matrix_set(right,k1,k2,gsl_matrix_get(evec,k2,k1)); } gsl_matrix_set(mid,k1,k1,ser/(ser+1)); } gsl_matrix *temp= gsl_matrix_alloc (400, 400); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,1.0, evec, mid, 0.0, temp); gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,1.0, temp, right, 0.0, evec); gsl_matrix_free(mid); gsl_matrix_free(right); gsl_vector_free (eval); for (k1=0;k1<400;k1++) for(k2=0;k2<400;k2++) { prop[k1*400+k2]=gsl_matrix_get(evec,k1,k2); if (prop[k1*400+k2]<0) prop[k1*400+k2]=-prop[k1*400+k2]; } gsl_matrix_free (evec); gsl_matrix_free (temp); for (k1=0;k1<20;k1++) for(k2=0;k2<20;k2++) for(k3=0;k3<20;k3++) for(k4=0;k4<20;k4++) { pro1[k1*20+k2]+=prop[(k1*20+k3)*400+(k2*20+k4)]; pro2[k3*20+k4]+=prop[(k1*20+k3)*400+(k2*20+k4)]; } if (allnumber!=0) { for (k=0;k<160000;k++) prop[k]=prop[k]/allnumber; for (k=0;k<400;k++) { pro1[k]=pro1[k]/allnumber; pro2[k]=pro2[k]/allnumber; } } allnumber=0.0; for (k1=0;k1<20;k1++) for (k2=0;k2<20;k2++) { if (pro1[k1*20+k2]==0) { continue; } else { for (k3=0;k3<20;k3++) for (k4=0;k4<20;k4++) { if (pro2[k3*20+k4]==0||prop[(k1*20+k3)*400+(k2*20+k4)]==0) { continue; } else { allnumber+=prop[(k1*20+k3)*400+(k2*20+k4)]*log(prop[(k1*20+k3)*400+(k2*20+k4)]/pro1[k1*20+k2]/pro2[k3*20+k4]); } } } } mys[i*l+j]=allnumber; mys[j*l+i]=allnumber; free(prop); free(pro1); free(pro2); } } free(edge); return mys; }
{ "alphanum_fraction": 0.4297380061, "avg_line_length": 25.0127659574, "ext": "c", "hexsha": "fe0b1a67bf08c3f37fb79571e8455b56793abd17", "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": "af78cfdb47577199585179c3b04cc6cf3d6b401c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wzmao/mbio", "max_forks_repo_path": ".old/correlation_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "af78cfdb47577199585179c3b04cc6cf3d6b401c", "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": "wzmao/mbio", "max_issues_repo_path": ".old/correlation_gsl.c", "max_line_length": 146, "max_stars_count": 2, "max_stars_repo_head_hexsha": "af78cfdb47577199585179c3b04cc6cf3d6b401c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wzmao/mbio", "max_stars_repo_path": ".old/correlation_gsl.c", "max_stars_repo_stars_event_max_datetime": "2018-05-25T14:01:17.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-28T12:23:02.000Z", "num_tokens": 2032, "size": 5878 }
#ifndef OPENMC_VOLUME_CALC_H #define OPENMC_VOLUME_CALC_H #include "openmc/position.h" #include "openmc/tallies/trigger.h" #include "pugixml.hpp" #include "xtensor/xtensor.hpp" #include <array> #include <string> #include <vector> #include <gsl/gsl> namespace openmc { //============================================================================== // Volume calculation class //============================================================================== class VolumeCalculation { public: // Aliases, types struct Result { std::array<double, 2> volume; //!< Mean/standard deviation of volume std::vector<int> nuclides; //!< Index of nuclides std::vector<double> atoms; //!< Number of atoms for each nuclide std::vector<double> uncertainty; //!< Uncertainty on number of atoms int iterations; //!< Number of iterations needed to obtain the results }; // Results for a single domain // Constructors VolumeCalculation(pugi::xml_node node); // Methods //! \brief Stochastically determine the volume of a set of domains along with the //! average number densities of nuclides within the domain // //! \return Vector of results for each user-specified domain std::vector<Result> execute() const; //! \brief Write volume calculation results to HDF5 file // //! \param[in] filename Path to HDF5 file to write //! \param[in] results Vector of results for each domain void to_hdf5(const std::string& filename, const std::vector<Result>& results) const; // Tally filter and map types enum class TallyDomain { UNIVERSE, MATERIAL, CELL }; // Data members TallyDomain domain_type_; //!< Type of domain (cell, material, etc.) size_t n_samples_; //!< Number of samples to use double threshold_ {-1.0}; //!< Error threshold for domain volumes TriggerMetric trigger_type_ {TriggerMetric::not_active}; //!< Trigger metric for the volume calculation Position lower_left_; //!< Lower-left position of bounding box Position upper_right_; //!< Upper-right position of bounding box std::vector<int> domain_ids_; //!< IDs of domains to find volumes of private: //! \brief Check whether a material has already been hit for a given domain. //! If not, add new entries to the vectors // //! \param[in] i_material Index in global materials vector //! \param[in,out] indices Vector of material indices //! \param[in,out] hits Number of hits corresponding to each material void check_hit(int i_material, std::vector<int>& indices, std::vector<int>& hits) const; }; //============================================================================== // Global variables //============================================================================== namespace model { extern std::vector<VolumeCalculation> volume_calcs; } //============================================================================== // Non-member functions //============================================================================== void free_memory_volume(); } // namespace openmc #endif // OPENMC_VOLUME_CALC_H
{ "alphanum_fraction": 0.6031078019, "avg_line_length": 32.5157894737, "ext": "h", "hexsha": "3258be9d6b583ed2d0fbe7f264002426da978551", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z", "max_forks_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mehmeturkmen/openmc", "max_forks_repo_path": "include/openmc/volume_calc.h", "max_issues_count": 9, "max_issues_repo_head_hexsha": "ffe0f0283a81d32759e4f877909bbb64d5ad0d3d", "max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z", "max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mehmeturkmen/openmc", "max_issues_repo_path": "include/openmc/volume_calc.h", "max_line_length": 105, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Hit-Weixg/openmc", "max_stars_repo_path": "include/openmc/volume_calc.h", "max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z", "num_tokens": 644, "size": 3089 }
#include "quantum_gates.h" #include "quac_p.h" #include <stdlib.h> #include <stdio.h> #include <petsc.h> #include <stdarg.h> int _num_quantum_gates = 0; int _current_gate = 0; struct quantum_gate_struct _quantum_gate_list[MAX_GATES]; int _min_gate_enum = 5; // Minimum gate enumeration number int _gate_array_initialized = 0; int _num_circuits = 0; int _current_circuit = 0; circuit _circuit_list[MAX_GATES]; void (*_get_val_j_functions_gates[MAX_GATES])(PetscInt,struct quantum_gate_struct,PetscInt*,PetscInt[],PetscScalar[],PetscInt); /* EventFunction is one step in Petsc to apply some action at a specific time. * This function checks to see if an event has happened. */ PetscErrorCode _QG_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) { /* Check if the time has passed a gate */ if (_current_gate<_num_quantum_gates) { /* We signal that we passed the time by returning a negative number */ fvalue[0] = _quantum_gate_list[_current_gate].time - t; } else { fvalue[0] = t; } return(0); } /* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function * to apply that event. */ PetscErrorCode _QG_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[],PetscReal t, Vec U,PetscBool forward,void* ctx) { /* We only have one event at the moment, so we do not need to branch. * If we had more than one event, we would put some logic here. */ if (nevents) { /* Apply the current gate */ //Deprecated? /* _apply_gate(_quantum_gate_list[_current_gate].my_gate_type,_quantum_gate_list[_current_gate].qubit_numbers,U); */ /* Increment our gate counter */ _current_gate = _current_gate + 1; } TSSetSolution(ts,U); return(0); } /* EventFunction is one step in Petsc to apply some action at a specific time. * This function checks to see if an event has happened. */ PetscErrorCode _QC_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) { /* Check if the time has passed a gate */ PetscInt current_gate,num_gates; PetscLogEventBegin(_qc_event_function_event,0,0,0,0); if (_current_circuit<_num_circuits) { current_gate = _circuit_list[_current_circuit].current_gate; num_gates = _circuit_list[_current_circuit].num_gates; if (current_gate<num_gates) { /* We signal that we passed the time by returning a negative number */ fvalue[0] = _circuit_list[_current_circuit].gate_list[current_gate].time +_circuit_list[_current_circuit].start_time - t; } else { if (nid==0){ printf("ERROR! current_gate should never be larger than num_gates in _QC_EventFunction\n"); exit(0); } } } else { fvalue[0] = t; } PetscLogEventEnd(_qc_event_function_event,0,0,0,0); return(0); } /* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function * to apply that event. */ PetscErrorCode _QC_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[], PetscReal t,Vec U,PetscBool forward,void* ctx) { PetscInt current_gate,num_gates; PetscReal gate_time; /* We only have one event at the moment, so we do not need to branch. * If we had more than one event, we would put some logic here. */ PetscLogEventBegin(_qc_postevent_function_event,0,0,0,0); if (nevents) { num_gates = _circuit_list[_current_circuit].num_gates; current_gate = _circuit_list[_current_circuit].current_gate; gate_time = _circuit_list[_current_circuit].gate_list[current_gate].time; /* Apply all gates at a given time incrementally */ while (current_gate<num_gates && _circuit_list[_current_circuit].gate_list[current_gate].time == gate_time){ /* apply the current gate */ printf("current_gate %d num_gates %d\n",current_gate,num_gates); _apply_gate(_circuit_list[_current_circuit].gate_list[current_gate],U); /* Increment our gate counter */ _circuit_list[_current_circuit].current_gate = _circuit_list[_current_circuit].current_gate + 1; current_gate = _circuit_list[_current_circuit].current_gate; } if(_circuit_list[_current_circuit].current_gate>=_circuit_list[_current_circuit].num_gates){ /* We've exhausted this circuit; move on to the next. */ _current_circuit = _current_circuit + 1; } } TSSetSolution(ts,U); PetscLogEventEnd(_qc_postevent_function_event,0,0,0,0); return(0); } /* Add a gate to the list */ void add_gate(PetscReal time,gate_type my_gate_type,...) { int num_qubits=0,qubit,i; va_list ap; if (my_gate_type==HADAMARD) { num_qubits = 1; } else if (my_gate_type==CNOT){ num_qubits = 2; } else { if (nid==0){ printf("ERROR! Gate type not recognized!\n"); exit(0); } } // Store arguments in list _quantum_gate_list[_num_quantum_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); _quantum_gate_list[_num_quantum_gates].time = time; _quantum_gate_list[_num_quantum_gates].my_gate_type = my_gate_type; _quantum_gate_list[_num_quantum_gates]._get_val_j_from_global_i = HADAMARD_get_val_j_from_global_i; // Loop through and store qubits for (i=0;i<num_qubits;i++){ qubit = va_arg(ap,int); _quantum_gate_list[_num_quantum_gates].qubit_numbers[i] = qubit; } _num_quantum_gates = _num_quantum_gates + 1; } /* Apply a specific gate */ void _apply_gate(struct quantum_gate_struct this_gate,Vec rho){ PetscScalar op_vals[total_levels*2]; Mat gate_mat; //FIXME Consider having only one static Mat for all gates, rather than creating new ones every time Vec tmp_answer; PetscInt dim,i,Istart,Iend,num_js,these_js[total_levels*2]; // FIXME: maybe total_levels*2 is too much or not enough? Consider having a better bound. PetscLogEventBegin(_apply_gate_event,0,0,0,0); if (_lindblad_terms){ dim = total_levels*total_levels; } else { dim = total_levels; } VecDuplicate(rho,&tmp_answer); //Create a new vec with the same size as rho MatCreate(PETSC_COMM_WORLD,&gate_mat); MatSetSizes(gate_mat,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(gate_mat); MatMPIAIJSetPreallocation(gate_mat,4,NULL,4,NULL); //This matrix is incredibly sparse! MatSetUp(gate_mat); /* Construct the gate matrix, on the fly */ MatGetOwnershipRange(gate_mat,&Istart,&Iend); for (i=Istart;i<Iend;i++){ if (_lindblad_terms){ // Get the corresponding j and val for the superoperator U* cross U this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,0); } else { // Get the corresponding j and val for just the matrix U this_gate._get_val_j_from_global_i(i,this_gate,&num_js,these_js,op_vals,-1); } MatSetValues(gate_mat,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(gate_mat,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(gate_mat,MAT_FINAL_ASSEMBLY); /* MatView(gate_mat,PETSC_VIEWER_STDOUT_SELF); */ MatMult(gate_mat,rho,tmp_answer); VecCopy(tmp_answer,rho); //Copy our tmp_answer array into rho VecDestroy(&tmp_answer); //Destroy the temp answer MatDestroy(&gate_mat); PetscLogEventEnd(_apply_gate_event,0,0,0,0); } /*z * _construct_gate_mat constructs the matrix needed for the quantum * computing gates. * * Inputs: * gate_type my_gate_type type of quantum gate * int *s * Outputs: * Mat gate_mat: the expanded, superoperator matrix for that gate */ void _construct_gate_mat(gate_type my_gate_type,int *systems,Mat gate_mat){ PetscInt i,j,i_mat,j_mat,k1,k2,k3,k4,n_before1,n_before2,my_levels,n_after; PetscInt i1,j1,i2=0,j2=0,comb_levels,control=-1,moved_system; PetscReal val1,val2; PetscScalar add_to_mat; if (my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ /* Figure out which system is first in our basis * 0 and 1 is hardcoded because CNOT gates have only 2 qubits */ n_before1 = subsystem_list[systems[0]]->n_before; n_before2 = subsystem_list[systems[1]]->n_before; control = 0; moved_system = systems[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ n_after = total_levels/(4*n_before1); /* Check which is the control and which is the target */ if (n_before2<n_before1) { n_after = total_levels/(4*n_before2); control = 1; moved_system = systems[0]; n_before1 = n_before2; } /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; for (k1=0;k1<n_after;k1++){ for (k2=0;k2<n_before1;k2++){ for (i=0;i<4;i++){ //4 is hardcoded because there are only 4 entries val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); /* Get I_b cross CNOT cross I_a in the temporary basis */ i1 = i1*n_after + k1 + k2*my_levels*n_after; j1 = j1*n_after + k1 + k2*my_levels*n_after; /* Permute to computational basis * To aid in the computation, we generated the matrix in the 'temporary basis', * where we exchanged the subsystem immediately after the first qubit with * the second qubit of interest. I.e., doing a CNOT(q3,q7) * Computational basis: q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 * Temporary basis: q1 q2 q3 q7 q5 q6 q4 q8 q9 q10 * This allows us to calculate CNOT easily - we just need to change * the basis back to the computational one. * * Since the control variable tells us which qubit was the first, * we switched the system immediately before that one with the * stored variable moved_system */ _change_basis_ij_pair(&i1,&j1,systems[control]+1,moved_system); for (k3=0;k3<n_after;k3++){ for (k4=0;k4<n_before1;k4++){ for (j=0;j<4;j++){ //4 is hardcoded because there are only 4 entries val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); /* Get I_b cross CNOT cross I_a in the temporary basis */ i2 = i2*n_after + k3 + k4*my_levels*n_after; j2 = j2*n_after + k3 + k4*my_levels*n_after; /* Permute to computational basis */ _change_basis_ij_pair(&i2,&j2,systems[control]+1,moved_system); add_to_mat = val1*val2; /* Do the normal kron product expansion */ i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; MatSetValue(gate_mat,i_mat,j_mat,add_to_mat,ADD_VALUES); } } } } } } } else if (my_gate_type == HADAMARD) { /* * The Hadamard gate is a one qubit gate defined as: * * H = 1/sqrt(2) 1 1 * 1 -1 * * Find the necessary Hilbert space dimensions for constructing the * full space matrix. */ n_before1 = subsystem_list[systems[0]]->n_before; my_levels = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit n_after = total_levels/(my_levels*n_before1); comb_levels = my_levels*my_levels*n_before1*n_after; for (k4=0;k4<n_before1*n_after;k4++){ for (i=0;i<4;i++){ // 4 hardcoded because there are 4 values in the hadamard val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); for (j=0;j<4;j++){ val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); i2 = i2 + k4*my_levels; j2 = j2 + k4*my_levels; /* * We need my_levels*n_before*n_after because we are taking * H cross (Ia cross Ib cross H), so the the size of the second operator * is my_levels*n_before*n_after */ add_to_mat = val1*val2; i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels); } } } } else if (my_gate_type == SIGMAX || my_gate_type == SIGMAY || my_gate_type == SIGMAZ || my_gate_type == SWAP) { /* * The pauli matrices are two qubit gates, sigmax, sigmay, sigmaz * The SWAP gate swaps two qubits. */ n_before1 = subsystem_list[systems[0]]->n_before; my_levels = subsystem_list[systems[0]]->my_levels; //Should be 2, because qubit n_after = total_levels/(my_levels*n_before1); comb_levels = my_levels*my_levels*n_before1*n_after; for (k4=0;k4<n_before1*n_after;k4++){ for (i=0;i<2;i++){// 2 hardcoded because there are 4 values in the hadamard val1 = _get_val_in_subspace_gate(i,my_gate_type,control,&i1,&j1); for (j=0;j<2;j++){ val2 = _get_val_in_subspace_gate(j,my_gate_type,control,&i2,&j2); i2 = i2 + k4*my_levels; j2 = j2 + k4*my_levels; /* * We need my_levels*n_before*n_after because we are taking * H cross (Ia cross Ib cross H), so the the size of the second operator * is my_levels*n_before*n_after */ add_to_mat = val1*val2; i_mat = my_levels*n_before1*n_after*i1 + i2; j_mat = my_levels*n_before1*n_after*j1 + j2; _add_to_PETSc_kron_ij(gate_mat,add_to_mat,i_mat,j_mat,n_before1,n_after,comb_levels); } } } } return; } void _change_basis_ij_pair(PetscInt *i_op,PetscInt *j_op,PetscInt system1,PetscInt system2){ PetscInt na1,na2,lev1,lev2; /* * To apply our change of basis we use the neat trick that the row number * in a given basis can be calculated similar to how a binary number is * calculated (but generalized in that some bits can have more than two * states. e.g. with three qubits * i(| 0 1 0 >) = 0*4 + 1*2 + 0*1 = 2 * where i() is the index, in this ordering, of the ket. * Another example, with 1 2level, 1 3levels, and 1 4 level system: * i(| 0 1 0 >) = 0*12 + 1*4 + 0*1 = 4 * that is, * i(| a b c >) = a*n_af^a + b*n_af^b + c*n_af^c * where n_af^a is the Hilbert space before system a, etc. * * Given a specific i, and only switching two systems, * we can calculate i's partner in the switched basis * by subtracting off the part from the current basis and * adding in the part from the desired basis. This leaves everything * else the same, but switches the two systems of interest. * * We need to be able to go from i to a specific subsystem's state. * This is accomplished with the formula: * (i/n_a % l) * Take our example above: * three qubits: 2 -> 2/4 % 2 = 0$2 = 0 * 2 -> 2/2 % 2 = 1%2 = 1 * 2 -> 2/1 % 2 = 2%2 = 0 * Or, the other example: 4 -> 4/12 % 2 = 0 * 4 -> 4/4 % 3 = 1 * 4 -> 4/1 % 4 = 0 * Note that this depends on integer division - 4/12 = 0 * * Using this, we can precisely calculate a system's part of the sum, * subtract that off, and then add the new basis. * * For example, let's switch our qubits from before around: * i(| 1 0 0 >) = 1*4 + 0*2 + 0*1 = 4 * Now, switch back to the original basis. Note we swapped q3 and q2 * first, subtract off the contributions from q3 and q2 * i_new = 4 - 1*4 - 0*2 = 0 * Now, add on the contributions in the original basis * i_new = 0 + 0*4 + 1*2 = 2 * Algorithmically, * i_new = i - (i/na1)%lev1 * na1 - (i/na2)%lev2 * na2 * + (i/na2)%lev1 * na1 + (i/na1)%lev2 * na2 * Note that we use our formula above to calculate the qubits * state in this basis, given this specific i. */ lev1 = subsystem_list[system1]->my_levels; na1 = total_levels/(lev1*subsystem_list[system1]->n_before); lev2 = subsystem_list[system2]->my_levels; na2 = total_levels/(lev2*subsystem_list[system2]->n_before); // Changed from lev1->lev2 *i_op = *i_op - ((*i_op/na1)%lev1)*na1 - ((*i_op/na2)%lev2)*na2 + ((*i_op/na1)%lev2)*na2 + ((*i_op/na2)%lev1)*na1; *j_op = *j_op - ((*j_op/na1)%lev1)*na1 - ((*j_op/na2)%lev2)*na2 + ((*j_op/na1)%lev2)*na2 + ((*j_op/na2)%lev1)*na1; return; } /* * _get_val_in_subspace_gate is a simple function that returns the * i_op,j_op pair and val for a given index; * Inputs: * int i: current index * gate_type my_gate_type the gate type * Outputs: * int *i_op: row value in subspace * int *j_op: column value in subspace * Return value: * PetscScalar val: value at i_op,j_op */ PetscScalar _get_val_in_subspace_gate(PetscInt i,gate_type my_gate_type,PetscInt control,PetscInt *i_op,PetscInt *j_op){ PetscScalar val=0.0; if (my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ if (control==0) { if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 1; val = 1.0; } else if (i==2) { *i_op = 2; *j_op = 3; val = 1.0; } else if (i==3) { *i_op = 3; *j_op = 2; val = 1.0; } } else if (control==1) { if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 3; val = 1.0; } else if (i==2) { *i_op = 2; *j_op = 2; val = 1.0; } else if (i==3) { *i_op = 3; *j_op = 1; val = 1.0; } } } else if (my_gate_type == HADAMARD) { /* * The Hadamard gate is a one qubit gate defined as: * * H = 1/sqrt(2) 1 1 * 1 -1 * * Find the necessary Hilbert space dimensions for constructing the * full space matrix. */ if (i==0){ *i_op = 0; *j_op = 0; val = 1.0/sqrt(2); } else if (i==1) { *i_op = 0; *j_op = 1; val = 1.0/sqrt(2); } else if (i==2) { *i_op = 1; *j_op = 0; val = 1.0/sqrt(2); } else if (i==3) { *i_op = 1; *j_op = 1; val = -1.0/sqrt(2); } } else if (my_gate_type == SIGMAX){ /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ if (i==0){ *i_op = 0; *j_op = 1; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 0; val = 1.0; } else if (i==2){ *i_op = 1; *j_op = 1; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 0; val = 0.0; } } else if (my_gate_type == SIGMAX){ /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ if (i==0){ *i_op = 0; *j_op = 1; val = -PETSC_i; } else if (i==1) { *i_op = 1; *j_op = 0; val = PETSC_i; } else if (i==2){ *i_op = 1; *j_op = 1; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 0; val = 0.0; } } else if (my_gate_type == SIGMAZ){ /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ if (i==0){ *i_op = 0; *j_op = 0; val = 1.0; } else if (i==1) { *i_op = 1; *j_op = 1; val = 1.0; }else if (i==2){ *i_op = 1; *j_op = 0; val = 0.0; } else if (i==2) { *i_op = 0; *j_op = 1; val = 0.0; } } return val; } /* * create_circuit initializez the circuit struct. Gates can be added * later. * * Inputs: * circuit circ: circuit to be initialized * PetscIn num_gates_est: an estimate of the number of gates in * the circuit; can be negative, if no * estimate is known. * Outputs: * operator *new_op: lowering op (op), raising op (op->dag), and number op (op->n) */ void create_circuit(circuit *circ,PetscInt num_gates_est){ (*circ).start_time = 0.0; (*circ).num_gates = 0; (*circ).current_gate = 0; /* * If num_gates_est was positive when passed in, use that * as the initial gate_list size, otherwise set to * 100. gate_list will be dynamically resized when needed. */ if (num_gates_est>0) { (*circ).gate_list_size = num_gates_est; } else { // Default gate_list_size (*circ).gate_list_size = 100; } // Allocate gate list (*circ).gate_list = malloc((*circ).gate_list_size * sizeof(struct quantum_gate_struct)); } /* * Add a gate to a circuit. * Inputs: * circuit circ: circuit to add to * PetscReal time: time that gate would be applied, counting from 0 at * the start of the circuit * gate_type my_gate_type: which gate to add * ...: list of qubit gate will act on, other (U for controlled_U?) */ void add_gate_to_circuit(circuit *circ,PetscReal time,gate_type my_gate_type,...){ PetscReal theta,phi,lambda; int num_qubits=0,qubit,i; va_list ap; if (_gate_array_initialized==0){ //Initialize the array of gate function pointers _initialize_gate_function_array(); _gate_array_initialized = 1; } _check_gate_type(my_gate_type,&num_qubits); if ((*circ).num_gates==(*circ).gate_list_size){ if (nid==0){ printf("ERROR! Gate list not large enough!\n"); exit(1); } } // Store arguments in list (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); (*circ).gate_list[(*circ).num_gates].time = time; (*circ).gate_list[(*circ).num_gates].my_gate_type = my_gate_type; (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = _get_val_j_functions_gates[my_gate_type+_min_gate_enum]; if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ) { va_start(ap,num_qubits+1); } else if (my_gate_type==U3){ va_start(ap,num_qubits+3); } else { va_start(ap,num_qubits); } // Loop through and store qubits for (i=0;i<num_qubits;i++){ qubit = va_arg(ap,int); if (qubit>=num_subsystems) { if (nid==0){ // Disable warning because of qasm parser will make the circuit before // the qubits are allocated //printf("Warning! Qubit number greater than total systems\n"); } } (*circ).gate_list[(*circ).num_gates].qubit_numbers[i] = qubit; } if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ||my_gate_type==PHASESHIFT){ //Get the theta parameter from the last argument passed in theta = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].theta = theta; (*circ).gate_list[(*circ).num_gates].phi = 0; (*circ).gate_list[(*circ).num_gates].lambda = 0; } else if (my_gate_type==U3){ theta = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].theta = theta; phi = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].phi = phi; lambda = va_arg(ap,PetscReal); (*circ).gate_list[(*circ).num_gates].lambda = lambda; } else { //Set theta to 0 (*circ).gate_list[(*circ).num_gates].theta = 0; (*circ).gate_list[(*circ).num_gates].phi = 0; (*circ).gate_list[(*circ).num_gates].lambda = 0; } (*circ).num_gates = (*circ).num_gates + 1; return; } /* * Add a circuit to another circuit. * Assumes whole circuit happens at time */ void add_circuit_to_circuit(circuit *circ,circuit circ_to_add,PetscReal time){ int num_qubits=0,i,j; // Check that we can fit the circuit in if (((*circ).num_gates+circ_to_add.num_gates-1)==(*circ).gate_list_size){ if (nid==0){ printf("ERROR! Gate list not large enough to add this circuit!\n"); exit(1); } } for (i=0;i<circ_to_add.num_gates;i++){ // Copy gate information over (*circ).gate_list[(*circ).num_gates].time = time; if (circ_to_add.gate_list[i].my_gate_type<0){ num_qubits = 2; } else { num_qubits = 1; } (*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int)); for (j=0;j<num_qubits;j++){ (*circ).gate_list[(*circ).num_gates].qubit_numbers[j] = circ_to_add.gate_list[i].qubit_numbers[j]; } (*circ).gate_list[(*circ).num_gates].my_gate_type = circ_to_add.gate_list[i].my_gate_type; (*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = circ_to_add.gate_list[i]._get_val_j_from_global_i; (*circ).gate_list[(*circ).num_gates].theta = circ_to_add.gate_list[i].theta; (*circ).num_gates = (*circ).num_gates + 1; } return; } /* register a circuit to be run a specific time during the time stepping */ void start_circuit_at_time(circuit *circ,PetscReal time){ (*circ).start_time = time; _circuit_list[_num_circuits] = *circ; _num_circuits = _num_circuits + 1; } /* * * tensor_control - switch on which superoperator to compute * -1: I cross G or just G (the difference is controlled by the passed in i's, but * the internal logic is exactly the same) * 0: G* cross G * 1: G* cross I */ void _get_val_j_from_global_i_gates(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ operator this_op1,this_op2; PetscInt n_after,i_sub,tmp_int,control,moved_system,my_levels,num_js_i1=0,num_js_i2=0; PetscInt k1,k2,n_before1,n_before2,i_tmp,j_sub,extra_after,i1,i2,j1,js_i1[2],js_i2[2]; PetscScalar vals_i1[2],vals_i2[2],theta,phi,lambda; //2 is hardcoded because 2 is the largest number of js from 1 i (HADAMARD) /* * We store our gates as a type and affected systems; * we use the stored information to calculate the global j(s) location * and nonzero value(s) for a give global i * * Fo all 2-qubit gates, we use the fact that * diagonal elements are diagonal, even in global space * and that off-diagonal elements can be worked out from the * following: * Off diagonal elements: * if (i_sub==1) * i = 1 * n_af + k1 + k2*n_me*n_af * j = 0 * n_af + k1 + k2*n_me*n_af * if (i_sub==0) * i = 0 * n_af + k1 + k2*n_l*n_af * j = 1 * n_af + k1 + k2*n_l*n_af * We work out k1 and k2 from i to get j. * */ if (tensor_control!= 0) { if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } if (gate.my_gate_type > 0) { // Single qubit gates are coded as positive numbers //Get the system this is affecting this_op1 = subsystem_list[gate.qubit_numbers[0]]; if (this_op1->my_levels!=2) { //Check that it is a two level system if (nid==0){ printf("ERROR! Single qubit gates can only affect 2-level systems\n"); exit(0); } } n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after; i_sub = i/n_after%this_op1->my_levels; //Use integer arithmetic to get floor function //Branch on the gate types if (gate.my_gate_type == HADAMARD){ /* * HADAMARD gate * * 1/sqrt(2) | 1 1 | * | 1 -1 | * Hadamard gates have two values per row, * with both diagonal anad off diagonal elements * */ *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = pow(2,-0.5); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = pow(2,-0.5); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -pow(2,-0.5); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = pow(2,-0.5); } else { if (nid==0){ printf("ERROR! Hadamard gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAX){ /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAY){ /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = -1.0*PETSC_i; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[0] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[0] = 1.0*PETSC_i; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == SIGMAZ){ /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == EYE){ /* * Identity (EYE) gate * * | 1 0 | * | 0 1 | * */ *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == PHASESHIFT){ /* * PHASESHIFT gate * * | 1 0 | * | 0 e^(-i*theta) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta); } else { if (nid==0){ printf("ERROR! phaseshift gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == T){ /* * T gate * * | 1 0 | * | 0 e^(i*pi/4) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! t gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == TDAG){ /* * TDAG gate * * | 1 0 | * | 0 e^(-i*pi/4) | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! tdag gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == S){ /* * S gate * * | 1 0 | * | 0 i | * */ *num_js = 1; theta = gate.theta; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! t gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == RX){ /* * RX gate * * | cos(theta/2) i*sin(theta/2) | * | i*sin(theta/2) cos(theta/2) | * */ theta = gate.theta; *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else if (gate.my_gate_type == U3) { /* * u3 gate * * u3(theta,phi,lambda) = | cos(theta/2) -e^(i lambda) * sin(theta/2) | * | e^(i phi) sin(theta/2) e^(i (lambda+phi)) cos(theta/2) | * the u3 gate is a general one qubit transformation. * the u2 gate is u3(pi/2,phi,lambda) * the u1 gate is u3(0,0,lambda) * The u3 gate has two elements per row, * with both diagonal anad off diagonal elements * */ theta = gate.theta; phi = gate.phi; lambda = gate.lambda; *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(this_op1->my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(this_op1->my_levels*n_after); js[1] = 0 * n_after + k1 + k2*this_op1->my_levels*n_after; vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! u3 gate is only defined for qubits\n"); exit(0); } } } else { if (nid==0){ printf("ERROR! Gate type not understood! %d\n", gate.my_gate_type); exit(0); } } } else { //Two qubit gates this_op1 = subsystem_list[gate.qubit_numbers[0]]; this_op2 = subsystem_list[gate.qubit_numbers[1]]; if (this_op1->my_levels * this_op2->my_levels != 4) { //Check that it is a two level system if (nid==0){ printf("ERROR! Two qubit gates can only affect two 2-level systems (global_i)\n"); exit(0); } } n_before1 = this_op1->n_before; n_before2 = this_op2->n_before; control = 0; moved_system = gate.qubit_numbers[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ n_after = total_levels/(4*n_before1)*extra_after; /* * Check which is the control and which is the target, * flip if need be. */ if (n_before2<n_before1) { n_after = total_levels/(4*n_before2); control = 1; moved_system = gate.qubit_numbers[0]; n_before1 = n_before2; } /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; /* * Permute to temporary basis * Get the i_sub in the permuted basis */ i_tmp = i; _change_basis_ij_pair(&i_tmp,&j1,gate.qubit_numbers[control]+1,moved_system); // j1 useless here i_sub = i_tmp/n_after%my_levels; //Use integer arithmetic to get floor function if (gate.my_gate_type == CNOT) { /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CNOT gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CXZ) { /* The controlled-XZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * sig_z * 0 0 0 -1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit if (control==0){ // Diagonal vals[0] = 1.0; js[0] = i; } else { // Off diagonal vals[0] = -1.0; tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ if (control==0){ vals[0] = -1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal vals[0] = 1.0; js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CXZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CZX) { /* The controlled-ZX gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * sig_x * 0 0 0 1 * 0 0 -1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = -1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CZX gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CZ) { /* The controlled-Z gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * 0 0 1 0 * 0 0 0 -1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * * Controlled-z is the same for both possible controls */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==2){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==3){ vals[0] = -1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == CmZ) { /* The controlled-mZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 -sig_z * 0 0 -1 0 * 0 0 0 1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal js[0] = i; if (control==0) { vals[0] = 1.0; } else { vals[0] = -1.0; } } else if (i_sub==2){ // Diagonal js[0] = i; if (control==0) { vals[0] = -1.0; } else { vals[0] = 1.0; } } else if (i_sub==3){ vals[0] = 1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CmZ gate is only defined for 2 qubits!\n"); exit(0); } } } else if (gate.my_gate_type == SWAP) { /* The swap gate swaps two qubits. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 0 1 0 = 0 sig_z * sig_x * 0 1 0 0 * 0 0 0 1 */ *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==2){ vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==3){ vals[0] = 1.0; // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! SWAP gate is only defined for 2 qubits!\n"); exit(0); } } } else { if (nid==0){ printf("ERROR!Two Qubit gate type not understood! %d\n",gate.my_gate_type); exit(0); } } } if (tensor_control==1){ //Take complex conjugate of answer to get U* cross I for (i=0;i<*num_js;i++){ vals[i] = PetscConjComplex(vals[i]); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ _get_val_j_from_global_i_gates(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ _get_val_j_from_global_i_gates(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void combine_circuit_to_mat2(Mat *matrix_out,circuit circ){ PetscScalar op_val,op_vals[total_levels],vals[2]={0}; PetscInt Istart,Iend; PetscInt i,j,k,l,this_i,these_js[total_levels],js[2]={0},num_js_tmp=0,num_js,num_js_current; // Should this inherit its stucture from full_A? MatCreate(PETSC_COMM_WORLD,matrix_out); MatSetType(*matrix_out,MATMPIAIJ); MatSetSizes(*matrix_out,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(*matrix_out); MatMPIAIJSetPreallocation(*matrix_out,16,NULL,16,NULL); /* * Calculate G1*G2*G3*.. using the following observation: * Each gate is very sparse - having no more than * 2 values per row. This allows us to efficiently do the * multiplication by just touching the nonzero values */ MatGetOwnershipRange(*matrix_out,&Istart,&Iend); for (i=Istart;i<Iend;i++){ this_i = i; // The leading index which we check // Reset the result for the row num_js = 1; these_js[0] = i; op_vals[0] = 1.0; for (j=0;j<circ.num_gates;j++){ num_js_current = num_js; for (k=0;k<num_js_current;k++){ // Loop through all of the js from the previous gate multiplications this_i = these_js[k]; op_val = op_vals[k]; _get_val_j_from_global_i_gates(this_i,circ.gate_list[j],&num_js_tmp,js,vals,-1); // Get the corresponding j and val /* * Assume there is always at least 1 nonzero per row. This is a good assumption * because all basic quantum gates have at least 1 nonzero per row */ // WARNING! CODE NOT FINISHED // WILL NOT WORK FOR HADAMARD * HADAMARD these_js[k] = js[0]; op_vals[k] = op_val*vals[0]; for (l=1;l<num_js_tmp;l++){ //If we have more than 1 num_js_tmp, we append to the end of the list these_js[num_js+l-1] = js[l]; op_vals[num_js+l-1] = op_val*vals[l]; } num_js = num_js + num_js_tmp - 1; //If we spawned an extra j, add it here } } MatSetValues(*matrix_out,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(*matrix_out,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(*matrix_out,MAT_FINAL_ASSEMBLY); return; } void combine_circuit_to_mat(Mat *matrix_out,circuit circ){ PetscScalar op_vals[2]; PetscInt Istart,Iend,i_mat; PetscInt i,these_js[2],num_js; Mat tmp_mat1,tmp_mat2,tmp_mat3; // Should this inherit its stucture from full_A? MatCreate(PETSC_COMM_WORLD,&tmp_mat1); MatSetType(tmp_mat1,MATMPIAIJ); MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(tmp_mat1); MatMPIAIJSetPreallocation(tmp_mat1,2,NULL,2,NULL); /* Construct the first matrix in tmp_mat1 */ MatGetOwnershipRange(tmp_mat1,&Istart,&Iend); for (i=Istart;i<Iend;i++){ circ.gate_list[0]._get_val_j_from_global_i(i,circ.gate_list[0],&num_js,these_js,op_vals,-1); // Get the corresponding j and val MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY); for (i_mat=1;i_mat<circ.num_gates;i_mat++){ // Create the next matrix MatCreate(PETSC_COMM_WORLD,&tmp_mat2); MatSetType(tmp_mat2,MATMPIAIJ); MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,total_levels,total_levels); MatSetFromOptions(tmp_mat2); MatMPIAIJSetPreallocation(tmp_mat2,2,NULL,2,NULL); /* Construct new matrix */ MatGetOwnershipRange(tmp_mat2,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,-1); // Get the corresponding j and val MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY); // Now do matrix matrix multiply MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3); MatDestroy(&tmp_mat1); MatDestroy(&tmp_mat2); //Do I need to destroy it? //Store tmp_mat3 into tmp_mat1 MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1); MatDestroy(&tmp_mat3); } //Copy tmp_mat1 into *matrix_out MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);; MatDestroy(&tmp_mat1); return; } void combine_circuit_to_super_mat(Mat *matrix_out,circuit circ){ PetscScalar op_vals[4]; PetscInt Istart,Iend,i_mat,dim; PetscInt i,these_js[4],num_js; Mat tmp_mat1,tmp_mat2,tmp_mat3; // Should this inherit its stucture from full_A? dim = total_levels*total_levels; MatCreate(PETSC_COMM_WORLD,&tmp_mat1); MatSetType(tmp_mat1,MATMPIAIJ); MatSetSizes(tmp_mat1,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(tmp_mat1); MatMPIAIJSetPreallocation(tmp_mat1,8,NULL,8,NULL); /* Construct the first matrix in tmp_mat1 */ MatGetOwnershipRange(tmp_mat1,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[0],&num_js,these_js,op_vals,0); // Get the corresponding j and val MatSetValues(tmp_mat1,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat1,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat1,MAT_FINAL_ASSEMBLY); for (i_mat=1;i_mat<circ.num_gates;i_mat++){ // Create the next matrix MatCreate(PETSC_COMM_WORLD,&tmp_mat2); MatSetType(tmp_mat2,MATMPIAIJ); MatSetSizes(tmp_mat2,PETSC_DECIDE,PETSC_DECIDE,dim,dim); MatSetFromOptions(tmp_mat2); MatMPIAIJSetPreallocation(tmp_mat2,8,NULL,8,NULL); /* Construct new matrix */ MatGetOwnershipRange(tmp_mat2,&Istart,&Iend); for (i=Istart;i<Iend;i++){ _get_val_j_from_global_i_gates(i,circ.gate_list[i_mat],&num_js,these_js,op_vals,0); // Get the corresponding j and val MatSetValues(tmp_mat2,1,&i,num_js,these_js,op_vals,ADD_VALUES); } MatAssemblyBegin(tmp_mat2,MAT_FINAL_ASSEMBLY); MatAssemblyEnd(tmp_mat2,MAT_FINAL_ASSEMBLY); // Now do matrix matrix multiply MatMatMult(tmp_mat2,tmp_mat1,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&tmp_mat3); MatDestroy(&tmp_mat1); MatDestroy(&tmp_mat2); //Do I need to destroy it? //Store tmp_mat3 into tmp_mat1 MatConvert(tmp_mat3,MATSAME,MAT_INITIAL_MATRIX,&tmp_mat1); MatDestroy(&tmp_mat3); } //Copy tmp_mat1 into *matrix_out MatConvert(tmp_mat1,MATSAME,MAT_INITIAL_MATRIX,matrix_out);; MatDestroy(&tmp_mat1); return; } /* * No issue for js_i* = -1 because every row is guaranteed to have a 0 * in all the gates implemented below. * See commit: 9956c78171fdac1fa0ef9e2f0a39cbffd4d755dc where this was an issue * in _get_val_j_from_global_i for raising / lowering / number operators, where * -1 was used to say there was no nonzero in that row. */ void CNOT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled NOT gate has two inputs, a target and a control. * the target output is equal to the target input if the control is * |0> and is flipped if the control input is |1> (Marinescu 146) * As a matrix, for a two qubit system: * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * 0 0 0 1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CNOT gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CNOT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CNOT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CXZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-XZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_x * sig_z * 0 0 0 -1 * 0 0 1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit if (control==0){ // Diagonal vals[0] = 1.0; js[0] = i; } else { // Off diagonal vals[0] = -1.0; tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ if (control==0){ vals[0] = -1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal vals[0] = 1.0; js[0] = i; } } else if (i_sub==3){ vals[0] = 1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CXZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CXZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CXZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,moved_system; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-Z gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * 0 0 1 0 * 0 0 0 -1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * * Controlled-z is the same for both possible controls */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==2){ // Diagonal vals[0] = 1.0; js[0] = i; } else if (i_sub==3){ vals[0] = -1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CmZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,moved_system; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-mZ gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 -sig_z * 0 0 -1 0 * 0 0 0 1 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace * */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Diagonal js[0] = i; if (control==0) { vals[0] = 1.0; } else { vals[0] = -1.0; } } else if (i_sub==2){ // Diagonal js[0] = i; if (control==0) { vals[0] = -1.0; } else { vals[0] = 1.0; } } else if (i_sub==3){ vals[0] = 1.0; js[0] = i; } else { if (nid==0){ printf("ERROR! CmZ gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CmZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CmZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void CZX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The controlled-ZX gate has two inputs, a target and a control. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 1 0 0 = 0 sig_z * sig_x * 0 0 0 1 * 0 0 -1 0 * Of course, when there are other qubits, tensor products and such * must be applied to get the full basis representation. * * Note that this is a temporary gate; i.e., we will create a more * general controlled-U gate at a later time that will replace this. */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); *num_js = 1; if (i_sub==0){ // Same, regardless of control // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; if (control==0){ // Diagonal js[0] = i; } else { // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } } else if (i_sub==2){ vals[0] = 1.0; if (control==0){ // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 3; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else { // Diagonal js[0] = i; } } else if (i_sub==3){ vals[0] = -1.0; if (control==0){ // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } else { // Off diagonal element tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; } /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1);//i_tmp useless here js[0] = j1; } else { if (nid==0){ printf("ERROR! CZX gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ CZX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ CZX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SWAP_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1=0,num_js_i2=0,js_i1[2],js_i2[2]; PetscInt control,i_tmp,my_levels,j_sub,moved_system,j1; PetscScalar vals_i1[2],vals_i2[2]; /* The swap gate swaps two qubits. * As a matrix, for a two qubit system * 1 0 0 0 I2 0 * 0 0 1 0 = 0 sig_z * sig_x * 0 1 0 0 * 0 0 0 1 */ if (tensor_control!= 0) { /* 4 is hardcoded because 2 qubits with 2 levels each */ my_levels = 4; // Get the correct hilbert space information i_tmp = i; _get_n_after_2qbit(&i_tmp,gate.qubit_numbers,tensor_control,&n_after,&control,&moved_system,&i_sub); printf("\n tensor_control %d,control %d,i_sub %d n_after %d\n", tensor_control, control, i_sub, n_after ); *num_js = 1; if (i_sub==0){ // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else if (i_sub==1){ // Check which is the control bit vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 2; j1 = (j_sub) * n_after + k1 + k2*my_levels*n_after; // 3 = j_sub // Permute back to computational basis _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==2){ vals[0] = 1.0; // Off diagonal tmp_int = i_tmp - i_sub * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); j_sub = 1; j1 = j_sub * n_after + k1 + k2*my_levels*n_after; /* Permute back to computational basis */ _change_basis_ij_pair(&i_tmp,&j1,moved_system,gate.qubit_numbers[control]+1); // i_tmp useless here js[0] = j1; } else if (i_sub==3){ // Diagonal vals[0] = 1.0; /* * We shouldn't need to deal with any permutation here; * i_sub is in the permuted basis, but we know that a * diagonal element is diagonal in all bases, so * we just use the computational basis value. p */ js[0] = i; } else { if (nid==0){ printf("ERROR! SWAP gate is only defined for 2 qubits!\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SWAP_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SWAP_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void HADAMARD_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * HADAMARD gate * * 1/sqrt(2) | 1 1 | * | 1 -1 | * Hadamard gates have two values per row, * with both diagonal anad off diagonal elements * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = pow(2,-0.5); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = pow(2,-0.5); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -pow(2,-0.5); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = pow(2,-0.5); } else { if (nid==0){ printf("ERROR! Hadamard gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ HADAMARD_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ HADAMARD_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void U3_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta,lambda,phi; /* * u3 gate * * u3(theta,phi,lambda) = | cos(theta/2) -e^(i lambda) * sin(theta/2) | * | e^(i phi) sin(theta/2) e^(i (lambda+phi)) cos(theta/2) | * the u3 gate is a general one qubit transformation. * the u2 gate is u3(pi/2,phi,lambda) * the u1 gate is u3(0,0,lambda) * The u3 gate has two elements per row, * with both diagonal anad off diagonal elements * */ theta = gate.theta; phi = gate.phi; lambda = gate.lambda; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = -PetscExpComplex(PETSC_i*lambda)*PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*(lambda+phi))*PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = PetscExpComplex(PETSC_i*phi)*PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! u3 gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ U3_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ U3_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void EYE_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2]; PetscScalar vals_i1[2],vals_i2[2]; /* * Identity (EYE) gate * * | 1 0 | * | 0 1 | * */ if (tensor_control!= 0) { _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; js[0] = i; vals[0] = 1.0; } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ EYE_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ EYE_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void PHASESHIFT_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * PHASESHIFT gate * * | 1 0 | * | 0 e^(-i*theta) | * */ theta=gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta); } else { if (nid==0){ printf("ERROR! phaseshift gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ PHASESHIFT_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ PHASESHIFT_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAZ gate * * | 1 0 | * | 0 -1 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1.0; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = -1.0; } else { if (nid==0){ printf("ERROR! sigmaz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RZ_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RZ gate * * | exp(i*theta/2) 0 | * | 0 -exp(i*theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RZ_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RZ_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RY gate * * | cos(theta/2) sin(theta/2) | * | -sin(theta/2) cos(theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2.0); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = -PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void RX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * RX gate * * | cos(theta/2) i*sin(theta/2) | * | i*sin(theta/2) cos(theta/2) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 2; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscCosReal(theta/2); // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[1] = 0 * n_after + k1 + k2*my_levels*n_after; vals[1] = PETSC_i * PetscSinReal(theta/2); } else { if (nid==0){ printf("ERROR! rz gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ RX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ RX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAY_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAY gate * * | 0 -1.j | * | 1.j 0 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[0] = -1.0*PETSC_i; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = 0 * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0*PETSC_i; } else { if (nid==0){ printf("ERROR! sigmay gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAY_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAY_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void SIGMAX_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,tmp_int,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; /* * SIGMAX gate * * | 0 1 | * | 1 0 | * */ if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Off diagonal element tmp_int = i - 0 * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = (0 + 1) * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0; } else if (i_sub==1){ // Off diagonal element tmp_int = i - (0+1) * n_after; k2 = tmp_int/(my_levels*n_after);//Use integer arithmetic to get floor function k1 = tmp_int%(my_levels*n_after); js[0] = 0 * n_after + k1 + k2*my_levels*n_after; vals[0] = 1.0; } else { if (nid==0){ printf("ERROR! sigmax gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ SIGMAX_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ SIGMAX_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void T_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * T gate * * | 1 0 | * | 0 exp(i*pi/4) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! T gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ T_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ T_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void TDAG_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * TDAG gate * * | 1 0 | * | 0 exp(i*pi/4) | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PetscExpComplex(-PETSC_i*PETSC_PI/4); } else { if (nid==0){ printf("ERROR! T gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ TDAG_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ TDAG_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void S_get_val_j_from_global_i(PetscInt i,struct quantum_gate_struct gate,PetscInt *num_js, PetscInt js[],PetscScalar vals[],PetscInt tensor_control){ PetscInt n_after,i_sub,k1,k2,i1,i2,num_js_i1,num_js_i2,js_i1[2],js_i2[2],my_levels; PetscScalar vals_i1[2],vals_i2[2]; PetscReal theta; /* * S gate * * | 1 0 | * | 0 i | * */ theta = gate.theta; if (tensor_control!= 0) { my_levels = 2; //Hardcoded becase single qubit gate _get_n_after_1qbit(i,gate.qubit_numbers[0],tensor_control,&n_after,&i_sub); *num_js = 1; if (i_sub==0) { // Diagonal element js[0] = i; vals[0] = 1; } else if (i_sub==1){ // Diagonal element js[0] = i; vals[0] = PETSC_i; } else { if (nid==0){ printf("ERROR! S gate is only defined for qubits\n"); exit(0); } } } else { /* * U* cross U * To calculate this, we first take our i_global, convert * it to i1 (for U*) and i2 (for U) within their own * part of the Hilbert space. pWe then treat i1 and i2 as * global i's for the matrices U* and U themselves, which * gives us j's for those matrices. We then expand the j's * to get the full space representation, using the normal * tensor product. */ /* Calculate i1, i2 */ i1 = i/total_levels; i2 = i%total_levels; /* Now, get js for U* (i1) by calling this function */ S_get_val_j_from_global_i(i1,gate,&num_js_i1,js_i1,vals_i1,-1); /* Now, get js for U (i2) by calling this function */ S_get_val_j_from_global_i(i2,gate,&num_js_i2,js_i2,vals_i2,-1); /* * Combine j's to get U* cross U * Must do all possible permutations */ *num_js = 0; for(k1=0;k1<num_js_i1;k1++){ for(k2=0;k2<num_js_i2;k2++){ js[*num_js] = total_levels * js_i1[k1] + js_i2[k2]; //Need to take complex conjugate to get true U* vals[*num_js] = PetscConjComplex(vals_i1[k1])*vals_i2[k2]; *num_js = *num_js + 1; } } } return; } void _get_n_after_2qbit(PetscInt *i,int qubit_numbers[],PetscInt tensor_control,PetscInt *n_after, PetscInt *control, PetscInt *moved_system, PetscInt *i_sub){ operator this_op1,this_op2; PetscInt n_before1,n_before2,extra_after,my_levels=4,j1; //4 is hardcoded because 2 qbits if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } //Two qubit gates this_op1 = subsystem_list[qubit_numbers[0]]; this_op2 = subsystem_list[qubit_numbers[1]]; if (this_op1->my_levels * this_op2->my_levels != 4) { //Check that it is a two level system if (nid==0){ printf("ERROR! Two qubit gates can only affect two 2-level systems (global_i)\n"); exit(0); } } n_before1 = this_op1->n_before; n_before2 = this_op2->n_before; *control = 0; *moved_system = qubit_numbers[1]; /* 2 is hardcoded because CNOT gates are for qubits, which have 2 levels */ /* 4 is hardcoded because 2 qubits with 2 levels each */ *n_after = total_levels/(4*n_before1)*extra_after; /* * Check which is the control and which is the target, * flip if need be. */ if (n_before2<n_before1) { *n_after = total_levels/(4*n_before2); *control = 1; *moved_system = qubit_numbers[0]; n_before1 = n_before2; } /* * Permute to temporary basis * Get the i_sub in the permuted basis */ _change_basis_ij_pair(i,&j1,qubit_numbers[*control]+1,*moved_system); // j1 useless here *i_sub = *i/(*n_after)%my_levels; //Use integer arithmetic to get floor function return; } void _get_n_after_1qbit(PetscInt i,int qubit_number,PetscInt tensor_control,PetscInt *n_after,PetscInt *i_sub){ operator this_op1; PetscInt extra_after; if (tensor_control==1) { extra_after = total_levels; } else { extra_after = 1; } //Get the system this is affecting this_op1 = subsystem_list[qubit_number]; if (this_op1->my_levels!=2) { //Check that it is a two level system if (nid==0){ printf("ERROR! Single qubit gates can only affect 2-level systems\n"); exit(0); } } *n_after = total_levels/(this_op1->my_levels*this_op1->n_before)*extra_after; *i_sub = i/(*n_after)%this_op1->my_levels; //Use integer arithmetic to get floor function return; } // Check that the gate type is valid and set the number of qubits void _check_gate_type(gate_type my_gate_type,int *num_qubits){ if (my_gate_type==HADAMARD||my_gate_type==SIGMAX||my_gate_type==SIGMAY||my_gate_type==SIGMAZ||my_gate_type==EYE|| my_gate_type==RZ||my_gate_type==RX||my_gate_type==RY||my_gate_type==U3||my_gate_type==PHASESHIFT||my_gate_type==T||my_gate_type==TDAG||my_gate_type==S) { *num_qubits = 1; } else if (my_gate_type==CNOT||my_gate_type==CXZ||my_gate_type==CZ||my_gate_type==CmZ||my_gate_type==CZX||my_gate_type==SWAP){ *num_qubits = 2; } else { if (nid==0){ printf("ERROR! Gate type not recognized\n"); exit(0); } } } /* * Put the gate function pointers into an array */ void _initialize_gate_function_array(){ _get_val_j_functions_gates[CZX+_min_gate_enum] = CZX_get_val_j_from_global_i; _get_val_j_functions_gates[CmZ+_min_gate_enum] = CmZ_get_val_j_from_global_i; _get_val_j_functions_gates[CZ+_min_gate_enum] = CZ_get_val_j_from_global_i; _get_val_j_functions_gates[CXZ+_min_gate_enum] = CXZ_get_val_j_from_global_i; _get_val_j_functions_gates[CNOT+_min_gate_enum] = CNOT_get_val_j_from_global_i; _get_val_j_functions_gates[HADAMARD+_min_gate_enum] = HADAMARD_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAX+_min_gate_enum] = SIGMAX_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAY+_min_gate_enum] = SIGMAY_get_val_j_from_global_i; _get_val_j_functions_gates[SIGMAZ+_min_gate_enum] = SIGMAZ_get_val_j_from_global_i; _get_val_j_functions_gates[EYE+_min_gate_enum] = EYE_get_val_j_from_global_i; _get_val_j_functions_gates[RX+_min_gate_enum] = RX_get_val_j_from_global_i; _get_val_j_functions_gates[RY+_min_gate_enum] = RY_get_val_j_from_global_i; _get_val_j_functions_gates[RZ+_min_gate_enum] = RZ_get_val_j_from_global_i; _get_val_j_functions_gates[U3+_min_gate_enum] = U3_get_val_j_from_global_i; _get_val_j_functions_gates[SWAP+_min_gate_enum] = SWAP_get_val_j_from_global_i; _get_val_j_functions_gates[PHASESHIFT+_min_gate_enum] = PHASESHIFT_get_val_j_from_global_i; _get_val_j_functions_gates[T+_min_gate_enum] = T_get_val_j_from_global_i; _get_val_j_functions_gates[TDAG+_min_gate_enum] = TDAG_get_val_j_from_global_i; _get_val_j_functions_gates[S+_min_gate_enum] = S_get_val_j_from_global_i; }
{ "alphanum_fraction": 0.5716961563, "avg_line_length": 34.0442687747, "ext": "c", "hexsha": "1ca90ac558e934ff29655862b9329f4eee53ce25", "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": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sriharikrishna/QuaC", "max_forks_repo_path": "src/quantum_gates.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "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": "sriharikrishna/QuaC", "max_issues_repo_path": "src/quantum_gates.c", "max_line_length": 159, "max_stars_count": null, "max_stars_repo_head_hexsha": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sriharikrishna/QuaC", "max_stars_repo_path": "src/quantum_gates.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 38624, "size": 129198 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_matrix.h> #include "globals.h" #include "SimulationSteps.h" //#define WDON int P; int Np; gsl_matrix *LIFT; gsl_matrix *VolMat; gsl_matrix *MassMatrix; int main(int argc, char **argv) { if (argc != 2) { printf("Usage: ./Simulation 'Fort.14'\n"); printf("Fort.14: Mesh for the channel\n"); exit(EXIT_FAILURE); } char *Mesh = argv[1]; //printf("Enter the polynomial approximation order:\n"); //scanf("%d", &P); P = 1; Np = P+1; store_mesh(Mesh); /* for (int i = 0; i < NumEl; i++) { for (int j = 0; j < Np; j++) printf("x = %lf \t z = %lf \t S0 = %3.18lf\n", NodalX[i*Np+j] , Nodalz[i*Np+j], dz[i*Np+j]); } exit(1); */ // Create VolMat, LIFT and MassMatrix calculateLIFTVolMat(P, Np, &LIFT, &VolMat, &MassMatrix); double FinalTime; printf("Enter the time you would like to run the simulation till:\n"); scanf("%lf", &FinalTime); initialize(); /* Impose boundary conditions and couple the channels to the junction */ boundary_conditions(); /* Step through time */ time_evolution(FinalTime); return(0); }
{ "alphanum_fraction": 0.6307961505, "avg_line_length": 16.0985915493, "ext": "c", "hexsha": "efcb8923722a5869ac6e7d51bb97e588bd9aa0b5", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_path": "1DCode/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "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": "evalseth/DG-RAIN", "max_issues_repo_path": "1DCode/main.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_path": "1DCode/main.c", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "num_tokens": 362, "size": 1143 }
/* Ballistic: a software to benchmark ballistic models. AUTHORS: Javier Burguete Tolosa. Copyright 2018, AUTHORS. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file equation.c * \brief Source file with the equation data and functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2018. */ #define _GNU_SOURCE #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_rng.h> #include <libxml/parser.h> #include "config.h" #include "utils.h" #include "equation.h" #define DEBUG_EQUATION 0 ///< macro to debug the equation functions. long double r0[3]; ///< position vector. long double r1[3]; ///< velocity vector. long double r2[3]; ///< acceleration vector. long double ro0[3]; ///< backup of the position vector. long double ro1[3]; ///< backup of the velocity vector. long double ro2[3]; ///< backup of the acceleration vector. void (*equation_acceleration) (Equation * eq, long double *r0, long double *r1, long double *r2, long double t); ///< pointer to the function to calculate the acceleration. void (*equation_solution) (Equation * eq, long double *r0, long double *r1, long double t); ///< pointer to the function to calculate the analytical solution. long double (*equation_step_size) (Equation * eq); ///< pointer to the function to calculate the time step size. int (*equation_land) (Equation * eq, long double, long double *t, long double *dt); ///< pointer to the function to finalize the trajectory. long double kt; ///< stability time step size coefficient. long double dt; ///< time step size. unsigned long int nevaluations; ///< number of evaluations of the acceleration function. /** * Function to calculate the acceleration on non-resitance model. * * This function calculates the acceleration vector on a non-resistance * model. The movement equation is: * \f{equation}\ddot{\vec{r}}=\vec{g}\f} * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector. */ static void equation_acceleration_0 (Equation * eq __attribute__ ((unused)), ///< Equation struct. long double *r0 __attribute__ ((unused)), ///< position vector. long double *r1 __attribute__ ((unused)), ///< velocity vector. long double *r2, ///< acceleration vector. long double t __attribute__ ((unused))) ///< actual time. { #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_0: start\n"); #endif r2[0] = r2[1] = 0.L; r2[2] = -G; ++nevaluations; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_0: ax=%Lg ay=%Lg az=%Lg\n", r2[0], r2[1], r2[2]); fprintf (stderr, "equation_acceleration_0: end\n"); #endif } /** * Function to solve the non-resistance model. * * This function solves the movement on a resistance model characterized by the * movement equation: * \f{equation}{\ddot{\vec{r}}=\vec{g},\f} * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector. * The analytical solution is: * \f{equation}\dot{\vec{r}}=\dot{\vec{r}}_0+\vec{g}\,t,\f} * \f{equation}\vec{r}=\vec{r}_0+\dot{\vec{r}}_0\,t+\frac12\,\vec{g}\,t^2.\f} */ static void equation_solution_0 (Equation * eq, ///< Equation struct. long double *r0, ///< position vector. long double *r1, ///< velocity vector. long double t) ///< time. { #if DEBUG_EQUATION fprintf (stderr, "equation_solution_0: start\n"); #endif r1[0] = eq->v[0]; r1[1] = eq->v[1]; r1[2] = eq->v[2] - eq->g * t; r0[0] = eq->r[0] + eq->v[0] * t; r0[1] = eq->r[1] + eq->v[1] * t; r0[2] = eq->r[2] + t * (eq->v[2] - t * 0.5L * G); #if DEBUG_EQUATION fprintf (stderr, "equation_solution_0: vx=%Lg vy=%Lg vz=%Lg\n", r1[0], r1[1], r1[2]); fprintf (stderr, "equation_solution_0: x=%Lg y=%Lg z=%Lg\n", r0[0], r0[1], r0[2]); fprintf (stderr, "equation_solution_0: end\n"); #endif } /** * Function to calculate the acceleration on the 1st resistance model. * * This function calculates the acceleration vector on a resistance model * model characterized by the movement equation: * \f[\ddot{\vec{r}}=\vec{g}-\lambda\,\left(\dot{\vec{r}}-\vec{w}\right)\f] * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector, * \f$\vec{w}=\left(w_x,\;w_y\;0\right)\f$ the wind velocity vector and * \f$\lambda\f$ a resistance coefficient. */ static void equation_acceleration_1 (Equation * eq, ///< Equation struct. long double *r0 __attribute__ ((unused)), ///< position vector. long double *r1, ///< velocity vector. long double *r2, ///< acceleration vector. long double t __attribute__ ((unused))) ///< actual time. { #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_1: start\n"); #endif r2[0] = -eq->lambda * (r1[0] - eq->w[0]); r2[1] = -eq->lambda * (r1[1] - eq->w[1]); r2[2] = -eq->g - eq->lambda * r1[2]; ++nevaluations; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_1: ax=%Lg ay=%Lg az=%Lg\n", r2[0], r2[1], r2[2]); fprintf (stderr, "equation_acceleration_1: end\n"); #endif } /** * Function to solve the 1st resistance model. * * This function solves the movement on a resistance model characterized by the * movement equation: * \f{equation} * \ddot{\vec{r}}=\vec{g}-\lambda\,\left(\dot{\vec{r}}-\vec{w}\right), * \f} * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector, * \f$\vec{w}=(w_x,\;w_y,\;0)\f$ the wind velocity vector and * \f$\lambda\f$ a resistance coefficient. * The analytical solution is: * \f{equation} * \dot{\vec{r}}=\dot{\vec{r}}_0\,\exp\left(-\lambda\,t\right) * +\left(\vec{w}+\frac{\vec{g}}{\lambda}\right) * \,\left[1-\exp\left(-\lambda\,t\right)\right], * \f} * \f{equation} * \vec{r}=\vec{r}_0+\left(\vec{w}+\frac{\vec{g}}{\lambda}\right)\,t * +\frac{\dot{\vec{r}}_0-\vec{w}-\vec{g}/\lambda}{\lambda} * \,\left[1-\exp\left(-\lambda\,t\right)\right]. * \f} */ static void equation_solution_1 (Equation * eq, ///< Equation struct. long double *r0, ///< position vector. long double *r1, ///< velocity vector. long double t) ///< time. { long double v[2]; long double li, gl, elt, k; #if DEBUG_EQUATION fprintf (stderr, "equation_solution_1: start\n"); #endif v[0] = eq->v[0] - eq->w[0]; v[1] = eq->v[1] - eq->w[1]; elt = expl (-eq->lambda * t); r1[0] = eq->w[0] + v[0] * elt; r1[1] = eq->w[1] + v[1] * elt; li = 1.L / eq->lambda; gl = eq->g * li; r1[2] = (eq->v[2] + gl) * elt - gl; k = li * (1.L - elt); r0[0] = eq->r[0] + eq->w[0] * t + v[0] * k; r0[1] = eq->r[1] + eq->w[1] * t + v[1] * k; r0[2] = eq->r[2] - gl * t + (eq->v[2] + gl) * k; #if DEBUG_EQUATION fprintf (stderr, "equation_solution_1: vx=%Lg vy=%Lg vz=%Lg\n", r1[0], r1[1], r1[2]); fprintf (stderr, "equation_solution_1: x=%Lg y=%Lg z=%Lg\n", r0[0], r0[1], r0[2]); fprintf (stderr, "equation_solution_1: end\n"); #endif } /** * Function to calculate the acceleration on 2nd resistance model. * * This function calculates the acceleration vector on a resistance model * model characterized by the movement equations: * \f[\left.\begin{array}{r} * \ddot{x}=-\lambda\,\left|\dot{x}-w_x\right|\,\left(\dot{x}-w_x\right),\\ * \ddot{y}=-\lambda\,\left|\dot{y}-w_y\right|\,\left(\dot{y}-w_y\right),\\ * \ddot{z}=-g-\lambda\,\left|\dot{z}\right|\,\dot{z}, * \end{array}\right\}\f] * with g the gravitational constant, \f$w_x\f$ and \f$w_y\f$ the wind velocity * vector components and \f$\lambda\f$ a resistance coefficient. */ static void equation_acceleration_2 (Equation * eq, ///< Equation struct. long double *r0 __attribute__ ((unused)), ///< position vector. long double *r1, ///< velocity vector. long double *r2, ///< acceleration vector. long double t __attribute__ ((unused))) ///< actual time. { long double v[2]; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_2: start\n"); #endif v[0] = r1[0] - eq->w[0]; v[1] = r1[1] - eq->w[1]; r2[0] = -eq->lambda * fabsl (v[0]) * v[0]; r2[1] = -eq->lambda * fabsl (v[1]) * v[1]; r2[2] = -eq->g - eq->lambda * fabsl (r1[2]) * r1[2]; ++nevaluations; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_2: ax=%Lg ay=%Lg az=%Lg\n", r2[0], r2[1], r2[2]); fprintf (stderr, "equation_acceleration_2: end\n"); #endif } /** * Function to solve the 2nd resistance mode. * * This function solves the movement on a resistance model characterized by the * movement equations: * \f{equation}\left.\begin{array}{r} * \ddot{x}=-\lambda\,\left|\dot{x}-w_x\right|\,\left(\dot{x}-w_x\right)\\ * \ddot{y}=-\lambda\,\left|\dot{y}-w_y\right|\,\left(\dot{y}-w_y\right)\\ * \ddot{z}=-g-\lambda\,\left|\dot{z}\right|\,\dot{z} * \end{array}\right\}\f} * with g the gravitational constant, \f$w_x\f$ and \f$w_y\f$ the wind velocity * vector components and \f$\lambda\f$ a resistance coefficient. * The analytical solution is: * \f{equation} * \dot{x}=w_x+\frac{\dot{x}_0-w_x}{1+\lambda\,\left|\dot{x}_0-w_x\right|\,t}, * \f} * \f{equation} * \dot{y}=w_y+\frac{\dot{y}_0-w_y}{1+\lambda\,\left|\dot{y}_0-w_y\right|\,t}, * \f} * \f{equation} * \dot{z}=\left\{\begin{array}{cl} * \dot{z}_0\leq 0\Rightarrow & \sqrt{\frac{g}{\lambda}}\, * \frac{\dot{z}_0\,\cosh\left(\sqrt{g\,\lambda}\,t\right) * -\sqrt{g/\lambda}\,\sinh\left(\sqrt{g\,\lambda}\,t\right)} * {\sqrt{g/\lambda}\,\cosh\left(\sqrt{g\,\lambda}\,t\right) * -\dot{z}_0\,\sinh\left(\sqrt{g\,\lambda}\,t\right)},\\ * \dot{z}_0>0,\; * t\leq\frac{\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)} * {\sqrt{g\,\lambda}}\Rightarrow & * \sqrt{\frac{g}{\lambda}} * \,\tan\left[\arctan\left(\dot{z}_0\,\sqrt{\frac{\lambda}{g}}\right) * -\sqrt{g\,\lambda}\,t\right],\\ * \dot{z}_0>0,\; * t>\frac{\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)} * {\sqrt{g\,\lambda}}\Rightarrow & * -\sqrt{\frac{g}{\lambda}}\,\tanh\left[\sqrt{g\,\lambda}\,t * -\arctan\left(\dot{z}_0\,\sqrt{\frac{\lambda}{g}}\right)\right], * \end{array}\right. * \f} * \f{equation} * x=x_0+w_x\,t+\frac{\dot{x}_0-w_x}{\lambda\,\left|\dot{x}_0-w_x\right|} * \,\ln\left(1+\lambda\,\left|\dot{x}_0-w_x\right|\,t\right), * \f} * \f{equation} * y=y_0+w_y\,t+\frac{\dot{y}_0-w_y}{\lambda\,\left|\dot{y}_0-w_y\right|} * \,\ln\left(1+\lambda\,\left|\dot{y}_0-w_y\right|\,t\right), * \f} * \f{equation} * z=\left\{\begin{array}{cl} * \dot{z}_0\leq 0\Rightarrow & z_0 * -\frac{\ln\left[\cosh\left(\sqrt{g\,\lambda}\,t\right) * -\dot{z}_0\,\sqrt{\lambda/g}\, * \sinh\left(\sqrt{g\,\lambda}\,t\right)\right]}{\lambda},\\ * \dot{z}_0>0,\; * t\leq\frac{\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)} * {\sqrt{g\,\lambda}}\Rightarrow & * z_0+\frac{1}{\lambda}\,\ln\left\{\frac{\cos\left[ * \arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)-\sqrt{g\,\lambda}\,t\right]} * {\cos\left[\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)\right]}\right\},\\ * \dot{z}_0>0,\; * t>\frac{\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)} * {\sqrt{g\,\lambda}}\Rightarrow & * z_0-\frac{\ln\left\{ * \cos\left[\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)\right] * \,\cosh\left[\sqrt{g\,\lambda}\,t * -\arctan\left(\dot{z}_0\,\sqrt{\lambda/g}\right)\right]\right\}}{\lambda} * \end{array}\right. * \f} */ static void equation_solution_2 (Equation * eq, ///< Equation struct. long double *r0, ///< position vector. long double *r1, ///< velocity vector. long double t) ///< actual time. { long double v[2], k[2]; long double tc, g_l, gl, glt, lt, li, alpha; #if DEBUG_EQUATION fprintf (stderr, "equation_solution_2: start\n"); #endif v[0] = eq->v[0] - eq->w[0]; v[1] = eq->v[1] - eq->w[1]; lt = eq->lambda * t; k[0] = 1.L + lt * fabsl (v[0]); k[1] = 1.L + lt * fabsl (v[1]); r1[0] = eq->w[0] + v[0] / k[0]; r1[1] = eq->w[1] + v[1] / k[1]; li = 1.L / eq->lambda; k[0] = li * logl (k[0]); k[1] = li * logl (k[1]); r0[0] = eq->r[0] + eq->w[0] * t; r0[1] = eq->r[1] + eq->w[1] * t; if (v[0] >= 0.L) r0[0] += k[0]; else r0[0] -= k[0]; if (v[1] >= 0.L) r0[1] += k[1]; else r0[1] -= k[1]; gl = sqrtl (eq->g * eq->lambda); glt = gl * t; g_l = sqrtl (eq->g / eq->lambda); r0[2] = eq->r[2]; if (eq->v[2] <= 0.L) { k[0] = coshl (glt); k[1] = sinhl (glt); r1[2] = g_l * (eq->v[2] * k[0] - g_l * k[1]) / (g_l * k[0] - eq->v[2] * k[1]); r0[2] -= li * logl (k[0] - eq->v[2] * k[1] / g_l); } else { alpha = atanl (eq->v[2] / g_l); tc = alpha / gl; if (t <= tc) { r1[2] = g_l * tanl (alpha - glt); r0[2] += li * logl (cosl (alpha - glt) / cosl (alpha)); } else { t -= tc; glt = gl * t; r1[2] = -g_l * tanhl (glt); r0[2] -= li * logl (cosl (alpha) * coshl (glt)); } } #if DEBUG_EQUATION fprintf (stderr, "equation_solution_2: vx=%Lg vy=%Lg vz=%Lg\n", r1[0], r1[1], r1[2]); fprintf (stderr, "equation_solution_2: x=%Lg y=%Lg z=%Lg\n", r0[0], r0[1], r0[2]); fprintf (stderr, "equation_solution_2: end\n"); #endif } /** * Function to calculate the acceleration on a forced model. * * This function calculates the acceleration vector on a forced model. The * movement equation is: * \f{equation} * \ddot{\vec{r}}=\vec{g}+\vec{w}\,\exp\left(-\lambda\,t\right) * \f} * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector, \f$\lambda\f$ the * force decay factor and \f$\vec{w}=\left(w_x,\;w_y\;0\right)\f$ the force * vector. */ static void equation_acceleration_3 (Equation * eq, ///< Equation struct. long double *r0 __attribute__ ((unused)), ///< position vector. long double *r1 __attribute__ ((unused)), ///< velocity vector. long double *r2, ///< acceleration vector. long double t) ///< actual time. { long double elt; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_3: start\n"); #endif elt = expl (-eq->lambda * t); r2[0] = eq->w[0] * elt; r2[1] = eq->w[1] * elt; r2[2] = -G; ++nevaluations; #if DEBUG_EQUATION fprintf (stderr, "equation_acceleration_3: ax=%Lg ay=%Lg az=%Lg\n", r2[0], r2[1], r2[2]); fprintf (stderr, "equation_acceleration_3: end\n"); #endif } /** * Function to solve the forced model. * * This function solves the movement on a forced model characterized by the * movement equation: * \f{equation} * \ddot{\vec{r}}=\vec{g}+\vec{w}\,\exp\left(-\lambda\,t\right) * \f} * with \f$\vec{g}=(0,\;0,\;-g)\f$ the gravity field vector, \f$\lambda\f$ the * force decay factor and \f$\vec{w}=\left(w_x,\;w_y\;0\right)\f$ the force * vector. * The analytical solution is: * \f{equation} * \dot{\vec{r}}=\dot{\vec{r}}_0+\vec{g}\,t * +\frac{\vec{w}}{\lambda}\left[1-\exp\left(-\lambda\,t\right)\right],\f} * \f{equation}\vec{r}=\vec{r}_0 * +\left(\dot{\vec{r}}_0+\frac{\vec{w}}{\lambda}\right)\,t * +\frac12\,\vec{g}\,t^2 * +\frac{\vec{w}}{\lambda^2}\,\left[1-\exp\left(-\lambda\,t\right)\right]. * \f} */ static void equation_solution_3 (Equation * eq, ///< Equation struct. long double *r0, ///< position vector. long double *r1, ///< velocity vector. long double t) ///< time. { long double li, k; #if DEBUG_EQUATION fprintf (stderr, "equation_solution_3: start\n"); #endif li = 1.L / eq->lambda; k = li * (1.L - expl (-eq->lambda * t)); r1[0] = eq->v[0] + eq->w[0] * k; r1[1] = eq->v[1] + eq->w[1] * k; r1[2] = eq->v[2] - eq->g * t; k *= li; r0[0] = eq->r[0] + (eq->v[0] + eq->w[0] * li) * t - eq->w[0] * k; r0[1] = eq->r[1] + (eq->v[1] + eq->w[1] * li) * t - eq->w[1] * k; r0[2] = eq->r[2] + t * (eq->v[2] - t * 0.5L * G); #if DEBUG_EQUATION fprintf (stderr, "equation_solution_3: vx=%Lg vy=%Lg vz=%Lg\n", r1[0], r1[1], r1[2]); fprintf (stderr, "equation_solution_3: x=%Lg y=%Lg z=%Lg\n", r0[0], r0[1], r0[2]); fprintf (stderr, "equation_solution_3: end\n"); #endif } /** * Function to solve numerically the equation by the mean point method. * * \return solution time. */ long double equation_solve (Equation * eq, ///< Equation struct. long double *r0, ///< position vector solution. long double *r1) ///< velocity vector solution. { long double r02[3], r12[3]; long double t1, t2, t3; unsigned int i; #if DEBUG_EQUATION fprintf (stderr, "equation_solve: start\n"); #endif t1 = 0.L; t2 = 1.L; equation_solution (eq, r02, r12, t2); while (r02[2] > 0.L) { t2 *= 2.L; equation_solution (eq, r02, r12, t2); } for (i = 0; i < 64; ++i) { t3 = 0.5L * (t1 + t2); equation_solution (eq, r02, r12, t3); if (r02[2] > 0.L) t1 = t3; else t2 = t3; } memcpy (r0, r02, 3 * sizeof (long double)); memcpy (r1, r12, 3 * sizeof (long double)); #if DEBUG_EQUATION fprintf (stderr, "equation_solve: vx=%Lg vy=%Lg vz=%Lg\n", r1[0], r1[1], r1[2]); fprintf (stderr, "equation_solve: x=%Lg y=%Lg z=%Lg\n", r0[0], r0[1], r0[2]); fprintf (stderr, "equation_solve: t=%Lg\n", t3); fprintf (stderr, "equation_solve: end\n"); #endif return t3; } /** * Function to set a constant time step size. * * \return time step size. */ static long double equation_step_size_0 (Equation * eq __attribute__ ((unused))) ///< Equation struct. { #if DEBUG_EQUATION fprintf (stderr, "equation_step_size_0: start\n"); fprintf (stderr, "equation_step_size_0: dt=%Lg\n", dt); fprintf (stderr, "equation_step_size_0: end\n"); #endif return dt; } /** * Function to set the time step size based on stability condition for the 1st * resistance model. * * \return time step size. */ static long double equation_step_size_1 (Equation * eq) ///< Equation struct. { long double dt; #if DEBUG_EQUATION fprintf (stderr, "equation_step_size_1: start\n"); #endif dt = kt / fabsl (eq->lambda); #if DEBUG_EQUATION fprintf (stderr, "equation_step_size_1: dt=%Lg\n", dt); fprintf (stderr, "equation_step_size_1: end\n"); #endif return dt; } /** * Function to set the time step size based on stability condition for the 2nd * resistance model. * * \return time step size. */ static long double equation_step_size_2 (Equation * eq) ///< Equation struct. { long double dt; #if DEBUG_EQUATION fprintf (stderr, "equation_step_size_2: start\n"); #endif dt = kt / (fabsl (eq->lambda) * fmaxl (fabsl (r1[0] - eq->w[0]), fmaxl (fabsl (r1[1] - eq->w[1]), fabsl (r1[2])))); #if DEBUG_EQUATION fprintf (stderr, "equation_step_size_2: dt=%Lg\n", dt); fprintf (stderr, "equation_step_size_2: end\n"); #endif return dt; } /** * Function to finish the trajectory based on final time. * * \return 1 on finish, 0 on continuing. */ static int equation_land_0 (Equation * eq, ///< Equation struct. long double to, ///< old time. long double *t, ///< next time. long double *dt) ///< time step size. { long double tf; #if DEBUG_EQUATION fprintf (stderr, "equation_land_0: start\n"); fprintf (stderr, "equation_land_0: to=%Lg\n", to); #endif tf = eq->tf; if (to >= tf) { #if DEBUG_EQUATION fprintf (stderr, "equation_land_0: landing\n"); fprintf (stderr, "equation_land_0: end\n"); #endif return 1; } *t = to + *dt; if (*t >= tf) { *dt = tf - to; *t = tf; } #if DEBUG_EQUATION fprintf (stderr, "equation_land_0: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_0: no landing\n"); fprintf (stderr, "equation_land_0: end\n"); #endif return 0; } /** * Function to finish the trajectory based on 1st order landing. * * \return 1 on finish, 0 on continuing. */ static int equation_land_1 (Equation * eq __attribute__ ((unused)), ///< Equation struct. long double to, ///< old time. long double *t, ///< next time. long double *dt) ///< time step size. { long double h; #if DEBUG_EQUATION fprintf (stderr, "equation_land_1: start\n"); fprintf (stderr, "equation_land_1: to=%Lg\n", to); #endif if (r0[2] > 0.) { *t = to + *dt; #if DEBUG_EQUATION fprintf (stderr, "equation_land_1: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_1: no landing\n"); fprintf (stderr, "equation_land_1: end\n"); #endif return 0; } h = r0[2] / r1[2]; r0[0] -= h * r1[0]; r0[1] -= h * r1[1]; r0[2] -= h * r1[2]; r1[0] -= h * r2[0]; r1[1] -= h * r2[1]; r1[2] -= h * r2[2]; *t = to - h; #if DEBUG_EQUATION fprintf (stderr, "equation_land_1: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_1: landing\n"); fprintf (stderr, "equation_land_1: end\n"); #endif return 1; } /** * Function to finish the trajectory based on 2nd order landing. * * \return 1 on finish, 0 on continuing. */ static int equation_land_2 (Equation * eq __attribute__ ((unused)), ///< Equation struct. long double to, ///< old time. long double *t, ///< next time. long double *dt) ///< time step size. { long double h; #if DEBUG_EQUATION fprintf (stderr, "equation_land_2: start\n"); fprintf (stderr, "equation_land_2: to=%Lg\n", to); #endif if (r0[2] > 0.) { *t = to + *dt; #if DEBUG_EQUATION fprintf (stderr, "equation_land_2: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_2: no landing\n"); fprintf (stderr, "equation_land_2: end\n"); #endif return 0; } h = solve_quadratic (0.5L * r2[2], -r1[2], r0[2], 0.L, *dt); r0[0] -= h * (r1[0] - h * 0.5L * r2[0]); r0[1] -= h * (r1[1] - h * 0.5L * r2[1]); r0[2] -= h * (r1[2] - h * 0.5L * r2[2]); r1[0] -= h * r2[0]; r1[1] -= h * r2[1]; r1[2] -= h * r2[2]; *t = to - h; #if DEBUG_EQUATION fprintf (stderr, "equation_land_2: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_2: landing\n"); fprintf (stderr, "equation_land_2: end\n"); #endif return 1; } /** * Function to finish the trajectory based on 3rd order landing. * * \return 1 on finish, 0 on continuing. */ static int equation_land_3 (Equation * eq __attribute__ ((unused)), ///< Equation struct. long double to, ///< old time. long double *t, ///< next time. long double *dt) ///< time step size. { long double h, r3[3]; #if DEBUG_EQUATION fprintf (stderr, "equation_land_3: start\n"); fprintf (stderr, "equation_land_3: to=%Lg\n", to); #endif if (r0[2] > 0.) { *t = to + *dt; #if DEBUG_EQUATION fprintf (stderr, "equation_land_3: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_3: no landing\n"); fprintf (stderr, "equation_land_3: end\n"); #endif return 0; } r3[0] = (r2[0] - ro2[0]) / *dt; r3[1] = (r2[1] - ro2[1]) / *dt; r3[2] = (r2[2] - ro2[2]) / *dt; h = solve_cubic (-1.L / 6.L * r3[2], 0.5L * r2[2], -r1[2], r0[2], 0.L, *dt); r0[0] -= h * (r1[0] - h * (0.5L * r2[0] - h * 1.L / 6.L * r3[0])); r0[1] -= h * (r1[1] - h * (0.5L * r2[1] - h * 1.L / 6.L * r3[1])); r0[2] -= h * (r1[2] - h * (0.5L * r2[2] - h * 1.L / 6.L * r3[2])); r1[0] -= h * (r2[0] - h * 0.5L * r3[0]); r1[1] -= h * (r2[1] - h * 0.5L * r3[1]); r1[2] -= h * (r2[2] - h * 0.5L * r3[2]); *t = to - h; #if DEBUG_EQUATION fprintf (stderr, "equation_land_3: t=%Lg dt=%Lg\n", *t, *dt); fprintf (stderr, "equation_land_3: landing\n"); fprintf (stderr, "equation_land_3: end\n"); #endif return 1; } /** * Function to init the equation variables. */ void equation_init (Equation * eq, ///< Equation struct. gsl_rng * rng) ///< gsl_rng struct. { long double v, ha, va; #if DEBUG_EQUATION fprintf (stderr, "equation_init: start\n"); #endif switch (eq->type) { case 1: case 2: case 3: eq->lambda = eq->min_lambda + (eq->max_lambda - eq->min_lambda) * gsl_rng_uniform (rng); } v = eq->min_velocity + (eq->max_velocity - eq->min_velocity) * gsl_rng_uniform (rng); ha = 2.L * M_PIl * gsl_rng_uniform (rng); eq->r[0] = eq->r[1] = 0.L; va = eq->vertical_angle * M_PIl / 180.L; eq->v[2] = v * sinl (va); eq->v[1] = v * cosl (va); eq->v[0] = eq->v[1] * cosl (ha); eq->v[1] *= sinl (ha); v = eq->max_wind * gsl_rng_uniform (rng); ha = 2.L * M_PIl * gsl_rng_uniform (rng); eq->w[0] = v * cosl (ha); eq->w[1] = v * sinl (ha); #if DEBUG_EQUATION fprintf (stderr, "equation_init: end\n"); #endif } /** * Function to read the equation data on a XML node. * * \return 1 on success, 0 on error. */ int equation_read_xml (Equation * eq, ///< Equation struct. xmlNode * node, ///< XML node., unsigned int initial) ///< type of initial conditions. { const char *message[] = { "Bad XML node", "Bad type", "Unknown type", "Bad x", "Bad y", "Bad z", "Bad vx", "Bad vy", "Bad vz", "Bad wx", "Bad wy", "Bad lambda", "Bad minimum velocity", "Bad maximum velocity", "Bad vertical angle", "Bad maximum wind", "Bad minimum lambda", "Bad maximum lambda", "Bad g", "Bad time step type", "Bad dt", "Bad kt", "Unknown time step type", "Bad land type", "Bad t", "Unknown land type" }; int e, error_code; #if DEBUG_EQUATION fprintf (stderr, "equation_read_xml: start\n"); fprintf (stderr, "equation_read_xml: name=%s\n", node->name); #endif if (xmlStrcmp (node->name, XML_EQUATION)) { e = 0; goto exit_on_error; } eq->type = xml_node_get_uint (node, XML_TYPE, &error_code); if (error_code) { e = 1; goto exit_on_error; } switch (eq->type) { case 0: equation_acceleration = equation_acceleration_0; equation_solution = equation_solution_0; break; case 1: equation_acceleration = equation_acceleration_1; equation_solution = equation_solution_1; break; case 2: equation_acceleration = equation_acceleration_2; equation_solution = equation_solution_2; break; case 3: equation_acceleration = equation_acceleration_3; equation_solution = equation_solution_3; break; default: e = 2; goto exit_on_error; } eq->r[0] = xml_node_get_float_with_default (node, XML_X, 0.L, &error_code); if (error_code) { e = 3; goto exit_on_error; } eq->r[1] = xml_node_get_float_with_default (node, XML_Y, 0.L, &error_code); if (error_code) { e = 4; goto exit_on_error; } eq->r[2] = xml_node_get_float (node, XML_Z, &error_code); if (error_code || eq->r[2] < 0.L) { e = 5; goto exit_on_error; } if (initial) { eq->v[0] = xml_node_get_float_with_default (node, XML_VX, 0.L, &error_code); if (error_code) { e = 6; goto exit_on_error; } eq->v[1] = xml_node_get_float_with_default (node, XML_VY, 0.L, &error_code); if (error_code) { e = 7; goto exit_on_error; } eq->v[2] = xml_node_get_float_with_default (node, XML_VZ, 0.L, &error_code); if (error_code) { e = 8; goto exit_on_error; } eq->w[0] = xml_node_get_float_with_default (node, XML_WX, 0.L, &error_code); if (error_code) { e = 9; goto exit_on_error; } eq->w[1] = xml_node_get_float_with_default (node, XML_WY, 0.L, &error_code); if (error_code) { e = 10; goto exit_on_error; } switch (eq->type) { case 1: case 2: case 3: eq->lambda = xml_node_get_float_with_default (node, XML_LAMBDA, 0.L, &error_code); if (error_code) { e = 11; goto exit_on_error; } } } else { eq->min_velocity = xml_node_get_float_with_default (node, XML_VMIN, 0.L, &error_code); if (error_code || eq->min_velocity < 0.L) { e = 12; goto exit_on_error; } eq->max_velocity = xml_node_get_float (node, XML_VMAX, &error_code); if (error_code || eq->max_velocity <= 0.L) { e = 13; goto exit_on_error; } eq->vertical_angle = xml_node_get_float (node, XML_VERTICAL_ANGLE, &error_code); if (error_code) { e = 14; goto exit_on_error; } eq->max_wind = xml_node_get_float_with_default (node, XML_WMAX, 0.L, &error_code); if (error_code || eq->max_wind < 0.L) { e = 15; goto exit_on_error; } switch (eq->type) { case 1: case 2: case 3: eq->min_lambda = xml_node_get_float_with_default (node, XML_LAMBDA_MIN, 0.L, &error_code); if (error_code) { e = 16; goto exit_on_error; } eq->max_lambda = xml_node_get_float_with_default (node, XML_LAMBDA_MAX, 0.L, &error_code); if (error_code || eq->max_lambda < eq->min_lambda) { e = 17; goto exit_on_error; } } } eq->g = xml_node_get_float_with_default (node, XML_G, G, &error_code); if (error_code) { e = 18; goto exit_on_error; } eq->size_type = xml_node_get_uint (node, XML_TIME_STEP, &error_code); if (error_code) { e = 19; goto exit_on_error; } switch (eq->size_type) { case 0: equation_step_size = equation_step_size_0; dt = xml_node_get_float (node, XML_DT, &error_code); if (error_code) { e = 20; goto exit_on_error; } break; case 1: switch (eq->type) { case 1: equation_step_size = equation_step_size_1; break; case 2: equation_step_size = equation_step_size_2; } kt = xml_node_get_float (node, XML_KT, &error_code); if (error_code) { e = 21; goto exit_on_error; } break; default: e = 22; goto exit_on_error; } eq->land_type = xml_node_get_uint (node, XML_LAND, &error_code); if (error_code) { e = 23; goto exit_on_error; } switch (eq->land_type) { case 0: equation_land = equation_land_0; eq->tf = xml_node_get_float (node, XML_T, &error_code); if (error_code || eq->tf < 0.) { e = 24; goto exit_on_error; } break; case 1: equation_land = equation_land_1; break; case 2: equation_land = equation_land_2; break; case 3: equation_land = equation_land_3; break; default: e = 25; goto exit_on_error; } #if DEBUG_EQUATION fprintf (stderr, "equation_read_xml: success\n"); fprintf (stderr, "equation_read_xml: end\n"); #endif return 1; exit_on_error: #if DEBUG_EQUATION fprintf (stderr, "equation_read_xml: error\n"); #endif error_add (message[e]); #if DEBUG_EQUATION fprintf (stderr, "equation_read_xml: end\n"); #endif return 0; }
{ "alphanum_fraction": 0.5683582626, "avg_line_length": 30.6345270891, "ext": "c", "hexsha": "8297b7c1d6c20a265669031fc6586ca611a9f7f8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ballistic", "max_forks_repo_path": "1.1.0/equation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "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": "jburguete/ballistic", "max_issues_repo_path": "1.1.0/equation.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ballistic", "max_stars_repo_path": "1.1.0/equation.c", "max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z", "num_tokens": 11218, "size": 33361 }
/* mcmc.h * David W. Pearson * 17 July 2018 * * This header file will be responsible for running Markov Chain Monte Carlo fitting. */ #ifndef _MCMC_H_ #define _MCMC_H_ #include "bispectrum_model.h" #include <iostream> #include <fstream> #include <random> #include <vector> #include <string> #include <cmath> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> std::random_device seeder; std::mt19937_64 gen(seeder()); std::uniform_real_distribution<double> dist(-1.0, 1.0); class bkmcmc{ int num_data, num_pars; std::vector<double> data; // These should have size of num_data std::vector<std::vector<double>> Psi; // num_data vectors of size num_data std::vector<double> theta_0, theta_i, param_vars, min, max; // These should all have size of num_pars std::vector<float4> k; // This should have size of num_data std::vector<bool> limit_pars; // This should have size of num_pars double chisq_0, chisq_i; // Sets the values of theta_i. void get_param_real(); // done // Calculates the chi^2 for the current proposal, theta_i double calc_chi_squared(); // done // Performs one MCMC trial. Returns true if proposal accepted, false otherwise bool trial(float4 *ks, double *Bk, double &L, double &R); // done // Writes the current accepted parameters to the screen void write_theta_screen(); // done // Burns the requested number of parameter realizations to move to a higher likelihood region void burn_in(int num_burn, float4 *ks, double *Bk); // done // Changes the initial guesses for the search range around parameters until acceptance = 0.234 void tune_vars(float4 *ks, double *Bk); // done public: std::vector<double> model; // These should have size num_data // Initializes most of the data members and gets an initial chisq_0 bkmcmc(std::string data_file, std::string cov_file, std::vector<double> &pars, std::vector<double> &vars, float4 *ks, double *Bk); // done // Displays information to the screen to check that the vectors are all the correct size void check_init(); // done // Sets which parameters should be limited and what the limits are void set_param_limits(std::vector<bool> &lim_pars, std::vector<double> &min_in, std::vector<double> &max_in); // done // Runs the MCMC chain for num_draws realizations, writing to reals_file void run_chain(int num_draws, int num_burn, std::string reals_file, float4 *ks, double *Bk, bool new_chain); }; void bkmcmc::get_param_real() { for (int i = 0; i < bkmcmc::num_pars; ++i) { if (bkmcmc::limit_pars[i]) { if (bkmcmc::theta_0[i] + bkmcmc::param_vars[i] > bkmcmc::max[i]) { double center = bkmcmc::max[i] - bkmcmc::param_vars[i]; bkmcmc::theta_i[i] = center + dist(gen)*bkmcmc::param_vars[i]; } else if (bkmcmc::theta_0[i] - bkmcmc::param_vars[i] < bkmcmc::min[i]) { double center = bkmcmc::min[i] + bkmcmc::param_vars[i]; bkmcmc::theta_i[i] = center + dist(gen)*bkmcmc::param_vars[i]; } else { bkmcmc::theta_i[i] = bkmcmc::theta_0[i] + dist(gen)*bkmcmc::param_vars[i]; } } else { bkmcmc::theta_i[i] = bkmcmc::theta_0[i] + dist(gen)*bkmcmc::param_vars[i]; } } } double bkmcmc::calc_chi_squared() { double chisq = 0.0; for (int i = 0; i < bkmcmc::num_data; ++i) { for (int j = i; j < bkmcmc::num_data; ++j) { if (bkmcmc::data[i] > 0 && bkmcmc::data[j] > 0) { chisq += (bkmcmc::data[i] - bkmcmc::model[i])*Psi[i][j]*(bkmcmc::data[j] - bkmcmc::model[j]); } } } return chisq; } bool bkmcmc::trial(float4 *ks, double *d_Bk, double &L, double &R) { bkmcmc::get_param_real(); model_calc(bkmcmc::theta_i, ks, d_Bk, bkmcmc::model); bkmcmc::chisq_i = bkmcmc::calc_chi_squared(); L = exp(0.5*(bkmcmc::chisq_0 - bkmcmc::chisq_i)); R = (dist(gen) + 1.0)/2.0; if (L > R) { for (int i = 0; i < bkmcmc::num_pars; ++i) bkmcmc::theta_0[i] = bkmcmc::theta_i[i]; bkmcmc::chisq_0 = bkmcmc::chisq_i; return true; } else { return false; } } void bkmcmc::write_theta_screen() { std::cout.precision(6); for (int i = 0; i < bkmcmc::num_pars; ++i) { std::cout.width(15); std::cout << bkmcmc::theta_0[i]; } std::cout.width(15); std::cout << pow(bkmcmc::theta_0[3]*bkmcmc::theta_0[4]*bkmcmc::theta_0[4],1.0/3.0); std::cout.width(15); std::cout << bkmcmc::chisq_0; std::cout.flush(); } void bkmcmc::burn_in(int num_burn, float4 *ks, double *d_Bk) { std::cout << "Burning the first " << num_burn << " trials to move to higher likelihood..." << std::endl; double L, R; for (int i = 0; i < num_burn; ++i) { bool move = bkmcmc::trial(ks, d_Bk, L, R); if (true) { std::cout << "\r"; std::cout.width(5); std::cout << i; bkmcmc::write_theta_screen(); std::cout.width(15); std::cout << L; std::cout.width(15); std::cout << R; std::cout.flush(); } } std::cout << std::endl; } void bkmcmc::tune_vars(float4 *ks, double *d_Bk) { std::cout << "Tuning acceptance ratio..." << std::endl; double acceptance = 0.0; while (acceptance <= 0.233 || acceptance >= 0.235) { int accept = 0; double L, R; for (int i = 0; i < 10000; ++i) { bool move = bkmcmc::trial(ks, d_Bk, L, R); if (move) { std::cout << "\r"; bkmcmc::write_theta_screen(); accept++; } } std::cout << std::endl; acceptance = double(accept)/10000.0; if (acceptance <= 0.233) { for (int i = 0; i < bkmcmc::num_pars; ++i) bkmcmc::param_vars[i] *= 0.99; } if (acceptance >= 0.235) { for (int i = 0; i < bkmcmc::num_pars; ++i) bkmcmc::param_vars[i] *= 1.01; } std::cout << "acceptance = " << acceptance << std::endl; } std::ofstream fout; fout.open("variances.dat", std::ios::out); for (int i = 0; i < bkmcmc::num_pars; ++i) fout << bkmcmc::param_vars[i] << " "; fout << "\n"; fout.close(); } bkmcmc::bkmcmc(std::string data_file, std::string cov_file, std::vector<double> &pars, std::vector<double> &vars, float4 *ks, double *d_Bk) { std::ifstream fin; std::ofstream fout; std::cout << "Reading in and storing data file..." << std::endl; if (std::ifstream(data_file)) { fin.open(data_file.c_str(), std::ios::in); while (!fin.eof()) { float4 kt; double B; fin >> kt.w >> kt.x >> kt.y >> kt.z >> B; if (!fin.eof()) { bkmcmc::k.push_back(kt); bkmcmc::data.push_back(B); bkmcmc::model.push_back(0.0); } } fin.close(); } else { std::stringstream message; message << "Could not open " << data_file << std::endl; throw std::runtime_error(message.str()); } bkmcmc::num_data = bkmcmc::data.size(); std::cout << "num_data = " << bkmcmc::num_data << std::endl; gsl_matrix *cov = gsl_matrix_alloc(bkmcmc::num_data, bkmcmc::num_data); gsl_matrix *psi = gsl_matrix_alloc(bkmcmc::num_data, bkmcmc::num_data); gsl_permutation *perm = gsl_permutation_alloc(bkmcmc::num_data); std::cout << "Reading in covariance and computing its inverse..." << std::endl; if (std::ifstream(cov_file)) { fin.open(cov_file.c_str(), std::ios::in); for (int i = 0; i < bkmcmc::num_data; ++i) { for (int j = 0; j < bkmcmc::num_data; ++j) { double element; fin >> element; gsl_matrix_set(cov, i, j, element); } } fin.close(); } else { std::stringstream message; message << "Could not open " << cov_file << std::endl; throw std::runtime_error(message.str()); } int s; gsl_linalg_LU_decomp(cov, perm, &s); gsl_linalg_LU_invert(cov, perm, psi); for (int i = 0; i < bkmcmc::num_data; ++i) { std::vector<double> row; row.reserve(bkmcmc::num_data); for (int j = 0; j < bkmcmc::num_data; ++j) { row.push_back((1.0 - double(bkmcmc::num_data + 1.0)/2048.0)*gsl_matrix_get(psi, i, j)); } bkmcmc::Psi.push_back(row); } gsl_matrix_free(cov); gsl_matrix_free(psi); gsl_permutation_free(perm); gpuErrchk(cudaMemcpy(ks, bkmcmc::k.data(), bkmcmc::num_data*sizeof(float4), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_Bk, bkmcmc::model.data(), bkmcmc::num_data*sizeof(double), cudaMemcpyHostToDevice)); bkmcmc::num_pars = pars.size(); std::cout << "num_pars = " << bkmcmc::num_pars << std::endl; for (int i = 0; i < bkmcmc::num_pars; ++i) { bkmcmc::theta_0.push_back(pars[i]); bkmcmc::theta_i.push_back(0.0); bkmcmc::limit_pars.push_back(false); bkmcmc::max.push_back(0.0); bkmcmc::min.push_back(0.0); bkmcmc::param_vars.push_back(vars[i]); } std::cout << "Calculating initial model and chi^2..." << std::endl; model_calc(bkmcmc::theta_0, ks, d_Bk, bkmcmc::model); bkmcmc::chisq_0 = bkmcmc::calc_chi_squared(); fout.open("Bk_mod_check.dat", std::ios::out); for (int i =0; i < bkmcmc::num_data; ++i) { fout.precision(3); fout << bkmcmc::k[i].x << " " << bkmcmc::k[i].y << " " << bkmcmc::k[i].z << " "; fout.precision(15); fout << bkmcmc::data[i] << " " << bkmcmc::model[i] << "\n"; } fout.close(); } void bkmcmc::check_init() { std::cout << "Number of data points: " << bkmcmc::num_data << std::endl; std::cout << " data.size() = " << bkmcmc::data.size() << std::endl; std::cout << " model.size() = " << bkmcmc::model.size() << std::endl; std::cout << " Psi.size() = " << bkmcmc::Psi.size() << std::endl; std::cout << "Number of parameters: " << bkmcmc::num_pars << std::endl; std::cout << " theta_0.size() = " << bkmcmc::theta_0.size() << std::endl; std::cout << " theta_i.size() = " << bkmcmc::theta_i.size() << std::endl; std::cout << " limit_pars.size()= " << bkmcmc::limit_pars.size() << std::endl; std::cout << " min.size() = " << bkmcmc::min.size() << std::endl; std::cout << " max.size() = " << bkmcmc::max.size() << std::endl; std::cout << " param_vars.size()= " << bkmcmc::param_vars.size() << std::endl; } void bkmcmc::set_param_limits(std::vector<bool> &lim_pars, std::vector<double> &min_in, std::vector<double> &max_in) { for (int i = 0; i < bkmcmc::num_pars; ++i) { bkmcmc::limit_pars[i] = lim_pars[i]; bkmcmc::max[i] = max_in[i]; bkmcmc::min[i] = min_in[i]; } } void bkmcmc::run_chain(int num_draws, int num_burn, std::string reals_file, float4 *ks, double *d_Bk, bool new_chain) { int num_old_rels = 0; if (new_chain) { std::cout << "Starting new chain..." << std::endl; bkmcmc::burn_in(num_burn, ks, d_Bk); bkmcmc::tune_vars(ks, d_Bk); } else { std::cout << "Resuming previous chain..." << std::endl; std::ifstream fin; fin.open("variances.dat", std::ios::in); for (int i = 0; i < bkmcmc::num_pars; ++i) { double var; fin >> var; bkmcmc::param_vars[i] = var; } fin.close(); fin.open(reals_file.c_str(), std::ios::in); while (!fin.eof()) { double alpha; num_old_rels++; std::cout << "\r"; for (int i = 0; i < bkmcmc::num_pars; ++i) { fin >> bkmcmc::theta_0[i]; std::cout.width(10); std::cout << bkmcmc::theta_0[i]; } fin >> alpha; fin >> bkmcmc::chisq_0; std::cout.width(10); std::cout << alpha; std::cout.width(10); std::cout << bkmcmc::chisq_0; } fin.close(); num_old_rels--; } std::ofstream fout; double L, R; fout.open(reals_file.c_str(), std::ios::app); fout.precision(15); for (int i = 0; i < num_draws; ++i) { bool move = bkmcmc::trial(ks, d_Bk, L, R); for (int par = 0; par < bkmcmc::num_pars; ++par) { fout << bkmcmc::theta_0[par] << " "; } double alpha = pow(bkmcmc::theta_0[3]*bkmcmc::theta_0[4]*bkmcmc::theta_0[4], 1.0/3.0); fout << alpha << " " << bkmcmc::chisq_0 << "\n"; if (move) { std::cout << "\r"; std::cout.width(15); std::cout << i + num_old_rels; bkmcmc::write_theta_screen(); } } std::cout << std::endl; fout.close(); } #endif
{ "alphanum_fraction": 0.5434098066, "avg_line_length": 36.3433242507, "ext": "h", "hexsha": "e32bd6f013212785a6da0fc6844cd3468fac91e9", "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": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dpearson1983/BIMODAL", "max_forks_repo_path": "include/mcmc.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "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": "dpearson1983/BIMODAL", "max_issues_repo_path": "include/mcmc.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dpearson1983/BIMODAL", "max_stars_repo_path": "include/mcmc.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4015, "size": 13338 }
#pragma once #include "nkw_common.h" #include "utility/types.h" #include <gsl/gsl> namespace cws80 { class NativeUI; // bool im_select(nk_context *ctx, NativeUI &nat, gsl::span<const std::string> choices, uint *value); } // namespace cws80
{ "alphanum_fraction": 0.6769230769, "avg_line_length": 17.3333333333, "ext": "h", "hexsha": "0e63185975f55cf40291b98bce7747202436e0fb", "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": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/cws80", "max_forks_repo_path": "sources/ui/detail/nkw_select.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/cws80", "max_issues_repo_path": "sources/ui/detail/nkw_select.h", "max_line_length": 66, "max_stars_count": 4, "max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/cws80", "max_stars_repo_path": "sources/ui/detail/nkw_select.h", "max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z", "num_tokens": 70, "size": 260 }
/*! \file allvars.h * \brief declares global variables. * * This file declares all global variables and structures. Further variables should be added here, and declared as * \e \b extern. The actual existence of these variables is provided by the file \ref allvars.cxx. To produce * \ref allvars.cxx from \ref allvars.h, do the following: * * \arg Erase all \#define's, typedef's, and enum's * \arg add \#include "allvars.h", delete the \#ifndef ALLVARS_H conditional * \arg delete all keywords 'extern' * \arg delete all struct definitions enclosed in {...}, e.g. * "extern struct global_data_all_processes {....} All;" * becomes "struct global_data_all_processes All;" */ #ifndef ALLVARS_H #define ALLVARS_H #include <cstdio> #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <cmath> #include <string> #include <vector> #include <algorithm> #include <map> #include <getopt.h> #include <sys/stat.h> #include <sys/timeb.h> #include <gsl/gsl_heapsort.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> ///\name Include for NBodyFramework library. //@{ ///nbody code #include <NBody.h> ///Math code #include <NBodyMath.h> ///Binary KD-Tree code #include <KDTree.h> ///Extra routines that analyze a distribution of particles #include <Analysis.h> //@} // ///\name for checking the endian of floats //#include <endianutils.h> ///if using OpenMP API #ifdef USEOPENMP #include <omp.h> #include "ompvar.h" #endif ///if using HDF API #ifdef USEHDF #include "H5Cpp.h" #ifndef H5_NO_NAMESPACE using namespace H5; #endif #endif ///if using ADIOS API #ifdef USEADIOS #include "adios.h" #endif //#include "swiftinterface.h" // //using namespace Swift; using namespace std; using namespace Math; using namespace NBody; //-- Structures and external variables /// \defgroup PARTTYPES Particle types //@{ #define GASTYPE 0 #define DARKTYPE 1 #define DARK2TYPE 2 #define DARK3TYPE 3 #define STARTYPE 4 #define BHTYPE 5 #define WINDTYPE 6 #define NPARTTYPES 7 //number of baryon types +1, to store all baryons #define NBARYONTYPES 5 //@} /// \defgroup SEARCHTYPES Specify particle type to be searched, all, dm only, separate //@{ #define PSTALL 1 #define PSTDARK 2 #define PSTSTAR 3 #define PSTGAS 4 #define PSTBH 5 #define PSTNOBH 6 //@} /// \defgroup STRUCTURETYPES Specific structure type, allow for other types beside HALO //@{ /// \todo note that here I have set background group type to a halo structure type but that can be changed #define HALOSTYPE 10 #define HALOCORESTYPE 5 #define WALLSTYPE 1 #define VOIDSTYPE 2 #define FILAMENTSTYPE 3 #define BGTYPE 10 #define GROUPNOPARENT -1 #define FOF3DTYPE 7 #define FOF3DGROUP -2 //@} /// \defgroup FOFTYPES FOF search types //@{ //subsets made ///call \ref FOFStreamwithprob #define FOFSTPROB 1 ///6D FOF search but only with outliers #define FOF6DSUBSET 7 ///like \ref FOFStreamwithprob search but search is limited to nearest physical neighbours #define FOFSTPROBNN 9 ///like \ref FOFStreamwithprob search but here linking length adjusted by velocity offset, smaller lengths for larger velocity offsets #define FOFSTPROBLX 10 ///like \ref FOFSTPROBLX but for NN search #define FOFSTPROBNNLX 11 ///like \ref FOFSTPROBNN but there is not linking length applied just use nearest neighbours #define FOFSTPROBNNNODIST 12 //for iterative method with FOFStreamwithprob //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELL 13 //#define FOFSTPROBIT 13 #define FOFSTPROBSCALEELLNN 14 //solely phase-space tensor core growth substructure search #define FOF6DCORE 6 ///phase-space FOF but no subset produced #define FOFSTNOSUBSET 2 ///no subsets made, just 6d (with each 6dfof search using 3d fof velocity dispersion,) #define FOF6DADAPTIVE 3 ///6d fof but only use single velocity dispersion from largest 3d fof object #define FOF6D 4 ///3d search #define FOF3D 5 ///baryon 6D FOF search #define FOFBARYON6D 0 ///baryon phase tensor search #define FOFBARYONPHASETENSOR 1 //@} /// \defgroup INTERATIVESEARCHPARAMS for iterative subsubstructure search //@{ /// this is minimum particle number size for a subsearch to proceed whereby substructure split up into CELLSPLITNUM new cells #define MINCELLSIZE 100 #define CELLSPLITNUM 8 #define MINSUBSIZE MINCELLSIZE*CELLSPLITNUM #define MAXSUBLEVEL 8 /// maximum fraction a cell can take of a halo #define MAXCELLFRACTION 0.1 //@} ///\defgroup GRIDTYPES Type of Grid structures //@{ #define PHYSENGRID 1 #define PHASEENGRID 2 #define PHYSGRID 3 //@} /// \name Max number of neighbouring cells used in interpolation of background velocity field. //@{ //if cells were cubes this would be all the neighbours that full enclose the cube, 6 faces+20 diagonals //using daganoals may not be ideal. Furthermore, code using adaptive grid that if effectively produces //cell that are rectangular prisms. Furthermore, not all cells will share a boundary with another cell. //So just consider "faces". #define MAXNGRID 6 //@} ///\defgroup INPUTTYPES defining types of input //@{ #define NUMINPUTS 5 #define IOGADGET 1 #define IOHDF 2 #define IOTIPSY 3 #define IORAMSES 4 #define IONCHILADA 5 //@} ///\defgroup OUTPUTTYPES defining format types of output //@{ #define OUTASCII 0 #define OUTBINARY 1 #define OUTHDF 2 #define OUTADIOS 3 //@} /// \name For Unbinding //@{ ///number below which just use PP calculation for potential, which occurs roughly at when n~2*log(n) (from scaling of n^2 vs n ln(n) for PP vs tree and factor of 2 is ///for extra overhead in producing tree. For reasonable values of n (>100) this occurs at ~100. Here to account for extra memory need for tree, we use n=3*log(n) or 150 #define UNBINDNUM 150 ///when unbinding check to see if system is bound and least bound particle is also bound #define USYSANDPART 0 ///when unbinding check to see if least bound particle is also bound #define UPART 1 ///use the bulk centre of mass velocity to define velocity reference frame when determining if particle bound #define CMVELREF 0 ///use the particle at potential minimum. Issues if too few particles used as particles will move in and out of deepest point of the potential well #define POTREF 1 ///use Centre-of-mass to caculate Properties #define PROPREFCM 0 ///use most bound particle to calculate properties #define PROPREFMBP 1 ///use minimum potential particle to calculat properties #define PROPREFMINPOT 2 //@} /// \name For Tree potential calculation //@{ ///leafflag indicating in tree-calculation of potential, reached a leaf node that does not satisfy mono-pole approx #define leafflag 1 ///split flag means node not used as subcells are searched #define splitflag -1 ///cellflag means a node that is not necessarily a leaf node can be approximated by mono-pole #define cellflag 0 //@} /// \defgroup OMPLIMS For determining whether loop contains enough for openm to be worthwhile. //@{ #ifndef USEOPENMP #define ompsearchnum 50000 #define ompunbindnum 1000 #define ompperiodnum 50000 #define omppropnum 50000 #endif //@} /// \defgroup PROPLIMS Particle limits for calculating properties //@{ #define PROPNFWMINNUM 100 #define PROPCMMINNUM 10 #define PROPROTMINNUM 10 #define PROPMORPHMINNUM 10 //@} ///\name halo id modifers used with current snapshot value to make temporally unique halo identifiers #ifdef LONGINT #define HALOIDSNVAL 1000000000000L #else #define HALOIDSNVAL 1000000 #endif ///\defgroup radial profile parameters //@{ #define PROFILERNORMPHYS 0 #define PROFILERNORMR200CRIT 1 #define PROFILERBINTYPELOG 0 //@} ///\defgroup GASPARAMS Useful constants for gas //@{ ///mass of helium relative to hydrogen #define M_HetoM_H 4.0026 //@} /// Structure stores unbinding information struct UnbindInfo { ///\name flag whether unbind groups, keep bg potential when unbinding, type of unbinding and reference frame //@{ int unbindflag,bgpot,unbindtype,cmvelreftype; //@} ///boolean as to whether code calculate potentials or potentials are externally provided bool icalculatepotential; ///fraction of potential energy that kinetic energy is allowed to be and consider particle bound Double_t Eratio; ///minimum bound mass fraction Double_t minEfrac; ///when to recalculate kinetic energies if cmvel has changed enough Double_t cmdelta; ///maximum fraction of particles to remove when unbinding in one given unbinding step Double_t maxunbindfrac; ///Maximum fraction of particles that can be considered unbound before group removed entirely Double_t maxunboundfracforiterativeunbind; ///Max allowed unbound fraction to speed up unbinding Double_t maxallowedunboundfrac; ///minimum number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Int_t Npotref; ///fraction of number of particles to use to calculate reference frame if using particles around deepest potential well as reference frame Double_t fracpotref; ///\name gravity and tree potential calculation; //@{ int BucketSize; Double_t TreeThetaOpen; ///softening length Double_t eps; //@} UnbindInfo(){ icalculatepotential=true; unbindflag=0; bgpot=1; unbindtype=UPART; cmvelreftype=CMVELREF; cmdelta=0.02; Eratio=1.0; minEfrac=1.0; BucketSize=8; TreeThetaOpen=0.5; eps=0.0; Npotref=20; fracpotref=1.0; maxunbindfrac=0.5; maxunboundfracforiterativeunbind=0.95; maxallowedunboundfrac=0.025; } }; /// Structure stores information used when calculating bulk (sub)structure properties /// which is used in \ref substructureproperties.cxx struct PropInfo { //interate till this much mass in contained in a spherical region to calculate cm quantities Double_t cmfrac,cmadjustfac; PropInfo(){ cmfrac=0.1; cmadjustfac=0.7; } }; /* Structure to hold the location of a top-level cell. */ struct cell_loc { /* Coordinates x,y,z */ double loc[3]; }; /// Options structure stores useful variables that have user determined values which are altered by \ref GetArgs in \ref ui.cxx struct Options { ///\name filenames //@{ char *fname,*outname,*smname,*pname,*gname; char *ramsessnapname; //@} ///input format int inputtype; ///number of snapshots int num_files,snum; ///if parallel reading, number of files read in parallel int nsnapread; ///for output, specify the formats, ie. many separate files int iseparatefiles; ///for output specify the format HDF, binary or ascii \ref OUTHDF, \ref OUTBINARY, \ref OUTASCII int ibinaryout; ///for extended output allowing extraction of particles int iextendedoutput; /// output extra fields in halo properties int iextrahalooutput; /// calculate and output extra gas fields int iextragasoutput; /// calculate and output extra star fields int iextrastaroutput; /// calculate and output extra bh fields int iextrabhoutput; /// calculate and output extra interloper fields int iextrainterloperoutput; /// calculate subind like properties int isubfindproperties; ///for output, produce subfind like format int isubfindoutput; ///disable particle id related output like fof.grp or catalog_group data. Useful if just want halo properties ///and not interested in tracking. Code writes halo properties catalog and exits. int inoidoutput; ///return propery data in in comoving little h units instead of standard physical units int icomoveunit; /// input is a cosmological simulation so can use box sizes, cosmological parameters, etc to set scales int icosmologicalin; /// input buffer size when reading data long int inputbufsize; /// mpi paritcle buffer size when sending input particle information long int mpiparticletotbufsize,mpiparticlebufsize; /// mpi factor by which to multiple the memory allocated, ie: buffer region /// to reduce likelihood of having to expand/allocate new memory Double_t mpipartfac; /// run FOF using OpenMP int iopenmpfof; /// size of openmp FOF region int openmpfofsize; ///\name length,m,v,grav conversion units //@{ Double_t lengthinputconversion, massinputconversion, energyinputconversion, velocityinputconversion; Double_t SFRinputconversion, metallicityinputconversion, stellarageinputconversion; int istellaragescalefactor, isfrisssfr; Double_t G; Double_t lengthtokpc, velocitytokms, masstosolarmass, energyperunitmass, timetoseconds; Double_t SFRtosolarmassperyear, stellaragetoyrs, metallicitytosolar; //@} ///period (comove) Double_t p; ///\name scale factor, Hubunit, h, cosmology, virial density. These are used if linking lengths are scaled or trying to define virlevel using the cosmology //@{ Double_t a,H,h; Double_t Omega_m, Omega_b, Omega_cdm, Omega_Lambda, Omega_k, Omega_r, Omega_nu, Omega_de, w_de; Double_t rhocrit, rhobg, virlevel, virBN98; int comove; /// to store the internal code unit to kpc and the distance^2 of 30 kpc, and 50 kpc Double_t lengthtokpc30pow2, lengthtokpc50pow2; //@} ///to store number of each particle types so that if only searching one particle type, assumes order of gas, dark (halo, disk,bulge), star, special or sink for pfof tipsy style output Int_t numpart[NPARTTYPES]; ///\name parameters that control the local and average volumes used to calculate the local velocity density and the mean field, also the size of the leafnode in the kd-tree used when searching the tree for fof neighbours //@{ int iLocalVelDenApproxCalcFlag; int Nvel, Nsearch, Bsize; Int_t Ncell; Double_t Ncellfac; //@} ///minimum group size int MinSize; ///allows for field halos to have a different minimum size int HaloMinSize; ///Significance parameter for groups Double_t siglevel; ///whether to search for substructures at all int iSubSearch; ///type of search int foftype,fofbgtype; ///grid type, physical, physical+entropy splitting criterion, phase+entropy splitting criterion. Note that this parameter should not be changed from the default value int gridtype; ///flag indicating search all particle types or just dark matter int partsearchtype; ///flag indicating a separate baryonic search is run, looking for all particles that are associated in phase-space ///with dark matter particles that belong to a structure int iBaryonSearch; /// FOF search for baryons int ifofbaryonsearch; ///flag indicating if move to CM frame for substructure search int icmrefadjust; /// flag indicating if CM is interated shrinking spheres int iIterateCM; /// flag to sort output particle lists by binding energy (or potential if not on) int iSortByBindingEnergy; /// what reference position to use when calculating Properties int iPropertyReferencePosition; /// what particle type is used to define reference position int ParticleTypeForRefenceFrame; ///threshold on particle ELL value, normalized logarithmic distance from predicted maxwellian velocity density. Double_t ellthreshold; ///\name fofstream search parameters //@{ Double_t thetaopen,Vratio,ellphys; //@} ///fof6d search parameters Double_t ellvel; ///scaling for ellphs and ellvel Double_t ellxscale,ellvscale; ///flag to use iterative method int iiterflag; ///\name factors used to multiply the input values to find initial candidate particles and for mergering groups in interative search //@{ Double_t ellfac,ellxfac,vfac,thetafac,nminfac; Double_t fmerge; //@} ///factors to alter halo linking length search (related to substructure search) //@{ Double_t ellhalophysfac,ellhalovelfac; //@} ///\name parameters related to 3DFOF search & subsequent 6DFOF search //@{ Double_t ellhalo3dxfac; Double_t ellhalo6dxfac; Double_t ellhalo6dvfac; int iKeepFOF; Int_t num3dfof; //@} //@{ ///\name factors used to check for halo mergers, large background substructures and store the velocity scale when searching for associated baryon substructures //@{ Double_t HaloMergerSize,HaloMergerRatio,HaloSigmaV,HaloVelDispScale,HaloLocalSigmaV; Double_t fmergebg; //@} ///flag indicating a single halo is passed or must run search for FOF haloes Int_t iSingleHalo; ///flag indicating haloes are to be check for self-boundness after being searched for substructure Int_t iBoundHalos; /// store denv ratio statistics //@{ int idenvflag; Double_t denvstat[3]; //@} ///verbose output flag int iverbose; ///whether or not to write a fof.grp tipsy like array file int iwritefof; ///whether mass properties for field objects are inclusive int iInclusiveHalo; ///if no mass value stored then store global mass value Double_t MassValue; ///structure that contains variables for unbinding UnbindInfo uinfo; ///structure that contains variables for property calculation PropInfo pinfo; ///effective resolution for zoom simulations Int_t Neff; ///if during substructure search, want to also search for larger substructures //using the more time consuming local velocity calculations (partly in lieu of using the faster core search) int iLargerCellSearch; ///\name extra stuff for halo merger check and identification of multiple halo core and flag for fully adaptive linking length using number density of candidate objects //@{ /// run halo core search for mergers int iHaloCoreSearch; ///maximum sublevel at which we search for phase-space cores int maxnlevelcoresearch; ///parameters associated with phase-space search for cores of mergers Double_t halocorexfac, halocorevfac, halocorenfac, halocoresigmafac; ///x and v space linking lengths calculated for each object int iAdaptiveCoreLinking; ///use phase-space tensor core assignment int iPhaseCoreGrowth; ///number of iterations int halocorenumloops; ///factor by which one multiples the configuration space dispersion when looping for cores Double_t halocorexfaciter; ///factor by which one multiples the velocity space dispersion when looping for cores Double_t halocorevfaciter; ///factor by which one multiples the min num when looping for cores Double_t halocorenumfaciter; ///factor by which a core must be seperated from main core in phase-space in sigma units Double_t halocorephasedistsig; ///factor by which a substructure s must be closer than in phase-space to merger with another substructure in sigma units Double_t coresubmergemindist; //@} ///for storing a snapshot value to make halo ids unique across snapshots long long snapshotvalue; ///\name for reading gadget info with lots of extra sph, star and bh blocks //@{ int gnsphblocks,gnstarblocks,gnbhblocks; //@} /// \name Extra HDF flags indicating the existence of extra baryonic/dm particle types //@{ /// input naming convention int ihdfnameconvention; /// input contains dm particles int iusedmparticles; /// input contains hydro/gas particles int iusegasparticles; /// input contains star particles int iusestarparticles; /// input contains black hole/sink particles int iusesinkparticles; /// input contains wind particles int iusewindparticles; /// input contains tracer particles int iusetracerparticles; /// input contains extra dark type particles int iuseextradarkparticles; //@} /// if want full spherical overdensity, factor by which size is multiplied to get ///bucket of particles Double_t SphericalOverdensitySeachFac; ///minimum enclosed mass on which to base SO calculations, <1 Double_t SphericalOverdensityMinHaloFac; ///if want to the particle IDs that are within the SO overdensity of a halo int iSphericalOverdensityPartList; /// \name Extra variables to store information useful in zoom simluations //@{ /// store the lowest dark matter particle mass Double_t zoomlowmassdm; //@} ///\name extra runtime flags //@{ ///scale lengths. Useful if searching single halo system and which to automatically scale linking lengths int iScaleLengths; /// \name Swift/Metis related quantitites //@{ //Swift::siminfo swiftsiminfo; double spacedimension[3]; /* Number of top-level cells. */ int numcells; /* Number of top-level cells in each dimension. */ int numcellsperdim; /* Locations of top-level cells. */ cell_loc *cellloc; /*! Top-level cell width. */ double cellwidth[3]; /*! Inverse of the top-level cell width. */ double icellwidth[3]; /*! Holds the node ID of each top-level cell. */ const int *cellnodeids; //@} /// \name options related to calculation of aperture/profile //@{ int iaperturecalc; int aperturenum,apertureprojnum; vector<Double_t> aperture_values_kpc; vector<string> aperture_names_kpc; vector<Double_t> aperture_proj_values_kpc; vector<string> aperture_proj_names_kpc; int iprofilecalc, iprofilenorm, iprofilebintype; int profilenbins; int iprofilecumulative; string profileradnormstring; vector<Double_t> profile_bin_edges; //@} /// \name options related to calculation of arbitrary overdensities masses, radii, angular momentum //@{ int SOnum; vector<Double_t> SOthresholds_values_crit; vector<string> SOthresholds_names_crit; //@} /// \name options related to calculating star forming gas quantities //@{ Double_t gas_sfr_threshold; //@} Options() { lengthinputconversion = 1.0; massinputconversion = 1.0; velocityinputconversion = 1.0; SFRinputconversion = 1.0; metallicityinputconversion = 1.0; energyinputconversion = 1.0; stellarageinputconversion =1.0; istellaragescalefactor = 1; isfrisssfr = 0; G = 1.0; p = 0.0; a = 1.0; H = 0.; h = 1.0; Omega_m = 1.0; Omega_Lambda = 0.0; Omega_b = 0.0; Omega_cdm = Omega_m; Omega_k = 0; Omega_r = 0.0; Omega_nu = 0.0; Omega_de = 0.0; w_de = -1.0; rhobg = 1.0; virlevel = -1; comove=0; H=100.0;//value of Hubble flow in h 1 km/s/Mpc MassValue=1.0; inputtype=IOGADGET; num_files=1; nsnapread=1; fname=outname=smname=pname=gname=outname=NULL; Bsize=32; Nvel=32; Nsearch=256; Ncellfac=0.01; iSubSearch=1; partsearchtype=PSTALL; for (int i=0;i<NPARTTYPES;i++)numpart[i]=0; foftype=FOFSTPROB; gridtype=PHYSENGRID; fofbgtype=FOF6D; idenvflag=0; iBaryonSearch=0; icmrefadjust=1; iIterateCM = 1; iLocalVelDenApproxCalcFlag = 1 ; Neff=-1; ellthreshold=1.5; thetaopen=0.05; Vratio=1.25; ellphys=0.2; MinSize=20; HaloMinSize=-1; siglevel=2.0; ellvel=0.5; ellxscale=ellvscale=1.0; ellhalophysfac=ellhalovelfac=1.0; ellhalo6dxfac=1.0; ellhalo6dvfac=1.25; ellhalo3dxfac=-1.0; iiterflag=0; ellfac=2.5; ellxfac=3.0; vfac=1.0; thetafac=1.0; nminfac=0.5; fmerge=0.25; HaloMergerSize=10000; HaloMergerRatio=0.2; HaloVelDispScale=0; fmergebg=0.5; iSingleHalo=0; iBoundHalos=0; iInclusiveHalo=0; iKeepFOF=0; iSortByBindingEnergy=1; iPropertyReferencePosition=PROPREFCM; ParticleTypeForRefenceFrame=-1; iLargerCellSearch=0; iHaloCoreSearch=0; iAdaptiveCoreLinking=0; iPhaseCoreGrowth=1; maxnlevelcoresearch=5; halocorexfac=0.5; halocorevfac=2.0; halocorenfac=0.1; halocoresigmafac=2.0; halocorenumloops=3; halocorexfaciter=0.75; halocorevfaciter=0.75; halocorenumfaciter=1.0; halocorephasedistsig=2.0; coresubmergemindist=0.0; iverbose=0; iwritefof=0; iseparatefiles=0; ibinaryout=0; iextendedoutput=0; isubfindoutput=0; inoidoutput=0; icomoveunit=0; icosmologicalin=1; iextrahalooutput=0; iextragasoutput=0; iextrastaroutput=0; iextrainterloperoutput=0; isubfindproperties=0; iusedmparticles=1; iusegasparticles=1; iusestarparticles=1; iusesinkparticles=1; iusewindparticles=0; iusetracerparticles=0; #ifdef HIGHRES iuseextradarkparticles=1; #else iuseextradarkparticles=0; #endif snapshotvalue=0; gnsphblocks=4; gnstarblocks=2; gnbhblocks=2; iScaleLengths=0; inputbufsize=100000; mpiparticletotbufsize=-1; mpiparticlebufsize=-1; lengthtokpc=-1.0; velocitytokms=-1.0; masstosolarmass=-1.0; #if defined(GASON) || defined(STARON) || defined(BHON) SFRtosolarmassperyear=-1.0; stellaragetoyrs=-1.0; metallicitytosolar=-1.0; #endif lengthtokpc30pow2=30.0*30.0; lengthtokpc50pow2=50.0*50.0; SphericalOverdensitySeachFac=2.5; SphericalOverdensityMinHaloFac=0.05; iSphericalOverdensityPartList=0; mpipartfac=0.1; #if USEHDF ihdfnameconvention=-1; #endif iaperturecalc=0; aperturenum=0; apertureprojnum=0; SOnum=0; iprofilecalc=0; iprofilenorm=PROFILERNORMR200CRIT; iprofilebintype=PROFILERBINTYPELOG; iprofilecumulative=0; profilenbins=0; #ifdef USEOPENMP iopenmpfof = 1; openmpfofsize = ompfofsearchnum; #endif } }; struct ConfigInfo{ //list the name of the info vector<string> nameinfo; //vector<float> datainfo; vector<string> datainfo; //vector<int> datatype; ConfigInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER //general search operations nameinfo.push_back("Particle_search_type"); datainfo.push_back(to_string(opt.partsearchtype)); nameinfo.push_back("FoF_search_type"); datainfo.push_back(to_string(opt.foftype)); nameinfo.push_back("FoF_Field_search_type"); datainfo.push_back(to_string(opt.fofbgtype)); nameinfo.push_back("Search_for_substructure"); datainfo.push_back(to_string(opt.iSubSearch)); nameinfo.push_back("Keep_FOF"); datainfo.push_back(to_string(opt.iKeepFOF)); nameinfo.push_back("Iterative_searchflag"); datainfo.push_back(to_string(opt.iiterflag)); nameinfo.push_back("Unbind_flag"); datainfo.push_back(to_string(opt.uinfo.unbindflag)); nameinfo.push_back("Baryon_searchflag"); datainfo.push_back(to_string(opt.iBaryonSearch)); nameinfo.push_back("CMrefadjustsubsearch_flag"); datainfo.push_back(to_string(opt.icmrefadjust)); nameinfo.push_back("Halo_core_search"); datainfo.push_back(to_string(opt.iHaloCoreSearch)); nameinfo.push_back("Use_adaptive_core_search"); datainfo.push_back(to_string(opt.iAdaptiveCoreLinking)); nameinfo.push_back("Use_phase_tensor_core_growth"); datainfo.push_back(to_string(opt.iPhaseCoreGrowth)); //local field parameters nameinfo.push_back("Cell_fraction"); datainfo.push_back(to_string(opt.Ncellfac)); nameinfo.push_back("Grid_type"); datainfo.push_back(to_string(opt.gridtype)); nameinfo.push_back("Nsearch_velocity"); datainfo.push_back(to_string(opt.Nvel)); nameinfo.push_back("Nsearch_physical"); datainfo.push_back(to_string(opt.Nsearch)); //substructure search parameters nameinfo.push_back("Outlier_threshold"); datainfo.push_back(to_string(opt.ellthreshold)); nameinfo.push_back("Significance_level"); datainfo.push_back(to_string(opt.siglevel)); nameinfo.push_back("Velocity_ratio"); datainfo.push_back(to_string(opt.Vratio)); nameinfo.push_back("Velocity_opening_angle"); datainfo.push_back(to_string(opt.thetaopen)); ///\todo this configuration option will be deprecated. Replaced by Substructure_physical_linking_length //nameinfo.push_back("Physical_linking_length"); //datainfo.push_back(to_string(opt.ellphys)); nameinfo.push_back("Substructure_physical_linking_length"); datainfo.push_back(to_string(opt.ellphys)); nameinfo.push_back("Velocity_linking_length"); datainfo.push_back(to_string(opt.ellvel)); nameinfo.push_back("Minimum_size"); datainfo.push_back(to_string(opt.MinSize)); //field object specific searches nameinfo.push_back("Minimum_halo_size"); datainfo.push_back(to_string(opt.HaloMinSize)); ///\todo this configuration option will be deprecated. Replaced by Halo_3D_physical_linking_length //nameinfo.push_back("Halo_linking_length_factor"); //datainfo.push_back(to_string(opt.ellhalophysfac)); nameinfo.push_back("Halo_3D_linking_length"); datainfo.push_back(to_string(opt.ellhalo3dxfac)); nameinfo.push_back("Halo_velocity_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalovelfac)); //specific to 6DFOF field search nameinfo.push_back("Halo_6D_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalo6dxfac)); nameinfo.push_back("Halo_6D_vel_linking_length_factor"); datainfo.push_back(to_string(opt.ellhalo6dvfac)); //specific search for 6d fof core searches nameinfo.push_back("Halo_core_ellx_fac"); datainfo.push_back(to_string(opt.halocorexfac)); nameinfo.push_back("Halo_core_ellv_fac"); datainfo.push_back(to_string(opt.halocorevfac)); nameinfo.push_back("Halo_core_ncellfac"); datainfo.push_back(to_string(opt.halocorenfac)); nameinfo.push_back("Halo_core_adaptive_sigma_fac"); datainfo.push_back(to_string(opt.halocoresigmafac)); nameinfo.push_back("Halo_core_num_loops"); datainfo.push_back(to_string(opt.halocorenumloops)); nameinfo.push_back("Halo_core_loop_ellx_fac"); datainfo.push_back(to_string(opt.halocorexfaciter)); nameinfo.push_back("Halo_core_loop_ellv_fac"); datainfo.push_back(to_string(opt.halocorevfaciter)); nameinfo.push_back("Halo_core_loop_elln_fac"); datainfo.push_back(to_string(opt.halocorenumfaciter)); nameinfo.push_back("Halo_core_phase_significance"); datainfo.push_back(to_string(opt.halocorephasedistsig)); //for changing factors used in iterative search nameinfo.push_back("Iterative_threshold_factor"); datainfo.push_back(to_string(opt.ellfac)); nameinfo.push_back("Iterative_linking_length_factor"); datainfo.push_back(to_string(opt.ellxfac)); nameinfo.push_back("Iterative_Vratio_factor"); datainfo.push_back(to_string(opt.vfac)); nameinfo.push_back("Iterative_ThetaOp_factor"); datainfo.push_back(to_string(opt.thetafac)); //for changing effective resolution when rescaling linking lengh nameinfo.push_back("Effective_resolution"); datainfo.push_back(to_string(opt.Neff)); //for changing effective resolution when rescaling linking lengh nameinfo.push_back("Singlehalo_search"); datainfo.push_back(to_string(opt.iSingleHalo)); //units, cosmology nameinfo.push_back("Length_unit"); datainfo.push_back(to_string(opt.lengthinputconversion)); nameinfo.push_back("Velocity_unit"); datainfo.push_back(to_string(opt.velocityinputconversion)); nameinfo.push_back("Mass_unit"); datainfo.push_back(to_string(opt.massinputconversion)); nameinfo.push_back("Length_input_unit_conversion_to_output_unit"); datainfo.push_back(to_string(opt.lengthinputconversion)); nameinfo.push_back("Velocity_input_unit_conversion_to_output_unit"); datainfo.push_back(to_string(opt.velocityinputconversion)); nameinfo.push_back("Mass_input_unit_conversion_to_output_unit"); datainfo.push_back(to_string(opt.massinputconversion)); nameinfo.push_back("Star_formation_rate_input_unit_conversion_to_output_unit"); datainfo.push_back(to_string(opt.SFRinputconversion)); nameinfo.push_back("Metallicity_input_unit_conversion_to_output_unit"); datainfo.push_back(to_string(opt.metallicityinputconversion)); nameinfo.push_back("Stellar_age_input_is_cosmological_scalefactor"); datainfo.push_back(to_string(opt.istellaragescalefactor)); nameinfo.push_back("Hubble_unit"); datainfo.push_back(to_string(opt.H)); nameinfo.push_back("Gravity"); datainfo.push_back(to_string(opt.G)); nameinfo.push_back("Mass_value"); datainfo.push_back(to_string(opt.MassValue)); nameinfo.push_back("Length_unit_to_kpc"); datainfo.push_back(to_string(opt.lengthtokpc)); nameinfo.push_back("Velocity_to_kms"); datainfo.push_back(to_string(opt.velocitytokms)); nameinfo.push_back("Mass_to_solarmass"); datainfo.push_back(to_string(opt.masstosolarmass)); nameinfo.push_back("Star_formation_rate_to_solarmassperyear"); datainfo.push_back(to_string(opt.SFRtosolarmassperyear)); nameinfo.push_back("Metallicity_to_solarmetallicity"); datainfo.push_back(to_string(opt.metallicitytosolar)); nameinfo.push_back("Stellar_age_to_yr"); datainfo.push_back(to_string(opt.stellaragetoyrs)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); nameinfo.push_back("Scale_factor"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("h_val"); datainfo.push_back(to_string(opt.h)); nameinfo.push_back("Omega_m"); datainfo.push_back(to_string(opt.Omega_m)); nameinfo.push_back("Omega_Lambda"); datainfo.push_back(to_string(opt.Omega_Lambda)); nameinfo.push_back("Critical_density"); datainfo.push_back(to_string(opt.rhobg)); nameinfo.push_back("Virial_density"); datainfo.push_back(to_string(opt.virlevel)); nameinfo.push_back("Omega_cdm"); datainfo.push_back(to_string(opt.Omega_cdm)); nameinfo.push_back("Omega_b"); datainfo.push_back(to_string(opt.Omega_b)); nameinfo.push_back("Omega_r"); datainfo.push_back(to_string(opt.Omega_r)); nameinfo.push_back("Omega_nu"); datainfo.push_back(to_string(opt.Omega_nu)); nameinfo.push_back("Omega_DE"); datainfo.push_back(to_string(opt.Omega_de)); nameinfo.push_back("w_of_DE"); datainfo.push_back(to_string(opt.w_de)); //unbinding nameinfo.push_back("Softening_length"); datainfo.push_back(to_string(opt.uinfo.eps)); nameinfo.push_back("Allowed_kinetic_potential_ratio"); datainfo.push_back(to_string(opt.uinfo.Eratio)); nameinfo.push_back("Min_bound_mass_frac"); datainfo.push_back(to_string(opt.uinfo.minEfrac)); nameinfo.push_back("Bound_halos"); datainfo.push_back(to_string(opt.iBoundHalos)); nameinfo.push_back("Keep_background_potential"); datainfo.push_back(to_string(opt.uinfo.bgpot)); nameinfo.push_back("Kinetic_reference_frame_type"); datainfo.push_back(to_string(opt.uinfo.cmvelreftype)); nameinfo.push_back("Min_npot_ref"); datainfo.push_back(to_string(opt.uinfo.Npotref)); nameinfo.push_back("Frac_pot_ref"); datainfo.push_back(to_string(opt.uinfo.fracpotref)); nameinfo.push_back("Unbinding_type"); datainfo.push_back(to_string(opt.uinfo.unbindtype)); //property related nameinfo.push_back("Inclusive_halo_masses"); datainfo.push_back(to_string(opt.iInclusiveHalo)); nameinfo.push_back("Extensive_halo_properties_output"); datainfo.push_back(to_string(opt.iextrahalooutput)); nameinfo.push_back("Extensive_gas_properties_output"); datainfo.push_back(to_string(opt.iextragasoutput)); nameinfo.push_back("Iterate_cm_flag"); datainfo.push_back(to_string(opt.iIterateCM)); nameinfo.push_back("Sort_by_binding_energy"); datainfo.push_back(to_string(opt.iSortByBindingEnergy)); //other options nameinfo.push_back("Verbose"); datainfo.push_back(to_string(opt.iverbose)); nameinfo.push_back("Write_group_array_file"); datainfo.push_back(to_string(opt.iwritefof)); nameinfo.push_back("Snapshot_value"); datainfo.push_back(to_string(opt.snapshotvalue)); //io related nameinfo.push_back("Cosmological_input"); datainfo.push_back(to_string(opt.icosmologicalin)); nameinfo.push_back("Input_chunk_size"); datainfo.push_back(to_string(opt.inputbufsize)); nameinfo.push_back("MPI_particle_total_buf_size"); datainfo.push_back(to_string(opt.mpiparticletotbufsize)); nameinfo.push_back("Separate_output_files"); datainfo.push_back(to_string(opt.iseparatefiles)); nameinfo.push_back("Binary_output"); datainfo.push_back(to_string(opt.ibinaryout)); nameinfo.push_back("Comoving_units"); datainfo.push_back(to_string(opt.icomoveunit)); nameinfo.push_back("Extended_output"); datainfo.push_back(to_string(opt.iextendedoutput)); //gadget io related to extra info for sph, stars, bhs, nameinfo.push_back("NSPH_extra_blocks"); datainfo.push_back(to_string(opt.gnsphblocks)); nameinfo.push_back("NStar_extra_blocks"); datainfo.push_back(to_string(opt.gnstarblocks)); nameinfo.push_back("NBH_extra_blocks"); datainfo.push_back(to_string(opt.gnbhblocks)); //mpi related configuration nameinfo.push_back("MPI_part_allocation_fac"); datainfo.push_back(to_string(opt.mpiparticletotbufsize)); #endif } }; struct SimInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; SimInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); if (opt.icosmologicalin) { nameinfo.push_back("ScaleFactor"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("h_val"); datainfo.push_back(to_string(opt.h)); nameinfo.push_back("Omega_m"); datainfo.push_back(to_string(opt.Omega_m)); nameinfo.push_back("Omega_Lambda"); datainfo.push_back(to_string(opt.Omega_Lambda)); nameinfo.push_back("Omega_cdm"); datainfo.push_back(to_string(opt.Omega_cdm)); nameinfo.push_back("Omega_b"); datainfo.push_back(to_string(opt.Omega_b)); nameinfo.push_back("w_of_DE"); datainfo.push_back(to_string(opt.w_de)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); nameinfo.push_back("Hubble_unit"); datainfo.push_back(to_string(opt.H)); } else{ nameinfo.push_back("Time"); datainfo.push_back(to_string(opt.a)); nameinfo.push_back("Period"); datainfo.push_back(to_string(opt.p)); } //units nameinfo.push_back("Length_unit"); datainfo.push_back(to_string(opt.lengthinputconversion)); nameinfo.push_back("Velocity_unit"); datainfo.push_back(to_string(opt.velocityinputconversion)); nameinfo.push_back("Mass_unit"); datainfo.push_back(to_string(opt.massinputconversion)); nameinfo.push_back("Gravity"); datainfo.push_back(to_string(opt.G)); #ifdef NOMASS nameinfo.push_back("Mass_value"); datainfo.push_back(to_string(opt.MassValue)); #endif #endif } }; struct UnitInfo{ //list the name of the info vector<string> nameinfo; vector<string> datainfo; UnitInfo(Options &opt){ //if compiler is super old and does not have at least std 11 implementation to_string does not exist #ifndef OLDCCOMPILER nameinfo.push_back("Cosmological_Sim"); datainfo.push_back(to_string(opt.icosmologicalin)); nameinfo.push_back("Comoving_or_Physical"); datainfo.push_back(to_string(opt.icomoveunit)); //units nameinfo.push_back("Length_unit_to_kpc"); datainfo.push_back(to_string(opt.lengthtokpc)); nameinfo.push_back("Velocity_unit_to_kms"); datainfo.push_back(to_string(opt.velocitytokms)); nameinfo.push_back("Mass_unit_to_solarmass"); datainfo.push_back(to_string(opt.masstosolarmass)); #if defined(GASON) || defined(STARON) || defined(BHON) nameinfo.push_back("Metallicity_unit_to_solar"); datainfo.push_back(to_string(opt.metallicitytosolar)); nameinfo.push_back("SFR_unit_to_solarmassperyear"); datainfo.push_back(to_string(opt.SFRtosolarmassperyear)); nameinfo.push_back("Stellar_age_unit_to_yr"); datainfo.push_back(to_string(opt.stellaragetoyrs)); #endif #endif } }; /// N-dim grid cell struct GridCell { int ndim; Int_t gid; //middle of cell, and boundaries of cell Double_t xm[6], xbl[6],xbu[6]; //mass, radial size of in cell Double_t mass, rsize; //number of particles in cell Int_t nparts,*nindex; //neighbouring grid cells and distance from cell centers Int_t nnidcells[MAXNGRID]; Double_t nndist[MAXNGRID]; Double_t den; GridCell(int N=3){ ndim=N; nparts=0; den=0; } ~GridCell(){ if (nparts>0)delete nindex; } }; /*! structure stores bulk properties like \f$ m,\ (x,y,z)_{\rm cm},\ (vx,vy,vz)_{\rm cm},\ V_{\rm max},\ R_{\rm max}, \f$ which is calculated in \ref substructureproperties.cxx */ struct PropData { ///\name order in structure hierarchy and number of subhaloes //@{ long long haloid,hostid,directhostid, hostfofid; Int_t numsubs; //@} ///\name properties of total object including DM, gas, stars, bh, etc //@{ ///number of particles Int_t num; ///number of particles in FOF envelop Int_t gNFOF,gN6DFOF; ///centre of mass Coordinate gcm, gcmvel; ///Position of most bound particle, and also of particle with min potential Coordinate gposmbp, gvelmbp, gposminpot, gvelminpot; ///\name physical properties regarding mass, size //@{ Double_t gmass,gsize,gMvir,gRvir,gRcm,gRmbp,gRminpot,gmaxvel,gRmaxvel,gMmaxvel,gRhalfmass,gMassTwiceRhalfmass; Double_t gM200c,gR200c,gM200m,gR200m,gMFOF,gM6DFOF,gM500c,gR500c,gMBN98,gRBN98; //to store exclusive masses of halo ignoring substructure Double_t gMvir_excl,gRvir_excl,gM200c_excl,gR200c_excl,gM200m_excl,gR200m_excl,gMBN98_excl,gRBN98_excl; //@} ///\name physical properties for shape/mass distribution //@{ ///axis ratios Double_t gq,gs; ///eigenvector Matrix geigvec; //@} ///\name physical properties for velocity //@{ ///velocity dispersion Double_t gsigma_v; ///dispersion tensor Matrix gveldisp; //@} ///physical properties for dynamical state Double_t Efrac,Pot,T; ///physical properties for angular momentum Coordinate gJ; Coordinate gJ200m, gJ200c, gJBN98; ///physical properties for angular momentum exclusive Coordinate gJ200m_excl, gJ200c_excl, gJBN98_excl; ///Keep track of position of least unbound particle and most bound particle pid and minimum potential Int_t iunbound,ibound, iminpot; ///Type of structure int stype; ///concentration (and related quantity used to calculate a concentration) Double_t cNFW, VmaxVvir2; ///Bullock & Peebles spin parameters Double_t glambda_B,glambda_P; ///measure of rotational support Double_t Krot; //@} ///\name halo properties within RVmax //@{ Double_t RV_q,RV_s; Matrix RV_eigvec; Double_t RV_sigma_v; Matrix RV_veldisp; Coordinate RV_J; Double_t RV_lambda_B,RV_lambda_P; Double_t RV_Krot; //@} ///\name radial profiles //@{ vector<unsigned int> aperture_npart; vector<float> aperture_mass; vector<float> aperture_veldisp; vector<float> aperture_vrdisp; vector<float> aperture_rhalfmass; vector<Coordinate> aperture_mass_proj; vector<Coordinate> aperture_rhalfmass_proj; vector<Coordinate> aperture_L; vector<unsigned int> profile_npart; vector<unsigned int> profile_npart_inclusive; vector<float> profile_mass; vector<float> profile_mass_inclusive; vector<Coordinate> profile_L; #if defined(GASON) || defined(STARON) || defined(BHON) vector<unsigned int> aperture_npart_dm; vector<float> aperture_mass_dm; vector<float> aperture_veldisp_dm; vector<float> aperture_vrdisp_dm; vector<float> aperture_rhalfmass_dm; #endif //@} vector<Double_t> SO_mass, SO_radius; vector<Coordinate> SO_angularmomentum; #ifdef GASON ///\name gas specific quantities //@{ ///number of particles int n_gas; ///mass Double_t M_gas, M_gas_rvmax, M_gas_30kpc, M_gas_50kpc, M_gas_500c; ///mass in spherical overdensities Double_t M_200crit_gas, M_200mean_gas, M_BN98_gas; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas, M_200mean_excl_gas, M_BN98_excl_gas; ///pos/vel info Coordinate cm_gas,cmvel_gas; ///velocity/angular momentum info Double_t Krot_gas; Coordinate L_gas; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas, L_200mean_gas, L_BN98_gas; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas, L_200mean_excl_gas, L_BN98_excl_gas; //dispersion Matrix veldisp_gas; ///morphology Double_t MassTwiceRhalfmass_gas, Rhalfmass_gas, q_gas, s_gas; Matrix eigvec_gas; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas, Z_gas, SFR_gas; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas, Z_mean_gas, SFR_mean_gas; ///physical properties for dynamical state Double_t Efrac_gas, Pot_gas, T_gas; //@} ///\name gas radial profiles //@{ vector<unsigned int> aperture_npart_gas; vector<float> aperture_mass_gas; vector<float> aperture_veldisp_gas; vector<float> aperture_vrdisp_gas; vector<float> aperture_SFR_gas; vector<float> aperture_rhalfmass_gas; vector<Coordinate> aperture_mass_proj_gas; vector<Coordinate> aperture_rhalfmass_proj_gas; vector<Coordinate> aperture_SFR_proj_gas; vector<Coordinate> aperture_L_gas; vector<unsigned int> profile_npart_gas; vector<unsigned int> profile_npart_inclusive_gas; vector<float> profile_mass_gas; vector<float> profile_mass_inclusive_gas; vector<Coordinate> profile_L_gas; //@} vector<Double_t> SO_mass_gas; vector<Coordinate> SO_angularmomentum_gas; #ifdef STARON ///\name star forming gas specific quantities //@{ ///number of particles int n_gas_sf; ///mass Double_t M_gas_sf, M_gas_sf_rvmax,M_gas_sf_30kpc,M_gas_sf_50kpc, M_gas_sf_500c; ///mass in spherical overdensities Double_t M_200crit_gas_sf, M_200mean_gas_sf, M_BN98_gas_sf; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas_sf, M_200mean_excl_gas_sf, M_BN98_excl_gas_sf; ///velocity/angular momentum info Double_t Krot_gas_sf; Coordinate L_gas_sf; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas_sf, L_200mean_gas_sf, L_BN98_gas_sf; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas_sf, L_200mean_excl_gas_sf, L_BN98_excl_gas_sf; //dispersion Double_t sigV_gas_sf; ///morphology Double_t MassTwiceRhalfmass_gas_sf, Rhalfmass_gas_sf, q_gas_sf, s_gas_sf; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas_sf, Z_gas_sf, SFR_gas_sf; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas_sf, Z_mean_gas_sf, SFR_mean_gas_sf; //@} ///\name gas star forming radial profiles //@{ vector<unsigned int> aperture_npart_gas_sf; vector<float> aperture_mass_gas_sf; vector<float> aperture_veldisp_gas_sf; vector<float> aperture_vrdisp_gas_sf; vector<float> aperture_rhalfmass_gas_sf; vector<Coordinate> aperture_mass_proj_gas_sf; vector<Coordinate> aperture_rhalfmass_proj_gas_sf; vector<Coordinate> aperture_L_gas_sf; vector<unsigned int> profile_npart_gas_sf; vector<unsigned int> profile_npart_inclusive_gas_sf; vector<float> profile_mass_gas_sf; vector<float> profile_mass_inclusive_gas_sf; vector<Coordinate> profile_L_gas_sf; //@} vector<Double_t> SO_mass_gas_sf; vector<Coordinate> SO_angularmomentum_gas_sf; ///\name star forming gas specific quantities //@{ ///number of particles int n_gas_nsf; ///mass Double_t M_gas_nsf, M_gas_nsf_rvmax,M_gas_nsf_30kpc,M_gas_nsf_50kpc, M_gas_nsf_500c; ///mass in spherical overdensities Double_t M_200crit_gas_nsf, M_200mean_gas_nsf, M_BN98_gas_nsf; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_gas_nsf, M_200mean_excl_gas_nsf, M_BN98_excl_gas_nsf; ///velocity/angular momentum info Double_t Krot_gas_nsf; Coordinate L_gas_nsf; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_gas_nsf, L_200mean_gas_nsf, L_BN98_gas_nsf; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_gas_nsf, L_200mean_excl_gas_nsf, L_BN98_excl_gas_nsf; //dispersion Double_t sigV_gas_nsf; ///morphology Double_t MassTwiceRhalfmass_gas_nsf, Rhalfmass_gas_nsf, q_gas_nsf, s_gas_nsf; ///mass weighted sum of temperature, metallicty, star formation rate Double_t Temp_gas_nsf, Z_gas_nsf; ///mean temperature,metallicty,star formation rate Double_t Temp_mean_gas_nsf, Z_mean_gas_nsf; //@} ///\name gas star forming radial profiles //@{ vector<unsigned int> aperture_npart_gas_nsf; vector<float> aperture_mass_gas_nsf; vector<float> aperture_veldisp_gas_nsf; vector<float> aperture_vrdisp_gas_nsf; vector<float> aperture_rhalfmass_gas_nsf; vector<Coordinate> aperture_mass_proj_gas_nsf; vector<Coordinate> aperture_rhalfmass_proj_gas_nsf; vector<Coordinate> aperture_L_gas_nsf; vector<unsigned int> profile_npart_gas_nsf; vector<unsigned int> profile_npart_inclusive_gas_nsf; vector<float> profile_mass_gas_nsf; vector<float> profile_mass_inclusive_gas_nsf; vector<Coordinate> profile_L_gas_nsf; //@} vector<Double_t> SO_mass_gas_nsf; vector<Coordinate> SO_angularmomentum_gas_nsf; #endif #endif #ifdef STARON ///\name star specific quantities //@{ ///number of particles int n_star; ///mass Double_t M_star, M_star_rvmax, M_star_30kpc, M_star_50kpc, M_star_500c; ///mass in spherical overdensities Double_t M_200crit_star, M_200mean_star, M_BN98_star; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_star, M_200mean_excl_star, M_BN98_excl_star; ///pos/vel info Coordinate cm_star,cmvel_star; ///velocity/angular momentum info Double_t Krot_star; Coordinate L_star; ///physical properties for angular momentum (can be inclusive or exclusive ) Coordinate L_200crit_star, L_200mean_star, L_BN98_star; ///physical properties for angular momentum exclusiveto object Coordinate L_200crit_excl_star, L_200mean_excl_star, L_BN98_excl_star; Matrix veldisp_star; ///morphology Double_t MassTwiceRhalfmass_star, Rhalfmass_star,q_star,s_star; Matrix eigvec_star; ///mean age,metallicty Double_t t_star,Z_star; ///mean age,metallicty Double_t t_mean_star,Z_mean_star; ///physical properties for dynamical state Double_t Efrac_star,Pot_star,T_star; //@} ///\name stellar radial profiles //@{ vector<unsigned int> aperture_npart_star; vector<float> aperture_mass_star; vector<float> aperture_veldisp_star; vector<float> aperture_vrdisp_star; vector<float> aperture_rhalfmass_star; vector<Coordinate> aperture_mass_proj_star; vector<Coordinate> aperture_rhalfmass_proj_star; vector<Coordinate> aperture_L_star; vector<unsigned int> profile_npart_star; vector<unsigned int> profile_npart_inclusive_star; vector<float> profile_mass_star; vector<float> profile_mass_inclusive_star; vector<Coordinate> profile_L_star; //@} vector<Double_t> SO_mass_star; vector<Coordinate> SO_angularmomentum_star; #endif #ifdef BHON ///\name black hole specific quantities //@{ ///number of BH int n_bh; ///mass Double_t M_bh, M_bh_mostmassive; ///mean accretion rate, metallicty Double_t acc_bh, acc_bh_mostmassive; ///\name blackhole aperture/radial profiles //@{ vector<int> aperture_npart_bh; vector<float> aperture_mass_bh; vector<Coordinate> aperture_L_bh; //@} vector<Double_t> SO_mass_bh; vector<Coordinate> SO_angularmomentum_bh; //@} #endif #ifdef HIGHRES ///\name low resolution interloper particle specific quantities //@{ ///number of interloper low res particles int n_interloper; ///mass Double_t M_interloper; ///mass in spherical overdensities Double_t M_200crit_interloper, M_200mean_interloper, M_BN98_interloper; ///mass in spherical overdensities inclusive of all masses Double_t M_200crit_excl_interloper, M_200mean_excl_interloper, M_BN98_excl_interloper; vector<unsigned int> aperture_npart_interloper; vector<float> aperture_mass_interloper; vector<unsigned int> profile_npart_interloper; vector<unsigned int> profile_npart_inclusive_interloper; vector<float> profile_mass_interloper; vector<float> profile_mass_inclusive_interloper; vector<Double_t> SO_mass_interloper; //@} #endif PropData() { num=gNFOF=gN6DFOF=0; gmass=gsize=gRmbp=gmaxvel=gRmaxvel=gRvir=gR200m=gR200c=gRhalfmass=gMassTwiceRhalfmass=Efrac=Pot=T=0.; gMFOF=gM6DFOF=0; gM500c=gR500c=0; gMBN98=gRBN98=0; gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.; gJ[0]=gJ[1]=gJ[2]=0; gJ200m[0]=gJ200m[1]=gJ200m[2]=0; gJ200c[0]=gJ200c[1]=gJ200c[2]=0; gJBN98[0]=gJBN98[1]=gJBN98[2]=0; gveldisp=Matrix(0.); gq=gs=1.0; Krot=0.; gM200m_excl=gM200c_excl=gMBN98_excl=0; gR200m_excl=gR200c_excl=gRBN98_excl=0; gJ200m_excl[0]=gJ200m_excl[1]=gJ200m_excl[2]=0; gJ200c_excl[0]=gJ200c_excl[1]=gJ200c_excl[2]=0; gJBN98_excl[0]=gJBN98_excl[1]=gJBN98_excl[2]=0; RV_sigma_v=0; RV_q=RV_s=1.; RV_J[0]=RV_J[1]=RV_J[2]=0; RV_veldisp=Matrix(0.); RV_eigvec=Matrix(0.); RV_lambda_B=RV_lambda_P=RV_Krot=0; #ifdef GASON M_gas_rvmax=M_gas_30kpc=M_gas_50kpc=0; n_gas=M_gas=Efrac_gas=0; cm_gas[0]=cm_gas[1]=cm_gas[2]=cmvel_gas[0]=cmvel_gas[1]=cmvel_gas[2]=0.; L_gas[0]=L_gas[1]=L_gas[2]=0; q_gas=s_gas=1.0; MassTwiceRhalfmass_gas=Rhalfmass_gas=0; eigvec_gas=Matrix(1,0,0,0,1,0,0,0,1); Temp_gas=Z_gas=SFR_gas=0.0; Temp_mean_gas=Z_mean_gas=SFR_mean_gas=0.0; veldisp_gas=Matrix(0.); Krot_gas=T_gas=Pot_gas=0; M_200mean_gas=M_200crit_gas=M_BN98_gas=0; M_200mean_excl_gas=M_200crit_excl_gas=M_BN98_excl_gas=0; L_200crit_gas[0]=L_200crit_gas[1]=L_200crit_gas[2]=0; L_200mean_gas[0]=L_200mean_gas[1]=L_200mean_gas[2]=0; L_BN98_gas[0]=L_BN98_gas[1]=L_BN98_gas[2]=0; L_200crit_excl_gas[0]=L_200crit_excl_gas[1]=L_200crit_excl_gas[2]=0; L_200mean_excl_gas[0]=L_200mean_excl_gas[1]=L_200mean_excl_gas[2]=0; L_BN98_excl_gas[0]=L_BN98_excl_gas[1]=L_BN98_excl_gas[2]=0; #ifdef STARON M_gas_sf=M_gas_sf_rvmax=M_gas_sf_30kpc=M_gas_sf_50kpc=0; L_gas_sf[0]=L_gas_sf[1]=L_gas_sf[2]=0; q_gas_sf=s_gas_sf=1.0; MassTwiceRhalfmass_gas_sf=Rhalfmass_gas_sf=0; Temp_gas_sf=Z_gas_sf=0.0; Temp_mean_gas_sf=Z_mean_gas_sf=0.0; sigV_gas_sf=0; M_200mean_gas_sf=M_200crit_gas_sf=M_BN98_gas_sf=0; M_200mean_excl_gas_sf=M_200crit_excl_gas_sf=M_BN98_excl_gas_sf=0; L_200crit_gas_sf[0]=L_200crit_gas_sf[1]=L_200crit_gas_sf[2]=0; L_200mean_gas_sf[0]=L_200mean_gas_sf[1]=L_200mean_gas_sf[2]=0; L_BN98_gas_sf[0]=L_BN98_gas_sf[1]=L_BN98_gas_sf[2]=0; L_200crit_excl_gas_sf[0]=L_200crit_excl_gas_sf[1]=L_200crit_excl_gas_sf[2]=0; L_200mean_excl_gas_sf[0]=L_200mean_excl_gas_sf[1]=L_200mean_excl_gas_sf[2]=0; L_BN98_excl_gas_sf[0]=L_BN98_excl_gas_sf[1]=L_BN98_excl_gas_sf[2]=0; M_gas_nsf=M_gas_nsf_rvmax=M_gas_nsf_30kpc=M_gas_nsf_50kpc=0; L_gas_nsf[0]=L_gas_nsf[1]=L_gas_nsf[2]=0; q_gas_nsf=s_gas_nsf=1.0; MassTwiceRhalfmass_gas_nsf=Rhalfmass_gas_nsf=0; Temp_gas_nsf=Z_gas_nsf=0.0; Temp_mean_gas_nsf=Z_mean_gas_nsf=0.0; sigV_gas_nsf=0; M_200mean_gas_nsf=M_200crit_gas_nsf=M_BN98_gas_nsf=0; M_200mean_excl_gas_nsf=M_200crit_excl_gas_nsf=M_BN98_excl_gas_nsf=0; L_200crit_gas_nsf[0]=L_200crit_gas_nsf[1]=L_200crit_gas_nsf[2]=0; L_200mean_gas_nsf[0]=L_200mean_gas_nsf[1]=L_200mean_gas_nsf[2]=0; L_BN98_gas_nsf[0]=L_BN98_gas_nsf[1]=L_BN98_gas_nsf[2]=0; L_200crit_excl_gas_nsf[0]=L_200crit_excl_gas_nsf[1]=L_200crit_excl_gas_nsf[2]=0; L_200mean_excl_gas_nsf[0]=L_200mean_excl_gas_nsf[1]=L_200mean_excl_gas_nsf[2]=0; L_BN98_excl_gas_nsf[0]=L_BN98_excl_gas_nsf[1]=L_BN98_excl_gas_nsf[2]=0; #endif #endif #ifdef STARON M_star_rvmax=M_star_30kpc=M_star_50kpc=0; n_star=M_star=Efrac_star=0; cm_star[0]=cm_star[1]=cm_star[2]=cmvel_star[0]=cmvel_star[1]=cmvel_star[2]=0.; L_star[0]=L_star[1]=L_star[2]=0; q_star=s_star=1.0; MassTwiceRhalfmass_star=Rhalfmass_star=0; eigvec_star=Matrix(1,0,0,0,1,0,0,0,1); t_star=Z_star=0.; t_mean_star=Z_mean_star=0.; veldisp_star=Matrix(0.); Krot_star=T_star=Pot_star=0; M_200mean_star=M_200crit_star=M_BN98_star=0; M_200mean_excl_star=M_200crit_excl_star=M_BN98_excl_star=0; L_200crit_star[0]=L_200crit_star[1]=L_200crit_star[2]=0; L_200mean_star[0]=L_200mean_star[1]=L_200mean_star[2]=0; L_BN98_star[0]=L_BN98_star[1]=L_BN98_star[2]=0; L_200crit_excl_star[0]=L_200crit_excl_star[1]=L_200crit_excl_star[2]=0; L_200mean_excl_star[0]=L_200mean_excl_star[1]=L_200mean_excl_star[2]=0; L_BN98_excl_star[0]=L_BN98_excl_star[1]=L_BN98_excl_star[2]=0; #endif #ifdef BHON n_bh=M_bh=0; M_bh_mostmassive=0; acc_bh=0; acc_bh_mostmassive=0; #endif #ifdef HIGHRES n_interloper=M_interloper=0; #endif } ///equals operator, useful if want inclusive information before substructure search PropData& operator=(const PropData &p){ num=p.num; gcm=p.gcm;gcmvel=p.gcmvel; gposmbp=p.gposmbp;gvelmbp=p.gvelmbp; gposminpot=p.gposminpot;gvelminpot=p.gvelminpot; gmass=p.gmass;gsize=p.gsize; gMvir=p.gMvir;gRvir=p.gRvir;gRmbp=p.gRmbp; gmaxvel=gmaxvel=p.gmaxvel;gRmaxvel=p.gRmaxvel;gMmaxvel=p.gMmaxvel; gM200c=p.gM200c;gR200c=p.gR200c; gM200m=p.gM200m;gR200m=p.gR200m; gM500c=p.gM500c;gR500c=p.gR500c; gMBN98=p.gMBN98;gRBN98=p.gRBN98; gNFOF=p.gNFOF; gMFOF=p.gMFOF; gM200c_excl=p.gM200c_excl;gR200c_excl=p.gR200c_excl; gM200m_excl=p.gM200m_excl;gR200m_excl=p.gR200m_excl; gMBN98_excl=p.gMBN98_excl;gRBN98_excl=p.gRBN98_excl; gJ=p.gJ; gJ200c=p.gJ200c; gJ200m=p.gJ200m; gJBN98=p.gJBN98; gJ200c_excl=p.gJ200c_excl; gJ200m_excl=p.gJ200m_excl; gJBN98_excl=p.gJBN98_excl; ///expand to copy all the gas, star, bh, stuff #ifdef GASON M_200mean_gas=p.M_200mean_gas; M_200crit_gas=p.M_200crit_gas; M_BN98_gas=p.M_BN98_gas; M_200mean_excl_gas=p.M_200mean_excl_gas; M_200crit_excl_gas=p.M_200crit_excl_gas; M_BN98_excl_gas=p.M_BN98_excl_gas; L_200mean_gas=p.L_200mean_gas; L_200crit_gas=p.L_200crit_gas; L_BN98_gas=p.L_BN98_gas; L_200mean_excl_gas=p.L_200mean_excl_gas; L_200crit_excl_gas=p.L_200crit_excl_gas; L_BN98_excl_gas=p.L_BN98_excl_gas; #ifdef STARON M_200mean_gas_sf=p.M_200mean_gas_sf; M_200crit_gas_sf=p.M_200crit_gas_sf; M_BN98_gas_sf=p.M_BN98_gas_sf; M_200mean_excl_gas_sf=p.M_200mean_excl_gas_sf; M_200crit_excl_gas_sf=p.M_200crit_excl_gas_sf; M_BN98_excl_gas_sf=p.M_BN98_excl_gas_sf; L_200mean_gas_sf=p.L_200mean_gas_sf; L_200crit_gas_sf=p.L_200crit_gas_sf; L_BN98_gas_sf=p.L_BN98_gas_sf; L_200mean_excl_gas_sf=p.L_200mean_excl_gas_sf; L_200crit_excl_gas_sf=p.L_200crit_excl_gas_sf; L_BN98_excl_gas_sf=p.L_BN98_excl_gas_sf; M_200mean_gas_nsf=p.M_200mean_gas_nsf; M_200crit_gas_nsf=p.M_200crit_gas_nsf; M_BN98_gas_nsf=p.M_BN98_gas_nsf; M_200mean_excl_gas_nsf=p.M_200mean_excl_gas_nsf; M_200crit_excl_gas_nsf=p.M_200crit_excl_gas_nsf; M_BN98_excl_gas_nsf=p.M_BN98_excl_gas_nsf; L_200mean_gas_nsf=p.L_200mean_gas_nsf; L_200crit_gas_nsf=p.L_200crit_gas_nsf; L_BN98_gas_nsf=p.L_BN98_gas_nsf; L_200mean_excl_gas_nsf=p.L_200mean_excl_gas_nsf; L_200crit_excl_gas_nsf=p.L_200crit_excl_gas_nsf; L_BN98_excl_gas_nsf=p.L_BN98_excl_gas_nsf; #endif #endif #ifdef STARON M_200mean_star=p.M_200mean_star; M_200crit_star=p.M_200crit_star; M_BN98_star=p.M_BN98_star; M_200mean_excl_star=p.M_200mean_excl_star; M_200crit_excl_star=p.M_200crit_excl_star; M_BN98_excl_star=p.M_BN98_excl_star; L_200mean_star=p.L_200mean_star; L_200crit_star=p.L_200crit_star; L_BN98_star=p.L_BN98_star; L_200mean_excl_star=p.L_200mean_excl_star; L_200crit_excl_star=p.L_200crit_excl_star; L_BN98_excl_star=p.L_BN98_excl_star; #endif aperture_npart=p.aperture_npart; aperture_mass=p.aperture_mass; aperture_veldisp=p.aperture_veldisp; aperture_vrdisp=p.aperture_vrdisp; aperture_rhalfmass=p.aperture_rhalfmass; #if defined(GASON) || defined(STARON) || defined(BHON) aperture_npart_dm=p.aperture_npart_dm; aperture_mass_dm=p.aperture_mass_dm; aperture_veldisp_dm=p.aperture_veldisp_dm; aperture_vrdisp_dm=p.aperture_vrdisp_dm; aperture_rhalfmass_dm=p.aperture_rhalfmass_dm; #endif #ifdef GASON aperture_npart_gas=p.aperture_npart_gas; aperture_mass_gas=p.aperture_mass_gas; aperture_veldisp_gas=p.aperture_veldisp_gas; aperture_rhalfmass_gas=p.aperture_rhalfmass_gas; #ifdef STARON aperture_SFR_gas=p.aperture_SFR_gas; aperture_npart_gas_sf=p.aperture_npart_gas_sf; aperture_npart_gas_nsf=p.aperture_npart_gas_nsf; aperture_mass_gas_sf=p.aperture_mass_gas_sf; aperture_mass_gas_nsf=p.aperture_mass_gas_nsf; aperture_veldisp_gas_sf=p.aperture_veldisp_gas_sf; aperture_veldisp_gas_nsf=p.aperture_veldisp_gas_nsf; aperture_vrdisp_gas_sf=p.aperture_vrdisp_gas_sf; aperture_vrdisp_gas_nsf=p.aperture_vrdisp_gas_nsf; aperture_rhalfmass_gas_sf=p.aperture_rhalfmass_gas_sf; aperture_rhalfmass_gas_nsf=p.aperture_rhalfmass_gas_nsf; #endif #endif #ifdef STARON aperture_npart_star=p.aperture_npart_star; aperture_mass_star=p.aperture_mass_star; aperture_veldisp_star=p.aperture_veldisp_star; aperture_vrdisp_star=p.aperture_vrdisp_star; aperture_rhalfmass_star=p.aperture_rhalfmass_star; #endif aperture_mass_proj=p.aperture_mass_proj; aperture_rhalfmass_proj=p.aperture_rhalfmass_proj; #ifdef GASON aperture_mass_proj_gas=p.aperture_mass_proj_gas; aperture_rhalfmass_proj_gas=p.aperture_rhalfmass_proj_gas; #ifdef STARON aperture_mass_proj_gas_sf=p.aperture_mass_proj_gas_sf; aperture_rhalfmass_proj_gas_nsf=p.aperture_rhalfmass_proj_gas_nsf; #endif #endif #ifdef STARON aperture_mass_proj_star=p.aperture_mass_proj_star; aperture_rhalfmass_proj_star=p.aperture_rhalfmass_proj_star; #endif profile_npart=p.profile_npart; profile_mass=p.profile_mass; profile_npart_inclusive=p.profile_npart_inclusive; profile_mass_inclusive=p.profile_mass_inclusive; #ifdef GASON profile_npart_gas=p.profile_npart_gas; profile_mass_gas=p.profile_mass_gas; profile_npart_inclusive_gas=p.profile_npart_inclusive_gas; profile_mass_inclusive_gas=p.profile_mass_inclusive_gas; #ifdef STARON profile_npart_gas_sf=p.profile_npart_gas_sf; profile_mass_gas_sf=p.profile_mass_gas_sf; profile_npart_inclusive_gas_sf=p.profile_npart_inclusive_gas_sf; profile_mass_inclusive_gas_sf=p.profile_mass_inclusive_gas_sf; profile_npart_gas_nsf=p.profile_npart_gas_nsf; profile_mass_gas_nsf=p.profile_mass_gas_nsf; profile_npart_inclusive_gas_nsf=p.profile_npart_inclusive_gas_nsf; profile_mass_inclusive_gas_nsf=p.profile_mass_inclusive_gas_nsf; #endif #endif #ifdef STARON profile_npart_star=p.profile_npart_star; profile_mass_star=p.profile_mass_star; profile_npart_inclusive_star=p.profile_npart_inclusive_star; profile_mass_inclusive_star=p.profile_mass_inclusive_star; #endif return *this; } //allocate memory for profiles void Allocate(Options &opt) { AllocateApertures(opt); AllocateProfiles(opt); AllocateSOs(opt); } void AllocateApertures(Options &opt) { if (opt.iaperturecalc && opt.aperturenum>0) { aperture_npart.resize(opt.aperturenum); aperture_mass.resize(opt.aperturenum); aperture_veldisp.resize(opt.aperturenum); aperture_vrdisp.resize(opt.aperturenum); aperture_rhalfmass.resize(opt.aperturenum); #ifdef GASON aperture_npart_gas.resize(opt.aperturenum); aperture_mass_gas.resize(opt.aperturenum); aperture_veldisp_gas.resize(opt.aperturenum); aperture_vrdisp_gas.resize(opt.aperturenum); aperture_rhalfmass_gas.resize(opt.aperturenum); #ifdef STARON aperture_SFR_gas.resize(opt.aperturenum); aperture_npart_gas_sf.resize(opt.aperturenum); aperture_npart_gas_nsf.resize(opt.aperturenum); aperture_mass_gas_sf.resize(opt.aperturenum); aperture_mass_gas_nsf.resize(opt.aperturenum); aperture_veldisp_gas_sf.resize(opt.aperturenum); aperture_veldisp_gas_nsf.resize(opt.aperturenum); aperture_vrdisp_gas_sf.resize(opt.aperturenum); aperture_vrdisp_gas_nsf.resize(opt.aperturenum); aperture_rhalfmass_gas_sf.resize(opt.aperturenum); aperture_rhalfmass_gas_nsf.resize(opt.aperturenum); #endif #endif #ifdef STARON aperture_npart_star.resize(opt.aperturenum); aperture_mass_star.resize(opt.aperturenum); aperture_veldisp_star.resize(opt.aperturenum); aperture_vrdisp_star.resize(opt.aperturenum); aperture_rhalfmass_star.resize(opt.aperturenum); #endif #ifdef HIGHRES aperture_npart_interloper.resize(opt.aperturenum); aperture_mass_interloper.resize(opt.aperturenum); #endif #if defined(GASON) || defined(STARON) || defined(BHON) //if searching all types, also store dm only aperture quantities if (opt.partsearchtype==PSTALL) { aperture_npart_dm.resize(opt.aperturenum); aperture_mass_dm.resize(opt.aperturenum); aperture_veldisp_dm.resize(opt.aperturenum); aperture_vrdisp_dm.resize(opt.aperturenum); aperture_rhalfmass_dm.resize(opt.aperturenum); } #endif for (auto &x:aperture_npart) x=0; for (auto &x:aperture_mass) x=-1; for (auto &x:aperture_veldisp) x=0; for (auto &x:aperture_rhalfmass) x=-1; #ifdef GASON for (auto &x:aperture_npart_gas) x=0; for (auto &x:aperture_mass_gas) x=-1; for (auto &x:aperture_veldisp_gas) x=0; for (auto &x:aperture_rhalfmass_gas) x=-1; #ifdef STARON for (auto &x:aperture_SFR_gas) x=0; for (auto &x:aperture_npart_gas_sf) x=0; for (auto &x:aperture_mass_gas_sf) x=-1; for (auto &x:aperture_npart_gas_nsf) x=0; for (auto &x:aperture_mass_gas_nsf) x=-1; for (auto &x:aperture_veldisp_gas_sf) x=0; for (auto &x:aperture_veldisp_gas_nsf) x=0; for (auto &x:aperture_rhalfmass_gas_sf) x=-1; for (auto &x:aperture_rhalfmass_gas_nsf) x=-1; #endif #endif #ifdef STARON for (auto &x:aperture_npart_star) x=0; for (auto &x:aperture_mass_star) x=-1; for (auto &x:aperture_veldisp_star) x=0; for (auto &x:aperture_rhalfmass_star) x=-1; #endif #ifdef HIGHRES for (auto &x:aperture_npart_interloper) x=0; for (auto &x:aperture_mass_interloper) x=-1; #endif #if defined(GASON) || defined(STARON) || defined(BHON) if (opt.partsearchtype==PSTALL) { for (auto &x:aperture_npart_dm) x=0; for (auto &x:aperture_mass_dm) x=-1; for (auto &x:aperture_veldisp_dm) x=0; for (auto &x:aperture_rhalfmass_dm) x=0; } #endif } if (opt.iaperturecalc && opt.apertureprojnum>0) { aperture_mass_proj.resize(opt.apertureprojnum); aperture_rhalfmass_proj.resize(opt.apertureprojnum); #ifdef GASON aperture_mass_proj_gas.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas.resize(opt.apertureprojnum); #ifdef STARON aperture_SFR_proj_gas.resize(opt.apertureprojnum); aperture_mass_proj_gas_sf.resize(opt.apertureprojnum); aperture_mass_proj_gas_nsf.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas_sf.resize(opt.apertureprojnum); aperture_rhalfmass_proj_gas_nsf.resize(opt.apertureprojnum); #endif #endif #ifdef STARON aperture_mass_proj_star.resize(opt.apertureprojnum); aperture_rhalfmass_proj_star.resize(opt.apertureprojnum); #endif for (auto &x:aperture_mass_proj) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj) x[0]=x[1]=x[2]=-1; #ifdef GASON for (auto &x:aperture_mass_proj_gas) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas) x[0]=x[1]=x[2]=-1; #ifdef STARON for (auto &x:aperture_SFR_proj_gas) x[0]=x[1]=x[2]=0; for (auto &x:aperture_mass_proj_gas_sf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas_sf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_mass_proj_gas_nsf) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_gas_nsf) x[0]=x[1]=x[2]=-1; #endif #endif #ifdef STARON for (auto &x:aperture_mass_proj_star) x[0]=x[1]=x[2]=-1; for (auto &x:aperture_rhalfmass_proj_star) x[0]=x[1]=x[2]=-1; #endif } } void AllocateProfiles(Options &opt) { if (opt.iprofilecalc) { profile_npart.resize(opt.profilenbins); profile_mass.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart[i]=profile_mass[i]=0; #ifdef GASON profile_npart_gas.resize(opt.profilenbins); profile_mass_gas.resize(opt.profilenbins); #ifdef STARON profile_npart_gas_sf.resize(opt.profilenbins); profile_mass_gas_sf.resize(opt.profilenbins); profile_npart_gas_nsf.resize(opt.profilenbins); profile_mass_gas_nsf.resize(opt.profilenbins); #endif for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas[i]=profile_mass_gas[i]=0; #ifdef STARON for (auto i=0;i<opt.profilenbins;i++) profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_star.resize(opt.profilenbins); profile_mass_star.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_star[i]=profile_mass_star[i]=0; #endif if (opt.iInclusiveHalo>0) { profile_npart_inclusive.resize(opt.profilenbins); profile_mass_inclusive.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive[i]=profile_mass_inclusive[i]=0; #ifdef GASON profile_npart_inclusive_gas.resize(opt.profilenbins); profile_mass_inclusive_gas.resize(opt.profilenbins); #ifdef STARON profile_npart_inclusive_gas_sf.resize(opt.profilenbins); profile_mass_inclusive_gas_sf.resize(opt.profilenbins); profile_npart_inclusive_gas_nsf.resize(opt.profilenbins); profile_mass_inclusive_gas_nsf.resize(opt.profilenbins); #endif for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas[i]=profile_mass_inclusive_gas[i]=0; #ifdef STARON for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_gas_sf[i]=profile_mass_inclusive_gas_sf[i]=profile_npart_inclusive_gas_nsf[i]=profile_mass_inclusive_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_inclusive_star.resize(opt.profilenbins); profile_mass_inclusive_star.resize(opt.profilenbins); for (auto i=0;i<opt.profilenbins;i++) profile_npart_inclusive_star[i]=profile_mass_inclusive_star[i]=0; #endif } } } void AllocateSOs(Options &opt) { if (opt.SOnum>0) { SO_mass.resize(opt.SOnum); SO_radius.resize(opt.SOnum); for (auto &x:SO_mass) x=0; for (auto &x:SO_radius) x=0; if (opt.iextrahalooutput) { SO_angularmomentum.resize(opt.SOnum); for (auto &x:SO_angularmomentum) {x[0]=x[1]=x[2]=0;} #ifdef GASON if (opt.iextragasoutput) { SO_mass_gas.resize(opt.SOnum); for (auto &x:SO_mass_gas) x=0; SO_angularmomentum_gas.resize(opt.SOnum); for (auto &x:SO_angularmomentum_gas) {x[0]=x[1]=x[2]=0;} #ifdef STARON #endif } #endif #ifdef STARON if (opt.iextrastaroutput) { SO_mass_star.resize(opt.SOnum); for (auto &x:SO_mass_star) x=0; SO_angularmomentum_star.resize(opt.SOnum); for (auto &x:SO_angularmomentum_star) {x[0]=x[1]=x[2]=0;} } #endif #ifdef HIGHRES if (opt.iextrainterloperoutput) { SO_mass_interloper.resize(opt.SOnum); for (auto &x:SO_mass_interloper) x=0; } #endif } } } void CopyProfileToInclusive(Options &opt) { for (auto i=0;i<opt.profilenbins;i++) { profile_npart_inclusive[i]=profile_npart[i]; profile_mass_inclusive[i]=profile_mass[i]; profile_npart[i]=profile_mass[i]=0; #ifdef GASON profile_npart_inclusive_gas[i]=profile_npart_gas[i]; profile_mass_inclusive_gas[i]=profile_mass_gas[i]; profile_npart_gas[i]=profile_mass_gas[i]=0; #ifdef STARON profile_npart_inclusive_gas_sf[i]=profile_npart_gas_sf[i]; profile_mass_inclusive_gas_sf[i]=profile_mass_gas_sf[i]; profile_npart_gas_sf[i]=profile_mass_gas_sf[i]=0; profile_npart_inclusive_gas_nsf[i]=profile_npart_gas_nsf[i]; profile_mass_inclusive_gas_nsf[i]=profile_mass_gas_nsf[i]; profile_npart_gas_nsf[i]=profile_mass_gas_nsf[i]=0; #endif #endif #ifdef STARON profile_npart_inclusive_star[i]=profile_npart_star[i]; profile_mass_inclusive_star[i]=profile_mass_star[i]; profile_npart_star[i]=profile_mass_star[i]=0; #endif } } ///converts the properties data into comoving little h values ///so masses, positions have little h values and positions are comoving void ConverttoComove(Options &opt){ gcm=gcm*opt.h/opt.a; gposmbp=gposmbp*opt.h/opt.a; gposminpot=gposminpot*opt.h/opt.a; gmass*=opt.h; gMvir*=opt.h; gM200c*=opt.h; gM200m*=opt.h; gM500c*=opt.h; gMBN98*=opt.h; gMFOF*=opt.h; gsize*=opt.h/opt.a; gRmbp*=opt.h/opt.a; gRmaxvel*=opt.h/opt.a; gRvir*=opt.h/opt.a; gR200c*=opt.h/opt.a; gR200m*=opt.h/opt.a; gR500c*=opt.h/opt.a; gRBN98*=opt.h/opt.a; gMassTwiceRhalfmass*=opt.h; gRhalfmass*=opt.h/opt.a; gJ=gJ*opt.h*opt.h/opt.a; gJ200m=gJ200m*opt.h*opt.h/opt.a; gJ200c=gJ200c*opt.h*opt.h/opt.a; gJBN98=gJBN98*opt.h*opt.h/opt.a; RV_J=RV_J*opt.h*opt.h/opt.a; if (opt.iextrahalooutput) { gM200c_excl*=opt.h; gM200m_excl*=opt.h; gMBN98_excl*=opt.h; gR200c_excl*=opt.h/opt.a; gR200m_excl*=opt.h/opt.a; gRBN98_excl*=opt.h/opt.a; gJ200m_excl=gJ200m_excl*opt.h*opt.h/opt.a; gJ200c_excl=gJ200c_excl*opt.h*opt.h/opt.a; gJBN98_excl=gJBN98_excl*opt.h*opt.h/opt.a; } #ifdef GASON M_gas*=opt.h; M_gas_rvmax*=opt.h; M_gas_30kpc*=opt.h; M_gas_50kpc*=opt.h; M_gas_500c*=opt.h; cm_gas=cm_gas*opt.h/opt.a; L_gas=L_gas*opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas*=opt.h; Rhalfmass_gas*=opt.h/opt.a; if (opt.iextragasoutput) { M_200mean_gas*=opt.h; M_200crit_gas*=opt.h; M_BN98_gas*=opt.h; M_200mean_excl_gas*=opt.h; M_200crit_excl_gas*=opt.h; M_BN98_excl_gas*=opt.h; L_200crit_gas=L_200crit_gas*opt.h*opt.h/opt.a; L_200mean_gas=L_200mean_gas*opt.h*opt.h/opt.a; L_BN98_gas=L_BN98_gas*opt.h*opt.h/opt.a; L_200crit_excl_gas=L_200crit_excl_gas*opt.h*opt.h/opt.a; L_200mean_excl_gas=L_200mean_excl_gas*opt.h*opt.h/opt.a; L_BN98_excl_gas=L_BN98_excl_gas*opt.h*opt.h/opt.a; } #ifdef STARON M_gas_sf*=opt.h; L_gas_sf*=opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas_sf*=opt.h; Rhalfmass_gas_sf*=opt.h/opt.a; M_gas_nsf*=opt.h; L_gas_nsf*=opt.h*opt.h/opt.a; MassTwiceRhalfmass_gas_nsf*=opt.h; Rhalfmass_gas_nsf*=opt.h/opt.a; if (opt.iextragasoutput) { M_200mean_gas_sf*=opt.h; M_200crit_gas_sf*=opt.h; M_BN98_gas_sf*=opt.h; M_200mean_excl_gas_sf*=opt.h; M_200crit_excl_gas_sf*=opt.h; M_BN98_excl_gas_sf*=opt.h; L_200crit_gas_sf*=opt.h*opt.h/opt.a; L_200mean_gas_sf*=opt.h*opt.h/opt.a; L_BN98_gas_sf*=opt.h*opt.h/opt.a; L_200crit_excl_gas_sf*=opt.h*opt.h/opt.a; L_200mean_excl_gas_sf*=opt.h*opt.h/opt.a; L_BN98_excl_gas_sf*=opt.h*opt.h/opt.a; M_200mean_gas_nsf*=opt.h; M_200crit_gas_nsf*=opt.h; M_BN98_gas_nsf*=opt.h; M_200mean_excl_gas_nsf*=opt.h; M_200crit_excl_gas_nsf*=opt.h; M_BN98_excl_gas_nsf*=opt.h; L_200crit_gas_nsf*=opt.h*opt.h/opt.a; L_200mean_gas_nsf*=opt.h*opt.h/opt.a; L_BN98_gas_nsf*=opt.h*opt.h/opt.a; L_200crit_excl_gas_nsf*=opt.h*opt.h/opt.a; L_200mean_excl_gas_nsf*=opt.h*opt.h/opt.a; L_BN98_excl_gas_nsf*=opt.h*opt.h/opt.a; } #endif #endif #ifdef STARON M_star*=opt.h; M_star_rvmax*=opt.h; M_star_30kpc*=opt.h; M_star_50kpc*=opt.h; M_star_500c*=opt.h; cm_star=cm_star*opt.h/opt.a; MassTwiceRhalfmass_star*=opt.h/opt.a; Rhalfmass_star*=opt.h/opt.a; L_star=L_star*opt.h*opt.h/opt.a; #endif #ifdef BHON M_bh*=opt.h; #endif #ifdef HIGHRES M_interloper*=opt.h; #endif if (opt.iaperturecalc) { for (auto i=0;i<opt.iaperturecalc;i++) { aperture_mass[i]*=opt.h; #ifdef GASON aperture_mass_gas[i]*=opt.h; #ifdef STARON aperture_mass_gas_sf[i]*=opt.h; aperture_mass_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON aperture_mass_star[i]*=opt.h; #endif } } if (opt.SOnum>0) { for (auto i=0;i<opt.SOnum;i++) { SO_mass[i] *= opt.h; SO_radius[i] *= opt.h/opt.a; if (opt.iextrahalooutput) { SO_angularmomentum[i]*=(opt.h*opt.h/opt.a); #ifdef GASON SO_mass_gas[i] *= opt.h; SO_angularmomentum_gas[i]*=(opt.h*opt.h/opt.a); #ifdef STARON #endif #endif #ifdef STARON SO_mass_star[i] *= opt.h; SO_angularmomentum_star[i]*=(opt.h*opt.h/opt.a); #endif } } } } void ConvertProfilestoComove(Options &opt){ for (auto i=0;i<opt.profilenbins;i++) { profile_mass[i]*=opt.h; #ifdef GASON profile_mass_gas[i]*=opt.h; #ifdef STARON profile_mass_gas_sf[i]*=opt.h; profile_mass_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON profile_mass_star[i]*=opt.h; #endif } if (opt.iInclusiveHalo) { for (auto i=0;i<opt.profilenbins;i++) { profile_mass_inclusive[i]*=opt.h; #ifdef GASON profile_mass_inclusive_gas[i]*=opt.h; #ifdef STARON profile_mass_inclusive_gas_sf[i]*=opt.h; profile_mass_inclusive_gas_nsf[i]*=opt.h; #endif #endif #ifdef STARON profile_mass_inclusive_star[i]*=opt.h; #endif } } } ///write (append) the properties data to an already open binary file void WriteBinary(fstream &Fout, Options&opt){ long long lval; long unsigned idval; unsigned int ival; double val, val3[3],val9[9]; idval=haloid; Fout.write((char*)&idval,sizeof(idval)); lval=ibound; Fout.write((char*)&lval,sizeof(idval)); lval=iminpot; Fout.write((char*)&lval,sizeof(idval)); lval=hostid; Fout.write((char*)&lval,sizeof(idval)); idval=numsubs; Fout.write((char*)&idval,sizeof(idval)); idval=num; Fout.write((char*)&idval,sizeof(idval)); ival=stype; Fout.write((char*)&ival,sizeof(ival)); if (opt.iKeepFOF==1) { idval=directhostid; Fout.write((char*)&idval,sizeof(idval)); idval=hostfofid; Fout.write((char*)&idval,sizeof(idval)); } val=gMvir; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=gcm[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gposmbp[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gposminpot[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gcmvel[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gvelmbp[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gvelminpot[k]; Fout.write((char*)val3,sizeof(val)*3); val=gmass; Fout.write((char*)&val,sizeof(val)); val=gMFOF; Fout.write((char*)&val,sizeof(val)); val=gM200m; Fout.write((char*)&val,sizeof(val)); val=gM200c; Fout.write((char*)&val,sizeof(val)); val=gMBN98; Fout.write((char*)&val,sizeof(val)); val=Efrac; Fout.write((char*)&val,sizeof(val)); val=gRvir; Fout.write((char*)&val,sizeof(val)); val=gsize; Fout.write((char*)&val,sizeof(val)); val=gR200m; Fout.write((char*)&val,sizeof(val)); val=gR200c; Fout.write((char*)&val,sizeof(val)); val=gRBN98; Fout.write((char*)&val,sizeof(val)); val=gRhalfmass; Fout.write((char*)&val,sizeof(val)); val=gRmaxvel; Fout.write((char*)&val,sizeof(val)); val=gmaxvel; Fout.write((char*)&val,sizeof(val)); val=gsigma_v; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=gveldisp(k,n); Fout.write((char*)val9,sizeof(val)*9); val=glambda_B; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=gJ[k]; Fout.write((char*)val3,sizeof(val)*3); val=gq; Fout.write((char*)&val,sizeof(val)); val=gs; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=geigvec(k,n); Fout.write((char*)val9,sizeof(val)*9); val=cNFW; Fout.write((char*)&val,sizeof(val)); val=Krot; Fout.write((char*)&val,sizeof(val)); val=T; Fout.write((char*)&val,sizeof(val)); val=Pot; Fout.write((char*)&val,sizeof(val)); val=RV_sigma_v; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_veldisp(k,n); Fout.write((char*)val9,sizeof(val)*9); val=RV_lambda_B; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=RV_J[k]; Fout.write((char*)val3,sizeof(val)*3); val=RV_q; Fout.write((char*)&val,sizeof(val)); val=RV_s; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=RV_eigvec(k,n); Fout.write((char*)val9,sizeof(val)*9); if (opt.iextrahalooutput) { for (int k=0;k<3;k++) val3[k]=gJ200m[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gJ200c[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gJBN98[k]; Fout.write((char*)val3,sizeof(val)*3); if (opt.iInclusiveHalo>0) { val=gM200m_excl; Fout.write((char*)&val,sizeof(val)); val=gM200c_excl; Fout.write((char*)&val,sizeof(val)); val=gMBN98_excl; Fout.write((char*)&val,sizeof(val)); val=gR200m_excl; Fout.write((char*)&val,sizeof(val)); val=gR200c_excl; Fout.write((char*)&val,sizeof(val)); val=gRBN98_excl; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=gJ200m_excl[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gJ200c_excl[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=gJBN98_excl[k]; Fout.write((char*)val3,sizeof(val)*3); } } #ifdef GASON idval=n_gas; Fout.write((char*)&idval,sizeof(idval)); val=M_gas; Fout.write((char*)&val,sizeof(val)); val=M_gas_rvmax; Fout.write((char*)&val,sizeof(val)); val=M_gas_30kpc; Fout.write((char*)&val,sizeof(val)); val=M_gas_500c; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=cm_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=cmvel_gas[k]; Fout.write((char*)val3,sizeof(val)*3); val=Efrac_gas; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_gas(k,n); Fout.write((char*)val9,sizeof(val)*9); for (int k=0;k<3;k++) val3[k]=L_gas[k]; Fout.write((char*)val3,sizeof(val)*3); val=q_gas; Fout.write((char*)&val,sizeof(val)); val=s_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_gas(k,n); Fout.write((char*)val9,sizeof(val)*9); val=Krot_gas; Fout.write((char*)&val,sizeof(val)); val=Temp_mean_gas; Fout.write((char*)&val,sizeof(val)); #ifdef STARON val=Z_mean_gas; Fout.write((char*)&val,sizeof(val)); val=SFR_gas; Fout.write((char*)&val,sizeof(val)); #endif if (opt.iextragasoutput) { val=M_200mean_gas; Fout.write((char*)&val,sizeof(val)); val=M_200crit_gas; Fout.write((char*)&val,sizeof(val)); val=M_BN98_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_gas[k]; Fout.write((char*)val3,sizeof(val)*3); if (opt.iInclusiveHalo>0) { val=M_200mean_excl_gas; Fout.write((char*)&val,sizeof(val)); val=M_200crit_excl_gas; Fout.write((char*)&val,sizeof(val)); val=M_BN98_excl_gas; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas[k]; Fout.write((char*)val3,sizeof(val)*3); } } #endif #ifdef STARON idval=n_star; Fout.write((char*)&idval,sizeof(idval)); val=M_star; Fout.write((char*)&val,sizeof(val)); val=M_star_rvmax; Fout.write((char*)&val,sizeof(val)); val=M_star_30kpc; Fout.write((char*)&val,sizeof(val)); val=M_star_500c; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=cm_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=cmvel_star[k]; Fout.write((char*)val3,sizeof(val)*3); val=Efrac_star; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=veldisp_star(k,n); Fout.write((char*)val9,sizeof(val)*9); for (int k=0;k<3;k++) val3[k]=L_star[k]; Fout.write((char*)val3,sizeof(val)*3); val=q_star; Fout.write((char*)&val,sizeof(val)); val=s_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) for (int n=0;n<3;n++) val9[k*3+n]=eigvec_star(k,n); Fout.write((char*)val9,sizeof(val)*9); val=Krot_star; Fout.write((char*)&val,sizeof(val)); val=t_mean_star; Fout.write((char*)&val,sizeof(val)); val=Z_mean_star; Fout.write((char*)&val,sizeof(val)); if (opt.iextrastaroutput) { val=M_200mean_star; Fout.write((char*)&val,sizeof(val)); val=M_200crit_star; Fout.write((char*)&val,sizeof(val)); val=M_BN98_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_star[k]; Fout.write((char*)val3,sizeof(val)*3); if (opt.iInclusiveHalo>0) { val=M_200mean_excl_star; Fout.write((char*)&val,sizeof(val)); val=M_200crit_excl_star; Fout.write((char*)&val,sizeof(val)); val=M_BN98_excl_star; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_excl_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_excl_star[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_excl_star[k]; Fout.write((char*)val3,sizeof(val)*3); } } #endif #ifdef BHON idval=n_bh; Fout.write((char*)&idval,sizeof(idval)); val=M_bh; Fout.write((char*)&val,sizeof(val)); #endif #ifdef HIGHRES idval=n_interloper; Fout.write((char*)&idval,sizeof(idval)); val=M_interloper; Fout.write((char*)&val,sizeof(val)); #endif #if defined(GASON) && defined(STARON) val=M_gas_sf; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_gas_sf; Fout.write((char*)&val,sizeof(val)); val=sigV_gas_sf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); val=Krot_gas_sf; Fout.write((char*)&val,sizeof(val)); val=Temp_mean_gas_sf; Fout.write((char*)&val,sizeof(val)); val=Z_mean_gas_sf; Fout.write((char*)&val,sizeof(val)); if (opt.iextragasoutput) { val=M_200mean_gas_sf; Fout.write((char*)&val,sizeof(val)); val=M_200crit_gas_sf; Fout.write((char*)&val,sizeof(val)); val=M_BN98_gas_sf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); if (opt.iInclusiveHalo>0) { val=M_200mean_excl_gas_sf; Fout.write((char*)&val,sizeof(val)); val=M_200crit_excl_gas_sf; Fout.write((char*)&val,sizeof(val)); val=M_BN98_excl_gas_sf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas_sf[k]; Fout.write((char*)val3,sizeof(val)*3); } } val=M_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=Rhalfmass_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=sigV_gas_nsf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); val=Krot_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=Temp_mean_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=Z_mean_gas_nsf; Fout.write((char*)&val,sizeof(val)); if (opt.iextragasoutput) { val=M_200mean_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=M_200crit_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=M_BN98_gas_nsf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); if (opt.iInclusiveHalo>0) { val=M_200mean_excl_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=M_200crit_excl_gas_nsf; Fout.write((char*)&val,sizeof(val)); val=M_BN98_excl_gas_nsf; Fout.write((char*)&val,sizeof(val)); for (int k=0;k<3;k++) val3[k]=L_200mean_excl_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_200crit_excl_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); for (int k=0;k<3;k++) val3[k]=L_BN98_excl_gas_nsf[k]; Fout.write((char*)val3,sizeof(val)*3); } } #endif if (opt.iaperturecalc && opt.aperturenum>0){ for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_npart[j],sizeof(int)); } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_npart_gas[j],sizeof(int)); } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_npart_gas_sf[j],sizeof(int)); } for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_npart_gas_nsf[j],sizeof(int)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_npart_star[j],sizeof(int)); } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_mass[j],sizeof(val)); } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_mass_gas[j],sizeof(val)); } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_mass_gas_sf[j],sizeof(val)); } for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_mass_gas_nsf[j],sizeof(val)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_mass_star[j],sizeof(val)); } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_rhalfmass[j],sizeof(val)); } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_rhalfmass_gas[j],sizeof(val)); } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_rhalfmass_gas_sf[j],sizeof(val)); } for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_rhalfmass_gas_nsf[j],sizeof(val)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_rhalfmass_star[j],sizeof(val)); } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_veldisp[j],sizeof(val)); } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_veldisp_gas[j],sizeof(val)); } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_veldisp_gas_sf[j],sizeof(val)); } for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_veldisp_gas_nsf[j],sizeof(val)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_veldisp_star[j],sizeof(val)); } #endif #if defined(GASON) && defined(STARON) for (auto j=0;j<opt.aperturenum;j++) { Fout.write((char*)&aperture_SFR_gas[j],sizeof(val)); } #endif } if (opt.iaperturecalc && opt.apertureprojnum>0){ for (auto k=0;k<3;k++) { for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_mass_proj[j][k],sizeof(val)); } #ifdef GASON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_mass_proj_gas[j][k],sizeof(val)); } #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_mass_proj_gas_sf[j][k],sizeof(val)); } for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_mass_proj_gas_nsf[j][k],sizeof(val)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_mass_proj_star[j][k],sizeof(val)); } #endif for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_rhalfmass_proj[j][k],sizeof(val)); } #ifdef GASON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_rhalfmass_proj_gas[j][k],sizeof(val)); } #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_rhalfmass_proj_gas_sf[j][k],sizeof(val)); } for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_rhalfmass_proj_gas_nsf[j][k],sizeof(val)); } #endif #endif #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_rhalfmass_proj_star[j][k],sizeof(val)); } #endif #if defined(GASON) && defined(STARON) for (auto j=0;j<opt.apertureprojnum;j++) { Fout.write((char*)&aperture_SFR_proj_gas[j][k],sizeof(val)); } #endif } } if (opt.SOnum>0){ for (auto j=0;j<opt.SOnum;j++) { Fout.write((char*)&SO_mass[j],sizeof(int)); } for (auto j=0;j<opt.SOnum;j++) { Fout.write((char*)&SO_radius[j],sizeof(int)); } #ifdef GASON if (opt.iextragasoutput && opt.iextrahalooutput) for (auto j=0;j<opt.SOnum;j++) { Fout.write((char*)&SO_mass_gas[j],sizeof(int)); } #ifdef STARON #endif #endif #ifdef STARON if (opt.iextrastaroutput && opt.iextrahalooutput) for (auto j=0;j<opt.SOnum;j++) { Fout.write((char*)&SO_mass_star[j],sizeof(int)); } #endif } if (opt.SOnum>0 && opt.iextrahalooutput){ for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum[j][k],sizeof(int)); } #ifdef GASON if (opt.iextragasoutput) for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum_gas[j][k],sizeof(int)); } #ifdef STARON #endif #endif #ifdef STARON if (opt.iextrastaroutput) for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout.write((char*)&SO_angularmomentum_star[j][k],sizeof(int)); } #endif } } ///write (append) the properties data to an already open ascii file void WriteAscii(fstream &Fout, Options&opt){ Fout<<haloid<<" "; Fout<<ibound<<" "; Fout<<iminpot<<" "; Fout<<hostid<<" "; Fout<<numsubs<<" "; Fout<<num<<" "; Fout<<stype<<" "; if (opt.iKeepFOF==1) { Fout<<directhostid<<" "; Fout<<hostfofid<<" "; } Fout<<gMvir<<" "; for (int k=0;k<3;k++) Fout<<gcm[k]<<" "; for (int k=0;k<3;k++) Fout<<gposmbp[k]<<" "; for (int k=0;k<3;k++) Fout<<gposminpot[k]<<" "; for (int k=0;k<3;k++) Fout<<gcmvel[k]<<" "; for (int k=0;k<3;k++) Fout<<gvelmbp[k]<<" "; for (int k=0;k<3;k++) Fout<<gvelminpot[k]<<" "; Fout<<gmass<<" "; Fout<<gMFOF<<" "; Fout<<gM200m<<" "; Fout<<gM200c<<" "; Fout<<gMBN98<<" "; Fout<<Efrac<<" "; Fout<<gRvir<<" "; Fout<<gsize<<" "; Fout<<gR200m<<" "; Fout<<gR200c<<" "; Fout<<gRBN98<<" "; Fout<<gRhalfmass<<" "; Fout<<gRmaxvel<<" "; Fout<<gmaxvel<<" "; Fout<<gsigma_v<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<gveldisp(k,n)<<" "; Fout<<glambda_B<<" "; for (int k=0;k<3;k++) Fout<<gJ[k]<<" "; Fout<<gq<<" "; Fout<<gs<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<geigvec(k,n)<<" "; Fout<<cNFW<<" "; Fout<<Krot<<" "; Fout<<T<<" "; Fout<<Pot<<" "; Fout<<RV_sigma_v<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_veldisp(k,n)<<" "; Fout<<RV_lambda_B<<" "; for (int k=0;k<3;k++) Fout<<RV_J[k]<<" "; Fout<<RV_q<<" "; Fout<<RV_s<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<RV_eigvec(k,n)<<" "; if (opt.iextrahalooutput) { for (int k=0;k<3;k++) Fout<<gJ200m[k]<<" "; for (int k=0;k<3;k++) Fout<<gJ200c[k]<<" "; for (int k=0;k<3;k++) Fout<<gJBN98[k]<<" "; if (opt.iInclusiveHalo>0) { Fout<<gM200m_excl<<" "; Fout<<gM200c_excl<<" "; Fout<<gMBN98_excl<<" "; Fout<<gR200m_excl<<" "; Fout<<gR200c_excl<<" "; Fout<<gRBN98_excl<<" "; for (int k=0;k<3;k++) Fout<<gJ200m_excl[k]<<" "; for (int k=0;k<3;k++) Fout<<gJ200c_excl[k]<<" "; for (int k=0;k<3;k++) Fout<<gJBN98_excl[k]<<" "; } } #ifdef GASON Fout<<n_gas<<" "; Fout<<M_gas<<" "; Fout<<M_gas_rvmax<<" "; Fout<<M_gas_30kpc<<" "; //Fout<<M_gas_50kpc<<" "; Fout<<M_gas_500c<<" "; for (int k=0;k<3;k++) Fout<<cm_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<cmvel_gas[k]<<" "; Fout<<Efrac_gas<<" "; Fout<<Rhalfmass_gas<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_gas(k,n)<<" "; for (int k=0;k<3;k++) Fout<<L_gas[k]<<" "; Fout<<q_gas<<" "; Fout<<s_gas<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_gas(k,n)<<" "; Fout<<Krot_gas<<" "; Fout<<Temp_mean_gas<<" "; #ifdef STARON Fout<<Z_mean_gas<<" "; Fout<<SFR_gas<<" "; #endif if (opt.iextragasoutput) { Fout<<M_200mean_gas<<" "; Fout<<M_200crit_gas<<" "; Fout<<M_BN98_gas<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_gas[k]<<" "; if (opt.iInclusiveHalo>0) { Fout<<M_200mean_excl_gas<<" "; Fout<<M_200crit_excl_gas<<" "; Fout<<M_BN98_excl_gas<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas[k]<<" "; } } #endif #ifdef STARON Fout<<n_star<<" "; Fout<<M_star<<" "; Fout<<M_star_rvmax<<" "; Fout<<M_star_30kpc<<" "; //Fout<<M_star_50kpc<<" "; Fout<<M_star_500c<<" "; for (int k=0;k<3;k++) Fout<<cm_star[k]<<" "; for (int k=0;k<3;k++) Fout<<cmvel_star[k]<<" "; Fout<<Efrac_star<<" "; Fout<<Rhalfmass_star<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<veldisp_star(k,n)<<" "; for (int k=0;k<3;k++) Fout<<L_star[k]<<" "; Fout<<q_star<<" "; Fout<<s_star<<" "; for (int k=0;k<3;k++) for (int n=0;n<3;n++) Fout<<eigvec_star(k,n)<<" "; Fout<<Krot_star<<" "; Fout<<t_mean_star<<" "; Fout<<Z_mean_star<<" "; if (opt.iextrastaroutput) { Fout<<M_200mean_star<<" "; Fout<<M_200crit_star<<" "; Fout<<M_BN98_star<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_star[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_star[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_star[k]<<" "; if (opt.iInclusiveHalo>0) { Fout<<M_200mean_excl_star<<" "; Fout<<M_200crit_excl_star<<" "; Fout<<M_BN98_excl_star<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_excl_star[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_excl_star[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_excl_star[k]<<" "; } } #endif #ifdef BHON Fout<<n_bh<<" "; Fout<<M_bh<<" "; #endif #ifdef HIGHRES Fout<<n_interloper<<" "; Fout<<M_interloper<<" "; if (opt.iextrainterloperoutput) { Fout<<M_200mean_interloper<<" "; Fout<<M_200crit_interloper<<" "; Fout<<M_BN98_interloper<<" "; if (opt.iInclusiveHalo>0) { Fout<<M_200mean_excl_interloper<<" "; Fout<<M_200crit_excl_interloper<<" "; Fout<<M_BN98_excl_interloper<<" "; } } #endif #if defined(GASON) && defined(STARON) Fout<<M_gas_sf<<" "; Fout<<Rhalfmass_gas_sf<<" "; Fout<<sigV_gas_sf<<" "; for (int k=0;k<3;k++) Fout<<L_gas_sf[k]<<" "; Fout<<Krot_gas_sf<<" "; Fout<<Temp_mean_gas_sf<<" "; Fout<<Z_mean_gas_sf<<" "; if (opt.iextragasoutput) { Fout<<M_200mean_gas_sf<<" "; Fout<<M_200crit_gas_sf<<" "; Fout<<M_BN98_gas_sf<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_gas_sf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_gas_sf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_gas_sf[k]<<" "; if (opt.iInclusiveHalo>0) { Fout<<M_200mean_excl_gas_sf<<" "; Fout<<M_200crit_excl_gas_sf<<" "; Fout<<M_BN98_excl_gas_sf<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas_sf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas_sf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas_sf[k]<<" "; } } Fout<<M_gas_nsf<<" "; Fout<<Rhalfmass_gas_nsf<<" "; Fout<<sigV_gas_nsf<<" "; for (int k=0;k<3;k++) Fout<<L_gas_nsf[k]<<" "; Fout<<Krot_gas_nsf<<" "; Fout<<Temp_mean_gas_nsf<<" "; Fout<<Z_mean_gas_nsf<<" "; if (opt.iextragasoutput) { Fout<<M_200mean_gas_nsf<<" "; Fout<<M_200crit_gas_nsf<<" "; Fout<<M_BN98_gas_nsf<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_gas_nsf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_gas_nsf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_gas_nsf[k]<<" "; if (opt.iInclusiveHalo>0) { Fout<<M_200mean_excl_gas_nsf<<" "; Fout<<M_200crit_excl_gas_nsf<<" "; Fout<<M_BN98_excl_gas_nsf<<" "; for (int k=0;k<3;k++) Fout<<L_200mean_excl_gas_nsf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_200crit_excl_gas_nsf[k]<<" "; for (int k=0;k<3;k++) Fout<<L_BN98_excl_gas_nsf[k]<<" "; } } #endif if (opt.iaperturecalc && opt.aperturenum>0){ for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart[j]<<" "; } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart_gas[j]<<" "; } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart_gas_sf[j]<<" "; } for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart_gas_nsf[j]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart_star[j]<<" "; } #endif #ifdef HIGHRES for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_npart_interloper[j]<<" "; } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass[j]<<" "; } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass_gas[j]<<" "; } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass_gas_sf[j]<<" "; } for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass_gas_nsf[j]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass_star[j]<<" "; } #endif #ifdef HIGHRES for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_mass_interloper[j]<<" "; } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_rhalfmass[j]<<" "; } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_rhalfmass_gas[j]<<" "; } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_rhalfmass_gas_sf[j]<<" "; } for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_rhalfmass_gas_nsf[j]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_rhalfmass_star[j]<<" "; } #endif for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_veldisp[j]<<" "; } #ifdef GASON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_veldisp_gas[j]<<" "; } #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_veldisp_gas_sf[j]<<" "; } for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_veldisp_gas_nsf[j]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_veldisp_star[j]<<" "; } #endif #if defined(GASON) && defined(STARON) for (auto j=0;j<opt.aperturenum;j++) { Fout<<aperture_SFR_gas[j]<<" "; } #endif } if (opt.iaperturecalc && opt.apertureprojnum>0) { for (auto k=0;k<3;k++) { for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_mass_proj[j][k]<<" "; } #ifdef GASON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_mass_proj_gas[j][k]<<" "; } #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_mass_proj_gas_sf[j][k]<<" "; } for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_mass_proj_gas_nsf[j][k]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_mass_proj_star[j][k]<<" "; } #endif for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_rhalfmass_proj[j][k]<<" "; } #ifdef GASON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_rhalfmass_proj_gas[j][k]<<" "; } #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_rhalfmass_proj_gas_sf[j][k]<<" "; } for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_rhalfmass_proj_gas_nsf[j][k]<<" "; } #endif #endif #ifdef STARON for (auto j=0;j<opt.apertureprojnum;j++){ Fout<<aperture_rhalfmass_proj_star[j][k]<<" "; } #endif #if defined(GASON) && defined(STARON) for (auto j=0;j<opt.apertureprojnum;j++) { Fout<<aperture_SFR_proj_gas[j][k]<<" "; } #endif } } if (opt.SOnum>0){ for (auto j=0;j<opt.SOnum;j++) { Fout<<SO_mass[j]<<" "; } for (auto j=0;j<opt.SOnum;j++) { Fout<<SO_radius[j]<<" "; } #ifdef GASON if (opt.iextragasoutput && opt.iextrahalooutput) for (auto j=0;j<opt.SOnum;j++) { Fout<<SO_mass_gas[j]<<" "; } #ifdef STARON #endif #endif #ifdef STARON if (opt.iextrastaroutput && opt.iextrahalooutput) for (auto j=0;j<opt.SOnum;j++) { Fout<<SO_mass_star[j]<<" "; } #endif #ifdef HIGHRES if (opt.iextrainterloperoutput && opt.iextrahalooutput) for (auto j=0;j<opt.SOnum;j++) { Fout<<SO_mass_interloper[j]<<" "; } #endif } if (opt.SOnum>0 && opt.iextrahalooutput){ for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout<<SO_angularmomentum[j][k]<<" "; } #ifdef GASON if (opt.iextragasoutput) for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout<<SO_angularmomentum_gas[j][k]<<" "; } #ifdef STARON #endif #endif #ifdef STARON if (opt.iextrastaroutput) for (auto j=0;j<opt.SOnum;j++) { for (auto k=0;k<3;k++) Fout<<SO_angularmomentum_star[j][k]<<" "; } #endif } Fout<<endl; } #ifdef USEHDF ///write (append) the properties data to an already open hdf file void WriteHDF(H5File &Fhdf, DataSpace *&dataspaces, DataSet *&datasets, Options&opt){ }; #endif }; /*! Structures stores header info of the data writen by the \ref PropData data structure, specifically the \ref PropData::WriteBinary, \ref PropData::WriteAscii, \ref PropData::WriteHDF routines Must ensure that these routines are all altered together so that the io makes sense. */ struct PropDataHeader{ //list the header info vector<string> headerdatainfo; #ifdef USEHDF vector<PredType> predtypeinfo; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospredtypeinfo; #endif PropDataHeader(Options&opt){ int sizeval; #ifdef USEHDF vector<PredType> desiredproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE); else desiredproprealtype.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif headerdatainfo.push_back("ID"); headerdatainfo.push_back("ID_mbp"); headerdatainfo.push_back("ID_minpot"); headerdatainfo.push_back("hostHaloID"); headerdatainfo.push_back("numSubStruct"); headerdatainfo.push_back("npart"); headerdatainfo.push_back("Structuretype"); if (opt.iKeepFOF==1){ headerdatainfo.push_back("hostDirectHaloID"); headerdatainfo.push_back("hostFOFID"); } //if using hdf, store the type #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_U64LE); predtypeinfo.push_back(PredType::STD_I32LE); if (opt.iKeepFOF==1){ predtypeinfo.push_back(PredType::STD_I64LE); predtypeinfo.push_back(PredType::STD_I64LE); } #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_integer); if (opt.iKeepFOF==1){ adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_long); } #endif headerdatainfo.push_back("Mvir"); headerdatainfo.push_back("Xc"); headerdatainfo.push_back("Yc"); headerdatainfo.push_back("Zc"); headerdatainfo.push_back("Xcmbp"); headerdatainfo.push_back("Ycmbp"); headerdatainfo.push_back("Zcmbp"); headerdatainfo.push_back("Xcminpot"); headerdatainfo.push_back("Ycminpot"); headerdatainfo.push_back("Zcminpot"); headerdatainfo.push_back("VXc"); headerdatainfo.push_back("VYc"); headerdatainfo.push_back("VZc"); headerdatainfo.push_back("VXcmbp"); headerdatainfo.push_back("VYcmbp"); headerdatainfo.push_back("VZcmbp"); headerdatainfo.push_back("VXcminpot"); headerdatainfo.push_back("VYcminpot"); headerdatainfo.push_back("VZcminpot"); headerdatainfo.push_back("Mass_tot"); headerdatainfo.push_back("Mass_FOF"); headerdatainfo.push_back("Mass_200mean"); headerdatainfo.push_back("Mass_200crit"); headerdatainfo.push_back("Mass_BN98"); headerdatainfo.push_back("Efrac"); headerdatainfo.push_back("Rvir"); headerdatainfo.push_back("R_size"); headerdatainfo.push_back("R_200mean"); headerdatainfo.push_back("R_200crit"); headerdatainfo.push_back("R_BN98"); headerdatainfo.push_back("R_HalfMass"); headerdatainfo.push_back("Rmax"); headerdatainfo.push_back("Vmax"); headerdatainfo.push_back("sigV"); headerdatainfo.push_back("veldisp_xx"); headerdatainfo.push_back("veldisp_xy"); headerdatainfo.push_back("veldisp_xz"); headerdatainfo.push_back("veldisp_yx"); headerdatainfo.push_back("veldisp_yy"); headerdatainfo.push_back("veldisp_yz"); headerdatainfo.push_back("veldisp_zx"); headerdatainfo.push_back("veldisp_zy"); headerdatainfo.push_back("veldisp_zz"); headerdatainfo.push_back("lambda_B"); headerdatainfo.push_back("Lx"); headerdatainfo.push_back("Ly"); headerdatainfo.push_back("Lz"); headerdatainfo.push_back("q"); headerdatainfo.push_back("s"); headerdatainfo.push_back("eig_xx"); headerdatainfo.push_back("eig_xy"); headerdatainfo.push_back("eig_xz"); headerdatainfo.push_back("eig_yx"); headerdatainfo.push_back("eig_yy"); headerdatainfo.push_back("eig_yz"); headerdatainfo.push_back("eig_zx"); headerdatainfo.push_back("eig_zy"); headerdatainfo.push_back("eig_zz"); headerdatainfo.push_back("cNFW"); headerdatainfo.push_back("Krot"); headerdatainfo.push_back("Ekin"); headerdatainfo.push_back("Epot"); //some properties within RVmax headerdatainfo.push_back("RVmax_sigV"); headerdatainfo.push_back("RVmax_veldisp_xx"); headerdatainfo.push_back("RVmax_veldisp_xy"); headerdatainfo.push_back("RVmax_veldisp_xz"); headerdatainfo.push_back("RVmax_veldisp_yx"); headerdatainfo.push_back("RVmax_veldisp_yy"); headerdatainfo.push_back("RVmax_veldisp_yz"); headerdatainfo.push_back("RVmax_veldisp_zx"); headerdatainfo.push_back("RVmax_veldisp_zy"); headerdatainfo.push_back("RVmax_veldisp_zz"); headerdatainfo.push_back("RVmax_lambda_B"); headerdatainfo.push_back("RVmax_Lx"); headerdatainfo.push_back("RVmax_Ly"); headerdatainfo.push_back("RVmax_Lz"); headerdatainfo.push_back("RVmax_q"); headerdatainfo.push_back("RVmax_s"); headerdatainfo.push_back("RVmax_eig_xx"); headerdatainfo.push_back("RVmax_eig_xy"); headerdatainfo.push_back("RVmax_eig_xz"); headerdatainfo.push_back("RVmax_eig_yx"); headerdatainfo.push_back("RVmax_eig_yy"); headerdatainfo.push_back("RVmax_eig_yz"); headerdatainfo.push_back("RVmax_eig_zx"); headerdatainfo.push_back("RVmax_eig_zy"); headerdatainfo.push_back("RVmax_eig_zz"); if (opt.iextrahalooutput) { headerdatainfo.push_back("Lx_200mean"); headerdatainfo.push_back("Ly_200mean"); headerdatainfo.push_back("Lz_200mean"); headerdatainfo.push_back("Lx_200crit"); headerdatainfo.push_back("Ly_200crit"); headerdatainfo.push_back("Lz_200crit"); headerdatainfo.push_back("Lx_BN98"); headerdatainfo.push_back("Ly_BN98"); headerdatainfo.push_back("Lz_BN98"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl"); headerdatainfo.push_back("Mass_200crit_excl"); headerdatainfo.push_back("Mass_BN98_excl"); headerdatainfo.push_back("R_200mean_excl"); headerdatainfo.push_back("R_200crit_excl"); headerdatainfo.push_back("R_BN98_excl"); headerdatainfo.push_back("Lx_200mean_excl"); headerdatainfo.push_back("Ly_200mean_excl"); headerdatainfo.push_back("Lz_200mean_excl"); headerdatainfo.push_back("Lx_200crit_excl"); headerdatainfo.push_back("Ly_200crit_excl"); headerdatainfo.push_back("Lz_200crit_excl"); headerdatainfo.push_back("Lx_BN98_excl"); headerdatainfo.push_back("Ly_BN98_excl"); headerdatainfo.push_back("Lz_BN98_excl"); } } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #ifdef GASON headerdatainfo.push_back("n_gas"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_gas"); headerdatainfo.push_back("M_gas_Rvmax"); headerdatainfo.push_back("M_gas_30kpc"); //headerdatainfo.push_back("M_gas_50kpc"); headerdatainfo.push_back("M_gas_500c"); headerdatainfo.push_back("Xc_gas"); headerdatainfo.push_back("Yc_gas"); headerdatainfo.push_back("Zc_gas"); headerdatainfo.push_back("VXc_gas"); headerdatainfo.push_back("VYc_gas"); headerdatainfo.push_back("VZc_gas"); headerdatainfo.push_back("Efrac_gas"); headerdatainfo.push_back("R_HalfMass_gas"); headerdatainfo.push_back("veldisp_xx_gas"); headerdatainfo.push_back("veldisp_xy_gas"); headerdatainfo.push_back("veldisp_xz_gas"); headerdatainfo.push_back("veldisp_yx_gas"); headerdatainfo.push_back("veldisp_yy_gas"); headerdatainfo.push_back("veldisp_yz_gas"); headerdatainfo.push_back("veldisp_zx_gas"); headerdatainfo.push_back("veldisp_zy_gas"); headerdatainfo.push_back("veldisp_zz_gas"); headerdatainfo.push_back("Lx_gas"); headerdatainfo.push_back("Ly_gas"); headerdatainfo.push_back("Lz_gas"); headerdatainfo.push_back("q_gas"); headerdatainfo.push_back("s_gas"); headerdatainfo.push_back("eig_xx_gas"); headerdatainfo.push_back("eig_xy_gas"); headerdatainfo.push_back("eig_xz_gas"); headerdatainfo.push_back("eig_yx_gas"); headerdatainfo.push_back("eig_yy_gas"); headerdatainfo.push_back("eig_yz_gas"); headerdatainfo.push_back("eig_zx_gas"); headerdatainfo.push_back("eig_zy_gas"); headerdatainfo.push_back("eig_zz_gas"); headerdatainfo.push_back("Krot_gas"); headerdatainfo.push_back("T_gas"); #ifdef STARON headerdatainfo.push_back("Zmet_gas"); headerdatainfo.push_back("SFR_gas"); #endif if (opt.iextragasoutput) { headerdatainfo.push_back("Mass_200mean_gas"); headerdatainfo.push_back("Mass_200crit_gas"); headerdatainfo.push_back("Mass_BN98_gas"); headerdatainfo.push_back("Lx_200c_gas"); headerdatainfo.push_back("Ly_200c_gas"); headerdatainfo.push_back("Lz_200c_gas"); headerdatainfo.push_back("Lx_200m_gas"); headerdatainfo.push_back("Ly_200m_gas"); headerdatainfo.push_back("Lz_200m_gas"); headerdatainfo.push_back("Lx_BN98_gas"); headerdatainfo.push_back("Ly_BN98_gas"); headerdatainfo.push_back("Lz_BN98_gas"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl_gas"); headerdatainfo.push_back("Mass_200crit_excl_gas"); headerdatainfo.push_back("Mass_BN98_excl_gas"); headerdatainfo.push_back("Lx_200c_excl_gas"); headerdatainfo.push_back("Ly_200c_excl_gas"); headerdatainfo.push_back("Lz_200c_excl_gas"); headerdatainfo.push_back("Lx_200m_excl_gas"); headerdatainfo.push_back("Ly_200m_excl_gas"); headerdatainfo.push_back("Lz_200m_excl_gas"); headerdatainfo.push_back("Lx_BN98_excl_gas"); headerdatainfo.push_back("Ly_BN98_excl_gas"); headerdatainfo.push_back("Lz_BN98_excl_gas"); } } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef STARON headerdatainfo.push_back("n_star"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_star"); headerdatainfo.push_back("M_star_Rvmax"); headerdatainfo.push_back("M_star_30kpc"); //headerdatainfo.push_back("M_star_50kpc"); headerdatainfo.push_back("M_star_500c"); headerdatainfo.push_back("Xc_star"); headerdatainfo.push_back("Yc_star"); headerdatainfo.push_back("Zc_star"); headerdatainfo.push_back("VXc_star"); headerdatainfo.push_back("VYc_star"); headerdatainfo.push_back("VZc_star"); headerdatainfo.push_back("Efrac_star"); headerdatainfo.push_back("R_HalfMass_star"); headerdatainfo.push_back("veldisp_xx_star"); headerdatainfo.push_back("veldisp_xy_star"); headerdatainfo.push_back("veldisp_xz_star"); headerdatainfo.push_back("veldisp_yx_star"); headerdatainfo.push_back("veldisp_yy_star"); headerdatainfo.push_back("veldisp_yz_star"); headerdatainfo.push_back("veldisp_zx_star"); headerdatainfo.push_back("veldisp_zy_star"); headerdatainfo.push_back("veldisp_zz_star"); headerdatainfo.push_back("Lx_star"); headerdatainfo.push_back("Ly_star"); headerdatainfo.push_back("Lz_star"); headerdatainfo.push_back("q_star"); headerdatainfo.push_back("s_star"); headerdatainfo.push_back("eig_xx_star"); headerdatainfo.push_back("eig_xy_star"); headerdatainfo.push_back("eig_xz_star"); headerdatainfo.push_back("eig_yx_star"); headerdatainfo.push_back("eig_yy_star"); headerdatainfo.push_back("eig_yz_star"); headerdatainfo.push_back("eig_zx_star"); headerdatainfo.push_back("eig_zy_star"); headerdatainfo.push_back("eig_zz_star"); headerdatainfo.push_back("Krot_star"); headerdatainfo.push_back("tage_star"); headerdatainfo.push_back("Zmet_star"); if (opt.iextrastaroutput) { headerdatainfo.push_back("Mass_200mean_star"); headerdatainfo.push_back("Mass_200crit_star"); headerdatainfo.push_back("Mass_BN98_star"); headerdatainfo.push_back("Lx_200c_star"); headerdatainfo.push_back("Ly_200c_star"); headerdatainfo.push_back("Lz_200c_star"); headerdatainfo.push_back("Lx_200m_star"); headerdatainfo.push_back("Ly_200m_star"); headerdatainfo.push_back("Lz_200m_star"); headerdatainfo.push_back("Lx_BN98_star"); headerdatainfo.push_back("Ly_BN98_star"); headerdatainfo.push_back("Lz_BN98_star"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl_star"); headerdatainfo.push_back("Mass_200crit_excl_star"); headerdatainfo.push_back("Mass_BN98_excl_star"); headerdatainfo.push_back("Lx_200c_excl_star"); headerdatainfo.push_back("Ly_200c_excl_star"); headerdatainfo.push_back("Lz_200c_excl_star"); headerdatainfo.push_back("Lx_200m_excl_star"); headerdatainfo.push_back("Ly_200m_excl_star"); headerdatainfo.push_back("Lz_200m_excl_star"); headerdatainfo.push_back("Lx_BN98_excl_star"); headerdatainfo.push_back("Ly_BN98_excl_star"); headerdatainfo.push_back("Lz_BN98_excl_star"); } } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef BHON headerdatainfo.push_back("n_bh"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_bh"); #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #ifdef HIGHRES headerdatainfo.push_back("n_interloper"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif headerdatainfo.push_back("M_interloper"); if (opt.iextrainterloperoutput) { headerdatainfo.push_back("Mass_200mean_interloper"); headerdatainfo.push_back("Mass_200crit_interloper"); headerdatainfo.push_back("Mass_BN98_interloper"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl_interloper"); headerdatainfo.push_back("Mass_200crit_excl_interloper"); headerdatainfo.push_back("Mass_BN98_excl_interloper"); } } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif #if defined(GASON) && defined(STARON) headerdatainfo.push_back("M_gas_sf"); headerdatainfo.push_back("R_HalfMass_gas_sf"); headerdatainfo.push_back("sigV_gas_sf"); headerdatainfo.push_back("Lx_gas_sf"); headerdatainfo.push_back("Ly_gas_sf"); headerdatainfo.push_back("Lz_gas_sf"); headerdatainfo.push_back("Krot_gas_sf"); headerdatainfo.push_back("T_gas_sf"); headerdatainfo.push_back("Zmet_gas_sf"); if (opt.iextragasoutput) { headerdatainfo.push_back("Mass_200mean_gas_sf"); headerdatainfo.push_back("Mass_200crit_gas_sf"); headerdatainfo.push_back("Mass_BN98_gas_sf"); headerdatainfo.push_back("Lx_200c_gas_sf"); headerdatainfo.push_back("Ly_200c_gas_sf"); headerdatainfo.push_back("Lz_200c_gas_sf"); headerdatainfo.push_back("Lx_200m_gas_sf"); headerdatainfo.push_back("Ly_200m_gas_sf"); headerdatainfo.push_back("Lz_200m_gas_sf"); headerdatainfo.push_back("Lx_BN98_gas_sf"); headerdatainfo.push_back("Ly_BN98_gas_sf"); headerdatainfo.push_back("Lz_BN98_gas_sf"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl_gas_sf"); headerdatainfo.push_back("Mass_200crit_excl_gas_sf"); headerdatainfo.push_back("Mass_BN98_excl_gas_sf"); headerdatainfo.push_back("Lx_200c_excl_gas_sf"); headerdatainfo.push_back("Ly_200c_excl_gas_sf"); headerdatainfo.push_back("Lz_200c_excl_gas_sf"); headerdatainfo.push_back("Lx_200m_excl_gas_sf"); headerdatainfo.push_back("Ly_200m_excl_gas_sf"); headerdatainfo.push_back("Lz_200m_excl_gas_sf"); headerdatainfo.push_back("Lx_BN98_excl_gas_sf"); headerdatainfo.push_back("Ly_BN98_excl_gas_sf"); headerdatainfo.push_back("Lz_BN98_excl_gas_sf"); } } headerdatainfo.push_back("M_gas_nsf"); headerdatainfo.push_back("R_HalfMass_gas_nsf"); headerdatainfo.push_back("sigV_gas_nsf"); headerdatainfo.push_back("Lx_gas_nsf"); headerdatainfo.push_back("Ly_gas_nsf"); headerdatainfo.push_back("Lz_gas_nsf"); headerdatainfo.push_back("Krot_gas_nsf"); headerdatainfo.push_back("T_gas_nsf"); headerdatainfo.push_back("Zmet_gas_nsf"); if (opt.iextragasoutput) { headerdatainfo.push_back("Mass_200mean_gas_nsf"); headerdatainfo.push_back("Mass_200crit_gas_nsf"); headerdatainfo.push_back("Mass_BN98_gas_nsf"); headerdatainfo.push_back("Lx_200c_gas_nsf"); headerdatainfo.push_back("Ly_200c_gas_nsf"); headerdatainfo.push_back("Lz_200c_gas_nsf"); headerdatainfo.push_back("Lx_200m_gas_nsf"); headerdatainfo.push_back("Ly_200m_gas_nsf"); headerdatainfo.push_back("Lz_200m_gas_nsf"); headerdatainfo.push_back("Lx_BN98_gas_nsf"); headerdatainfo.push_back("Ly_BN98_gas_nsf"); headerdatainfo.push_back("Lz_BN98_gas_nsf"); if (opt.iInclusiveHalo>0) { headerdatainfo.push_back("Mass_200mean_excl_gas_nsf"); headerdatainfo.push_back("Mass_200crit_excl_gas_nsf"); headerdatainfo.push_back("Mass_BN98_excl_gas_nsf"); headerdatainfo.push_back("Lx_200c_excl_gas_nsf"); headerdatainfo.push_back("Ly_200c_excl_gas_nsf"); headerdatainfo.push_back("Lz_200c_excl_gas_nsf"); headerdatainfo.push_back("Lx_200m_excl_gas_nsf"); headerdatainfo.push_back("Ly_200m_excl_gas_nsf"); headerdatainfo.push_back("Lz_200m_excl_gas_nsf"); headerdatainfo.push_back("Lx_BN98_excl_gas_nsf"); headerdatainfo.push_back("Ly_BN98_excl_gas_nsf"); headerdatainfo.push_back("Lz_BN98_excl_gas_nsf"); } } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif #endif //if aperture information calculated also include if (opt.iaperturecalc>0 && opt.aperturenum>0) { for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef GASON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_gas_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_gas_sf_")+opt.aperture_names_kpc[i]+string("_kpc"))); for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_gas_nsf_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #endif #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_star_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #ifdef HIGHRES for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_npart_interloper_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_int); #endif for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef GASON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_gas_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_gas_sf_")+opt.aperture_names_kpc[i]+string("_kpc"))); for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_gas_nsf_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #endif #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_star_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #ifdef HIGHRES for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_mass_interloper_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_rhalfmass_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef GASON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_rhalfmass_gas_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_rhalfmass_gas_sf_")+opt.aperture_names_kpc[i]+string("_kpc"))); for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_rhalfmass_gas_nsf_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #endif #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_rhalfmass_star_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_veldisp_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef GASON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_veldisp_gas_")+opt.aperture_names_kpc[i]+string("_kpc"))); #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_veldips_gas_sf_")+opt.aperture_names_kpc[i]+string("_kpc"))); for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_veldisp_gas_nsf_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #endif #ifdef STARON for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_veldisp_star_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #if defined(GASON) && defined(STARON) for (auto i=0; i<opt.aperturenum;i++) headerdatainfo.push_back((string("Aperture_SFR_gas_")+opt.aperture_names_kpc[i]+string("_kpc"))); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } if (opt.iaperturecalc>0 && opt.apertureprojnum>0) { for (auto k=0;k<3;k++) { string projname = "Projected_aperture_"+to_string(k+1)+"_"; for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("mass_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #ifdef GASON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("mass_gas_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #ifdef STARON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("mass_gas_sf_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("mass_gas_nsf_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #endif #endif #ifdef STARON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("mass_star_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #endif for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("rhalfmass_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #ifdef GASON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("rhalfmass_gas_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #ifdef STARON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("rhalfmass_gas_sf_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("rhalfmass_gas_nsf_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #endif #endif #ifdef STARON for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("rhalfmass_star_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #endif #if defined(GASON) && defined(STARON) for (auto i=0; i<opt.apertureprojnum;i++) headerdatainfo.push_back(projname+string("SFR_gas_")+opt.aperture_proj_names_kpc[i]+string("_kpc")); #endif } #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } //if aperture information calculated also include if (opt.SOnum>0) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Mass_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_R_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } #ifdef GASON if (opt.iextragasoutput && opt.iextrahalooutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Mass_gas_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } #ifdef STARON #endif } #endif #ifdef STARON if (opt.iextrastaroutput && opt.iextrahalooutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Mass_star_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } } #endif #ifdef HIGHRES if (opt.iextrainterloperoutput && opt.iextrahalooutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Mass_interloper_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } } #endif } if (opt.SOnum>0 && opt.iextrahalooutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Lx_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Ly_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Lz_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); for (auto k=0;k<3;k++) { #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } } #ifdef GASON if (opt.iextragasoutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Lx_gas_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Ly_gas_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Lz_gas_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); for (auto k=0;k<3;k++) { #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } } #ifdef STARON #endif } #endif #ifdef STARON if (opt.iextrastaroutput) { for (auto i=0; i<opt.SOnum;i++) { headerdatainfo.push_back((string("SO_Lx_star_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Ly_star_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); headerdatainfo.push_back((string("SO_Lz_star_")+opt.SOthresholds_names_crit[i]+string("_rhocrit"))); for (auto k=0;k<3;k++) { #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } } } #endif } } }; /*! Structures stores profile info of the data writen by the \ref PropData profiles data structures, specifically the \ref PropData::WriteProfileBinary, \ref PropData::WriteProfileAscii, \ref PropData::WriteProfileHDF routines */ struct ProfileDataHeader{ //list the header info vector<string> headerdatainfo; #ifdef USEHDF vector<PredType> predtypeinfo; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospredtypeinfo; #endif int numberscalarentries, numberarrayallgroupentries, numberarrayhaloentries; int offsetscalarentries, offsetarrayallgroupentries, offsetarrayhaloentries; ProfileDataHeader(Options&opt){ int sizeval; #ifdef USEHDF vector<PredType> desiredproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE); else desiredproprealtype.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif offsetscalarentries=0; headerdatainfo.push_back("ID"); #ifdef USEHDF predtypeinfo.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif //if normalisation is phys then no need for writing normalisation block if (opt.iprofilenorm != PROFILERNORMPHYS) { headerdatainfo.push_back(opt.profileradnormstring); #ifdef USEHDF predtypeinfo.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiospredtypeinfo.push_back(desiredadiosproprealtype[0]); #endif } numberscalarentries=headerdatainfo.size(); offsetarrayallgroupentries=headerdatainfo.size(); headerdatainfo.push_back("Npart_profile"); #ifdef GASON headerdatainfo.push_back("Npart_profile_gas"); #ifdef STARON headerdatainfo.push_back("Npart_profile_gas_sf"); headerdatainfo.push_back("Npart_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Npart_profile_star"); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer); #endif headerdatainfo.push_back("Mass_profile"); #ifdef GASON headerdatainfo.push_back("Mass_profile_gas"); #ifdef STARON headerdatainfo.push_back("Mass_profile_gas_sf"); headerdatainfo.push_back("Mass_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Mass_profile_star"); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real); #endif numberarrayallgroupentries=headerdatainfo.size()-offsetarrayallgroupentries; //stuff for inclusive halo/SO profiles if (opt.iInclusiveHalo >0) { offsetarrayhaloentries=headerdatainfo.size(); headerdatainfo.push_back("Npart_inclusive_profile"); #ifdef GASON headerdatainfo.push_back("Npart_inclusive_profile_gas"); #ifdef STARON headerdatainfo.push_back("Npart_inclusive_profile_gas_sf"); headerdatainfo.push_back("Npart_inclusive_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Npart_inclusive_profile_star"); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::STD_U32LE); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_unsigned_integer); #endif headerdatainfo.push_back("Mass_inclusive_profile"); #ifdef GASON headerdatainfo.push_back("Mass_inclusive_profile_gas"); #ifdef STARON headerdatainfo.push_back("Mass_inclusive_profile_gas_sf"); headerdatainfo.push_back("Mass_inclusive_profile_gas_nsf"); #endif #endif #ifdef STARON headerdatainfo.push_back("Mass_inclusive_profile_star"); #endif #ifdef USEHDF sizeval=predtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) predtypeinfo.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS sizeval=adiospredtypeinfo.size(); for (int i=sizeval;i<headerdatainfo.size();i++) adiospredtypeinfo.push_back(ADIOS_DATATYPES::adios_real); #endif numberarrayhaloentries=headerdatainfo.size()-offsetarrayhaloentries; } } }; /*! Structure used to keep track of a structure's parent structure note that level could be sim->halo->subhalo->subsubhalo or even sim->wall/void/filament->halo->substructure->subsubstructure here sim is stype=0,gid=0, and the other structure types are to be defined. The data structure is meant to be traversed from - level 0 structures ("field" objects) - level 0 pointer to nextlevel - nextlevel containing nginlevel objects */ struct StrucLevelData { ///structure type and number in current level of hierarchy Int_t stype,nsinlevel; ///points to the the head pfof address of the group and parent Particle **Phead; Int_t **gidhead; ///parent pointers point to the address of the parents gidhead and Phead Particle **Pparenthead; Int_t **gidparenthead; ///add uber parent pointer (that is pointer to field halo) Int_t **giduberparenthead; ///allowing for multiple structure types at a given level in the hierarchy Int_t *stypeinlevel; StrucLevelData *nextlevel; StrucLevelData(Int_t numgroups=-1){ if (numgroups<=0) { Phead=NULL; Pparenthead=NULL; gidhead=NULL; gidparenthead=NULL; giduberparenthead=NULL; nextlevel=NULL; stypeinlevel=NULL; nsinlevel=0; } else Allocate(numgroups); } ///just allocate memory void Allocate(Int_t numgroups){ nsinlevel=numgroups; Phead=new Particle*[numgroups+1]; gidhead=new Int_t*[numgroups+1]; stypeinlevel=new Int_t[numgroups+1]; gidparenthead=new Int_t*[numgroups+1]; giduberparenthead=new Int_t*[numgroups+1]; nextlevel=NULL; } ///initialize void Initialize(){ for (Int_t i=1;i<=nsinlevel;i++) {gidhead[i]=NULL;gidparenthead[i]=NULL;giduberparenthead[i]=NULL;} } ~StrucLevelData(){ if (nextlevel!=NULL) delete nextlevel; nextlevel=NULL; if (nsinlevel>0) { delete[] Phead; delete[] gidhead; delete[] stypeinlevel; delete[] gidparenthead; delete[] giduberparenthead; } } }; #if defined(USEHDF)||defined(USEADIOS) ///store the names of datasets in catalog output struct DataGroupNames { ///store names of catalog group files vector<string> prop; #ifdef USEHDF //store the data type vector<PredType> propdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospropdatatype; #endif ///store names of catalog group files vector<string> group; #ifdef USEHDF vector<PredType> groupdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiosgroupdatatype; #endif ///store the names of catalog particle files vector<string> part; #ifdef USEHDF vector<PredType> partdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiospartdatatype; #endif ///store the names of catalog particle type files vector<string> types; #ifdef USEHDF vector<PredType> typesdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiostypesdatatype; #endif ///store the names of hierarchy files vector<string> hierarchy; #ifdef USEHDF vector<PredType> hierarchydatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adioshierarchydatatype; #endif ///store names of SO files vector<string> SO; #ifdef USEHDF vector<PredType> SOdatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> SOdatatype; #endif //store names of profile files vector<string> profile; #ifdef USEHDF //store the data type vector<PredType> profiledatatype; #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> adiosprofiledatatype; #endif DataGroupNames(){ #ifdef USEHDF vector<PredType> desiredproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredproprealtype.push_back(PredType::NATIVE_DOUBLE); else desiredproprealtype.push_back(PredType::NATIVE_FLOAT); #endif #ifdef USEADIOS vector<ADIOS_DATATYPES> desiredadiosproprealtype; if (sizeof(Double_t)==sizeof(double)) desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_double); else desiredadiosproprealtype.push_back(ADIOS_DATATYPES::adios_real); #endif prop.push_back("File_id"); prop.push_back("Num_of_files"); prop.push_back("Num_of_groups"); prop.push_back("Total_num_of_groups"); prop.push_back("Cosmological_Sim"); prop.push_back("Comoving_or_Physical"); prop.push_back("Period"); prop.push_back("Time"); prop.push_back("Length_unit_to_kpc"); prop.push_back("Velocity_to_kms"); prop.push_back("Mass_unit_to_solarmass"); #if defined(GASON) || defined(STARON) || defined(BHON) prop.push_back("Metallicity_unit_to_solar"); prop.push_back("SFR_unit_to_solarmassperyear"); prop.push_back("Stellar_age_unit_to_yr"); #endif #ifdef USEHDF propdatatype.push_back(PredType::STD_I32LE); propdatatype.push_back(PredType::STD_I32LE); propdatatype.push_back(PredType::STD_U64LE); propdatatype.push_back(PredType::STD_U64LE); propdatatype.push_back(PredType::STD_U32LE); propdatatype.push_back(PredType::STD_U32LE); propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); #if defined(GASON) || defined(STARON) || defined(BHON) propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); propdatatype.push_back(desiredproprealtype[0]); #endif #endif #ifdef USEADIOS adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); #if defined(GASON) || defined(STARON) || defined(BHON) adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); adiospropdatatype.push_back(desiredadiosproprealtype[0]); #endif #endif group.push_back("File_id"); group.push_back("Num_of_files"); group.push_back("Num_of_groups"); group.push_back("Total_num_of_groups"); group.push_back("Group_Size"); group.push_back("Offset"); group.push_back("Offset_unbound"); #ifdef USEHDF groupdatatype.push_back(PredType::STD_I32LE); groupdatatype.push_back(PredType::STD_I32LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U32LE); groupdatatype.push_back(PredType::STD_U64LE); groupdatatype.push_back(PredType::STD_U64LE); #endif #ifdef USEADIOS adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosgroupdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif part.push_back("File_id"); part.push_back("Num_of_files"); part.push_back("Num_of_particles_in_groups"); part.push_back("Total_num_of_particles_in_all_groups"); part.push_back("Particle_IDs"); #ifdef USEHDF partdatatype.push_back(PredType::STD_I32LE); partdatatype.push_back(PredType::STD_I32LE); partdatatype.push_back(PredType::STD_U64LE); partdatatype.push_back(PredType::STD_U64LE); partdatatype.push_back(PredType::STD_I64LE); #endif #ifdef USEADIOS adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiospartdatatype.push_back(ADIOS_DATATYPES::adios_long); #endif types.push_back("File_id"); types.push_back("Num_of_files"); types.push_back("Num_of_particles_in_groups"); types.push_back("Total_num_of_particles_in_all_groups"); types.push_back("Particle_types"); #ifdef USEHDF typesdatatype.push_back(PredType::STD_I32LE); typesdatatype.push_back(PredType::STD_I32LE); typesdatatype.push_back(PredType::STD_U64LE); typesdatatype.push_back(PredType::STD_U64LE); typesdatatype.push_back(PredType::STD_U16LE); #endif #ifdef USEADIOS adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiostypesdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_short); #endif hierarchy.push_back("File_id"); hierarchy.push_back("Num_of_files"); hierarchy.push_back("Num_of_groups"); hierarchy.push_back("Total_num_of_groups"); hierarchy.push_back("Number_of_substructures_in_halo"); hierarchy.push_back("Parent_halo_ID"); #ifdef USEHDF hierarchydatatype.push_back(PredType::STD_I32LE); hierarchydatatype.push_back(PredType::STD_I32LE); hierarchydatatype.push_back(PredType::STD_U64LE); hierarchydatatype.push_back(PredType::STD_U64LE); hierarchydatatype.push_back(PredType::STD_U32LE); hierarchydatatype.push_back(PredType::STD_I64LE); #endif #ifdef USEADIOS adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adioshierarchydatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); #endif SO.push_back("File_id"); SO.push_back("Num_of_files"); SO.push_back("Num_of_SO_regions"); SO.push_back("Total_num_of_SO_regions"); SO.push_back("Num_of_particles_in_SO_regions"); SO.push_back("Total_num_of_particles_in_SO_regions"); SO.push_back("SO_size"); SO.push_back("Offset"); SO.push_back("Particle_IDs"); #if defined(GASON) || defined(STARON) || defined(BHON) SO.push_back("Particle_types"); #endif #ifdef USEHDF SOdatatype.push_back(PredType::STD_I32LE); SOdatatype.push_back(PredType::STD_I32LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_U32LE); SOdatatype.push_back(PredType::STD_U64LE); SOdatatype.push_back(PredType::STD_I64LE); #if defined(GASON) || defined(STARON) || defined(BHON) SOdatatype.push_back(PredType::STD_I32LE); #endif #endif #ifdef USEADIOS adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_integer); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_long); #if defined(GASON) || defined(STARON) || defined(BHON) adiosSOdatatype.push_back(ADIOS_DATATYPES::adios_integer); #endif #endif profile.push_back("File_id"); profile.push_back("Num_of_files"); profile.push_back("Num_of_groups"); profile.push_back("Total_num_of_groups"); profile.push_back("Num_of_halos"); profile.push_back("Total_num_of_halos"); profile.push_back("Radial_norm"); profile.push_back("Inclusive_profiles_flag"); profile.push_back("Num_of_bin_edges"); profile.push_back("Radial_bin_edges"); #ifdef USEHDF profiledatatype.push_back(PredType::STD_I32LE); profiledatatype.push_back(PredType::STD_I32LE); profiledatatype.push_back(PredType::STD_U64LE); profiledatatype.push_back(PredType::STD_U64LE); profiledatatype.push_back(PredType::STD_U64LE); profiledatatype.push_back(PredType::STD_U64LE); profiledatatype.push_back(PredType::C_S1); profiledatatype.push_back(PredType::STD_I32LE); profiledatatype.push_back(PredType::STD_I32LE); profiledatatype.push_back(desiredproprealtype[0]); #endif #ifdef USEADIOS adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_unsigned_long); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_string); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(ADIOS_DATATYPES::adios_integer); adiosprofiledatatype.push_back(desiredadiosproprealtype[0]); #endif } }; #endif ///Useful structore to store information of leaf nodes in the tree struct leaf_node_info{ int num, numtot; Int_t id, istart, iend; Coordinate cm; Double_t size; #ifdef USEMPI Double_t searchdist; #endif }; ///if using MPI API #ifdef USEMPI #include <mpi.h> ///Includes external global variables used for MPI version of code #include "mpivar.h" #endif extern StrucLevelData *psldata; #endif
{ "alphanum_fraction": 0.6490147362, "avg_line_length": 38.1906420022, "ext": "h", "hexsha": "9cf741ed875eafdfa85e2218878572fe2c55cd16", "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": "3d518101e870b943777155d585db2e458e74e13f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mtrebitsch/VELOCIraptor-STF", "max_forks_repo_path": "src/allvars.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d518101e870b943777155d585db2e458e74e13f", "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": "mtrebitsch/VELOCIraptor-STF", "max_issues_repo_path": "src/allvars.h", "max_line_length": 224, "max_stars_count": null, "max_stars_repo_head_hexsha": "3d518101e870b943777155d585db2e458e74e13f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mtrebitsch/VELOCIraptor-STF", "max_stars_repo_path": "src/allvars.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 48274, "size": 175486 }
#pragma once #include "Cesium3DTiles/BoundingVolume.h" #include "Cesium3DTiles/Gltf.h" #include "Cesium3DTiles/Library.h" #include "Cesium3DTiles/TileContentLoadResult.h" #include "Cesium3DTiles/TileContentLoader.h" #include "Cesium3DTiles/TileID.h" #include "Cesium3DTiles/TileRefine.h" #include "CesiumGltf/GltfReader.h" #include <cstddef> #include <glm/mat4x4.hpp> #include <gsl/span> #include <spdlog/fwd.h> namespace Cesium3DTiles { class Tileset; /** * @brief Creates {@link TileContentLoadResult} from glTF data. */ class CESIUM3DTILES_API GltfContent final : public TileContentLoader { public: /** * @copydoc TileContentLoader::load * * The result will only contain the `model`. Other fields will be * empty or have default values. */ std::unique_ptr<TileContentLoadResult> load(const TileContentLoadInput& input) override; /** * @brief Create a {@link TileContentLoadResult} from the given data. * * (Only public to be called from `Batched3DModelContent`) * * @param pLogger Only used for logging * @param url The URL, only used for logging * @param data The actual glTF data * @return The {@link TileContentLoadResult} */ static std::unique_ptr<TileContentLoadResult> load( const std::shared_ptr<spdlog::logger>& pLogger, const std::string& url, const gsl::span<const std::byte>& data); /** * @brief Creates texture coordinates for raster tiles that are mapped to 3D * tiles. * * This is not supposed to be called by clients. * * It will be called for all {@link RasterMappedTo3DTile} objects of a * {@link Tile}, and extend the accessors of the given glTF model with * accessors that contain the texture coordinate sets for different * projections. Further details are not specified here. * * @param gltf The glTF model. * @param textureCoordinateID The texture coordinate ID. * @param projection The {@link CesiumGeospatial::Projection}. * @param rectangle The {@link CesiumGeometry::Rectangle}. * @return The bounding region. */ static CesiumGeospatial::BoundingRegion createRasterOverlayTextureCoordinates( CesiumGltf::Model& gltf, uint32_t textureCoordinateID, const CesiumGeospatial::Projection& projection, const CesiumGeometry::Rectangle& rectangle); private: static CesiumGltf::GltfReader _gltfReader; }; } // namespace Cesium3DTiles
{ "alphanum_fraction": 0.7274989631, "avg_line_length": 31.3116883117, "ext": "h", "hexsha": "edd11c5d0ecfec1ae0546de0ff9a42696f221d66", "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": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "zy6p/cesium-native", "max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "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": "zy6p/cesium-native", "max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "zy6p/cesium-native", "max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/GltfContent.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 641, "size": 2411 }
#ifndef IOSLICEMUT_H #define IOSLICEMUT_H #include <WinSock2.h> #include <variant> #include <gsl/span> namespace laio { template<typename T> using Result = std::variant<T, std::exception>; namespace net { class IoSpanMut { WSABUF _raw_wsa_buffer; public: explicit constexpr IoSpanMut(const WSABUF& wsaBuffer) noexcept : _raw_wsa_buffer{wsaBuffer} {} explicit constexpr IoSpanMut(WSABUF&& wsaBuffer) noexcept : _raw_wsa_buffer{std::move(wsaBuffer)} {} // NOLINT(hicpp-move-const-arg,performance-move-const-arg) static inline IoSpanMut create(unsigned char buf[]) noexcept { static_assert(sizeof(*buf) <= (std::numeric_limits<ULONG>::max)()); // Seriously? Casting an unsigned char to a signed char? // Well behaved for all 128 ASCII characters - Blows up for any value lesser than 0 or greater than 127 return IoSpanMut{std::move(WSABUF{ // NOLINT(hicpp-move-const-arg,performance-move-const-arg) sizeof(*buf), reinterpret_cast<CHAR*>(buf), })}; } inline Result<std::monostate> advance(std::size_t n) noexcept { if (static_cast<std::size_t>(sizeof(_raw_wsa_buffer.len)) < n) { return std::out_of_range("Advancing out of range"); } _raw_wsa_buffer.len -= static_cast<ULONG>(n); _raw_wsa_buffer.buf += n; return std::monostate{}; } inline gsl::span<const unsigned char> as_span() noexcept { return gsl::span<const unsigned char>{ reinterpret_cast<const unsigned char*>(_raw_wsa_buffer.buf), static_cast<int>(_raw_wsa_buffer.len) }; } inline gsl::span<unsigned char> as_mut_span() noexcept { return gsl::span<unsigned char>{ reinterpret_cast<unsigned char*>(_raw_wsa_buffer.buf), static_cast<int>(_raw_wsa_buffer.len) }; } }; } // namespace net } // namespace laio #endif // IOSLICEMUT_H
{ "alphanum_fraction": 0.5650066108, "avg_line_length": 34.9076923077, "ext": "h", "hexsha": "ff99dfb9124ee395f0c372512204a21598aac0db", "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": "b94040757213b77639c7ea368b2efa83ca71b164", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mjptree/laio", "max_forks_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b94040757213b77639c7ea368b2efa83ca71b164", "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": "mjptree/laio", "max_issues_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_line_length": 119, "max_stars_count": null, "max_stars_repo_head_hexsha": "b94040757213b77639c7ea368b2efa83ca71b164", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mjptree/laio", "max_stars_repo_path": "src/laio_net/utils/IoSpanMut.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 503, "size": 2269 }
#define _XOPEN_SOURCE 600 #include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <stdint.h> #include <time.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <errno.h> #include "fileio.h" #include "ipf_balance.h" #include "likelihood.h" #include "master_tasks.h" #include "mutation.h" #include "randomisation.h" #include "resampling.h" #include "typedefs.h" static const int ALG = 5; static const int MASTER = 0; int main ( int argc, char *argv[] ) { struct Process process; struct Estimates estimates; long * inds; long * BM; int do_resampling; double * w; double * x; double * x_resamp; double * proc_w; double * output; double my_normal_weight; double rsamp_time = 0; double rsamp_start = 0; double comm_time = 0; double comm_start; double comm_time2 = 0; double total_w = 1.0; double weight_time = 0.0; double mutation_time = 0.0; double init_time = 0.0; long n_xfer; unsigned int *cnts; long *cnts_l; const gsl_rng_type *T; double timer_start; // Parse command line arguments int run_idx = 0; if(argc > 1) run_idx = atoi(argv[1]); long N = 1000; if(argc > 2) N = atol(argv[2]); int state_dim; if ( argc > 3 ) state_dim = atoi( argv[ 3 ] ); else { perror("State dimesion must be provided"); return -1; } double epc_threshold; if (argc > 4 ) epc_threshold = atof( argv[ 4 ] ); else { perror("Reampling threshold must be provided"); return -1; } // Initialize the MPI environment MPI_Init(NULL, NULL); gsl_rng_env_setup(); T = gsl_rng_default; gsl_rng *rgen; rgen = gsl_rng_alloc( T ); // Get the number of processes int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // Get the rank of the process int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); // Start the timer struct timespec start_time;; clock_gettime(CLOCK_REALTIME, &start_time); MPI_Barrier( MPI_COMM_WORLD ); timer_start = MPI_Wtime(); long data_length; process = readProcessFile( state_dim ); data_length = (int)process.n; //--------------- // Initialisation //--------------- x = malloc( sizeof( double ) * N * state_dim); w = malloc( sizeof( double ) * N ); inds = malloc( sizeof( long ) * N ); x_resamp = malloc( sizeof( double ) * N * state_dim); proc_w = malloc( sizeof( double ) * world_size ); cnts = malloc( sizeof( unsigned int ) * world_size ); cnts_l = malloc( sizeof( long ) * world_size ); BM = malloc( sizeof( long ) * world_size * world_size ); initialise_balancing( world_size ); // Initial distribution setup setupInitialSeed( world_rank, rgen ); // Create initial sample createInitialSample( x, N, rgen, state_dim ); // Setup the randomisation set_resamplingseed( world_rank ); int output_dim = 2 + state_dim + 2 * world_size + world_size * state_dim; if ( world_rank == MASTER ) output = malloc( sizeof( double ) * output_dim * data_length ); MPI_Barrier( MPI_COMM_WORLD ); init_time += MPI_Wtime() - timer_start; my_normal_weight = 1.0 / world_size; // main loop for( long n = 0; n < data_length; n++ ) { // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); timer_start = MPI_Wtime(); evaluateLikelihoods( x, process, state_dim, data_length, N, n, w, my_normal_weight ); MPI_Barrier( MPI_COMM_WORLD ); weight_time += MPI_Wtime() - timer_start ; // compute the relevant estimates estimates = estimateOutput( w, x, world_rank, N, run_idx, state_dim ); // Combine the results of all filters combineEstimates( world_rank, state_dim, estimates, output, n, output_dim, world_size, &total_w, &my_normal_weight, &do_resampling, epc_threshold ); // printf("My weight %i: %f\n", (int)world_rank,my_normal_weight); // ----------------------------- // RESAMPLING // ----------------------------- // Resampling within processors MPI_Barrier( MPI_COMM_WORLD ); rsamp_start = MPI_Wtime(); serial_multinomial_resample_sng_noutk( N, w, inds, N ); for ( long i = 0; i < N; i++) for ( int d = 0; d < state_dim; d++ ) x_resamp[ state_dim * i + d ] = x[ state_dim * inds[ i ] + d ]; for ( long i = 0; i < N; i++) for ( int d = 0; d < state_dim ; d++ ) x[ state_dim * i + d ] = x_resamp[ state_dim * i + d ]; // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); rsamp_time += MPI_Wtime() - rsamp_start; comm_start = MPI_Wtime(); if ( do_resampling ) { //my_weight = estimates.w; // sum of weights for the current process // -------------------------- // START THE FULL INTERACTION // -------------------------- // Processes send their weights to the MASTER process MPI_Gather( &my_normal_weight, 1, MPI_DOUBLE, proc_w, 1, MPI_DOUBLE, MASTER, MPI_COMM_WORLD ); MPI_Barrier( MPI_COMM_WORLD ); // Sample how many particles need to be taken from each process if ( world_rank == MASTER ) { gsl_ran_multinomial( rgen, ( size_t ) world_size, ( unsigned int ) ( world_size ), proc_w, cnts ); for( int j = 0; j < world_size; j++ ) cnts_l[ j ] = ( long ) cnts[ j ]; } // Send the island resampled index array to all processes MPI_Bcast( cnts_l, world_size, MPI_LONG, MASTER, MPI_COMM_WORLD ); //if ( world_rank == MASTER ) // for ( int j = 0; j < world_size; j++ ) // output[ output_dim * n + count_offset + j ] = cnts_l[ j ]; // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); comm_time2 += MPI_Wtime() - comm_start; comm_start = MPI_Wtime(); // Calculate how the islands should be communicated calculate_balancing_matrix( cnts_l, world_size , BM , 1 ); if ( cnts_l[ world_rank ] < 1 ) { // this process needs an island // iterate over all processes (other than the current) and see if that // process has surplus particles for ( int i = 0; i < world_size; i++ ) { if ( i != world_rank ) { // NB! BM[ world_size * i + world_rank ] should be 0 or 1 n_xfer = BM[ world_size * i + world_rank ] * N; if ( n_xfer > 0 ) { MPI_Recv( x, N * state_dim, MPI_DOUBLE, i, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE ); cnts_l[ world_rank ] += n_xfer; } } } } else if ( cnts_l[ world_rank ] > 1 ) { // this process has excess islands // iterate over all processes (other than the current) and see if // they need particles for (int i = 0; i < world_size; i++ ) { if( world_rank != i ) { // NB! BM[ world_size * i + world_rank ] should be 0 or 1 n_xfer = BM[ world_size * world_rank + i] * N; if ( n_xfer > 0 ) { MPI_Send( x, n_xfer * state_dim, MPI_DOUBLE, i, 2, MPI_COMM_WORLD ); cnts_l[ world_rank ] -= n_xfer; } } } } my_normal_weight = 1.0 / world_size; } //else { // printf("Skip resample!\n"); // } //if ( world_rank == MASTER ) { // printf("%i: %f\n", (int)n,my_normal_weight); //} // ---------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); comm_time += MPI_Wtime() - comm_start; timer_start = MPI_Wtime(); mutation(N, x, state_dim, rgen ); // ----------------------------------------------------------------------------- MPI_Barrier( MPI_COMM_WORLD ); mutation_time += MPI_Wtime() - timer_start ; } struct timespec end_time; clock_gettime(CLOCK_REALTIME, &end_time); createOutput( ALG, world_rank, output, data_length, world_size, run_idx, N, state_dim, start_time, end_time, comm_time, rsamp_time, comm_time2, weight_time, mutation_time, init_time, (int)( atof( argv[ 4 ] ) * 100 ) ); finalise_balancing(); // Finalize the MPI environment. MPI_Finalize(); return 0; }
{ "alphanum_fraction": 0.5752447722, "avg_line_length": 26.6012861736, "ext": "c", "hexsha": "994b25adb4e47b5d22403bbfad7eee90bc8b36cc", "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": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_path": "src/ipf2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "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": "heinekmp/AIRPF", "max_issues_repo_path": "src/ipf2.c", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_path": "src/ipf2.c", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "num_tokens": 2274, "size": 8273 }
/* integration/workspace.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> gsl_integration_workspace * gsl_integration_workspace_alloc (const size_t n) { gsl_integration_workspace * w ; if (n == 0) { GSL_ERROR_VAL ("workspace length n must be positive integer", GSL_EDOM, 0); } w = (gsl_integration_workspace *) malloc (sizeof (gsl_integration_workspace)); if (w == 0) { GSL_ERROR_VAL ("failed to allocate space for workspace struct", GSL_ENOMEM, 0); } w->alist = (double *) malloc (n * sizeof (double)); if (w->alist == 0) { free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for alist ranges", GSL_ENOMEM, 0); } w->blist = (double *) malloc (n * sizeof (double)); if (w->blist == 0) { free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for blist ranges", GSL_ENOMEM, 0); } w->rlist = (double *) malloc (n * sizeof (double)); if (w->rlist == 0) { free (w->blist); free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for rlist ranges", GSL_ENOMEM, 0); } w->elist = (double *) malloc (n * sizeof (double)); if (w->elist == 0) { free (w->rlist); free (w->blist); free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for elist ranges", GSL_ENOMEM, 0); } w->order = (size_t *) malloc (n * sizeof (size_t)); if (w->order == 0) { free (w->elist); free (w->rlist); free (w->blist); free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for order ranges", GSL_ENOMEM, 0); } w->level = (size_t *) malloc (n * sizeof (size_t)); if (w->level == 0) { free (w->order); free (w->elist); free (w->rlist); free (w->blist); free (w->alist); free (w); /* exception in constructor, avoid memory leak */ GSL_ERROR_VAL ("failed to allocate space for order ranges", GSL_ENOMEM, 0); } w->size = 0 ; w->limit = n ; w->maximum_level = 0 ; return w ; } void gsl_integration_workspace_free (gsl_integration_workspace * w) { free (w->level) ; free (w->order) ; free (w->elist) ; free (w->rlist) ; free (w->blist) ; free (w->alist) ; free (w) ; } /* size_t gsl_integration_workspace_limit (gsl_integration_workspace * w) { return w->limit ; } size_t gsl_integration_workspace_size (gsl_integration_workspace * w) { return w->size ; } */
{ "alphanum_fraction": 0.6236499585, "avg_line_length": 23.4480519481, "ext": "c", "hexsha": "dcf8ee0bca416d0fb9c1cddd43e1bb6b75f64f27", "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/integration/workspace.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/integration/workspace.c", "max_line_length": 72, "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/integration/workspace.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": 1024, "size": 3611 }
/** * Interface of spce_pathlength.h */ #ifndef _SPCE_PATHLENGTH_H #define _SPCE_PATHLENGTH_H #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_spline.h> #include "spc_trace_functions.h" extern int abscissa_to_pathlength (const trace_func * const func, gsl_vector * const data); #endif /* !_SPCE_PATHLENGTH_H */
{ "alphanum_fraction": 0.762295082, "avg_line_length": 19.2631578947, "ext": "h", "hexsha": "dc0f71ea42ee694e284c577d8f484b8cd70ed243", "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/spce_pathlength.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/spce_pathlength.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/spce_pathlength.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 100, "size": 366 }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program */ /* GCG --- Generic Column Generation */ /* a Dantzig-Wolfe decomposition based extension */ /* of the branch-cut-and-price framework */ /* SCIP --- Solving Constraint Integer Programs */ /* */ /* Copyright (C) 2010-2019 Operations Research, RWTH Aachen University */ /* Zuse Institute Berlin (ZIB) */ /* */ /* This program 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 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 Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file graph_gcg.h * @brief Implementation of the graph which supports both node and edge weights. * @author Igor Pesic */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef GCG_GRAPH_GCG_H_ #define GCG_GRAPH_GCG_H_ #include <map> #include "bridge.h" #ifdef WITH_GSL #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_spblas.h> #endif namespace gcg { class EdgeGCG { public: int src, dest; double weight; EdgeGCG() {} EdgeGCG(int s, int d, double w): src(s), dest(d), weight(w) {} } ; class GraphGCG: public gcg::Bridge { private: bool undirected; bool locked; // true if we are not allowed to change the graph anymore bool initialized; // true if at least 1 node std::vector<int> nodes; #ifdef WITH_GSL gsl_spmatrix* adj_matrix_sparse; gsl_spmatrix* working_adj_matrix; // this one is used ONLY during MCL algorithm! #else std::vector<std::vector<double>> adj_matrix; /** For undirected graphs, this matrix is symmetrical */ #endif std::vector<EdgeGCG*> edges; public: GraphGCG(); GraphGCG(int _n_nodes, bool _undirected); virtual ~GraphGCG(); virtual SCIP_RETCODE addNNodes(int _n_nodes); virtual SCIP_RETCODE addNNodes(int _n_nodes, std::vector<int> weights); virtual int getNNodes(); virtual int getNEdges(); #ifdef WITH_GSL virtual gsl_spmatrix* getAdjMatrix(); virtual void expand(int factor); virtual void inflate(double factor); virtual void colL1Norm(); virtual void prune(); virtual bool stopMCL(int iter); virtual std::vector<int> getClustersMCL(); virtual void initMCL(); virtual void clearMCL(); #else virtual std::vector<std::vector<double>> getAdjMatrix(); #endif virtual SCIP_RETCODE getEdges(std::vector<void*>& edges); virtual SCIP_Bool isEdge(int node_i, int node_j); virtual int getNNeighbors(int node); virtual std::vector<int> getNeighbors(int node); virtual std::vector<std::pair<int, double> > getNeighborWeights(int node); virtual SCIP_RETCODE addNode(int node, int weight); virtual SCIP_RETCODE addNode(); /** Sets node weight to 0 and the ID to the next available. */ virtual SCIP_RETCODE deleteNode(int node); virtual SCIP_RETCODE addEdge(int i, int j); /** Sets edge weight to 1. */ virtual SCIP_RETCODE addEdge(int node_i, int node_j, double weight); virtual SCIP_RETCODE setEdge(int node_i, int node_j, double weight); virtual SCIP_RETCODE deleteEdge(int node_i, int node_j); virtual int graphGetWeights(int node); virtual double getEdgeWeight(int node_i, int node_j); virtual int edgeComp(const EdgeGCG* a, const EdgeGCG* b); virtual SCIP_RETCODE flush(); // lock the graph and compresses the adj matrix if we use GSL virtual SCIP_RETCODE normalize(); virtual double getEdgeWeightPercentile(double q); }; } /* namespace gcg */ #endif /* GCG_GRAPH_GCG_H_ */
{ "alphanum_fraction": 0.5582906656, "avg_line_length": 42.3166666667, "ext": "h", "hexsha": "bb70a64eada23fb9a150ab3e3f3b6b2780f076c5", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-19T01:15:11.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-19T01:15:11.000Z", "max_forks_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "avrech/scipoptsuite-6.0.2-avrech", "max_forks_repo_path": "gcg/src/graph/graph_gcg.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "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": "avrech/scipoptsuite-6.0.2-avrech", "max_issues_repo_path": "gcg/src/graph/graph_gcg.h", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "avrech/scipoptsuite-6.0.2-avrech", "max_stars_repo_path": "gcg/src/graph/graph_gcg.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1162, "size": 5078 }
/* MPCOTool: The Multi-Purposes Calibration and Optimization Tool. A software to perform calibrations or optimizations of empirical parameters. AUTHORS: Javier Burguete and Borja Latorre. Copyright 2012-2019, AUTHORS. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file main.c * \brief Main source file. * \authors Javier Burguete and Borja Latorre. * \copyright Copyright 2012-2019, all rights reserved. */ #define _GNU_SOURCE #include "config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <locale.h> #include <gsl/gsl_rng.h> #include <libxml/parser.h> #include <libintl.h> #include <glib.h> #include <json-glib/json-glib.h> #ifdef G_OS_WIN32 #include <windows.h> #endif #if HAVE_MPI #include <mpi.h> #endif #if HAVE_GTK #include <gio/gio.h> #include <gtk/gtk.h> #endif #include "genetic/genetic.h" #include "utils.h" #include "experiment.h" #include "variable.h" #include "input.h" #include "optimize.h" #if HAVE_GTK #include "interface.h" #endif #include "mpcotool.h" int main (int argn, char **argc) { #if HAVE_GTK show_pending = process_pending; #endif return mpcotool (argn, argc); }
{ "alphanum_fraction": 0.7636986301, "avg_line_length": 29.5696202532, "ext": "c", "hexsha": "4ea87389464f1fa053bb3288af6f2150d2b918e7", "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": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/mpcotool", "max_forks_repo_path": "4.0.5/main.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "jburguete/mpcotool", "max_issues_repo_path": "4.0.5/main.c", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/mpcotool", "max_stars_repo_path": "4.0.5/main.c", "max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z", "num_tokens": 547, "size": 2336 }
/** * \file DelayInterface.h */ #ifndef ATK_DELAY_DELAYINTERFACE_H #define ATK_DELAY_DELAYINTERFACE_H #include <ATK/Delay/config.h> #include <gsl/gsl> #include <map> namespace ATK { /// Interface for a fixed filter class ATK_DELAY_EXPORT DelayInterface { public: virtual ~DelayInterface() = default; /// Sets the delay of the filter virtual void set_delay(gsl::index delay) = 0; /// Returns the delay virtual gsl::index get_delay() const = 0; }; /// Interface for a universal filter template<class DataType> class ATK_DELAY_EXPORT UniversalDelayInterface { public: virtual ~UniversalDelayInterface() = default; /// Sets the blend of the filter virtual void set_blend(DataType blend) = 0; /// Returns the blend virtual DataType get_blend() const = 0; /// Sets the feedback of the filter virtual void set_feedback(DataType feedback) = 0; /// Returns the feedback virtual DataType get_feedback() const = 0; /// Sets the feedforward of the filter virtual void set_feedforward(DataType feedforward) = 0; /// Returns the feedforward virtual DataType get_feedforward() const = 0; }; } #endif
{ "alphanum_fraction": 0.6943744752, "avg_line_length": 23.82, "ext": "h", "hexsha": "c5ed4a1af7d356bacdca115fd37f59289bc4f8aa", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_path": "ATK/Delay/DelayInterface.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_path": "ATK/Delay/DelayInterface.h", "max_line_length": 59, "max_stars_count": 23, "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_path": "ATK/Delay/DelayInterface.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "num_tokens": 284, "size": 1191 }
#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" void purify(LDP ld, double threshold_min, double threshold_max); struct ld_purify_params { double threshold_min, threshold_max; const char* file_input; const char* file_output; }; int main(int argc, const char * argv[]) { sm_set_program_name(argv[0]); options_banner("ld_purify: Makes sure that the file format is valid. \n * Sets valid=0 if reading is outside interval "); struct ld_purify_params p; struct option* ops = options_allocate(20); options_double(ops, "threshold_min", &p.threshold_min, 0.01, "Sets valid=0 if readings are less than this threshold."); options_double(ops, "threshold_max", &p.threshold_max, 79.0, "Sets valid=0 if readings are more than this threshold."); 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)) { 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; LDP ld; int count = -1; while( (ld = ld_from_json_stream(in))) { purify(ld, p.threshold_min, p.threshold_max); if(!ld_valid_fields(ld)) { sm_error("Wait, we didn't purify enough (#%d in file)\n", count); continue; } ld_write_as_json(ld, out); ld_free(ld); } return 0; } void purify(LDP ld, double threshold_min, double threshold_max) { for(int i=0;i<ld->nrays;i++) { if(!ld->valid[i]) continue; double rho = ld->readings[i]; if( is_nan(rho) | (rho < threshold_min) | (rho > threshold_max) ) { ld->readings[i] = GSL_NAN; ld->valid[i] = 0; ld->alpha[i] = GSL_NAN; ld->alpha_valid[i] = 0; } } }
{ "alphanum_fraction": 0.672242551, "avg_line_length": 21.7386363636, "ext": "c", "hexsha": "53de4558288e615e087b1087586c97baf891e41d", "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_purify.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_purify.c", "max_line_length": 122, "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_purify.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 572, "size": 1913 }
#include <algorithm> #include <numeric> #ifdef HAS_MKL #include <mkl.h> #else #include <cblas.h> #endif #ifdef __SSE4_2__ #include <emmintrin.h> #endif typedef double Real; inline void GetTotalTraction_(Real *TotalTraction, const Real *CauchyStressTensor, const Real *ElectricDisplacementx, int ndim) { if (ndim==3) { TotalTraction[0] = CauchyStressTensor[0]; TotalTraction[1] = CauchyStressTensor[4]; TotalTraction[2] = CauchyStressTensor[8]; TotalTraction[3] = CauchyStressTensor[1]; TotalTraction[4] = CauchyStressTensor[2]; TotalTraction[5] = CauchyStressTensor[5]; TotalTraction[6] = ElectricDisplacementx[0]; TotalTraction[7] = ElectricDisplacementx[1]; TotalTraction[8] = ElectricDisplacementx[2]; } else if (ndim == 2) { TotalTraction[0] = CauchyStressTensor[0]; TotalTraction[1] = CauchyStressTensor[3]; TotalTraction[2] = CauchyStressTensor[1]; TotalTraction[3] = ElectricDisplacementx[0]; TotalTraction[4] = ElectricDisplacementx[1]; } } inline void FillConstitutiveB_(Real *B, const Real* SpatialGradient, int ndim, int nvar, int rows, int cols) { int i = 0; if (ndim == 3) { for (; i<rows; ++i) { // Store in registers const Real a0 = SpatialGradient[i*ndim]; const Real a1 = SpatialGradient[i*ndim+1]; const Real a2 = SpatialGradient[i*ndim+2]; // MECHANICAL TERMS B[i*cols*nvar] = a0; B[i*cols*nvar+cols+1] = a1; B[i*cols*nvar+2*(cols+1)] = a2; B[i*cols*nvar+cols+5] = a2; B[i*cols*nvar+2*cols+5] = a1; B[i*cols*nvar+4] = a2; B[i*cols*nvar+2*cols+4] = a0; B[i*cols*nvar+3] = a1; B[i*cols*nvar+cols+3] = a0; // ELECTROSTATIC TERMS B[i*cols*nvar+3*cols+6] = a0; B[i*cols*nvar+3*cols+7] = a1; B[i*cols*nvar+3*cols+8] = a2; } } else if (ndim == 2) { for (; i<rows; ++i) { // Store in registers const Real a0 = SpatialGradient[i*ndim]; const Real a1 = SpatialGradient[i*ndim+1]; // MECHANICAL TERMS B[i*cols*nvar] = a0; B[i*cols*nvar+cols+1] = a1; B[i*cols*nvar+2] = a1; B[i*cols*nvar+cols+2] = a0; // ELECTROSTATIC TERMS B[i*cols*nvar+2*cols+3] = a0; B[i*cols*nvar+2*cols+4] = a1; } } } inline void _ConstitutiveStiffnessIntegrandDPF_Filler_(Real *stiffness, Real *traction, const Real* SpatialGradient, const Real* ElectricDisplacementx, const Real* CauchyStressTensor, const Real* H_Voigt, const Real* detJ, int ngauss, int noderpelem, int ndim, int nvar, int H_VoigtSize, int requires_geometry_update) { int local_size = nvar*noderpelem; Real *t; #ifdef __SSE4_2__ if (ndim==3) { t = (Real*)_mm_malloc(9*sizeof(Real),32); } else if (ndim==2) { t = (Real*)_mm_malloc(5*sizeof(Real),32); } Real *B = (Real*)_mm_malloc(H_VoigtSize*local_size*sizeof(Real),32); Real *HBT = (Real*)_mm_malloc(H_VoigtSize*local_size*sizeof(Real),32); Real *BDB_1 = (Real*)_mm_malloc(local_size*local_size*sizeof(Real),32); #else if (ndim==3) { t = (Real*)malloc(9*sizeof(Real)); } else if (ndim==2) { t = (Real*)malloc(5*sizeof(Real)); } // Real *local_traction = (Real*)malloc(local_size*sizeof(Real)); // std::fill(local_traction,local_traction+local_size,0.); Real *B = (Real*)malloc(H_VoigtSize*local_size*sizeof(Real)); Real *HBT = (Real*)malloc(H_VoigtSize*local_size*sizeof(Real)); Real *BDB_1 = (Real*)malloc(local_size*local_size*sizeof(Real)); #endif std::fill(B,B+H_VoigtSize*local_size,0.); // std::fill(HBT,HBT+H_VoigtSize*local_size,0.); for (int igauss = 0; igauss < ngauss; ++igauss) { FillConstitutiveB_(B,&SpatialGradient[igauss*ndim*noderpelem],ndim,nvar,noderpelem,H_VoigtSize); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, H_VoigtSize, local_size, H_VoigtSize, 1.0, &H_Voigt[igauss*H_VoigtSize*H_VoigtSize], H_VoigtSize, B, H_VoigtSize, 0.0, HBT, local_size); cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, local_size, local_size, H_VoigtSize, 1.0, B, H_VoigtSize, HBT, local_size, 0.0, BDB_1, local_size); // Multiply stiffness with detJ const Real detJ_igauss = detJ[igauss]; for (int i=0; i<local_size*local_size; ++i) { stiffness[i] += BDB_1[i]*detJ_igauss; } if (requires_geometry_update==1) { // Compute tractions GetTotalTraction_(t, &CauchyStressTensor[igauss*ndim*ndim], &ElectricDisplacementx[igauss*ndim], ndim); // Multiply B with traction - for loop is okay // std::fill(local_traction,local_traction+local_size,0.); for (int i=0; i<local_size; ++i) { Real tmp = 0; for (int j=0; j<H_VoigtSize; ++j) { tmp += B[i*H_VoigtSize+j]*t[j]; } // local_traction[i] = tmp; traction[i] += tmp*detJ_igauss; } // // Multiply traction with detJ // for (int i=0; i<local_size; ++i) { // traction[i] += local_traction[i]*detJ_igauss; // } } } #ifdef __SSE4_2__ _mm_free(t); _mm_free(B); _mm_free(HBT); _mm_free(BDB_1); #else free(t); // free(local_traction); free(B); free(HBT); free(BDB_1); #endif // Real AA[12]; // 3x4 // Real BB[12]; // 4x3 // Real CC[12]; // std::iota(AA,AA+12,1); // std::iota(BB,BB+12,2); // cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, // 3, 3, 4, 1.0, AA, 4, BB, 3, 0.0, CC, 3); // for (int i=0; i<9; ++i) { // // std::cout << AA[i] << " " << BB[i] << '\n'; // std::cout << CC[i] << '\n'; // } // std::cout << '\n'; }
{ "alphanum_fraction": 0.5480739117, "avg_line_length": 29.7023255814, "ext": "h", "hexsha": "3ee72e6bb580413a0bda7f4439390d1536a93d06", "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/_ConstitutiveStiffness_/_ConstitutiveStiffnessDPF_.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/_ConstitutiveStiffness_/_ConstitutiveStiffnessDPF_.h", "max_line_length": 148, "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/_ConstitutiveStiffness_/_ConstitutiveStiffnessDPF_.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": 2072, "size": 6386 }
#ifndef _GALAXY_H_ #define _GALAXY_H_ #include <vector> #include <gsl/gsl_integration.h> #include "cosmology.h" #include <vector_types.h> class galaxy{ double ra, dec, red, w, nbar; double3 cart; bool cart_set; public: galaxy(double RA, double DEC, double RED, double NZ, double W); void bin(std::vector<double> &delta, int3 N, double3 L, double3 r_min, cosmology &cosmo, double3 &pk_nbw, double3 &bk_nbw, gsl_integration_workspace *ws); void set_cartesian(cosmology &cosmo, double3 r_min, gsl_integration_workspace *ws); double3 get_unshifted_cart(cosmology &cosmo, gsl_integration_workspace *ws); double3 get_cart(); }; #endif
{ "alphanum_fraction": 0.6434210526, "avg_line_length": 26.2068965517, "ext": "h", "hexsha": "67bfe0e4f224f5b8684d633a2917f7636abf8f95", "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": "5c805a432d948490290d209c1856fdb0bc9d1b8d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dpearson1983/CUBE", "max_forks_repo_path": "include/galaxy.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c805a432d948490290d209c1856fdb0bc9d1b8d", "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": "dpearson1983/CUBE", "max_issues_repo_path": "include/galaxy.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "5c805a432d948490290d209c1856fdb0bc9d1b8d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dpearson1983/CUBE", "max_stars_repo_path": "include/galaxy.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 199, "size": 760 }
/* * Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com * * 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 or any later version. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. A copy of the GNU General Public License is available at: * http://www.fsf.org/licensing/licenses */ /***************************************************************************** * dgt_usefftw.h * * Discrete Gabor Transform by Using FFTW. * * These routines are designed for calculating discrete Gabor transform and * its inversion of 1D signals. In order to eliminate the border effect, the * input signal("signal") is extended by three forms: zeros padded("zpd"), * periodized extension("ppd") and symetric extension("sym"). * * The analysis/synthesis function is given by users, and it's daul * (synthesis/analysis) function can be computed by "daul" routine. The over * sampling rate is equal to N/dM, where N denotes frequency sampling numbers * and dM denotes the time sampling interval. * * N and dM should can be devided evenly by the window length "Lw". The * recovered signal just has the elements from 1 to dM*floor(Ls/dM) of the * original signal. So you'd better let dM can be deviede evenly by the * original signal length "Ls". * * Zhang Ming, 2010-03, Xi'an Jiaotong University. *****************************************************************************/ #ifndef DGT_USEFFTW_H #define DGT_USEFFTW_H #include <string> #include <complex> #include <fftw.h> #include <matrix.h> #include <linequs1.h> //#include <linequs3.h> #include <utilities.h> namespace splab { template<typename Type> Vector<Type> daulFFTW( const Vector<Type>&, int, int ); template<typename Type> Matrix< complex<Type> > dgtFFTW( const Vector<Type>&, const Vector<Type>&, int, int, const string &mode = "zpd" ); template<typename Type> Vector<Type> idgtFFTW( const Matrix< complex<Type> >&, const Vector<Type>&, int, int ); #include <dgt_usefftw-impl.h> } // namespace splab #endif // DGT_USEFFTW_H
{ "alphanum_fraction": 0.6320075164, "avg_line_length": 35.8764044944, "ext": "h", "hexsha": "92858272fa9226ef1708822ade0bc8c279ab6cba", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2020-10-14T07:34:59.000Z", "max_forks_repo_forks_event_min_datetime": "2016-04-26T10:14:20.000Z", "max_forks_repo_head_hexsha": "14ed37d1cc72e55d1592e78e3dda758cd46a3698", "max_forks_repo_licenses": [ "Naumen", "Condor-1.1", "MS-PL" ], "max_forks_repo_name": "wjiang/motioncorr", "max_forks_repo_path": "src/SP++3/include/dgt_usefftw.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "14ed37d1cc72e55d1592e78e3dda758cd46a3698", "max_issues_repo_issues_event_max_datetime": "2016-06-10T01:07:42.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-24T10:55:18.000Z", "max_issues_repo_licenses": [ "Naumen", "Condor-1.1", "MS-PL" ], "max_issues_repo_name": "wjiang/motioncorr", "max_issues_repo_path": "src/SP++3/include/dgt_usefftw.h", "max_line_length": 80, "max_stars_count": 11, "max_stars_repo_head_hexsha": "c77ee034bba2ef184837e070dde43f75d8a4e1e7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cianfrocco-lab/Motion-correction", "max_stars_repo_path": "motioncorr_v2.1/src/SP++3/include/dgt_usefftw.h", "max_stars_repo_stars_event_max_datetime": "2021-01-21T02:58:43.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-21T19:47:53.000Z", "num_tokens": 687, "size": 3193 }
/* bst/gsl_bst_rb.h * * 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. */ #ifndef __GSL_BST_RB_H__ #define __GSL_BST_RB_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_bst_types.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 #ifndef GSL_BST_RB_MAX_HEIGHT #define GSL_BST_RB_MAX_HEIGHT 48 #endif /* red-black node */ struct gsl_bst_rb_node { struct gsl_bst_rb_node *rb_link[2]; /* subtrees */ void *rb_data; /* pointer to data */ unsigned char rb_color; /* color */ }; /* red-black tree data structure */ typedef struct { struct gsl_bst_rb_node *rb_root; /* tree's root */ gsl_bst_cmp_function *rb_compare; /* comparison function */ void *rb_param; /* extra argument to |rb_compare| */ const gsl_bst_allocator *rb_alloc; /* memory allocator */ size_t rb_count; /* number of items in tree */ unsigned long rb_generation; /* generation number */ } gsl_bst_rb_table; /* red-black traverser structure */ typedef struct { const gsl_bst_rb_table *rb_table; /* tree being traversed */ struct gsl_bst_rb_node *rb_node; /* current node in tree */ struct gsl_bst_rb_node *rb_stack[GSL_BST_RB_MAX_HEIGHT]; /* all the nodes above |rb_node| */ size_t rb_height; /* number of nodes in |rb_parent| */ unsigned long rb_generation; /* generation number */ } gsl_bst_rb_traverser; __END_DECLS #endif /* __GSL_BST_RB_H__ */
{ "alphanum_fraction": 0.6728902166, "avg_line_length": 31.5058823529, "ext": "h", "hexsha": "370a6c2d8ae47857769b2514fa7463ac2e1add5d", "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_bst_rb.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_bst_rb.h", "max_line_length": 82, "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_bst_rb.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": 650, "size": 2678 }
/* ** read nuisance covariates file into a matrix ** ** G.Lohmann, MPI-KYB, 2018 */ #include <viaio/Vlib.h> #include <viaio/mu.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> extern int VStringToken (char *,char *,int,int); extern int line_empty(char *buf,int len); extern int CheckBuffer(char *buf,int len); extern int VistaFormat(char *buf,int len); extern int test_ascii(int val); gsl_matrix *VReadCovariates(VString cfile,VBoolean demean) { float x=0; int i=0,j=0,nrows=0,ncols=0,len=10000,tlen=80; char *buf = (char *)VCalloc(len,sizeof(char)); char *token = (char *)VCalloc(tlen,sizeof(char)); FILE *fp = fopen(cfile,"r"); if (fp == NULL) VError(" err opening covariates file %s",cfile); /* get matrix dimensions */ while (!feof(fp)) { for (j=0; j<len; j++) buf[j] = '\0'; if (fgets(buf,len,fp) == NULL) break; if (VistaFormat(buf,len) > 1) VError(" File %s must be a text file",cfile); if (CheckBuffer(buf,len) < 1) continue; if (! test_ascii((int)buf[0])) VError(" File %s: line %d begins with an illegal character (%c)",cfile,nrows,buf[0]); j = 0; while (VStringToken(buf,token,j,tlen)) { sscanf(token,"%f",&x); j++; } if (j > ncols) ncols = j; nrows++; } rewind(fp); fprintf(stderr," Nuisance covariates: %d x %d\n",nrows,ncols); if (ncols < 1) VError(" Nuisance covariates: no columns in file %s",cfile); /* read into matrix */ gsl_matrix *dest = gsl_matrix_calloc(nrows,ncols); i=0; while (!feof(fp)) { for (j=0; j<len; j++) buf[j] = '\0'; if (fgets(buf,len,fp) == NULL) break; if (CheckBuffer(buf,len) < 1) continue; j = 0; while (VStringToken(buf,token,j,tlen)) { if (j >= ncols) break; sscanf(token,"%f",&x); gsl_matrix_set(dest,i,j,(double)x); j++; } i++; if (i >= nrows) break; } if (!demean) return dest; /* subtract mean */ double u=0,sum1=0,sum2=0,nx=0,mean=0,sigma=0,tiny=1.0e-6; for (i=0; i<dest->size2; i++) { sum1 = sum2 = nx = 0; for (j=0; j<dest->size1; j++) { u = gsl_matrix_get(dest,j,i); sum1 += u; sum2 += u*u; nx++; } mean = sum1/nx; sigma = sqrt((sum2 - nx * mean * mean) / (nx - 1.0)); if (sigma < tiny) VError(" Nuisance regressors: column %d is constant",i); for (j=0; j<dest->size1; j++) { u = gsl_matrix_get(dest,j,i); u = (u-mean); gsl_matrix_set(dest,j,i,u); } } return dest; }
{ "alphanum_fraction": 0.5875728155, "avg_line_length": 24.7596153846, "ext": "c", "hexsha": "5cbce8d57f937baa4515b4add36680442b44cc20", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/vlisa_2ndlevel/Covariates.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/vlisa_2ndlevel/Covariates.c", "max_line_length": 120, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/vlisa_2ndlevel/Covariates.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 864, "size": 2575 }
#include <stdio.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_integration.h> #include "testint.c" gsl_integration_workspace *w; int inverse; double cauchy (double x, void *p) { return gsl_ran_cauchy_pdf (x, *(double*)p); } double gaussian (double x, void *p) { return gsl_ran_gaussian_pdf (x, *(double*)p); } double laplace (double x, void *p) { return gsl_ran_laplace_pdf (x, *(double*)p); } double rayleigh (double x, void *p) { return gsl_ran_rayleigh_pdf (x, *(double*)p); } double flat (double x, void *p) { double * c = (double *)p; return gsl_ran_flat_pdf (x, c[0], c[1]); } double lognormal (double x, void *p) { double * c = (double *)p; return gsl_ran_lognormal_pdf (x, c[0], c[1]); } double gamma (double x, void *p) { double * c = (double *)p; return gsl_ran_gamma_pdf (x, c[0], c[1]); } double chisq (double x, void *p) { double * c = (double *)p; return gsl_ran_chisq_pdf (x, c[0]); } double fdist (double x, void *p) { double * c = (double *)p; return gsl_ran_fdist_pdf (x, c[0], c[1]); } double tdist (double x, void *p) { double * c = (double *)p; return gsl_ran_tdist_pdf (x, c[0]); } double beta (double x, void *p) { double * c = (double *)p; return gsl_ran_beta_pdf (x, c[0], c[1]); } double gumbel1 (double x, void *p) { double * c = (double *)p; return gsl_ran_gumbel1_pdf (x, c[0], c[1]); } double gumbel2 (double x, void *p) { double * c = (double *)p; return gsl_ran_gumbel2_pdf (x, c[0], c[1]); } double weibull (double x, void *p) { double * c = (double *)p; return gsl_ran_weibull_pdf (x, c[0], c[1]); } double pareto (double x, void *p) { double * c = (double *)p; return gsl_ran_pareto_pdf (x, c[0], c[1]); } double logistic (double x, void *p) { double * c = (double *)p; return gsl_ran_logistic_pdf (x, c[0]); } double integrate (gsl_function * f, double a, double b) { double res = 0, err = 0; double tol = 1e-12; gsl_integration_qag (f, a, b, 0, tol, 1000, 0, w, &res, &err); return res; } double integrate_lower (gsl_function * f, double b) { double res = 0, err = 0; qagil (f, b, 0, 1e-12, 1000, w, &res, &err); return res; } double integrate_upper (gsl_function * f, double a) { double res = 0, err = 0; qagiu (f, a, 0, 1e-12, 1000, w, &res, &err); return res; } int test (const char * name, gsl_function * f, double x[], int N, char *fmt) { int i; double res, err, sum = 0, sumerr = 0; printf ("void test_auto_%s (void);\n\n", name); printf ("void\ntest_auto_%s (void)\n{\n", name); /* gsl_set_error_handler_off(); */ w = gsl_integration_workspace_alloc (1000); for (i = 0; i < N; i++) { res = 0; err = 0; if (x[0] < -1000) { if (x[i] < 0) { res = integrate_lower (f, x[i]); } else { res = 1 - integrate_upper (f, x[i]); } sum = res; } else { if (i == 0) sum += 0; else sum += integrate(f, x[i-1], x[i]); } if (res < 0) continue; printf (fmt, "_P", x[i], sum); if (inverse && (sum != 0 && sum != 1) && (x[i] == 0 || sum * 1e-4 < GSL_FN_EVAL(f,x[i]) * fabs(x[i]))) printf (fmt, "_Pinv", sum, x[i]); } printf("\n"); sum=0; sumerr=0; for (i = N-1; i >= 0; i--) { res = 0; err = 0; if (x[N-1] > 1000) { if (x[i] > 0) { res = integrate_upper (f, x[i]); } else { res = 1-integrate_lower (f, x[i]); } sum = res; } else { if (i == N-1) sum += 0; else sum += integrate(f, x[i], x[i+1]); } printf (fmt, "_Q", x[i], sum); if (inverse && (sum != 0 && sum != 1) && (x[i] == 0 || sum * 1e-4 < GSL_FN_EVAL(f,x[i]) * fabs(x[i]))) printf (fmt, "_Qinv", sum, x[i]); } printf ("}\n\n"); gsl_integration_workspace_free (w); } int main (void) { const int N = 43; double xall[] = { -1e10, -1e9, -1e8, -1e7, -1e6, -1e5, -1e4, -1e3, -1e2, -1e1, -1, -1e-1, -1e-2, -1e-3, -1e-4, -1e-5, -1e-6, -1e-7, -1e-8, -1e-9, -1e-10, 0, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 }; const int Npos = 22; double xpos[] = { 0, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 }; const int N01 = 23; double x01[] = { 0, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 0.9, 0.99, 0.999, 0.9999, 0.99999, 1.0 }; #define TEST(name,params,range,n) { double p[] = { params } ; gsl_function f = {&name, p}; test(#name, &f, range, n, " TEST(gsl_cdf_" #name "%s, (%.16e," #params "), %.12e, TEST_TOL6);\n"); } #define TEST2(name,p1,p2,range,n) { double p[] = { p1,p2 } ; gsl_function f = {&name, p}; test(#name, &f, range, n, " TEST(gsl_cdf_" #name "%s, (%.16e," #p1 "," #p2 "), %.12e, TEST_TOL6);\n"); } #define TEST2A(desc,name,p1,p2,range,n) { double p[] = { p1,p2 } ; gsl_function f = {&name, p}; test(#desc, &f, range, n, " TEST(gsl_cdf_" #name "%s, (%.16e," #p1 "," #p2 "), %.12e, TEST_TOL6);\n"); } inverse = 0; TEST2(beta, 1.3, 2.7, x01, N01); TEST2(fdist, 5.3, 2.7, xpos, Npos); inverse = 1; TEST(cauchy, 1.3, xall, N); TEST(gaussian, 1.3, xall, N); TEST(laplace, 1.3, xall, N); TEST(rayleigh, 1.3, xpos, Npos); TEST2(flat, 1.3, 750.0, xpos, Npos); TEST2(lognormal, 1.3,2.7, xpos, Npos); TEST2(gamma, 1.3,2.7, xpos, Npos); TEST(chisq, 1.3, xpos, Npos); TEST(tdist, 1.3, xall, N); TEST2(gumbel1, 1.3, 2.7, xall, N); TEST2(gumbel2, 1.3, 2.7, xpos, Npos); TEST2(weibull, 1.3, 2.7, xpos, Npos); TEST2(pareto, 1.3, 2.7, xpos, Npos); TEST(logistic, 1.3, xall, N); TEST2A(gammalarge, gamma, 1.3,123.0, xpos, Npos); }
{ "alphanum_fraction": 0.5204764236, "avg_line_length": 20.0950819672, "ext": "c", "hexsha": "500e758406a6be5be402a4db7e0c0aea8a5a4dbc", "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/cdf/testgen.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/cdf/testgen.c", "max_line_length": 203, "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/cdf/testgen.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": 2587, "size": 6129 }
/* permutation/test.c * * Copyright (C) 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. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_permute_double.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> unsigned int p5[120][5] = { {0, 1, 2, 3, 4}, {0, 1, 2, 4, 3}, {0, 1, 3, 2, 4}, {0, 1, 3, 4, 2}, {0, 1, 4, 2, 3}, {0, 1, 4, 3, 2}, {0, 2, 1, 3, 4}, {0, 2, 1, 4, 3}, {0, 2, 3, 1, 4}, {0, 2, 3, 4, 1}, {0, 2, 4, 1, 3}, {0, 2, 4, 3, 1}, {0, 3, 1, 2, 4}, {0, 3, 1, 4, 2}, {0, 3, 2, 1, 4}, {0, 3, 2, 4, 1}, {0, 3, 4, 1, 2}, {0, 3, 4, 2, 1}, {0, 4, 1, 2, 3}, {0, 4, 1, 3, 2}, {0, 4, 2, 1, 3}, {0, 4, 2, 3, 1}, {0, 4, 3, 1, 2}, {0, 4, 3, 2, 1}, {1, 0, 2, 3, 4}, {1, 0, 2, 4, 3}, {1, 0, 3, 2, 4}, {1, 0, 3, 4, 2}, {1, 0, 4, 2, 3}, {1, 0, 4, 3, 2}, {1, 2, 0, 3, 4}, {1, 2, 0, 4, 3}, {1, 2, 3, 0, 4}, {1, 2, 3, 4, 0}, {1, 2, 4, 0, 3}, {1, 2, 4, 3, 0}, {1, 3, 0, 2, 4}, {1, 3, 0, 4, 2}, {1, 3, 2, 0, 4}, {1, 3, 2, 4, 0}, {1, 3, 4, 0, 2}, {1, 3, 4, 2, 0}, {1, 4, 0, 2, 3}, {1, 4, 0, 3, 2}, {1, 4, 2, 0, 3}, {1, 4, 2, 3, 0}, {1, 4, 3, 0, 2}, {1, 4, 3, 2, 0}, {2, 0, 1, 3, 4}, {2, 0, 1, 4, 3}, {2, 0, 3, 1, 4}, {2, 0, 3, 4, 1}, {2, 0, 4, 1, 3}, {2, 0, 4, 3, 1}, {2, 1, 0, 3, 4}, {2, 1, 0, 4, 3}, {2, 1, 3, 0, 4}, {2, 1, 3, 4, 0}, {2, 1, 4, 0, 3}, {2, 1, 4, 3, 0}, {2, 3, 0, 1, 4}, {2, 3, 0, 4, 1}, {2, 3, 1, 0, 4}, {2, 3, 1, 4, 0}, {2, 3, 4, 0, 1}, {2, 3, 4, 1, 0}, {2, 4, 0, 1, 3}, {2, 4, 0, 3, 1}, {2, 4, 1, 0, 3}, {2, 4, 1, 3, 0}, {2, 4, 3, 0, 1}, {2, 4, 3, 1, 0}, {3, 0, 1, 2, 4}, {3, 0, 1, 4, 2}, {3, 0, 2, 1, 4}, {3, 0, 2, 4, 1}, {3, 0, 4, 1, 2}, {3, 0, 4, 2, 1}, {3, 1, 0, 2, 4}, {3, 1, 0, 4, 2}, {3, 1, 2, 0, 4}, {3, 1, 2, 4, 0}, {3, 1, 4, 0, 2}, {3, 1, 4, 2, 0}, {3, 2, 0, 1, 4}, {3, 2, 0, 4, 1}, {3, 2, 1, 0, 4}, {3, 2, 1, 4, 0}, {3, 2, 4, 0, 1}, {3, 2, 4, 1, 0}, {3, 4, 0, 1, 2}, {3, 4, 0, 2, 1}, {3, 4, 1, 0, 2}, {3, 4, 1, 2, 0}, {3, 4, 2, 0, 1}, {3, 4, 2, 1, 0}, {4, 0, 1, 2, 3}, {4, 0, 1, 3, 2}, {4, 0, 2, 1, 3}, {4, 0, 2, 3, 1}, {4, 0, 3, 1, 2}, {4, 0, 3, 2, 1}, {4, 1, 0, 2, 3}, {4, 1, 0, 3, 2}, {4, 1, 2, 0, 3}, {4, 1, 2, 3, 0}, {4, 1, 3, 0, 2}, {4, 1, 3, 2, 0}, {4, 2, 0, 1, 3}, {4, 2, 0, 3, 1}, {4, 2, 1, 0, 3}, {4, 2, 1, 3, 0}, {4, 2, 3, 0, 1}, {4, 2, 3, 1, 0}, {4, 3, 0, 1, 2}, {4, 3, 0, 2, 1}, {4, 3, 1, 0, 2}, {4, 3, 1, 2, 0}, {4, 3, 2, 0, 1}, {4, 3, 2, 1, 0} } ; unsigned int c5[120][5] = { {4, 3, 2, 1, 0}, {3, 4, 2, 1, 0}, {4, 2, 3, 1, 0}, {2, 3, 4, 1, 0}, {2, 4, 3, 1, 0}, {3, 2, 4, 1, 0}, {4, 3, 1, 2, 0}, {3, 4, 1, 2, 0}, {4, 1, 2, 3, 0}, {1, 2, 3, 4, 0}, {1, 2, 4, 3, 0}, {3, 1, 2, 4, 0}, {4, 1, 3, 2, 0}, {1, 3, 4, 2, 0}, {4, 2, 1, 3, 0}, {2, 1, 3, 4, 0}, {2, 4, 1, 3, 0}, {1, 3, 2, 4, 0}, {1, 4, 3, 2, 0}, {3, 1, 4, 2, 0}, {2, 1, 4, 3, 0}, {3, 2, 1, 4, 0}, {1, 4, 2, 3, 0}, {2, 3, 1, 4, 0}, {4, 3, 2, 0, 1}, {3, 4, 2, 0, 1}, {4, 2, 3, 0, 1}, {2, 3, 4, 0, 1}, {2, 4, 3, 0, 1}, {3, 2, 4, 0, 1}, {4, 3, 0, 1, 2}, {3, 4, 0, 1, 2}, {4, 0, 1, 2, 3}, {0, 1, 2, 3, 4}, {0, 1, 2, 4, 3}, {3, 0, 1, 2, 4}, {4, 0, 1, 3, 2}, {0, 1, 3, 4, 2}, {4, 2, 0, 1, 3}, {2, 0, 1, 3, 4}, {2, 4, 0, 1, 3}, {0, 1, 3, 2, 4}, {0, 1, 4, 3, 2}, {3, 0, 1, 4, 2}, {2, 0, 1, 4, 3}, {3, 2, 0, 1, 4}, {0, 1, 4, 2, 3}, {2, 3, 0, 1, 4}, {4, 3, 0, 2, 1}, {3, 4, 0, 2, 1}, {4, 0, 2, 3, 1}, {0, 2, 3, 4, 1}, {0, 2, 4, 3, 1}, {3, 0, 2, 4, 1}, {4, 3, 1, 0, 2}, {3, 4, 1, 0, 2}, {4, 1, 0, 2, 3}, {1, 0, 2, 3, 4}, {1, 0, 2, 4, 3}, {3, 1, 0, 2, 4}, {4, 1, 3, 0, 2}, {1, 3, 4, 0, 2}, {4, 0, 2, 1, 3}, {0, 2, 1, 3, 4}, {0, 2, 4, 1, 3}, {1, 3, 0, 2, 4}, {1, 4, 3, 0, 2}, {3, 1, 4, 0, 2}, {0, 2, 1, 4, 3}, {3, 0, 2, 1, 4}, {1, 4, 0, 2, 3}, {0, 2, 3, 1, 4}, {4, 0, 3, 2, 1}, {0, 3, 4, 2, 1}, {4, 2, 0, 3, 1}, {2, 0, 3, 4, 1}, {2, 4, 0, 3, 1}, {0, 3, 2, 4, 1}, {4, 1, 0, 3, 2}, {1, 0, 3, 4, 2}, {4, 2, 1, 0, 3}, {2, 1, 0, 3, 4}, {2, 4, 1, 0, 3}, {1, 0, 3, 2, 4}, {4, 0, 3, 1, 2}, {0, 3, 4, 1, 2}, {4, 1, 2, 0, 3}, {1, 2, 0, 3, 4}, {1, 2, 4, 0, 3}, {0, 3, 1, 2, 4}, {0, 3, 1, 4, 2}, {1, 4, 0, 3, 2}, {1, 4, 2, 0, 3}, {0, 3, 2, 1, 4}, {2, 1, 4, 0, 3}, {2, 0, 3, 1, 4}, {0, 4, 3, 2, 1}, {3, 0, 4, 2, 1}, {2, 0, 4, 3, 1}, {3, 2, 0, 4, 1}, {0, 4, 2, 3, 1}, {2, 3, 0, 4, 1}, {1, 0, 4, 3, 2}, {3, 1, 0, 4, 2}, {2, 1, 0, 4, 3}, {3, 2, 1, 0, 4}, {1, 0, 4, 2, 3}, {2, 3, 1, 0, 4}, {0, 4, 3, 1, 2}, {3, 0, 4, 1, 2}, {1, 2, 0, 4, 3}, {3, 1, 2, 0, 4}, {0, 4, 1, 2, 3}, {1, 2, 3, 0, 4}, {1, 3, 0, 4, 2}, {0, 4, 1, 3, 2}, {0, 4, 2, 1, 3}, {1, 3, 2, 0, 4}, {2, 0, 4, 1, 3}, {2, 1, 3, 0, 4} } ; unsigned int cycles[120] = { 5, 4, 4, 3, 3, 4, 4, 3, 3, 2, 2, 3, 3, 2, 4, 3, 3, 2, 2, 3, 3, 4, 2, 3, 4, 3, 3, 2, 2, 3, 3, 2, 2, 1, 1, 2, 2, 1, 3, 2, 2, 1, 1, 2, 2, 3, 1, 2, 3, 2, 2, 1, 1, 2, 4, 3, 3, 2, 2, 3, 3, 2, 2, 1, 1, 2, 2, 3, 1, 2, 2, 1, 2, 1, 3, 2, 2, 1, 3, 2, 4, 3, 3, 2, 2, 1, 3, 2, 2, 1, 1, 2, 2, 1, 3, 2, 1, 2, 2, 3, 1, 2, 2, 3, 3, 4, 2, 3, 1, 2, 2, 3, 1, 2, 2, 1, 1, 2, 2, 3 } ; unsigned int inversions[120] = { 0, 1, 1, 2, 2, 3, 1, 2, 2, 3, 3, 4, 2, 3, 3, 4, 4, 5, 3, 4, 4, 5, 5, 6, 1, 2, 2, 3, 3, 4, 2, 3, 3, 4, 4, 5, 3, 4, 4, 5, 5, 6, 4, 5, 5, 6, 6, 7, 2, 3, 3, 4, 4, 5, 3, 4, 4, 5, 5, 6, 4, 5, 5, 6, 6, 7, 5, 6, 6, 7, 7, 8, 3, 4, 4, 5, 5, 6, 4, 5, 5, 6, 6, 7, 5, 6, 6, 7, 7, 8, 6, 7, 7, 8, 8, 9, 4, 5, 5, 6, 6, 7, 5, 6, 6, 7, 7, 8, 6, 7, 7, 8, 8, 9, 7, 8, 8, 9, 9, 10 } ; int main (void) { gsl_ieee_env_setup (); { int i = 0, j, status = 0; gsl_permutation * p ; p = gsl_permutation_alloc (5); gsl_permutation_init (p); do { for (j = 0; j < 5; j++) { status |= (p->data[j] != p5[i][j]); } i++; } while (gsl_permutation_next(p) == GSL_SUCCESS); gsl_test(status, "gsl_permutation_next, 5-th order permutation, 120 steps"); do { i--; for (j = 0; j < 5; j++) { status |= (p->data[j] != p5[i][j]); } } while (gsl_permutation_prev(p) == GSL_SUCCESS); gsl_test(status, "gsl_permutation_prev, 5-th order permutation, 120 steps"); gsl_permutation_free (p); } #ifdef JUNK { int i; int status = 0 ; gsl_permutation * p1 = gsl_permutation_alloc (5); gsl_permutation * p2 = gsl_permutation_alloc (5); gsl_permutation * p = gsl_permutation_alloc (5); double v[5] = { 100.0, 101.0, 102.0, 103.0, 104.0 } ; gsl_permutation_init (p1); do { gsl_permutation_init (p2); do { double x[5], y[5]; /* Compute x= p1 p2 v */ memcpy (x, v, 5 * sizeof(double)); gsl_permute (p2->data, x, 1, 5); gsl_permute (p1->data, x, 1, 5); /* Compute P= p1 p2, y = P v */ gsl_permutation_mul (p, p1, p2); memcpy (y, v, 5 * sizeof(double)); gsl_permute (p->data, y, 1, 5); for (i = 0; i < 5; i++) { if (x[i] != y[i]) status = 1; } if (status == 1) break; } while (gsl_permutation_next(p2) == GSL_SUCCESS); if (status == 1) break; } while (gsl_permutation_next(p1) == GSL_SUCCESS); gsl_permutation_free (p1); gsl_permutation_free (p2); gsl_permutation_free (p); gsl_test(status, "gsl_permutation_mul, all 5-th order combinations"); } #endif /* testing cycles representations */ { int i = 0, j, status = 0; gsl_permutation * p = gsl_permutation_alloc (5); gsl_permutation * plin = gsl_permutation_alloc (5); gsl_permutation * pcan = gsl_permutation_alloc (5); gsl_permutation_init (p); do { gsl_permutation_memcpy (plin, p); for (j = 0; j < 5; j++) { pcan->data[j] = 0; } gsl_permutation_linear_to_canonical (pcan, plin); for (j = 0; j < 5; j++) { status |= (pcan->data[j] != c5[i][j]); } status |= (gsl_permutation_canonical_cycles (pcan) != cycles[i]); status |= (gsl_permutation_linear_cycles (plin) != cycles[i]); for (j = 0; j < 5; j++) { plin->data[j] = 0; } gsl_permutation_canonical_to_linear (plin, pcan); for (j = 0; j < 5; j++) { status |= (plin->data[j] != p5[i][j]); } i++; } while (gsl_permutation_next(p) == GSL_SUCCESS); gsl_permutation_free (p); gsl_permutation_free (plin); gsl_permutation_free (pcan); gsl_test (status, "gsl_permutation canonical conversion, 5-th order permutation, 120 steps"); } /* testing number of inversions */ { int i = 0, status = 0; gsl_permutation * p = gsl_permutation_alloc (5); gsl_permutation_init (p); do { status |= gsl_permutation_inversions (p) != inversions[i]; i++; } while (gsl_permutation_next(p) == GSL_SUCCESS); gsl_permutation_free (p); gsl_test (status, "gsl_permutation_inversions, 5-th order permutation, 120 steps"); } exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.4215588059, "avg_line_length": 33.1627906977, "ext": "c", "hexsha": "9e76e5654e40241cb91807d0e9bd6e4abe0a5f6c", "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/test.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/test.c", "max_line_length": 97, "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/test.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": 5824, "size": 9982 }
/** * * @file al4san/codelet_dlacpy.c * * @copyright 2009-2014 The University of Tennessee and The University of * Tennessee Research Foundation. All rights reserved. * @copyright 2012-2018 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria, * Univ. Bordeaux. All rights reserved. * @copyright 2017-2018 King Abdullah University of Science and Technology (KAUST). * All rights reserved. * @brief Chameleon dlacpy AL4SAN codelet * * @version 1.1.0 * @author Rabab Alomairy * @date 2018-09-19 * @generated d Wed Jan 16 11:13:56 2019 * */ /** * * @ingroup CORE_CHAMELEON_Complex64_t * */ #include <lapacke.h> #include <al4san.h> #include <runtime/al4san_quark.h> #include <runtime/al4san_starpu.h> AL4SAN_TASK_CPU(lacpy1, lacpy_cpu_func1) void EIG_AL4SAN_CORE_dlacpy1(AL4SAN_option_t *options, int uplo, int m, int n, int nb, const AL4SAN_desc_t *A, int Am, int An, int lda, const AL4SAN_desc_t *B, int Bm, int Bn, int ldb ) { (void)nb; AL4SAN_Insert_Task(AL4SAN_TASK(lacpy1), (AL4SAN_option_t*)options, AL4SAN_VALUE, &uplo, sizeof(int), AL4SAN_VALUE, &m, sizeof(int), AL4SAN_VALUE, &n, sizeof(int), AL4SAN_INPUT, AL4SAN_ADDR(A, double, Am, An), AL4SAN_DEP, AL4SAN_VALUE, &lda, sizeof(int), AL4SAN_OUTPUT, AL4SAN_ADDR(B, double, Bm, Bn), AL4SAN_DEP, AL4SAN_VALUE, &ldb, sizeof(int), AL4SAN_PRIORITY, options->priority, sizeof(int), AL4SAN_LABEL, "dlacpy", sizeof(char), AL4SAN_COLOR, "white", sizeof(char), ARG_END); } #if !defined(CHAMELEON_SIMULATION) void lacpy_cpu_func1(AL4SAN_arg_list *al4san_arg) { int uplo; int M; int N; int displA; int displB; const double *A; int LDA; double *B; int LDB; AL4SAN_Unpack_Arg(al4san_arg, &uplo, &M, &N, &A, &LDA, &B, &LDB); CORE_dlacpy(uplo, M, N, A, LDA, B , LDB); } #endif /* !defined(CHAMELEON_SIMULATION) */
{ "alphanum_fraction": 0.5019485581, "avg_line_length": 35.1506849315, "ext": "c", "hexsha": "06addacaf1e9948ae5aadaed52b115281b93116a", "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": "93bc603d2b6262439a659ef98908839f678f1c95", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ecrc/al4san", "max_forks_repo_path": "example/gesvp/codelets/al4san/codelet_dlacpy1.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95", "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": "ecrc/al4san", "max_issues_repo_path": "example/gesvp/codelets/al4san/codelet_dlacpy1.c", "max_line_length": 103, "max_stars_count": 9, "max_stars_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ecrc/al4san", "max_stars_repo_path": "example/gesvp/codelets/al4san/codelet_dlacpy1.c", "max_stars_repo_stars_event_max_datetime": "2021-05-12T19:35:26.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-25T19:18:14.000Z", "num_tokens": 662, "size": 2566 }
#pragma once #include "Common.h" #include <boost/graph/adjacency_list.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/edge_list.hpp> #include <boost/graph/graph_selectors.hpp> #include <boost/graph/properties.hpp> #include <boost/graph/visitors.hpp> #include <any> #include <forward_list> #include <functional> #include <gsl/span> #include <set> #include <string_view> #include <variant> namespace bcos::scheduler { class GraphKeyLocks { public: using Ptr = std::shared_ptr<GraphKeyLocks>; using KeyLock = std::tuple<std::string, std::string>; using KeyLockView = std::tuple<std::string_view, std::string_view>; using ContractView = std::string_view; using KeyView = std::string_view; GraphKeyLocks() = default; GraphKeyLocks(const GraphKeyLocks&) = delete; GraphKeyLocks(GraphKeyLocks&&) = delete; GraphKeyLocks& operator=(const GraphKeyLocks&) = delete; GraphKeyLocks& operator=(GraphKeyLocks&&) = delete; bool batchAcquireKeyLock(std::string_view contract, gsl::span<std::string const> keyLocks, ContextID contextID, Seq seq); bool acquireKeyLock( std::string_view contract, std::string_view key, ContextID contextID, Seq seq); std::vector<std::string> getKeyLocksNotHoldingByContext( std::string_view contract, ContextID excludeContextID) const; void releaseKeyLocks(ContextID contextID, Seq seq); bool detectDeadLock(ContextID contextID); struct Vertex : public std::variant<ContextID, KeyLock> { using std::variant<ContextID, KeyLock>::variant; bool operator==(const KeyLockView& rhs) const { if (index() != 1) { return false; } auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(*this))), std::string_view(std::get<1>(std::get<1>(*this)))); return view == rhs; } }; private: struct VertexIterator { using kind = boost::vertex_property_tag; }; using VertexProperty = boost::property<VertexIterator, const Vertex*>; struct EdgeSeq { using kind = boost::edge_property_tag; }; using EdgeProperty = boost::property<EdgeSeq, int64_t>; using Graph = boost::adjacency_list<boost::multisetS, boost::multisetS, boost::bidirectionalS, VertexProperty, EdgeProperty>; using VertexPropertyTag = boost::property_map<Graph, VertexIterator>::const_type; using EdgePropertyTag = boost::property_map<Graph, EdgeSeq>::const_type; using VertexID = Graph::vertex_descriptor; using EdgeID = Graph::edge_descriptor; Graph m_graph; std::map<Vertex, VertexID, std::less<>> m_vertexes; VertexID touchContext(ContextID contextID); VertexID touchKeyLock(KeyLockView keylockView); void addEdge(VertexID source, VertexID target, Seq seq); void removeEdge(VertexID source, VertexID target, Seq seq); }; } // namespace bcos::scheduler namespace std { inline bool operator<(const bcos::scheduler::GraphKeyLocks::Vertex& lhs, const bcos::scheduler::GraphKeyLocks::KeyLockView& rhs) { if (lhs.index() != 1) { return true; } auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(lhs))), std::string_view(std::get<1>(std::get<1>(lhs)))); return view < rhs; } inline bool operator<(const bcos::scheduler::GraphKeyLocks::KeyLockView& lhs, const bcos::scheduler::GraphKeyLocks::Vertex& rhs) { if (rhs.index() != 1) { return false; } auto view = std::make_tuple(std::string_view(std::get<0>(std::get<1>(rhs))), std::string_view(std::get<1>(std::get<1>(rhs)))); return lhs < view; } } // namespace std
{ "alphanum_fraction": 0.6733386709, "avg_line_length": 30.2177419355, "ext": "h", "hexsha": "bd436ed17a54cb7d20444311a2ad1fc32a205dc0", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-08-04T02:51:38.000Z", "max_forks_repo_forks_event_min_datetime": "2021-06-10T02:44:20.000Z", "max_forks_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "xueying4402/FISCO-BCOS", "max_forks_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_issues_count": 14, "max_issues_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_issues_repo_issues_event_max_datetime": "2021-09-06T14:42:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-06-21T10:15:26.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "xueying4402/FISCO-BCOS", "max_issues_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "737e08752e8904c7c24e3737f8f46bf5327ef792", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "xueying4402/FISCO-BCOS", "max_stars_repo_path": "bcos-scheduler/src/GraphKeyLocks.h", "max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z", "num_tokens": 959, "size": 3747 }