Search is not available for this dataset
text
string
meta
dict
//====---- Sudoku/Board_Section.h ----====// // // Internal in-between object for provide access to a section of Board. //====--------------------------------------------------------------------====// #pragma once #include "Board_Section_iterator.h" #include "Board_Section_traits.h" // Convenience include #include "Location.h" #include "Location_Utilities.h" #include "exceptions.h" #include "traits.h" #include <gsl/gsl> // index #include <type_traits> #include "Board.fwd.h" // Forward declarations #include <cassert> namespace Sudoku::Board_Section { template<typename T, int N, Section S, bool is_const> class [[nodiscard]] Board_Section_ { using index = gsl::index; using Location = ::Sudoku::Location<N>; using Location_Block = ::Sudoku::Location_Block<N>; using OwnerT = std::conditional_t<is_const, Board<T, N> const&, Board<T, N>&>; // explicit friends for conversion friend class Board_Section_<T, N, Section::row, true>; friend class Board_Section_<T, N, Section::row, false>; friend class Board_Section_<T, N, Section::col, true>; friend class Board_Section_<T, N, Section::col, false>; friend class Board_Section_<T, N, Section::block, true>; friend class Board_Section_<T, N, Section::block, false>; public: using value_type = T; using pointer = std::conditional_t<is_const, T const*, T*>; using reference = std::conditional_t<is_const, T const&, T&>; using iterator = Section_iterator<T, N, S, is_const, false>; using const_iterator = Section_iterator<T, N, S, true, false>; using reverse_iterator = Section_iterator<T, N, S, is_const, true>; using const_reverse_iterator = Section_iterator<T, N, S, true, true>; template<typename idT, typename = std::enable_if_t<is_int_v<idT>>> constexpr Board_Section_(OwnerT board, idT id) noexcept : board_(board), id_(id) { assert(is_valid_size<N>(id)); } constexpr Board_Section_(OwnerT board, Location loc) noexcept : board_(board), id_(to_id(loc)) { assert(is_valid<N>(loc)); } // Conversion to other Section type (maintaining or gaining const) template< Section Sx, bool B, typename = std::enable_if_t<!B || B == is_const>> constexpr Board_Section_( Board_Section_<T, N, Sx, B> other, index pivot_elem) noexcept : board_(other.board_), id_(to_id(other.location(pivot_elem))) { } // [[implicit]] conversion to const // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) constexpr operator Board_Section_<T, N, S, true>() const noexcept { return Board_Section_<T, N, S, true>(board_, id_); } [[nodiscard]] static constexpr int size() noexcept { return elem_size<N>; } [[nodiscard]] constexpr index id() const noexcept { return id_; } [[nodiscard]] constexpr Location location(index elem) const noexcept; [[nodiscard]] constexpr reference front() noexcept { return (*this)[0]; } [[nodiscard]] constexpr reference back() noexcept { return (*this)[static_cast<index>(size()) - 1]; } [[nodiscard]] constexpr reference operator[](const index elem) noexcept { return board_[location(elem)]; } [[nodiscard]] constexpr T const& operator[](const index elem) const noexcept { return board_[location(elem)]; } // Checked access [[nodiscard]] constexpr reference at(const index elem); constexpr iterator begin() noexcept { return iterator(&board_, id_, 0); } constexpr iterator end() noexcept { return iterator(&board_, id_, size()); } [[nodiscard]] constexpr const_iterator cbegin() const noexcept { return const_iterator(&board_, id_, 0); } [[nodiscard]] constexpr const_iterator cend() const noexcept { return const_iterator(&board_, id_, size()); } [[nodiscard]] constexpr const_iterator begin() const noexcept { return cbegin(); } [[nodiscard]] constexpr const_iterator end() const noexcept { return cend(); } constexpr reverse_iterator rbegin() noexcept { return reverse_iterator(&board_, id_, size() - 1); } constexpr reverse_iterator rend() noexcept { return reverse_iterator(&board_, id_, -1); } [[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(&board_, id_, size() - 1); } [[nodiscard]] constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(&board_, id_, -1); } [[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept { return crbegin(); } [[nodiscard]] constexpr const_reverse_iterator rend() const noexcept { return crend(); } private: OwnerT board_; const gsl::index id_{}; // Internal helper static constexpr gsl::index to_id(Location loc) noexcept; }; //====--------------------------------------------------------------------====// // Member Functions // Checked access template<typename T, int N, Section S, bool is_const> [[nodiscard]] inline constexpr typename Board_Section_<T, N, S, is_const>::reference Board_Section_<T, N, S, is_const>::at(const index elem) { if (!is_valid_size<N>(elem)) { throw error::invalid_Location{"Board_Section::at(elem)"}; } return board_.at(location(elem)); } template<typename T, int N, Section S, bool is_const> [[nodiscard]] constexpr Location<N> Board_Section_<T, N, S, is_const>::location(index elem) const noexcept { assert(is_valid_size<N>(elem)); switch (S) { case Section::row: return Location(id_, elem); case Section::col: return Location(elem, id_); case Section::block: return Location_Block(id_, elem); } } // Internal helper template<typename T, int N, Section S, bool is_const> inline constexpr gsl::index Board_Section_<T, N, S, is_const>::to_id(Location loc) noexcept { switch (S) { case Section::row: return loc.row(); case Section::col: return loc.col(); case Section::block: return loc.block(); } } } // namespace Sudoku::Board_Section
{ "alphanum_fraction": 0.6850527749, "avg_line_length": 30.4352331606, "ext": "h", "hexsha": "18983960b85df3b63d0358500e8752a0e7a5638c", "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": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "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": "FeodorFitsner/fwkSudoku", "max_issues_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_path": "Sudoku/Sudoku/Board_Section.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1453, "size": 5874 }
/* Copyright (c) Facebook, Inc. and its affiliates. * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cblas.h> #include <complex.h> #defmacro DEFINE_SVV(TNAME, TYPE, OPNAME, OPTEXT) #define OPER(a,b) OPTEXT TYPE TNAME##Vector_##OPNAME(TYPE *a, TYPE *b, int n) { /* try cblas */ #if #TYPE == "float" && #OPNAME == "dot" return cblas_sdot(n, a, 1, b, 1); #elif #TYPE == "double" && #OPNAME == "dot" return cblas_ddot(n, a, 1, b, 1); #else int i; TYPE s = 0; # pragma unroll(i) for(i=0;i<n;i++) s += OPER(a[i],b[i]); return s; #endif } #endmacro #defmacro FORALLTYPES(macro,...) macro(Int, int, __VA_ARGS__) macro(Long, long, __VA_ARGS__) macro(Float, float, __VA_ARGS__) macro(Double, double, __VA_ARGS__) macro(Complex, complex double, __VA_ARGS__) #endmacro FORALLTYPES(DEFINE_SVV,dot,(a)*(b)); FORALLTYPES(DEFINE_SVV,sqrdist,((a)-(b))*((a)-(b))) #define DEFINE_TYPEINFO(TNAME,TYPE) { #TNAME, #TYPE }, struct { const char *tname, *type; } typeInfo[] = { FORALLTYPES(DEFINE_TYPEINFO) };
{ "alphanum_fraction": 0.6391304348, "avg_line_length": 23.4693877551, "ext": "c", "hexsha": "d6f723938957425dbab86175554dee410375c55b", "lang": "C", "max_forks_count": 13, "max_forks_repo_forks_event_max_datetime": "2021-11-05T17:48:08.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-28T07:43:06.000Z", "max_forks_repo_head_hexsha": "4cc6c6bbd722f89fdcb667f7705a2262dceb6979", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zydeco/CParser", "max_forks_repo_path": "tests/testmacro.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "4cc6c6bbd722f89fdcb667f7705a2262dceb6979", "max_issues_repo_issues_event_max_datetime": "2021-03-25T06:57:33.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-05T04:25:00.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zydeco/CParser", "max_issues_repo_path": "tests/testmacro.c", "max_line_length": 66, "max_stars_count": 113, "max_stars_repo_head_hexsha": "4cc6c6bbd722f89fdcb667f7705a2262dceb6979", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zydeco/CParser", "max_stars_repo_path": "tests/testmacro.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:52:14.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-02T14:52:33.000Z", "num_tokens": 377, "size": 1150 }
/* * 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 applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h #define applicationwin32_3971e4cb_1be6_4066_b7ea_da679d40c987_h #include <gslib/string.h> #include <gslib/std.h> #include <ariel/application.h> #include <windows.h> #undef min #undef max __ariel_begin__ typedef LRESULT(__stdcall *fnwndproc)(HWND, UINT, WPARAM, LPARAM); typedef list<string> arg_list; extern void set_execute_path_as_directory(); extern void init_application_environment(app_env& env); extern void init_application_environment(app_env& env, HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc); struct app_data { HINSTANCE hinst = nullptr; HWND hwnd = nullptr; fnwndproc wndproc = nullptr; arg_list arglist; public: bool install(const app_config& cfg, const app_env& env); int run(); }; struct app_env { HINSTANCE hinst = nullptr; HINSTANCE hprevinst = nullptr; arg_list arglist; public: void init(HINSTANCE hinst, HINSTANCE hprevinst, const gchar* argv[], int argc) { init_application_environment(*this, hinst, hprevinst, argv, argc); } }; __ariel_end__ #endif
{ "alphanum_fraction": 0.7158908507, "avg_line_length": 34.1369863014, "ext": "h", "hexsha": "39cf3e5e09d220bfcebba24042f8da32ff22fdca", "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/applicationwin32.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/applicationwin32.h", "max_line_length": 154, "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/applicationwin32.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": 576, "size": 2492 }
/* multimin/convergence.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 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 <gsl/gsl_multimin.h> #include <gsl/gsl_blas.h> int gsl_multimin_test_gradient (const gsl_vector *g, double epsabs) { double norm; if (epsabs < 0.0) { GSL_ERROR ("absolute tolerance is negative", GSL_EBADTOL); } norm = gsl_blas_dnrm2(g); if (norm < epsabs) { return GSL_SUCCESS; } return GSL_CONTINUE; } int gsl_multimin_test_size (const double size, double epsabs) { if (epsabs < 0.0) { GSL_ERROR ("absolute tolerance is negative", GSL_EBADTOL); } if (size < epsabs) { return GSL_SUCCESS; } return GSL_CONTINUE; }
{ "alphanum_fraction": 0.6964038728, "avg_line_length": 24.5084745763, "ext": "c", "hexsha": "c468d3a71d4ed5f18455a673403c33478a420964", "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/multimin/convergence.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/multimin/convergence.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/multimin/convergence.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": 390, "size": 1446 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_randist.h> int main (void) { double x; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); for (x = 0.1 ; x < 2; x+= 0.1) { double y0 = exp(x); double err = 0.1*y0; printf("%g %g %g\n", x, y0 + gsl_ran_gaussian(r, err), err); } }
{ "alphanum_fraction": 0.5466321244, "avg_line_length": 15.44, "ext": "c", "hexsha": "e8f78a130d9717ee8d7d6dca176e4d939461454b", "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/multifit/demo3.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/multifit/demo3.c", "max_line_length": 66, "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/multifit/demo3.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": 140, "size": 386 }
#include <math.h> #include <stdlib.h> #include <gsl/gsl_siman.h> /* set up parameters for this simulated annealing run */ /* how many points do we try before stepping */ #define N_TRIES 200 /* how many iterations for each T? */ #define ITERS_FIXED_T 10 /* max step size in random walk */ #define STEP_SIZE 10 /* Boltzmann constant */ #define K 1.0 /* initial temperature */ #define T_INITIAL 0.002 /* damping factor for temperature */ #define MU_T 1.005 #define T_MIN 2.0e-6 gsl_siman_params_t params = {N_TRIES, ITERS_FIXED_T, STEP_SIZE, K, T_INITIAL, MU_T, T_MIN}; /* now some functions to test in one dimension */ double E1(void *xp) { double x = * ((double *) xp); return exp(-pow((x-1.0),2.0))*sin(8*x); } double M1(void *xp, void *yp) { double x = *((double *) xp); double y = *((double *) yp); return fabs(x - y); } void S1(const gsl_rng * r, void *xp, double step_size) { double old_x = *((double *) xp); double new_x; double u = gsl_rng_uniform(r); new_x = u*2*step_size - step_size + old_x; memcpy(xp, &new_x, sizeof(new_x)); } void P1(void *xp) { printf("%12g", *((double *) xp)); } int main(int argc, char *argv[]) { gsl_rng_type * T; gsl_rng * r; double x_initial = 15.5; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_siman_solve(r, &x_initial, E1, S1, M1, P1, NULL, NULL, NULL, sizeof(double), params); return 0; }
{ "alphanum_fraction": 0.6013071895, "avg_line_length": 19.125, "ext": "c", "hexsha": "72131dc64de682b2f473f469574803e799e8cf07", "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/siman/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/siman/demo.c", "max_line_length": 56, "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/siman/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 446, "size": 1530 }
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <complex.h> #include <float.h> #include <fftw3.h> #include "gauss_conv.h" #include "seis_data.h" #include "calculate_source.h" void calculate_source(seis_data *obs, seis_data *syn, double *syn_src, double *obs_src, int src_no) { double lambda1, lambda2; /* <---Regularization parameters for Tikhonov regularization */ int npts = obs->num_samples; int num_rec = obs->num_rec; int N = npts; /* fft size */ int Nfreq = N/2 +1; /* size of freq vector */ int i, j; /* counters for loops */ /*************************************************************************/ /* allocate space for vector of sizes */ int *nn = malloc(sizeof(*nn) * num_rec); /* allocate space for syn/obs and Fourier transforms */ double *sd = fftw_malloc(sizeof(*sd) * N * num_rec); fftw_complex *SD = fftw_malloc(sizeof(*SD) * Nfreq * num_rec); /* allocate space for syn/obs source and Fourier transforms */ double *k = fftw_malloc(sizeof(*k) * N); fftw_complex *K = fftw_malloc(sizeof(*K) * Nfreq); /* Allocate space for Fourier transform of Green's function (impulse response) */ fftw_complex *G = fftw_malloc(sizeof(*G) * Nfreq * num_rec); /* allocate some temporary working space */ fftw_complex *temp = fftw_malloc(sizeof(*temp) * 3 * N); fftw_complex *num = temp + N; fftw_complex *den = temp + 2 * N; /* check memory allocations */ if (!nn || !sd || !SD || !k || !K || !G || !temp) { fprintf(stderr,"Error: calculate_source: memory allocation failure\n"); exit(1); } /*************************************************************************/ /* fill array of sizes - all sizes are the same */ for (i=0;i<num_rec;i++) nn[i] = N; /* make FFTW plans */ fftw_plan plan_forward_sd, plan_forward_k, plan_backward_K; /* synth/obs data - forward only */ plan_forward_sd = fftw_plan_many_dft_r2c(1,nn,num_rec,sd,NULL,1,N,SD,NULL,1,Nfreq,FFTW_MEASURE); /* synth/obs source - forward and backward */ plan_forward_k = fftw_plan_dft_r2c_1d(N,k,K,FFTW_MEASURE); plan_backward_K = fftw_plan_dft_c2r_1d(N,K,k,FFTW_MEASURE); /*************************************************************************/ /* copy synth source and data over */ for (j=0;j<npts;j++) { k[j] = syn_src[j]; } for (j=npts;j<N;j++) { /* zero padding */ k[j] = 0.0; } for (i=0;i<num_rec;i++) { for (j=0;j<npts;j++) { sd[i*N + j] = syn->traces[src_no*npts*num_rec + i*npts + j]; } for (j=npts;j<N;j++) { /* zero padding */ sd[i*N + j] = 0.0; } } /* Execute FFTW plans */ fftw_execute(plan_forward_sd); fftw_execute(plan_forward_k); /*************************************************************************/ /* calculate denominator of first fraction */ /* zero out num and den of second fraction */ for (j=0;j<N;j++) { /* pre computing this reduces the number of divisions by a factor of num_rec */ temp[j] = 1.0 / (conj(K[j]) * K[j] + lambda1); num[j] = 0.0; den[j] = 0.0; } /* solve for Green's function (freq domain) */ for (i=0;i<num_rec;i++) { /* alternatively, call spectral_division_wl or spectral_division_tik */ /* in these cases temp does not need to be the inverse as above */ for (j=0;j<N;j++) { G[i*N + j] = conj(K[j]) * SD[i*N + j] * temp[j]; } } /*************************************************************************/ /* copy over observed data and take Fourier transform */ for (i=0;i<num_rec;i++) { for (j=0;j<npts;j++) { sd[i*N + j] = obs->traces[src_no*npts*num_rec + i*npts + j]; } for (j=npts;j<N;j++) { /* zero padding */ sd[i*N + j] = 0.0; } } fftw_execute(plan_forward_sd); /*************************************************************************/ /* solve for obs source in least squares sense */ for (i=0;i<num_rec;i++) { for (j=0;j<N;j++) { num[j] += conj(G[i*N + j]) * SD[j]; den[j] += conj(G[i*N + j]) * G[i*N + j]; } } /* alternatively, call spectral_division_wl or spectral_division_tik */ for (j=0;j<N;j++) { K[j] = num[j] / (den[j] +lambda2); } /* Execute FFTW plan for backwards transform of k */ fftw_execute(plan_backward_K); /* scale k */ double sf = 1.0 / (double)N; for (j=0;i<N;j++) { k[j] = sf * k[j]; } /* get minimum phase reconstruction. write result in output vector */ min_phase_reconstruction(k, obs_src, N); } void min_phase_reconstruction(const double *signal_in, double *signal_out, const int npts) { /* construct a minimum phase wavelet from the data in signal_in */ /* npts is the actual length of the data without any padding */ /* signal_out should be allocated already and able to hold at least npts values */ /* this restricts us to even N */ int N = next_power2(npts*8); /* allocate temporary arrays */ fftw_complex *x1 = malloc(sizeof(*x1) * N); fftw_complex *x2 = malloc(sizeof(*x2) * N); if (!x1 || !x2) { fprintf(stderr, "Error: min_phase_reconstruction: Memory allocation failure\n"); exit(1); } /* make fftw plans */ fftw_plan ft_plan_for, ft_plan_bac; ft_plan_for = fftw_plan_dft_1d(N, x1, x2, FFTW_FORWARD, FFTW_MEASURE); ft_plan_bac = fftw_plan_dft_1d(N, x2, x1, FFTW_BACKWARD, FFTW_MEASURE); int i; /* copy data over */ for (i=0;i<npts;i++) { x1[i] = signal_in[i]; } /* put zero padding at the end */ for (i=npts;i<N;i++) { x1[i] = 0.0; } /* forward fft */ fftw_execute(ft_plan_for); /* take log of abs */ /* <---TODO: need to handle values with 0 magnitude */ for (i=0;i<N;i++) { x2[i] = log(cabs(x2[i])); } /* inverse fft */ fftw_execute(ft_plan_bac); /* for inverse fft, need to divide values by fft length */ double scale_fact = 1.0 / (double)N; int half_ind = N/2; /* window signal */ /* first element (zero frequency) is unchanged - take real part and scale */ x1[0] = scale_fact * creal(x1[0]); /* take real part, scale, and window - positive freqs by 2, negative freqs by 0 */ for (i=1;i<N/2;i++) { x1[i] = 2.0 * scale_fact * creal(x1[i]); x1[i + half_ind] = 0.0; } /* element at N/2 (nyquist frequency) is unchanged - take real part and scale */ x1[half_ind] = scale_fact * creal(x1[half_ind]); /* execute forward fft of windowed signal */ fftw_execute(ft_plan_for); /* run signal through (complex) exponential */ for (i=0;i<N;i++) { x2[i] = cexp(x2[i]); } /* take inverse fft */ fftw_execute(ft_plan_bac); /* take real part and scale data. place result in output array*/ for (i=0;i<npts;i++) { signal_out[i] = scale_fact * creal(x1[i]); } /* clean up */ fftw_free(x1); fftw_free(x2); fftw_destroy_plan(ft_plan_for); fftw_destroy_plan(ft_plan_bac); } void spectral_division_wl(fftw_complex *num, fftw_complex *den, int N, double wtr, fftw_complex *out) { int i; double tol = 2 * DBL_EPSILON; /* temporary to hold magnitude of den */ double *d_mag = malloc(sizeof(*d_mag) * N); if (!d_mag) { fprintf(stderr, "Error: spectral_division_wl: Memory allocation failure\n"); exit(1); } double d_amp_max = cabs(den[0]); /* get magnitude of den and pick max */ for (i=0;i<N;i++) { d_mag[i] = cabs(den[i]); d_amp_max = d_mag[i] > d_amp_max ? d_mag[i] : d_amp_max; } double wtr_use = wtr * d_amp_max; fftw_complex den_use; for (i=0;i<N;i++) { if (d_mag[i] < tol) { /* den magnitude equal to zero */ /* set value to wtr_use */ den_use = wtr_use; } else if (d_mag[i] < wtr_use) { /* den magnitude less than water level */ /* keep phase the same, but change magnitude to wtr_use */ den_use = wtr_use * (den[i] / d_mag[i]); } else { /* den magnitude greater than water level */ /* no change */ den_use = den[i]; } out[i] = num[i] / den_use; } free(d_mag); } void spectral_division_tik(fftw_complex *num, fftw_complex *den, int N, double lambda, fftw_complex *out) { int i; for (i=0;i<N;i++) { out[i] = (conj(den[i]) * num[i]) / (conj(den[i]) * den[i] + lambda); } } void fft_convolution(double *x, double *h, double *y, int npts) { /* convolution of two equal length signals, x and h. */ /* x and h are both npts long */ /* the result (y) is length 2*npts-1 */ /* y should already be allocated */ /* fft size needs to be at least 2*npts -1 */ int N = next_power2(2 * npts); int fft_freq_sz = N/2 + 1; double *x_in = fftw_malloc(sizeof(*x_in) * N * 2); fftw_complex *X = fftw_malloc(sizeof(*X) * fft_freq_sz * 2); if (!x_in || !X) { fprintf(stderr,"Error: fft_convolution: memory allocation failure\n"); exit(1); } double *h_in = x_in + N; fftw_complex *H = X + fft_freq_sz; int how_many = 2; int n[2] = {N,N}; int stride = 1; int rank = 1; fftw_plan fplan, bplan; fplan = fftw_plan_many_dft_r2c(rank,n,how_many,x_in,NULL,stride,N,X,NULL,stride,fft_freq_sz,FFTW_MEASURE); bplan = fftw_plan_dft_c2r_1d(N,X,x_in,FFTW_MEASURE); int i; /* copy data */ for (i=0;i<npts;i++) { x_in[i] = x[i]; h_in[i] = h[i]; } /* add zero padding */ for (i=npts;i<N;i++) { x_in[i] = 0.0; h_in[i] = 0.0; } /* execute forward plan */ fftw_execute(fplan); /* perform multiplication - keep result in X */ for (i=0;i<fft_freq_sz;i++) { X[i] *= H[i]; } /* execute backward plan */ fftw_execute(bplan); /* scale and copy data to output array */ double sf = 1.0 / (double)N; for (i=0;i<2*npts-1;i++) { y[i] = sf * x_in[i]; } /* clean up */ fftw_destroy_plan(fplan); fftw_destroy_plan(bplan); fftw_free(x_in); fftw_free(X); } #include <lapacke.h> void deconvolution_system(const double *x, double *h, const double *y, const int npts, const double lambda) { /* NOTE: This is really only practical when npts is fairly small */ /* */ /* the convolution problem can be formulated as a matrix multiplication */ /* X*h = y, where the columns of X contain shifted copies of x */ /* Therefore, the deconvolution problem is solving this overdetermined */ /* system for h. To do this, we solve (X'*X + lambda*I)*h = X'*y */ /* where ' denotes matrix transpose, I is the identity matrix, and */ /* lambda is a Tikhonov regularization parameter */ /* x and h should be length npts and y is length (2*npts-1) */ int N = next_power2(2*npts); int freq_sz = N/2 + 1; int conv_sz = 2*npts -1; double *X = malloc(sizeof(*X) * npts * conv_sz); double *xx = malloc(sizeof(*xx) * 3 * npts); double *yy = malloc(sizeof(*yy) * conv_sz); double *s = malloc(sizeof(*s) * npts); /* s holds the singular values */ /* copy data and zero pad */ int i, j; for (i=0;i<npts;i++) { xx[i] = 0.0; xx[i+npts] = x[i]; xx[i+2*npts] = 0.0; yy[i] = y[i]; } for (i=npts;i<conv_sz;i++) { yy[i] = y[i]; } for (i=0;i<npts;i++) { for (j=0;j<conv_sz;j++) { X[i*conv_sz + j] = xx[(npts - i) + j]; } } char trans = 'N'; int m = conv_sz; /* number of rows in X */ int n = npts; /* number of cols in X */ int nrhs = 1; /* number of right hand side (1) */ int lda = m; /* leading dim of A, m for col major layout */ int ldb = m; /* leading dim of B */ double rcond = lambda; int rank; int info; info = LAPACKE_dgelss(LAPACK_COL_MAJOR, m, n, nrhs, X, lda, yy, ldb, s, rcond, &rank); if (info != 0) { fprintf(stderr, "Error: deconvolution_system: Lapack failure\n"); exit(1); } /* copy solution over to h */ for (i=0;i<npts;i++) { h[i] = yy[i]; } }
{ "alphanum_fraction": 0.524657112, "avg_line_length": 25.75, "ext": "c", "hexsha": "ef40326bd6838cf148b14a2c02db6adcf6646a7f", "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": "5fbb42590dec4187314eb1bd21ea8d24c207209b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dt-jackson/FWI", "max_forks_repo_path": "src/calculate_source.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5fbb42590dec4187314eb1bd21ea8d24c207209b", "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": "dt-jackson/FWI", "max_issues_repo_path": "src/calculate_source.c", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "5fbb42590dec4187314eb1bd21ea8d24c207209b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dt-jackson/FWI", "max_stars_repo_path": "src/calculate_source.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3663, "size": 12978 }
// // Extrap1d.h #ifndef __NeutronDetectorSim__Extrap1d__ #define __NeutronDetectorSim__Extrap1d__ #include <iostream> #include <vector> #include <eigen3/Eigen/Dense> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include "ConsolePrint.hpp" class Extrap1d { public: Extrap1d(Eigen::ArrayXd x, Eigen::ArrayXd y); Extrap1d(std::vector<double> x, std::vector<double> y); ~Extrap1d(); double operator()(const double &x); Eigen::ArrayXd operator()(const Eigen::ArrayXd &x); private: double min, max; Eigen::ArrayXd x; Eigen::ArrayXd y; gsl_spline *interpolator; gsl_interp_accel *accelerator; }; #endif /* defined(__NeutronDetectorSim__Extrap1d__) */
{ "alphanum_fraction": 0.7496274218, "avg_line_length": 22.3666666667, "ext": "h", "hexsha": "44e56ce46ec4db71c8ae7549dc9cf59fa4cd6861", "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": "f972ca7fb3ec1f64086d3d62d3c6d8db1b4e4846", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SkyToGround/DetectorSensitivity", "max_forks_repo_path": "Extrap1d.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f972ca7fb3ec1f64086d3d62d3c6d8db1b4e4846", "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": "SkyToGround/DetectorSensitivity", "max_issues_repo_path": "Extrap1d.h", "max_line_length": 56, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f972ca7fb3ec1f64086d3d62d3c6d8db1b4e4846", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SkyToGround/DetectorSensitivity", "max_stars_repo_path": "Extrap1d.h", "max_stars_repo_stars_event_max_datetime": "2021-02-13T16:43:32.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-13T16:43:32.000Z", "num_tokens": 204, "size": 671 }
#ifndef GLOBALS #define GLOBALS #include <gsl/gsl_matrix.h> extern int NumEl; extern int NumEdges; extern int NumNodes; extern int P; extern int Np; extern gsl_matrix *LIFT; extern gsl_matrix *VolMat; extern gsl_matrix *MassMatrix; extern double *x; extern double *y; extern double *z; extern double *b; extern double *m1; extern double *m2; extern double *db; extern double *dm1; extern double *dm2; extern double *dz; extern double *dh; extern double *nFriction; extern double *NodalX; extern double *NodalY; extern double *NodalB; extern double *Nodalz; extern double *Nodalm1; extern double *Nodalm2; extern double *NodalnFriction; extern double *A; extern double *Q; //extern double *Fhat1L; //extern double *Fhat1R; //extern double *Fhat2L; //extern double *Fhat2R; extern double *RHSA; extern double *RHSQ; extern double dt; extern double max_lambda; extern double mindh; extern const double g; extern const double H0; extern const double VELZERO; extern int *WD; // keeps track of the wet/dry status of an element #endif
{ "alphanum_fraction": 0.7583892617, "avg_line_length": 17.6779661017, "ext": "h", "hexsha": "33c4f009add39941efd57f8533e1231644592124", "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/globals.h", "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/globals.h", "max_line_length": 67, "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/globals.h", "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": 294, "size": 1043 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2019 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp> * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #include <stdio.h> #include <cblas.h> #include <rokko/cmatrix.h> int main() { int n = 4; double** a = alloc_dmatrix(n, n); mat_elem(a, 0, 0) = 0.959291425205444; mat_elem(a, 0, 1) = 0.257508254123736; mat_elem(a, 0, 2) = 0.243524968724989; mat_elem(a, 0, 3) = 0.251083857976031; mat_elem(a, 1, 0) = 0.547215529963803; mat_elem(a, 1, 1) = 0.840717255983663; mat_elem(a, 1, 2) = 0.929263623187228; mat_elem(a, 1, 3) = 0.616044676146639; mat_elem(a, 2, 0) = 0.138624442828679; mat_elem(a, 2, 1) = 0.254282178971531; mat_elem(a, 2, 2) = 0.349983765984809; mat_elem(a, 2, 3) = 0.473288848902729; mat_elem(a, 3, 0) = 0.149294005559057; mat_elem(a, 3, 1) = 0.814284826068816; mat_elem(a, 3, 2) = 0.196595250431208; mat_elem(a, 3, 3) = 0.351659507062997; double* x = alloc_dvector(n); x[0] = 0.830828627896291; x[1] = 0.585264091152724; x[2] = 0.549723608291140; x[3] = 0.917193663829810; double* y = alloc_dvector(n); y[0] = 0.961898080855054; y[1] = 0.00463422413406744; y[2] = 0.774910464711502; y[3] = 0.817303220653433; double alpha = 2.3; double beta = 0.5; printf("a: "); fprint_dmatrix(stdout, n, n, a); printf("x: "); fprint_dvector(stdout, n, x); printf("y: "); fprint_dvector(stdout, n, y); cblas_dgemv(CblasColMajor, CblasNoTrans, n, n, alpha, mat_ptr(a), n, vec_ptr(x), 1, beta, vec_ptr(y), 1); printf("%10.5f * a * x + %10.5f * y: ", alpha, beta); fprint_dvector(stdout, n, y); free_dmatrix(a); free_dvector(x); free_dvector(y); } /* gemv.m A = [0.959291425205444,0.257508254123736,0.243524968724989,0.251083857976031;0.547215529963803,0.840717255983663,0.929263623187228,0.616044676146639;0.138624442828679,0.254282178971531,0.349983765984809,0.473288848902729;0.149294005559057,0.814284826068816,0.196595250431208,0.351659507062997] x = [0.830828627896291;0.585264091152724;0.549723608291140;0.917193663829810] y = [0.961898080855054;0.00463422413406744;0.774910464711502;0.817303220653433] 2.3 * A * x + 0.5 * y */
{ "alphanum_fraction": 0.6460176991, "avg_line_length": 35.5142857143, "ext": "c", "hexsha": "116b5a9020b27fad80deed29fec629d791568a82", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "example/blas/dgemv.c", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "example/blas/dgemv.c", "max_line_length": 293, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "example/blas/dgemv.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 1001, "size": 2486 }
/* stable/stable.h * * Main header file of Libstable. Contains all declarations of the * usable functions in the library. * * Copyright (C) 2013. Javier Royuela del Val * Federico Simmross Wattenberg * * 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; version 3 of the License. * * 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, see <http://www.gnu.org/licenses/>. * * * Javier Royuela del Val. * E.T.S.I. Telecomunicación * Universidad de Valladolid * Paseo de Belén 15, 47002 Valladolid, Spain. * jroyval@lpi.tel.uva.es */ #ifndef _stable_H_ #define _stable_H_ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_vector.h> #define TINY 1e-50 #define EPS 2.2204460492503131E-16 #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) /******************************************************************************/ /* Library parameters */ /******************************************************************************/ extern FILE * FLOG; // Log file (optional) extern FILE * FINTEG; // Integrand evaluations output file (debug purposes) extern unsigned short THREADS; // threads of execution (0 => total available) extern unsigned short IT_MAX; // Maximum # of iterations in quadrature methods extern unsigned short SUBS; // # of integration subintervals extern unsigned short METHOD1; // Integration method on main subinterval extern unsigned short METHOD2; // Integration method on second subinterval extern unsigned short METHOD3; // Integration method on third subinterval extern unsigned short INV_MAXITER; // Maximum # of iterations inversion method extern double relTOL; // Relative error tolerance extern double absTOL; // Absolut error tolerance //extern double FACTOR; // extern double ALPHA_TH; // Alpha threshold extern double BETA_TH; // Beta threshold extern double EXP_MAX; // Exponent maximum value extern double XXI_TH; // Zeta threshold extern double THETA_TH; // Theta threshold extern double AUX1; // Auxiliary values extern double AUX2; #ifdef DEBUG extern unsigned int integ_eval; // # of integrand evaluations #endif /******************************************************************************/ /******************************************************************************/ // Particular cases enum { NOVALID =-1, STABLE, ALPHA_1, GAUSS , CAUCHY, LEVY, STABLE_B1, ALPHA_1_B1 }; // Function to evaluate enum { CDF, PDF }; // Quadrature methods enum { STABLE_QAG2 = 0, STABLE_QUADSTEP, STABLE_QROMBPOL, STABLE_QROMBRAT, STABLE_QNG, STABLE_QAG1, STABLE_QAG5, STABLE_VECT }; /************************************************************************ ************************************************************************ * Scalar methods * ************************************************************************ ************************************************************************/ /* Scalar methods are those that, for each thread of execution, obtain a single evaluation of the desired function, at a single point. */ /******************************************************************************/ /* Stable distribution structure. */ /******************************************************************************/ struct StableDistStruct { /* Parameters: 0-parametrization describen in Nolan, 1997 is employed by default alpha : stability index beta : skewness parameter scale: scale parameter mu_0 : 0-parametrization location parameter mu_1 : correspondig 1-parametrization location parameter */ double alpha; double beta; double sigma; double mu_0; double mu_1; /* Particular cases indicator (Gauss, Cauchy, Levy distribution, alpha==1, etc.) */ int ZONE; /* Pointers to pdf and cdf evaluation functions */ double(*stable_pdf_point)(struct StableDistStruct *, const double, double *); double(*stable_cdf_point)(struct StableDistStruct *, const double, double *); /* Precalculated values. */ double alphainvalpha1; /* alpha/(alpha-1)*/ double xi; /* -beta*tan(alpha*pi/2)*/ double theta0; /* 1/alpha*atan(beta*(tan(alpha*pi/2))=atan(-xi)/alpha;*/ double c1, c2_part, c3; /* additive and multiplicative constants*/ double k1; /* cos(alpha*theta0)^(1/(alpha-1)) = (1+xi^2)^(-0.5/(alpha-1));*/ double S; /* (1+xi^2)^(1/(2*alpha));*/ double Vbeta1; /*pow(1/dist->alpha,dist->alphainvalpha1) * (dist->alpha-1)*pow(-cos(dist->alpha*PI_2),1/(dist->alpha-1))*/ /* These ones change from point to point of evaluation */ double theta0_; /* theta0_ = +-theta0 */ double beta_; double xxipow; /* (x-xi)^(alpha/(alpha-1))*/ /* gsl integration workspace */ gsl_integration_workspace * gslworkspace; /* gsl random numbers generator */ gsl_rng * gslrand; }; typedef struct StableDistStruct StableDist; /******************************************************************************/ /* Auxiliary functions */ /******************************************************************************/ unsigned int stable_get_THREADS(); void stable_set_THREADS(unsigned int threads); unsigned int stable_get_IT_MAX(); void stable_set_IT_MAX(unsigned int itmax); unsigned int stable_get_INV_MAXITER(); void stable_set_INV_MAXITER(unsigned int invmaxiter); int stable_get_METHOD1(); void stable_set_METHOD1(int method); int stable_get_METHOD2(); void stable_set_METHOD2(int method); int stable_get_METHOD3(); void stable_set_METHOD3(int method); double stable_get_relTOL(); void stable_set_relTOL(double reltol); double stable_get_absTOL(); void stable_set_absTOL(double abstol); double stable_get_ALPHA_TH(); void stable_set_ALPHA_TH(double alphath); double stable_get_BETA_TH(); void stable_set_BETA_TH(double betath); double stable_get_XXI_TH(); void stable_set_XXI_TH(double xxith); double stable_get_THETA_TH(); void stable_set_THETA_TH(double thetath); FILE * stable_get_FINTEG(); FILE * stable_set_FINTEG(char * filename); FILE * stable_get_FLOG(); FILE * stable_set_FLOG(char * filename); StableDist *stable_create(double alpha, double beta, double sigma, double mu, int parametrization); StableDist *stable_copy(StableDist *src_dist); void stable_free(StableDist *dist); int stable_setparams(StableDist *dist, double alpha, double beta, double sigma, double mu, int parametrization); int stable_checkparams(double alpha, double beta, double sigma, double mu, int parametrization); void error_handler (const char * reason, const char * file, int line, int gsl_errno); /******************************************************************************/ /* PDF in particular cases */ /******************************************************************************/ double stable_pdf_point_GAUSS(StableDist *dist, const double x, double *err); double stable_pdf_point_CAUCHY(StableDist *dist, const double x, double *err); double stable_pdf_point_LEVY(StableDist *dist, const double x, double *err); /******************************************************************************/ /* PDF otherwise */ /******************************************************************************/ double stable_pdf_point_STABLE(StableDist *dist, const double x, double *err); double stable_pdf_point_ALPHA_1(StableDist *dist, const double x, double *err); double stable_pdf_point(StableDist *dist, const double x, double *err); void stable_pdf(StableDist *dist, const double* x, const unsigned int Nx, double *pdf, double *err); /******************************************************************************/ /* PDF integrand functions */ /******************************************************************************/ double stable_pdf_g(double theta, void *dist); double stable_pdf_g_aux1(double theta, void *args); double stable_pdf_g_aux2(double theta, void *args); /******************************************************************************/ /* CDF in particular cases */ /******************************************************************************/ double stable_cdf_point_GAUSS(StableDist *dist, const double x, double *err); double stable_cdf_point_CAUCHY(StableDist *dist, const double x, double *err); double stable_cdf_point_LEVY(StableDist *dist, const double x, double *err); /******************************************************************************/ /* CDF otherwise */ /******************************************************************************/ double stable_cdf_point_STABLE(StableDist *dist, const double x, double *err); double stable_cdf_point_ALPHA_1(StableDist *dist, const double x, double *err); double stable_cdf_point(StableDist *dist, const double x, double *err); void stable_cdf(StableDist *dist, const double* x, const unsigned int Nx, double *cdf, double *err); /******************************************************************************/ /* CDF integrad functions */ /******************************************************************************/ double stable_cdf_g(double theta, void *dist); /******************************************************************************/ /* CDF^{-1} (quantiles) */ /******************************************************************************/ double stable_q_point(StableDist * dist, const double q, double * err); void stable_q(StableDist *dist, const double* q, const unsigned int Nq, double * inv, double * err); /************************************************************************ ************************************************************************ * Vectorial methods * ************************************************************************ ************************************************************************/ /* Alternative non-parallelized methods of evaluation have been implemented. These methods exploit the fact that some calculations are shared between different points of evaluation when evaluating the PDF or CDF, so these calculations can be realized just once. The performance achieved is high, sometimes comparable with parallel methods when little precision is required. However, achievable precision with these methods is low and non desired behavior of the PDF and CDF evaluation is observed. */ /* Stable distribution structure for vectorial methods*/ typedef struct { /* Parameters: 0-parametrization describen in Nolan, 1997 is employed by default alpha : stability index beta : skewness parameter scale: scale parameter mu_0 : 0-parametrization location parameter mu_1 : correspondig 1-parametrization location parameter */ double alpha; double beta; double sigma; double mu_0; double mu_1; /* Particular cases indicator (Gauss, Cauchy, Levy distribution, alpha==1, etc.) */ int ZONE; /* Precalculated values */ double alphainvalpha1; /* alpha/(alpha-1)*/ double xi; /* -beta*tan(alpha*pi/2)*/ double theta0; /* 1/alpha*atan(beta*(tan(alpha*pi/2))=atan(-xi)/alpha;*/ double c1, c2_part, c3; /* additive and multiplicative constants*/ double k1; /* cos(alpha*theta0)^(1/(alpha-1)) = (1+xi^2)^(-0.5/(alpha-1));*/ double S; /* (1+xi^2)^(1/(2*alpha));*/ double Vbeta1; /*pow(1/dist->alpha,dist->alphainvalpha1) * (dist->alpha-1)*pow(-cos(dist->alpha*PI_2),1/(dist->alpha-1))*/ /* These ones change from point to point of evaluation */ double theta0_; /* theta0_ = +-theta0 */ double beta_; double *xxipow; /* (x-xi)^(alpha/(alpha-1))*/ gsl_integration_workspace * gslworkspace; gsl_rng * gslrand; } StableDistV; typedef struct { double (*ptr_funcion)(StableDist *dist, const double x, double *err); StableDist *dist; const double *x; int Nx; double *pdf; double *err; } StableArgsPdf; typedef struct { double (*ptr_funcion)(StableDist *dist, const double x, double *err); StableDist *dist; const double *x; int Nx; double *cdf; double *err; } StableArgsCdf; /************************************************************************ ************************************************************************ * Parameter estimation * ************************************************************************ ************************************************************************/ /******************************************************************************/ /* Parameter estimation structure */ /******************************************************************************/ typedef struct { StableDist *dist; double *data; unsigned int length; double nu_c; double nu_z; } stable_like_params; /* Estimation functions */ void stable_fit_init(StableDist *dist, const double *data, const unsigned int length, double *nu_c,double *nu_z); int stable_fit_koutrouvelis(StableDist *dist, const double *data, const unsigned int length); int stable_fit(StableDist *dist, const double *data, const unsigned int length); int stable_fit_mle(StableDist *dist, const double *data, const unsigned int length); int stable_fit_mle2d(StableDist *dist, const double *data, const unsigned int length); int stable_fit_whole(StableDist *dist, const double *data, const unsigned int length); /* Auxiliary functions */ gsl_complex stable_samplecharfunc_point(const double* x, const unsigned int N, double t); void stable_samplecharfunc(const double* x, const unsigned int Nx, const double* t, const unsigned int Nt, gsl_complex * z); void stable_fft(double *data, const unsigned int length, double * y); double stable_loglikelihood(StableDist *dist, double *data, const unsigned int length); //stable_like_params int stable_fit_iter_whole(StableDist *dist, const double * data, const unsigned int length); int stable_fit_iter(StableDist *dist, const double * data, const unsigned int length, const double nu_c, const double nu_z); double stable_loglike_p(stable_like_params *params); double stable_minusloglikelihood(const gsl_vector * theta, void * p); /************************************************************************ ************************************************************************ * Random numbers generation * ************************************************************************ ************************************************************************/ void stable_rnd(StableDist *dist, double* rnd, unsigned int n); double stable_rnd_point(StableDist *dist); void stable_rnd_seed(StableDist * dist, unsigned long int s); #endif //stable_H
{ "alphanum_fraction": 0.5316678823, "avg_line_length": 36.3982300885, "ext": "h", "hexsha": "2f3e7b60f9db335e4b1d6a35c7c337de5311561a", "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": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "TantraLabs/gonum", "max_forks_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "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": "TantraLabs/gonum", "max_issues_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "TantraLabs/gonum", "max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3287, "size": 16452 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for the implementation of the Fourier domain response for LIGO-VIRGO detectors. * */ #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "LLVgeometry.h" #include "struct.h" #include "LLVFDresponse.h" #include "timeconversion.h" /************************************************************/ /********* Functions setting detector geometry **************/ /* Function setting the response matrix of a given detector, in cartesian coordinates */ void SetMatrixD( gsl_matrix* D, /* Output: matrix of the detector response Dij */ const Detectortag tag) /* Tag identifying the detector */ { /* Allocating and defining the cartesian unit vectors along the two arms */ gsl_vector* nx = gsl_vector_alloc(3); gsl_vector* ny = gsl_vector_alloc(3); if(tag==LHO) { gsl_vector_set(nx, 0, LAL_LHO_4K_ARM_X_DIRECTION_X); gsl_vector_set(nx, 1, LAL_LHO_4K_ARM_X_DIRECTION_Y); gsl_vector_set(nx, 2, LAL_LHO_4K_ARM_X_DIRECTION_Z); gsl_vector_set(ny, 0, LAL_LHO_4K_ARM_Y_DIRECTION_X); gsl_vector_set(ny, 1, LAL_LHO_4K_ARM_Y_DIRECTION_Y); gsl_vector_set(ny, 2, LAL_LHO_4K_ARM_Y_DIRECTION_Z); } else if(tag==LLO) { gsl_vector_set(nx, 0, LAL_LLO_4K_ARM_X_DIRECTION_X); gsl_vector_set(nx, 1, LAL_LLO_4K_ARM_X_DIRECTION_Y); gsl_vector_set(nx, 2, LAL_LLO_4K_ARM_X_DIRECTION_Z); gsl_vector_set(ny, 0, LAL_LLO_4K_ARM_Y_DIRECTION_X); gsl_vector_set(ny, 1, LAL_LLO_4K_ARM_Y_DIRECTION_Y); gsl_vector_set(ny, 2, LAL_LLO_4K_ARM_Y_DIRECTION_Z); } else if(tag==VIRGO) { gsl_vector_set(nx, 0, LAL_VIRGO_ARM_X_DIRECTION_X); gsl_vector_set(nx, 1, LAL_VIRGO_ARM_X_DIRECTION_Y); gsl_vector_set(nx, 2, LAL_VIRGO_ARM_X_DIRECTION_Z); gsl_vector_set(ny, 0, LAL_VIRGO_ARM_Y_DIRECTION_X); gsl_vector_set(ny, 1, LAL_VIRGO_ARM_Y_DIRECTION_Y); gsl_vector_set(ny, 2, LAL_VIRGO_ARM_Y_DIRECTION_Z); } else { printf("Error: invalid detector tag\n"); exit(1); } /* Setting the components of the matrix D = 1/2 (nx nx - ny ny) */ for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { gsl_matrix_set(D, i, j, 1./2*(gsl_vector_get(nx, i)*gsl_vector_get(nx, j) - gsl_vector_get(ny, i)*gsl_vector_get(ny, j))); } } gsl_vector_free(nx); gsl_vector_free(ny); } /* Function setting the position of a detector, in cartesian coordinates */ void SetVectorXd( gsl_vector* Xd, /* Output: position vector of the detector */ const Detectortag tag) /* Tag identifying the detector */ { if(tag==LHO) { gsl_vector_set(Xd, 0, LAL_LHO_4K_VERTEX_LOCATION_X_SI); gsl_vector_set(Xd, 1, LAL_LHO_4K_VERTEX_LOCATION_Y_SI); gsl_vector_set(Xd, 2, LAL_LHO_4K_VERTEX_LOCATION_Z_SI); } else if(tag==LLO) { gsl_vector_set(Xd, 0, LAL_LLO_4K_VERTEX_LOCATION_X_SI); gsl_vector_set(Xd, 1, LAL_LLO_4K_VERTEX_LOCATION_Y_SI); gsl_vector_set(Xd, 2, LAL_LLO_4K_VERTEX_LOCATION_Z_SI); } else if(tag==VIRGO) { gsl_vector_set(Xd, 0, LAL_VIRGO_VERTEX_LOCATION_X_SI); gsl_vector_set(Xd, 1, LAL_VIRGO_VERTEX_LOCATION_Y_SI); gsl_vector_set(Xd, 2, LAL_VIRGO_VERTEX_LOCATION_Z_SI); } else { printf("Error: invalid detector tag\n"); exit(1); } } /* Function setting the cartesian coordinates of the wave frame vectors (X,Y,Z), given the position in the sky and polarization */ void SetVectorsXYZ( gsl_vector* X, /* Output: cartesian vector of the wave frame unit vector X */ gsl_vector* Y, /* Output: cartesian vector of the wave frame unit vector Y */ gsl_vector* Z, /* Output: cartesian vector of the wave frame unit vector Z */ const double theta, /* First angle for the position in the sky (Earth-based spherical angle) */ const double phi, /* Second angle for the position in the sky (Earth-based spherical angle) */ const double psi) /* Polarization angle */ { double cospsi = cos(psi); double sinpsi = sin(psi); double costheta = cos(theta); double sintheta = sin(theta); double cosphi = cos(phi); double sinphi = sin(phi); /* Unit vector X */ gsl_vector_set(X, 0, -cospsi*sinphi+sinpsi*costheta*cosphi); gsl_vector_set(X, 1, cospsi*cosphi+sinpsi*costheta*sinphi); gsl_vector_set(X, 2, -sinpsi*sintheta); /* Unit vector Y */ gsl_vector_set(Y, 0, sinpsi*sinphi+cospsi*costheta*cosphi); gsl_vector_set(Y, 1, -sinpsi*cosphi+cospsi*costheta*sinphi); gsl_vector_set(Y, 2, -cospsi*sintheta); /* Unit vector Z */ gsl_vector_set(Z, 0, -sintheta*cosphi); gsl_vector_set(Z, 1, -sintheta*sinphi); gsl_vector_set(Z, 2, -costheta); } /***************************************/ /********* Core functions **************/ /* Function to convert string input network string to Networktag */ Networktag ParseNetworktag(char* string) { Networktag tag; if(strcmp(string, "L")==0) tag = L; else if(strcmp(string, "H")==0) tag = H; else if(strcmp(string, "V")==0) tag = V; else if(strcmp(string, "LH")==0) tag = LH; else if(strcmp(string, "LV")==0) tag = LV; else if(strcmp(string, "HV")==0) tag = HV; else if(strcmp(string, "LHV")==0) tag = LHV; else { printf("Error in ParseNetworktag: string not recognized.\n"); exit(1); } return tag; } /* Function evaluating the Fourier-domain factors for LHV detectors */ /* Note: in case only one or two detectors are considered, amplitudes for the missing ones are set to 0 */ /* Contrarily to the LISA case, here returns trivially 0 or 1 */ /* (allows minimal changes from the old structure that assumed LHV - but not optimal) */ static int EvaluateDetectorFactor3Det( double* factor1, /* Output for factor for detector 1 */ double* factor2, /* Output for factor for detector 2 */ double* factor3, /* Output for factor for detector 3 */ const Networktag networktag) /* Selector for the detector network */ { switch(networktag) { case L: *factor1 = 1.; *factor2 = 0; *factor3 = 0; break; case H: *factor1 = 0; *factor2 = 1.; *factor3 = 0; break; case V: *factor1 = 0; *factor2 = 0; *factor3 = 1.; break; case LH: *factor1 = 1.; *factor2 = 1.; *factor3 = 0; break; case LV: *factor1 = 1.; *factor2 = 0; *factor3 = 1.; break; case HV: *factor1 = 0; *factor2 = 1.; *factor3 = 1.; break; case LHV: *factor1 = 1.; *factor2 = 1.; *factor3 = 1.; break; default: printf("Error in EvaluateDetectorFactor3Det: networktag not recognized.\n"); exit(1); } return SUCCESS; } /* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response (for a given detector), for given values of the inclination, position in the sky and polarization angle */ int LLVSimFDResponse( struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */ struct tagListmodesCAmpPhaseFrequencySeries **lists, /* Output: list of contribution of each mode in the detector signal, in Frequency-domain amplitude and phase form, for the given detector and sky position */ const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */ const double ra, /* Position in the sky: J2000.0 right ascension (rad) */ const double dec, /* Position in the sky: J2000.0 declination (rad) */ const double inclination, /* Inclination of the source (rad) */ const double psi, /* Polarization angle (rad) */ const Detectortag tag) /* Tag identifying the detector */ { /* Define matrix D and position vector Xd of the detector */ gsl_matrix* D = gsl_matrix_alloc(3,3); gsl_vector* Xd = gsl_vector_alloc(3); SetVectorXd(Xd, tag); SetMatrixD(D, tag); /* Conversion from (ra, dec) to the Earth-based spherical angles (theta, phi) - neglecting nutation and precession, and identifying UT1 and UTC, so accurate roughly to a second of time */ double gmst_angle = gmst_angle_from_gpstime(gpstime); double theta = PI/2 - dec; double phi = ra - gmst_angle; /* Define waveframe unit vectors (X,Y,Z) */ gsl_vector* X = gsl_vector_alloc(3); gsl_vector* Y = gsl_vector_alloc(3); gsl_vector* Z = gsl_vector_alloc(3); SetVectorsXYZ(X, Y, Z, theta, phi, psi); /* Compute the delay from geocenter to the detector */ double delaylength; gsl_blas_ddot(Xd, Z, &delaylength); double twopidelay = 2*PI*delaylength/C_SI; /* Compute the value of pattern functions Fplus, Fcross */ gsl_vector* DX = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */ gsl_vector* DY = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */ gsl_blas_dgemv( CblasNoTrans, 1., D, X, 0, DX); gsl_blas_dgemv( CblasNoTrans, 1., D, Y, 0, DY); double XDX; double XDY; double YDY; gsl_blas_ddot(X, DX, &XDX); gsl_blas_ddot(X, DY, &XDY); gsl_blas_ddot(Y, DY, &YDY); double Fplus = XDX - YDY; double Fcross = 2*XDY; /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */ ListmodesCAmpPhaseFrequencySeries* listelement = *listhlm; while(listelement) { /* Definitions: l,m, frequency series and length */ int l = listelement->l; int m = listelement->m; CAmpPhaseFrequencySeries* freqseries = listelement->freqseries; gsl_vector* freq = freqseries->freq; gsl_vector* amp_real = freqseries->amp_real; gsl_vector* amp_imag = freqseries->amp_imag; gsl_vector* phase = freqseries->phase; int len = (int) freq->size; double f; double complex camp; double complex camps; /* Computing the Ylm combined factors for plus and cross for this mode */ /* Capital Phi is set to 0 by convention */ double complex Yfactorplus; double complex Yfactorcross; if (!(l%2)) { Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); } else { Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); } /* Initializing frequency series structure for this mode, for the signal s = F+ h+ + Fx hx */ CAmpPhaseFrequencySeries *modefreqseriess = NULL; CAmpPhaseFrequencySeries_Init(&modefreqseriess, len); gsl_vector* freqs = modefreqseriess->freq; gsl_vector* amp_reals = modefreqseriess->amp_real; gsl_vector* amp_imags = modefreqseriess->amp_imag; gsl_vector* phases = modefreqseriess->phase; /* Loop over the frequencies - multiplying by F+, Fx, and add phase due to the delay from geocenter to the detector */ double complex factorcamp = Fplus*Yfactorplus + Fcross*Yfactorcross; for(int j=0; j<len; j++) { f = gsl_vector_get(freq, j); camp = gsl_vector_get(amp_real, j) + I*gsl_vector_get(amp_imag, j); camps = camp * factorcamp; gsl_vector_set(amp_reals, j, creal(camps)); gsl_vector_set(amp_imags, j, cimag(camps)); gsl_vector_set(phases, j, gsl_vector_get(phase, j) + twopidelay*f); } /* Copying the vectors of frequencies */ gsl_vector_memcpy(freqs, freq); /* Append the modes to the ouput list-of-modes structures */ *lists = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*lists, modefreqseriess, l, m); /* Going to the next mode in the list */ listelement = listelement->next; } /* Cleaning */ gsl_matrix_free(D); gsl_vector_free(Xd); gsl_vector_free(X); gsl_vector_free(Y); gsl_vector_free(Z); gsl_vector_free(DX); gsl_vector_free(DY); return SUCCESS; } /* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response for a given detector network, for given values of the inclination, position in the sky and polarization angle */ /* Note: as for now, asssumes the three detectors are L,H,V - amplitudes simply set to 0 in those that are not selected by networktag */ int LLVSimFDResponse3Det( struct tagListmodesCAmpPhaseFrequencySeries **list1, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */ struct tagListmodesCAmpPhaseFrequencySeries **list2, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */ struct tagListmodesCAmpPhaseFrequencySeries **list3, /* Output: list of contributions of each mode in the signal of detector 1, in Frequency-domain amplitude and phase form */ struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */ const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */ const double ra, /* Position in the sky: J2000.0 right ascension (rad) */ const double dec, /* Position in the sky: J2000.0 declination (rad) */ const double inclination, /* Inclination of the source (rad) */ const double psi, /* Polarization angle (rad) */ const Networktag tag) /* Tag identifying the network to use */ { /* Read which detectors are to be included in the network */ double factor1 = 0; double factor2 = 0; double factor3 = 0; EvaluateDetectorFactor3Det(&factor1, &factor2, &factor3, tag); /* Define matrix D and position vector Xd for the 3 detectors */ gsl_matrix* D1 = gsl_matrix_alloc(3,3); gsl_matrix* D2 = gsl_matrix_alloc(3,3); gsl_matrix* D3 = gsl_matrix_alloc(3,3); gsl_vector* Xd1 = gsl_vector_alloc(3); gsl_vector* Xd2 = gsl_vector_alloc(3); gsl_vector* Xd3 = gsl_vector_alloc(3); SetVectorXd(Xd1, LHO); SetVectorXd(Xd2, LLO); SetVectorXd(Xd3, VIRGO); SetMatrixD(D1, LHO); SetMatrixD(D2, LLO); SetMatrixD(D3, VIRGO); /* Conversion from (ra, dec) to the Earth-based spherical angles (theta, phi) - neglecting nutation and precession, and identifying UT1 and UTC, so accurate roughly to a second of time */ double gmst_angle = gmst_angle_from_gpstime(gpstime); double theta = PI/2 - dec; double phi = ra - gmst_angle; /* Define waveframe unit vectors (X,Y,Z) */ gsl_vector* X = gsl_vector_alloc(3); gsl_vector* Y = gsl_vector_alloc(3); gsl_vector* Z = gsl_vector_alloc(3); SetVectorsXYZ(X, Y, Z, theta, phi, psi); /* Compute the delays from geocenter to each detector */ double delaylength1 = 0; double delaylength2 = 0; double delaylength3 = 0; gsl_blas_ddot(Xd1, Z, &delaylength1); gsl_blas_ddot(Xd2, Z, &delaylength2); gsl_blas_ddot(Xd3, Z, &delaylength3); double twopidelay1 = 2*PI*delaylength1/C_SI; double twopidelay2 = 2*PI*delaylength2/C_SI; double twopidelay3 = 2*PI*delaylength3/C_SI; /* Compute the value of pattern functions Fplus, Fcross for each detector */ gsl_vector* DX1 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */ gsl_vector* DY1 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */ gsl_vector* DX2 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */ gsl_vector* DY2 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */ gsl_vector* DX3 = gsl_vector_calloc(3); /* Temporary vector D.X, initialized to 0 */ gsl_vector* DY3 = gsl_vector_calloc(3); /* Temporary vector D.Y, initialized to 0 */ gsl_blas_dgemv( CblasNoTrans, 1., D1, X, 0, DX1); gsl_blas_dgemv( CblasNoTrans, 1., D1, Y, 0, DY1); gsl_blas_dgemv( CblasNoTrans, 1., D2, X, 0, DX2); gsl_blas_dgemv( CblasNoTrans, 1., D2, Y, 0, DY2); gsl_blas_dgemv( CblasNoTrans, 1., D3, X, 0, DX3); gsl_blas_dgemv( CblasNoTrans, 1., D3, Y, 0, DY3); double XDX1 = 0.; double XDY1 = 0.; double YDY1 = 0.; double XDX2 = 0.; double XDY2 = 0.; double YDY2 = 0.; double XDX3 = 0.; double XDY3 = 0.; double YDY3 = 0.; gsl_blas_ddot(X, DX1, &XDX1); gsl_blas_ddot(X, DY1, &XDY1); gsl_blas_ddot(Y, DY1, &YDY1); gsl_blas_ddot(X, DX2, &XDX2); gsl_blas_ddot(X, DY2, &XDY2); gsl_blas_ddot(Y, DY2, &YDY2); gsl_blas_ddot(X, DX3, &XDX3); gsl_blas_ddot(X, DY3, &XDY3); gsl_blas_ddot(Y, DY3, &YDY3); double Fplus1 = XDX1 - YDY1; double Fcross1 = 2*XDY1; double Fplus2 = XDX2 - YDY2; double Fcross2 = 2*XDY2; double Fplus3 = XDX3 - YDY3; double Fcross3 = 2*XDY3; /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */ ListmodesCAmpPhaseFrequencySeries* listelement = *listhlm; while(listelement) { /* Definitions: l,m, frequency series and length */ int l = listelement->l; int m = listelement->m; CAmpPhaseFrequencySeries* freqseries = listelement->freqseries; gsl_vector* freq = freqseries->freq; gsl_vector* amp_real = freqseries->amp_real; gsl_vector* amp_imag = freqseries->amp_imag; gsl_vector* phase = freqseries->phase; int len = (int) freq->size; double f; double complex camp; double complex camp1; double complex camp2; double complex camp3; /* Computing the Ylm combined factors for plus and cross for this mode */ /* Capital Phi is set to 0 by convention */ double complex Yfactorplus; double complex Yfactorcross; if (!(l%2)) { Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); } else { Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m))); } /* Initializing frequency series structure for this mode, for the signal s = F+ h+ + Fx hx in each detector */ CAmpPhaseFrequencySeries *modefreqseries1 = NULL; CAmpPhaseFrequencySeries *modefreqseries2 = NULL; CAmpPhaseFrequencySeries *modefreqseries3 = NULL; CAmpPhaseFrequencySeries_Init(&modefreqseries1, len); CAmpPhaseFrequencySeries_Init(&modefreqseries2, len); CAmpPhaseFrequencySeries_Init(&modefreqseries3, len); gsl_vector* freq1 = modefreqseries1->freq; gsl_vector* freq2 = modefreqseries2->freq; gsl_vector* freq3 = modefreqseries3->freq; gsl_vector* amp_real1 = modefreqseries1->amp_real; gsl_vector* amp_real2 = modefreqseries2->amp_real; gsl_vector* amp_real3 = modefreqseries3->amp_real; gsl_vector* amp_imag1 = modefreqseries1->amp_imag; gsl_vector* amp_imag2 = modefreqseries2->amp_imag; gsl_vector* amp_imag3 = modefreqseries3->amp_imag; gsl_vector* phase1 = modefreqseries1->phase; gsl_vector* phase2 = modefreqseries2->phase; gsl_vector* phase3 = modefreqseries3->phase; /* Loop over the frequencies - multiplying by F+, Fx, and add phase due to the delay from geocenter to the detector */ double complex factorcamp1 = Fplus1*Yfactorplus + Fcross1*Yfactorcross; double complex factorcamp2 = Fplus2*Yfactorplus + Fcross2*Yfactorcross; double complex factorcamp3 = Fplus3*Yfactorplus + Fcross3*Yfactorcross; for(int j=0; j<len; j++) { f = gsl_vector_get(freq, j); camp = gsl_vector_get(amp_real, j) + I*gsl_vector_get(amp_imag, j); /* Note: include factor123 as detector selectors, which are simpy 0 or 1 whether the detector is in the array or not */ camp1 = factor1 * camp * factorcamp1; camp2 = factor2 * camp * factorcamp2; camp3 = factor3 * camp * factorcamp3; gsl_vector_set(amp_real1, j, creal(camp1)); gsl_vector_set(amp_real2, j, creal(camp2)); gsl_vector_set(amp_real3, j, creal(camp3)); gsl_vector_set(amp_imag1, j, cimag(camp1)); gsl_vector_set(amp_imag2, j, cimag(camp2)); gsl_vector_set(amp_imag3, j, cimag(camp3)); gsl_vector_set(phase1, j, gsl_vector_get(phase, j) + twopidelay1*f); gsl_vector_set(phase2, j, gsl_vector_get(phase, j) + twopidelay2*f); gsl_vector_set(phase3, j, gsl_vector_get(phase, j) + twopidelay3*f); } /* Copying the vectors of frequencies */ gsl_vector_memcpy(freq1, freq); gsl_vector_memcpy(freq2, freq); gsl_vector_memcpy(freq3, freq); /* Append the modes to the ouput list-of-modes structures */ *list1 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*list1, modefreqseries1, l, m); *list2 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*list2, modefreqseries2, l, m); *list3 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*list3, modefreqseries3, l, m); /* Going to the next mode in the list */ listelement = listelement->next; } /* Cleaning */ gsl_matrix_free(D1); gsl_matrix_free(D2); gsl_matrix_free(D3); gsl_vector_free(Xd1); gsl_vector_free(Xd2); gsl_vector_free(Xd3); gsl_vector_free(X); gsl_vector_free(Y); gsl_vector_free(Z); gsl_vector_free(DX1); gsl_vector_free(DX2); gsl_vector_free(DX3); gsl_vector_free(DY1); gsl_vector_free(DY2); gsl_vector_free(DY3); return SUCCESS; }
{ "alphanum_fraction": 0.6777339421, "avg_line_length": 42.0876865672, "ext": "c", "hexsha": "ab99925c6a88b32bad6c2d87ac37c41148012b48", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "LLVsim/LLVFDresponse.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_path": "LLVsim/LLVFDresponse.c", "max_line_length": 222, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "LLVsim/LLVFDresponse.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 6591, "size": 22559 }
/* specfunc/gamma_inc.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "gsl_sf_erf.h" #include "gsl_sf_exp.h" #include "gsl_sf_log.h" #include "gsl_sf_gamma.h" #include "error.h" /* The dominant part, * D(a,x) := x^a e^(-x) / Gamma(a+1) */ static int gamma_inc_D(const double a, const double x, gsl_sf_result * result) { if(a < 10.0) { double lnr; gsl_sf_result lg; gsl_sf_lngamma_e(a+1.0, &lg); lnr = a * log(x) - x - lg.val; result->val = exp(lnr); result->err = 2.0 * GSL_DBL_EPSILON * (fabs(lnr) + 1.0) * fabs(result->val); return GSL_SUCCESS; } else { double mu = (x-a)/a; double term1; gsl_sf_result gstar; gsl_sf_result ln_term; gsl_sf_log_1plusx_mx_e(mu, &ln_term); /* log(1+mu) - mu */ gsl_sf_gammastar_e(a, &gstar); term1 = exp(a*ln_term.val)/sqrt(2.0*M_PI*a); result->val = term1/gstar.val; result->err = 2.0 * GSL_DBL_EPSILON * (fabs(a*ln_term.val) + 1.0) * fabs(result->val); result->err += gstar.err/fabs(gstar.val) * fabs(result->val); return GSL_SUCCESS; } } /* P series representation. */ static int gamma_inc_P_series(const double a, const double x, gsl_sf_result * result) { const int nmax = 5000; gsl_sf_result D; int stat_D = gamma_inc_D(a, x, &D); double sum = 1.0; double term = 1.0; int n; for(n=1; n<nmax; n++) { term *= x/(a+n); sum += term; if(fabs(term/sum) < GSL_DBL_EPSILON) break; } result->val = D.val * sum; result->err = D.err * fabs(sum); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); if(n == nmax) GSL_ERROR ("error", GSL_EMAXITER); else return stat_D; } /* Q large x asymptotic */ static int gamma_inc_Q_large_x(const double a, const double x, gsl_sf_result * result) { const int nmax = 5000; gsl_sf_result D; const int stat_D = gamma_inc_D(a, x, &D); double sum = 1.0; double term = 1.0; double last = 1.0; int n; for(n=1; n<nmax; n++) { term *= (a-n)/x; if(fabs(term/last) > 1.0) break; if(fabs(term/sum) < GSL_DBL_EPSILON) break; sum += term; last = term; } result->val = D.val * (a/x) * sum; result->err = D.err * fabs((a/x) * sum); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); if(n == nmax) GSL_ERROR ("error", GSL_EMAXITER); else return stat_D; } /* Uniform asymptotic for x near a, a and x large. * See [Temme, p. 285] * FIXME: need c1 coefficient */ static int gamma_inc_Q_asymp_unif(const double a, const double x, gsl_sf_result * result) { const double rta = sqrt(a); const double eps = (x-a)/a; gsl_sf_result ln_term; const int stat_ln = gsl_sf_log_1plusx_mx_e(eps, &ln_term); /* log(1+eps) - eps */ const double eta = eps * sqrt(-2.0*ln_term.val/(eps*eps)); gsl_sf_result erfc; double R; double c0, c1; gsl_sf_erfc_e(eta*M_SQRT2*rta, &erfc); if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) { c0 = -1.0/3.0 + eps*(1.0/12.0 - eps*(23.0/540.0 - eps*(353.0/12960.0 - eps*589.0/30240.0))); c1 = 0.0; } else { double rt_term; rt_term = sqrt(-2.0 * ln_term.val/(eps*eps)); c0 = (1.0 - 1.0/rt_term)/eps; c1 = 0.0; } R = exp(-0.5*a*eta*eta)/(M_SQRT2*M_SQRTPI*rta) * (c0 + c1/a); result->val = 0.5 * erfc.val + R; result->err = GSL_DBL_EPSILON * fabs(R * 0.5 * a*eta*eta) + 0.5 * erfc.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_ln; } /* Continued fraction for Q. * * Q(a,x) = D(a,x) a/x F(a,x) * 1 (1-a)/x 1/x (2-a)/x 2/x (3-a)/x * F(a.x) = ---- ------- ----- -------- ----- -------- ... * 1 + 1 + 1 + 1 + 1 + 1 + * * Uses Gautschi equivalent series method for the CF evaluation. * * Assumes a != x + 1, so that the first term of the * CF recursion is not undefined. This is why we need * gamma_inc_Q_CF_protected() below. Based on a problem * report by Teemu Ikonen [Tue Oct 10 12:17:19 MDT 2000]. */ static int gamma_inc_Q_CF(const double a, const double x, gsl_sf_result * result) { const int kmax = 5000; gsl_sf_result D; const int stat_D = gamma_inc_D(a, x, &D); double sum = 1.0; double tk = 1.0; double rhok = 0.0; int k; for(k=1; k<kmax; k++) { double ak; if(GSL_IS_ODD(k)) ak = (0.5*(k+1.0)-a)/x; else ak = 0.5*k/x; rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok)); tk *= rhok; sum += tk; if(fabs(tk/sum) < GSL_DBL_EPSILON) break; } result->val = D.val * (a/x) * sum; result->err = D.err * fabs((a/x) * sum); result->err += GSL_DBL_EPSILON * (2.0 + 0.5*k) * fabs(result->val); if(k == kmax) GSL_ERROR ("error", GSL_EMAXITER); else return stat_D; } /* See note above for gamma_inc_Q_CF(). */ static int gamma_inc_Q_CF_protected(const double a, const double x, gsl_sf_result * result) { if(fabs(1.0 - a + x) < 2.0*GSL_DBL_EPSILON) { /* * This is a problem region because when * 1.0 - a + x = 0 the first term of the * CF recursion is undefined. * * I missed this condition when I first * implemented gamma_inc_Q_CF() function, * so now I have to fix it by side-stepping * this point, using the recursion relation * Q(a,x) = Q(a-1,x) + x^(a-1) e^(-z) / Gamma(a) * = Q(a-1,x) + D(a-1,x) * to lower 'a' by one, giving an a=x point, * which is fine. */ gsl_sf_result D; gsl_sf_result tmp_CF; const int stat_tmp_CF = gamma_inc_Q_CF(a-1.0, x, &tmp_CF); const int stat_D = gamma_inc_D(a-1.0, x, &D); result->val = tmp_CF.val + D.val; result->err = tmp_CF.err + D.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_2(stat_tmp_CF, stat_D); } else { return gamma_inc_Q_CF(a, x, result); } } /* Useful for small a and x. Handles the subtraction analytically. */ static int gamma_inc_Q_series(const double a, const double x, gsl_sf_result * result) { double term1; /* 1 - x^a/Gamma(a+1) */ double sum; /* 1 + (a+1)/(a+2)(-x)/2! + (a+1)/(a+3)(-x)^2/3! + ... */ int stat_sum; double term2; /* a temporary variable used at the end */ { /* Evaluate series for 1 - x^a/Gamma(a+1), small a */ const double pg21 = -2.404113806319188570799476; /* PolyGamma[2,1] */ const double lnx = log(x); const double el = M_EULER+lnx; const double c1 = -el; const double c2 = M_PI*M_PI/12.0 - 0.5*el*el; const double c3 = el*(M_PI*M_PI/12.0 - el*el/6.0) + pg21/6.0; const double c4 = -0.04166666666666666667 * (-1.758243446661483480 + lnx) * (-0.764428657272716373 + lnx) * ( 0.723980571623507657 + lnx) * ( 4.107554191916823640 + lnx); const double c5 = -0.0083333333333333333 * (-2.06563396085715900 + lnx) * (-1.28459889470864700 + lnx) * (-0.27583535756454143 + lnx) * ( 1.33677371336239618 + lnx) * ( 5.17537282427561550 + lnx); const double c6 = -0.0013888888888888889 * (-2.30814336454783200 + lnx) * (-1.65846557706987300 + lnx) * (-0.88768082560020400 + lnx) * ( 0.17043847751371778 + lnx) * ( 1.92135970115863890 + lnx) * ( 6.22578557795474900 + lnx); const double c7 = -0.00019841269841269841 * (-2.5078657901291800 + lnx) * (-1.9478900888958200 + lnx) * (-1.3194837322612730 + lnx) * (-0.5281322700249279 + lnx) * ( 0.5913834939078759 + lnx) * ( 2.4876819633378140 + lnx) * ( 7.2648160783762400 + lnx); const double c8 = -0.00002480158730158730 * (-2.677341544966400 + lnx) * (-2.182810448271700 + lnx) * (-1.649350342277400 + lnx) * (-1.014099048290790 + lnx) * (-0.191366955370652 + lnx) * ( 0.995403817918724 + lnx) * ( 3.041323283529310 + lnx) * ( 8.295966556941250 + lnx); const double c9 = -2.75573192239859e-6 * (-2.8243487670469080 + lnx) * (-2.3798494322701120 + lnx) * (-1.9143674728689960 + lnx) * (-1.3814529102920370 + lnx) * (-0.7294312810261694 + lnx) * ( 0.1299079285269565 + lnx) * ( 1.3873333251885240 + lnx) * ( 3.5857258865210760 + lnx) * ( 9.3214237073814600 + lnx); const double c10 = -2.75573192239859e-7 * (-2.9540329644556910 + lnx) * (-2.5491366926991850 + lnx) * (-2.1348279229279880 + lnx) * (-1.6741881076349450 + lnx) * (-1.1325949616098420 + lnx) * (-0.4590034650618494 + lnx) * ( 0.4399352987435699 + lnx) * ( 1.7702236517651670 + lnx) * ( 4.1231539047474080 + lnx) * ( 10.342627908148680 + lnx); term1 = a*(c1+a*(c2+a*(c3+a*(c4+a*(c5+a*(c6+a*(c7+a*(c8+a*(c9+a*c10))))))))); } { /* Evaluate the sum. */ const int nmax = 5000; double t = 1.0; int n; sum = 1.0; for(n=1; n<nmax; n++) { t *= -x/(n+1.0); sum += (a+1.0)/(a+n+1.0)*t; if(fabs(t/sum) < GSL_DBL_EPSILON) break; } if(n == nmax) stat_sum = GSL_EMAXITER; else stat_sum = GSL_SUCCESS; } term2 = (1.0 - term1) * a/(a+1.0) * x * sum; result->val = term1 + term2; result->err = GSL_DBL_EPSILON * (fabs(term1) + 2.0*fabs(term2)); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_sum; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_gamma_inc_Q_e(const double a, const double x, gsl_sf_result * result) { if(a <= 0.0 || x < 0.0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(x <= 0.5*a) { /* If the series is quick, do that. It is * robust and simple. */ gsl_sf_result P; int stat_P = gamma_inc_P_series(a, x, &P); result->val = 1.0 - P.val; result->err = P.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_P; } else if(a >= 1.0e+06 && (x-a)*(x-a) < a) { /* Then try the difficult asymptotic regime. * This is the only way to do this region. */ return gamma_inc_Q_asymp_unif(a, x, result); } else if(a < 0.2 && x < 5.0) { /* Cancellations at small a must be handled * analytically; x should not be too big * either since the series terms grow * with x and log(x). */ return gamma_inc_Q_series(a, x, result); } else if(a <= x) { if(x <= 1.0e+06) { /* Continued fraction is excellent for x >~ a. * We do not let x be too large when x > a since * it is somewhat pointless to try this there; * the function is rapidly decreasing for * x large and x > a, and it will just * underflow in that region anyway. We * catch that case in the standard * large-x method. */ return gamma_inc_Q_CF(a, x, result); } else { return gamma_inc_Q_large_x(a, x, result); } } else { if(a < 0.8*x) { /* Continued fraction again. The convergence * is a little slower here, but that is fine. * We have to trade that off against the slow * convergence of the series, which is the * only other option. */ return gamma_inc_Q_CF(a, x, result); } else { gsl_sf_result P; int stat_P = gamma_inc_P_series(a, x, &P); result->val = 1.0 - P.val; result->err = P.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_P; } } } int gsl_sf_gamma_inc_P_e(const double a, const double x, gsl_sf_result * result) { if(a <= 0.0 || x < 0.0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 20.0 || x < 0.5*a) { /* Do the easy series cases. Robust and quick. */ return gamma_inc_P_series(a, x, result); } else if(a > 1.0e+06 && (x-a)*(x-a) < a) { /* Crossover region. Note that Q and P are * roughly the same order of magnitude here, * so the subtraction is stable. */ gsl_sf_result Q; int stat_Q = gamma_inc_Q_asymp_unif(a, x, &Q); result->val = 1.0 - Q.val; result->err = Q.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_Q; } else if(a <= x) { /* Q <~ P in this area, so the * subtractions are stable. */ gsl_sf_result Q; int stat_Q; if(a > 0.2*x) { stat_Q = gamma_inc_Q_CF(a, x, &Q); } else { stat_Q = gamma_inc_Q_large_x(a, x, &Q); } result->val = 1.0 - Q.val; result->err = Q.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_Q; } else { if((x-a)*(x-a) < a) { /* This condition is meant to insure * that Q is not very close to 1, * so the subtraction is stable. */ gsl_sf_result Q; int stat_Q = gamma_inc_Q_CF_protected(a, x, &Q); result->val = 1.0 - Q.val; result->err = Q.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return stat_Q; } else { return gamma_inc_P_series(a, x, result); } } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_gamma_inc_P(const double a, const double x) { EVAL_RESULT(gsl_sf_gamma_inc_P_e(a, x, &result)); } double gsl_sf_gamma_inc_Q(const double a, const double x) { EVAL_RESULT(gsl_sf_gamma_inc_Q_e(a, x, &result)); }
{ "alphanum_fraction": 0.5563333333, "avg_line_length": 28.6806883365, "ext": "c", "hexsha": "ca3d903a3f70bba8b262617435dd47c7e0fd0bbb", "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/specfunc/gamma_inc.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/specfunc/gamma_inc.c", "max_line_length": 96, "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/specfunc/gamma_inc.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 5015, "size": 15000 }
/* vector/gsl_vector_complex_float.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_COMPLEX_FLOAT_H__ #define __GSL_VECTOR_COMPLEX_FLOAT_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_float.h> #include <gsl/gsl_vector_complex.h> #include <gsl/gsl_block_complex_float.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; float *data; gsl_block_complex_float *block; int owner; } gsl_vector_complex_float; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_view; typedef _gsl_vector_complex_float_view gsl_vector_complex_float_view; typedef struct { gsl_vector_complex_float vector; } _gsl_vector_complex_float_const_view; typedef const _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view; /* Allocation */ gsl_vector_complex_float *gsl_vector_complex_float_alloc (const size_t n); gsl_vector_complex_float *gsl_vector_complex_float_calloc (const size_t n); gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_block (gsl_block_complex_float * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_complex_float * gsl_vector_complex_float_alloc_from_vector (gsl_vector_complex_float * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_complex_float_free (gsl_vector_complex_float * v); /* Views */ _gsl_vector_complex_float_view gsl_vector_complex_float_view_array (float *base, size_t n); _gsl_vector_complex_float_view gsl_vector_complex_float_view_array_with_stride (float *base, size_t stride, size_t n); _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array (const float *base, size_t n); _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_view_array_with_stride (const float *base, size_t stride, size_t n); _gsl_vector_complex_float_view gsl_vector_complex_float_subvector (gsl_vector_complex_float *base, size_t i, size_t n); _gsl_vector_complex_float_view gsl_vector_complex_float_subvector_with_stride (gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector (const gsl_vector_complex_float *base, size_t i, size_t n); _gsl_vector_complex_float_const_view gsl_vector_complex_float_const_subvector_with_stride (const gsl_vector_complex_float *v, size_t i, size_t stride, size_t n); _gsl_vector_float_view gsl_vector_complex_float_real (gsl_vector_complex_float *v); _gsl_vector_float_view gsl_vector_complex_float_imag (gsl_vector_complex_float *v); _gsl_vector_float_const_view gsl_vector_complex_float_const_real (const gsl_vector_complex_float *v); _gsl_vector_float_const_view gsl_vector_complex_float_const_imag (const gsl_vector_complex_float *v); /* Operations */ gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i); void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z); gsl_complex_float *gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i); const gsl_complex_float *gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i); void gsl_vector_complex_float_set_zero (gsl_vector_complex_float * v); void gsl_vector_complex_float_set_all (gsl_vector_complex_float * v, gsl_complex_float z); int gsl_vector_complex_float_set_basis (gsl_vector_complex_float * v, size_t i); int gsl_vector_complex_float_fread (FILE * stream, gsl_vector_complex_float * v); int gsl_vector_complex_float_fwrite (FILE * stream, const gsl_vector_complex_float * v); int gsl_vector_complex_float_fscanf (FILE * stream, gsl_vector_complex_float * v); int gsl_vector_complex_float_fprintf (FILE * stream, const gsl_vector_complex_float * v, const char *format); int gsl_vector_complex_float_memcpy (gsl_vector_complex_float * dest, const gsl_vector_complex_float * src); int gsl_vector_complex_float_reverse (gsl_vector_complex_float * v); int gsl_vector_complex_float_swap (gsl_vector_complex_float * v, gsl_vector_complex_float * w); int gsl_vector_complex_float_swap_elements (gsl_vector_complex_float * v, const size_t i, const size_t j); int gsl_vector_complex_float_isnull (const gsl_vector_complex_float * v); int gsl_vector_complex_float_ispos (const gsl_vector_complex_float * v); int gsl_vector_complex_float_isneg (const gsl_vector_complex_float * v); #ifdef HAVE_INLINE extern inline gsl_complex_float gsl_vector_complex_float_get (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { gsl_complex_float zero = {{0, 0}}; GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero); } #endif return *GSL_COMPLEX_FLOAT_AT (v, i); } extern inline void gsl_vector_complex_float_set (gsl_vector_complex_float * v, const size_t i, gsl_complex_float z) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif *GSL_COMPLEX_FLOAT_AT (v, i) = z; } extern inline gsl_complex_float * gsl_vector_complex_float_ptr (gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } extern inline const gsl_complex_float * gsl_vector_complex_float_const_ptr (const gsl_vector_complex_float * v, const size_t i) { #if GSL_RANGE_CHECK if (i >= v->size) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return GSL_COMPLEX_FLOAT_AT (v, i); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_COMPLEX_FLOAT_H__ */
{ "alphanum_fraction": 0.6664631913, "avg_line_length": 33.0282258065, "ext": "h", "hexsha": "0823a23e62e8be74aa5765cc3ea5e9b08864f801", "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/vector/gsl_vector_complex_float.h", "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/vector/gsl_vector_complex_float.h", "max_line_length": 108, "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/vector/gsl_vector_complex_float.h", "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": 1708, "size": 8191 }
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_statistics_double.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_iarray.h" #include "tz_stack_attribute.h" #include "tz_image_lib.h" #include "tz_objdetect.h" #include "tz_imatrix.h" #include "tz_stack_math.h" #include "tz_stack_bwdist.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_matlabio.h" #include "tz_darray.h" #include "tz_stack_draw.h" #include "tz_stack_code.h" #include "tz_stack_bwmorph.h" #include "tz_stack.h" #include "tz_voxel_graphics.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; //char matlab_path[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } /* if (argc < 3) { strcpy(matlab_path, "/Applications/MATLAB74/bin/matlab"); } else { strcpy(matlab_path, argv[2]); } */ char file_path[100]; sprintf(file_path, "../data/%s/mask.tif", neuron_name); Stack *stack = Read_Stack(file_path); //Stack_Not(stack, stack); //Set_Matlab_Path(matlab_path); //Stack *dist = Stack_Bwdist(stack); /* Objlabel_Workspace *ow = New_Objlabel_Workspace(); ow->conn = 18; Stack_Not(stack, stack); Stack *dist = Stack_Boundary_Code(stack, NULL, ow); Stack_Not(stack, stack); */ Stack *dist = Stack_Bwdist_L_U16(stack, NULL, 1); sprintf(file_path, "../data/%s/dist.tif", neuron_name); Write_Stack(file_path, dist); printf("Distance map %s created.\n", file_path); /* Write_Stack(file_path, Scale_Double_Stack((double *)dist->array, stack->width, stack->height, stack->depth, GREY)); */ Kill_Stack(stack); //Stack *seeds = Stack_Local_Max(dist, NULL, STACK_LOCMAX_FLAT); //Stack_Clean_Locmax(dist, seeds); Stack *seeds = Stack_Locmax_Region(dist, 26); //Write_Stack("../data/test.tif", seeds); Object_3d_List *objs = Stack_Find_Object_N(seeds, NULL, 1, 0, 26); Zero_Stack(seeds); int objnum = 0; while (objs != NULL) { Object_3d *obj = objs->data; Voxel_t center; Object_3d_Central_Voxel(obj, center); Set_Stack_Pixel(seeds, center[0], center[1], center[2], 0, 1); objs = objs->next; objnum++; } printf("objnum: %d\n", objnum); sprintf(file_path, "../data/%s/seeds.tif", neuron_name); Write_Stack(file_path, seeds); printf("%s (seed mask) created.\n", file_path); /* int max_idx = 0; double max_dist = darray_max((double *) (dist->array), Stack_Voxel_Number(dist), &max_idx); */ Voxel_List *list = Stack_To_Voxel_List(seeds); printf("%d\n", Voxel_List_Length(list)); int *seed_offset = (int *) malloc(sizeof(int) * Voxel_List_Length(list)); int i; int idx = Voxel_List_Length(list) - 1; int stack_length = Stack_Voxel_Number(seeds); for (i = 0; i < stack_length; i++) { if (seeds->array[i] > 0) { seed_offset[idx--] = i; } } if (idx != -1) { TZ_WARN(ERROR_DATA_VALUE); } sprintf(file_path, "../data/%s/seed_offset.ar", neuron_name); iarray_write(file_path, seed_offset, Voxel_List_Length(list)); printf("%s (seed indices) created.\n", file_path); Pixel_Array *pa = Voxel_List_Sampling(dist, list); sprintf(file_path, "../data/%s/seeds.pa", neuron_name); Pixel_Array_Write(file_path, pa); printf("%s (seed values d^2) created.\n", file_path); //double *pa_array = (double *) pa->array; uint16 *pa_array16 = (uint16 *) pa->array; double *pa_array = darray_malloc(pa->size); for (i = 0; i < pa->size; i++) { pa_array[i] = sqrt(pa_array16[i]); } sprintf(file_path, "../data/%s/seeds.ar", neuron_name); darray_write(file_path, pa_array, pa->size); printf("%s (seed values d) created.\n", file_path); /* printf("mean: %g, std: %g\n", gsl_stats_mean(pa_array, 1, pa->size), sqrt(gsl_stats_variance(pa_array, 1, pa->size))); printf("%g\n", gsl_stats_max(pa_array, 1, pa->size)); */ //int max_idx2; //double max_dist2 = darray_max(pa_array, pa->size, &max_idx2); int n = Stack_Voxel_Number(seeds); //double *dist_array = (double *) dist->array; uint16 *dist_array = (uint16 *) dist->array; for (i = 0; i < n; i++) { if (dist_array[i] == 1) { seeds->array[i] = 0; } } sprintf(file_path, "../data/%s/large_seeds.tif", neuron_name); Write_Stack(file_path, seeds); printf("%s (seeds for d > 1) created.\n", file_path); Kill_Stack(dist); Kill_Stack(seeds); free(seed_offset); Kill_Pixel_Array(pa); return 0; }
{ "alphanum_fraction": 0.6574561404, "avg_line_length": 26.9822485207, "ext": "c", "hexsha": "81b21d73c2e421fec1bb9db19712de50f65eb0ea", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_seed.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_seed.c", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_seed.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 1399, "size": 4560 }
/* * global.h * * Created on: Apr 5, 2013 * Authors: vgomez, Sep Thijssen */ #ifndef GLOBAL_H_ #define GLOBAL_H_ #include <vector> #include <math.h> #include <iostream> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <ctime> #include <hal_quadrotor/State.h> #define SIZE_MSG 5 using namespace std; // Message structure // IIIII.XXX.xxx.YYY.yyy.ZZZ.zzz.UUU.uuu.VVV.vvv.WWW.vvv // IIIII identifier of the UVA // XXX.xxx position x // YYY.yyy position y // ZZZ.zzz position z // UUU.uuu velocity x // VVV.vvv velocity y // WWW.www velocity z typedef vector<double> vec; typedef vector<vec> vvec; template<typename G> ostream& operator<<(ostream& os, const vector<G>& v) { typename vector<G>::const_iterator it; for (it=v.begin(); it!=v.end(); it++) os << *it << " "; os << endl; return os; } string getState(const hal_quadrotor::State::ConstPtr& msg); #endif /* GLOBAL_H_ */
{ "alphanum_fraction": 0.6804798255, "avg_line_length": 17.6346153846, "ext": "h", "hexsha": "aa993eaf1353cac23080f88901a097233979ab3c", "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": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "jiangchenzhu/crates_zhejiang", "max_forks_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "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": "jiangchenzhu/crates_zhejiang", "max_issues_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_line_length": 59, "max_stars_count": null, "max_stars_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "jiangchenzhu/crates_zhejiang", "max_stars_repo_path": "thirdparty/cm_picontrol/pi/global.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 283, "size": 917 }
#include <stdio.h> #include <gsl/gsl_permutation.h> int main (void) { gsl_permutation * p = gsl_permutation_alloc (3); gsl_permutation_init (p); do { gsl_permutation_fprintf (stdout, p, " %u"); printf ("\n"); } while (gsl_permutation_next(p) == GSL_SUCCESS); gsl_permutation_free (p); return 0; }
{ "alphanum_fraction": 0.6407185629, "avg_line_length": 15.1818181818, "ext": "c", "hexsha": "08ebf63a6b096dfe4d5dec72d5258d587ff9b2d5", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/permseq.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/permseq.c", "max_line_length": 50, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/permseq.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": 100, "size": 334 }
#ifndef OPENMC_CELL_H #define OPENMC_CELL_H #include <cstdint> #include <functional> // for hash #include <limits> #include <memory> // for unique_ptr #include <string> #include <unordered_map> #include <vector> #include <gsl/gsl> #include "hdf5.h" #include "pugixml.hpp" #include "dagmc.h" #include "openmc/constants.h" #include "openmc/neighbor_list.h" #include "openmc/position.h" #include "openmc/surface.h" namespace openmc { //============================================================================== // Constants //============================================================================== enum class Fill { MATERIAL, UNIVERSE, LATTICE }; // TODO: Convert to enum constexpr int32_t OP_LEFT_PAREN {std::numeric_limits<int32_t>::max()}; constexpr int32_t OP_RIGHT_PAREN {std::numeric_limits<int32_t>::max() - 1}; constexpr int32_t OP_COMPLEMENT {std::numeric_limits<int32_t>::max() - 2}; constexpr int32_t OP_INTERSECTION {std::numeric_limits<int32_t>::max() - 3}; constexpr int32_t OP_UNION {std::numeric_limits<int32_t>::max() - 4}; //============================================================================== // Global variables //============================================================================== class Cell; class ParentCell; class CellInstance; class Universe; class UniversePartitioner; namespace model { extern std::unordered_map<int32_t, int32_t> cell_map; extern std::vector<std::unique_ptr<Cell>> cells; extern std::unordered_map<int32_t, int32_t> universe_map; extern std::vector<std::unique_ptr<Universe>> universes; } // namespace model //============================================================================== //! A geometry primitive that fills all space and contains cells. //============================================================================== class Universe { public: int32_t id_; //!< Unique ID std::vector<int32_t> cells_; //!< Cells within this universe //! \brief Write universe information to an HDF5 group. //! \param group_id An HDF5 group id. void to_hdf5(hid_t group_id) const; BoundingBox bounding_box() const; std::unique_ptr<UniversePartitioner> partitioner_; }; //============================================================================== //============================================================================== class Cell { public: //---------------------------------------------------------------------------- // Constructors, destructors, factory functions explicit Cell(pugi::xml_node cell_node); Cell() {}; virtual ~Cell() = default; //---------------------------------------------------------------------------- // Methods //! \brief Determine if a cell contains the particle at a given location. //! //! The bounds of the cell are detemined by a logical expression involving //! surface half-spaces. At initialization, the expression was converted //! to RPN notation. //! //! The function is split into two cases, one for simple cells (those //! involving only the intersection of half-spaces) and one for complex cells. //! Simple cells can be evaluated with short circuit evaluation, i.e., as soon //! as we know that one half-space is not satisfied, we can exit. This //! provides a performance benefit for the common case. In //! contains_complex, we evaluate the RPN expression using a stack, similar to //! how a RPN calculator would work. //! \param r The 3D Cartesian coordinate to check. //! \param u A direction used to "break ties" the coordinates are very //! close to a surface. //! \param on_surface The signed index of a surface that the coordinate is //! known to be on. This index takes precedence over surface sense //! calculations. virtual bool contains(Position r, Direction u, int32_t on_surface) const = 0; //! Find the oncoming boundary of this cell. virtual std::pair<double, int32_t> distance(Position r, Direction u, int32_t on_surface, Particle* p) const = 0; //! Write all information needed to reconstruct the cell to an HDF5 group. //! \param group_id An HDF5 group id. virtual void to_hdf5(hid_t group_id) const = 0; //! Get the BoundingBox for this cell. virtual BoundingBox bounding_box() const = 0; //---------------------------------------------------------------------------- // Accessors //! Get the temperature of a cell instance //! \param[in] instance Instance index. If -1 is given, the temperature for //! the first instance is returned. //! \return Temperature in [K] double temperature(int32_t instance = -1) const; //! Set the temperature of a cell instance //! \param[in] T Temperature in [K] //! \param[in] instance Instance index. If -1 is given, the temperature for //! all instances is set. //! \param[in] set_contained If this cell is not filled with a material, //! collect all contained cells with material fills and set their //! temperatures. void set_temperature(double T, int32_t instance = -1, bool set_contained = false); //! Get the name of a cell //! \return Cell name const std::string& name() const { return name_; }; //! Set the temperature of a cell instance //! \param[in] name Cell name void set_name(const std::string& name) { name_ = name; }; //! Get all cell instances contained by this cell //! \return Map with cell indexes as keys and instances as values std::unordered_map<int32_t, std::vector<int32_t>> get_contained_cells() const; protected: void get_contained_cells_inner(std::unordered_map<int32_t, std::vector<int32_t>>& contained_cells, std::vector<ParentCell>& parent_cells) const; public: //---------------------------------------------------------------------------- // Data members int32_t id_; //!< Unique ID std::string name_; //!< User-defined name Fill type_; //!< Material, universe, or lattice int32_t universe_; //!< Universe # this cell is in int32_t fill_; //!< Universe # filling this cell int32_t n_instances_{0}; //!< Number of instances of this cell //! \brief Index corresponding to this cell in distribcell arrays int distribcell_index_{C_NONE}; //! \brief Material(s) within this cell. //! //! May be multiple materials for distribcell. std::vector<int32_t> material_; //! \brief Temperature(s) within this cell. //! //! The stored values are actually sqrt(k_Boltzmann * T) for each temperature //! T. The units are sqrt(eV). std::vector<double> sqrtkT_; //! Definition of spatial region as Boolean expression of half-spaces std::vector<std::int32_t> region_; //! Reverse Polish notation for region expression std::vector<std::int32_t> rpn_; bool simple_; //!< Does the region contain only intersections? //! \brief Neighboring cells in the same universe. NeighborList neighbors_; Position translation_ {0, 0, 0}; //!< Translation vector for filled universe //! \brief Rotational tranfsormation of the filled universe. // //! The vector is empty if there is no rotation. Otherwise, the first 9 values //! give the rotation matrix in row-major order. When the user specifies //! rotation angles about the x-, y- and z- axes in degrees, these values are //! also present at the end of the vector, making it of length 12. std::vector<double> rotation_; std::vector<int32_t> offset_; //!< Distribcell offset table }; struct CellInstanceItem { int32_t index {-1}; //! Index into global cells array int lattice_indx{-1}; //! Flat index value of the lattice cell }; //============================================================================== class CSGCell : public Cell { public: CSGCell(); explicit CSGCell(pugi::xml_node cell_node); bool contains(Position r, Direction u, int32_t on_surface) const; std::pair<double, int32_t> distance(Position r, Direction u, int32_t on_surface, Particle* p) const; void to_hdf5(hid_t group_id) const; BoundingBox bounding_box() const; protected: bool contains_simple(Position r, Direction u, int32_t on_surface) const; bool contains_complex(Position r, Direction u, int32_t on_surface) const; BoundingBox bounding_box_simple() const; static BoundingBox bounding_box_complex(std::vector<int32_t> rpn); //! Applies DeMorgan's laws to a section of the RPN //! \param start Starting point for token modification //! \param stop Stopping point for token modification static void apply_demorgan(std::vector<int32_t>::iterator start, std::vector<int32_t>::iterator stop); //! Removes complement operators from the RPN //! \param rpn The rpn to remove complement operators from. static void remove_complement_ops(std::vector<int32_t>& rpn); //! Returns the beginning position of a parenthesis block (immediately before //! two surface tokens) in the RPN given a starting position at the end of //! that block (immediately after two surface tokens) //! \param start Starting position of the search //! \param rpn The rpn being searched static std::vector<int32_t>::iterator find_left_parenthesis(std::vector<int32_t>::iterator start, const std::vector<int32_t>& rpn); }; //============================================================================== #ifdef DAGMC class DAGCell : public Cell { public: DAGCell(); bool contains(Position r, Direction u, int32_t on_surface) const; std::pair<double, int32_t> distance(Position r, Direction u, int32_t on_surface, Particle* p) const; BoundingBox bounding_box() const; void to_hdf5(hid_t group_id) const; moab::DagMC* dagmc_ptr_; //!< Pointer to DagMC instance int32_t dag_index_; //!< DagMC index of cell }; #endif //============================================================================== //! Speeds up geometry searches by grouping cells in a search tree. // //! Currently this object only works with universes that are divided up by a //! bunch of z-planes. It could be generalized to other planes, cylinders, //! and spheres. //============================================================================== class UniversePartitioner { public: explicit UniversePartitioner(const Universe& univ); //! Return the list of cells that could contain the given coordinates. const std::vector<int32_t>& get_cells(Position r, Direction u) const; private: //! A sorted vector of indices to surfaces that partition the universe std::vector<int32_t> surfs_; //! Vectors listing the indices of the cells that lie within each partition // //! There are n+1 partitions with n surfaces. `partitions_.front()` gives the //! cells that lie on the negative side of `surfs_.front()`. //! `partitions_.back()` gives the cells that lie on the positive side of //! `surfs_.back()`. Otherwise, `partitions_[i]` gives cells sandwiched //! between `surfs_[i-1]` and `surfs_[i]`. std::vector<std::vector<int32_t>> partitions_; }; //============================================================================== //! Define a containing (parent) cell //============================================================================== struct ParentCell { gsl::index cell_index; gsl::index lattice_index; }; //============================================================================== //! Define an instance of a particular cell //============================================================================== struct CellInstance { //! Check for equality bool operator==(const CellInstance& other) const { return index_cell == other.index_cell && instance == other.instance; } gsl::index index_cell; gsl::index instance; }; struct CellInstanceHash { std::size_t operator()(const CellInstance& k) const { return 4096*k.index_cell + k.instance; } }; //============================================================================== // Non-member functions //============================================================================== void read_cells(pugi::xml_node node); #ifdef DAGMC int32_t next_cell(DAGCell* cur_cell, DAGSurface* surf_xed); #endif } // namespace openmc #endif // OPENMC_CELL_H
{ "alphanum_fraction": 0.6053059896, "avg_line_length": 34.7118644068, "ext": "h", "hexsha": "5cd819c26ce2003401f2d5352c84e2e1d5cb9c8c", "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": "fe12fb1e96253cf9f0e65fbdc021bf65bb8918bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sinkaa-ife/openmc", "max_forks_repo_path": "include/openmc/cell.h", "max_issues_count": 9, "max_issues_repo_head_hexsha": "fe12fb1e96253cf9f0e65fbdc021bf65bb8918bc", "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": "sinkaa-ife/openmc", "max_issues_repo_path": "include/openmc/cell.h", "max_line_length": 95, "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/cell.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": 2689, "size": 12288 }
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include <numpy/arrayobject.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> // Forward function declaration. static PyObject *zsampler_sample_region(PyObject *self, PyObject *args); static PyObject *zsampler_sample_categorical(PyObject *self, PyObject *args); // Boilerplate: method list. static PyMethodDef methods[] = { { "sample_region", zsampler_sample_region, METH_VARARGS, "Doc string."}, { "sample_bulk_categorical", zsampler_sample_categorical, METH_VARARGS, "Doc string."}, { NULL, NULL, 0, NULL } /* Sentinel */ }; static struct PyModuleDef sampler_module = { PyModuleDef_HEAD_INIT, "zsampler", /* name of module */ "", /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ methods }; PyMODINIT_FUNC PyInit_zsampler(void) { import_array(); // crucial command if NumPy API is used return PyModule_Create(&sampler_module); } /***************************************************************************** * Helper methods * *****************************************************************************/ void print_int_array(npy_int64* array, int length) { for(int i = 0; i < length; i++) { printf("%ld ", array[i]); } printf("\n"); } void print_f_array(npy_float64* array, int length) { for(int i = 0; i < length; i++) { printf("%lf ", array[i]); } printf("\n"); } static PyObject* zsampler_sample_categorical(PyObject *self, PyObject *args) { PyArrayObject *py_Z, *py_prob; if (!PyArg_ParseTuple(args, "O!O!", &PyArray_Type, &py_Z, &PyArray_Type, &py_prob)) { return NULL; } npy_int64 C_N, C_K; C_N = PyArray_SHAPE(py_prob)[0]; C_K = PyArray_SHAPE(py_prob)[1]; const gsl_rng_type * C_T; gsl_rng * C_r; gsl_rng_env_setup(); C_T = gsl_rng_taus; C_r = gsl_rng_alloc (C_T); double *_prob; // probabilities for sampling from multinomial _prob = (double*)malloc(C_K * sizeof(double)); unsigned int *_new_sample; _new_sample = (unsigned int*)malloc(C_K * sizeof(unsigned int)); PyArrayObject* out_Z = (PyArrayObject*)PyArray_NewCopy(py_Z, NPY_ANYORDER); for (int i=0; i < C_N; i++) { for (int k=0; k < C_K; k++) { _prob[k] = (*(npy_float64*)PyArray_GETPTR2(py_prob, i, k)); } gsl_ran_multinomial(C_r, (size_t)C_K, 1, _prob, _new_sample); for (int k = 0; k < C_K; k++) { npy_int64* Zk = (npy_int64*)PyArray_GETPTR2(out_Z, i, k); Zk[0] = (npy_int64)_new_sample[k]; } } free(_prob); free(_new_sample); gsl_rng_free(C_r); return (PyObject*)out_Z; // no need to IncRef out_Z } // Mixture weight priors is block-specific static PyObject* zsampler_sample_region(PyObject *self, PyObject *args) { // Input variables PyArrayObject *py_Z, *py_counts, *py_covariates, *py_beta, *py_alpha; PyArrayObject *py_region_alloc, *py_region_label_counts; /* parse single numpy array argument */ if (!PyArg_ParseTuple(args, "O!O!O!O!O!O!O!", &PyArray_Type, &py_Z, &PyArray_Type, &py_counts, &PyArray_Type, &py_covariates, &PyArray_Type, &py_beta, &PyArray_Type, &py_alpha, &PyArray_Type, &py_region_alloc, &PyArray_Type, &py_region_label_counts)) { return NULL; } Py_INCREF(py_region_alloc); Py_INCREF(py_region_label_counts); const gsl_rng_type * C_T; gsl_rng * C_r; gsl_rng_env_setup(); C_T = gsl_rng_taus; C_r = gsl_rng_alloc (C_T); // Temporary variables npy_int64 C_N, C_K, C_J; C_N = PyArray_SHAPE(py_Z)[0]; C_K = PyArray_SHAPE(py_Z)[1]; C_J = PyArray_SHAPE(py_beta)[0]; PyArrayObject* out_Z = (PyArrayObject*)PyArray_NewCopy(py_Z, NPY_ANYORDER); npy_int64 *C_counts = (npy_int64 *) PyArray_DATA(py_counts); npy_float64 *C_alpha = (npy_float64 *) PyArray_DATA(py_alpha); npy_int64 *C_region_alloc = (npy_int64 *) PyArray_DATA(py_region_alloc); npy_int64 C_labelsum; npy_int64 *C_label_counts; C_label_counts = (npy_int64*)malloc(C_K * sizeof(npy_int64)); double *_mu; _mu = (double*)malloc(C_K * sizeof(double)); double *_logpoi; _logpoi = (double*)malloc(C_K * sizeof(double)); double *_logcat; _logcat =(double*)malloc(C_K * sizeof(double)); double *_lik; _lik =(double*)malloc(C_K * sizeof(double)); double *_prob; // probabilities for sampling from multinomial _prob = (double*)malloc(C_K * sizeof(double)); unsigned int *_new_sample; _new_sample = (unsigned int*)malloc(C_K * sizeof(unsigned int)); npy_float64 C_alpha_sum = 0.0; for(int k=0; k < C_K; k++) { C_alpha_sum = C_alpha_sum + C_alpha[k]; } for (int i=0; i < C_N; i++) { C_labelsum = 0; for (int k = 0; k < C_K; k++) { // subtract current cell counts from the region counts npy_int64* accessor = (npy_int64*)PyArray_GETPTR2(py_region_label_counts, C_region_alloc[i], k); accessor[0] = accessor[0] - (*(npy_int64*)PyArray_GETPTR2(out_Z, i, k)); // TODO: make this simpler C_label_counts[k] = accessor[0]; C_labelsum = C_labelsum + C_label_counts[k]; } // computation of likelihood and interim calculations for (int k=0; k < C_K; k++) { _mu[k] = 0; for (int j=0; j < C_J; j++) { _mu[k] = _mu[k] + ((*(npy_float64*)PyArray_GETPTR2(py_covariates, i, j)) * (*(npy_float64*)PyArray_GETPTR2(py_beta, j, k))); } _logpoi[k] = ((double)C_counts[i])*_mu[k] - exp(_mu[k]); _logcat[k] = log(((double)C_label_counts[k] + C_alpha[k]) / ((double)C_labelsum + C_alpha_sum)); _lik[k] = (_logpoi[k] + _logcat[k]); } double maxval = _lik[0]; for (int k=0; k < C_K; k++) { if(_lik[k] > maxval) { maxval = _lik[k]; } } double sumexp = 0; for (int k=0; k < C_K; k++) { sumexp = sumexp + exp((double)_lik[k] - maxval); } double logsumexp = maxval + log(sumexp); for (int k=0; k < C_K; k++) { _prob[k] = exp((double)_lik[k] - logsumexp); } gsl_ran_multinomial(C_r, (size_t)C_K, 1, _prob, _new_sample); for (int k = 0; k < C_K; k++) { npy_int64* Zk = (npy_int64*)PyArray_GETPTR2(out_Z, i, k); Zk[0] = (npy_int64)_new_sample[k]; // update the region label counts npy_int64* accessor = (npy_int64*)PyArray_GETPTR2(py_region_label_counts, C_region_alloc[i], k); accessor[0] = accessor[0] + Zk[0]; } } free(C_label_counts); free(_mu); free(_logpoi); free(_logcat); free(_lik); free(_prob); free(_new_sample); gsl_rng_free(C_r); Py_DECREF(py_region_alloc); Py_DECREF(py_region_label_counts); return (PyObject*)out_Z; // no need to IncRef out_Z }
{ "alphanum_fraction": 0.5907097835, "avg_line_length": 31.188034188, "ext": "c", "hexsha": "7390950efe690954cd7fbddd6a7a981d6a5ea640", "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": "9e535a636e710a9fa146cbbd4613ece70ec90791", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jp2011/spatial-poisson-mixtures", "max_forks_repo_path": "src/z_sampler/src/sampler.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "9e535a636e710a9fa146cbbd4613ece70ec90791", "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": "jp2011/spatial-poisson-mixtures", "max_issues_repo_path": "src/z_sampler/src/sampler.c", "max_line_length": 136, "max_stars_count": 3, "max_stars_repo_head_hexsha": "9e535a636e710a9fa146cbbd4613ece70ec90791", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jp2011/spatial-poisson-mixtures", "max_stars_repo_path": "src/z_sampler/src/sampler.c", "max_stars_repo_stars_event_max_datetime": "2022-03-07T12:13:04.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-18T10:57:47.000Z", "num_tokens": 2076, "size": 7298 }
/* movstat/apply.c * * 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_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_movstat.h> /* gsl_movstat_apply_accum() Apply moving window statistic to input vector. This is a generalized routine to handle window endpoints and apply a given accumulator to the input vector. Inputs: endtype - end point handling criteria x - input vector, size n accum - accumulator to apply moving window statistic accum_params - parameters to pass to accumulator y - output vector, size n z - second output vector (i.e. minmax), size n; can be NULL w - workspace Notes: 1) It is allowed to have x = y for in-place moving statistics */ int gsl_movstat_apply_accum(const gsl_movstat_end_t endtype, const gsl_vector * x, const gsl_movstat_accum * accum, void * accum_params, gsl_vector * y, gsl_vector * z, gsl_movstat_workspace * w) { if (x->size != y->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else if (z != NULL && x->size != z->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else { const int n = (int) x->size; const int H = w->H; /* number of samples to left of current sample */ const int J = w->J; /* number of samples to right of current sample */ int i; double x1 = 0.0; /* pad values for data edges */ double xN = 0.0; double result[2]; /* initialize accumulator */ (accum->init)(w->K, w->state); /* pad initial window if necessary */ if (endtype != GSL_MOVSTAT_END_TRUNCATE) { if (endtype == GSL_MOVSTAT_END_PADZERO) { x1 = 0.0; xN = 0.0; } else if (endtype == GSL_MOVSTAT_END_PADVALUE) { x1 = gsl_vector_get(x, 0); xN = gsl_vector_get(x, n - 1); } /* pad initial windows with H values */ for (i = 0; i < H; ++i) (accum->insert)(x1, w->state); } else if (accum->delete_oldest == NULL) /* FIXME XXX */ { /* save last K - 1 samples of x for later (needed for in-place input/output) */ int idx1 = GSL_MAX(n - J - H, 0); int idx2 = n - 1; for (i = idx1; i <= idx2; ++i) w->work[i - idx1] = gsl_vector_get(x, i); } /* process input vector and fill y(0:n - J - 1) */ for (i = 0; i < n; ++i) { double xi = gsl_vector_get(x, i); int idx = i - J; (accum->insert)(xi, w->state); if (idx >= 0) { (accum->get)(accum_params, result, w->state); gsl_vector_set(y, idx, result[0]); if (z != NULL) gsl_vector_set(z, idx, result[1]); } } if (endtype == GSL_MOVSTAT_END_TRUNCATE) { /* need to fill y(n-J:n-1) using shrinking windows */ int idx1 = GSL_MAX(n - J, 0); int idx2 = n - 1; if (accum->delete_oldest == NULL) { int wsize = n - GSL_MAX(n - J - H, 0); /* size of work array */ for (i = idx1; i <= idx2; ++i) { int nsamp = n - GSL_MAX(i - H, 0); /* number of samples in this window */ int j; (accum->init)(w->K, w->state); for (j = wsize - nsamp; j < wsize; ++j) (accum->insert)(w->work[j], w->state); /* yi = acc_get [ work(i:K-2) ] */ (accum->get)(accum_params, result, w->state); gsl_vector_set(y, i, result[0]); if (z != NULL) gsl_vector_set(z, i, result[1]); } } else { for (i = idx1; i <= idx2; ++i) { if (i - H > 0) { /* delete oldest window sample as we move closer to edge */ (accum->delete_oldest)(w->state); } /* yi = acc_get [ work(i:K-2) ] */ (accum->get)(accum_params, result, w->state); gsl_vector_set(y, i, result[0]); if (z != NULL) gsl_vector_set(z, i, result[1]); } } } else { /* pad final windows and fill y(n-J:n-1) */ for (i = 0; i < J; ++i) { int idx = n - J + i; (accum->insert)(xN, w->state); if (idx >= 0) { (accum->get)(accum_params, result, w->state); gsl_vector_set(y, idx, result[0]); if (z != NULL) gsl_vector_set(z, idx, result[1]); } } } return GSL_SUCCESS; } } /* gsl_movstat_apply() Apply user-defined moving window function to input vector Inputs: endtype - end point handling criteria F - user-defined function x - input vector, size n y - output vector, size n w - workspace */ int gsl_movstat_apply(const gsl_movstat_end_t endtype, const gsl_movstat_function * F, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w) { int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_userfunc, (void *) F, y, NULL, w); return status; }
{ "alphanum_fraction": 0.5056809574, "avg_line_length": 31.2843601896, "ext": "c", "hexsha": "8ad56ebb9b37beca83f3523f71a37c3d6a1c8156", "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/apply.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/apply.c", "max_line_length": 103, "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/apply.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": 1645, "size": 6601 }
#ifndef EIGEN_BENCH_UTIL_H #define EIGEN_BENCH_UTIL_H #include <Eigen/Core> #include "BenchTimer.h" using namespace std; using namespace Eigen; #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition.hpp> #include <boost/preprocessor/seq.hpp> #include <boost/preprocessor/array.hpp> #include <boost/preprocessor/arithmetic.hpp> #include <boost/preprocessor/comparison.hpp> #include <boost/preprocessor/punctuation.hpp> #include <boost/preprocessor/punctuation/comma.hpp> #include <boost/preprocessor/stringize.hpp> template<typename MatrixType> void initMatrix_random(MatrixType& mat) __attribute__((noinline)); template<typename MatrixType> void initMatrix_random(MatrixType& mat) { mat.setRandom();// = MatrixType::random(mat.rows(), mat.cols()); } template<typename MatrixType> void initMatrix_identity(MatrixType& mat) __attribute__((noinline)); template<typename MatrixType> void initMatrix_identity(MatrixType& mat) { mat.setIdentity(); } #ifndef __INTEL_COMPILER #define DISABLE_SSE_EXCEPTIONS() { \ int aux; \ asm( \ "stmxcsr %[aux] \n\t" \ "orl $32832, %[aux] \n\t" \ "ldmxcsr %[aux] \n\t" \ : : [aux] "m" (aux)); \ } #else #define DISABLE_SSE_EXCEPTIONS() #endif #ifdef BENCH_GMM #include <gmm/gmm.h> template <typename EigenMatrixType, typename GmmMatrixType> void eiToGmm(const EigenMatrixType& src, GmmMatrixType& dst) { dst.resize(src.rows(),src.cols()); for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) dst(i,j) = src.coeff(i,j); } #endif #ifdef BENCH_GSL #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> template <typename EigenMatrixType> void eiToGsl(const EigenMatrixType& src, gsl_matrix** dst) { for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) gsl_matrix_set(*dst, i, j, src.coeff(i,j)); } #endif #ifdef BENCH_UBLAS #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> template <typename EigenMatrixType, typename UblasMatrixType> void eiToUblas(const EigenMatrixType& src, UblasMatrixType& dst) { dst.resize(src.rows(),src.cols()); for (int j=0; j<src.cols(); ++j) for (int i=0; i<src.rows(); ++i) dst(i,j) = src.coeff(i,j); } template <typename EigenType, typename UblasType> void eiToUblasVec(const EigenType& src, UblasType& dst) { dst.resize(src.size()); for (int j=0; j<src.size(); ++j) dst[j] = src.coeff(j); } #endif #endif // EIGEN_BENCH_UTIL_H
{ "alphanum_fraction": 0.7077896402, "avg_line_length": 27.1935483871, "ext": "h", "hexsha": "8883a13804414f6682c984a9268785c5f6f20cf5", "lang": "C", "max_forks_count": 1380, "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_issues_count": 851, "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_line_length": 98, "max_stars_count": 3457, "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_path": "src/Eigen-3.3/bench/BenchUtil.h", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "num_tokens": 714, "size": 2529 }
#ifndef ARRAY_H #define ARRAY_H #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cassert> #include <iostream> #include <algorithm> #include <charm++.h> #if CMK_HAS_CBLAS #include <cblas.h> #endif namespace CharjArray { class Range { public: int size, start, stop; Range() {} Range(int size_) : size(size_), start(0), stop(size) {} Range(int start_, int stop_) : size(stop_ - start_), start(start_), stop(stop_) { assert(stop >= start); } void pup(PUP::er& p) { p | size; p | start; p | stop; } }; template<int dims> class Domain { public: Range ranges[dims]; Domain() {} Domain(Range ranges_[]) { for (int i = 0; i < dims; i++) ranges[i] = ranges_[i]; } Domain(Range range) { ranges[0] = range; } Domain(Range range1, Range range2) { // TODO: fix Charj generator so it uses the array ranges[0] = range1; ranges[1] = range2; } int size() const { int total = 0; for (int i = 0; i < dims; i++) if (total == 0) total = ranges[i].size; else total *= ranges[i].size; return total; } void pup(PUP::er& p) { for (int i=0; i<dims; ++i) p | ranges[i]; } }; template<int dims> class RowMajor { public: static int access(const int i, const Domain<dims> &d) { return i - d.ranges[0].start; } static int access(const int i, const int j, const Domain<dims> &d) { return (i - d.ranges[0].start) * d.ranges[1].size + j - d.ranges[1].start; } // Generic access method, not used right now. // static int access(const int *i, const Domain<dims> &d) { // int off = i[0]; // int dimoff = 1; // for (int j = ndims-1; j > 0; --j) { // dimoff *= d.ranges[j].size; // off += dimoff * (i[j] - d.ranges[j].start); // } // return off; // } }; template<int dims> class ColMajor { public: static int access(const int i, const Domain<dims> &d) { return i - d.ranges[0].start; } static int access(const int i, const int j, const Domain<dims> &d) { return (j - d.ranges[1].start) * d.ranges[1].size + i - d.ranges[0].start; } }; template<class type, int dims = 1, class atype = RowMajor<dims> > class Array { private: Domain<dims> domain; type *block; int ref_cout; bool did_init; Array* ref_parent; public: Array(Domain<dims> domain_) : ref_parent(0), did_init(false) { init(domain_); } Array(type **block_) : did_init(false) { block = *block_; } Array(type& block_) : did_init(false) { block = &block_; } Array() : ref_parent(0), did_init(false) { } Array(Array* parent, Domain<dims> domain_) : ref_parent(parent), did_init(false) { domain = domain_; block = parent->block; } void init(Domain<dims> &domain_) { domain = domain_; //if (atype == ROW_MAJOR) block = new type[domain.size()]; //printf("Array: allocating memory, size=%d, base pointer=%p\n", // domain.size(), block); did_init = true; } type* raw() { return block; } ~Array() { if (did_init) delete[] block; } /*type* operator[] (const Domain<dims> &domain) { return block[domain.ranges[0].size]; }*/ type& operator[] (const int i) { return block[atype::access(i, domain)]; } const type& operator[] (const int i) const { return block[atype::access(i, domain)]; } type& access(const int i) { return this->operator[](i); } type& access(const int i, const int j) { //printf("Array: accessing, index (%d,%d), offset=%d, base pointer=%p\n", //i, j, atype::access(i, j, domain), block); return block[atype::access(i, j, domain)]; } type& access(const int i, const Range r) { Domain<1> d(r); //printf("Array: accessing subrange, size = %d, range (%d,%d), base pointer=%p\n", //d.size(), r.start, r.stop, block); type* buf = new type[d.size()]; for (int j = 0; j < d.size(); j++) { //printf("Array: copying element (%d,%d), base pointer=%p\n", i, j, block); buf[j] = block[atype::access(i, j, domain)]; } return *buf; } const type& access(const int i, const int j) const { return block[atype::access(i, j, domain)]; } Array<type, dims, atype>* operator[] (const Domain<dims> &domain) { return new Array<type, dims, atype>(this, domain); } int size() const { return domain.size(); } int size(int dim) const { return domain.ranges[dim].size; } void pup(PUP::er& p) { p | domain; if (p.isUnpacking()) { block = new type[domain.size()]; } PUParray(p, block, domain.size()); } void fill(const type &t) { for (int i = 0; i < domain.size(); ++i) block[i] = t; } /// Do these arrays have the same shape and contents? bool operator==(const Array &rhs) const { for (int i = 0; i < dims; ++i) if (this->size(i) != rhs.size(i)) return false; for (int i = 0; i < this->size(); ++i) if (this->block[i] != rhs.block[i]) return false; return true; } bool operator!=(const Array &rhs) const { return !(*this == rhs); } }; /** A local Matrix class for various sorts of linear-algebra work. Indexed from 0, to reflect the C-heritage of Charj. */ template <typename V, class atype = RowMajor<2> > class Matrix : public Array<V, 2, atype> { public: Matrix() { } /// A square matrix Matrix(unsigned int n) : Array<V,2,atype>(Domain<2>(n,n)) { } /// A identity matrix static Matrix* ident(int n) { Matrix *ret = new Matrix(n); ret->fill(0); for (int i = 0; i < n; ++i) ret->access(i,i) = 1; return ret; } }; template <typename T, class atype = RowMajor<1> > class Vector : public Array<T, 1, atype> { public: Vector() { } Vector(unsigned int n) : Array<T, 1, atype>(Range(n)) { } }; /// Compute the inner (dot) product v1^T * v2 // To compute v1^H * v2, call as dot(v1.C(), v2) template<typename T, class atype1, class atype2> T dot(const Vector<T, atype1> *pv1, const Vector<T, atype2> *pv2) { const Vector<T, atype1> &v1 = *pv1, &v2 = *pv2; assert(v1.size() == v2.size()); // XXX: This default initialization worries me some, since it // won't necessarily be an additive identity for all T. - Phil T ret = T(); int size = v1.size(); for (int i = 0; i < size; ++i) ret += v1[i] * v2[i]; return ret; } #if CMK_HAS_CBLAS template <> float dot<float, RowMajor<1>, RowMajor<1> >(const Vector<float, RowMajor<1> > *pv1, const Vector<float, RowMajor<1> > *pv2) { const Vector<float, RowMajor<1> > &v1 = *pv1, &v2 = *pv2; assert(v1.size() == v2.size()); return cblas_sdot(v1.size(), &(v1[0]), 1, &(v2[0]), 1); } template <> double dot<double, RowMajor<1>, RowMajor<1> >(const Vector<double, RowMajor<1> > *pv1, const Vector<double, RowMajor<1> > *pv2) { const Vector<double, RowMajor<1> > &v1 = *pv1, &v2 = *pv2; assert(v1.size() == v2.size()); return cblas_ddot(v1.size(), &(v1[0]), 1, &(v2[0]), 1); } #endif /// Computer the 1-norm of the given vector template<typename T, class atype> T norm1(const Vector<T, atype> *pv) { const Vector<T, atype> &v = *pv; // XXX: See comment about additive identity in dot(), above T ret = T(); int size = v.size(); for (int i = 0; i < size; ++i) ret += v[i]; return ret; } /// Compute the Euclidean (2) norm of the given vector template<typename T, class atype> T norm2(const Vector<T, atype> *pv) { const Vector<T, atype> &v = *pv; // XXX: See comment about additive identity in dot(), above T ret = T(); int size = v.size(); for (int i = 0; i < size; ++i) ret += v[i] * v[i]; return sqrt(ret); } #if CMK_HAS_CBLAS template<> float norm2<float, RowMajor<1> >(const Vector<float, RowMajor<1> > *pv) { const Vector<float, RowMajor<1> > &v = *pv; return cblas_snrm2(v.size(), &(v[0]), 1); } template<> double norm2<double, RowMajor<1> >(const Vector<double, RowMajor<1> > *pv) { const Vector<double, RowMajor<1> > &v = *pv; return cblas_dnrm2(v.size(), &(v[0]), 1); } #endif /// Compute the infinity (max) norm of the given vector // Will fail on zero-length vectors template<typename T, class atype> T normI(const Vector<T, atype> *pv) { const Vector<T, atype> &v = *pv; T ret = v[0]; int size = v.size(); for (int i = 1; i < size; ++i) ret = max(ret, v[i]); return ret; } /// Scale a vector by some constant template<typename T, typename U, class atype> void scale(const T &t, Vector<U, atype> *pv) { const Vector<T, atype> &v = *pv; int size = v.size(); for (int i = 0; i < size; ++i) v[i] = t * v[i]; } #if CMK_HAS_CBLAS template<> void scale<float, float, RowMajor<1> >(const float &t, Vector<float, RowMajor<1> > *pv) { Vector<float, RowMajor<1> > &v = *pv; cblas_sscal(v.size(), t, &(v[0]), 1); } template<> void scale<double, double, RowMajor<1> >(const double &t, Vector<double, RowMajor<1> > *pv) { Vector<double, RowMajor<1> > &v = *pv; cblas_dscal(v.size(), t, &(v[0]), 1); } #endif /// Add one vector to a scaled version of another template<typename T, typename U, class atype> void axpy(const T &a, const Vector<U, atype> *px, Vector<U, atype> *py) { Vector<T, atype> &x = *px; const Vector<T, atype> &y = *py; int size = x.size(); assert(size == y.size()); for (int i = 0; i < size; ++i) x[i] = a * x[i] + y[i]; } #if CMK_HAS_CBLAS template<> void axpy<float, float, RowMajor<1> >(const float &a, const Vector<float, RowMajor<1> > *px, Vector<float, RowMajor<1> > *py) { const Vector<float, RowMajor<1> > &x = *px; Vector<float, RowMajor<1> > &y = *py; int size = x.size(); assert(size == y.size()); cblas_saxpy(size, a, &(x[0]), 1, &(y[0]), 1); } template<> void axpy<double, double, RowMajor<1> >(const double &a, const Vector<double, RowMajor<1> > *px, Vector<double, RowMajor<1> > *py) { const Vector<double, RowMajor<1> > &x = *px; Vector<double, RowMajor<1> > &y = *py; int size = x.size(); assert(size == y.size()); cblas_daxpy(size, a, &(x[0]), 1, &(y[0]), 1); } #endif } #endif
{ "alphanum_fraction": 0.5543853108, "avg_line_length": 25.6062052506, "ext": "h", "hexsha": "f3b248ce11b4b67b29cab17b3abfa0aadd09e74f", "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": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "scottkwarren/config-db", "max_forks_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "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": "scottkwarren/config-db", "max_issues_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_line_length": 88, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fb5c3da2465e5cff0ad30950493b11d452bd686b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "scottkwarren/config-db", "max_stars_repo_path": "NAMD_2.12_Source/charm-6.7.1/src/langs/charj/src/charj/libs/Array.h", "max_stars_repo_stars_event_max_datetime": "2019-01-17T20:07:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-17T20:07:23.000Z", "num_tokens": 3371, "size": 10729 }
#pragma once #include "iparam.h" #include "configaccess.h" #include "optioninfo.h" #include "format.h" #include "streamreader.h" #include <gsl/gsl> #include <cmdlime/errors.h> #include <cmdlime/customnames.h> #include <sstream> #include <optional> #include <memory> #include <functional> namespace cmdlime::detail{ template<typename T> class Param : public IParam{ public: Param(std::string name, std::string shortName, std::string type, std::function<T&()> paramGetter) : info_(std::move(name), std::move(shortName), std::move(type)) , paramGetter_(std::move(paramGetter)) { } void setDefaultValue(const T& value) { hasValue_ = true; defaultValue_ = value; } OptionInfo& info() override { return info_; } const OptionInfo& info() const override { return info_; } private: bool read(const std::string& data) override { auto stream = std::stringstream{data}; if (!readFromStream(stream, paramGetter_())) return false; hasValue_ = true; return true; } bool hasValue() const override { return hasValue_; } bool isOptional() const override { return defaultValue_.has_value(); } std::string defaultValue() const override { if (!defaultValue_.has_value()) return {}; auto stream = std::stringstream{}; stream << defaultValue_.value(); return stream.str(); } private: OptionInfo info_; std::function<T&()> paramGetter_; std::optional<T> defaultValue_; bool hasValue_ = false; }; template <> inline bool Param<std::string>::read(const std::string& data) { paramGetter_() = data; hasValue_ = true; return true; } template<typename T, typename TConfig> class ParamCreator{ using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider; public: ParamCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<T&()> paramGetter) : cfg_(cfg) { Expects(!varName.empty()); Expects(!type.empty()); param_ = std::make_unique<Param<T>>(NameProvider::name(varName), NameProvider::shortName(varName), NameProvider::valueName(type), std::move(paramGetter)); } ParamCreator<T, TConfig>& operator<<(const std::string& info) { param_->info().addDescription(info); return *this; } ParamCreator<T, TConfig>& operator<<(const Name& customName) { param_->info().resetName(customName.value()); return *this; } ParamCreator<T, TConfig>& operator<<(const ShortName& customName) { static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled, "Current command line format doesn't support short names"); param_->info().resetShortName(customName.value()); return *this; } ParamCreator<T, TConfig>& operator<<(const WithoutShortName&) { static_assert(Format<ConfigAccess<TConfig>::format()>::shortNamesEnabled, "Current command line format doesn't support short names"); param_->info().resetShortName({}); return *this; } ParamCreator<T, TConfig>& operator<<(const ValueName& valueName) { param_->info().resetValueName(valueName.value()); return *this; } ParamCreator<T, TConfig>& operator()(T defaultValue = {}) { defaultValue_ = std::move(defaultValue); param_->setDefaultValue(defaultValue_); return *this; } operator T() { ConfigAccess<TConfig>{cfg_}.addParam(std::move(param_)); return defaultValue_; } private: std::unique_ptr<Param<T>> param_; T defaultValue_; TConfig& cfg_; }; template <typename T, typename TConfig> ParamCreator<T, TConfig> makeParamCreator(TConfig& cfg, const std::string& varName, const std::string& type, std::function<T&()> paramGetter) { return ParamCreator<T, TConfig>{cfg, varName, type, std::move(paramGetter)}; } }
{ "alphanum_fraction": 0.5821364452, "avg_line_length": 26.2117647059, "ext": "h", "hexsha": "7b1a3e27ad2c9038c5763fdb1f6bfd875b9ba5f8", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_line_length": 88, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/param.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 968, "size": 4456 }
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <terminal/GraphicsAttributes.h> #include <terminal/Hyperlink.h> #include <terminal/primitives.h> #include <crispy/BufferObject.h> #include <crispy/Comparison.h> #include <crispy/assert.h> #include <gsl/span> #include <gsl/span_ext> #include <iterator> #include <sstream> #include <string> #include <vector> namespace terminal { enum class LineFlags : uint8_t { None = 0x0000, Wrappable = 0x0001, Wrapped = 0x0002, Marked = 0x0004, // TODO: DoubleWidth = 0x0010, // TODO: DoubleHeight = 0x0020, }; // clang-format off template <typename, bool> struct OptionalProperty; template <typename T> struct OptionalProperty<T, false> {}; template <typename T> struct OptionalProperty<T, true> { T value; }; // clang-format on /** * Line storage with call columns sharing the same SGR attributes. */ struct TrivialLineBuffer { ColumnCount displayWidth; GraphicsAttributes textAttributes; GraphicsAttributes fillAttributes = textAttributes; HyperlinkId hyperlink {}; ColumnCount usedColumns {}; crispy::BufferFragment text {}; void reset(GraphicsAttributes _attributes) noexcept { textAttributes = _attributes; fillAttributes = _attributes; hyperlink = {}; usedColumns = {}; text.reset(); } }; template <typename Cell> using InflatedLineBuffer = std::vector<Cell>; /// Unpacks a TrivialLineBuffer into an InflatedLineBuffer<Cell>. template <typename Cell> InflatedLineBuffer<Cell> inflate(TrivialLineBuffer const& input); template <typename Cell> using LineStorage = std::variant<TrivialLineBuffer, InflatedLineBuffer<Cell>>; /** * Line<Cell> API. * * TODO: Use custom allocator for ensuring cache locality of Cells to sibling lines. * TODO: Make the line optimization work. */ template <typename Cell> class Line { public: Line() = default; Line(Line const&) = default; Line(Line&&) noexcept = default; Line& operator=(Line const&) = default; Line& operator=(Line&&) noexcept = default; using TrivialBuffer = TrivialLineBuffer; using InflatedBuffer = InflatedLineBuffer<Cell>; using Storage = LineStorage<Cell>; using value_type = Cell; using iterator = typename InflatedBuffer::iterator; using reverse_iterator = typename InflatedBuffer::reverse_iterator; using const_iterator = typename InflatedBuffer::const_iterator; Line(LineFlags _flags, ColumnCount _width, GraphicsAttributes _templateSGR): storage_ { TrivialBuffer { _width, _templateSGR } }, flags_ { static_cast<unsigned>(_flags) } { } Line(LineFlags _flags, InflatedBuffer _buffer): storage_ { std::move(_buffer) }, flags_ { static_cast<unsigned>(_flags) } { } void reset(LineFlags _flags, GraphicsAttributes _attributes) noexcept { flags_ = static_cast<unsigned>(_flags); if (isTrivialBuffer()) trivialBuffer().reset(_attributes); else setBuffer(TrivialBuffer { size(), _attributes }); } void fill(LineFlags _flags, GraphicsAttributes const& _attributes, char32_t _codepoint, uint8_t _width) noexcept { if (_codepoint == 0) reset(_flags, _attributes); else { flags_ = static_cast<unsigned>(_flags); for (Cell& cell: inflatedBuffer()) { cell.reset(); cell.write(_attributes, _codepoint, _width); } } } /// Tests if all cells are empty. [[nodiscard]] bool empty() const noexcept { if (isTrivialBuffer()) return trivialBuffer().text.empty(); for (auto const& cell: inflatedBuffer()) if (!cell.empty()) return false; return true; } /** * Fills this line with the given content. * * @p _start offset into this line of the first charater * @p _sgr graphics rendition for the line starting at @c _start until the end * @p _ascii the US-ASCII characters to fill with */ void fill(ColumnOffset _start, GraphicsAttributes const& _sgr, std::string_view _ascii) { auto& buffer = inflatedBuffer(); assert(unbox<size_t>(_start) + _ascii.size() <= buffer.size()); auto constexpr ASCII_Width = 1; auto const* s = _ascii.data(); Cell* i = &buffer[unbox<size_t>(_start)]; Cell* e = i + _ascii.size(); while (i != e) (i++)->write(_sgr, static_cast<char32_t>(*s++), ASCII_Width); auto const e2 = buffer.data() + buffer.size(); while (i != e2) (i++)->reset(); } [[nodiscard]] ColumnCount size() const noexcept { if (isTrivialBuffer()) return trivialBuffer().displayWidth; else return ColumnCount::cast_from(inflatedBuffer().size()); } void resize(ColumnCount _count); gsl::span<Cell const> trim_blank_right() const noexcept; gsl::span<Cell const> cells() const noexcept { return inflatedBuffer(); } gsl::span<Cell> useRange(ColumnOffset _start, ColumnCount _count) noexcept { #if defined(__clang__) && __clang_major__ <= 11 auto const bufferSpan = gsl::span(inflatedBuffer()); return bufferSpan.subspan(unbox<size_t>(_start), unbox<size_t>(_count)); #else // Clang <= 11 cannot deal with this (e.g. FreeBSD 13 defaults to Clang 11). return gsl::span(inflatedBuffer()).subspan(unbox<size_t>(_start), unbox<size_t>(_count)); #endif } Cell& useCellAt(ColumnOffset _column) noexcept { Require(ColumnOffset(0) <= _column); Require(_column <= ColumnOffset::cast_from(size())); // Allow off-by-one for sentinel. return inflatedBuffer()[unbox<size_t>(_column)]; } [[nodiscard]] uint8_t cellEmptyAt(ColumnOffset column) const noexcept { if (isTrivialBuffer()) { Require(ColumnOffset(0) <= column); Require(column < ColumnOffset::cast_from(size())); return unbox<size_t>(column) >= trivialBuffer().text.size() || trivialBuffer().text[column.as<size_t>()] == 0x20; } return inflatedBuffer().at(unbox<size_t>(column)).empty(); } [[nodiscard]] uint8_t cellWithAt(ColumnOffset column) const noexcept { if (isTrivialBuffer()) { Require(ColumnOffset(0) <= column); Require(column < ColumnOffset::cast_from(size())); return 1; // TODO: When trivial line is to support Unicode, this should be adapted here. } return inflatedBuffer().at(unbox<size_t>(column)).width(); } [[nodiscard]] LineFlags flags() const noexcept { return static_cast<LineFlags>(flags_); } [[nodiscard]] bool marked() const noexcept { return isFlagEnabled(LineFlags::Marked); } void setMarked(bool _enable) { setFlag(LineFlags::Marked, _enable); } [[nodiscard]] bool wrapped() const noexcept { return isFlagEnabled(LineFlags::Wrapped); } void setWrapped(bool _enable) { setFlag(LineFlags::Wrapped, _enable); } [[nodiscard]] bool wrappable() const noexcept { return isFlagEnabled(LineFlags::Wrappable); } void setWrappable(bool _enable) { setFlag(LineFlags::Wrappable, _enable); } [[nodiscard]] LineFlags wrappableFlag() const noexcept { return wrappable() ? LineFlags::Wrappable : LineFlags::None; } [[nodiscard]] LineFlags wrappedFlag() const noexcept { return marked() ? LineFlags::Wrapped : LineFlags::None; } [[nodiscard]] LineFlags markedFlag() const noexcept { return marked() ? LineFlags::Marked : LineFlags::None; } [[nodiscard]] LineFlags inheritableFlags() const noexcept { auto constexpr Inheritables = unsigned(LineFlags::Wrappable) | unsigned(LineFlags::Marked); return static_cast<LineFlags>(flags_ & Inheritables); } void setFlag(LineFlags _flag, bool _enable) noexcept { if (_enable) flags_ |= static_cast<unsigned>(_flag); else flags_ &= ~static_cast<unsigned>(_flag); } [[nodiscard]] bool isFlagEnabled(LineFlags _flag) const noexcept { return (flags_ & static_cast<unsigned>(_flag)) != 0; } [[nodiscard]] InflatedBuffer reflow(ColumnCount _newColumnCount); [[nodiscard]] std::string toUtf8() const; [[nodiscard]] std::string toUtf8Trimmed() const; // Returns a reference to this mutable grid-line buffer. // // If this line has been stored in an optimized state, then // the line will be first unpacked into a vector of grid cells. InflatedBuffer& inflatedBuffer(); InflatedBuffer const& inflatedBuffer() const; [[nodiscard]] TrivialBuffer& trivialBuffer() noexcept { return std::get<TrivialBuffer>(storage_); } [[nodiscard]] TrivialBuffer const& trivialBuffer() const noexcept { return std::get<TrivialBuffer>(storage_); } [[nodiscard]] bool isTrivialBuffer() const noexcept { return std::holds_alternative<TrivialBuffer>(storage_); } [[nodiscard]] bool isInflatedBuffer() const noexcept { return !std::holds_alternative<TrivialBuffer>(storage_); } void setBuffer(TrivialBuffer const& buffer) noexcept { storage_ = buffer; } void setBuffer(InflatedBuffer buffer) { storage_ = std::move(buffer); } void reset(GraphicsAttributes textAttributes, GraphicsAttributes fillAttributes, HyperlinkId hyperlink, crispy::BufferFragment text, ColumnCount columnsUsed) { storage_ = TrivialBuffer { size(), textAttributes, fillAttributes, hyperlink, columnsUsed, std::move(text) }; } private: Storage storage_; unsigned flags_ = 0; }; constexpr LineFlags operator|(LineFlags a, LineFlags b) noexcept { return LineFlags(unsigned(a) | unsigned(b)); } constexpr LineFlags operator~(LineFlags a) noexcept { return LineFlags(~unsigned(a)); } constexpr LineFlags operator&(LineFlags a, LineFlags b) noexcept { return LineFlags(unsigned(a) & unsigned(b)); } template <typename Cell> inline typename Line<Cell>::InflatedBuffer& Line<Cell>::inflatedBuffer() { if (std::holds_alternative<TrivialBuffer>(storage_)) storage_ = inflate<Cell>(std::get<TrivialBuffer>(storage_)); return std::get<InflatedBuffer>(storage_); } template <typename Cell> inline typename Line<Cell>::InflatedBuffer const& Line<Cell>::inflatedBuffer() const { return const_cast<Line<Cell>*>(this)->inflatedBuffer(); } } // namespace terminal namespace fmt // {{{ { template <> struct formatter<terminal::LineFlags> { template <typename ParseContext> auto parse(ParseContext& ctx) { return ctx.begin(); } template <typename FormatContext> auto format(const terminal::LineFlags _flags, FormatContext& ctx) const { static const std::array<std::pair<terminal::LineFlags, std::string_view>, 3> nameMap = { std::pair { terminal::LineFlags::Wrappable, std::string_view("Wrappable") }, std::pair { terminal::LineFlags::Wrapped, std::string_view("Wrapped") }, std::pair { terminal::LineFlags::Marked, std::string_view("Marked") }, }; std::string s; for (auto const& mapping: nameMap) { if ((mapping.first & _flags) != terminal::LineFlags::None) { if (!s.empty()) s += ","; s += mapping.second; } } return fmt::format_to(ctx.out(), "{}", s); } }; } // namespace fmt
{ "alphanum_fraction": 0.6407603465, "avg_line_length": 29.8277511962, "ext": "h", "hexsha": "3a94504a6f2ab4ad83940910384e77f741924e3d", "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": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "christianparpart/libterminal", "max_forks_repo_path": "src/terminal/Line.h", "max_issues_count": 69, "max_issues_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_issues_repo_issues_event_max_datetime": "2019-09-22T23:25:49.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-17T18:57:16.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "christianparpart/libterminal", "max_issues_repo_path": "src/terminal/Line.h", "max_line_length": 110, "max_stars_count": 4, "max_stars_repo_head_hexsha": "0e6d75a2042437084c9f9880a5c8b5661a02da07", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "christianparpart/libterminal", "max_stars_repo_path": "src/terminal/Line.h", "max_stars_repo_stars_event_max_datetime": "2019-09-19T08:57:15.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-14T22:29:57.000Z", "num_tokens": 2919, "size": 12468 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_blas.h> #include <omp.h> #include "util.h" int main(int argc, char *argv[]) { char* input_fileName1 = argv[1]; char* input_fileName2 = argv[2]; int N_doc_bg = atoi(argv[3]); int N_kw = atoi(argv[4]); int N_obs = atoi(argv[5]); int N_iter = atoi(argv[6]); double lambda = atof(argv[7]); char* output_fileName = argv[8]; int N_doc = 480000/2; int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs); int* matrix_bgi = (int*) malloc(sizeof(int) * N_kw * N_kw); int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs); int* true_index = (int*) malloc(sizeof(int) * N_kw); int* permutation = (int*) malloc(sizeof(int) * N_obs); gsl_matrix* matrix_obs; for (int round = 0; round < 10; round++) { char input_fileName1_extend[40]; char input_fileName2_extend[40]; sprintf(input_fileName1_extend, "%s%d", input_fileName1, round); sprintf(input_fileName2_extend, "%s%d", input_fileName2, round); // Setup struct timeval tv1,tv2; gettimeofday(&tv1, NULL); read_matrix(&true_index, &matrix_bgi, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend); read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend); gettimeofday(&tv2, NULL); printf("Reading done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); for (int iter = 0; iter < 10; iter++) { printf("Run %d\n", iter); matrix_obs = gsl_matrix_alloc(N_obs, N_obs); gettimeofday(&tv1, NULL); pad_matrix(&matrix_padded, &matrix, lambda, N_obs, N_doc); gettimeofday(&tv2, NULL); printf("Padding done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); gettimeofday(&tv1, NULL); observe_matrix(matrix_obs, &matrix_padded, N_obs); gettimeofday(&tv2, NULL); printf("Observed matrix generated: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); gettimeofday(&tv1, NULL); attack(matrix_obs, &matrix_bgi, &permutation, N_kw, N_obs, N_doc, N_iter); gettimeofday(&tv2, NULL); printf("Main attack done: %d.\n", (tv2.tv_sec - tv1.tv_sec)); fflush(stdout); char output_fileName_full[40]; sprintf(output_fileName_full, "%s%d-%d", output_fileName, round, iter); print_result(output_fileName_full, &permutation, &true_index, N_obs); //sprintf(output_fileName_full, "%s%d-%d-full", output_fileName, round, iter); //print_full_result(output_fileName_full, &permutation, &true_index, N_obs); } } free(matrix); free(matrix_padded); gsl_matrix_free(matrix_obs); return(0); } double log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc) { if (idx1 == idx2) return(0.0); int idx1_m = (*permutation)[idx1]; int idx2_m = (*permutation)[idx2]; double mean1, mean2, mean3; mean3 = 0; double var = 0; if (gsl_matrix_get(matrix_obs, idx1, idx1) > (*matrix)[idx1_m*N_kw + idx1_m]) { mean1 = (*matrix)[idx1_m*N_kw + idx2_m]; double x1, x2; x1 = gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx1_m]; x2 = gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx1_m*N_kw + idx2_m]; mean3 = x1 / N_doc * x2; var += x1 / N_doc * x2 * (N_doc - x2) / N_doc; } else { mean1 = (*matrix)[idx1_m*N_kw + idx2_m] * gsl_matrix_get(matrix_obs, idx1, idx1) / (*matrix)[idx1_m*N_kw + idx1_m]; var += mean1 / (*matrix)[idx1_m*N_kw + idx1_m] * ((*matrix)[idx1_m*N_kw + idx1_m] - gsl_matrix_get(matrix_obs, idx1, idx1)); } if (gsl_matrix_get(matrix_obs, idx2, idx2) > (*matrix)[idx2_m*N_kw + idx2_m]) { mean2 = mean1; double x1, x2; x1 = gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx2_m*N_kw + idx2_m]; x2 = gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx2_m]; mean3 += x1 / N_doc * x2; var += x1 / N_doc * x2 * (N_doc - x2) / N_doc; } else { mean2 = mean1 * gsl_matrix_get(matrix_obs, idx2, idx2) / (*matrix)[idx2_m*N_kw + idx2_m]; var += mean2 / (*matrix)[idx2_m*N_kw + idx2_m] * ((*matrix)[idx2_m*N_kw + idx2_m] - gsl_matrix_get(matrix_obs, idx2, idx2)); } var += 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx2_m*N_kw + idx2_m]); double score = gsl_ran_gaussian_pdf(mean2 + mean3 - gsl_matrix_get(matrix_obs, idx1, idx2), sqrt(var)); if (score == 0) return(-500.0); return(log(score)); } void attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, int N_iter) { // Initialise data structures double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs); double* score_row1 = (double*) malloc(sizeof(double) * N_obs); double* score_row2 = (double*) malloc(sizeof(double) * N_obs); int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs); int* permutation_inv = (int*) malloc(sizeof(int) * N_kw); // Initialise permutations for (int ii = 0; ii < N_obs; ii++) (*permutation)[ii] = ii; for (int ii = 0; ii < N_obs; ii++) permutation_tmp[ii] = ii; for (int ii = 0; ii < N_obs; ii++) permutation_inv[ii] = ii; for (int ii = N_obs; ii < N_kw; ii++) permutation_inv[ii] = -1; // Initialising RNG const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); struct timeval tv1,tv2; gettimeofday(&tv1, NULL); // Compute initial score #pragma omp parallel for shared(score_matrix, matrix_obs, matrix) for (int ii = 0; ii < N_obs * N_obs; ii++) score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc); gettimeofday(&tv2, NULL); printf("Initial score computed: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); // Iterations of simulated annealing double temp = (double) N_kw; int N_stuck = 0; for (int iter = 0; iter < N_iter; iter++) { /* Status code */ if (iter % (N_iter / 10) == 0) { gettimeofday(&tv1, NULL); printf("Iteration: %d, %d, %d.\n", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec)); fflush(stdout); gettimeofday(&tv2, NULL); } if (N_stuck >= 20000) iter = N_iter; /* Main code */ int idx1, idx2; permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, N_kw, N_obs); int ii = 0; #pragma omp parallel for shared(score_row1) for (ii = 0; ii < N_obs; ii++) score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc); if (idx2 >= 0) #pragma omp parallel for shared(score_row2) for (ii = 0; ii < N_obs; ii++) score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc); double score_diff = 0; for (int ii = 0; ii < N_obs; ii++) score_diff += score_row1[ii]; for (int ii = 0; ii < N_obs; ii++) score_diff -= score_matrix[idx1*N_obs + ii]; if (idx2 >= 0) { for (int ii = 0; ii < N_obs; ii++) score_diff += score_row2[ii]; for (int ii = 0; ii < N_obs; ii++) score_diff -= score_matrix[idx2*N_obs + ii]; } // compute difference in score, with exponentiation score_diff = score_diff / temp; if (score_diff < -40) score_diff = 0; else if (score_diff > 0) score_diff = 1.01; else score_diff = exp(score_diff); if (gsl_ran_flat(r, 0, 1) < score_diff) { // Update the scores for (int ii = 0; ii < N_obs; ii++) score_matrix[idx1*N_obs + ii] = score_row1[ii]; for (int ii = 0; ii < N_obs; ii++) score_matrix[ii*N_obs + idx1] = score_row1[ii]; if (idx2 >= 0) { for (int ii = 0; ii < N_obs; ii++) score_matrix[idx2*N_obs + ii] = score_row2[ii]; for (int ii = 0; ii < N_obs; ii++) score_matrix[ii*N_obs + idx2] = score_row2[ii]; } // Update the permutation permutation_inv[(*permutation)[idx1]] = -1; (*permutation)[idx1] = permutation_tmp[idx1]; permutation_inv[permutation_tmp[idx1]] = idx1; if (idx2 >= 0) { (*permutation)[idx2] = permutation_tmp[idx2]; permutation_inv[permutation_tmp[idx2]] = idx2; } N_stuck = 0; } else { // Update the permutation permutation_tmp[idx1] = (*permutation)[idx1]; if (idx2 >= 0) permutation_tmp[idx2] = (*permutation)[idx2]; N_stuck += 1; } temp *= 0.995; } free(score_matrix); free(score_row1); free(score_row2); gsl_rng_free(r); } void print_result(char* output_fileName, int** permutation, int** true_index, int N_obs) { FILE* fp = fopen(output_fileName, "w"); int count = 0; for (int ii = 0; ii < N_obs; ii++) if ((*permutation)[ii] == (*true_index)[ii]) count++; fprintf(fp, "%d\n", count); fclose(fp); printf("Success: %d/%d.\n", count, N_obs); } void print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs) { FILE* fp = fopen(output_fileName, "w"); int count = 0; for (int ii = 0; ii < N_obs; ii++) fprintf(fp, "%d, %d\n", (*permutation)[ii], (*true_index)[ii]); fclose(fp); }
{ "alphanum_fraction": 0.5669749261, "avg_line_length": 34.1661237785, "ext": "c", "hexsha": "480104b7a3a4ff9457f06d19c842150a97b53a9d", "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": "39602b0912b21afc45e73008e598f4377ba237eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_path": "PRT-EMM/attack_mp.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_path": "PRT-EMM/attack_mp.c", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_path": "PRT-EMM/attack_mp.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3059, "size": 10489 }
/* multifit_nlinear/subspace2D.c * * Copyright (C) 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 <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_poly.h> /* * This module implements a 2D subspace trust region subproblem method, * as outlined in * * [1] G. A. Shultz, R. B. Schnabel, and R. H. Byrd * A Family of Trust-Region-Based Algorithms for Unconstrained * Minimization with Strong Global Convergence Properties, * SIAM Journal on Numerical Analysis 1985 22:1, 47-67 * * [2] R. H. Byrd, R. B. Schnabel, G. A. Shultz, * Approximate solution of the trust region problem by * minimization over two-dimensional subspaces, * Mathematical Programming, January 1988, Volume 40, * Issue 1, pp 247-263 * * The idea is to solve: * * min_{dx} g^T dx + 1/2 dx^T B dx * * with constraints: * * ||D dx|| <= delta * dx \in span{dx_sd, dx_gn} * * where B is the Hessian matrix, B = J^T J * * The steps are as follows: * * 1. preloop: * a. Compute Gauss-Newton and steepest descent vectors, * dx_gn, dx_sd * b. Compute an orthonormal basis for span(D dx_sd, D dx_gn) by * constructing W = [ D dx_sd, D dx_gn ] and performing a QR * decomposition of W. The 2 columns of the Q matrix * will then span the column space of W. W should have rank 2 * unless D*dx_sd and D*dx_gn are parallel, in which case it will * have rank 1. * c. Precompute various quantities needed for the step calculation * * 2. step: * a. If the Gauss-Newton step is inside the trust region, use it * b. if W has rank 1, we cannot form a 2D subspace, so in this case * follow the steepest descent direction to the trust region boundary * and use that as the step. * c. In the full rank 2 case, if the GN point is outside the trust region, * then the minimizer of the objective function lies on the trust * region boundary. Therefore the minimization problem becomes: * * min_{dx} g^T dx + 1/2 dx^T B dx, with ||dx|| = delta, dx = Q * x * * where x is a 2-vector to be determined and the columns of Q are * the orthonormal basis vectors of the subspace. Note the equality * constraint now instead of <=. In terms of the new variable x, * the minimization problem becomes: * * min_x subg^T x + 1/2 x^T subB x, with ||Q*x|| = ||x|| = delta * * where: * subg = Q^T g (2-by-1) * subB = Q^T B Q (2-by-2) * * This equality constrained 2D minimization problem can be solved * with a Lagrangian multiplier, which results in a 4th degree polynomial * equation to be solved. The equation is: * * lambda^4 1 * + lambda^3 2 tr(B) * + lambda^2 (tr(B)^2 + 2 det(B) - g^T g / delta^2) * + lambda^1 (2 det(B) tr(B) - 2 g^T adj(B)^T g / delta^2) * + lambda^0 (det(B)^2 - g^T adj(B)^T adj(B) g / delta^2) * * where adj(B) is the adjugate matrix of B. * * We then check each of the 4 solutions for lambda to determine which * lambda results in the smallest objective function value. This x * is then used to construct the final step: dx = Q*x */ typedef struct { size_t n; /* number of observations */ size_t p; /* number of parameters */ gsl_vector *dx_gn; /* Gauss-Newton step, size p */ gsl_vector *dx_sd; /* steepest descent step, size p */ double norm_Dgn; /* || D dx_gn || */ double norm_Dsd; /* || D dx_sd || */ gsl_vector *workp; /* workspace, length p */ gsl_vector *workn; /* workspace, length n */ gsl_matrix *W; /* orthonormal basis for 2D subspace, p-by-2 */ gsl_matrix *JQ; /* J * Q, n-by-p */ gsl_vector *tau; /* Householder scalars */ gsl_vector *subg; /* subspace gradient = W^T g, 2-by-1 */ gsl_matrix *subB; /* subspace Hessian = W^T B W, 2-by-2 */ gsl_permutation *perm; /* permutation matrix */ double trB; /* Tr(subB) */ double detB; /* det(subB) */ double normg; /* || subg || */ double term0; /* g^T adj(B)^T adj(B) g */ double term1; /* g^T adj(B)^T g */ size_t rank; /* rank of [ dx_sd, dx_gn ] matrix */ gsl_poly_complex_workspace *poly_p; /* tunable parameters */ gsl_multifit_nlinear_parameters params; } subspace2D_state_t; #include "common.c" static void * subspace2D_alloc (const void * params, const size_t n, const size_t p); static void subspace2D_free(void *vstate); static int subspace2D_init(const void *vtrust_state, void *vstate); static int subspace2D_preloop(const void * vtrust_state, void * vstate); static int subspace2D_step(const void * vtrust_state, const double delta, gsl_vector * dx, void * vstate); static int subspace2D_preduction(const void * vtrust_state, const gsl_vector * dx, double * pred, void * vstate); static int subspace2D_solution(const double lambda, gsl_vector * x, subspace2D_state_t * state); static double subspace2D_objective(const gsl_vector * x, subspace2D_state_t * state); static int subspace2D_calc_gn(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx); static int subspace2D_calc_sd(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx, subspace2D_state_t * state); static void * subspace2D_alloc (const void * params, const size_t n, const size_t p) { const gsl_multifit_nlinear_parameters *par = (const gsl_multifit_nlinear_parameters *) params; subspace2D_state_t *state; state = calloc(1, sizeof(subspace2D_state_t)); if (state == NULL) { GSL_ERROR_NULL ("failed to allocate subspace2D state", GSL_ENOMEM); } state->dx_gn = gsl_vector_alloc(p); if (state->dx_gn == NULL) { GSL_ERROR_NULL ("failed to allocate space for dx_gn", GSL_ENOMEM); } state->dx_sd = gsl_vector_alloc(p); if (state->dx_sd == NULL) { GSL_ERROR_NULL ("failed to allocate space for dx_sd", GSL_ENOMEM); } state->workp = gsl_vector_alloc(p); if (state->workp == NULL) { GSL_ERROR_NULL ("failed to allocate space for workp", GSL_ENOMEM); } state->workn = gsl_vector_alloc(n); if (state->workn == NULL) { GSL_ERROR_NULL ("failed to allocate space for workn", GSL_ENOMEM); } state->W = gsl_matrix_alloc(p, 2); if (state->W == NULL) { GSL_ERROR_NULL ("failed to allocate space for W", GSL_ENOMEM); } state->JQ = gsl_matrix_alloc(n, p); if (state->JQ == NULL) { GSL_ERROR_NULL ("failed to allocate space for JQ", GSL_ENOMEM); } state->tau = gsl_vector_alloc(2); if (state->tau == NULL) { GSL_ERROR_NULL ("failed to allocate space for tau", GSL_ENOMEM); } state->subg = gsl_vector_alloc(2); if (state->subg == NULL) { GSL_ERROR_NULL ("failed to allocate space for subg", GSL_ENOMEM); } state->subB = gsl_matrix_alloc(2, 2); if (state->subB == NULL) { GSL_ERROR_NULL ("failed to allocate space for subB", GSL_ENOMEM); } state->perm = gsl_permutation_alloc(2); if (state->perm == NULL) { GSL_ERROR_NULL ("failed to allocate space for perm", GSL_ENOMEM); } state->poly_p = gsl_poly_complex_workspace_alloc(5); if (state->poly_p == NULL) { GSL_ERROR_NULL ("failed to allocate space for poly workspace", GSL_ENOMEM); } state->n = n; state->p = p; state->rank = 0; state->params = *par; return state; } static void subspace2D_free(void *vstate) { subspace2D_state_t *state = (subspace2D_state_t *) vstate; if (state->dx_gn) gsl_vector_free(state->dx_gn); if (state->dx_sd) gsl_vector_free(state->dx_sd); if (state->workp) gsl_vector_free(state->workp); if (state->workn) gsl_vector_free(state->workn); if (state->W) gsl_matrix_free(state->W); if (state->JQ) gsl_matrix_free(state->JQ); if (state->tau) gsl_vector_free(state->tau); if (state->subg) gsl_vector_free(state->subg); if (state->subB) gsl_matrix_free(state->subB); if (state->perm) gsl_permutation_free(state->perm); if (state->poly_p) gsl_poly_complex_workspace_free(state->poly_p); free(state); } /* subspace2D_init() Initialize subspace2D solver Inputs: vtrust_state - trust state vstate - workspace Return: success/error */ static int subspace2D_init(const void *vtrust_state, void *vstate) { (void)vtrust_state; (void)vstate; return GSL_SUCCESS; } /* subspace2D_preloop() Initialize subspace2D method prior to iteration loop. This involves computing the Gauss-Newton step and steepest descent step Notes: on output, 1) state->dx_gn contains Gauss-Newton step 2) state->dx_sd contains steepest descent step 3) state->rank contains the rank([dx_sd, dx_gn]) 4) if full rank subspace (rank = 2), then: state->trB = Tr(subB) state->detB = det(subB) state->normg = || subg || */ static int subspace2D_preloop(const void * vtrust_state, void * vstate) { int status; const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; subspace2D_state_t *state = (subspace2D_state_t *) vstate; gsl_vector_view v; double work_data[2]; gsl_vector_view work = gsl_vector_view_array(work_data, 2); int signum; /* calculate Gauss-Newton step */ status = subspace2D_calc_gn(trust_state, state->dx_gn); if (status) return status; /* now calculate the steepest descent step */ status = subspace2D_calc_sd(trust_state, state->dx_sd, state); if (status) return status; /* store norms */ state->norm_Dgn = scaled_enorm(trust_state->diag, state->dx_gn); state->norm_Dsd = scaled_enorm(trust_state->diag, state->dx_sd); /* * now compute orthonormal basis for span(D dx_sd, D dx_gn) using * QR decomposition; set W = [ D dx_sd, D dx_gn ] and normalize each * column to unit magnitude. Then the Q matrix will form a basis for Col(W) */ v = gsl_matrix_column(state->W, 0); gsl_vector_memcpy(&v.vector, state->dx_sd); gsl_vector_mul(&v.vector, trust_state->diag); if (state->norm_Dsd != 0) gsl_vector_scale(&v.vector, 1.0 / state->norm_Dsd); v = gsl_matrix_column(state->W, 1); gsl_vector_memcpy(&v.vector, state->dx_gn); gsl_vector_mul(&v.vector, trust_state->diag); if (state->norm_Dgn != 0) gsl_vector_scale(&v.vector, 1.0 / state->norm_Dgn); /* use a rank revealing QR decomposition in case dx_sd and dx_gn * are parallel */ gsl_linalg_QRPT_decomp(state->W, state->tau, state->perm, &signum, &work.vector); /* check for parallel dx_sd, dx_gn, in which case rank will be 1 */ state->rank = gsl_linalg_QRPT_rank(state->W, -1.0); if (state->rank == 2) { /* * full rank subspace, compute: * subg = Q^T D^{-1} g * subB = Q^T D^{-1} B D^{-1} Q where B = J^T J */ const size_t p = state->p; size_t i; gsl_matrix_view JQ = gsl_matrix_submatrix(state->JQ, 0, 0, state->n, GSL_MIN(2, p)); double B00, B10, B11, g0, g1; /* compute subg */ gsl_vector_memcpy(state->workp, trust_state->g); gsl_vector_div(state->workp, trust_state->diag); gsl_linalg_QR_QTvec(state->W, state->tau, state->workp); g0 = gsl_vector_get(state->workp, 0); g1 = gsl_vector_get(state->workp, 1); gsl_vector_set(state->subg, 0, g0); gsl_vector_set(state->subg, 1, g1); /* compute subB */ /* compute J D^{-1} */ gsl_matrix_memcpy(state->JQ, trust_state->J); for (i = 0; i < p; ++i) { gsl_vector_view c = gsl_matrix_column(state->JQ, i); double di = gsl_vector_get(trust_state->diag, i); gsl_vector_scale(&c.vector, 1.0 / di); } /* compute J D^{-1} Q */ gsl_linalg_QR_matQ(state->W, state->tau, state->JQ); /* compute subB = Q^T D^{-1} J^T J D^{-1} Q */ gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, &JQ.matrix, 0.0, state->subB); B00 = gsl_matrix_get(state->subB, 0, 0); B10 = gsl_matrix_get(state->subB, 1, 0); B11 = gsl_matrix_get(state->subB, 1, 1); state->trB = B00 + B11; state->detB = B00*B11 - B10*B10; state->normg = gsl_blas_dnrm2(state->subg); /* g^T adj(B)^T adj(B) g */ state->term0 = (B10*B10 + B11*B11)*g0*g0 - 2*B10*(B00 + B11)*g0*g1 + (B00*B00 + B10*B10)*g1*g1; /* g^T adj(B)^T g */ state->term1 = B11 * g0 * g0 + g1 * (B00*g1 - 2*B10*g0); } return GSL_SUCCESS; } /* subspace2D_step() Calculate a new step with 2D subspace method. Based on [1]. We seek a vector dx in span{dx_gn, dx_sd} which minimizes the model function subject to ||dx|| <= delta */ static int subspace2D_step(const void * vtrust_state, const double delta, gsl_vector * dx, void * vstate) { const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; subspace2D_state_t *state = (subspace2D_state_t *) vstate; if (state->norm_Dgn <= delta) { /* Gauss-Newton step is inside trust region, use it as final step * since it is the global minimizer of the quadratic model function */ gsl_vector_memcpy(dx, state->dx_gn); } else if (state->rank < 2) { /* rank of [dx_sd, dx_gn] is 1, meaning dx_sd and dx_gn * are parallel so we can't form a 2D subspace. Follow the steepest * descent direction to the trust region boundary as our step */ gsl_vector_memcpy(dx, state->dx_sd); gsl_vector_scale(dx, delta / state->norm_Dsd); } else { int status; const double delta_sq = delta * delta; double u = state->normg / delta; double a[5]; double z[8]; #if 1 a[0] = state->detB * state->detB - state->term0 / delta_sq; a[1] = 2 * state->detB * state->trB - 2 * state->term1 / delta_sq; a[2] = state->trB * state->trB + 2 * state->detB - u * u; a[3] = 2 * state->trB; a[4] = 1.0; #else double TrB_D = state->trB * delta; double detB_D = state->detB * delta; double normg_sq = state->normg * state->normg; a[0] = detB_D * detB_D - state->term0; a[1] = 2 * state->detB * state->trB * delta_sq - 2 * state->term1; a[2] = TrB_D * TrB_D + 2 * state->detB * delta_sq - normg_sq; a[3] = 2 * state->trB * delta_sq; a[4] = delta_sq; #endif status = gsl_poly_complex_solve(a, 5, state->poly_p, z); if (status == GSL_SUCCESS) { size_t i; double min = 0.0; int mini = -1; double x_data[2]; gsl_vector_view x = gsl_vector_view_array(x_data, 2); /* * loop through all four values of the Lagrange multiplier * lambda. For each lambda, evaluate the objective function * with Re(lambda) to determine which lambda minimizes the * function */ for (i = 0; i < 4; ++i) { double cost, normx; /*fprintf(stderr, "root: %.12e + %.12e i\n", z[2*i], z[2*i+1]);*/ status = subspace2D_solution(z[2*i], &x.vector, state); if (status != GSL_SUCCESS) continue; /* singular matrix system */ /* ensure ||x|| = delta */ normx = gsl_blas_dnrm2(&x.vector); if (normx == 0.0) continue; gsl_vector_scale(&x.vector, delta / normx); /* evaluate objective function to determine minimizer */ cost = subspace2D_objective(&x.vector, state); if (mini < 0 || cost < min) { mini = (int) i; min = cost; } } if (mini < 0) { /* did not find minimizer - should not get here */ return GSL_FAILURE; } else { /* compute x which minimizes objective function */ subspace2D_solution(z[2*mini], &x.vector, state); /* dx = Q * x */ gsl_vector_set_zero(dx); gsl_vector_set(dx, 0, gsl_vector_get(&x.vector, 0)); gsl_vector_set(dx, 1, gsl_vector_get(&x.vector, 1)); gsl_linalg_QR_Qvec(state->W, state->tau, dx); /* compute final dx by multiplying by D^{-1} */ gsl_vector_div(dx, trust_state->diag); } } else { GSL_ERROR ("gsl_poly_complex_solve failed", status); } } return GSL_SUCCESS; } static int subspace2D_preduction(const void * vtrust_state, const gsl_vector * dx, double * pred, void * vstate) { const gsl_multifit_nlinear_trust_state *trust_state = (const gsl_multifit_nlinear_trust_state *) vtrust_state; subspace2D_state_t *state = (subspace2D_state_t *) vstate; *pred = quadratic_preduction(trust_state->f, trust_state->J, dx, state->workn); return GSL_SUCCESS; } /* solve 2D subspace problem: (B + lambda*I) x = -g */ static int subspace2D_solution(const double lambda, gsl_vector * x, subspace2D_state_t * state) { int status = GSL_SUCCESS; double C_data[4]; gsl_matrix_view C = gsl_matrix_view_array(C_data, 2, 2); double B00 = gsl_matrix_get(state->subB, 0, 0); double B10 = gsl_matrix_get(state->subB, 1, 0); double B11 = gsl_matrix_get(state->subB, 1, 1); /* construct C = B + lambda*I */ gsl_matrix_set(&C.matrix, 0, 0, B00 + lambda); gsl_matrix_set(&C.matrix, 1, 0, B10); gsl_matrix_set(&C.matrix, 0, 1, B10); gsl_matrix_set(&C.matrix, 1, 1, B11 + lambda); /* use modified Cholesky in case C is not positive definite */ gsl_linalg_mcholesky_decomp(&C.matrix, state->perm, NULL); gsl_linalg_mcholesky_solve(&C.matrix, state->perm, state->subg, x); gsl_vector_scale(x, -1.0); return status; } /* evaluate 2D objective function: f(x) = g^T x + 1/2 x^T B x */ static double subspace2D_objective(const gsl_vector * x, subspace2D_state_t * state) { double f; double y_data[2]; gsl_vector_view y = gsl_vector_view_array(y_data, 2); /* compute: y = g + 1/2 B x */ gsl_vector_memcpy(&y.vector, state->subg); gsl_blas_dsymv(CblasLower, 0.5, state->subB, x, 1.0, &y.vector); /* compute: f = x^T ( g + 1/2 B x ) */ gsl_blas_ddot(x, &y.vector, &f); return f; } /* subspace2D_calc_gn() Calculate Gauss-Newton step which satisfies: J dx_gn = -f Inputs: trust_state - trust state variables dx - (output) Gauss-Newton step Return: success/error */ static int subspace2D_calc_gn(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx) { int status; const gsl_multifit_nlinear_parameters *params = trust_state->params; /* initialize linear least squares solver */ status = (params->solver->init)(trust_state, trust_state->solver_state); if (status) return status; /* prepare the linear solver to compute Gauss-Newton step */ status = (params->solver->presolve)(0.0, trust_state, trust_state->solver_state); if (status) return status; /* solve: J dx_gn = -f for Gauss-Newton step */ status = (params->solver->solve)(trust_state->f, dx, trust_state, trust_state->solver_state); if (status) return status; return GSL_SUCCESS; } /* subspace2D_calc_sd() Calculate steepest descent step, dx_sd = - || D^{-1} g ||^2 / || J D^{-2} g ||^2 D^{-2} g Inputs: trust_state - trust state variables dx - (output) steepest descent vector state - workspace Return: success/error */ static int subspace2D_calc_sd(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx, subspace2D_state_t * state) { double norm_Dinvg; /* || D^{-1} g || */ double norm_JDinv2g; /* || J D^{-2} g || */ double alpha; /* || D^{-1} g ||^2 / || J D^{-2} g ||^2 */ double u; /* compute workp = D^{-1} g and its norm */ gsl_vector_memcpy(state->workp, trust_state->g); gsl_vector_div(state->workp, trust_state->diag); norm_Dinvg = gsl_blas_dnrm2(state->workp); /* compute workp = D^{-2} g */ gsl_vector_div(state->workp, trust_state->diag); /* compute: workn = J D^{-2} g */ gsl_blas_dgemv(CblasNoTrans, 1.0, trust_state->J, state->workp, 0.0, state->workn); norm_JDinv2g = gsl_blas_dnrm2(state->workn); u = norm_Dinvg / norm_JDinv2g; alpha = u * u; /* dx_sd = -alpha D^{-2} g */ gsl_vector_memcpy(dx, state->workp); gsl_vector_scale(dx, -alpha); return GSL_SUCCESS; } static const gsl_multifit_nlinear_trs subspace2D_type = { "2D-subspace", subspace2D_alloc, subspace2D_init, subspace2D_preloop, subspace2D_step, subspace2D_preduction, subspace2D_free }; const gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_subspace2D = &subspace2D_type;
{ "alphanum_fraction": 0.6247681939, "avg_line_length": 31.0519662921, "ext": "c", "hexsha": "1c532783dc2d2dc998fa6d1987cfa5eccefb94f0", "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/multifit_nlinear/subspace2D.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/multifit_nlinear/subspace2D.c", "max_line_length": 101, "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/multifit_nlinear/subspace2D.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": 6483, "size": 22109 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * 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. * * * * Filename: evol.c * * Description: Evolution of the density matrix with a given generator * * Version: 1.0 * Created: 02/05/2014 14:40:25 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv2.h> #include "funcs.h" /* * FUNCTION * Name: generator * Description: Setting the dydt in Bloch form * */ int generator ( double t, const double y[], double dydt[], void* PARS ) { /* Extracting the matrix address from PARS */ gsl_matrix* M = (gsl_matrix*) PARS ; /* Generator */ unsigned int i , j ; for ( i = 0; i < 4 ; i++ ) dydt[i] = 0 ; for ( i = 1 ; i < 4 ; i++ ) for ( j = 0 ; j < 4 ; j++ ) dydt[i] = dydt[i] + gsl_matrix_get( M, i, j )*y[j] ; return GSL_SUCCESS; } /* ----- end of function generator ----- */ /* * FUNCTION * Name: jac * Description: Jacobian matrix of the generator (which is exactly the Bloch matrix) * */ int jac ( double t, const double y[], double dfdy[] , double dfdt[], void* PARS ) { /* Taking the generator Bloch's matrix address from PARS */ gsl_matrix* bloch = (gsl_matrix*) PARS ; /* Creating a matrix view of the array dfdy */ gsl_matrix_view m = gsl_matrix_view_array ( dfdy , 4, 4 ) ; /* Initializing the jacobian matrix with the Bloch generator */ unsigned int i, j ; for ( i = 0 ; i < 4 ; i++ ) for ( j = 0 ; j < 4 ; j++ ) gsl_matrix_set ( &m.matrix, i, j, gsl_matrix_get(bloch,i,j) ) ; for ( i = 0 ; i < 4 ; i++ ) dfdt[i] = 0 ; return GSL_SUCCESS; } /* ----- end of function jac ----- */ /* * FUNCTION * Name: evol * Description: * */ int evol ( double t, gsl_vector* state, double step, gsl_odeiv2_evolve* e, gsl_odeiv2_control* c, gsl_odeiv2_step* s, gsl_odeiv2_system* sys ) { /* Creating the array 'rho' for the vector 'state' */ double rho[4] ; unsigned int i ; for ( i = 0 ; i < 4 ; i++ ) rho[i] = VECTOR( state, i ) ; /* evolving the array 'rho' */ int status = gsl_odeiv2_evolve_apply_fixed_step ( e, c, s, sys, &t, step, rho ) ; if ( status != GSL_SUCCESS ) { printf("STATUS: %d\n", status) ; exit(1) ; } /* updating vector 'state' */ for ( i = 0 ; i < 4 ; i++ ) gsl_vector_set( state, i, rho[i] ) ; return status ; } /* ----- end of function evol ----- */
{ "alphanum_fraction": 0.6455664406, "avg_line_length": 29.0583941606, "ext": "c", "hexsha": "321e5bf219593affe4ee876b2ccc69f291a8629d", "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": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "evol.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "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": "j-silver/quantum_dots", "max_issues_repo_path": "evol.c", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "evol.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1144, "size": 3981 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_core_Token_h_ #define SQ_INCLUDE_GUARD_core_Token_h_ #include "Token.fwd.h" #include "core/typeutil.h" #include <gsl/gsl> #include <iosfwd> #include <regex> #include <string_view> #include <vector> namespace sq { enum class TokenKind : int { BoolFalse, BoolTrue, Colon, Comma, Dot, DQString, Eof, Equals, Float, GreaterThan, GreaterThanOrEqualTo, Identifier, Integer, LBrace, LBracket, LessThan, LessThanOrEqualTo, LParen, RBrace, RBracket, RParen }; class Token { public: /** * Create a Token object. * * @param query the full query string in which the token was found. * @param pos the character position within the query at which the token * was found. * @param len the length, in characters, of the token. * @param kind the kind of the token. */ Token(std::string_view query, gsl::index pos, gsl::index len, TokenKind kind) noexcept; /** * Get the full query string in which the token was found. */ SQ_ND std::string_view query() const noexcept; /** * Get the character position within the query at which the token was * found. */ SQ_ND gsl::index pos() const noexcept; /** * Get the length, in characters, of the token. */ SQ_ND gsl::index len() const noexcept; /** * Get a std::string_view pointing to the characters of the token. */ SQ_ND std::string_view view() const noexcept; /** * Get the kind of the token. */ SQ_ND TokenKind kind() const noexcept; private: std::string_view query_; gsl::index pos_; gsl::index len_; TokenKind kind_; }; std::ostream &operator<<(std::ostream &os, TokenKind kind); /** * Print information about a token. * * The text printed includes information about the position of the token in the * input query, not just the characters that make up the token. */ std::ostream &operator<<(std::ostream &os, const Token &token); } // namespace sq #endif // SQ_INCLUDE_GUARD_core_Token_h_
{ "alphanum_fraction": 0.6322609473, "avg_line_length": 21.3142857143, "ext": "h", "hexsha": "e0d7b2f7ebefe171ff493c13a1e07212d0056bc2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/core/include/core/Token.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/core/include/core/Token.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/core/include/core/Token.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 547, "size": 2238 }
// Copyright 2019 John McFarlane // // 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 WSS_BOARD_H #define WSS_BOARD_H #include "coord.h" #include "grid.h" #include "load_buffer.h" #include <ssize.h> #include <wss_assert.h> #include <fmt/printf.h> #include <gsl/string_span> #include <array> #include <optional> #include <unordered_map> template<typename T> class board { public: board(board&&) = default; explicit board(int init_edge) :edge{init_edge}, cells{std::make_unique<T[]>(edge*edge)} { } int size() const { return edge; } T const& cell(coord c) const { WSS_ASSERT(c[0]>=0); WSS_ASSERT(c[0]<edge); WSS_ASSERT(c[1]>=0); WSS_ASSERT(c[1]<edge); return cells.get()[c[0]+c[1]*edge]; } T& cell(coord c) { WSS_ASSERT(c[0]>=0); WSS_ASSERT(c[0]<edge); WSS_ASSERT(c[1]>=0); WSS_ASSERT(c[1]<edge); return cells.get()[c[0]+c[1]*edge]; } private: int edge; std::unique_ptr<T[]> cells; }; template<typename CellType, typename TextToCell> std::optional<board<CellType>> make_board( std::vector<std::vector<char>> const& lines, TextToCell const& mapping) { auto edge{ssize(lines)}; board<CellType> result{int(edge)}; for (auto row_index{0}; row_index!=edge; ++row_index) { auto const& line{lines[row_index]}; auto const num_fields{ssize(line)}; if (num_fields!=edge) { fmt::print(stderr, "error: input row #{} has {} fields, expected {}.\n", row_index+1, num_fields, edge); return std::nullopt; } for (auto column_index{0}; column_index!=edge; ++column_index) { auto const field{line[column_index]}; auto const cell_found{mapping(field)}; if (!cell_found) { fmt::print( stderr, "Unrecognised field, '{}', in row #{}, column #{}.\n", (char)field, row_index+1, column_index+1); return std::nullopt; } result.cell(coord{column_index,row_index}) = *cell_found; } } return result; } template<typename CellType, typename TextToCell> std::optional<board<CellType>> load_board( gsl::cstring_span<> filename, TextToCell const& mapping) { auto const buffer{load_buffer(filename)}; if (!buffer) { return std::nullopt; } auto const fields{parse_grid(*buffer)}; return make_board<CellType>(fields, mapping); } template<typename T> void transpose(board<T>& b) { auto const edge = ssize(b); for (auto row = 0; row != edge; ++row) { for (auto column = 0; column != row; ++ column) { std::swap(b.cell(coord{column, row}), b.cell(coord{row, column})); } } } #endif //WSS_BOARD_H
{ "alphanum_fraction": 0.5925498123, "avg_line_length": 25.4632352941, "ext": "h", "hexsha": "7afc8b4a451028fa9ff7fde956dd358ff051df7d", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-23T18:04:41.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-23T18:04:41.000Z", "max_forks_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "johnmcfarlane/wss", "max_forks_repo_path": "src/play/board.h", "max_issues_count": 21, "max_issues_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_issues_repo_issues_event_max_datetime": "2022-03-18T23:55:35.000Z", "max_issues_repo_issues_event_min_datetime": "2019-10-28T22:07:55.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "johnmcfarlane/wss", "max_issues_repo_path": "src/play/board.h", "max_line_length": 78, "max_stars_count": 4, "max_stars_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "johnmcfarlane/wss", "max_stars_repo_path": "src/play/board.h", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:23:02.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T09:40:23.000Z", "num_tokens": 856, "size": 3463 }
/* $Id$ */ /*--------------------------------------------------------------------*/ /*; Copyright (C) 2008-2016 */ /*; Associated Universities, Inc. Washington DC, USA. */ /*; */ /*; 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 Massachusetts Ave, Cambridge, */ /*; MA 02139, USA. */ /*; */ /*;Correspondence about this software should be addressed as follows: */ /*; Internet email: bcotton@nrao.edu. */ /*; Postal address: William Cotton */ /*; National Radio Astronomy Observatory */ /*; 520 Edgemont Road */ /*; Charlottesville, VA 22903-2475 USA */ /*--------------------------------------------------------------------*/ #ifndef OBITSPECTRUMFIT_H #define OBITSPECTRUMFIT_H #include "Obit.h" #include "ObitErr.h" #include "ObitImage.h" #include "ObitBeamShape.h" #include "ObitThread.h" #include "ObitInfoList.h" #ifdef HAVE_GSL #include <gsl/gsl_multifit_nlin.h> #endif /* HAVE_GSL */ /*-------- Obit: Merx mollis mortibus nuper ------------------*/ /** * \file ObitSpectrumFit.h * * ObitSpectrumFit Class for fitting spectra to image pixels * * This class does least squares fitting of log(s) as a polynomial in log($\nu$). * Either an image cube or a set of single plane images at arbitrary * frequencies may be fitted. * The result is an image cube of Log(S) with multiples of powers of log($\nu$) * as the planes. * The function ObitSpectrumFitEval will evaluate this fit and return an image * with the flux densities at the desired frequencies. * * \section ObitSpectrumFitaccess Creators and Destructors * An ObitSpectrumFit will usually be created using ObitSpectrumFitCreate which allows * specifying a name for the object as well as other information. * * A copy of a pointer to an ObitSpectrumFit should always be made using the * #ObitSpectrumFitRef function which updates the reference count in the object. * Then whenever freeing an ObitSpectrumFit or changing a pointer, the function * #ObitSpectrumFitUnref will decrement the reference count and destroy the object * when the reference count hits 0. * There is no explicit destructor. */ /*--------------Class definitions-------------------------------------*/ /** ObitSpectrumFit Class structure. */ typedef struct { #include "ObitSpectrumFitDef.h" /* this class definition */ } ObitSpectrumFit; /*----------------- Macroes ---------------------------*/ /** * Macro to unreference (and possibly destroy) an ObitSpectrumFit * returns a ObitSpectrumFit*. * in = object to unreference */ #define ObitSpectrumFitUnref(in) ObitUnref (in) /** * Macro to reference (update reference count) an ObitSpectrumFit. * returns a ObitSpectrumFit*. * in = object to reference */ #define ObitSpectrumFitRef(in) ObitRef (in) /** * Macro to determine if an object is the member of this or a * derived class. * Returns TRUE if a member, else FALSE * in = object to reference */ #define ObitSpectrumFitIsA(in) ObitIsA (in, ObitSpectrumFitGetClass()) /*---------------Public functions---------------------------*/ /** Public: Class initializer. */ void ObitSpectrumFitClassInit (void); /** Public: Default Constructor. */ ObitSpectrumFit* newObitSpectrumFit (gchar* name); /** Public: Create/initialize ObitSpectrumFit structures */ ObitSpectrumFit* ObitSpectrumFitCreate (gchar* name, olong nterm); /** Typedef for definition of class pointer structure */ typedef ObitSpectrumFit* (*ObitSpectrumFitCreateFP) (gchar* name, olong nterm); /** Public: ClassInfo pointer */ gconstpointer ObitSpectrumFitGetClass (void); /** Public: Copy (deep) constructor. */ ObitSpectrumFit* ObitSpectrumFitCopy (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err); /** Public: Copy structure. */ void ObitSpectrumFitClone (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err); /** Public: Fit spectrum to an image cube */ void ObitSpectrumFitCube (ObitSpectrumFit* in, ObitImage *inImage, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitCubeFP) (ObitSpectrumFit* in, ObitImage *inImage, ObitImage *outImage, ObitErr *err); /** Public: Fit spectrum to an array of images */ void ObitSpectrumFitImArr (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitImArrFP) (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, ObitImage *outImage, ObitErr *err); /* Do actual fitting */ void ObitSpectrumFitter (ObitSpectrumFit* in, ObitErr *err); typedef void(*ObitSpectrumFitterFP) (ObitSpectrumFit* in, ObitErr *err); /** Public: Evaluate spectrum */ void ObitSpectrumFitEval (ObitSpectrumFit* in, ObitImage *inImage, odouble outFreq, ObitImage *outImage, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef void(*ObitSpectrumFitEvalFP) (ObitSpectrumFit* in, ObitImage *inImage, odouble outFreq, ObitImage *outImage, ObitErr *err); /** Private: Write output image */ void ObitSpectrumWriteOutput (ObitSpectrumFit* in, ObitImage *outImage, ObitErr *err); typedef void (*ObitSpectrumWriteOutputFP) (ObitSpectrumFit* in, ObitImage *outImage, ObitErr *err); /** Public: Fit single spectrum */ ofloat* ObitSpectrumFitSingle (olong nfreq, olong nterm, odouble refFreq, odouble *freq, ofloat *flux, ofloat *sigma, gboolean doBrokePow, ObitErr *err); /** Typedef for definition of class pointer structure */ typedef ofloat*(*ObitSpectrumFitSingleFP) (olong nfreq, olong nterm, odouble refFreq, odouble *freq, ofloat *flux, ofloat *sigma, gboolean doBrokePow, ObitErr *err); /** Public: Make fitting arg structure */ gpointer ObitSpectrumFitMakeArg (olong nfreq, olong nterm, odouble refFreq, odouble *freq, gboolean doBrokePow, ofloat **out, ObitErr *err); /** Public: Fit single spectrum using arg */ void ObitSpectrumFitSingleArg (gpointer arg, ofloat *flux, ofloat *sigma, ofloat *out); /** Public: Kill fitting arg structure */ void ObitSpectrumFitKillArg (gpointer arg); /*----------- ClassInfo Structure -----------------------------------*/ /** * ClassInfo Structure. * Contains class name, a pointer to any parent class * (NULL if none) and function pointers. */ typedef struct { #include "ObitSpectrumFitClassDef.h" } ObitSpectrumFitClassInfo; #endif /* OBITFSPECTRUMFIT_H */
{ "alphanum_fraction": 0.6346104397, "avg_line_length": 42.7362637363, "ext": "h", "hexsha": "91f694e692075bd9161528156fb7f9bc766c4857", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z", "max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_forks_repo_licenses": [ "Linux-OpenIB" ], "max_forks_repo_name": "sarrvesh/Obit", "max_forks_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Linux-OpenIB" ], "max_issues_repo_name": "sarrvesh/Obit", "max_issues_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_line_length": 93, "max_stars_count": 5, "max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986", "max_stars_repo_licenses": [ "Linux-OpenIB" ], "max_stars_repo_name": "sarrvesh/Obit", "max_stars_repo_path": "ObitSystem/Obit/include/ObitSpectrumFit.h", "max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z", "num_tokens": 1926, "size": 7778 }
#include <stdio.h> #include <string.h> #include <gsl/gsl_statistics_double.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_image_lib.h" #include "tz_objdetect.h" #include "tz_imatrix.h" #include "tz_stack_math.h" #include "tz_stack_bwdist.h" #include "tz_pixel_array.h" #include "tz_stack_bwmorph.h" #include "tz_stack_draw.h" #include "tz_dmatrix.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } char file_path[100]; sprintf(file_path, "../data/%s/objseed.tif", neuron_name); Stack *seedimg = Read_Stack(file_path); Object_3d_List *objs = Stack_Find_Object_N(seedimg, NULL, 1, 0, 26); Stack *stack2 = NULL; Object_3d *obj = NULL; stack2 = NULL; Object_3d_List *objs2 = NULL; sprintf(file_path, "../data/%s/bundle.tif", neuron_name); stack2 = Read_Stack(file_path); while (objs != NULL) { obj = Stack_Grow_Object(stack2, 1, objs->data->voxels[0]); if (obj != NULL) { if (obj->size > 1000) { if (objs2 == NULL) { objs2 = Object_3d_List_New(); objs2->data = obj; } else { Object_3d_List_Add(&objs2, obj); Print_Object_3d_Info(obj); } } else { Kill_Object_3d(obj); } } objs = objs->next; } Print_Object_3d_List_Compact(objs2); Stack *bundle = Make_Stack(GREY, stack2->width, stack2->height, stack2->depth); Zero_Stack(bundle); Stack_Draw_Objects_Bw(bundle, objs2, 1); sprintf(file_path, "../data/%s/grow_bundle.tif", neuron_name); Write_Stack(file_path, bundle); return 0; }
{ "alphanum_fraction": 0.6729828851, "avg_line_length": 22.7222222222, "ext": "c", "hexsha": "175c00228f3f9d55fde2f722ef9eb368423f1d5d", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_grow_bundle.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_grow_bundle.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_grow_bundle.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 509, "size": 1636 }
// // geru.h // Linear Algebra Template Library // // Created by Rodney James on 12/23/11. // Copyright (c) 2011 University of Colorado Denver. All rights reserved. // #ifndef _geru_h #define _geru_h /// @file geru.h Performs complex vector outer product. #include "latl.h" namespace LATL { /// @brief Performs a vector outer product of two complex vectors. /// /// For a complex matrix A, complex vectors x and y, and complex scalar alpha, /// /// A := alpha * x * y.' + A /// /// is computed. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param m Specifies the number of rows of the matrix A. m>=0 /// @param n Specifies the number of coumns of the matrix A. n>=0 /// @param alpha Complex scalar. /// @param x Pointer to complex vector x. /// @param incx Increment of the vector x. x!=0 /// @param y Pointer to complex vector y. /// @param incy Increment of the vector y. y!=0 /// @param A Pointer to complex m-by-n matrix A. /// @param ldA Column length of matrix A. ldA>=m. /// @ingroup BLAS template <typename real_t> int GERU(int_t m, int_t n, complex<real_t> alpha, complex<real_t> *x, int_t incx, complex<real_t> *y, int_t incy, complex<real_t> *A, int_t ldA) { using std::conj; const complex<real_t> zero(0.0,0.0); int_t i,j,kx,jy,ix; if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; else if((m==0)||(n==0)||(alpha==zero)) return 0; jy=(incy>0)?0:(1-n)*incy; kx=(incx>0)?0:(1-m)*incx; if(incx==1) { for(j=0;j<n;j++) { for(i=0;i<m;i++) A[i]+=x[i]*alpha*y[jy]; jy+=incy; A+=ldA; } } else { for(j=0;j<n;j++) { ix=kx; for(i=0;i<m;i++) { A[i]+=x[ix]*alpha*y[jy]; ix+=incx; } A+=ldA; jy+=incy; } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int GERU<float>(int_t m, int_t n, complex<float> alpha, complex<float> *x, int_t incx, complex<float> *y, int_t incy, complex<float> *A, int_t ldA) { if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; cblas_cgeru(CblasColMajor,m,n,&alpha,x,incx,y,incy,A,ldA); return 0; } template <> int GERU<double>(int_t m, int_t n, complex<double> alpha, complex<double> *x, int_t incx, complex<double> *y, int_t incy, complex<double> *A, int_t ldA) { if(m<0) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(incy==0) return -7; else if(ldA<m) return -9; cblas_cgeru(CblasColMajor,m,n,&alpha,x,incx,y,incy,A,ldA); return 0; } #endif } #endif
{ "alphanum_fraction": 0.520620155, "avg_line_length": 24.4318181818, "ext": "h", "hexsha": "8b11778e340b991ef2620e5869b1947357e5e9d4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/geru.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/geru.h", "max_line_length": 167, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/geru.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 994, "size": 3225 }
#pragma once #include "GradUtil.h" #ifndef _NOGSL #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #else #include "CustomSolver.h" #endif #include <limits> #include <math.h> #include <vector> #include "BasicError.h" #include "Util.h" using namespace std; class ValueGrad; class DistanceGrad { public: double dist; gsl_vector* grad; bool set; // TODO: this bit is not necessary if the default dist is 0 DistanceGrad(double d, gsl_vector* g): dist(d), grad(g), set(true) {} ~DistanceGrad(void) { gsl_vector_free(grad); } string print() { stringstream str; if (set) { str << "Dist: " << dist; } else { str << "Dist: NOT SET"; } return str.str(); } string printFull() { stringstream str; if (set) { str << "Dist: " << dist << endl; str << "DGrads: "; for (int i = 0; i < grad->size; i++) { str << gsl_vector_get(grad, i) << ", "; } if (dist > 1e5 || gsl_blas_dnrm2(grad) > 1e5) { str << "LARGE VALUES" << endl; } } else { str << "Dist: NOT SET"; } return str.str(); } static void dg_and(DistanceGrad* m, DistanceGrad* f, DistanceGrad* d); static void dg_or(DistanceGrad* m, DistanceGrad* f, DistanceGrad* d); static void dg_not(DistanceGrad* m, DistanceGrad* d); static void dg_ite(DistanceGrad* b, DistanceGrad* m, DistanceGrad* f, DistanceGrad* d); static double dg_copy(DistanceGrad* m, gsl_vector* grad); static void dg_copy(DistanceGrad* m, DistanceGrad* o); static double dg_times(DistanceGrad* m, DistanceGrad* f, gsl_vector* grad); static void dg_ite(DistanceGrad* m, DistanceGrad* f, double dval, gsl_vector* dgrad, DistanceGrad* o); static bool same(DistanceGrad* m, DistanceGrad* f); static double dg_combine(DistanceGrad* m, DistanceGrad* f); static void dg_combine(DistanceGrad* m, DistanceGrad* f, DistanceGrad* o); static double dg_combine(DistanceGrad* m, DistanceGrad* f, double cval, gsl_vector* grad, int bv, gsl_vector* o); static double dg_combine(DistanceGrad* m, DistanceGrad* f, double cval, int bv); static void dg_combine(vector<DistanceGrad*>& cdists, DistanceGrad* vdist, vector<ValueGrad*>& cvals, int bv, DistanceGrad* o); };
{ "alphanum_fraction": 0.6702947846, "avg_line_length": 28.6363636364, "ext": "h", "hexsha": "2131e4d93b1087ca6b144e75f0a899393bf1fc1f", "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/DataStructures/DistanceGrad.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/DataStructures/DistanceGrad.h", "max_line_length": 131, "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/DataStructures/DistanceGrad.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": 636, "size": 2205 }
/* * Author : Pierre Schnizer * Date : February 2005 * */ #include <pygsl/error_helpers.h> #include <pygsl/block_helpers.h> #include <pygsl/pygsl_features.h> #include <string.h> #include <gsl/gsl_fft.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_complex_float.h> #include <gsl/gsl_fft_real_float.h> #include <gsl/gsl_fft_halfcomplex_float.h> #include <gsl/gsl_blas.h> #ifdef _PYGSL_GSL_HAS_WAVELET #define forward forward_wavelet #define backward backward_wavelet #include <gsl/gsl_wavelet.h> #include <gsl/gsl_wavelet2d.h> #undef forward #undef backward #else /* #error Need GSL version 1.6 or higher with wavelet implementation! If you need it for a lower version #error add the different conditional compilation! */ #endif /* gsl version > 1.5*/ static PyObject *module = NULL; static const char filename[] = __FILE__; /* The types */ #include "transformtypes.h" /* The documentation strings */ #include "doc.h" /* The python type which allows to allocate and pass the work space */ #include "space.c" /* Function to copy the different arrays. */ #include "arraycopy.c" /* * Macros and functions which set the information up and call the * PyGSL_transform functions */ #include "fft.c" /* * The wavelet type and the methods to call the different transform functions. */ #ifdef _PYGSL_GSL_HAS_WAVELET #include "wavelet.c" #define PyGSL_WAVELET_TRANSFORM_TYPE(name) \ {#name, PyGSL_wavelet_init_ ## name, METH_VARARGS, NULL}, \ {#name "_centered", PyGSL_wavelet_init_ ## name ## _centered, METH_VARARGS, NULL}, #else #define PyGSL_WAVELET_TRANSFORM_TYPE(name) #endif /* * The real workers. */ #include "core.c" static PyMethodDef transformMethods[] = { /* workspace init functions */ {"complex_workspace", PyGSL_transform_space_init_COMPLEX_WORKSPACE, METH_VARARGS, (char*)cws_doc}, {"complex_wavetable", PyGSL_transform_space_init_COMPLEX_WAVETABLE, METH_VARARGS, (char*)cwt_doc}, {"real_workspace", PyGSL_transform_space_init_REAL_WORKSPACE, METH_VARARGS, (char*)rws_doc}, {"real_wavetable", PyGSL_transform_space_init_REAL_WAVETABLE, METH_VARARGS, (char*)rwt_doc}, {"halfcomplex_wavetable", PyGSL_transform_space_init_HALFCOMPLEX_WAVETABLE, METH_VARARGS, (char*)hcwt_doc}, {"complex_workspace_float", PyGSL_transform_space_init_COMPLEX_WORKSPACE_FLOAT, METH_VARARGS, (char*)cws_doc}, {"complex_wavetable_float", PyGSL_transform_space_init_COMPLEX_WAVETABLE_FLOAT, METH_VARARGS, (char*)cwt_doc}, {"real_workspace_float", PyGSL_transform_space_init_REAL_WORKSPACE_FLOAT, METH_VARARGS, (char*)rws_doc}, {"real_wavetable_float", PyGSL_transform_space_init_REAL_WAVETABLE_FLOAT, METH_VARARGS, (char*)rwt_doc}, {"halfcomplex_wavetable_float", PyGSL_transform_space_init_HALFCOMPLEX_WAVETABLE_FLOAT, METH_VARARGS, (char*)hcwt_doc}, #ifdef _PYGSL_GSL_HAS_WAVELET {"wavelet_workspace", PyGSL_transform_space_init_WAVELET_WORKSPACE, METH_VARARGS, (char*)ww_doc}, #endif /* transform functions */ PyGSL_TRANSFORM_FD_FUNCTION("complex_forward", fft_complex_forward, cf_doc) PyGSL_TRANSFORM_FD_FUNCTION("complex_backward", fft_complex_backward, cb_doc) PyGSL_TRANSFORM_FD_FUNCTION("complex_inverse", fft_complex_inverse, ci_doc) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_forward", fft_complex_radix2_forward, cf_doc_r2) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_backward", fft_complex_radix2_backward, cb_doc_r2) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_inverse", fft_complex_radix2_inverse, ci_doc_r2) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_dif_forward", fft_complex_radix2_dif_forward, cf_doc_r2_dif) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_dif_backward", fft_complex_radix2_dif_backward, cb_doc_r2_dif) PyGSL_TRANSFORM_FD_FUNCTION("complex_radix2_dif_inverse", fft_complex_radix2_dif_inverse, ci_doc_r2_dif) PyGSL_TRANSFORM_FD_FUNCTION("real_transform", fft_real_transform, rt_doc) PyGSL_TRANSFORM_FD_FUNCTION("halfcomplex_transform", fft_halfcomplex_transform, hc_doc) PyGSL_TRANSFORM_FD_FUNCTION("halfcomplex_inverse", fft_halfcomplex_inverse, hi_doc) PyGSL_TRANSFORM_FD_FUNCTION("real_radix2_transform", fft_real_radix2_transform, rt_doc_r2) PyGSL_TRANSFORM_FD_FUNCTION("halfcomplex_radix2_transform",fft_halfcomplex_radix2_transform, hc_doc_r2) PyGSL_TRANSFORM_FD_FUNCTION("halfcomplex_radix2_inverse", fft_halfcomplex_radix2_inverse, hi_doc_r2) /* helper functions */ {"halfcomplex_radix2_unpack", PyGSL_fft_halfcomplex_radix2_unpack, METH_VARARGS, (char*)un_doc_r2}, {"halfcomplex_radix2_unpack_float", PyGSL_fft_halfcomplex_radix2_unpack_float, METH_VARARGS, (char*)float_doc}, /* wavelet inits */ #ifdef _PYGSL_GSL_HAS_WAVELET PyGSL_WAVELET_TRANSFORM_TYPE(daubechies) PyGSL_WAVELET_TRANSFORM_TYPE(haar) PyGSL_WAVELET_TRANSFORM_TYPE(bspline) #endif {NULL, NULL, 0, NULL} /* Sentinel */ }; /* * Set the various function pointers for the different transforms. See the * structure _pygsl_transform_func_s for the functions. Some architectures do * not allow to initalise function pointers in static structures on the heap. * (some solaris versions? ) */ #define PYGSL_INIT_FUNCS(helpers, space, table, spacet, tablet) \ helpers.space_alloc = (pygsl_transform_helpn_t *) gsl_fft_ ## space ## _alloc; \ helpers.space_free = (pygsl_transform_help_t *) gsl_fft_ ## space ## _free; \ helpers.table_alloc = (pygsl_transform_helpn_t *) gsl_fft_ ## table ## _alloc; \ helpers.table_free = (pygsl_transform_help_t *) gsl_fft_ ## table ## _free; \ helpers.space_type = spacet; \ helpers.table_type = tablet; \ #define PYGSL_INIT_FUNCS_DF(helpers, space, table, spacet, tablet) \ PYGSL_INIT_FUNCS(helpers ## _funcs, space, table, spacet, tablet) \ PYGSL_INIT_FUNCS(helpers ## _float ## _funcs, space ## _float, table ## _float, spacet ## _FLOAT, tablet ## _FLOAT) static void init_helpers(void) { FUNC_MESS_BEGIN(); PYGSL_INIT_FUNCS_DF(complex, complex_workspace, complex_wavetable, COMPLEX_WORKSPACE, COMPLEX_WAVETABLE) PYGSL_INIT_FUNCS_DF(real, real_workspace, real_wavetable, REAL_WORKSPACE, REAL_WAVETABLE) PYGSL_INIT_FUNCS_DF(halfcomplex, real_workspace, halfcomplex_wavetable, REAL_WORKSPACE, HALFCOMPLEX_WAVETABLE) DEBUG_MESS(3, "PyArray_FLOAT = %d ", PyArray_FLOAT ); DEBUG_MESS(3, "PyArray_DOUBLE = %d ", PyArray_DOUBLE ); DEBUG_MESS(3, "PyArray_CFLOAT = %d ", PyArray_CFLOAT ); DEBUG_MESS(3, "PyArray_CDOUBLE = %d ", PyArray_CDOUBLE); #ifdef _PYGSL_GSL_HAS_WAVELET DEBUG_MESS(4, "%s @ %p", "daubechies", gsl_wavelet_daubechies); DEBUG_MESS(4, "%s @ %p", "daubechies_centered", gsl_wavelet_daubechies_centered); DEBUG_MESS(4, "%s @ %p", "haar", gsl_wavelet_haar); DEBUG_MESS(4, "%s @ %p", "haar_centered", gsl_wavelet_haar_centered); DEBUG_MESS(4, "%s @ %p", "bspline", gsl_wavelet_bspline); DEBUG_MESS(4, "%s @ %p", "bspline_centered", gsl_wavelet_bspline_centered); #endif FUNC_MESS_END(); } DL_EXPORT(void) init_transform(void) { PyObject *m = NULL, *dict = NULL, *item = NULL; FUNC_MESS_BEGIN(); PyGSL_transform_space_pytype.ob_type = &PyType_Type; #ifdef _PYGSL_GSL_HAS_WAVELET PyGSL_wavelet_pytype.ob_type = &PyType_Type; #endif m = Py_InitModule("_transform", transformMethods); module = m; init_pygsl(); init_helpers(); if (m == NULL) return; dict = PyModule_GetDict(m); if (dict == NULL) return; if (!(item = PyString_FromString(transform_module_doc))){ PyErr_SetString(PyExc_ImportError, "I could not generate module doc string!"); return; } if (PyDict_SetItemString(dict, "__doc__", item) != 0){ PyErr_SetString(PyExc_ImportError, "I could not init doc string!"); return; } FUNC_MESS_END(); return; } /* * Local Variables: * mode: C * c-file-style: "python" * End: */
{ "alphanum_fraction": 0.7407091507, "avg_line_length": 42.7447916667, "ext": "c", "hexsha": "f7c3d46986640364443976b97e4df691d626081a", "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/transform/transformmodule.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/transform/transformmodule.c", "max_line_length": 122, "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/transform/transformmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2259, "size": 8207 }
// // Created by Harold on 2020/9/30. // #ifndef M_MATH_M_INTEGRATION_H #define M_MATH_M_INTEGRATION_H #include <gsl/gsl_integration.h> namespace M_MATH { class IntegrationQAG { public: typedef double (*func_type)(double x, void* params); public: IntegrationQAG() : IntegrationQAG(1000, 1e-6) { } IntegrationQAG(size_t workspace_sz, double accuracy) : workspace_size(workspace_sz), accuracy_bound(accuracy), F() { workspace = gsl_integration_workspace_alloc(workspace_size); } ~IntegrationQAG() { gsl_integration_workspace_free(workspace); } void bind_func(func_type f, void* params) { F.function = f; F.params = params; } void integrate(double x0, double x1, double* result, double* error) { // default use key = 1: GSL_INTEG_GAUSS15 gsl_integration_qag(&F, x0, x1, 0, accuracy_bound, workspace_size, 1, workspace, result, error); } private: gsl_function F; size_t workspace_size; double accuracy_bound; gsl_integration_workspace* workspace; }; // change lambda function to function ptr struct Lambda { template<typename Tret, typename T> static Tret lambda_ptr_exec(double x, void* data) { return (Tret) (*(T*)fn<T>())(x, data); } template<typename Tret = void, typename Tfp = Tret(*)(double, void*), typename T> static Tfp ptr(T& t) { fn<T>(&t); return (Tfp) lambda_ptr_exec<Tret, T>; } template<typename T> static void* fn(void* new_fn = nullptr) { static void* fn; if (new_fn != nullptr) fn = new_fn; return fn; } }; } #endif //M_MATH_M_INTEGRATION_H
{ "alphanum_fraction": 0.5857988166, "avg_line_length": 28.1666666667, "ext": "h", "hexsha": "05269e9471055826a910ca5e91d7db7511658fc9", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_path": "include/m_integration.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_path": "include/m_integration.h", "max_line_length": 108, "max_stars_count": 2, "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_path": "include/m_integration.h", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "num_tokens": 443, "size": 1859 }
/* multirobust.c * * Copyright (C) 2013 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. * * This module contains routines related to robust linear least squares. The * algorithm used closely follows the publications: * * [1] DuMouchel, W. and F. O'Brien (1989), "Integrating a robust * option into a multiple regression computing environment," * Computer Science and Statistics: Proceedings of the 21st * Symposium on the Interface, American Statistical Association * * [2] Street, J.O., R.J. Carroll, and D. Ruppert (1988), "A note on * computing robust regression estimates via iteratively * reweighted least squares," The American Statistician, v. 42, * pp. 152-154. */ //#include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "linear_common.c" static int robust_test_convergence(const gsl_vector *c_prev, const gsl_vector *c, const double tol); static double robust_madsigma(const gsl_vector *x, gsl_multifit_robust_workspace *w); static double robust_robsigma(const gsl_vector *r, const double s, const double tune, gsl_multifit_robust_workspace *w); static double robust_sigma(const double s_ols, const double s_rob, gsl_multifit_robust_workspace *w); static int robust_covariance(const double sigma, gsl_matrix *cov, gsl_multifit_robust_workspace *w); /* gsl_multifit_robust_alloc Allocate a robust workspace Inputs: T - robust weighting algorithm n - number of observations p - number of model parameters Return: pointer to workspace */ gsl_multifit_robust_workspace * gsl_multifit_robust_alloc(const gsl_multifit_robust_type *T, const size_t n, const size_t p) { gsl_multifit_robust_workspace *w; if (n < p) { GSL_ERROR_VAL("observations n must be >= p", GSL_EINVAL, 0); } w = calloc(1, sizeof(gsl_multifit_robust_workspace)); if (w == 0) { GSL_ERROR_VAL("failed to allocate space for multifit_robust struct", GSL_ENOMEM, 0); } w->n = n; w->p = p; w->type = T; /* bdavis */ //w->maxiter = 100; /* maximum iterations */ w->maxiter = 5; /* maximum iterations */ /* bdavis */ w->tune = w->type->tuning_default; w->multifit_p = gsl_multifit_linear_alloc(n, p); if (w->multifit_p == 0) { GSL_ERROR_VAL("failed to allocate space for multifit_linear struct", GSL_ENOMEM, 0); } w->r = gsl_vector_alloc(n); if (w->r == 0) { GSL_ERROR_VAL("failed to allocate space for residuals", GSL_ENOMEM, 0); } w->weights = gsl_vector_alloc(n); if (w->weights == 0) { GSL_ERROR_VAL("failed to allocate space for weights", GSL_ENOMEM, 0); } w->c_prev = gsl_vector_alloc(p); if (w->c_prev == 0) { GSL_ERROR_VAL("failed to allocate space for c_prev", GSL_ENOMEM, 0); } w->resfac = gsl_vector_alloc(n); if (w->resfac == 0) { GSL_ERROR_VAL("failed to allocate space for residual factors", GSL_ENOMEM, 0); } w->psi = gsl_vector_alloc(n); if (w->psi == 0) { GSL_ERROR_VAL("failed to allocate space for psi", GSL_ENOMEM, 0); } w->dpsi = gsl_vector_alloc(n); if (w->dpsi == 0) { GSL_ERROR_VAL("failed to allocate space for dpsi", GSL_ENOMEM, 0); } w->QSI = gsl_matrix_alloc(p, p); if (w->QSI == 0) { GSL_ERROR_VAL("failed to allocate space for QSI", GSL_ENOMEM, 0); } w->D = gsl_vector_alloc(p); if (w->D == 0) { GSL_ERROR_VAL("failed to allocate space for D", GSL_ENOMEM, 0); } w->workn = gsl_vector_alloc(n); if (w->workn == 0) { GSL_ERROR_VAL("failed to allocate space for workn", GSL_ENOMEM, 0); } w->stats.sigma_ols = 0.0; w->stats.sigma_mad = 0.0; w->stats.sigma_rob = 0.0; w->stats.sigma = 0.0; w->stats.Rsq = 0.0; w->stats.adj_Rsq = 0.0; w->stats.rmse = 0.0; w->stats.sse = 0.0; w->stats.dof = n - p; w->stats.weights = w->weights; w->stats.r = w->r; return w; } /* gsl_multifit_robust_alloc() */ /* gsl_multifit_robust_free() Free memory associated with robust workspace */ void gsl_multifit_robust_free(gsl_multifit_robust_workspace *w) { if (w->multifit_p) gsl_multifit_linear_free(w->multifit_p); if (w->r) gsl_vector_free(w->r); if (w->weights) gsl_vector_free(w->weights); if (w->c_prev) gsl_vector_free(w->c_prev); if (w->resfac) gsl_vector_free(w->resfac); if (w->psi) gsl_vector_free(w->psi); if (w->dpsi) gsl_vector_free(w->dpsi); if (w->QSI) gsl_matrix_free(w->QSI); if (w->D) gsl_vector_free(w->D); if (w->workn) gsl_vector_free(w->workn); free(w); } /* gsl_multifit_robust_free() */ int gsl_multifit_robust_tune(const double tune, gsl_multifit_robust_workspace *w) { w->tune = tune; return GSL_SUCCESS; } const char * gsl_multifit_robust_name(const gsl_multifit_robust_workspace *w) { return w->type->name; } gsl_multifit_robust_stats gsl_multifit_robust_statistics(const gsl_multifit_robust_workspace *w) { return w->stats; } /* gsl_multifit_robust() Perform robust iteratively reweighted linear least squares fit Inputs: X - design matrix of basis functions y - right hand side vector c - (output) model coefficients cov - (output) covariance matrix w - workspace */ int gsl_multifit_robust(const gsl_matrix * X, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, gsl_multifit_robust_workspace *w) { /* check matrix and vector sizes */ if (X->size1 != y->size) { GSL_ERROR ("number of observations in y does not match rows of matrix X", GSL_EBADLEN); } else if (X->size2 != c->size) { GSL_ERROR ("number of parameters c does not match columns of matrix X", GSL_EBADLEN); } else if (cov->size1 != cov->size2) { GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR); } else if (c->size != cov->size1) { GSL_ERROR ("number of parameters does not match size of covariance matrix", GSL_EBADLEN); } else if (X->size1 != w->n || X->size2 != w->p) { GSL_ERROR ("size of workspace does not match size of observation matrix", GSL_EBADLEN); } else { int s; double chisq; const double tol = GSL_SQRT_DBL_EPSILON; int converged = 0; size_t numit = 0; const size_t n = y->size; double sigy = gsl_stats_sd(y->data, y->stride, n); double sig_lower; size_t i; /* * if the initial fit is very good, then finding outliers by comparing * them to the residual standard deviation is difficult. Therefore we * set a lower bound on the standard deviation estimate that is a small * fraction of the standard deviation of the data values */ sig_lower = 1.0e-6 * sigy; if (sig_lower == 0.0) sig_lower = 1.0; /* compute initial estimates using ordinary least squares */ s = gsl_multifit_linear(X, y, c, cov, &chisq, w->multifit_p); if (s) return s; /* save Q S^{-1} of original matrix */ gsl_matrix_memcpy(w->QSI, w->multifit_p->QSI); gsl_vector_memcpy(w->D, w->multifit_p->D); /* compute statistical leverage of each data point */ s = gsl_linalg_SV_leverage(w->multifit_p->A, w->resfac); if (s) return s; /* correct residuals with factor 1 / sqrt(1 - h) */ for (i = 0; i < n; ++i) { double h = gsl_vector_get(w->resfac, i); if (h > 0.9999) h = 0.9999; gsl_vector_set(w->resfac, i, 1.0 / sqrt(1.0 - h)); } /* compute residuals from OLS fit r = y - X c */ s = gsl_multifit_linear_residuals(X, y, c, w->r); if (s) return s; /* compute estimate of sigma from ordinary least squares */ w->stats.sigma_ols = gsl_blas_dnrm2(w->r) / sqrt((double) w->stats.dof); while (!converged && ++numit <= w->maxiter) { double sig; /* adjust residuals by statistical leverage (see DuMouchel and O'Brien) */ s = gsl_vector_mul(w->r, w->resfac); if (s) return s; /* compute estimate of standard deviation using MAD */ sig = robust_madsigma(w->r, w); /* scale residuals by standard deviation and tuning parameter */ gsl_vector_scale(w->r, 1.0 / (GSL_MAX(sig, sig_lower) * w->tune)); /* compute weights using these residuals */ s = w->type->wfun(w->r, w->weights); if (s) return s; gsl_vector_memcpy(w->c_prev, c); /* solve weighted least squares with new weights */ s = gsl_multifit_wlinear(X, w->weights, y, c, cov, &chisq, w->multifit_p); if (s) return s; /* compute new residuals r = y - X c */ s = gsl_multifit_linear_residuals(X, y, c, w->r); if (s) return s; converged = robust_test_convergence(w->c_prev, c, tol); } /* compute final MAD sigma */ w->stats.sigma_mad = robust_madsigma(w->r, w); /* compute robust estimate of sigma */ w->stats.sigma_rob = robust_robsigma(w->r, w->stats.sigma_mad, w->tune, w); /* compute final estimate of sigma */ w->stats.sigma = robust_sigma(w->stats.sigma_ols, w->stats.sigma_rob, w); /* store number of iterations */ w->stats.numit = numit; { double dof = (double) w->stats.dof; double rnorm = w->stats.sigma * sqrt(dof); /* see DuMouchel, sec 4.2 */ double ss_err = rnorm * rnorm; double ss_tot = gsl_stats_tss(y->data, y->stride, n); /* compute R^2 */ w->stats.Rsq = 1.0 - ss_err / ss_tot; /* compute adjusted R^2 */ w->stats.adj_Rsq = 1.0 - (1.0 - w->stats.Rsq) * (n - 1.0) / dof; /* compute rmse */ w->stats.rmse = sqrt(ss_err / dof); /* store SSE */ w->stats.sse = ss_err; } /* calculate covariance matrix = sigma^2 (X^T X)^{-1} */ s = robust_covariance(w->stats.sigma, cov, w); if (s) return s; /* raise an error if not converged */ /* bdavis */ /* Eliminating this check is to avoid an error when iterations */ /* exceed 5. A better solution is probably recommended, such as */ /* reverting to default of 100 if an input specification is not */ /* enabled and defined. */ /* bdavis@usgs.gov */ /* if (numit > w->maxiter) { GSL_ERROR("maximum iterations exceeded", GSL_EMAXITER); } */ /* bdavis */ return s; } } /* gsl_multifit_robust() */ /* Estimation of values for given x */ int gsl_multifit_robust_est(const gsl_vector * x, const gsl_vector * c, const gsl_matrix * cov, double *y, double *y_err) { int s = gsl_multifit_linear_est(x, c, cov, y, y_err); return s; } /*********************************** * INTERNAL ROUTINES * ***********************************/ /* robust_test_convergence() Test for convergence in robust least squares Convergence criteria: |c_i^(k) - c_i^(k-1)| <= tol * max(|c_i^(k)|, |c_i^(k-1)|) for all i. k refers to iteration number. Inputs: c_prev - coefficients from previous iteration c - coefficients from current iteration tol - tolerance Return: 1 if converged, 0 if not */ static int robust_test_convergence(const gsl_vector *c_prev, const gsl_vector *c, const double tol) { size_t p = c->size; size_t i; for (i = 0; i < p; ++i) { double ai = gsl_vector_get(c_prev, i); double bi = gsl_vector_get(c, i); if (fabs(bi - ai) > tol * GSL_MAX(fabs(ai), fabs(bi))) return 0; /* not yet converged */ } /* converged */ return 1; } /* robust_test_convergence() */ /* robust_madsigma() Estimate the standard deviation of the residuals using the Median-Absolute-Deviation (MAD) of the residuals, throwing away the smallest p residuals. See: Street et al, 1988 Inputs: r - vector of residuals w - workspace */ static double robust_madsigma(const gsl_vector *r, gsl_multifit_robust_workspace *w) { gsl_vector_view v; double sigma; size_t n = r->size; const size_t p = w->p; size_t i; /* copy |r| into workn */ for (i = 0; i < n; ++i) { gsl_vector_set(w->workn, i, fabs(gsl_vector_get(r, i))); } gsl_sort_vector(w->workn); /* * ignore the smallest p residuals when computing the median * (see Street et al 1988) */ v = gsl_vector_subvector(w->workn, p - 1, n - p + 1); sigma = gsl_stats_median_from_sorted_data(v.vector.data, v.vector.stride, v.vector.size) / 0.6745; return sigma; } /* robust_madsigma() */ /* robust_robsigma() Compute robust estimate of sigma so that sigma^2 * inv(X' * X) is a reasonable estimate of the covariance for robust regression. Based heavily on the equations of Street et al, 1988. Inputs: r - vector of residuals y - X c s - sigma estimate using MAD tune - tuning constant w - workspace */ static double robust_robsigma(const gsl_vector *r, const double s, const double tune, gsl_multifit_robust_workspace *w) { double sigma; size_t i; const size_t n = w->n; const size_t p = w->p; const double st = s * tune; double a, b, lambda; /* compute u = r / sqrt(1 - h) / st */ gsl_vector_memcpy(w->workn, r); gsl_vector_mul(w->workn, w->resfac); gsl_vector_scale(w->workn, 1.0 / st); /* compute w(u) and psi'(u) */ w->type->wfun(w->workn, w->psi); w->type->psi_deriv(w->workn, w->dpsi); /* compute psi(u) = u*w(u) */ gsl_vector_mul(w->psi, w->workn); /* Street et al, Eq (3) */ a = gsl_stats_mean(w->dpsi->data, w->dpsi->stride, n); /* Street et al, Eq (5) */ b = 0.0; for (i = 0; i < n; ++i) { double psi_i = gsl_vector_get(w->psi, i); double resfac = gsl_vector_get(w->resfac, i); double fac = 1.0 / (resfac*resfac); /* 1 - h */ b += fac * psi_i * psi_i; } b /= (double) (n - p); /* Street et al, Eq (5) */ lambda = 1.0 + ((double)p)/((double)n) * (1.0 - a) / a; sigma = lambda * sqrt(b) * st / a; return sigma; } /* robust_robsigma() */ /* robust_sigma() Compute final estimate of residual standard deviation, using the OLS and robust sigma estimates. This equation is taken from DuMouchel and O'Brien, sec 4.1: \hat{\sigma_R} Inputs: s_ols - OLS sigma s_rob - robust sigma w - workspace Return: final estimate of sigma */ static double robust_sigma(const double s_ols, const double s_rob, gsl_multifit_robust_workspace *w) { double sigma; const size_t p = w->p; const size_t n = w->n; /* see DuMouchel and O'Brien, sec 4.1 */ sigma = GSL_MAX(s_rob, sqrt((s_ols*s_ols*p*p + s_rob*s_rob*n) / (p*p + n))); return sigma; } /* robust_sigma() */ /* robust_covariance() Calculate final covariance matrix, defined as: sigma * (X^T X)^{-1} Inputs: sigma - residual standard deviation cov - (output) covariance matrix w - workspace */ static int robust_covariance(const double sigma, gsl_matrix *cov, gsl_multifit_robust_workspace *w) { int s = 0; const size_t p = w->p; const double s2 = sigma * sigma; size_t i, j; gsl_matrix *QSI = w->QSI; gsl_vector *D = w->D; /* Form variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */ for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (QSI, i); double d_i = gsl_vector_get (D, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (QSI, j); double d_j = gsl_vector_get (D, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s * s2 / (d_i * d_j)); gsl_matrix_set (cov, j, i, s * s2 / (d_i * d_j)); } } return s; } /* robust_covariance() */
{ "alphanum_fraction": 0.6053502002, "avg_line_length": 26.5941358025, "ext": "c", "hexsha": "594feb5c068ebe2c34bb0ef4adbe20c3128695f4", "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/multirobust.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/multirobust.c", "max_line_length": 100, "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/multirobust.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": 4978, "size": 17233 }
/* linalg/choleskyc.c * * Copyright (C) 2007 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_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> /* * This module contains routines related to the Cholesky decomposition * of a complex Hermitian positive definite matrix. */ static void cholesky_complex_conj_vector(gsl_vector_complex *v); /* gsl_linalg_complex_cholesky_decomp() Perform the Cholesky decomposition on a Hermitian positive definite matrix. See Golub & Van Loan, "Matrix Computations" (3rd ed), algorithm 4.2.2. Inputs: A - (input/output) complex postive definite matrix Return: success or error The lower triangle of A is overwritten with the Cholesky decomposition */ int gsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A) { const size_t N = A->size1; if (N != A->size2) { GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR); } else { size_t i, j; gsl_complex z; double ajj; for (j = 0; j < N; ++j) { z = gsl_matrix_complex_get(A, j, j); ajj = GSL_REAL(z); if (j > 0) { gsl_vector_complex_const_view aj = gsl_matrix_complex_const_subrow(A, j, 0, j); gsl_blas_zdotc(&aj.vector, &aj.vector, &z); ajj -= GSL_REAL(z); } if (ajj <= 0.0) { GSL_ERROR("matrix is not positive definite", GSL_EDOM); } ajj = sqrt(ajj); GSL_SET_COMPLEX(&z, ajj, 0.0); gsl_matrix_complex_set(A, j, j, z); if (j < N - 1) { gsl_vector_complex_view av = gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1); if (j > 0) { gsl_vector_complex_view aj = gsl_matrix_complex_subrow(A, j, 0, j); gsl_matrix_complex_view am = gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j); cholesky_complex_conj_vector(&aj.vector); gsl_blas_zgemv(CblasNoTrans, GSL_COMPLEX_NEGONE, &am.matrix, &aj.vector, GSL_COMPLEX_ONE, &av.vector); cholesky_complex_conj_vector(&aj.vector); } gsl_blas_zdscal(1.0 / ajj, &av.vector); } } /* Now store L^H in upper triangle */ for (i = 1; i < N; ++i) { for (j = 0; j < i; ++j) { z = gsl_matrix_complex_get(A, i, j); gsl_matrix_complex_set(A, j, i, gsl_complex_conjugate(z)); } } return GSL_SUCCESS; } } /* gsl_linalg_complex_cholesky_decomp() */ /* gsl_linalg_complex_cholesky_solve() Solve A x = b where A is in cholesky form */ int gsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky, const gsl_vector_complex * b, gsl_vector_complex * x) { if (cholesky->size1 != cholesky->size2) { GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR); } else if (cholesky->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (cholesky->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { gsl_vector_complex_memcpy (x, b); /* solve for y using forward-substitution, L y = b */ gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x); /* perform back-substitution, L^H x = y */ gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x); return GSL_SUCCESS; } } /* gsl_linalg_complex_cholesky_solve() */ /* gsl_linalg_complex_cholesky_svx() Solve A x = b in place where A is in cholesky form */ int gsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky, gsl_vector_complex * x) { if (cholesky->size1 != cholesky->size2) { GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR); } else if (cholesky->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* solve for y using forward-substitution, L y = b */ gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x); /* perform back-substitution, L^H x = y */ gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x); return GSL_SUCCESS; } } /* gsl_linalg_complex_cholesky_svx() */ /******************************************** * INTERNAL ROUTINES * ********************************************/ static void cholesky_complex_conj_vector(gsl_vector_complex *v) { size_t i; for (i = 0; i < v->size; ++i) { gsl_complex z = gsl_vector_complex_get(v, i); gsl_vector_complex_set(v, i, gsl_complex_conjugate(z)); } } /* cholesky_complex_conj_vector() */
{ "alphanum_fraction": 0.5885950413, "avg_line_length": 28.2710280374, "ext": "c", "hexsha": "1a2d464d6c7da74914792e30f83771514fdedf77", "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/linalg/choleskyc.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/linalg/choleskyc.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/linalg/choleskyc.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": 1586, "size": 6050 }
#include <jni.h> #include <omp.h> #ifdef __INTEL_COMPILER #include <mkl.h> #include <mkl_trans.h> #else #include <cblas.h> #endif JNIEXPORT jdouble JNICALL Java_edu_berkeley_bid_CBLAS_ddot (JNIEnv * env, jobject calling_obj, jint N, jdoubleArray jX, jint incX, jdoubleArray jY, jint incY){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jdouble returnValue; returnValue = cblas_ddot(N, X, incX, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); return returnValue; } JNIEXPORT jdouble JNICALL Java_edu_berkeley_bid_CBLAS_ddotxx (JNIEnv * env, jobject calling_obj, jint N, jdoubleArray jX, jint startX, jdoubleArray jY, jint startY){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jdouble returnValue; returnValue = cblas_ddot(N, X+startX, 1, Y+startY, 1); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); return returnValue; } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_ddotm (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jdoubleArray jX, jint ldx, jdoubleArray jY, jint ldy, jdoubleArray jZ){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jdouble * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i; for (i = 0; i < ncols; i++) { Z[i] = cblas_ddot(nrows, X+i*ldx, 1, Y+i*ldy, 1); } (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_ddotr (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jdoubleArray jX, jint ldx, jdoubleArray jY, jint ldy, jdoubleArray jZ){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jdouble * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i, j; for (i = 0; i < ncols; i++) { #pragma omp parallel for for (j = 0; j < nrows; j++) { Z[j] += X[j + i*ldx] * Y[j + i*ldy]; } } (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_daxpy (JNIEnv * env, jobject calling_obj, jint N, jdouble a, jdoubleArray jX, jint incX, jdoubleArray jY, jint incY){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_daxpy(N, a, X, incX, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_daxpyxx (JNIEnv * env, jobject calling_obj, jint N, jdouble a, jdoubleArray jX, jint startX, jdoubleArray jY, jint startY){ jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_daxpy(N, a, X+startX, 1, Y+startY, 1); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_dgemv (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint M, jint N, jdouble alpha, jdoubleArray jA, jint lda, jdoubleArray jX, jint incX, jdouble beta, jdoubleArray jY, jint incY){ jdouble * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jdouble * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jdouble * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_dgemv((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, M, N, alpha, A, lda, X, incX, beta, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_dgemm (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint transB, jint M, jint N, jint K, jdouble alpha, jdoubleArray jA, jint lda, jdoubleArray jB, jint ldb, jdouble beta, jdoubleArray jC, jint ldc){ jdouble * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jdouble * C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); cblas_dgemm((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_domatcopy (JNIEnv * env, jobject calling_obj, jstring j_order, jstring j_transA, jint M, jint N, jdouble alpha, jdoubleArray j_A, jint lda, jdoubleArray j_B, jint ldb) { char * order = (char *)(*env)->GetStringUTFChars(env, j_order, 0); char * transA = (char *)(*env)->GetStringUTFChars(env, j_transA, 0); jdouble * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER mkl_domatcopy(order[0], transA[0], M, N, alpha, A, lda, B, ldb); #else int corder = (order[0] == 'r' || order[0] == 'R') ? CblasRowMajor : CblasColMajor; int ctrans = (transA[0] == 't' || transA[0] == 'T') ? CblasTrans : CblasNoTrans; cblas_domatcopy(corder, ctrans, M, N, alpha, A, lda, B, ldb); #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); (*env)->ReleaseStringUTFChars(env, j_transA, transA); (*env)->ReleaseStringUTFChars(env, j_order, order); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_dmcscm (JNIEnv * env, jobject calling_obj, jint M, jint N, jdoubleArray j_A, jint lda, jdoubleArray j_B, jintArray j_ir, jintArray j_jc, jdoubleArray j_C, jint ldc){ jdouble * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); jint * ir = (*env)->GetPrimitiveArrayCritical(env, j_ir, JNI_FALSE); jint * jc = (*env)->GetPrimitiveArrayCritical(env, j_jc, JNI_FALSE); jdouble * C = (*env)->GetPrimitiveArrayCritical(env, j_C, JNI_FALSE); int ioff = jc[0]; int i; #pragma omp parallel for for (i = 0; i < N; i++) { int j, ir0; for (j = jc[i]-ioff; j < jc[i+1]-ioff; j++) { ir0 = ir[j]-ioff; cblas_daxpy(M, B[j], A+(ir0*lda), 1, C+(i*ldc), 1); } } (*env)->ReleasePrimitiveArrayCritical(env, j_C, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_jc, jc, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_ir, ir, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_dmcsrm (JNIEnv * env, jobject calling_obj, jint M, jint N, jdoubleArray j_A, jint lda, jdoubleArray j_B, jintArray j_ir, jintArray j_jc, jdoubleArray j_C, jint ldc){ jdouble * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); jint * ir = (*env)->GetPrimitiveArrayCritical(env, j_ir, JNI_FALSE); jint * jc = (*env)->GetPrimitiveArrayCritical(env, j_jc, JNI_FALSE); jdouble * C = (*env)->GetPrimitiveArrayCritical(env, j_C, JNI_FALSE); int ioff = jc[0]; int i; #pragma omp parallel for for (i = 0; i < N; i++) { int j, k; for (j = jc[i]-ioff; j < jc[i+1]-ioff; j++) { k = ir[j]-ioff; cblas_daxpy(M, B[j], A+(i*lda), 1, C+(k*ldc), 1); } } (*env)->ReleasePrimitiveArrayCritical(env, j_C, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_jc, jc, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_ir, ir, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT jfloat JNICALL Java_edu_berkeley_bid_CBLAS_sdot (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jX, jint incX, jfloatArray jY, jint incY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat returnValue; returnValue = cblas_sdot(N, X, incX, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); return returnValue; } JNIEXPORT jfloat JNICALL Java_edu_berkeley_bid_CBLAS_sdotxx (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jX, jint startX, jfloatArray jY, jint startY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat returnValue; returnValue = cblas_sdot(N, X+startX, 1, Y+startY, 1); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); return returnValue; } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_sdotm (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jfloatArray jX, jint ldx, jfloatArray jY, jint ldy, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i, j; for (i = 0; i < ncols; i++) { Z[i] = cblas_sdot(nrows, X+i*ldx, 1, Y+i*ldy, 1); } (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_sdotr (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jfloatArray jX, jint ldx, jfloatArray jY, jint ldy, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i, j; for (i = 0; i < ncols; i++) { #pragma omp parallel for for (j = 0; j < nrows; j++) { Z[j] += X[j + i*ldx] * Y[j + i*ldy]; } } (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_sgemv (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint M, jint N, jfloat alpha, jfloatArray jA, jint lda, jfloatArray jX, jint incX, jfloat beta, jfloatArray jY, jint incY){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_sgemv((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, M, N, alpha, A, lda, X, incX, beta, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_sgemm (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint transB, jint M, jint N, jint K, jfloat alpha, jfloatArray jA, jint lda, jfloatArray jB, jint ldb, jfloat beta, jfloatArray jC, jint ldc){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jfloat * C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); cblas_sgemm((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_sgemmx (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint transB, jint M, jint N, jint K, jfloat alpha, jfloatArray jA, jint Aoff, jint lda, jfloatArray jB, jint Boff, jint ldb, jfloat beta, jfloatArray jC, jint Coff, jint ldc){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jfloat * C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); cblas_sgemm((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, alpha, A+Aoff, lda, B+Boff, ldb, beta, C+Coff, ldc); (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_somatcopy (JNIEnv * env, jobject calling_obj, jstring j_order, jstring j_transA, jint M, jint N, jfloat alpha, jfloatArray j_A, jint lda, jfloatArray j_B, jint ldb) { char * order = (char *)(*env)->GetStringUTFChars(env, j_order, 0); char * transA = (char *)(*env)->GetStringUTFChars(env, j_transA, 0); jfloat * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER mkl_somatcopy(order[0], transA[0], M, N, alpha, A, lda, B, ldb); #else int corder = (order[0] == 'r' || order[0] == 'R') ? CblasRowMajor : CblasColMajor; int ctrans = (transA[0] == 't' || transA[0] == 'T') ? CblasTrans : CblasNoTrans; cblas_somatcopy(corder, ctrans, M, N, alpha, A, lda, B, ldb); #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); (*env)->ReleaseStringUTFChars(env, j_transA, transA); (*env)->ReleaseStringUTFChars(env, j_order, order); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_iomatcopy (JNIEnv * env, jobject calling_obj, jstring j_order, jstring j_transA, jint M, jint N, jintArray j_A, jint lda, jintArray j_B, jint ldb) { char * order = (char *)(*env)->GetStringUTFChars(env, j_order, 0); char * transA = (char *)(*env)->GetStringUTFChars(env, j_transA, 0); jfloat * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER mkl_somatcopy(order[0], transA[0], M, N, 1.0f, A, lda, B, ldb); #else int corder = (order[0] == 'r' || order[0] == 'R') ? CblasRowMajor : CblasColMajor; int ctrans = (transA[0] == 't' || transA[0] == 'T') ? CblasTrans : CblasNoTrans; cblas_somatcopy(corder, ctrans, M, N, 1.0f, A, lda, B, ldb); #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); (*env)->ReleaseStringUTFChars(env, j_transA, transA); (*env)->ReleaseStringUTFChars(env, j_order, order); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_lomatcopy (JNIEnv * env, jobject calling_obj, jstring j_order, jstring j_transA, jint M, jint N, jlongArray j_A, jint lda, jlongArray j_B, jint ldb) { char * order = (char *)(*env)->GetStringUTFChars(env, j_order, 0); char * transA = (char *)(*env)->GetStringUTFChars(env, j_transA, 0); jdouble * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER mkl_domatcopy(order[0], transA[0], M, N, 1.0, A, lda, B, ldb); #else int corder = (order[0] == 'r' || order[0] == 'R') ? CblasRowMajor : CblasColMajor; int ctrans = (transA[0] == 't' || transA[0] == 'T') ? CblasTrans : CblasNoTrans; cblas_domatcopy(corder, ctrans, M, N, 1.0, A, lda, B, ldb); #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); (*env)->ReleaseStringUTFChars(env, j_transA, transA); (*env)->ReleaseStringUTFChars(env, j_order, order); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_spermute (JNIEnv * env, jobject calling_obj, jint M, jint N, jint K, jfloatArray j_A, jfloatArray j_B) { int i, offset, step = M*N; jfloat * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER for (i = 0, offset = 0; i < K; i++, offset += step) { mkl_somatcopy('C', 'T', M, N, 1.0f, A+offset, M, B+offset, N); } #else for (i = 0, offset = 0; i < K; i++, offset += step) { cblas_somatcopy(CblasColMajor, CblasTrans, M, N, 1.0f, A+offset, M, B+offset, N); } #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_ipermute (JNIEnv * env, jobject calling_obj, jint M, jint N, jint K, jintArray j_A, jintArray j_B) { int i, offset, step = M*N; jfloat * A = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE)); jfloat * B = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE)); #ifdef __INTEL_COMPILER for (i = 0, offset = 0; i < K; i++, offset += step) { mkl_somatcopy('C', 'T', M, N, 1.0f, A+offset, M, B+offset, N); } #else for (i = 0, offset = 0; i < K; i++, offset += step) { cblas_somatcopy(CblasColMajor, CblasTrans, M, N, 1.0f, A+offset, M, B+offset, N); } #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_dpermute (JNIEnv * env, jobject calling_obj, jint M, jint N, jint K, jdoubleArray j_A, jdoubleArray j_B) { int i, offset, step = M*N; jdouble * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jdouble * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); #ifdef __INTEL_COMPILER for (i = 0, offset = 0; i < K; i++, offset += step) { mkl_domatcopy('C', 'T', M, N, 1.0, A+offset, M, B+offset, N); } #else for (i = 0, offset = 0; i < K; i++, offset += step) { cblas_domatcopy(CblasColMajor, CblasTrans, M, N, 1.0, A+offset, M, B+offset, N); } #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_lpermute (JNIEnv * env, jobject calling_obj, jint M, jint N, jint K, jlongArray j_A, jlongArray j_B) { int i, offset, step = M*N; jdouble * A = (jdouble *)((*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE)); jdouble * B = (jdouble *)((*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE)); #ifdef __INTEL_COMPILER for (i = 0, offset = 0; i < K; i++, offset += step) { mkl_domatcopy('C', 'T', M, N, 1.0, A+offset, M, B+offset, N); } #else for (i = 0, offset = 0; i < K; i++, offset += step) { cblas_domatcopy(CblasColMajor, CblasTrans, M, N, 1.0, A+offset, M, B+offset, N); } #endif (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_saxpy (JNIEnv * env, jobject calling_obj, jint N, jfloat a, jfloatArray jX, jint incX, jfloatArray jY, jint incY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_saxpy(N, a, X, incX, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_saxpyxx (JNIEnv * env, jobject calling_obj, jint N, jfloat a, jfloatArray jX, jint startX, jfloatArray jY, jint startY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); cblas_saxpy(N, a, X+startX, 1, Y+startY, 1); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_smcscm (JNIEnv * env, jobject calling_obj, jint M, jint N, jfloatArray j_A, jint lda, jfloatArray j_B, jintArray j_ir, jintArray j_jc, jfloatArray j_C, jint ldc){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); jint * ir = (*env)->GetPrimitiveArrayCritical(env, j_ir, JNI_FALSE); jint * jc = (*env)->GetPrimitiveArrayCritical(env, j_jc, JNI_FALSE); jfloat * C = (*env)->GetPrimitiveArrayCritical(env, j_C, JNI_FALSE); int ioff = jc[0]; int i; #pragma omp parallel for for (i = 0; i < N; i++) { int j, ir0; for (j = jc[i]-ioff; j < jc[i+1]-ioff; j++) { ir0 = ir[j]-ioff; cblas_saxpy(M, B[j], A+(ir0*lda), 1, C+(i*ldc), 1); } } (*env)->ReleasePrimitiveArrayCritical(env, j_C, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_jc, jc, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_ir, ir, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_smcsrm (JNIEnv * env, jobject calling_obj, jint M, jint N, jfloatArray j_A, jint lda, jfloatArray j_B, jintArray j_ir, jintArray j_jc, jfloatArray j_C, jint ldc){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, j_A, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, j_B, JNI_FALSE); jint * ir = (*env)->GetPrimitiveArrayCritical(env, j_ir, JNI_FALSE); jint * jc = (*env)->GetPrimitiveArrayCritical(env, j_jc, JNI_FALSE); jfloat * C = (*env)->GetPrimitiveArrayCritical(env, j_C, JNI_FALSE); int ioff = jc[0]; int i; #pragma omp parallel for for (i = 0; i < N; i++) { int j, jj, k; for (j = jc[i]-ioff; j < jc[i+1]-ioff; j++) { jj = ir[j]-ioff; if (M == 1) { C[jj*ldc] += B[j] * A[i*lda]; } else if (M > 10) { cblas_saxpy(M, B[j], A+(i*lda), 1, C+(jj*ldc), 1); } else { int iia = i*lda; int jjc = jj*ldc; float Bj = B[j]; for (k = 0; k < M; k++) { C[jjc+k] += Bj * A[iia+k]; } } } } (*env)->ReleasePrimitiveArrayCritical(env, j_C, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_jc, jc, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_ir, ir, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_B, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, j_A, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cdot (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jX, jint incX, jfloatArray jY, jint incY, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); cblas_cdotu_sub(N, X, incX, Y, incY, Z); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cdotxx (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jX, jint startX, jfloatArray jY, jint startY, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); cblas_cdotu_sub(N, X+startX, 1, Y+startY, 1, Z); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cdotm (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jfloatArray jX, jint ldx, jfloatArray jY, jint ldy, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i; for (i=0; i<2*ncols; i+=2) { cblas_cdotu_sub(nrows, X+i*ldx, 1, Y+i*ldy, 1, Z+i); } (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cdotr (JNIEnv * env, jobject calling_obj, jint nrows, jint ncols, jfloatArray jX, jint ldx, jfloatArray jY, jint ldy, jfloatArray jZ){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * Z = (*env)->GetPrimitiveArrayCritical(env, jZ, JNI_FALSE); int i, j; for (i = 0; i < ncols; i++) { #pragma omp parallel for for (j = 0; j < nrows; j++) { int ix, iy; ix = 2*(j + i*ldx); iy = 2*(j + i*ldy); Z[2*j] += X[ix] * Y[ix] - X[ix+1] * Y[ix+1]; Z[2*j+1] += X[ix] * Y[ix+1] + X[ix+1] * Y[ix]; } } (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jZ, Z, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cgemv (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint M, jint N, jfloatArray jAlpha, jfloatArray jA, jint lda, jfloatArray jX, jint incX, jfloatArray jBeta, jfloatArray jY, jint incY){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * alpha = (*env)->GetPrimitiveArrayCritical(env, jAlpha, JNI_FALSE); jfloat * beta = (*env)->GetPrimitiveArrayCritical(env, jBeta, JNI_FALSE); cblas_cgemv((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, M, N, alpha, A, lda, X, incX, beta, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jBeta, beta, 0); (*env)->ReleasePrimitiveArrayCritical(env, jAlpha, alpha, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_cgemm (JNIEnv * env, jobject calling_obj, jint order, jint transA, jint transB, jint M, jint N, jint K, jfloatArray jAlpha, jfloatArray jA, jint lda, jfloatArray jB, jint ldb, jfloatArray jBeta, jfloatArray jC, jint ldc){ jfloat * A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat * B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jfloat * C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); jfloat * alpha = (*env)->GetPrimitiveArrayCritical(env, jAlpha, JNI_FALSE); jfloat * beta = (*env)->GetPrimitiveArrayCritical(env, jBeta, JNI_FALSE); cblas_cgemm((CBLAS_ORDER)order, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_caxpy (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jA, jfloatArray jX, jint incX, jfloatArray jY, jint incY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * a = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); cblas_caxpy(N, a, X, incX, Y, incY); (*env)->ReleasePrimitiveArrayCritical(env, jA, a, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_caxpyxx (JNIEnv * env, jobject calling_obj, jint N, jfloatArray jA, jfloatArray jX, jint startX, jfloatArray jY, jint startY){ jfloat * X = (*env)->GetPrimitiveArrayCritical(env, jX, JNI_FALSE); jfloat * Y = (*env)->GetPrimitiveArrayCritical(env, jY, JNI_FALSE); jfloat * a = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); cblas_caxpy(N, a, X+startX, 1, Y+startY, 1); (*env)->ReleasePrimitiveArrayCritical(env, jA, a, 0); (*env)->ReleasePrimitiveArrayCritical(env, jY, Y, 0); (*env)->ReleasePrimitiveArrayCritical(env, jX, X, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_blockSgemm (JNIEnv *env, jobject obj, jint transA, jint transB, jint nr, jint nc, jint kk, jfloat alpha, jfloatArray jA, jint aoff, jint lda, jint astep, jfloatArray jB, jint boff, jint ldb, jint bstep, jfloat beta, jfloatArray jC, jint coff, jint ldc, jint cstep, jint reps) { int i, at, bt; jfloat *A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jfloat *B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jfloat *C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); at = (transA) ? CblasTrans : CblasNoTrans; bt = (transB) ? CblasTrans : CblasNoTrans; A += aoff; B += boff; C += coff; for (i = 0; i < reps; i++) { cblas_sgemm(CblasColMajor, at, bt, nr, nc, kk, alpha, A, lda, B, ldb, beta, C, ldc); A += astep; B += bstep; C += cstep; } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_blockDgemm (JNIEnv *env, jobject obj, jint transA, jint transB, jint nr, jint nc, jint kk, jdouble alpha, jdoubleArray jA, jint aoff, jint lda, jint astep, jdoubleArray jB, jint boff, jint ldb, jint bstep, jdouble beta, jdoubleArray jC, jint coff, jint ldc, jint cstep, jint reps) { int i, at, bt; jdouble *A = (*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE); jdouble *B = (*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE); jdouble *C = (*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE); at = (transA) ? CblasTrans : CblasNoTrans; bt = (transB) ? CblasTrans : CblasNoTrans; A += aoff; B += boff; C += coff; for (i = 0; i < reps; i++) { cblas_dgemm(CblasColMajor, at, bt, nr, nc, kk, alpha, A, lda, B, ldb, beta, C, ldc); A += astep; B += bstep; C += cstep; } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_blockSgemm4D (JNIEnv *env, jobject obj, jint transA, jint transB, jint nr, jint nc, jint kk, jfloat alpha, jfloatArray jA, jint aoff, jint lda, jint astep1, jint astep2, jfloatArray jB, jint boff, jint ldb, jint bstep1, jint bstep2, jfloat beta, jfloatArray jC, jint coff, jint ldc, jint cstep1, jint cstep2, jint reps1, jint reps2) { int i, j, at, bt; float *A = (float *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); float *B = (float *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); float *C = (float *)((*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE)); float *pA, *pB, *pC; at = (transA) ? CblasTrans : CblasNoTrans; bt = (transB) ? CblasTrans : CblasNoTrans; A += aoff; B += boff; C += coff; for (i = 0; i < reps2; i++) { for (j = 0; j < reps1; j++) { pA = A + (j * astep1 + i * astep2); pB = B + (j * bstep1 + i * bstep2); pC = C + (j * cstep1 + i * cstep2); cblas_sgemm(CblasColMajor, at, bt, nr, nc, kk, alpha, pA, lda, pB, ldb, beta, pC, ldc); } } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_blockDgemm4D (JNIEnv *env, jobject obj, jint transA, jint transB, jint nr, jint nc, jint kk, jdouble alpha, jdoubleArray jA, jint aoff, jint lda, jint astep1, jint astep2, jdoubleArray jB, jint boff, jint ldb, jint bstep1, jint bstep2, jdouble beta, jdoubleArray jC, jint coff, jint ldc, jint cstep1, jint cstep2, jint reps1, jint reps2) { int i, j, at, bt; double *A = (double *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); double *B = (double *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); double *C = (double *)((*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE)); double *pA, *pB, *pC; at = (transA) ? CblasTrans : CblasNoTrans; bt = (transB) ? CblasTrans : CblasNoTrans; A += aoff; B += boff; C += coff; for (i = 0; i < reps2; i++) { for (j = 0; j < reps1; j++) { pA = A + (j * astep1 + i * astep2); pB = B + (j * bstep1 + i * bstep2); pC = C + (j * cstep1 + i * cstep2); cblas_dgemm(CblasColMajor, at, bt, nr, nc, kk, alpha, pA, lda, pB, ldb, beta, pC, ldc); } } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_word2vecFwd (JNIEnv *env, jobject obj, jint nrows, jint ncols, const jint nwa, const jint nwb, jintArray jWA, jintArray jWB, jfloatArray jA, jfloatArray jB, jfloatArray jC) { jint * WA = (jint *)((*env)->GetPrimitiveArrayCritical(env, jWA, JNI_FALSE)); jint * WB = (jint *)((*env)->GetPrimitiveArrayCritical(env, jWB, JNI_FALSE)); jfloat * A = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jfloat * B = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); jfloat * C = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE)); int i; #pragma omp parallel for for (i = 0; i < ncols; i++) { int j, k, c, ia, ib, coff; float sum; for (j = 0; j < nwa; j++) { ia = nrows*WA[j+i*nwa]; for (k = 0; k < nwb; k++) { ib = nrows*WB[k+i*nwb]; sum = 0; for (c = 0; c < nrows; c++) { sum += A[c + ia] * B[c + ib]; } coff = nwa * (k + nwb * i); C[j + coff] = sum; } } } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); (*env)->ReleasePrimitiveArrayCritical(env, jWB, WB, 0); (*env)->ReleasePrimitiveArrayCritical(env, jWA, WA, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_word2vecBwd (JNIEnv *env, jobject obj, jint nrows, jint ncols, jint nwa, jint nwb, jintArray jWA, jintArray jWB, jfloatArray jA, jfloatArray jB, jfloatArray jDA, jfloatArray jDB, jfloatArray jC, jfloat lrate) { jint * WA = (jint *)((*env)->GetPrimitiveArrayCritical(env, jWA, JNI_FALSE)); jint * WB = (jint *)((*env)->GetPrimitiveArrayCritical(env, jWB, JNI_FALSE)); jfloat * A = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jfloat * B = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); jfloat * DA = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jDA, JNI_FALSE)); jfloat * DB = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jDB, JNI_FALSE)); jfloat * C = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jC, JNI_FALSE)); int i; #pragma omp parallel for for (i = 0; i < ncols; i++) { int j, k, c; float cv; int ia, ib; for (j = 0; j < nwa; j++) { ia = nrows*WA[j+i*nwa]; for (k = 0; k < nwb; k++) { ib = nrows*WB[k+i*nwb]; cv = lrate * C[j + nwa * (k + nwb * i)]; for (c = 0; c < nrows; c++) { A[c + ia] += cv * DB[c + ib]; } } } for (k = 0; k < nwb; k++) { ib = nrows*WB[k+i*nwb]; for (j = 0; j < nwa; j++) { ia = nrows*WA[j+i*nwa]; cv = lrate * C[j + nwa * (k + nwb * i)]; for (c = 0; c < nrows; c++) { B[c + ib] += cv * DA[c + ia]; } } } } (*env)->ReleasePrimitiveArrayCritical(env, jC, C, 0); (*env)->ReleasePrimitiveArrayCritical(env, jDB, DB, 0); (*env)->ReleasePrimitiveArrayCritical(env, jDA, DA, 0); (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); (*env)->ReleasePrimitiveArrayCritical(env, jWB, WB, 0); (*env)->ReleasePrimitiveArrayCritical(env, jWA, WA, 0); } #define mymax(A, B) ((A>B) ? A : B) #define mymin(A, B) ((A<B) ? A : B) JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_reduceTensorFloat (JNIEnv *env, jobject obj, jfloatArray jA, jfloatArray jB, jint m, jint n, jint p, jint op) { jfloat * A = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jfloat * B = (jfloat *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); int i, j; for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = A[k + m * n * i]; } } for (j = 1; j < n; j++) { switch (op) { case 0 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = B[k + m * i] + A[k + m * (j + n * i)]; } } } break; case 1 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = B[k + m * i] * A[k + m * (j + n * i)]; } } } break; case 2 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymax(B[k + m * i], A[k + m * (j + n * i)]); } } } break; case 3 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymin(B[k + m * i], A[k + m * (j + n * i)]); } } } break; default: {} } } (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_reduceTensorDouble (JNIEnv *env, jobject obj, jdoubleArray jA, jdoubleArray jB, jint m, jint n, jint p, jint op) { jdouble * A = (jdouble *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jdouble * B = (jdouble *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); int i, j; for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = A[k + m * n * i]; } } for (j = 1; j < n; j++) { switch (op) { case 0 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] += A[k + m * (j + n * i)]; } } } break; case 1 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] *= A[k + m * (j + n * i)]; } } } break; case 2 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymax(B[k + m * i], A[k + m * (j + n * i)]); } } } break; case 3 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymin(B[k + m * i], A[k + m * (j + n * i)]); } } } break; default: {} } } (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_reduceTensorInt (JNIEnv *env, jobject obj, jintArray jA, jintArray jB, jint m, jint n, jint p, jint op) { jint * A = (jint *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jint * B = (jint *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); int i, j; for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = A[k + m * n * i]; } } for (j = 1; j < n; j++) { switch (op) { case 0 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] += A[k + m * (j + n * i)]; } } } break; case 1 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] *= A[k + m * (j + n * i)]; } } } break; case 2 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymax(B[k + m * i], A[k + m * (j + n * i)]); } } } break; case 3 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymin(B[k + m * i], A[k + m * (j + n * i)]); } } } break; default: {} } } (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); } JNIEXPORT void JNICALL Java_edu_berkeley_bid_CBLAS_reduceTensorLong (JNIEnv *env, jobject obj, jlongArray jA, jlongArray jB, jint m, jint n, jint p, jint op) { jlong * A = (jlong *)((*env)->GetPrimitiveArrayCritical(env, jA, JNI_FALSE)); jlong * B = (jlong *)((*env)->GetPrimitiveArrayCritical(env, jB, JNI_FALSE)); int i, j; for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = A[k + m * n * i]; } } for (j = 1; j < n; j++) { switch (op) { case 0 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] += A[k + m * (j + n * i)]; } } } break; case 1 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] *= A[k + m * (j + n * i)]; } } } break; case 2 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymax(B[k + m * i], A[k + m * (j + n * i)]); } } } break; case 3 : { #pragma omp parallel for for (i = 0; i < p; i++) { int k; for (k = 0; k < m; k++) { B[k + m * i] = mymin(B[k + m * i], A[k + m * (j + n * i)]); } } } break; default: {} } } (*env)->ReleasePrimitiveArrayCritical(env, jB, B, 0); (*env)->ReleasePrimitiveArrayCritical(env, jA, A, 0); }
{ "alphanum_fraction": 0.6382784312, "avg_line_length": 38.3486073675, "ext": "c", "hexsha": "cc2e6a921b2cfdfd629060d1c6873e07ec8fe022", "lang": "C", "max_forks_count": 69, "max_forks_repo_forks_event_max_datetime": "2021-12-25T20:53:06.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-04T11:30:13.000Z", "max_forks_repo_head_hexsha": "dc97590ba5abdb0e6bb6d940ab050a5f6536e31d", "max_forks_repo_licenses": [ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ], "max_forks_repo_name": "BIDData/BIDMat", "max_forks_repo_path": "jni/src/BIDMat_CBLAS.c", "max_issues_count": 56, "max_issues_repo_head_hexsha": "dc97590ba5abdb0e6bb6d940ab050a5f6536e31d", "max_issues_repo_issues_event_max_datetime": "2020-08-11T16:41:27.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-06T18:13:49.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ], "max_issues_repo_name": "BIDData/BIDMat", "max_issues_repo_path": "jni/src/BIDMat_CBLAS.c", "max_line_length": 145, "max_stars_count": 212, "max_stars_repo_head_hexsha": "dc97590ba5abdb0e6bb6d940ab050a5f6536e31d", "max_stars_repo_licenses": [ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ], "max_stars_repo_name": "BIDData/BIDMat", "max_stars_repo_path": "jni/src/BIDMat_CBLAS.c", "max_stars_repo_stars_event_max_datetime": "2022-03-07T04:43:33.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-08T03:30:41.000Z", "num_tokens": 14265, "size": 42682 }
#pragma once #include "string.h" #include <math.h> #include "flow.h" extern "C" { #include <cblas.h> } void OpenblasGemm(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K, const float alpha, const float* A, const float* B, const float beta, float* C); void OpenblasGemv(const CBLAS_TRANSPOSE TransA, const int M, const int N, const float alpha, const float* A, const float* x, const float beta, float* y); void InitWeightBias(Flow &weight_, Flow &bias_); //Y[i] = X[i] void CopyData(const int N, const float* X, float* Y); //y[i] = exp(a[i]) void ExpData(const int n, const float* a, float* y); //y[i] = a[i]\b[i] void DivData(const int n, const float* a, const float* b, float* y); //X = alpha*X void ScalData(const int N, const float alpha, float *X); //Y=alpha*X+Y void AxpyData(const int N, const float alpha, const float* X, float* Y); //Y= alpha*X+beta*Y void AxpbyData(const int N, const float alpha, const float* X, const float beta, float* Y);
{ "alphanum_fraction": 0.6688804554, "avg_line_length": 27.7368421053, "ext": "h", "hexsha": "0f2d52798758760290823fda7f7cdfad027d7f44", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-04-18T07:00:35.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-14T01:18:04.000Z", "max_forks_repo_head_hexsha": "fbb9c4c589affe6194856c352f025fa3ab30b415", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ltj1486771935/LazyNet", "max_forks_repo_path": "include/math_function.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "fbb9c4c589affe6194856c352f025fa3ab30b415", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:09:21.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-02T09:37:09.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ltj1486771935/LazyNet", "max_issues_repo_path": "include/math_function.h", "max_line_length": 91, "max_stars_count": 15, "max_stars_repo_head_hexsha": "fbb9c4c589affe6194856c352f025fa3ab30b415", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "samylee/LazyNet", "max_stars_repo_path": "include/math_function.h", "max_stars_repo_stars_event_max_datetime": "2021-12-06T03:21:45.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-14T01:18:02.000Z", "num_tokens": 312, "size": 1054 }
#include "ccl_utils.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include "ccl_params.h" #include "ccl_error.h" #include <gsl/gsl_errno.h> /* ------- ROUTINE: ccl_linear spacing ------ INPUTS: [xmin,xmax] of the interval to be divided in N bins OUTPUT: bin edges in range [xmin,xmax] */ double * ccl_linear_spacing(double xmin, double xmax, int N) { double dx = (xmax-xmin)/(N -1.); double * x = malloc(sizeof(double)*N); if (x==NULL) { fprintf(stderr, "ERROR: Could not allocate memory for linear-spaced array (N=%d)\n", N); return x; } for (int i=0; i<N; i++) { x[i] = xmin + dx*i; } x[0]=xmin; //Make sure roundoff errors don't spoil edges x[N-1]=xmax; //Make sure roundoff errors don't spoil edges return x; } /* ------- ROUTINE: ccl_log spacing ------ INPUTS: [xmin,xmax] of the interval to be divided logarithmically in N bins TASK: divide an interval in N logarithmic bins OUTPUT: bin edges in range [xmin,xmax] */ double * ccl_log_spacing(double xmin, double xmax, int N) { if (N<2) { fprintf(stderr, "ERROR: Cannot make log-spaced array with %d points - need at least 2\n", N); return NULL; } if (!(xmin>0 && xmax>0)) { fprintf(stderr, "ERROR: Cannot make log-spaced array xmax or xmax non-positive (had %le, %le)\n", xmin, xmax); return NULL; } double log_xmax = log(xmax); double log_xmin = log(xmin); double dlog_x = (log_xmax - log_xmin) / (N-1.); double * x = malloc(sizeof(double)*N); if (x==NULL) { fprintf(stderr, "ERROR: Could not allocate memory for log-spaced array (N=%d)\n", N); return x; } for (int i=0; i<N; i++) { x[i] = exp(log_xmin + dlog_x*i); } x[0]=xmin; //Make sure roundoff errors don't spoil edges x[N-1]=xmax; //Make sure roundoff errors don't spoil edges return x; } //Spline creator //n -> number of points //x -> x-axis //y -> f(x)-axis //y0,yf -> values of f(x) to use beyond the interpolation range SplPar *ccl_spline_init(int n,double *x,double *y,double y0,double yf) { SplPar *spl=malloc(sizeof(SplPar)); if(spl==NULL) return NULL; spl->intacc=gsl_interp_accel_alloc(); spl->spline=gsl_spline_alloc(gsl_interp_cspline,n); int parstatus=gsl_spline_init(spl->spline,x,y,n); if(parstatus) { gsl_interp_accel_free(spl->intacc); gsl_spline_free(spl->spline); return NULL; } spl->x0=x[0]; spl->xf=x[n-1]; spl->y0=y0; spl->yf=yf; return spl; } //Evaluates spline at x checking for bound errors double ccl_spline_eval(double x,SplPar *spl) { if(x<=spl->x0) return spl->y0; else if(x>=spl->xf) return spl->yf; else { double y; int stat=gsl_spline_eval_e(spl->spline,x,spl->intacc,&y); if (stat!=GSL_SUCCESS) { ccl_raise_exception(stat,"ccl_utils.c: ccl_splin_eval(): gsl error\n"); return NAN; } return y; } } //Spline destructor void ccl_spline_free(SplPar *spl) { gsl_spline_free(spl->spline); gsl_interp_accel_free(spl->intacc); free(spl); }
{ "alphanum_fraction": 0.6427627231, "avg_line_length": 24.4032258065, "ext": "c", "hexsha": "e8ee0736f566a9a9fea49a84604d1832e8d13cb0", "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": "1683ee0af665e68924e67a11bffda26ab3269fe5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zdu863/3dcorrelation", "max_forks_repo_path": "src/ccl_utils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1683ee0af665e68924e67a11bffda26ab3269fe5", "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": "zdu863/3dcorrelation", "max_issues_repo_path": "src/ccl_utils.c", "max_line_length": 114, "max_stars_count": null, "max_stars_repo_head_hexsha": "1683ee0af665e68924e67a11bffda26ab3269fe5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zdu863/3dcorrelation", "max_stars_repo_path": "src/ccl_utils.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 962, "size": 3026 }
/* * The MIT License (MIT) * * Copyright (c) 2014 Boone "Bea" Adkins * * 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. */ /** * @class pomdp::MultinomialPolicy * * CompoundPolicy whose action is determined by sampling a <s>multinomial</s> categorical distribution across * sub-policies. * * @date Aug 10, 2013 * @author Bea Adkins */ #ifndef MULTINOMIAL_POLICY_H #define MULTINOMIAL_POLICY_H #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "assert_rng.h" #include "compound_policy.h" namespace pomdp { template <class Base_Policy> class MultinomialPolicy : public CompoundPolicySpec<Base_Policy> { public: MultinomialPolicy() : val_table_(NULL) { rng_ = gsl_rng_alloc(gsl_rng_taus2); // Randomly seed the RNG. srand(time(NULL)); gsl_rng_set (rng_, rand()); } virtual ~MultinomialPolicy() { gsl_rng_free(rng_); if(CompoundPolicySpec<Base_Policy>::isInit()) { gsl_ran_discrete_free(val_table_); } } virtual bool loadFromFiles(const std::vector<std::string>& paths) { if(!CompoundPolicySpec<Base_Policy>::loadFromFiles(paths)) return false; CompoundPolicySpec<Base_Policy>::is_init_ = false; // Not yet initialized. // Now that model number is known, initialize random number variables. freshenDistribution(); CompoundPolicySpec<Base_Policy>::is_init_ = true; return true; } virtual int applyPolicy(const FeatureValue& current) const { // Sample a policy index. int i_sampled_policy = sample(); if(i_sampled_policy == -1) return -1; ROS_ASSERT(0 <= i_sampled_policy && i_sampled_policy < CompoundPolicySpec<Base_Policy>::getNumModels()); // Apply that policy. ROS_DEBUG_STREAM("Appying policy #" << i_sampled_policy << ":"); return CompoundPolicySpec<Base_Policy>::models_[i_sampled_policy]->applyPolicy(current); } virtual bool setModelLikelihoods(const std::vector<double>& model_likelihoods) { if(!CompoundPolicySpec<Base_Policy>::setModelLikelihoods(model_likelihoods)) return false; freshenDistribution(); // With new model likelihoods return true; } protected: /** * Random number generator. */ gsl_rng* rng_; /** * Table for quickly sampling values. */ gsl_ran_discrete_t* val_table_; /** * @return int within [0, numModels] or -1 on error. */ int sample() const { if(!CompoundPolicySpec<Base_Policy>::isInit() || CompoundPolicySpec<Base_Policy>::getNumModels() == 0) return -1; // Sample a value. return gsl_ran_discrete(rng_, val_table_); } /** * Call this whenever model_likelihoods_ change, in value or length. */ void freshenDistribution() { ROS_ASSERT(CompoundPolicySpec<Base_Policy>::model_likelihoods_.size() > 0); if(CompoundPolicySpec<Base_Policy>::isInit()) gsl_ran_discrete_free(val_table_); val_table_ = gsl_ran_discrete_preproc(CompoundPolicySpec<Base_Policy>::model_likelihoods_.size(), &CompoundPolicySpec<Base_Policy>::model_likelihoods_[0]); } }; typedef MultinomialPolicy<MDPPolicy> MultinomialMDPPolicy; typedef MultinomialPolicy<POMDPPolicy> MultinomialPOMDPPolicy; } /* namespace pomdp */ #endif /* MULTINOMIAL_POLICY_H */
{ "alphanum_fraction": 0.7178489703, "avg_line_length": 29.9315068493, "ext": "h", "hexsha": "a604d87a10d8417ee7f96c9670f82584ed670772", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-08-08T12:57:53.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-10T04:40:07.000Z", "max_forks_repo_head_hexsha": "73af687f94fc41c2f60e4ae86702064a25ea59b3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "b-adkins/ros_pomdp", "max_forks_repo_path": "src/pomdp/include/multinomial_policy.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af687f94fc41c2f60e4ae86702064a25ea59b3", "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": "b-adkins/ros_pomdp", "max_issues_repo_path": "src/pomdp/include/multinomial_policy.h", "max_line_length": 109, "max_stars_count": 8, "max_stars_repo_head_hexsha": "73af687f94fc41c2f60e4ae86702064a25ea59b3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "b-adkins/ros_pomdp", "max_stars_repo_path": "src/pomdp/include/multinomial_policy.h", "max_stars_repo_stars_event_max_datetime": "2019-02-22T07:39:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-10T04:40:06.000Z", "num_tokens": 1063, "size": 4370 }
#ifndef CACHED_IMAGE_H #define CACHED_IMAGE_H #ifndef solaris # include <stdint.h> #endif #include "asf_meta.h" #include "float_image.h" #include <stdio.h> #include <sys/types.h> #include <glib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_histogram.h> //--------------------------------------------------------------------------- // Adding a new supported data type: // cache.c: // data_size() // cached_image_get_pixel() // cached_image_get_rgb() // stats.c: // generate_thumbnail_data() // big_image.c: // update_pixel_info() // read_X.c: (for clients that will handle the data type) // open_X_data() // typedef enum { UNDEFINED = 0, GREYSCALE_FLOAT = 1, GREYSCALE_BYTE = 2, RGB_BYTE = 3, RGB_FLOAT = 4 } ssv_data_type_t; // Stats structure -- this one is used by both greyscale and RGB typedef struct { double map_min, map_max; double avg, stddev; double act_min, act_max; // absolute min/max of all values int hist[256]; // histogram double no_data_value; // value indicating "no data" int have_no_data; // TRUE if "no_data_value" is present double no_data_min; double no_data_max; int have_no_data_range; int truncate; } ImageStats; // Stats structure -- this one is used only for RGB images, keeps track // of stats for each channel typedef struct { double map_min, map_max; double avg, stddev; double act_min, act_max; // absolute min/max of all values double no_data_value; int have_no_data; double no_data_max; double no_data_min; int have_no_data_range; int truncate; } ImageStatsRGB; // NOTE: At the moment, the Pixbuf that contains the displayed data // is plain RGB, not RGB-A, so adding support for transparency would // also involve changing big_image.c/make_big_image(), and you'd have // to add a method to the cache interface that returned the alpha // channel in addition to the rgb values. //--------------------------------------------------------------------------- // This is the client interface -- the set of function pointers, etc, // that encapsulate how the image cache gets data from the file. // See: -read.c/read_file() for how the cache is hooked up to the // client depending on what the file type is // -read_template.c for an example of how to add another client typedef int ReadClientFn(int row_start, int n_rows_to_get, void *dest, void *read_client_info, meta_parameters *meta, int data_type); typedef int ThumbFn(int thumb_size_x, int thumb_size_y, meta_parameters *meta, void *read_client_info, void *dest, int data_type); typedef void FreeFn(void *read_client_info); typedef struct { ReadClientFn *read_fn; ThumbFn *thumb_fn; FreeFn *free_fn; void *read_client_info; ssv_data_type_t data_type; int require_full_load; } ClientInterface; //--------------------------------------------------------------------------- // Here is the ImageCache stuff. The global ImageCache that holds the // loaded image is "data_ci". This is all private data. typedef struct { int nl, ns; // Image dimensions. ClientInterface *client; // pointers to data read implementations int n_tiles; // Number of tiles in memory int reached_max_tiles; // Have we loaded as many tiles as we can? int rows_per_tile; // Number of rows in each tile int entire_image_fits; // TRUE if we can load the entire image int *rowstarts; // Row numbers starting each tile unsigned char **cache; // Cached values (floats, unsigned chars ...) int *access_counts; // Updated when a tile is accessed int n_access; // used to find oldest tile ssv_data_type_t data_type;// type of data we have meta_parameters *meta; // metadata -- don't own this pointer ImageStats *stats; // not owned by us, not populated by us ImageStatsRGB *stats_r; // not owned by us, not populated by us ImageStatsRGB *stats_g; // not owned by us, not populated by us ImageStatsRGB *stats_b; // not owned by us, not populated by us } CachedImage; CachedImage * cached_image_new_from_file( const char *file, meta_parameters *meta, ClientInterface *client, ImageStats *stats, ImageStatsRGB *stats_r, ImageStatsRGB *stats_g, ImageStatsRGB *stats_b); float cached_image_get_pixel (CachedImage *self, int line, int samp); void cached_image_get_rgb(CachedImage *self, int line, int samp, unsigned char *r, unsigned char *g, unsigned char *b); void cached_image_get_rgb_float(CachedImage *self, int line, int samp, float *r, float *g, float *b); void load_thumbnail_data(CachedImage *self, int thumb_size_x, int thumb_size_y, void *dest); void cached_image_free (CachedImage *self); #endif
{ "alphanum_fraction": 0.6491967871, "avg_line_length": 37.1641791045, "ext": "h", "hexsha": "cd1a34771e073bdcb0b442e29a64a4af4c444936", "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/asf_view/cache.h", "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/asf_view/cache.h", "max_line_length": 79, "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/asf_view/cache.h", "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": 1164, "size": 4980 }
#pragma once #include <gsl/gsl> #include <memory> class BassEnhance; class Eq_5band; class Reverb; struct Fx_Parameter { const char *name; int default_value; enum Type { Integer, Boolean }; Type type; enum Flag { HasSeparator = 1 }; unsigned flags; }; class Synth_Fx { public: Synth_Fx(); ~Synth_Fx(); void init(float sample_rate); void clear(); void compute(float data[], unsigned nframes); int get_parameter(size_t index) const; void set_parameter(size_t index, int value); static gsl::span<const Fx_Parameter> parameters(); enum { P_Bass_Enhance, P_Bass_Amount, P_Bass_Tone, P_Eq_Enable, P_Eq_Low, P_Eq_Mid_Low, P_Eq_Mid, P_Eq_Mid_High, P_Eq_High, P_Reverb_Enable, P_Reverb_Amount, P_Reverb_Size, Parameter_Count, }; private: std::unique_ptr<BassEnhance> be_; std::unique_ptr<Eq_5band> eq_; std::unique_ptr<Reverb> rev_; bool be_enable_ = false; bool eq_enable_ = false; bool rev_enable_ = false; };
{ "alphanum_fraction": 0.6333938294, "avg_line_length": 20.0363636364, "ext": "h", "hexsha": "b497dc42768732c0456378be01ecb537afa17896", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z", "max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "jpcima/smf-dsp", "max_forks_repo_path": "sources/player/instruments/synth_fx.h", "max_issues_count": 19, "max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "jpcima/smf-dsp", "max_issues_repo_path": "sources/player/instruments/synth_fx.h", "max_line_length": 54, "max_stars_count": 22, "max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "jpcima/smf-dsp", "max_stars_repo_path": "sources/player/instruments/synth_fx.h", "max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z", "num_tokens": 305, "size": 1102 }
#include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> #include <math.h> typedef struct{ double g;//gravity double M;//mass of the car double m;//mass of the load double r;//length of the rope double C;//damping coefficient double k;//spring constang double F;//input force double T;//tension to the rope // double FF;//Fictitious force double x,x0;//x position of the load double y,y0;//y position of the load double X;//X position of the car double a;//angle (theta) double dx,dx0; double dy,dy0; double dX,dX0; double dr; double da,da0; double dXmax; double ddXmax; double Fmax; double ddx; double ddy; double ddX; double ddr; double dda; double h; int nh; double _h; int _dim; double *_y; double *_y_err; double *_dydt_in; double *_dydt_out; const gsl_odeiv_step_type *_T; gsl_odeiv_step *_s; gsl_odeiv_system _sys; double _t; } CRANE; #define dim_crane 4 int cranefunc (double t, const double y[], double f[], void *params) { CRANE *c = (CRANE *)params; #ifdef ICONIP2014 //wrong dynamics f[0] = y[1]; f[1] = -c->k*(y[0]-y[2])/c->m - c->C*(y[1]-y[3])/c->m;//iconip2014 f[2] = y[3]; f[3] = (c->k*(y[0]-y[2]) + c->F)/c->M;//iconip2014 // f[0] = y[1]; // f[1] = -c->k*(y[0]-y[2])/c->m - c->C*(y[1]-y[3])/c->m; // f[2] = y[3]; // f[3] = (c->k*(y[0]-y[2]) + c->C*(y[1]-y[3] + c->F)/c->M; #else //corrected dynamics f[0] = y[1]; f[1] = (-c->k*(y[0]-y[2]) - c->C*(y[1]-y[3]) )/c->m;//iconip2014 f[2] = y[3]; f[3] = ( c->k*(y[0]-y[2]) + c->C*(y[1]-y[3]) + c->F)/c->M;//iconip2014 #endif // f[0] = y[1]; // f[1] = -c->k*y[0]/c->m - c->C*y[1]/c->m - c->ddX; // f[2] = y[3]; // f[3] = (c->k*y[0] + c->F)/c->M; // // f[0] = y[1]; // f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; // f[2] = y[3]; // f[3] = (c->F+c->T*sin(y[0]))/c->M; return GSL_SUCCESS; } //////////////// #define square(x) ((x)*(x)) CRANE crane; int initialize() { crane.g=9.8; crane.M=100; crane.m=20;//10;//20 crane.r=5;//5; crane.C=10;//5; crane.k=15;// crane.dr=crane.ddr=0; crane.x0=0; crane.y0=crane.r; crane.dx0=crane.dy0=crane.da0=0; crane.dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//?? crane.ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//?? crane.Fmax=30.0;//check// crane.Fmax=30;//check #ifdef CRANESUB crane.h=AP_tS; crane.m=_crane_m; crane.r=_crane_r; crane.C=_crane_C; crane.k=_crane_k;// crane.dXmax=_crane_dXmax; if(_AP_umax>0) AP_u_max=crane.ddXmax=_AP_umax; else AP_u_max=crane.ddXmax; AP_u_min=-AP_u_max; // starttime=0; // totaltime=50; rr=AP_r=_AP_r;//10 rr_kyoyou=_rr_kyoyou; // p=(double *)malloc(buffsize*sizeof(double)); C_MODE=11; // iteration=_iteration; #else crane.h=0.01; // crane.h=0.0001; #endif crane.nh=10; crane._h=crane.h/crane.nh;//0.001 crane._dim=4; if(crane._y==NULL){ crane._y=(double*)malloc(crane._dim*sizeof(double)); crane._y_err=(double*)malloc(crane._dim*sizeof(double)); crane._dydt_in=(double*)malloc(crane._dim*sizeof(double)); crane._dydt_out=(double*)malloc(crane._dim*sizeof(double)); } crane._T= gsl_odeiv_step_rk4; crane._s= gsl_odeiv_step_alloc (crane._T, crane._dim); crane._sys= (gsl_odeiv_system){cranefunc, NULL, crane._dim, &crane}; // crane._sys[0]=cranefunc; // crane._sys[1]=NULL; // crane._sys[2]=crane._dim; // crane._sys[3]=&crane; //initialize variables crane._t=crane._y[0]=crane._y[1]=crane._y[2]=crane._y[3]=0; // crane.FF=0; int i;for(i=0;i<crane._dim;i++) crane._dydt_in[i]=0; GSL_ODEIV_FN_EVAL(&(crane._sys), crane._t, crane._y, crane._dydt_in); // crane.a =crane._y[0]; // crane.da =crane._y[1]; // crane.X =crane._y[2]; // crane.dX =crane._y[3]; // crane.x =crane.X+crane.r * sin(crane.a); //output y // crane.y =crane.r*cos(crane.a); // crane.dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//?? // crane.ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//?? return(0); } #ifndef CRANESUB char *fn="crane3io.dat"; FILE *fp; #endif//#ifndef CRANESUB //double plant(double uu) double plant(double uu) { if(uu>crane.ddXmax) uu=crane.ddXmax; else if(uu<-crane.ddXmax) uu=-crane.ddXmax; int n; for(n=0;n<crane.nh;n++){ crane.ddX=uu;//crane.ddX=(uu<crane.ddXmax)?uu:crane.ddXmax; if(crane.dX>=crane.dXmax && crane.ddX>0) crane.ddX=0; else if(crane.dX<=-crane.dXmax && crane.ddX<0) crane.ddX=0; int status = gsl_odeiv_step_apply (crane._s, crane._t, crane._h, crane._y, crane._y_err, crane._dydt_in, crane._dydt_out, &crane._sys); if (status != GSL_SUCCESS) {fprintf(stderr,"### failure of plant calc.\n"); break;} int i;for(i=0;i<dim_crane;i++) crane._dydt_in[i]=crane._dydt_out[i]; crane._t+=crane._h; crane.x =crane._y[0]; crane.dx =crane._y[1]; crane.X =crane._y[2]; crane.dX =crane._y[3]; // crane.x =crane.X+crane.a; //output y // crane.dx=(crane.x-crane.x0)/crane._h; //crane.x =crane.X+crane.r * sin(crane.a); //output y //crane.y =crane.r*cos(crane.a); // crane.dx=(crane.x-crane.x0)/crane._h; // crane.dy=(crane.y-crane.y0)/crane._h; crane.ddx=(crane.dx-crane.dx0)/crane._h; // crane.ddX=(crane.dX-crane.dX0)/crane._h; // crane.ddy=(crane.dy-crane.dy0)/crane._h; // crane.T=crane.m*sqrt(square(crane.ddx)+square(crane.ddy-crane.g)); crane.F=crane.M*crane.ddX-crane.k*(crane.x-crane.X)-crane.C*(crane.dx-crane.dX);; // crane.F=crane.M*crane.ddX-crane.k*(crane.x-crane.X); // crane.F=crane.M*crane.ddX-crane.T*sin(crane.a); // crane.dda=(crane.da-crane.da0)/crane._h; crane.x0=crane.x;//? // crane.y0=crane.y; crane.dx0=crane.dx;//? // crane.dy0=crane.dy; // crane.da0=crane.da; // crane.FF=crane.ddX; crane.dX0=crane.dX; } #ifndef CRANESUB fprintf(fp,"%.7e %.7e %.7e", crane._t,crane._y[0],crane._y[1]);//crane.x,crane.dx fprintf(fp," %.7e %.7e %.7e" ,crane.X,crane.dX,crane.ddX); fprintf(fp," %.7e %.7e %.7e" ,crane.x,crane.dx,crane.ddx); fprintf(fp," %.7e %.7e %.7e" ,crane.y,crane.dy,crane.ddy); fprintf(fp," %.7e %.7e" ,crane.T,crane.F); fprintf(fp,"\n"); #endif //#ifndef CRANESUB return(crane.x);//crane.x in [0,AP_y=10?] ==> rt in [0,1] } #ifndef CRANESUB int main(int argc,char **argv) { //////////////////////////////////////////////////// /// method 1 /// /// input ddX /// /// output a,x,y,F /// //////////////////////////////////////////////////// // double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1; double T=5; double t0=0; //stationary double t1=T+t0;//accelerate(speed up) double t2=T+t1;//free run double t3=T+t2;//decelerate(slow down) double t4=t0+50; //free run initialize(); int M=(t4/crane.h)+1; double *ddX=(double*)malloc(sizeof(double)*M); // double *F =(double*)malloc(sizeof(double)*M); double Vmax=1;//dX/dt=1[m/s] //C:10;K:15;M:100;m:10;TS:0.5;/*数式処理の場合、この行を実行しない.m=10,40,70,100にして行う*/ /* crane.M=100; crane.C=10; crane.k=15; crane.m=10;*/ int i; for(i=1;i<argc;i++){ if(strncmp(argv[i],"m:",2)==0){ sscanf(&argv[i][2],"%lf",&crane.m); // fprintf(stderr,"#m=%g",crane.m); } } fprintf(stderr,"#C:%g K:%g M:%g m:%g\n",crane.C,crane.k,crane.M,crane.m); double TS=0.5; double umax=10; int n; double t; //////////////////////////////////////////////////// /// set ddX /// //////////////////////////////////////////////////// int n0 =t0/crane.h+0.5, n4=t4/crane.h+0.5; for(t=0;t<t4;t+=crane.h){ double u; n=t/crane.h; if(t<=t0) u=0; //zero else if(t<=t1) u=umax*0.8; //accelerate else if(t<=t2) u=0; //free move else if(t<=t3) u=-umax*0.8;//decelerate else u=0; //free move ddX[n]=u;//?? // ddX[n]=u*crane.h;//?? } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// fp=fopen(fn,"w"); fprintf(fp,"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\n",crane.h,n0,n4,crane.M,crane.m,crane.r,crane.C); // double dx0=0,dy0=0,da0=0; // for(n=0;n<n4;){ for(t=0;t<t4;t+=crane.h){ n=t/crane.h; plant(ddX[n]); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn); gsl_odeiv_step_free (crane._s); return 0; } #endif //#ifndef SUB
{ "alphanum_fraction": 0.5509491091, "avg_line_length": 30.0244755245, "ext": "c", "hexsha": "86f82db3e06c2fb93b230f8239890dd79e629a66", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "1021/mspc/crane3sub.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "1021/mspc/crane3sub.c", "max_line_length": 111, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "1021/mspc/crane3sub.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3406, "size": 8587 }
/** * \file FFT.h */ #ifndef ATK_UTILITY_FFT_H #define ATK_UTILITY_FFT_H #include <complex> #include <cstdint> #include <memory> #include <vector> #include <gsl/gsl> #include <ATK/Utility/config.h> namespace ATK { /// An FFT class template<class DataType_> class ATK_UTILITY_EXPORT FFT { public: /// Builds the wrapper class FFT(); /// Destructor ~FFT(); FFT(const FFT&) = delete; FFT& operator=(const FFT&) = delete; /*! * @brief Sets a new size for the FFT and creates an associated plan for it * @ size is the new size of the plan */ void set_size(gsl::index size); gsl::index get_size() const; /*! * @brief Processes a FFT from a real input array and stores it internally * @param input is the real input array of data to process * @param input_size is the size of the input array */ void process(const DataType_* input, gsl::index input_size) const; /*! * @brief Processes a FFT from a real input to a complex output * @param input is the real input array of data to process * @param output is the complex output array * @param input_size is the size of both input and output arrays */ void process_forward(const DataType_* input, std::complex<DataType_>* output, gsl::index input_size) const; /*! * @brief Processes an inverse FFT from a complex input to a real output * @param input is the complex input array of data to process * @param output is the real output array * @param input_size is the size of both input and output arrays */ void process_backward(const std::complex<DataType_>* input, DataType_* output, gsl::index input_size) const; /*! * @brief Processes a FFT from a complex input array and stores it internally * @param input is the real input array of data to process * @param input_size is the size of the input array */ void process(const std::complex<DataType_>* input, gsl::index input_size) const; /*! * @brief Processes a FFT from a complex input to a complex output * @param input is the real input array of data to process * @param output is the complex output array * @param input_size is the size of both input and output arrays */ void process_forward(const std::complex<DataType_>* input, std::complex<DataType_>* output, gsl::index input_size) const; /*! * @brief Processes an inverse FFT from a complex input to a complex output * @param input is the complex input array of data to process * @param output is the real output array * @param input_size is the size of both input and output arrays */ void process_backward(const std::complex<DataType_>* input, std::complex<DataType_>* output, gsl::index input_size) const; /*! * @brief Computes the amplitude of the resulting spectrum * @param amp is the output angle container */ void get_amp(std::vector<DataType_>& amp) const; /*! * @brief Computes the angle of the resulting spectrum * @param angle is the output angle container */ void get_angle(std::vector<DataType_>& angle) const; protected: gsl::index size; class FFTImpl; std::unique_ptr<FFTImpl> impl; }; } #endif
{ "alphanum_fraction": 0.6809947805, "avg_line_length": 33.2346938776, "ext": "h", "hexsha": "07cda16200e7694bd9929aa4912d13879849a80c", "lang": "C", "max_forks_count": 48, "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_path": "ATK/Utility/FFT.h", "max_issues_count": 22, "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_path": "ATK/Utility/FFT.h", "max_line_length": 126, "max_stars_count": 249, "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_path": "ATK/Utility/FFT.h", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "num_tokens": 792, "size": 3257 }
/* * Copyright (c) 2011-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * * @precisions normal z -> s d c * */ #include <math.h> #include <stdlib.h> #include <core_blas.h> #include <cblas.h> #include "dplasma.h" /* #define DEBUG_BUTTERFLY */ /* Forward declaration of kernels for the butterfly transformation */ void BFT_zQTL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ); void BFT_zQBL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ); void BFT_zQTR_trans( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans ); void BFT_zQTR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans); void BFT_zQBR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ); void RBMM_zTOP( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans, PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec); void RBMM_zBTM( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans, PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec); /* Bodies of kernels for the butterfly transformation */ void BFT_zQTL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ) { int i, j; (void)lvl; (void)N; #if defined(DEBUG_BUTTERFLY) printf ("BFT_zQTL(mb:%d, nb:%d, lda:%d, i_seg:%d, j_seg:%d, lvl:%d, N:%d, bl_is_tr_trans:%d, is_diagonal:%d)\n", mb, nb, lda, i_seg, j_seg, lvl, N, bl_is_tr_trans, is_diagonal); #endif if( bl_is_tr_trans ){ for (j=0; j<nb; j++) { int start = is_diagonal ? j : 0; for (i=start; i<mb; i++) { PLASMA_Complex64_t ri = U_before[i_seg+i]; PLASMA_Complex64_t rj = U_after[j_seg+j]; #if defined(DEBUG_BUTTERFLY) printf ("HE A[%d][%d] = U_before[%d]*((tl[%d]+bl[%d]) + (tr[%d]+br[%d])) * U_after[%d]\n", i_seg+i, j_seg+j, i_seg+i, j*lda+i, j*lda+i, i*lda+j, j*lda+i, j_seg+j); #endif C[j*lda+i] = ri * ((tl[j*lda+i]+bl[j*lda+i]) + (tr[i*lda+j]+br[j*lda+i])) * rj; #if defined(DEBUG_BUTTERFLY) printf ("HE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(ri), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(rj)); #endif } } }else{ for (j=0; j<nb; j++) { int start = is_diagonal ? j : 0; for (i=start; i<mb; i++) { PLASMA_Complex64_t ri = U_before[i_seg+i]; PLASMA_Complex64_t rj = U_after[j_seg+j]; #if defined(DEBUG_BUTTERFLY) printf ("GE A[%d][%d] = U_before[%d]*((tl[%d]+bl[%d]) + (tr[%d]+br[%d])) * U_after[%d]\n", i_seg+i, j_seg+j, i_seg+i, j*lda+i, j*lda+i, j*lda+i, j*lda+i, j_seg+j); #endif C[j*lda+i] = ri * ((tl[j*lda+i]+bl[j*lda+i]) + (tr[j*lda+i]+br[j*lda+i])) * rj; #if defined(DEBUG_BUTTERFLY) printf ("GE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(ri), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[j*lda+i]), creal(br[j*lda+i]), creal(rj)); #endif } } } return; } void BFT_zQBL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ) { int i, j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) if( is_diagonal ) printf ("BFT_zQBL(diag)\n"); else printf ("BFT_zQBL(lower)\n"); #endif if( bl_is_tr_trans ){ for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t si = U_before[i_seg+r_to_s+i]; PLASMA_Complex64_t rj = U_after[j_seg+j]; #if defined(DEBUG_BUTTERFLY) printf ("HE A[%d][%d] = U_before[%d]*((tl[%d]-bl[%d]) + (tr[%d]-br[%d])) * U_after[%d]\n", i_seg+i+r_to_s, j_seg+j, i_seg+r_to_s+i, j*lda+i, j*lda+i, i*lda+j, j*lda+i, j_seg+j); #endif if( is_diagonal && j>i ){ /* If the tile of the TL quarter is on the diagonal, then we need to take the transpose element for the tiles that came from TL and BR */ C[j*lda+i] = si * ((tl[i*lda+j]-bl[j*lda+i]) + (tr[i*lda+j]-br[i*lda+j])) * rj; } else{ C[j*lda+i] = si * ((tl[j*lda+i]-bl[j*lda+i]) + (tr[i*lda+j]-br[j*lda+i])) * rj; } #if defined(DEBUG_BUTTERFLY) printf ("HE %lf %lf %lf %lf %lf %lf %lf\n",creal(C[j*lda+i]), creal(si), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(rj)); #endif } } }else{ for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t si = U_before[i_seg+r_to_s+i]; PLASMA_Complex64_t rj = U_after[j_seg+j]; #if defined(DEBUG_BUTTERFLY) printf ("GE A[%d][%d] = U_before[%d]*((tl[%d]-bl[%d]) + (tr[%d]-br[%d])) * U_after[%d]\n", i_seg+i+r_to_s, j_seg+j, i_seg+r_to_s+i, j*lda+i, j*lda+i, j*lda+i, j*lda+i, j_seg+j); #endif C[j*lda+i] = si * ((tl[j*lda+i]-bl[j*lda+i]) + (tr[j*lda+i]-br[j*lda+i])) * rj; #if defined(DEBUG_BUTTERFLY) printf ("GE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(si), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[j*lda+i]), creal(br[j*lda+i]), creal(rj)); #endif } } } return; } /* This function writes into a transposed tile, so C is always transposed. */ void BFT_zQTR_trans( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans ) { int i,j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) printf ("BFT_zQTR_trans()\n"); #endif if( bl_is_tr_trans ){ for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t ri = U_before[i_seg+i]; PLASMA_Complex64_t sj = U_after[j_seg+r_to_s+j]; #if defined(DEBUG_BUTTERFLY) printf ("HE A[%d][%d] = U_before[%d]*((tl[%d]+bl[%d]) - (tr[%d]+br[%d])) * U_after[%d]\n", i_seg+j, j_seg+i+r_to_s, i_seg+i, j*lda+i, j*lda+i, i*lda+j, j*lda+i, j_seg+r_to_s+j); #endif C[i*lda+j] = ri * ((tl[j*lda+i]+bl[j*lda+i]) - (tr[i*lda+j]+br[j*lda+i])) * sj; #if defined(DEBUG_BUTTERFLY) printf ("HE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[i*lda+j]), creal(ri), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(sj)); #endif } } }else{ assert(0); // This should never happen. } return; } void BFT_zQTR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans ) { int i, j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) printf ("BFT_zQTR()\n"); #endif if( bl_is_tr_trans ){ for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t ri = U_before[i_seg+i]; PLASMA_Complex64_t sj = U_after[j_seg+r_to_s+j]; #if defined(DEBUG_BUTTERFLY) printf ("HE A[%d][%d] = U_before[%d]*((tl[%d]+bl[%d]) - (tr[%d]+br[%d])) * U_after[%d]\n", i_seg+i, j_seg+j+r_to_s, i_seg+i, j*lda+i, j*lda+i, i*lda+j, j*lda+i, j_seg+r_to_s+j); #endif C[j*lda+i] = ri * ((tl[j*lda+i]+bl[j*lda+i]) - (tr[i*lda+j]+br[j*lda+i])) * sj; #if defined(DEBUG_BUTTERFLY) printf ("HE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(ri), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(sj)); #endif } } }else{ for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t ri = U_before[i_seg+i]; PLASMA_Complex64_t sj = U_after[j_seg+r_to_s+j]; #if defined(DEBUG_BUTTERFLY) printf ("GE A[%d][%d] = U_before[%d]*((tl[%d]+bl[%d]) - (tr[%d]+br[%d])) * U_after[%d]\n", i_seg+i, j_seg+j+r_to_s, i_seg+i, j*lda+i, j*lda+i, j*lda+i, j*lda+i, j_seg+r_to_s+j); #endif C[j*lda+i] = ri * ((tl[j*lda+i]+bl[j*lda+i]) - (tr[j*lda+i]+br[j*lda+i])) * sj; #if defined(DEBUG_BUTTERFLY) printf ("GE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(ri), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[j*lda+i]), creal(br[j*lda+i]), creal(sj)); #endif } } } return; } void BFT_zQBR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N, PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl, PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal ) { int i, j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) if( is_diagonal ) printf ("BFT_zQBR(diag)\n"); else printf ("BFT_zQBR(lower)\n"); #endif if( bl_is_tr_trans ){ for (j=0; j<nb; j++) { int start = is_diagonal ? j : 0; for (i=start; i<mb; i++) { PLASMA_Complex64_t si = U_before[i_seg+r_to_s+i]; PLASMA_Complex64_t sj = U_after[j_seg+r_to_s+j]; #if defined(DEBUG_BUTTERFLY) printf ("HE A[%d][%d] = U_before[%d]*((tl[%d]-bl[%d]) - (tr[%d]-br[%d])) * U_after[%d]\n", i_seg+i+r_to_s, j_seg+j+r_to_s, i_seg+r_to_s+i, j*lda+i, j*lda+i, i*lda+j, j*lda+i, j_seg+r_to_s+j); #endif C[j*lda+i] = si * ((tl[j*lda+i]-bl[j*lda+i]) - (tr[i*lda+j]-br[j*lda+i])) * sj; #if defined(DEBUG_BUTTERFLY) printf ("HE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(si), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(sj)); #endif } } }else{ for (j=0; j<nb; j++) { int start = is_diagonal ? j : 0; for (i=start; i<mb; i++) { PLASMA_Complex64_t si = U_before[i_seg+r_to_s+i]; PLASMA_Complex64_t sj = U_after[j_seg+r_to_s+j]; #if defined(DEBUG_BUTTERFLY) printf ("GE A[%d][%d] = U_before[%d]*((tl[%d]-bl[%d]) - (tr[%d]-br[%d])) * U_after[%d]\n", i_seg+i+r_to_s, j_seg+j+r_to_s, i_seg+r_to_s+i, j*lda+i, j*lda+i, j*lda+i, j*lda+i, j_seg+r_to_s+j); #endif C[j*lda+i] = si * ((tl[j*lda+i]-bl[j*lda+i]) - (tr[j*lda+i]-br[j*lda+i])) * sj; #if defined(DEBUG_BUTTERFLY) printf ("GE %lf %lf %lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(si), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[j*lda+i]), creal(br[j*lda+i]), creal(sj)); #endif } } } return; } void RBMM_zTOP( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans, PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec) { int i, j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) printf ("RBMM_zTOP()\n"); #endif for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t r = U_but_vec[i_seg+i]; if( PlasmaConjTrans == trans ){ #if defined(DEBUG_BUTTERFLY) printf ("C[%d] = U_but_vec[%d]*(top[%d]+btm[%d])\n", j*lda+i, i_seg+i, j*lda+i, j*lda+i); #endif C[j*lda+i] = r * (top[j*lda+i] + btm[j*lda+i]); #if defined(DEBUG_BUTTERFLY) printf ("%lf %lf %lf %lf\n",creal(C[j*lda+i]), creal(r), creal(top[j*lda+i]), creal(btm[j*lda+i])); #endif }else{ PLASMA_Complex64_t s = U_but_vec[i_seg+r_to_s+i]; #if defined(DEBUG_BUTTERFLY) printf ("C[%d] = U_but_vec[%d]*top[%d] + U_but_vec[%d]*btm[%d]\n", j*lda+i, i_seg+i, j*lda+i, i_seg+r_to_s+i, j*lda+i); #endif C[j*lda+i] = r*top[j*lda+i] + s*btm[j*lda+i]; #if defined(DEBUG_BUTTERFLY) printf ("%lf %lf %lf %lf %lf\n",creal(C[j*lda+i]), creal(r), creal(top[j*lda+i]), creal(s), creal(btm[j*lda+i])); #endif } } } return; } void RBMM_zBTM( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans, PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm, PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec) { int i, j; int r_to_s = N/(1<<(lvl+1)); #if defined(DEBUG_BUTTERFLY) printf ("RBMM_zBTM()\n"); #endif for (j=0; j<nb; j++) { for (i=0; i<mb; i++) { PLASMA_Complex64_t s = U_but_vec[i_seg+r_to_s+i]; if( PlasmaConjTrans == trans ){ #if defined(DEBUG_BUTTERFLY) printf ("C[%d] = U_but_vec[%d]*(top[%d]-btm[%d])\n", j*lda+i, i_seg+r_to_s+i, j*lda+i, j*lda+i); #endif C[j*lda+i] = s * (top[j*lda+i] - btm[j*lda+i]); #if defined(DEBUG_BUTTERFLY) printf ("%lf %lf %lf %lf\n",creal(C[j*lda+i]), creal(s), creal(top[j*lda+i]), creal(btm[j*lda+i])); #endif }else{ PLASMA_Complex64_t r = U_but_vec[i_seg+i]; #if defined(DEBUG_BUTTERFLY) printf ("C[%d] = U_but_vec[%d]*top[%d] - U_but_vec[%d]*btm[%d]\n", j*lda+i, i_seg+i, j*lda+i, i_seg+r_to_s+i, j*lda+i); #endif C[j*lda+i] = r*top[j*lda+i] - s*btm[j*lda+i]; #if defined(DEBUG_BUTTERFLY) printf ("%lf %lf %lf %lf %lf\n", creal(C[j*lda+i]), creal(r), creal(top[j*lda+i]), creal(s), creal(btm[j*lda+i])); #endif } } } return; }
{ "alphanum_fraction": 0.5677927782, "avg_line_length": 45.0029069767, "ext": "c", "hexsha": "70fdfbe4b7de356f653d50d0669e6e351b005dde", "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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/cores/core_zhebut.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/cores/core_zhebut.c", "max_line_length": 207, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/cores/core_zhebut.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 5545, "size": 15481 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_statistics.h> /* number of data points to fit */ #define N 200 /* number of fit coefficients */ #define NCOEFFS 12 /* nbreak = ncoeffs + 2 - k = ncoeffs - 2 since k = 4 */ #define NBREAK (NCOEFFS - 2) int main (void) { const size_t n = N; const size_t ncoeffs = NCOEFFS; const size_t nbreak = NBREAK; size_t i, j; gsl_bspline_workspace *bw; gsl_vector *B; double dy; gsl_rng *r; gsl_vector *c, *w; gsl_vector *x, *y; gsl_matrix *X, *cov; gsl_multifit_linear_workspace *mw; double chisq, Rsq, dof, tss; gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_default); /* allocate a cubic bspline workspace (k = 4) */ bw = gsl_bspline_alloc(4, nbreak); B = gsl_vector_alloc(ncoeffs); x = gsl_vector_alloc(n); y = gsl_vector_alloc(n); X = gsl_matrix_alloc(n, ncoeffs); c = gsl_vector_alloc(ncoeffs); w = gsl_vector_alloc(n); cov = gsl_matrix_alloc(ncoeffs, ncoeffs); mw = gsl_multifit_linear_alloc(n, ncoeffs); /* this is the data to be fitted */ for (i = 0; i < n; ++i) { double sigma; double xi = (15.0 / (N - 1)) * i; double yi = cos(xi) * exp(-0.1 * xi); sigma = 0.1 * yi; dy = gsl_ran_gaussian(r, sigma); yi += dy; gsl_vector_set(x, i, xi); gsl_vector_set(y, i, yi); gsl_vector_set(w, i, 1.0 / (sigma * sigma)); printf("%f %f\n", xi, yi); } /* use uniform breakpoints on [0, 15] */ gsl_bspline_knots_uniform(0.0, 15.0, bw); /* construct the fit matrix X */ for (i = 0; i < n; ++i) { double xi = gsl_vector_get(x, i); /* compute B_j(xi) for all j */ gsl_bspline_eval(xi, B, bw); /* fill in row i of X */ for (j = 0; j < ncoeffs; ++j) { double Bj = gsl_vector_get(B, j); gsl_matrix_set(X, i, j, Bj); } } /* do the fit */ gsl_multifit_wlinear(X, w, y, c, cov, &chisq, mw); dof = n - ncoeffs; tss = gsl_stats_wtss(w->data, 1, y->data, 1, y->size); Rsq = 1.0 - chisq / tss; fprintf(stderr, "chisq/dof = %e, Rsq = %f\n", chisq / dof, Rsq); printf("\n\n"); /* output the smoothed curve */ { double xi, yi, yerr; for (xi = 0.0; xi < 15.0; xi += 0.1) { gsl_bspline_eval(xi, B, bw); gsl_multifit_linear_est(B, c, cov, &yi, &yerr); printf("%f %f\n", xi, yi); } } gsl_rng_free(r); gsl_bspline_free(bw); gsl_vector_free(B); gsl_vector_free(x); gsl_vector_free(y); gsl_matrix_free(X); gsl_vector_free(c); gsl_vector_free(w); gsl_matrix_free(cov); gsl_multifit_linear_free(mw); return 0; } /* main() */
{ "alphanum_fraction": 0.5858514042, "avg_line_length": 22.504, "ext": "c", "hexsha": "311be68f7e0d206d12e29a2b11a042d899cb003b", "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/bspline.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/bspline.c", "max_line_length": 56, "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/bspline.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": 959, "size": 2813 }
//===--- Sudoku/Solver_find.h ---===// // // Helper functions, to find available options //===----------------------------------------------------------------------===// // list_where_* // appearance_*: collecting options by appearance count in a given set. //===----------------------------------------------------------------------===// #pragma once #include "Board_Section_traits.h" #include "Location.h" #include "Options.h" #include "Size.h" #include "Value.h" #include "traits.h" #include <gsl/gsl> #include <array> #include <vector> #include <algorithm> // find, find_if #include <iterator> #include <type_traits> // is_base_of #include "Board.fwd.h" // Forward declarations #include <cassert> namespace Sudoku { //===----------------------------------------------------------------------===// template<int N, typename SectionT> [[nodiscard]] auto list_where_option(SectionT, Value, ptrdiff_t rep_count = elem_size<N>); template<int N, typename ItrT> [[nodiscard]] auto list_where_option(ItrT begin, ItrT end, Value, ptrdiff_t rep_count = 0); template<int N, typename SectionT, typename Options = Options<elem_size<N>>> [[nodiscard]] auto list_where_option(const SectionT, const Options sample) noexcept(true); template<int N, typename SectionT, typename Options = Options<elem_size<N>>> [[nodiscard]] auto list_where_equal(SectionT, Options sample) noexcept(true); template<int N, typename Options = Options<elem_size<N>>> [[nodiscard]] auto list_where_subset(const Board<Options, N>&, const Options) noexcept(true); template<int N, typename SectionT, typename Options = Options<elem_size<N>>> [[nodiscard]] auto list_where_subset(const SectionT, const Options) noexcept(true); template<int N, typename SectionT, typename Options = Options<elem_size<N>>> [[nodiscard]] auto list_where_any_option(const SectionT, const Options sample) noexcept(true); template<int N, typename Options = Options<elem_size<N>>, typename SectionT> [[nodiscard]] Options appearance_once(SectionT section) noexcept; template<int N, typename Options = Options<elem_size<N>>, typename InItr_> [[nodiscard]] Options appearance_once(const InItr_ begin, const InItr_ end) noexcept; template<int N, typename SectionT> [[nodiscard]] auto appearance_sets(const SectionT section); template<int N, typename InItr_> [[nodiscard]] auto appearance_sets(const InItr_ begin, const InItr_ end); //===----------------------------------------------------------------------===// // List locations in [section] where [value] is an option template<int N, typename SectionT> inline auto list_where_option( const SectionT section, Value value, const ptrdiff_t rep_count /*= elem_size<N>*/) { { static_assert(Board_Section::traits::is_Section_v<SectionT>); assert(rep_count > 0 && rep_count <= elem_size<N>); } const auto begin = section.cbegin(); const auto end = section.cend(); return list_where_option<N>(begin, end, value, rep_count); } // List locations where [value] is an option template<int N, typename ItrT> auto list_where_option( const ItrT begin, const ItrT end, const Value value, ptrdiff_t rep_count /*= 0*/) { using Options = Options<elem_size<N>>; { static_assert(traits::is_input<ItrT>); static_assert( traits::iterator_to<ItrT, const Options> || traits::iterator_to<ItrT, Options>); assert(is_valid<N>(value)); if (rep_count == 0) rep_count = std::distance(begin, end); else assert(rep_count > 0 && rep_count <= std::distance(begin, end)); } std::vector<Location<N>> locations{}; locations.reserve(gsl::narrow_cast<size_t>(rep_count)); const auto check_option = [value](Options O) { return is_option(O, value); }; #if true // slightly faster, it saves one run of find_if on each execution, // but rep_count can be too small auto itr = begin; for (gsl::index i{0}; i < rep_count; ++i) { itr = std::find_if(itr, end, check_option); if (itr == end) { // rep_count too large break; } locations.push_back(itr.location()); ++itr; } assert( // rep_count not too low itr == end || std::find_if(itr, end, check_option) == end); #else for (auto last{std::find_if(begin, end, check_option)}; last != end; last = std::find_if(last, end, check_option)) { locations.push_back(last.location()); ++last; } assert( // rep_count not too low locations.size() <= gsl::narrow_cast<size_t>(rep_count)); #endif return locations; } // List locations in [section] containing [sample] template<int N, typename SectionT, typename Options> auto list_where_option( // NOLINT(bugprone-exception-escape) const SectionT section, const Options sample) noexcept(true) { // vector creation and growth could potentially throw, out of memory. { static_assert(Board_Section::traits::is_Section_v<SectionT>); } std::vector<Location<N>> locations{}; locations.reserve(size_t{elem_size<N>}); const auto check_option = [sample](Options O) noexcept { return sample == shared(O, sample); }; const auto end = section.cend(); for (auto last{std::find_if(section.cbegin(), end, check_option)}; last != end; last = std::find_if(last, end, check_option)) { if (!is_answer_fast(*last)) { locations.push_back(last.location()); } ++last; } return locations; } // List locations in [section] equal to [sample] template<int N, typename SectionT, typename Options> auto list_where_equal( // NOLINT(bugprone-exception-escape) const SectionT section, const Options sample) noexcept(true) { // vector creation and growth could potentially throw, out of memory. { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<typename SectionT::value_type, Options>); } std::vector<Location<N>> locations{}; locations.reserve(size_t{elem_size<N>}); const auto end = section.cend(); for (auto last{std::find(section.cbegin(), end, sample)}; last != end; last = std::find(last, end, sample)) { locations.push_back(last.location()); ++last; } return locations; } // All locations where available options are a subset of the sample. template<int N, typename Options> auto list_where_subset( // NOLINT(bugprone-exception-escape) const Board<Options, N>& board, const Options sample) noexcept(true) { // vector creation and growth could potentially throw, out of memory. using Location = Location<N>; std::vector<Location> list{}; list.reserve(sample.count()); // minimum for (int i{}; i < full_size<N>; ++i) { const auto& other = board[Location(i)]; if (!is_answer_fast(other) && // exclude processed answers (other == sample || shared(sample, other) == other)) { list.push_back(Location(i)); } } return list; } // All locations where available options are a subset of the sample. template<int N, typename SectionT, typename Options> auto list_where_subset( // NOLINT(bugprone-exception-escape) const SectionT section, const Options sample) noexcept(true) { // vector creation and growth could potentially throw, out of memory. { static_assert(Board_Section::traits::is_Section_v<SectionT>); } using Location = Location<N>; std::vector<Location> list{}; list.reserve(sample.count()); const auto end = section.cend(); for (auto itr = section.cbegin(); itr != end; ++itr) { const auto& other = *itr; if (!is_answer_fast(other) && // exclude processed answers (other == sample || shared(sample, other) == other)) { list.push_back(itr.location()); } } return list; } // All locations containing an option present in [sample] template<int N, typename SectionT, typename Options> auto list_where_any_option( // NOLINT(bugprone-exception-escape) const SectionT section, const Options sample) noexcept(true) { // vector creation and growth could potentially throw, out of memory. { static_assert(Board_Section::traits::is_Section_v<SectionT>); } using Location = Location<N>; std::vector<Location> locations{}; locations.reserve(sample.count_all()); const auto check_option = [sample](Options O) noexcept { return is_answer_fast(O) ? false : !(shared(O, sample).count_all() == 0u); }; const auto end = section.cend(); for (auto itr{std::find_if(section.cbegin(), end, check_option)}; itr != end; itr = std::find_if(itr, end, check_option)) { locations.push_back(itr.location()); ++itr; } return locations; } //===----------------------------------------------------------------------===// // returning options collected by appearance count in input-dataset template<int N, typename InItr_> auto appearance_sets(const InItr_ begin, const InItr_ end) { // clang-format off /* Example illustration Step 1) Collect input worker[n] | [0] | [1] | [2] | [3] 1 100 000 001 | 100 000 001 | 000 000 000 | | 2 110 100 010 | 110 100 011 | 100 000 000 | 000 000 000 | 3 010 000 011 | 110 100 011 | 110 000 011 | 000 000 000 | 000 000 000 4 000 000 011 | 110 100 011 | 110 000 011 | 000 000 011 | 000 000 000 5 101 100 111 | 111 100 111 | 110 100 011 | 100 000 011 | 000 000 011 6 A 000 001 000 | 111 101 111 | 110 101 011 | 100 001 011 | 000 001 011 7 101 100 110 | 111 101 111 | 111 101 111 | 100 101 011 | 100 001 011 8 100 110 010 | 111 111 111 | 111 101 111 | 100 101 011 | 100 101 011 9 010 000 101 | | 111 101 111 | 110 101 111 | 100 101 011 worker[n] contains options appearing more than n times Step 2) flip | 000 000 000 | 000 010 000 | 001 010 000 | 011 010 100 532 419 365 | ==0x | ==1x | <=2x | <=3x worker[n] contains options appearing n times or less Step 3) XOR [n-1] | == empty! | 000 010 000 | 001 000 000 | 010 000 100 | ==0x | ==1x | ==2x | ==3x worker[n] contains options appearing exactly n times // Q: What about the answer bit? // A: Always true (==not answered) //? Working with more or less than [elem_size] input elements? // Less than 9: possible worker[0] is not empty // Less than 3: no use for worker[3] // More than 9: shouldn't be an issue */ // clang-format on using Options = Options<elem_size<N>>; { static_assert( traits::iterator_to<InItr_, Options> || traits::iterator_to<InItr_, const Options>); } // To limit processing time, counting up to N constexpr auto max = size_t{N}; // default: (9x9 board) up-to 3 times std::array<Options, max + 1> worker{}; worker.fill(Options(Value{0})); // Collect options by appearance count // worker[n] contains options appearing more than n times (or answer) for (auto elem_itr = begin; elem_itr != end; ++elem_itr) { if (is_answer(*elem_itr)) { // add answer to all for (auto& set : worker) { set += *elem_itr; } // OR } else { for (size_t i{max}; i > 0; --i) { worker.at(i) += (worker.at(i - 1) & *elem_itr); // OR( AND ) } worker[0] += *elem_itr; // OR } } // flip -> worker[n] contains options appearing n times or less for (auto& option_set : worker) { option_set.flip(); } // TODO test: can trigger on partial sections; improve? // fails if not all options exist assert(worker[0].count_all() == 0); // XOR -> worker[n] options appearing n times for (size_t i{max}; i > 1; --i) { worker.at(i).XOR(worker.at(i - 1)); worker.at(i) += Options(Value{0}); // set not-answered } return worker; } // returning options collected by appearance count in section template<int N, typename SectionT> inline auto appearance_sets(const SectionT section) { // referral function, creates iterators return appearance_sets<N>(section.cbegin(), section.cend()); } // return a mask for values with a single appearance template<int N, typename Options, typename InItr_> Options appearance_once(const InItr_ begin, const InItr_ end) noexcept { { static_assert(traits::is_input<InItr_>); static_assert( traits::iterator_to<InItr_, Options> || traits::iterator_to<InItr_, const Options>); } Options sum(Value{0}); // helper all used Options worker(Value{0}); // multiple uses OR answer for (auto itr = begin; itr != end; ++itr) { if (is_answer(*itr)) { worker = *itr + worker; } else { worker += (sum & *itr); sum += *itr; } } return worker.flip(); // multiple uses -> single-use } // range-based-for template<int N, typename Options, typename SectionT> Options appearance_once(SectionT section) noexcept { { static_assert(Board_Section::traits::is_Section_v<SectionT>); static_assert(std::is_same_v<typename SectionT::value_type, Options>); } Options sum(Value{0}); // helper all used Options worker(Value{0}); // multiple uses OR answer for (const Options& item : section) { if (is_answer(item)) { worker = item + worker; // OR } else { worker += (sum & item); // OR ( AND ) sum += item; } } return worker.flip(); // multiple uses -> single-use } } // namespace Sudoku
{ "alphanum_fraction": 0.671018685, "avg_line_length": 29.5404157044, "ext": "h", "hexsha": "40220c9e98da207c1b2afda7dcb8c18233b786a8", "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": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_path": "Sudoku/Sudoku/Solvers_find.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "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": "FeodorFitsner/fwkSudoku", "max_issues_repo_path": "Sudoku/Sudoku/Solvers_find.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_path": "Sudoku/Sudoku/Solvers_find.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3552, "size": 12791 }
/* FRACTAL - A program growing fractals to benchmark parallelization and drawing libraries. Copyright 2009-2021, Javier Burguete Tolosa. 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 Javier Burguete Tolosa ``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 Javier Burguete Tolosa 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 simulator.c * \brief Source file to define the windows data and functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2009-2021, Javier Burguete Tolosa. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <gsl/gsl_rng.h> #include <glib.h> #include <libintl.h> #include <png.h> #include <ft2build.h> #include FT_FREETYPE_H #include <gtk/gtk.h> #include <GL/glew.h> #if HAVE_FREEGLUT #include <GL/freeglut.h> #elif HAVE_SDL #include <SDL.h> #elif HAVE_GLFW #include <GLFW/glfw3.h> extern GLFWwindow *window; #endif #include "config.h" #include "fractal.h" #include "image.h" #include "text.h" #include "graphic.h" #include "draw.h" #include "simulator.h" #if HAVE_SDL SDL_Event exit_event[1]; #endif static float phid = -45.; ///< Horizontal perspective angle (in degrees). static float thetad = 80.; ///< Vertical perspective angle (in degrees). /** * Function the set the perspective of a point. */ static void perspective (int x, ///< Point x-coordinate. int y, ///< Point y-coordinate. int z, ///< Point z-coordinate. float *X, ///< Perspective X-coordinate. float *Y) ///< Perspective Y-coordinate. { float cp, sp, st, ct; sincosf (graphic->phi, &sp, &cp); sincosf (graphic->theta, &st, &ct); *X = x * cp - y * sp; *Y = z * st + (y * cp + x * sp) * ct; } /** * Function to set the view perspective. */ static void set_perspective () { float k1, k2; phid = gtk_range_get_value (GTK_RANGE (dialog_simulator->hscale)); thetad = gtk_range_get_value (GTK_RANGE (dialog_simulator->vscale)); graphic->phi = phid * M_PI / 180.; graphic->theta = thetad * M_PI / 180.; if (fractal_3D) { perspective (0, 0, 0, &k1, &k2); graphic->xmin = k1; perspective (length, width, 0, &k1, &k2); graphic->xmax = k1; perspective (length, 0, 0, &k1, &k2); graphic->ymin = k2; perspective (0, width, height, &k1, &k2); graphic->ymax = k2; } draw (); } /** * Function to show an error message */ void show_error (const char *message) ///< Error message string. { GtkMessageDialog *dlg; dlg = (GtkMessageDialog *) gtk_message_dialog_new (dialog_simulator->window, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", message); #if !GTK4 gtk_widget_show_all (GTK_WIDGET (dlg)); g_signal_connect_swapped (dlg, "response", G_CALLBACK (gtk_widget_destroy), GTK_WIDGET (dlg)); #else gtk_widget_show (GTK_WIDGET (dlg)); g_signal_connect_swapped (dlg, "response", G_CALLBACK (gtk_window_destroy), GTK_WINDOW (dlg)); #endif } /** * Function to update the enabled fractal characteristics. */ static void dialog_options_update () { int i; DialogOptions *dlg = dialog_options; i = gtk_check_button_get_active (dlg->button_3D); gtk_widget_set_sensitive (GTK_WIDGET (dlg->label_length), i); gtk_widget_set_sensitive (GTK_WIDGET (dlg->entry_length), i); for (i = 0; i < N_RANDOM_SEED_TYPES; ++i) if (gtk_check_button_get_active (dlg->array_seeds[i])) break; i = (i == RANDOM_SEED_TYPE_FIXED) ? 1 : 0; gtk_widget_set_sensitive (GTK_WIDGET (dlg->label_seed), i); gtk_widget_set_sensitive (GTK_WIDGET (dlg->entry_seed), i); } /** * Function to close a dialog to set the fractal options. */ static void dialog_options_close (DialogOptions * dlg, ///< DialogOptions struct. int response_id) ///< Response identifier. { unsigned int i; if (response_id == GTK_RESPONSE_OK) { fractal_diagonal = gtk_check_button_get_active (dlg->button_diagonal); fractal_3D = gtk_check_button_get_active (dlg->button_3D); for (i = 0; i < N_FRACTAL_TYPES; ++i) if (gtk_check_button_get_active (dlg->array_fractals[i])) fractal_type = i; length = gtk_spin_button_get_value_as_int (dlg->entry_length); width = gtk_spin_button_get_value_as_int (dlg->entry_width); height = gtk_spin_button_get_value_as_int (dlg->entry_height); #if HAVE_GTKGLAREA gtk_widget_set_size_request (GTK_WIDGET (dialog_simulator->gl_area), width, height); #endif random_seed = gtk_spin_button_get_value_as_int (dlg->entry_seed); nthreads = gtk_spin_button_get_value_as_int (dlg->entry_nthreads); animating = gtk_check_button_get_active (dlg->button_animate); for (i = 0; i < N_RANDOM_TYPES; ++i) if (gtk_check_button_get_active (dlg->array_algorithms[i])) random_algorithm = i; for (i = 0; i < N_RANDOM_SEED_TYPES; ++i) if (gtk_check_button_get_active (dlg->array_seeds[i])) random_seed_type = i; medium_start (); set_perspective (); breaking = 1; } else if (response_id == GTK_RESPONSE_CANCEL); else return; #if !GTK4 gtk_widget_destroy (GTK_WIDGET (dlg->dialog)); #else gtk_window_destroy (GTK_WINDOW (dlg->dialog)); #endif } /** * Function to create a dialog to set the fractal options. */ static void dialog_options_create () { unsigned int i; const char *array_fractals[N_FRACTAL_TYPES] = { _("_Tree"), _("_Forest"), _("_Neuron") }; const char *array_algorithms[N_RANDOM_TYPES] = { "_mt19937", "_ranlxs0", "r_anlxs1", "ra_nlxs2", "ran_lxd1", "ranlx_d2", "ranlu_x", "ranlux_389", "_cmrg", "mr_g", "_taus2", "g_fsr4" }; const char *array_seeds[N_RANDOM_SEED_TYPES] = { _("_Default"), _("_Clock based"), _("_Fixed") }; DialogOptions *dlg = dialog_options; #if !GTK4 GtkContainer *content; #else GtkBox *content; #endif dlg->button_diagonal = (GtkCheckButton *) gtk_check_button_new_with_mnemonic (_("_Diagonal movement")); dlg->button_3D = (GtkCheckButton *) gtk_check_button_new_with_mnemonic ("3_D"); g_signal_connect (dlg->button_3D, "clicked", dialog_options_update, NULL); dlg->label_length = (GtkLabel *) gtk_label_new (_("Length")); dlg->label_width = (GtkLabel *) gtk_label_new (_("Width")); dlg->label_height = (GtkLabel *) gtk_label_new (_("Height")); dlg->label_seed = (GtkLabel *) gtk_label_new (_("Random seed")); dlg->label_nthreads = (GtkLabel *) gtk_label_new (_("Threads number")); dlg->entry_length = (GtkSpinButton *) gtk_spin_button_new_with_range (32., 2400., 1.); dlg->entry_width = (GtkSpinButton *) gtk_spin_button_new_with_range (32., 2400., 1.); dlg->entry_height = (GtkSpinButton *) gtk_spin_button_new_with_range (20., 2400., 1.); dlg->entry_seed = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 4294967295., 1.); dlg->entry_nthreads = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 64., 1.); dlg->grid_fractal = (GtkGrid *) gtk_grid_new (); dlg->array_fractals[0] = NULL; for (i = 0; i < N_FRACTAL_TYPES; ++i) { #if !GTK4 dlg->array_fractals[i] = (GtkRadioButton *) gtk_radio_button_new_with_mnemonic_from_widget (dlg->array_fractals[0], array_fractals[i]); #else dlg->array_fractals[i] = (GtkCheckButton *) gtk_check_button_new_with_mnemonic (array_fractals[i]); gtk_check_button_set_group (dlg->array_fractals[i], dlg->array_fractals[0]); #endif gtk_grid_attach (dlg->grid_fractal, GTK_WIDGET (dlg->array_fractals[i]), 0, i, 1, 1); } gtk_check_button_set_active (dlg->array_fractals[fractal_type], 1); dlg->frame_fractal = (GtkFrame *) gtk_frame_new (_("Fractal type")); gtk_frame_set_child (dlg->frame_fractal, GTK_WIDGET (dlg->grid_fractal)); dlg->button_animate = (GtkCheckButton *) gtk_check_button_new_with_mnemonic (_("_Animate")); gtk_check_button_set_active (dlg->button_animate, animating); dlg->grid_algorithm = (GtkGrid *) gtk_grid_new (); dlg->array_algorithms[0] = NULL; for (i = 0; i < N_RANDOM_TYPES; ++i) { #if !GTK4 dlg->array_algorithms[i] = (GtkRadioButton *) gtk_radio_button_new_with_mnemonic_from_widget (dlg->array_algorithms[0], array_algorithms[i]); #else dlg->array_algorithms[i] = (GtkCheckButton *) gtk_check_button_new_with_mnemonic (array_algorithms[i]); gtk_check_button_set_group (dlg->array_algorithms[i], dlg->array_algorithms[0]); #endif gtk_grid_attach (dlg->grid_algorithm, GTK_WIDGET (dlg->array_algorithms[i]), 0, i, 1, 1); } gtk_check_button_set_active (dlg->array_algorithms[random_algorithm], 1); dlg->frame_algorithm = (GtkFrame *) gtk_frame_new (_("Random algorithm")); gtk_frame_set_child (dlg->frame_algorithm, GTK_WIDGET (dlg->grid_algorithm)); dlg->grid_seed = (GtkGrid *) gtk_grid_new (); dlg->array_seeds[0] = NULL; for (i = 0; i < N_RANDOM_SEED_TYPES; ++i) { #if !GTK4 dlg->array_seeds[i] = (GtkRadioButton *) gtk_radio_button_new_with_mnemonic_from_widget (dlg->array_seeds[0], array_seeds[i]); #else dlg->array_seeds[i] = (GtkCheckButton *) gtk_check_button_new_with_mnemonic (array_seeds[i]); gtk_check_button_set_group (dlg->array_seeds[i], dlg->array_seeds[0]); #endif gtk_grid_attach (dlg->grid_seed, GTK_WIDGET (dlg->array_seeds[i]), 0, i, 1, 1); g_signal_connect (dlg->array_seeds[i], "clicked", dialog_options_update, NULL); } gtk_check_button_set_active (dlg->array_seeds[random_seed_type], 1); dlg->frame_seed = (GtkFrame *) gtk_frame_new (_("Random seed type")); gtk_frame_set_child (dlg->frame_seed, GTK_WIDGET (dlg->grid_seed)); dlg->grid = (GtkGrid *) gtk_grid_new (); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->button_diagonal), 0, 0, 2, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->button_3D), 0, 1, 2, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_length), 0, 2, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_length), 1, 2, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_width), 0, 3, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_width), 1, 3, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_height), 0, 4, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_height), 1, 4, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->frame_fractal), 0, 5, 2, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->button_animate), 0, 6, 2, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->frame_algorithm), 2, 0, 1, 8); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->frame_seed), 0, 7, 2, 2); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_seed), 0, 9, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_seed), 1, 9, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_nthreads), 0, 10, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_nthreads), 1, 10, 1, 1); dlg->logo = (GtkImage *) gtk_image_new_from_file ("logo2.png"); dlg->bar = (GtkHeaderBar *) gtk_header_bar_new (); #if !GTK4 gtk_header_bar_set_title (dlg->bar, _("Options")); gtk_header_bar_set_subtitle (dlg->bar, _("Set the fractal options")); gtk_header_bar_set_show_close_button (dlg->bar, 1); #endif gtk_header_bar_pack_start (dlg->bar, GTK_WIDGET (dlg->logo)); dlg->dialog = (GtkDialog *) gtk_dialog_new_with_buttons (NULL, dialog_simulator->window, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, _("_OK"), GTK_RESPONSE_OK, _("_Cancel"), GTK_RESPONSE_CANCEL, NULL); gtk_window_set_titlebar (GTK_WINDOW (dlg->dialog), GTK_WIDGET (dlg->bar)); #if !GTK4 content = (GtkContainer *) gtk_dialog_get_content_area (dlg->dialog); gtk_container_add (content, GTK_WIDGET (dlg->grid)); gtk_widget_show_all (GTK_WIDGET (dlg->dialog)); #else gtk_window_set_title (GTK_WINDOW (dlg->dialog), _("Options")); content = (GtkBox *) gtk_dialog_get_content_area (dlg->dialog); gtk_box_append (content, GTK_WIDGET (dlg->grid)); gtk_widget_show (GTK_WIDGET (dlg->dialog)); #endif gtk_check_button_set_active (dlg->button_diagonal, fractal_diagonal); gtk_check_button_set_active (dlg->button_3D, fractal_3D); gtk_spin_button_set_value (dlg->entry_length, length); gtk_spin_button_set_value (dlg->entry_width, width); gtk_spin_button_set_value (dlg->entry_height, height); gtk_spin_button_set_value (dlg->entry_seed, random_seed); gtk_spin_button_set_value (dlg->entry_nthreads, nthreads); dialog_options_update (); g_signal_connect_swapped (dlg->dialog, "response", G_CALLBACK (dialog_options_close), dlg); } /** * Function to show a help dialog. */ static void dialog_simulator_help () { gchar *authors[] = { "Javier Burguete Tolosa (jburguete@eead.csic.es)", NULL }; gtk_show_about_dialog (dialog_simulator->window, "program_name", "Fractal", "comments", _("A program using growing fractals to benchmark " "parallelization and drawing libraries"), "authors", authors, "translator-credits", _("Javier Burguete Tolosa (jburguete@eead.csic.es)"), "version", "3.4.15", "copyright", "Copyright 2009-2021 Javier Burguete Tolosa", "license-type", GTK_LICENSE_BSD, "logo", dialog_simulator->logo, "website-label", _("Website"), "website", "https://github.com/jburguete/fractal", NULL); } /** * Function to update the enabled window properties. */ void dialog_simulator_update () { gtk_widget_set_sensitive (GTK_WIDGET (dialog_simulator->button_start), !simulating); gtk_widget_set_sensitive (GTK_WIDGET (dialog_simulator->button_stop), simulating); set_perspective (); } /** * Function to show the fractal progress. */ void dialog_simulator_progress () { GMainContext *context; register unsigned int k; register float x; if (fractal_3D) { switch (fractal_type) { case 0: case 1: x = max_d / (float) (height - 1); break; default: k = length; if (width < k) k = width; if (height < k) k = height; k = k / 2; if (k) --k; x = fmin (1., max_d / (float) k); } } else { switch (fractal_type) { case 0: case 1: x = max_d / (float) (height - 1); break; default: k = width; if (height < k) k = height; k = k / 2 - 1; x = fmin (1., max_d / (float) k); } } gtk_progress_bar_set_fraction (dialog_simulator->progress, x); gtk_spin_button_set_value (dialog_simulator->entry_time, difftime (time (NULL), t0)); context = g_main_context_default (); while (g_main_context_pending (context)) g_main_context_iteration (context, 0); } /** * Function to close the dialog to save the graphical view. */ static void dialog_simulator_graphic_close (GtkFileChooserDialog * dlg, ///< GtkFileChooserDialog struct. int response_id) ///< Response identifier. { char *filename; if (response_id == GTK_RESPONSE_ACCEPT) filename = gtk_file_chooser_get_current_name (GTK_FILE_CHOOSER (dlg)); else filename = NULL; #if !GTK4 gtk_widget_destroy (GTK_WIDGET (dlg)); #else gtk_window_destroy (GTK_WINDOW (dlg)); #endif if (filename) { graphic_save (filename); g_free (filename); } } /** * Function to save the graphical view on a PNG file. */ static void dialog_simulator_graphic_save () { GtkFileChooserDialog *dlg; dlg = (GtkFileChooserDialog *) gtk_file_chooser_dialog_new (_("Save graphical"), dialog_simulator->window, GTK_FILE_CHOOSER_ACTION_SAVE, _("_Cancel"), GTK_RESPONSE_CANCEL, _("_Open"), GTK_RESPONSE_ACCEPT, NULL); #if !GTK4 gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dlg), 1); gtk_widget_show_all (GTK_WIDGET (dlg)); #else gtk_widget_show (GTK_WIDGET (dlg)); #endif g_signal_connect (dlg, "response", G_CALLBACK (dialog_simulator_graphic_close), NULL); } #if HAVE_GTKGLAREA static void dialog_simulator_draw_init (GtkGLArea * gl_area) { #if DEBUG printf ("dialog_simulator_draw_init: start\n"); #endif gtk_gl_area_make_current (gl_area); graphic_init (graphic, "logo.png"); #if DEBUG printf ("dialog_simulator_draw_init: end\n"); #endif } #elif HAVE_GLFW /** * Function to close the GLFW window. */ static void window_close () { glfwSetWindowShouldClose (window, GL_TRUE); } #endif /** * Function to create the main window. */ void dialog_simulator_create () { static char *tip_exit, *tip_options, *tip_start, *tip_stop, *tip_save, *tip_help; DialogSimulator *dlg; #if DEBUG printf ("dialog_simulator_create: start\n"); #endif dlg = dialog_simulator; #if HAVE_GTKGLAREA dlg->loop = g_main_loop_new (NULL, 0); #elif HAVE_SDL exit_event->type = SDL_QUIT; #endif tip_options = _("Fractal options"); tip_start = _("Start fractal growing"); tip_stop = _("Stop fractal growing"); tip_save = _("Save graphical"); tip_help = _("Help"); tip_exit = _("Exit"); #if !GTK4 dlg->logo = gtk_image_get_pixbuf (GTK_IMAGE (gtk_image_new_from_file ("logo.png"))); dlg->logo_min = gtk_image_get_pixbuf (GTK_IMAGE (gtk_image_new_from_file ("logo2.png"))); #else dlg->logo = gtk_image_get_paintable (GTK_IMAGE (gtk_image_new_from_file ("logo.png"))); dlg->logo_min = gtk_image_get_paintable (GTK_IMAGE (gtk_image_new_from_file ("logo2.png"))); #endif dlg->box = (GtkBox *) gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); dlg->button_options = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("preferences-system", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("preferences-system"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_options), tip_options); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_options)); g_signal_connect_swapped (dlg->button_options, "clicked", dialog_options_create, dlg->logo_min); dlg->button_start = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("system-run", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("system-run"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_start), tip_start); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_start)); g_signal_connect (dlg->button_start, "clicked", fractal, NULL); dlg->button_stop = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("process-stop", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("process-stop"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_stop), tip_stop); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_stop)); g_signal_connect (dlg->button_stop, "clicked", fractal_stop, NULL); dlg->button_save = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("document-save", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("document-save"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_save), tip_save); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_save)); g_signal_connect (dlg->button_save, "clicked", dialog_simulator_graphic_save, NULL); dlg->button_help = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("help-about", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("help-about"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_help), tip_help); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_help)); g_signal_connect (dlg->button_help, "clicked", dialog_simulator_help, NULL); dlg->button_exit = (GtkButton *) #if !GTK4 gtk_button_new_from_icon_name ("application-exit", GTK_ICON_SIZE_BUTTON); #else gtk_button_new_from_icon_name ("application-exit"); #endif gtk_widget_set_tooltip_text (GTK_WIDGET (dlg->button_exit), tip_exit); gtk_box_append (dlg->box, GTK_WIDGET (dlg->button_exit)); #if HAVE_GTKGLAREA g_signal_connect_swapped (dlg->button_exit, "clicked", (GCallback) g_main_loop_quit, dlg->loop); #elif HAVE_FREEGLUT g_signal_connect (dlg->button_exit, "clicked", glutLeaveMainLoop, NULL); #elif HAVE_SDL g_signal_connect_swapped (dlg->button_exit, "clicked", (void (*)) SDL_PushEvent, exit_event); #elif HAVE_GLFW g_signal_connect (dlg->button_exit, "clicked", (void (*)) window_close, NULL); #endif dlg->label_time = (GtkLabel *) gtk_label_new (_("Calculating time")); dlg->entry_time = (GtkSpinButton *) gtk_spin_button_new_with_range (0., 1.e6, 0.1); gtk_widget_set_sensitive (GTK_WIDGET (dlg->entry_time), 0); dlg->progress = (GtkProgressBar *) gtk_progress_bar_new (); gtk_progress_bar_set_text (dlg->progress, _("Progress")); dlg->hscale = (GtkScale *) gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, -90., 0., 1.); dlg->vscale = (GtkScale *) gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, 0., 90., 1.); gtk_scale_set_digits (dlg->hscale, 0); gtk_scale_set_digits (dlg->vscale, 0); gtk_range_set_value (GTK_RANGE (dlg->hscale), phid); gtk_range_set_value (GTK_RANGE (dlg->vscale), thetad); g_signal_connect (dlg->hscale, "value-changed", set_perspective, NULL); g_signal_connect (dlg->vscale, "value-changed", set_perspective, NULL); dlg->label_horizontal = (GtkLabel *) gtk_label_new (_("Horizontal perspective angle (º)")); dlg->label_vertical = (GtkLabel *) gtk_label_new (_("Vertical perspective angle (º)")); dlg->grid = (GtkGrid *) gtk_grid_new (); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->box), 0, 0, 3, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->progress), 0, 1, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_time), 1, 1, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->entry_time), 2, 1, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_horizontal), 0, 2, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->hscale), 1, 2, 2, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->label_vertical), 0, 3, 1, 1); gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->vscale), 1, 3, 2, 1); #if HAVE_GTKGLAREA dlg->gl_area = (GtkGLArea *) gtk_gl_area_new (); gtk_widget_set_size_request (GTK_WIDGET (dlg->gl_area), window_width, window_height); g_signal_connect (dlg->gl_area, "realize", (GCallback) dialog_simulator_draw_init, NULL); g_signal_connect (dlg->gl_area, "render", draw, NULL); g_signal_connect (dlg->gl_area, "resize", (GCallback) resize, NULL); #if WINDOW_GLAREA #if !GTK4 dlg->window_gl = (GtkWindow *) gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_icon (dlg->window_gl, dlg->logo_min); gtk_container_add (GTK_CONTAINER (dlg->window_gl), GTK_WIDGET (dlg->gl_area)); g_signal_connect_swapped (dlg->window_gl, "delete_event", (GCallback) g_main_loop_quit, dlg->loop); gtk_widget_show_all (GTK_WIDGET (dlg->window_gl)); #else dlg->window_gl = (GtkWindow *) gtk_window_new (); gtk_window_set_child (dlg->window_gl, GTK_WIDGET (dlg->gl_area)); g_signal_connect_swapped (dlg->window_gl, "close-request", (GCallback) g_main_loop_quit, dlg->loop); gtk_widget_show (GTK_WIDGET (dlg->window_gl)); #endif #else gtk_grid_attach (dlg->grid, GTK_WIDGET (dlg->gl_area), 0, 4, 3, 1); #endif #elif HAVE_SDL SDL_SetWindowMinimumSize (window, window_width, window_height); #elif HAVE_GLFW glfwSetWindowSizeLimits (window, window_width, window_height, GLFW_DONT_CARE, GLFW_DONT_CARE); #endif #if !GTK4 dlg->window = (GtkWindow *) gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (dlg->window, _("Fractal growing")); gtk_window_set_icon (dlg->window, dlg->logo_min); gtk_container_add (GTK_CONTAINER (dlg->window), GTK_WIDGET (dlg->grid)); #if HAVE_GTKGLAREA g_signal_connect_swapped (dlg->window, "delete_event", (GCallback) g_main_loop_quit, dlg->loop); #elif HAVE_FREEGLUT g_signal_connect (dlg->window, "delete_event", glutLeaveMainLoop, NULL); #elif HAVE_SDL g_signal_connect_swapped (dlg->window, "delete_event", (void (*)) SDL_PushEvent, exit_event); #elif HAVE_GLFW g_signal_connect (dlg->window, "delete_event", (void (*)) window_close, NULL); #endif gtk_widget_show_all (GTK_WIDGET (dlg->window)); #else dlg->window = (GtkWindow *) gtk_window_new (); gtk_window_set_title (dlg->window, _("Fractal growing")); gtk_window_set_child (dlg->window, GTK_WIDGET (dlg->grid)); #if HAVE_GTKGLAREA g_signal_connect_swapped (dlg->window, "close-request", (GCallback) g_main_loop_quit, dlg->loop); #elif HAVE_FREEGLUT g_signal_connect (dlg->window, "close-request", glutLeaveMainLoop, NULL); #elif HAVE_SDL g_signal_connect_swapped (dlg->window, "close-request", (void (*)) SDL_PushEvent, exit_event); #elif HAVE_GLFW g_signal_connect (dlg->window, "close-request", (void (*)) window_close, NULL); #endif gtk_widget_show (GTK_WIDGET (dlg->window)); #endif #if DEBUG printf ("dialog_simulator_create: end\n"); #endif }
{ "alphanum_fraction": 0.6657716173, "avg_line_length": 35.56, "ext": "c", "hexsha": "8c63d060edc01e49da55620c1248d9408d74f4da", "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": "95d711dcb7b385556fb77794bc01737b21e99774", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/fractal", "max_forks_repo_path": "3.4.15/simulator.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "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/fractal", "max_issues_repo_path": "3.4.15/simulator.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/fractal", "max_stars_repo_path": "3.4.15/simulator.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7259, "size": 27559 }
/* * 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 blr_models.c * \brief BLR models */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <string.h> #include <mpi.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_interp.h> #include "brains.h" /* cluster around outer disk face, Lopn_cos1 < Lopn_cos2 */ inline double theta_sample_outer(double gam, double Lopn_cos1, double Lopn_cos2) { return acos(Lopn_cos1 + (Lopn_cos2-Lopn_cos1) * pow(gsl_rng_uniform(gsl_r), gam)); } /* cluster around equatorial plane, Lopn_cos1 < Lopn_cos2 */ inline double theta_sample_inner(double gam, double Lopn_cos1, double Lopn_cos2) { /* note that cosine is a decreaing function */ double opn1 = acos(Lopn_cos1), opn2 = acos(Lopn_cos2); return opn2 + (opn1-opn2) * (1.0 - pow(gsl_rng_uniform(gsl_r), 1.0/gam)); } /*================================================================ * model 1 * Brewer et al. (2011)'s model * * geometry: radial Gamma distribution * dynamics: elliptical orbits *================================================================ */ void gen_cloud_sample_model1(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, dis, Lopn_cos, u; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb; double inc, F, beta, mu, k, a, s, rin, sig, Rs; double Lphi, Lthe, L, E; double V, weight, rnd; BLRmodel1 *model = (BLRmodel1 *)pm; double Emin, Lmax, Vr, Vr2, Vph, mbh, chi, lambda, q; Lopn_cos = cos(model->opn*PI/180.0); inc = acos(model->inc); beta = model->beta; F = model->F; mu = exp(model->mu); k = model->k; if(flag_type == 1) // 1D RM, no dynamical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); lambda = model->lambda; q = model->q; } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days a = 1.0/beta/beta; s = mu/a; rin = mu*F + Rs; sig = (1.0-F)*s; for(i=0; i<parset.n_cloud_per_task; i++) { // generate a direction of the angular momentum Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * gsl_rng_uniform(gsl_r)); Lthe = theta_sample(1.0, Lopn_cos, 1.0); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); x = r * cos(phi); y = r * sin(phi); z = 0.0; /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z;*/ xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y; zb = sin(Lthe) * x; zb0 = zb; if(zb0 < 0.0) zb = -zb; /* counter-rotate around y */ x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); y = yb; z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif /* velocity * note that a cloud moves in its orbit plane, whose direction * is determined by the direction of its angular momentum. */ Emin = - mbh/r; //Ecirc = 0.5 * Emin; //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r)); for(j=0; j<parset.n_vel_per_cloud; j++) { chi = lambda * gsl_ran_ugaussian(gsl_r); E = Emin / (1.0 + exp(-chi)); Lmax = sqrt(2.0 * r*r * (E + mbh/r)); if(lambda>1.0e-2) /* make sure that exp is caculatable. */ L = Lmax * lambda * log( (exp(1.0/lambda) - 1.0) * gsl_rng_uniform(gsl_r) + 1.0 ); else L = Lmax * (1.0 + lambda * log(gsl_rng_uniform(gsl_r)) ); Vr2 = 2.0 * (E + mbh/r) - L*L/r/r; if(Vr2>=0.0) { u = gsl_rng_uniform(gsl_r); Vr = sqrt(Vr2) * (u<q?-1.0:1.0); } else { Vr = 0.0; } Vph = L/r; /* RM cannot distinguish the orientation of the rotation. */ vx = Vr * cos(phi) - Vph * sin(phi); vy = Vr * sin(phi) + Vph * cos(phi); vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy; vzb = sin(Lthe) * vx; if(zb0 < 0.0) vzb = -vzb; vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); vy = vyb; vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc); V = -vx; //note the definition of the line-of-sight velocity. positive means a receding // velocity relative to the observer. clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*================================================================ * model 2 * * geometry: radial Gamma distribution * dynamics: elliptical orbits (Gaussian around circular orbits) *================================================================ */ void gen_cloud_sample_model2(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb; double inc, F, beta, mu, k, a, s, rin, sig, Rs; double Lphi, Lthe; double V, weight, rnd; BLRmodel2 *model = (BLRmodel2 *)pm; double Emin, Ecirc, Lcirc, Vcirc, Vr, Vph, mbh, sigr, sigtheta, rhor, rhotheta; Lopn_cos = cos(model->opn*PI/180.0); inc = acos(model->inc); beta = model->beta; F = model->F; mu = exp(model->mu); k = model->k; a = 1.0/beta/beta; s = mu/a; rin=mu*F; sig=(1.0-F)*s; if(flag_type == 1) //1D RM no dynamical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); sigr = model->sigr; sigtheta = model->sigtheta * PI; } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days a = 1.0/beta/beta; s = mu/a; rin = mu*F + Rs; sig = (1.0-F)*s; for(i=0; i<parset.n_cloud_per_task; i++) { /* generate a direction of the angular momentum */ Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * gsl_rng_uniform(gsl_r)); Lthe = theta_sample(1.0, Lopn_cos, 1.0); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); x = r * cos(phi); y = r * sin(phi); z = 0.0; /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z;*/ xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y; zb = sin(Lthe) * x; zb0 = zb; if(zb0 < 0.0) zb = -zb; /* counter-rotate around y */ x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); y = yb; z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif /* velocity * note that a cloud moves in its orbit plane, whose direction * is determined by the direction of its angular momentum. */ Emin = - mbh/r; Ecirc = 0.5 * Emin; Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r)); Vcirc = Lcirc/r; for(j=0; j<parset.n_vel_per_cloud; j++) { rhor = gsl_ran_ugaussian(gsl_r) * sigr + 1.0; rhotheta = gsl_ran_ugaussian(gsl_r) * sigtheta + 0.5*PI; Vr = rhor * cos(rhotheta) * Vcirc; Vph = rhor * fabs(sin(rhotheta)) * Vcirc; /* RM cannot distinguish the orientation of the rotation. make all clouds co-rotate */ vx = Vr * cos(phi) - Vph * sin(phi); vy = Vr * sin(phi) + Vph * cos(phi); vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy; vzb = sin(Lthe) * vx; if(zb0 < 0.0) vzb = -vzb; vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); vy = vyb; vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc); V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*==================================================================== * model 3 * * geometry: radial power law * dynamics: *==================================================================== */ void gen_cloud_sample_model3(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb; double inc, F, alpha, Rin, k, Rs; double Lphi, Lthe, L, E; double V, weight, rnd; BLRmodel3 *model = (BLRmodel3 *)pm; double Emin, Lmax, Vr, Vph, mbh, xi, q; Lopn_cos = cos(model->opn*PI/180.0); inc = acos(model->inc); alpha = model->alpha; F = model->F; Rin = exp(model->Rin); k = model->k; if(flag_type == 1) { mbh = 0.0; } else { mbh = exp(model->mbh); xi = model->xi; q = model->q; } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days if(F*Rin > rcloud_max_set) F = rcloud_max_set/Rin; for(i=0; i<parset.n_cloud_per_task; i++) { // generate a direction of the angular momentum Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * gsl_rng_uniform(gsl_r)); Lthe = theta_sample(1.0, Lopn_cos, 1.0); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } if(fabs(1.0-alpha) > 1.0e-4) rnd = pow( gsl_rng_uniform(gsl_r) * ( pow(F, 1.0-alpha) - 1.0) + 1.0, 1.0/(1.0-alpha) ); else rnd = exp( gsl_rng_uniform(gsl_r) * log(F) ); r = Rin * rnd + Rs; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); x = r * cos(phi); y = r * sin(phi); z = 0.0; /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z;*/ xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y; zb = sin(Lthe) * x; zb0 = zb; if(zb0 < 0.0) zb = -zb; // counter-rotate around y x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); y = yb; z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif // velocity // note that a cloud moves in its orbit plane, whose direction // is determined by the direction of its angular momentum. Emin = - mbh/r; //Ecirc = 0.5 * Emin; //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r)); for(j=0; j<parset.n_vel_per_cloud; j++) { E = Emin / 2.0; Lmax = sqrt(2.0 * r*r * (E + mbh/r)); L = Lmax; Vr = xi * sqrt(2.0*mbh/r); if(q <= 0.5) Vr = -Vr; Vph = L/r; //RM cannot distinguish the orientation of the rotation. vx = Vr * cos(phi) - Vph * sin(phi); vy = Vr * sin(phi) + Vph * cos(phi); vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy; vzb = sin(Lthe) * vx; if(zb0 < 0.0) vzb = -vzb; vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); vy = vyb; vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc); V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*! * model 4. * generate cloud sample. */ void gen_cloud_sample_model4(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb; double inc, F, alpha, Rin, k, Rs; double Lphi, Lthe, L, E; double V, weight, rnd; BLRmodel4 *model = (BLRmodel4 *)pm; double Emin, Lmax, Vr, Vph, mbh, xi, q; Lopn_cos = cos(model->opn*PI/180.0); inc = acos(model->inc); alpha = model->alpha; F = model->F; Rin = exp(model->Rin); k = model->k; if(flag_type == 1) // 1D RM, no dynamical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); xi = model->xi; q = model->q; } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days if(Rin*F > rcloud_max_set) F = rcloud_max_set/Rin; for(i=0; i<parset.n_cloud_per_task; i++) { /* generate a direction of the angular momentum */ Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * gsl_rng_uniform(gsl_r)); Lthe = theta_sample(1.0, Lopn_cos, 1.0); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } if(fabs(1.0-alpha) > 1.0e-4) rnd = pow( gsl_rng_uniform(gsl_r) * ( pow(F, 1.0-alpha) - 1.0) + 1.0, 1.0/(1.0-alpha) ); else rnd = exp( gsl_rng_uniform(gsl_r) * log(F) ); r = Rin * rnd + Rs; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); x = r * cos(phi); y = r * sin(phi); z = 0.0; /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z; */ xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y; zb = sin(Lthe) * x; zb0 = zb; if(zb0 < 0.0) zb = -zb; /* counter-rotate around y */ x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); y = yb; z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif // velocity // note that a cloud moves in its orbit plane, whose direction // is determined by the direction of its angular momentum. Emin = - mbh/r; //Ecirc = 0.5 * Emin; //Lcirc = sqrt(2.0 * r*r * (Ecirc + mbh/r)); for(j=0; j<parset.n_vel_per_cloud; j++) { E = Emin / 2.0; Lmax = sqrt(2.0 * r*r * (E + mbh/r)); L = Lmax; Vr = xi * sqrt(2.0*mbh/r); if(q<=0.5) Vr = -Vr; Vph = sqrt(1.0-2.0*xi*xi) * L/r; //RM cannot distinguish the orientation of the rotation. vx = Vr * cos(phi) - Vph * sin(phi); vy = Vr * sin(phi) + Vph * cos(phi); vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy; vzb = sin(Lthe) * vx; if(zb0 < 0.0) vzb = -vzb; vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); vy = vyb; vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc); V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*==================================================================== * model 5 * * geometry: double power-law * dynamics: elliptical orbits and inflow/outflow as in Pancoast's model *==================================================================== */ void gen_cloud_sample_model5(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, cos_phi, sin_phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, zb0; double inc, Fin, Fout, alpha, k, gam, mu, xi; double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot, sig_turb; double Lphi, Lthe, V, Vr, Vph, Vkep, rhoV, theV; double cos_Lphi, sin_Lphi, cos_Lthe, sin_Lthe, cos_inc_cmp, sin_inc_cmp; double weight, rndr, rnd, rnd_frac, rnd_xi, frac1, frac2, ratio, Rs, g; double vx, vy, vz, vxb, vyb, vzb; BLRmodel5 *model = (BLRmodel5 *)pm; Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */ inc = acos(model->inc); /* inclination angle in rad */ alpha = model->alpha; Fin = model->Fin; Fout = exp(model->Fout); mu = exp(model->mu); /* mean radius */ k = model->k; gam = model->gam; xi = model->xi; if(flag_type == 1) // 1D RM, no dynamical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); fellip = model->fellip; fflow = model->fflow; sigr_circ = exp(model->sigr_circ); sigthe_circ = exp(model->sigthe_circ); sigr_rad = exp(model->sigr_rad); sigthe_rad = exp(model->sigthe_rad); theta_rot = model->theta_rot*PI/180.0; sig_turb = exp(model->sig_turb); } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days if(mu*Fout > rcloud_max_set) Fout = rcloud_max_set/mu; frac1 = 1.0/(alpha+1.0) * (1.0 - pow(Fin, alpha+1.0)); frac2 = 1.0/(alpha-1.0) * (1.0 - pow(Fout, -alpha+1.0)); ratio = frac1/(frac1 + frac2); sin_inc_cmp = cos(inc);//sin(PI/2.0 - inc); cos_inc_cmp = sin(inc);//cos(PI/2.0 - inc); for(i=0; i<parset.n_cloud_per_task; i++) { /* generate a direction of the angular momentum of the orbit */ Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * pow(gsl_rng_uniform(gsl_r), gam)); Lthe = theta_sample(gam, Lopn_cos, 1.0); cos_Lphi = cos(Lphi); sin_Lphi = sin(Lphi); cos_Lthe = cos(Lthe); sin_Lthe = sin(Lthe); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd_frac = gsl_rng_uniform(gsl_r); rnd = gsl_rng_uniform(gsl_r); if(rnd_frac < ratio) { rndr = pow( 1.0 - rnd * (1.0 - pow(Fin, alpha+1.0)), 1.0/(1.0+alpha)); } else { rndr = pow( 1.0 - rnd * (1.0 - pow(Fout, -alpha+1.0)), 1.0/(1.0-alpha)); } r = rndr*mu + Rs; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); cos_phi = cos(phi); sin_phi = sin(phi); /* Polar coordinates to Cartesian coordinate */ x = r * cos_phi; y = r * sin_phi; z = 0.0; /* right-handed framework * first rotate around y axis by an angle of Lthe, then rotate around z axis * by an angle of Lphi */ /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z;*/ xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y; yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y; zb = sin_Lthe * x; zb0 = zb; rnd_xi = gsl_rng_uniform(gsl_r); if( (rnd_xi < 1.0 - xi) && zb0 < 0.0) zb = -zb; // counter-rotate around y, LOS is x-axis x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif Vkep = sqrt(mbh/r); for(j=0; j<parset.n_vel_per_cloud; j++) { rnd = gsl_rng_uniform(gsl_r); if(rnd < fellip) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_circ + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_circ + 0.5) * PI; } else { if(fflow <= 0.5) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad + 1.0) * PI + theta_rot; } else { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad ) * PI + theta_rot; } } Vr = sqrt(2.0) * rhoV * cos(theV); Vph = rhoV * fabs(sin(theV)); /* make all clouds co-rotate */ vx = Vr * cos_phi - Vph * sin_phi; vy = Vr * sin_phi + Vph * cos_phi; vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos_Lthe*cos_Lphi * vx + sin_Lphi * vy; vyb =-cos_Lthe*sin_Lphi * vx + cos_Lphi * vy; vzb = sin_Lthe * vx; if((rnd_xi < 1.0-xi) && zb0 < 0.0) vzb = -vzb; vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. V += gsl_ran_ugaussian(gsl_r) * sig_turb * Vkep; // add turbulence velocity if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light V = 0.9999*C_Unit * (V>0.0?1.0:-1.0); g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects V = (g-1.0)*C_Unit; clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*================================================================ * model 6 * Pancoast et al. (2014)'s model * * geometry: radial Gamma distribution * dynamics: ellipitcal orbits and inflow/outflow *================================================================ */ void gen_cloud_sample_model6(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, cos_phi, sin_phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb; double V, rhoV, theV, Vr, Vph, Vkep, Rs, g; double inc, F, beta, mu, k, gam, xi, a, s, sig, rin; double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot, sig_turb; double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp; double weight, rnd, rnd_xi; BLRmodel6 *model = (BLRmodel6 *)pm; Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */ inc = acos(model->inc); /* inclination angle in rad */ beta = model->beta; F = model->F; mu = exp(model->mu); /* mean radius */ k = model->k; gam = model-> gam; xi = model->xi; if(flag_type == 1) // 1D RM, no mbh parameters { mbh = 0.0; } else { mbh = exp(model->mbh); fellip = model->fellip; fflow = model->fflow; sigr_circ = exp(model->sigr_circ); sigthe_circ = exp(model->sigthe_circ); sigr_rad = exp(model->sigr_rad); sigthe_rad = exp(model->sigthe_rad); theta_rot = model->theta_rot*PI/180.0; sig_turb = exp(model->sig_turb); } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days a = 1.0/beta/beta; s = mu/a; rin=mu*F + Rs; // include Scharzschild radius sig=(1.0-F)*s; sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc); cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc); for(i=0; i<parset.n_cloud_per_task; i++) { // generate a direction of the angular momentum of the orbit Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * pow(gsl_rng_uniform(gsl_r), gam)); Lthe = theta_sample(gam, Lopn_cos, 1.0); sin_Lphi = sin(Lphi); cos_Lphi = cos(Lphi); sin_Lthe = sin(Lthe); cos_Lthe = cos(Lthe); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); cos_phi = cos(phi); sin_phi = sin(phi); /* Polar coordinates to Cartesian coordinate */ x = r * cos_phi; y = r * sin_phi; z = 0.0; /* right-handed framework * first rotate around y axis by an angle of Lthe, then rotate around z axis * by an angle of Lphi */ /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z; */ xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y; yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y; zb = sin_Lthe * x; zb0 = zb; rnd_xi = gsl_rng_uniform(gsl_r); if( (rnd_xi < 1.0 - xi) && zb0 < 0.0) zb = -zb; // counter-rotate around y, LOS is x-axis /* x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); y = yb; z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); */ x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) // 1D RM { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif Vkep = sqrt(mbh/r); for(j=0; j<parset.n_vel_per_cloud; j++) { rnd = gsl_rng_uniform(gsl_r); if(rnd < fellip) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_circ + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_circ + 0.5)*PI; } else { if(fflow <= 0.5) /* inflow */ { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad + 1.0) * PI + theta_rot; } else /* outflow */ { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad) * PI + theta_rot; } } Vr = sqrt(2.0) * rhoV * cos(theV); Vph = rhoV * fabs(sin(theV)); /* make all clouds co-rotate */ vx = Vr * cos_phi - Vph * sin_phi; vy = Vr * sin_phi + Vph * cos_phi; vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos_Lthe*cos_Lphi * vx + sin_Lphi * vy; vyb =-cos_Lthe*sin_Lphi * vx + cos_Lphi * vy; vzb = sin_Lthe * vx; if((rnd_xi < 1.0-xi) && zb0 < 0.0) vzb = -vzb; /*vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); vy = vyb; vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc);*/ vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. V += gsl_ran_ugaussian(gsl_r) * sig_turb * Vkep; // add turbulence velocity if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light V = 0.9999*C_Unit * (V>0.0?1.0:-1.0); g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects V = (g-1.0)*C_Unit; clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /*================================================================ * model 7 * shadowed model * * geometry: radial Gamma distribution * dynamics: elliptical orbits and inflow/outflow as in Pancoast'model *================================================================ */ void gen_cloud_sample_model7(const void *pm, int flag_type, int flag_save) { int i, j, nc, num_sh; double r, phi, dis, Lopn_cos, cos_phi, sin_phi; double x, y, z, xb, yb, zb, zb0, vx, vy, vz, vxb, vyb, vzb, Rs, g, sig_turb; double V, rhoV, theV, Vr, Vph, Vkep; double inc, F, beta, mu, k, gam, xi, a, s, sig, rin; double mbh, fellip, fflow, sigr_circ, sigthe_circ, sigr_rad, sigthe_rad, theta_rot; double Lphi, Lthe, sin_Lphi, cos_Lphi, sin_Lthe, cos_Lthe, sin_inc_cmp, cos_inc_cmp; double weight, rnd, rnd_xi; BLRmodel7 *model = (BLRmodel7 *)pm; Lopn_cos = cos(model->opn*PI/180.0); /* cosine of openning angle */ inc = acos(model->inc); /* inclination angle in rad */ beta = model->beta; F = model->F; mu = exp(model->mu); /* mean radius */ k = model->k; gam = model-> gam; xi = model->xi; if(flag_type == 1) // 1D RM, no dyamical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); fellip = model->fellip; fflow = model->fflow; sigr_circ = exp(model->sigr_circ); sigthe_circ = exp(model->sigthe_circ); sigr_rad = exp(model->sigr_rad); sigthe_rad = exp(model->sigthe_rad); theta_rot = model->theta_rot*PI/180.0; sig_turb = exp(model->sig_turb); } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days a = 1.0/beta/beta; s = mu/a; rin=Rs + mu*F; sig=(1.0-F)*s; sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc); cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc); num_sh = (int)(parset.n_cloud_per_task * model->fsh); for(i=0; i<num_sh; i++) { // generate a direction of the angular momentum of the orbit Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * pow(gsl_rng_uniform(gsl_r), gam)); Lthe = theta_sample(gam, Lopn_cos, 1.0); sin_Lphi = sin(Lphi); cos_Lphi = cos(Lphi); sin_Lthe = sin(Lthe); cos_Lthe = cos(Lthe); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); cos_phi = cos(phi); sin_phi = sin(phi); /* Polar coordinates to Cartesian coordinate */ x = r * cos_phi; y = r * sin_phi; z = 0.0; /* right-handed framework * first rotate around y axis by an angle of Lthe, then rotate around z axis * by an angle of Lphi */ /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z; */ xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y; yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y; zb = sin_Lthe * x; zb0 = zb; rnd_xi = gsl_rng_uniform(gsl_r); if( (rnd_xi < 1.0 - xi) && zb0 < 0.0) zb = -zb; // counter-rotate around y, LOS is x-axis x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif Vkep = sqrt(mbh/r); for(j=0; j<parset.n_vel_per_cloud; j++) { rnd = gsl_rng_uniform(gsl_r); if(rnd < fellip) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_circ + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_circ + 0.5) * PI; } else { if(fflow <= 0.5) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad + 1.0) *PI + theta_rot; } else { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad) * PI + theta_rot; } } Vr = sqrt(2.0) * rhoV * cos(theV); Vph = rhoV * fabs(sin(theV)); /* make all clouds co-rotate */ vx = Vr * cos_phi - Vph * sin_phi; vy = Vr * sin_phi + Vph * cos_phi; vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos_Lthe*cos_Lphi * vx + sin_Lphi * vy; vyb =-cos_Lthe*sin_Lphi * vx + cos_Lphi * vy; vzb = sin_Lthe * vx; if((rnd_xi < 1.0-xi) && zb0 < 0.0) vzb = -vzb; vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. V += gsl_ran_ugaussian(gsl_r) * sig_turb * Vkep; if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light V = 0.9999*C_Unit * (V>0.0?1.0:-1.0); g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects V = (g-1.0)*C_Unit; clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } //second BLR region rin = exp(model->mu_un) * model->F_un + Rs; a = 1.0/(model->beta_un * model->beta_un); sig = exp(model->mu_un) * (1.0-model->F_un)/a; double Lopn_cos_un1, Lopn_cos_un2; Lopn_cos_un1 = Lopn_cos; if(model->opn + model->opn_un < 90.0) Lopn_cos_un2 = cos((model->opn + model->opn_un)/180.0*PI); else Lopn_cos_un2 = 0.0; if(flag_type != 1) // 1D RM, no dynamical parameters { fellip = model->fellip_un; fflow = model->fflow_un; } for(i=num_sh; i<parset.n_cloud_per_task; i++) { // generate a direction of the angular momentum of the orbit Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos_un2 + (Lopn_cos_un1-Lopn_cos_un2) * pow(gsl_rng_uniform(gsl_r), gam)); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * pow(gsl_rng_uniform(gsl_r), gam)); Lthe = theta_sample(gam, Lopn_cos_un2, Lopn_cos_un1); sin_Lphi = sin(Lphi); cos_Lphi = cos(Lphi); sin_Lthe = sin(Lthe); cos_Lthe = cos(Lthe); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); cos_phi = cos(phi); sin_phi = sin(phi); /* Polar coordinates to Cartesian coordinate */ x = r * cos_phi; y = r * sin_phi; z = 0.0; /* right-handed framework * first rotate around y axis by an angle of Lthe, then rotate around z axis * by an angle of Lphi */ /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb =-cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z; */ xb = cos_Lthe*cos_Lphi * x + sin_Lphi * y; yb =-cos_Lthe*sin_Lphi * x + cos_Lphi * y; zb = sin_Lthe * x; zb0 = zb; rnd_xi = gsl_rng_uniform(gsl_r); if( (rnd_xi < 1.0 - xi) && zb0 < 0.0) zb = -zb; // counter-rotate around y, LOS is x-axis x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; weight = 0.5 + k*(x/r); clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif Vkep = sqrt(mbh/r); for(j=0; j<parset.n_vel_per_cloud; j++) { rnd = gsl_rng_uniform(gsl_r); if(rnd < fellip) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_circ + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_circ + 0.5) * PI; } else { if(fflow <= 0.5) { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad + 1.0) *PI + theta_rot; } else { rhoV = (gsl_ran_ugaussian(gsl_r) * sigr_rad + 1.0) * Vkep; theV = (gsl_ran_ugaussian(gsl_r) * sigthe_rad) * PI + theta_rot; } } Vr = sqrt(2.0) * rhoV * cos(theV); Vph = rhoV * fabs(sin(theV)); /* make all clouds co-rotate */ vx = Vr * cos_phi - Vph * sin_phi; vy = Vr * sin_phi + Vph * cos_phi; vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos_Lthe*cos_Lphi * vx + sin_Lphi * vy; vyb =-cos_Lthe*sin_Lphi * vx + cos_Lphi * vy; vzb = sin_Lthe * vx; if((rnd_xi < 1.0-xi) && zb0 < 0.0) vzb = -vzb; vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. V += gsl_ran_ugaussian(gsl_r) * sig_turb * Vkep; if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light V = 0.9999*C_Unit * (V>0.0?1.0:-1.0); g = sqrt( (1.0 + V/C_Unit) / (1.0 - V/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects V = (g-1.0)*C_Unit; clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } /* * model 8, generate cloud sample. * a disk wind model. */ void gen_cloud_sample_model8(const void *pm, int flag_type, int flag_save) { int i; double theta_min, theta_max, r_min, r_max, Rblr, Rv, mbh, alpha, gamma, xi, lambda, k; double rnd, r, r0, theta, phi, xb, yb, zb, x, y, z, l, weight, sin_inc_cmp, cos_inc_cmp, inc; double dis, density, vl, vesc, Vr, Vph, vx, vy, vz, vxb, vyb, vzb, V, rnd_xi, zb0, lmax, R; double v0=6.0/VelUnit; BLRmodel8 *model=(BLRmodel8 *)pm; theta_min = model->theta_min/180.0 * PI; theta_max = model->dtheta_max/180.0*PI + theta_min; theta_max = fmin(theta_max, 0.5*PI); model->dtheta_max = (theta_max-theta_min)/PI*180; r_min = exp(model->r_min); r_max = model->fr_max * r_min; if(r_max > 0.5*rcloud_max_set) r_max = 0.5*rcloud_max_set; model->fr_max = r_max/r_min; gamma = model->gamma; alpha = model->alpha; lambda = model->lamda; k = model->k; xi = model->xi; Rv = exp(model->Rv); Rblr = exp(model->Rblr); if(Rblr < r_max) Rblr = r_max; model->Rblr = log(Rblr); inc = acos(model->inc); mbh = exp(model->mbh); sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc); cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc); for(i=0; i<parset.n_cloud_per_task; i++) { rnd = gsl_rng_uniform(gsl_r); r0 = r_min + rnd * (r_max - r_min); theta = theta_min + (theta_max - theta_min) * pow(rnd, gamma); /* the maximum allowed value of l */ lmax = -r0*sin(theta) + sqrt(r0*r0*sin(theta)*sin(theta) + (Rblr*Rblr - r0*r0)); l = gsl_rng_uniform(gsl_r) * lmax; r = l * sin(theta) + r0; if(gsl_rng_uniform(gsl_r) < 0.5) zb = l * cos(theta); else zb =-l * cos(theta); phi = gsl_rng_uniform(gsl_r) * 2.0*PI; xb = r * cos(phi); yb = r * sin(phi); zb0 = zb; rnd_xi = gsl_rng_uniform(gsl_r); if( (rnd_xi < 1.0 - xi) && zb0 < 0.0) zb = -zb; vesc = sqrt(2.0*mbh/r0); vl = v0 + (vesc - v0) * pow(l/Rv, alpha)/(1.0 + pow(l/Rv, alpha)); density = pow(r0, lambda)/vl; // counter-rotate around y, LOS is x-axis x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; R = sqrt(r*r + zb*zb); weight = 0.5 + k*(x/R); clouds_weight[i] = weight * density; #ifndef SpecAstro dis = R - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = R - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = R - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = R - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = R - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif Vr = vl * sin(theta); vzb = vl * cos(theta); Vph = sqrt(mbh*r0) / r; vxb = Vr * cos(phi) - Vph * sin(phi); vyb = Vr * sin(phi) + Vph * cos(phi); if(zb < 0.0) vzb = -vzb; vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. postive means a receding // velocity relative to the observer. clouds_vel[i] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } return; } /* * model 9, generate cloud sample. * same with the Graivty Collaboration's model about 3C 273 published in Nature (2018, 563, 657), * except that the prior of inclination is uniform in cosine. * */ void gen_cloud_sample_model9(const void *pm, int flag_type, int flag_save) { int i, j, nc; double r, phi, dis, Lopn_cos; double x, y, z, xb, yb, zb, vx, vy, vz, vxb, vyb, vzb; double inc, F, beta, mu, a, s, rin, sig; double Lphi, Lthe, Vkep, Rs, g; double V, weight, rnd, sin_inc_cmp, cos_inc_cmp; BLRmodel9 *model = (BLRmodel9 *)pm; double Vr, Vph, mbh; Lopn_cos = cos(model->opn*PI/180.0); //Lopn = model->opn*PI/180.0; inc = acos(model->inc); beta = model->beta; F = model->F; mu = exp(model->mu); if(flag_type == 1) // 1D RM, no dynmaical parameters { mbh = 0.0; } else { mbh = exp(model->mbh); } Rs = 3.0e11*mbh/CM_PER_LD; // Schwarzchild radius in a unit of light-days a = 1.0/beta/beta; s = mu/a; rin = mu*F + Rs; sig = (1.0-F)*s; sin_inc_cmp = cos(inc); //sin(PI/2.0 - inc); cos_inc_cmp = sin(inc); //cos(PI/2.0 - inc); for(i=0; i<parset.n_cloud_per_task; i++) { // generate a direction of the angular momentum Lphi = 2.0*PI * gsl_rng_uniform(gsl_r); //Lthe = acos(Lopn_cos + (1.0-Lopn_cos) * gsl_rng_uniform(gsl_r)); //Lthe = gsl_rng_uniform(gsl_r) * Lopn; Lthe = theta_sample(1.0, Lopn_cos, 1.0); nc = 0; r = rcloud_max_set+1.0; while(r>rcloud_max_set || r<rcloud_min_set) { if(nc > 1000) { printf("# Error, too many tries in generating ridial location of clouds.\n"); exit(0); } rnd = gsl_ran_gamma(gsl_r, a, 1.0); // r = mu * F + (1.0-F) * gsl_ran_gamma(gsl_r, 1.0/beta/beta, beta*beta*mu); r = rin + sig * rnd; nc++; } phi = 2.0*PI * gsl_rng_uniform(gsl_r); x = r * cos(phi); y = r * sin(phi); z = 0.0; /*xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y - sin(Lthe)*cos(Lphi) * z; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y + sin(Lthe)*sin(Lphi) * z; zb = sin(Lthe) * x + cos(Lthe) * z;*/ xb = cos(Lthe)*cos(Lphi) * x + sin(Lphi) * y; yb = -cos(Lthe)*sin(Lphi) * x + cos(Lphi) * y; zb = sin(Lthe) * x; /* counter-rotate around y */ //x = xb * cos(PI/2.0-inc) + zb * sin(PI/2.0-inc); //y = yb; //z =-xb * sin(PI/2.0-inc) + zb * cos(PI/2.0-inc); x = xb * cos_inc_cmp + zb * sin_inc_cmp; y = yb; z =-xb * sin_inc_cmp + zb * cos_inc_cmp; weight = 1.0; clouds_weight[i] = weight; #ifndef SpecAstro dis = r - x; clouds_tau[i] = dis; if(flag_type == 1) { if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; } #else switch(flag_type) { case 1: /* 1D RM */ dis = r - x; clouds_tau[i] = dis; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\n", x, y, z); } continue; break; case 2: /* 2D RM */ dis = r - x; clouds_tau[i] = dis; break; case 3: /* SA */ clouds_alpha[i] = y; clouds_beta[i] = z; break; case 4: /* 1D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; case 5: /* 2D RM + SA */ dis = r - x; clouds_tau[i] = dis; clouds_alpha[i] = y; clouds_beta[i] = z; break; } #endif /* velocity * note that a cloud moves in its orbit plane, whose direction * is determined by the direction of its angular momentum. */ Vkep = sqrt(mbh/r); for(j=0; j<parset.n_vel_per_cloud; j++) { Vr = 0.0; Vph = Vkep; /* RM cannot distinguish the orientation of the rotation. */ vx = Vr * cos(phi) - Vph * sin(phi); vy = Vr * sin(phi) + Vph * cos(phi); vz = 0.0; /*vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy - sin(Lthe)*cos(Lphi) * vz; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy + sin(Lthe)*sin(Lphi) * vz; vzb = sin(Lthe) * vx + cos(Lthe) * vz;*/ vxb = cos(Lthe)*cos(Lphi) * vx + sin(Lphi) * vy; vyb =-cos(Lthe)*sin(Lphi) * vx + cos(Lphi) * vy; vzb = sin(Lthe) * vx; //vx = vxb * cos(PI/2.0-inc) + vzb * sin(PI/2.0-inc); //vy = vyb; //vz =-vxb * sin(PI/2.0-inc) + vzb * cos(PI/2.0-inc); vx = vxb * cos_inc_cmp + vzb * sin_inc_cmp; vy = vyb; vz =-vxb * sin_inc_cmp + vzb * cos_inc_cmp; V = -vx; //note the definition of the line-of-sight velocity. positive means a receding // velocity relative to the observer. if(fabs(V) >= C_Unit) // make sure that the velocity is smaller than speed of light V = 0.9999*C_Unit * (V>0.0?1.0:-1.0); g = (1.0 + V/C_Unit) / sqrt( (1.0 - V*V/C_Unit/C_Unit) ) / sqrt(1.0 - Rs/r); //relativistic effects V = (g-1.0)*C_Unit; clouds_vel[i*parset.n_vel_per_cloud + j] = V; if(flag_save && thistask==roottask) { if(i%(icr_cloud_save) == 0) fprintf(fcloud_out, "%f\t%f\t%f\t%f\t%f\t%f\t%f\n", x, y, z, vx*VelUnit, vy*VelUnit, vz*VelUnit, weight); } } } return; } void restart_action_1d(int iflag) { /* at present, nothing needs to do */ /* FILE *fp; char str[200]; sprintf(str, "%s/data/clouds_%04d.txt", parset.file_dir, thistask); if(iflag == 0) // write fp = fopen(str, "wb"); else // read fp = fopen(str, "rb"); if(fp == NULL) { printf("# Cannot open file %s.\n", str); } if(iflag == 0) { printf("# Writing restart at task %d.\n", thistask); } else { printf("# Reading restart at task %d.\n", thistask); } fclose(fp);*/ return; } void restart_action_2d(int iflag) { restart_action_1d(iflag); } #ifdef SpecAstro void restart_action_sa(int iflag) { restart_action_1d(iflag); } #endif
{ "alphanum_fraction": 0.5269230113, "avg_line_length": 26.560743427, "ext": "c", "hexsha": "df162f205c21e3ab2255d189ef1ad2400d86c98e", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/BRAINS", "max_forks_repo_path": "src/blr_models.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/BRAINS", "max_issues_repo_path": "src/blr_models.c", "max_line_length": 134, "max_stars_count": 6, "max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/BRAINS", "max_stars_repo_path": "src/blr_models.c", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "num_tokens": 20925, "size": 58593 }
#ifndef S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H #define S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H #include "s3d/utilities/rule_of_five.h" #include "s3d/video/capture/video_capture_types.h" #include "s3d/video/video_types.h" #include <gsl/gsl> #include <cstdint> #include <vector> namespace s3d { class StereoDemuxer : public rule_of_five_interface<StereoDemuxer> { public: using InputImageData = gsl::span<const uint8_t>; using OutputImageData = std::vector<uint8_t>; virtual void demux(const InputImageData& image, OutputImageData* leftImage, OutputImageData* rightImage) = 0; virtual Size demuxedSize() const = 0; virtual Stereo3DFormat getStereoFormat() const = 0; virtual void setSize(Size size) = 0; virtual void setPixelFormat(VideoPixelFormat format) = 0; }; } // namespace s3d #endif // S3D_VIDEO_STEREO_DEMUXER_STEREO_DEMUXER_H
{ "alphanum_fraction": 0.7502762431, "avg_line_length": 29.1935483871, "ext": "h", "hexsha": "dfbda76153bf5fb814c1cb8586f064848b2f6cef", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z", "max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "hugbed/OpenS3D", "max_forks_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_issues_count": 40, "max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "hugbed/OpenS3D", "max_issues_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_line_length": 68, "max_stars_count": 8, "max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "hugbed/OpenS3D", "max_stars_repo_path": "src/core/s3d/include/s3d/video/stereo_demuxer/stereo_demuxer.h", "max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z", "num_tokens": 253, "size": 905 }
// Copyright (c) 2013-2017 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 sbessel.h * * \brief Contains implementation of sirius::Spherical_Bessel_functions and sirius::sbessel_approx classes. */ #ifndef __SBESSEL_PW_H__ #define __SBESSEL_PW_H__ #include <gsl/gsl_sf_bessel.h> #include "eigenproblem.h" #include "Unit_cell/unit_cell.h" namespace sirius { /// Spherical Bessel functions \f$ j_{\ell}(q x) \f$ up to lmax. class Spherical_Bessel_functions { private: int lmax_{-1}; double q_{0}; Radial_grid<double> const* rgrid_{nullptr}; std::vector<Spline<double>> sbessel_; public: Spherical_Bessel_functions() { } Spherical_Bessel_functions(int lmax__, Radial_grid<double> const& rgrid__, double q__) : lmax_(lmax__) , q_(q__) , rgrid_(&rgrid__) { assert(q_ >= 0); sbessel_ = std::vector<Spline<double>>(lmax__ + 2); for (int l = 0; l <= lmax__ + 1; l++) { sbessel_[l] = Spline<double>(rgrid__); } std::vector<double> jl(lmax__ + 2); for (int ir = 0; ir < rgrid__.num_points(); ir++) { double t = rgrid__[ir] * q__; gsl_sf_bessel_jl_array(lmax__ + 1, t, &jl[0]); for (int l = 0; l <= lmax__ + 1; l++) { sbessel_[l](ir) = jl[l]; } } for (int l = 0; l <= lmax__ + 1; l++) { sbessel_[l].interpolate(); } } static void sbessel(int lmax__, double t__, double* jl__) { gsl_sf_bessel_jl_array(lmax__, t__, jl__); } static void sbessel_deriv_q(int lmax__, double q__, double x__, double* jl_dq__) { std::vector<double> jl(lmax__ + 2); sbessel(lmax__ + 1, x__ * q__, &jl[0]); for (int l = 0; l <= lmax__; l++) { if (q__ != 0) { jl_dq__[l] = (l / q__) * jl[l] - x__ * jl[l + 1]; } else { if (l == 1) { jl_dq__[l] = x__ / 3; } else { jl_dq__[l] = 0; } } } } Spline<double> const& operator[](int l__) const { assert(l__ <= lmax_); return sbessel_[l__]; } /// Derivative of Bessel function with respect to q. /** \f[ * \frac{\partial j_{\ell}(q x)}{\partial q} = \frac{\ell}{q} j_{\ell}(q x) - x j_{\ell+1}(q x) * \f] */ Spline<double> deriv_q(int l__) { assert(l__ <= lmax_); assert(q_ >= 0); Spline<double> s(*rgrid_); if (q_ != 0) { for (int ir = 0; ir < rgrid_->num_points(); ir++) { s(ir) = (l__ / q_) * sbessel_[l__](ir) - (*rgrid_)[ir] * sbessel_[l__ + 1](ir); } } else { if (l__ == 1) { for (int ir = 0; ir < rgrid_->num_points(); ir++) { s(ir) = (*rgrid_)[ir] / 3; } } } s.interpolate(); return std::move(s); } }; class sbessel_approx { private: Unit_cell const& unit_cell_; int lmax_; mdarray<std::vector<double>, 2> qnu_; mdarray<double, 4> coeffs_; int nqnu_max_; static double sbessel_l2norm(double nu, int l, double R) { if (std::abs(nu) < 1e-10) TERMINATE_NOT_IMPLEMENTED; if (l == 0) { return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3); } else { double jl[l + 2]; gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]); return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2; } } public: sbessel_approx(Unit_cell const& unit_cell__, int lmax__, double const qmin__, double const qmax__, double const eps__) : unit_cell_(unit_cell__), lmax_(lmax__) { PROFILE("sirius::sbessel_approx"); qnu_ = mdarray<std::vector<double>, 2>(lmax_ + 1, unit_cell_.num_atom_types()); for (int l = 0; l <= lmax_; l++) { for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { qnu_(l, iat) = build_approx_freq(qmin__, qmax__, l, unit_cell_.atom_type(iat).mt_radius(), eps__); } } nqnu_max_ = 0; for (int l = 0; l <= lmax_; l++) { for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { nqnu_max_ = std::max(nqnu_max_, static_cast<int>(qnu_(l, iat).size())); } } } void approximate(std::vector<double> const& q__) { PROFILE("sirius::sbessel_approx::approximate"); coeffs_ = mdarray<double, 4>(nqnu_max_, q__.size(), lmax_ + 1, unit_cell_.num_atom_types()); #pragma omp parallel for for (int l = 0; l <= lmax_; l++) { for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { int n = nqnu(l, iat); mdarray<double, 2> A(n, n); for (int iq = 0; iq < n; iq++) { for (int jq = 0; jq <= iq; jq++) { A(jq, iq) = A(iq, jq) = overlap(qnu_(l, iat)[jq], qnu_(l, iat)[iq], l, unit_cell_.atom_type(iat).mt_radius()); } for (int j = 0; j < (int)q__.size(); j++) { if (std::abs(q__[j]) < 1e-12) { coeffs_(iq, j, l, iat) = 0; } else { coeffs_(iq, j, l, iat) = overlap(qnu_(l, iat)[iq], q__[j], l, unit_cell_.atom_type(iat).mt_radius()); } } } linalg<CPU>::gesv(n, (int)q__.size(), A.at<CPU>(), A.ld(), &coeffs_(0, 0, l, iat), coeffs_.ld()); } } } inline double qnu(int const iq, int const l, int const iat) { return qnu_(l, iat)[iq]; } inline int nqnu(int const l, int const iat) { return static_cast<int>(qnu_(l, iat).size()); } inline int nqnu_max() { return nqnu_max_; } inline double coeff(int const iq, int const j, int const l, int const iat) { return coeffs_(iq, j, l, iat); } // \int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr // this integral can be computed analytically static double overlap(double nu1__, double nu2__, int l__, double R__) { if (std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) TERMINATE_NOT_IMPLEMENTED; if (std::abs(nu1__ - nu2__) < 1e-12) { if (l__ == 0) { return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3); } else { double jl[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]); return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2; } } else { if (l__ == 0) { return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) / (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3)); } else { double j1[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]); double j2[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]); return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2)); } } } std::vector<double> build_approx_freq(double const qmin__, double const qmax__, int const l__, double const R__, double const eps__) { std::vector<double> qnu; double min_val; int n = 2; do { n++; qnu.resize(n); for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1); dmatrix<double_complex> ovlp(n, n); for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { double o = overlap(qnu[j], qnu[i], l__, R__); ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__); } } std::vector<double> eval(n); dmatrix<double_complex> z(n, n); Eigensolver_lapack<double_complex> solver; solver.solve(n, ovlp, &eval[0], z); min_val = eval[0]; } while (min_val > eps__); return qnu; } }; class Spherical_Bessel_approximant { private: int lmax_; double R_; /// List of Bessel function scaling factors for each angular momentum. std::vector< std::vector<double> > qnu_; //mdarray<double, 4> coeffs_; int nqnu_max_; static double sbessel_l2norm(double nu, int l, double R) { if (std::abs(nu) < 1e-10) { if (l == 0) return std::pow(R, 3) / 3.0; return 0; } if (l == 0) { return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3); } else { double jl[l + 2]; gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]); return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2; } } public: Spherical_Bessel_approximant(int lmax__, double R__, double const qmin__, double const qmax__, double const eps__) : lmax_(lmax__), R_(R__) { PROFILE("sirius::Spherical_Bessel_approximant"); qnu_ = std::vector< std::vector<double> >(lmax_ + 1); #pragma omp parallel for for (int l = 0; l <= lmax_; l++) qnu_[l] = build_approx_freq(qmin__, qmax__, l, R_, eps__); nqnu_max_ = 0; for (int l = 0; l <= lmax_; l++) nqnu_max_ = std::max(nqnu_max_, nqnu(l)); } std::vector<double> approximate(int l__, double nu__) { int n = nqnu(l__); std::vector<double> x(n); matrix<double> A(n, n); for (int iq = 0; iq < n; iq++) { for (int jq = 0; jq <= iq; jq++) { A(jq, iq) = A(iq, jq) = overlap(qnu(jq, l__), qnu(iq, l__), l__, R_); } x[iq] = overlap(qnu(iq, l__), nu__, l__, R_); } linalg<CPU>::gesv(n, 1, A.at<CPU>(), A.ld(), &x[0], n); return x; } void approximate(std::vector<double> const& q__) { //runtime::Timer t("sirius::sbessel_approx::approximate"); //coeffs_ = mdarray<double, 4>(nqnu_max_, q__.size(), lmax_ + 1, unit_cell_.num_atom_types()); // //#pragma omp parallel for //for (int l = 0; l <= lmax_; l++) //{ // for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) // { // int n = nqnu(l, iat); // mdarray<double, 2> A(n, n); // for (int iq = 0; iq < n; iq++) // { // for (int jq = 0; jq <= iq; jq++) // { // A(jq, iq) = A(iq, jq) = overlap(qnu_(l, iat)[jq], qnu_(l, iat)[iq], l, // unit_cell_.atom_type(iat).mt_radius()); // } // for (int j = 0; j < (int)q__.size(); j++) // { // if (std::abs(q__[j]) < 1e-12) // { // coeffs_(iq, j, l, iat) = 0; // } // else // { // coeffs_(iq, j, l, iat) = overlap(qnu_(l, iat)[iq], q__[j], l, // unit_cell_.atom_type(iat).mt_radius()); // } // } // } // linalg<CPU>::gesv(n, (int)q__.size(), A.at<CPU>(), A.ld(), &coeffs_(0, 0, l, iat), coeffs_.ld()); // } //} } inline double qnu(int const iq, int const l) const { return qnu_[l][iq]; } inline int nqnu(int const l) const { return static_cast<int>(qnu_[l].size()); } inline int nqnu_max() const { return nqnu_max_; } //inline double coeff(int const iq, int const j, int const l, int const iat) //{ // return coeffs_(iq, j, l, iat); //} // // \int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr // this integral can be computed analytically static double overlap(double nu1__, double nu2__, int l__, double R__) { if (std::abs(nu1__) < 1e-10 && std::abs(nu2__) < 1e-10 && l__ == 0) return std::pow(R__, 3) / 3.0; if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ > 0) return 0; if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ == 0) { double nu = std::max(nu1__, nu2__); double nuR = nu * R__; return (std::sin(nuR) - nuR * std::cos(nuR)) / std::pow(nu, 3); } if (std::abs(nu1__ - nu2__) < 1e-12) { if (l__ == 0) { return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3); } else { double jl[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]); return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2; } } else { if (l__ == 0) { return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) / (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3)); } else { double j1[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]); double j2[l__ + 2]; gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]); return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2)); } } TERMINATE("this is wrong"); return -1; } std::vector<double> build_approx_freq(double const qmin__, double const qmax__, int const l__, double const R__, double const eps__) { std::vector<double> qnu; double min_val; int n = 2; do { n++; qnu.resize(n); for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1); dmatrix<double> ovlp(n, n); for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { double o = overlap(qnu[j], qnu[i], l__, R__); ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__); } } std::vector<double> eval(n); dmatrix<double> z(n, n); Eigensolver_lapack<double> solver; solver.solve(n, ovlp, &eval[0], z); min_val = eval[0]; } while (min_val > eps__); return qnu; } }; class Spherical_Bessel_approximant2 { private: int lmax_; double R_; /// List of Bessel function scaling factors for each angular momentum. std::vector<double> qnu_; static double sbessel_l2norm(double nu, int l, double R) { if (std::abs(nu) < 1e-10) { if (l == 0) return std::pow(R, 3) / 3.0; return 0; } if (l == 0) { return (nu * R * 2 - std::sin(nu * R * 2)) / 4 / std::pow(nu, 3); } else { double jl[l + 2]; gsl_sf_bessel_jl_array(l + 1, R * nu, &jl[0]); return std::pow(R, 3) * (jl[l] * jl[l] - jl[l + 1] * jl[l - 1]) / 2; } } public: Spherical_Bessel_approximant2(int lmax__, double R__, double const qmin__, double const qmax__, int nq__) : lmax_(lmax__), R_(R__) { PROFILE("sirius::Spherical_Bessel_approximant"); int nq = nfreq(qmin__, qmax__, 0, R__, 1e-12); qnu_.resize(nq); for (int i = 0; i < nq; i++) qnu_[i] = qmin__ + (qmax__ - qmin__) * i / (nq - 1); } std::vector<double> approximate(int l__, double nu__) { int n = nqnu(); std::vector<double> x(n); matrix<double> A(n, n); for (int iq = 0; iq < n; iq++) { for (int jq = 0; jq <= iq; jq++) { A(jq, iq) = A(iq, jq) = overlap(qnu(jq), qnu(iq), l__, R_); } x[iq] = overlap(qnu(iq), nu__, l__, R_); } linalg<CPU>::gesv(n, 1, A.at<CPU>(), A.ld(), &x[0], n); return x; } inline double qnu(int const iq) const { return qnu_[iq]; } inline int nqnu() const { return static_cast<int>(qnu_.size()); } // \int_0^{R} j(nu1 * r) * j(nu2 * r) * r^2 dr // this integral can be computed analytically static double overlap(double nu1__, double nu2__, int l__, double R__) { if (std::abs(nu1__) < 1e-10 && std::abs(nu2__) < 1e-10 && l__ == 0) return std::pow(R__, 3) / 3.0; if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ > 0) return 0; if ((std::abs(nu1__) < 1e-10 || std::abs(nu2__) < 1e-10) && l__ == 0) { double nu = std::max(nu1__, nu2__); double nuR = nu * R__; return (std::sin(nuR) - nuR * std::cos(nuR)) / std::pow(nu, 3); } if (std::abs(nu1__ - nu2__) < 1e-12) { if (l__ == 0) { return (nu2__ * R__ * 2 - std::sin(nu2__ * R__ * 2)) / 4 / std::pow(nu2__, 3); } else { std::vector<double> jl(l__ + 2); gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &jl[0]); return std::pow(R__, 3) * (jl[l__] * jl[l__] - jl[l__ + 1] * jl[l__ - 1]) / 2; } } else { if (l__ == 0) { return (nu2__ * std::cos(nu2__ * R__) * std::sin(nu1__ * R__) - nu1__ * std::cos(nu1__ * R__) * std::sin(nu2__ * R__)) / (std::pow(nu1__, 3) * nu2__ - nu1__ * std::pow(nu2__, 3)); } else { std::vector<double> j1(l__ + 2); gsl_sf_bessel_jl_array(l__ + 1, R__ * nu1__, &j1[0]); std::vector<double> j2(l__ + 2); gsl_sf_bessel_jl_array(l__ + 1, R__ * nu2__, &j2[0]); return std::pow(R__, 2) * (nu2__ * j2[l__ - 1] * j1[l__] - nu1__ * j1[l__ - 1] * j2[l__]) / (std::pow(nu1__, 2) - std::pow(nu2__, 2)); } } TERMINATE("this is wrong"); return -1; } int nfreq(double const qmin__, double const qmax__, int const l__, double const R__, double const eps__) { std::vector<double> qnu; double min_val; int n = 2; do { n++; qnu.resize(n); for (int i = 0; i < n; i++) qnu[i] = qmin__ + (qmax__ - qmin__) * i / (n - 1); dmatrix<double> ovlp(n, n); for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { double o = overlap(qnu[j], qnu[i], l__, R__); ovlp(j, i) = o / sbessel_l2norm(qnu[i], l__, R__) / sbessel_l2norm(qnu[j], l__, R__); } } std::vector<double> eval(n); dmatrix<double> z(n, n); Eigensolver_lapack<double> solver; solver.solve(n, ovlp, &eval[0], z); min_val = eval[0]; if (n > 100) return 100; } while (min_val > eps__); return n; } }; }; #endif
{ "alphanum_fraction": 0.4068694326, "avg_line_length": 34.1865569273, "ext": "h", "hexsha": "ad93b931937434fdf4572ed28f2c3e02fc353a59", "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": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ckae95/SIRIUS", "max_forks_repo_path": "src/sbessel.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "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": "ckae95/SIRIUS", "max_issues_repo_path": "src/sbessel.h", "max_line_length": 154, "max_stars_count": null, "max_stars_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ckae95/SIRIUS", "max_stars_repo_path": "src/sbessel.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6715, "size": 24922 }
#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 <stdbool.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/theory/basics.c" #include "../cosmolike_core/theory/structs.c" #include "../cosmolike_core/theory/parameters.c" #include "../cosmolike_core/emu17/P_cb/emu.c" #include "../cosmolike_core/theory/recompute.c" #include "../cosmolike_core/theory/cosmo3D.c" #include "../cosmolike_core/theory/redshift_spline.c" #include "../cosmolike_core/theory/halo.c" #include "../cosmolike_core/theory/HOD.c" #include "../cosmolike_core/theory/pt.c" #include "../cosmolike_core/theory/cosmo2D_fourier.c" #include "../cosmolike_core/theory/IA.c" #include "../cosmolike_core/theory/BAO.c" #include "../cosmolike_core/theory/external_prior.c" #include "../cosmolike_core/theory/covariances_3D.c" #include "../cosmolike_core/theory/covariances_fourier.c" #include "../cosmolike_core/theory/CMBxLSS_fourier.c" #include "../cosmolike_core/theory/covariances_CMBxLSS_fourier.c" #include "init_LSSxCMB.c" // Naming convention: // l = galaxy positions ("l" as in "lens sample") // k = kappa CMB ("k" as in "kappa") // s = kappa from source galaxies ("s" as in "source sample") // And alphabetical order void run_cov_ls_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ll_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ll_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ll_ll(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ls_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ss_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ls_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start); void run_cov_ls_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start); void run_cov_lk_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zl2, int start); void run_cov_lk_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2, int start); void run_cov_lk_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int start); void run_cov_lk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zs2, int start); void run_cov_lk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2,int start); void run_cov_kk_kk(char *OUTFILE, char *PATH, double *ell, double *dell,int start); void run_cov_kk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs2, int start); void run_cov_kk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n2, int start); void run_cov_ks_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int zs2,int start); void run_cov_ks_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int n2, int start); void run_cov_ll_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start); void run_cov_ll_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start); void run_cov_ll_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zl2,int start); void run_cov_ls_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int zl,zs,z3,z4,nl1,nl2,weight,i,j; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl = ZL(n1); zs = ZS(n1); printf("\nN_ggl = %d (%d, %d)\n", n1,zl,zs); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n", n2,z3,z4); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 <like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl); if (weight && ell[nl2] < like.lmax_shear){ if (test_zoverlap(zl,z3)*test_zoverlap(zl,z4)){ c_ng = cov_NG_gl_shear_tomo(ell[nl1],ell[nl2],zl,zs,z3,z4); } if (nl1 == nl2){ c_g = cov_G_gl_shear_tomo(ell[nl1],dell[nl1],zl,zs,z3,z4); } } i=like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1; j=like.Ncl*n2+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl,zs,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_ll_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl = %d \n", n1); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n", n2,z3,z4); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 <like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],z1); if (weight && ell[nl2] < like.lmax_shear){ if (test_zoverlap(z1,z3)*test_zoverlap(z1,z4)){ c_ng = cov_NG_cl_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_cl_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*n2+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_ll_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,zl,zs,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl_1 = %d \n", n1); zl = ZL(n2); zs = ZS(n2); printf("N_tomo_2 = %d (%d, %d)\n", n2,zl,zs); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],zl); if (weight){ if((z1 == zl)*test_zoverlap(z1,zs)){c_ng = cov_NG_cl_gl_tomo(ell[nl1],ell[nl2],z1,z2,zl,zs);} if (nl1 == nl2){ c_g = cov_G_cl_gl_tomo(ell[nl1],dell[nl1],z1,z2,zl,zs); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],z1,z2,zl,zs,c_g,c_ng); } } fclose(F1); } void run_cov_ll_ll(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl_1 = %d \n", n1); z3 = n2; z4 = n2; printf("N_cl_2 = %d\n", n2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],z3); if ((z1 == z3) && weight) { c_ng = cov_NG_cl_cl_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_cl_cl_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n2)+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_ls_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int zl1,zl2,zs1,zs2,nl1,nl2,i,j,weight; double c_ng, c_g; double fsky = survey.area/41253.0; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl1 = ZL(n1); zs1 = ZS(n1); printf("\nN_tomo_1 = %d (%d, %d)\n", n1,zl1,zs1); zl2 = ZL(n2); zs2 = ZS(n2); printf("N_tomo_2 = %d (%d, %d)\n", n2,zl2,zs2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1)*test_kmax(ell[nl2],zl2); if (weight && zl1 == zl2) { c_ng = cov_NG_gl_gl_tomo(ell[nl1],ell[nl2],zl1,zs1,zl2,zs2); } if (nl1 == nl2){ c_g = cov_G_gl_gl_tomo(ell[nl1],dell[nl1],zl1,zs1,zl2,zs2); } if (weight ==0 && n2 != n1){ c_g = 0; } i=like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,zs1,zl2,zs2,c_g,c_ng); } } fclose(F1); } void run_cov_ss_ss(char *OUTFILE, char *PATH, double *ell, double *dell,int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; z1 = Z1(n1); z2 = Z2(n1); printf("N_shear = %d\n", n1); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n",n2,z3,z4); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1] < like.lmax_shear && ell[nl2] < like.lmax_shear){ c_ng = cov_NG_shear_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_shear_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); if (ell[nl1] > like.lmax_shear && n1!=n2){c_g = 0.;} } i=like.Ncl*n1+nl1; j=like.Ncl*n2+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); //printf("%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } /*** CMBkappa part ****/ // ls_kk void run_cov_ls_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start) { int zl1, zs1,i,j, weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl1 = ZL(n1); zs1 = ZS(n1); printf("Bin for ls: %d (%d, %d)\n", n1, zl1, zs1); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1], zl1); if (weight && ell[nl2]<like.lmax_kappacmb) { c_ng = cov_NG_gs_kk(ell[nl1],ell[nl2], zl1, zs1); if (nl1==nl2){ c_g = cov_G_gs_kk(ell[nl1], dell[nl1], zl1, zs1); } } i=like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,zs1,0,0,c_g,c_ng); } } fclose(F1); } // ls_ks void run_cov_ls_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start) { int zl1, zs1,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl1 = ZL(n1); zs1 = ZS(n1); printf("Bin for ls: %d (%d, %d)\n", n1, zl1, zs1); printf("Bin for ks: %d\n", zs2); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1], zl1); if (weight && ell[nl2]<like.lmax_kappacmb) { if (test_zoverlap(zl1, zs2)) { c_ng = cov_NG_gs_ks(ell[nl1],ell[nl2], zl1, zs1, zs2); } if (nl1==nl2){ c_g = cov_G_gs_ks(ell[nl1], dell[nl1], zl1, zs1, zs2); } } i=like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,zs1,0,zs2,c_g,c_ng); } } fclose(F1); } // lk_lk void run_cov_lk_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zl2, int start) { int weight,i,j; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Lens bins: %d, %d\n", zl1, zl2); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1)*test_kmax(ell[nl2],zl2); bool compute = weight * (ell[nl1]<like.lmax_kappacmb) * (ell[nl2]<like.lmax_kappacmb); if (compute && (zl1==zl2)) { c_ng = cov_NG_gk_gk(ell[nl1],ell[nl2], zl1, zl2); } if (nl1==nl2){ c_g = cov_G_gk_gk(ell[nl1], dell[nl1], zl1, zl2); } if (!compute && (zl2!=zl1)) { c_g = 0; } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,0,zl2,0,c_g,c_ng); } } fclose(F1); } // lk_ls void run_cov_lk_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2, int start) { int zl2,zs2,nl1,nl2,i,j, weight; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_gkgs_Nell%d_Ns%d_Ng%d_%d", PATH, survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Lens bin for lk: %d\n", zl1); zl2 = ZL(n2); zs2 = ZS(n2); printf("N_tomo for ls = %d (%d, %d)\n", n2,zl2,zs2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1)*test_kmax(ell[nl2],zl2); if (weight && ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb) { if (zl1==zl2) { c_ng = cov_NG_gk_gs(ell[nl1],ell[nl2],zl1,zl2,zs2); } if (nl1==nl2){ c_g = cov_G_gk_gs(ell[nl1], dell[nl1], zl1,zl2,zs2); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,0,zl2,zs2,c_g,c_ng); } } fclose(F1); } // lk_kk void run_cov_lk_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int start) { int weight,i,j; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_gkkk_Nell%d_Ns%d_Ng%d_%d", PATH, survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Bin for lk: %d\n", zl1); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1); if (weight && ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb) { c_ng = cov_NG_gk_kk(ell[nl1],ell[nl2],zl1); if (nl1==nl2){ c_g = cov_G_gk_kk(ell[nl1],dell[nl1],zl1); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,0,0,0,c_g,c_ng); } } fclose(F1); } // lk_ks void run_cov_lk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zs2, int start) { int weight,i,j; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_gkks_Nell%d_Ns%d_Ng%d_%d", PATH, survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Bin for lk: %d\n", zl1); printf("Bin for ks: %d\n", zs2); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1], zl1); if (weight && ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb) { if (test_zoverlap(zl1, zs2)) { c_ng = cov_NG_gk_ks(ell[nl1],ell[nl2], zl1, zs2); } if (nl1==nl2){ c_g = cov_G_gk_ks(ell[nl1], dell[nl1], zl1, zs2); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,0,0,zs2,c_g,c_ng); } } fclose(F1); } // lk_ss void run_cov_lk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2,int start) { int zs2,zs3,nl1,nl2,weight,i,j; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_gkss_Nell%d_Ns%d_Ng%d_%d",PATH,survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Bin for lk: %d\n", zl1); zs2 = Z1(n2); zs3 = Z2(n2); printf("Bin for ss: %d (%d, %d)\n", n2, zs2, zs3); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 <like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1); if (weight && ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_shear){ if (test_zoverlap(zl1, zs2)*test_zoverlap(zl1, zs3)) { c_ng = cov_NG_gk_ss(ell[nl1],ell[nl2],zl1,zs2,zs3); } if (nl1==nl2){ c_g = cov_G_gk_ss(ell[nl1],dell[nl1],zl1,zs2, zs3); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl1)+nl1; j=like.Ncl*n2+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],zl1,0,zs2,zs3,c_g,c_ng); } } fclose(F1); } // kk_kk void run_cov_kk_kk(char *OUTFILE, char *PATH, double *ell, double *dell,int start) { int nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_kkkk_Nell%d_Ns%d_Ng%d_%d",PATH,survey.name, cmb.name,like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb){ c_ng = cov_NG_kk_kk(ell[nl1],ell[nl2]); } if (nl1==nl2){ c_g = cov_G_kk_kk(ell[nl1], dell[nl1]); } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],0,0,0,0,c_g,c_ng); // printf("l1, l2, Cg, Cng = %le, %le, %le, %le\n", ell[nl1], ell[nl2], c_g, c_ng); } } fclose(F1); } // kk_ks void run_cov_kk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs2, int start) { int nl1,nl2,i,j, weight; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_kkks_Nell%d_Ns%d_Ng%d_%d", PATH, survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Source bin for ks: %d\n", zs2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb) { c_ng = cov_NG_kk_ks(ell[nl1],ell[nl2],zs2); if (nl1==nl2){ c_g = cov_G_kk_ks(ell[nl1],dell[nl1], zs2); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],0,0,0,zs2,c_g,c_ng); } } fclose(F1); } // kk_ss void run_cov_kk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n2, int start) { int z2,z3,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; z2 = Z1(n2); z3 = Z2(n2); printf("Bin for ss: %d (%d, %d)\n", n2, z2, z3); // sprintf(filename,"%scov/%s_%s_cov_kkss_Nell%d_Ns%d_Ng%d_%d",PATH,survey.name, cmb.name,like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_shear){ c_ng = cov_NG_kk_ss(ell[nl1],ell[nl2],z2,z3); if (nl1==nl2){ c_g = cov_G_kk_ss(ell[nl1],dell[nl1],z2,z3); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl1; j=like.Ncl*n2+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],0,0,z2,z3,c_g,c_ng); } } fclose(F1); } // ks_ks void run_cov_ks_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int zs2,int start) { int nl1,nl2,i,j, weight; double c_ng, c_g; FILE *F1; char filename[300]; // sprintf(filename,"%scov/%s_%s_cov_ksks_Nell%d_Ns%d_Ng%d_%d", PATH, survey.name, cmb.name, like.Ncl, tomo.shear_Nbin, tomo.clustering_Nbin, start); // printf("Saving to: %s\n",filename); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); printf("Source bins for ks: %d, %d\n", zs1, zs2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_kappacmb) { c_ng = cov_NG_ks_ks(ell[nl1],ell[nl2],zs1,zs2); } if (nl1==nl2){ c_g = cov_G_ks_ks(ell[nl1],dell[nl1], zs1, zs2); } if ((ell[nl1]>like.lmax_kappacmb || ell[nl2]>like.lmax_kappacmb) && zs2!=zs1){ c_g = 0; } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],0,zs1,0,zs2,c_g,c_ng); } } fclose(F1); } // ks_ss void run_cov_ks_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int n2, int start) { int z2,z3,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; z2 = Z1(n2); z3 = Z2(n2); printf("Source bin for ks: %d\n", zs1); printf("Bin for ss: %d (%d, %d)\n", n2, z2, z3); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1]<like.lmax_kappacmb && ell[nl2]<like.lmax_shear){ c_ng = cov_NG_ks_ss(ell[nl1],ell[nl2],zs1,z2,z3); if (nl1==nl2){ c_g = cov_G_ks_ss(ell[nl1],dell[nl1],zs1,z2,z3); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs1)+nl1; j=like.Ncl*n2+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],0,zs1,z2,z3,c_g,c_ng); } } fclose(F1); } // ll_kk void run_cov_ll_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start) { int i,j, weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); // zl1 = ZL(n1); zs1 = ZS(n1); printf("Bin for ll: %d \n", n1); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1], n1); if (weight && ell[nl2]<like.lmax_kappacmb) { c_ng = cov_NG_gg_kk(ell[nl1],ell[nl2], n1, n1); if (nl1==nl2){ c_g = cov_G_gg_kk(ell[nl1], dell[nl1], n1, n1); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+tomo.shear_Nbin)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],n1,n1,0,0,c_g,c_ng); } } fclose(F1); } // ll_ks void run_cov_ll_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start) { int i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); // zl1 = ZL(n1); zs1 = ZS(n1); printf("Bin for ll: %d\n", n1); printf("Bin for ks: %d\n", zs2); for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1], n1); if (weight && ell[nl2]<like.lmax_kappacmb) { if (test_zoverlap(n1, zs2)) { c_ng = cov_NG_gg_ks(ell[nl1],ell[nl2], n1, n1, zs2); } if (nl1==nl2){ c_g = cov_G_gg_ks(ell[nl1], dell[nl1], n1, n1, zs2); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2; fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],n1,n1,0,zs2,c_g,c_ng); } } fclose(F1); } // ll_lk void run_cov_ll_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zl2,int start) { int z1,z2,zl,zs,nl1,nl2,i,j,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl_1 = %d \n", n1); // zl = ZL(n2); zs = ZS(n2); zl = zl2; printf("N_tomo_2 = %d\n", zl2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],zl); if (weight){ if((z1 == zl)) {c_ng = cov_NG_gg_gk(ell[nl1],ell[nl2],z1,z2,zl);} if (nl1 == nl2){ c_g = cov_G_gg_gk(ell[nl1],dell[nl1],z1,z2,zl); } } i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1; j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+zl)+nl2; fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell[nl2],z1,z2,zl,0,c_g,c_ng); } } fclose(F1); } int main(int argc, char** argv) { int i,l,m,n,o,s,p,nl1,t,k; char OUTFILE[400],filename[400],arg1[400],arg2[400]; int N_scenarios=2; double area_table[2]={18000.0,2000.0}; double nsource_table[2]={43.0,51.0}; double nlens_table[2]={50.0,66.0}; char survey_designation[2][200]={"WFIRSTwidexSO5","WFIRSTstdxSO5"}; char source_zfile[2][400]={"zdistri_WFIRST_LSST_lensing_fine_bin","zdistri_WFIRST_LSST_lensing_fine_bin"}; #ifdef ONESAMPLE char lens_zfile[2][400]={"zdistri_WFIRST_LSST_lensing_fine_bin","zdistri_WFIRST_LSST_lensing_fine_bin"}; nlens_table[0] = nsource_table[0]; nlens_table[1] = nsource_table[1]; #else char lens_zfile[2][400]={"zdistri_WFIRST_LSST_clustering_fine_bin","zdistri_WFIRST_LSST_clustering_fine_bin"}; #endif int hit=atoi(argv[1]); Ntable.N_a=100; k=1; t = atoi(argv[2]); //RUN MODE setup init_cosmo_runmode("emu"); // init_binning_fourier(20,30.0,3000.0,3000.0,21.0,10,10); init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10); init_survey(survey_designation[t],nsource_table[t],nlens_table[t],area_table[t]); sprintf(arg1,"zdistris/%s",source_zfile[t]); sprintf(arg2,"zdistris/%s",lens_zfile[t]); init_galaxies(arg1,arg2,"none","none","source_std","WF_SN10"); init_IA("none","GAMA"); init_probes("6x2pt"); init_cmb("so_Y5"); //set l-bins for shear, ggl, clustering, clusterWL double logdl=(log(like.lmax)-log(like.lmin))/like.Ncl; double *ell, *dell, *ell_Cluster, *dell_Cluster; ell=create_double_vector(0,like.Ncl-1); dell=create_double_vector(0,like.Ncl-1); ell_Cluster=create_double_vector(0,Cluster.lbin-1); dell_Cluster=create_double_vector(0,Cluster.lbin-1); int j=0; for(i=0;i<like.Ncl;i++){ ell[i]=exp(log(like.lmin)+(i+0.5)*logdl); dell[i]=exp(log(like.lmin)+(i+1)*logdl)-exp(log(like.lmin)+(i*logdl)); if(ell[i]<like.lmax_shear) printf("%le\n",ell[i]); } printf("----------------------------------\n"); sprintf(survey.name,"%s_area%le_ng%le_nl%le",survey_designation[t],survey.area,survey.n_gal,survey.n_lens); printf("area: %le n_source: %le n_lens: %le\n",survey.area,survey.n_gal,survey.n_lens); // sprintf(covparams.outdir,"/home/u17/timeifler/covparallel/"); #ifdef ONESAMPLE sprintf(covparams.outdir,"out_cov_wfirstxso_1sample/"); #else sprintf(covparams.outdir,"out_cov_wfirstxso/"); //sprintf(covparams.outdir,"/halo_nobackup/cosmos/teifler/covparallel/"); #endif printf("----------------------------------\n"); sprintf(OUTFILE,"%s_ssss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=l;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ss_ss(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_lsls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=l;m<tomo.ggl_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ls_ls(OUTFILE,covparams.outdir,ell,dell,l,m,k); } //printf("%d\n",k); k=k+1; } } sprintf(OUTFILE,"%s_llll_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ //auto bins only for now! for (m=l;m<tomo.clustering_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_ll(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; //printf("%d %d %d\n",l,m,k); } } sprintf(OUTFILE,"%s_llss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_ss(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_llls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.ggl_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_ls(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_lsss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ls_ss(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; //printf("%d\n",k); } } // lk_lk sprintf(OUTFILE,"%s_lklk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Nbin; l++){ for (m=l;m<tomo.clustering_Nbin; m++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_lk_lk(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; } } printf("lklk %d\n",k); // lk_ls sprintf(OUTFILE,"%s_lkls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Nbin; l++){ for (m=0;m<tomo.ggl_Npowerspectra; m++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_lk_ls(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; } } printf("lkls %d\n",k); // lk_kk sprintf(OUTFILE,"%s_lkkk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Nbin; l++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_lk_kk(OUTFILE,covparams.outdir,ell,dell,l,k); } // printf("%d\n",k); k=k+1; } printf("lkkk %d\n",k); // lk_ks sprintf(OUTFILE,"%s_lkks_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Nbin; l++){ for (m=0;m<tomo.shear_Nbin;m++) { if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_lk_ks(OUTFILE,covparams.outdir,ell,dell,l,m,k); } // printf("%d\n",k); k=k+1; } } printf("lkks %d\n",k); // lk_ss sprintf(OUTFILE,"%s_lkss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Nbin; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_lk_ss(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; // printf("%d\n",k); } } printf("lkss %d\n",k); // ls_kk sprintf(OUTFILE,"%s_lskk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ls_kk(OUTFILE,covparams.outdir,ell,dell,l,k); } // printf("%d\n",k); k=k+1; } printf("lskk%d\n",k); // ls_ks sprintf(OUTFILE,"%s_lsks_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.shear_Nbin;m++) { if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ls_ks(OUTFILE,covparams.outdir,ell,dell,l,m,k); } // printf("%d\n",k); k=k+1; } } printf("lsks %d\n",k); // kk_kk sprintf(OUTFILE,"%s_kkkk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_kk_kk(OUTFILE,covparams.outdir,ell,dell,k); } // printf("%d\n",k); k=k+1; printf("kkkk %d\n",k); // kk_ks sprintf(OUTFILE,"%s_kkks_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Nbin; l++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_kk_ks(OUTFILE,covparams.outdir,ell,dell,l,k); } // printf("%d\n",k); k=k+1; } printf("kkks %d\n",k); // kk_ss sprintf(OUTFILE,"%s_kkss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_kk_ss(OUTFILE,covparams.outdir,ell,dell,l,k); } k=k+1; // printf("%d\n",k); } printf("kkss %d\n",k); // ks_ks sprintf(OUTFILE,"%s_ksks_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Nbin; l++){ for (m=l;m<tomo.shear_Nbin; m++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ks_ks(OUTFILE,covparams.outdir,ell,dell,l,m,k); } // printf("%d\n",k); k=k+1; } } printf("ksks %d\n",k); // ks_ss sprintf(OUTFILE,"%s_ksss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Nbin; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ks_ss(OUTFILE,covparams.outdir,ell,dell,l,m,k); } k=k+1; // printf("%d\n",k); } } printf("ksss %d\n",k); // ll_kk sprintf(OUTFILE,"%s_llkk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_kk(OUTFILE,covparams.outdir,ell,dell,l,k); } // printf("%d\n",k); k=k+1; } printf("llkk %d\n",k); // ll_ks sprintf(OUTFILE,"%s_llks_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.shear_Nbin;m++) { if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_ks(OUTFILE,covparams.outdir,ell,dell,l,m,k); } // printf("%d\n",k); k=k+1; } } printf("llks %d\n",k); // ll_lk sprintf(OUTFILE,"%s_lllk_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.clustering_Nbin;m++) { if (k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); run_cov_ll_lk(OUTFILE,covparams.outdir,ell,dell,l,m,k); } // printf("%d\n",k); k=k+1; } } printf("lllk %d\n",k); printf("number of cov blocks for parallelization: %d\n",k-1); printf("-----------------\n"); printf("PROGRAM EXECUTED\n"); printf("-----------------\n"); return 0; }
{ "alphanum_fraction": 0.6000455615, "avg_line_length": 36.4455719557, "ext": "c", "hexsha": "04d64e90d9f766b84c5fd19095a9ce7be0e8fc62", "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": "compute_covariances_fourier_wfirstxso.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": "compute_covariances_fourier_wfirstxso.c", "max_line_length": 152, "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": "compute_covariances_fourier_wfirstxso.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15121, "size": 39507 }
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <immintrin.h> #include <omp.h> #include <Python.h> #include <numpy/arrayobject.h> #include <cblas.h> static PyObject *smmprod_func(PyObject* self, PyObject* args) { PyObject *A_obj = NULL; PyObject *A_arr = NULL; PyArrayObject *A = NULL; PyObject *B_obj = NULL; PyObject *B_arr = NULL; PyArrayObject *B = NULL; PyObject *Omega_obj = NULL; PyObject *Omega_row_arr = NULL; PyObject *Omega_col_arr = NULL; PyObject *Omega_seq = NULL; PyArrayObject *Omega_row = NULL; PyArrayObject *Omega_col = NULL; PyObject *Out_obj = NULL; PyObject *Out_arr = NULL; PyArrayObject *Out = NULL; int result = PyArg_ParseTuple( args, "OOOO", &A_obj, &B_obj, &Omega_obj, &Out_obj ); if (!result) { return NULL; } A_arr = PyArray_FROM_OTF(A_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (A_arr == NULL) { return NULL; } A = (PyArrayObject*) A_arr; B_arr = PyArray_FROM_OTF(B_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (B_arr == NULL) { return NULL; } B = (PyArrayObject*) B_arr; Omega_seq = PySequence_Fast(Omega_obj, "expected a sequence"); Omega_row_arr = PyArray_FROM_OTF(PySequence_Fast_GET_ITEM(Omega_seq, 0), NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (Omega_row_arr == NULL) { return NULL; } Omega_row = (PyArrayObject*) Omega_row_arr; Omega_col_arr = PyArray_FROM_OTF(PySequence_Fast_GET_ITEM(Omega_seq, 1), NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (Omega_col_arr == NULL) { return NULL; } Omega_col = (PyArrayObject*) Omega_col_arr; Out_arr = PyArray_FROM_OTF(Out_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); if (Out_arr == NULL) { return NULL; } Out = (PyArrayObject*) Out_arr; int ndimA = PyArray_NDIM(A); if (ndimA != 2) { PyErr_SetString(PyExc_ValueError, "A should be 2-dimensional"); return NULL; } int ndimB = PyArray_NDIM(B); if (ndimB != 2) { PyErr_SetString(PyExc_ValueError, "B should be 2-dimensional"); return NULL; } // int ndimOmega = PyArray_NDIM(B); // if (ndimOmega != 2) { // PyErr_SetString(PyExc_ValueError, // "Omega should be 2-dimensional"); // return NULL; // } npy_intp *dimsA = PyArray_DIMS(A); npy_intp *dimsB = PyArray_DIMS(B); npy_intp *dimsOmega_row = PyArray_DIMS(Omega_row); npy_intp *dimsOmega_col = PyArray_DIMS(Omega_col); if (dimsOmega_row[0] != dimsOmega_col[0]) { PyErr_SetString(PyExc_ValueError, "index arrays should have equal length"); return NULL; } if (dimsA[1] != dimsB[0] ) { PyErr_SetString(PyExc_ValueError, "Inner dimensions of A and B do not match"); return NULL; } double *bufferA = PyArray_DATA(A); double *bufferB = PyArray_DATA(B); double *bufferOmega_row = PyArray_DATA(Omega_row); double *bufferOmega_col = PyArray_DATA(Omega_col); double *bufferOut = PyArray_DATA(Out); //int m = dimsA[0]; int k = dimsA[1]; int n = dimsB[1]; int j = dimsOmega_row[0]; // Remove this pragma for single threaded execution #pragma omp parallel for for (int i=0; i<j; i++) { double *iA = bufferA + k * (int)(bufferOmega_row[i]); double *iB = bufferB + (int)(bufferOmega_col[i]); /* * The plain C version, without blas double val = 0; for (int x=0; x<k; x++) { val += *iA * *iB; iA += 1; iB += n; } *(bufferOut++) = val; */ bufferOut[i] = cblas_ddot(k, iA, 1, iB, n); } Py_DECREF(A_arr); Py_DECREF(B_arr); Py_DECREF(Omega_row_arr); Py_DECREF(Omega_col_arr); Py_DECREF(Omega_seq); Py_DECREF(Out); Py_RETURN_NONE; } static PyMethodDef smmprod_methods[] = { {"smmprod", smmprod_func, METH_VARARGS, "calculate fast smmprod in pure C"}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "_smmprod", NULL, -1, smmprod_methods }; PyObject * PyInit__smmprod(void) { import_array(); PyObject *module = PyModule_Create(&moduledef); return module; } #else void init_smmprod(void) { import_array(); Py_InitModule("_smmprod", smmprod_methods); return; } #endif
{ "alphanum_fraction": 0.6126604692, "avg_line_length": 24.5543478261, "ext": "c", "hexsha": "a076d0645d0d1ae60c55b599823c00986a4a130f", "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": "00f61b4ef08208d12e8e803d10f8ebbe16d8614a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "clemenshage/grslra", "max_forks_repo_path": "smmprod/smmprod.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "00f61b4ef08208d12e8e803d10f8ebbe16d8614a", "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": "clemenshage/grslra", "max_issues_repo_path": "smmprod/smmprod.c", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "00f61b4ef08208d12e8e803d10f8ebbe16d8614a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "clemenshage/grslra", "max_stars_repo_path": "smmprod/smmprod.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1294, "size": 4518 }
/** * @file dereverberation.h * @brief Single- and multi-channel dereverberation base on linear prediction in the subband domain. * @author John McDonough */ #ifndef DEREVERBERATION_H #define DEREVERBERATION_H #include <stdio.h> #include <assert.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> #include "common/jexception.h" #include "stream/stream.h" #include "feature/feature.h" /* #include <Eigen/Cholesky> #include <iostream> #include <Eigen/Dense> */ // ----- definition for class `SingleChannelWPEDereverberationFeature' ----- // class SingleChannelWPEDereverberationFeature : public VectorComplexFeatureStream { typedef vector<gsl_vector_complex*> Samples_; typedef Samples_::iterator SamplesIterator_; public: SingleChannelWPEDereverberationFeature(VectorComplexFeatureStreamPtr& samples, unsigned lowerN, unsigned upperN, unsigned iterationsN = 2, double loadDb = -20.0, double bandWidth = 0.0, double sampleRate = 16000.0, const String& nm = "SingleChannelWPEDereverberationFeature"); ~SingleChannelWPEDereverberationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); unsigned estimate_filter(int start_frame_no = 0, int frame_num = -1); void reset_filter(); void next_speaker(); void print_objective_func(int subbandX){ printing_subbandX_ = subbandX;} #ifdef ENABLE_LEGACY_BTK_API void nextSpeaker(){ next_speaker(); } #endif private: static const double subband_floor_; void fill_buffer_(int start_frame_no, int frame_num); void estimate_Gn_(); void calc_Rr_(unsigned subbandX); void calc_Thetan_(); void load_R_(); unsigned set_band_width_(double bandWidth, double sampleRate); const gsl_vector_complex* get_lags_(unsigned subbandX, unsigned sampleX); VectorComplexFeatureStreamPtr samples_; const unsigned lowerN_; const unsigned upperN_; const unsigned predictionN_; const unsigned iterationsN_; bool estimated_; unsigned framesN_; // no frames used for filter estimation const double load_factor_; const unsigned lower_bandWidthN_; const unsigned upper_bandWidthN_; Samples_ yn_; // buffer to keep observations gsl_matrix* thetan_; gsl_vector_complex** gn_; gsl_matrix_complex* R_; gsl_vector_complex* r_; gsl_vector_complex* lag_samples_; int printing_subbandX_; }; typedef Inherit<SingleChannelWPEDereverberationFeature, VectorComplexFeatureStreamPtr> SingleChannelWPEDereverberationFeaturePtr; // ----- definition for class `MultiChannelWPEDereverberation' ----- // class MultiChannelWPEDereverberation : public Countable { typedef vector<VectorComplexFeatureStreamPtr> SourceList_; typedef SourceList_::iterator SourceListIterator_; typedef vector<gsl_vector_complex*> FrameBrace_; typedef FrameBrace_::iterator FrameBraceIterator_; typedef vector<FrameBrace_> FrameBraceList_; typedef FrameBraceList_::iterator FrameBraceListIterator_; public: MultiChannelWPEDereverberation(unsigned subbandsN, unsigned channelsN, unsigned lowerN, unsigned upperN, unsigned iterationsN = 2, double loadDb = -20.0, double bandWidth = 0.0, double diagonal_bias = 0.0, double sampleRate = 16000.0); ~MultiChannelWPEDereverberation(); void reset(); unsigned size() const { return subbandsN_; } void set_input(VectorComplexFeatureStreamPtr& samples); const gsl_vector_complex* get_output(unsigned channelX); gsl_vector_complex** calc_every_channel_output(int frame_no = -5); unsigned estimate_filter(int start_frame_no = 0, int frame_num = -1); void reset_filter(); void next_speaker(); int frame_no() const { return frame_no_; } void print_objective_func(int subbandX){ printing_subbandX_ = subbandX;} #ifdef ENABLE_LEGACY_BTK_API void setInput(VectorComplexFeatureStreamPtr& samples){ set_input(samples); } const gsl_vector_complex* getOutput(unsigned channelX, int frame_no = -5){ return get_output(channelX); } void nextSpeaker(){ next_speaker(); } #endif private: static const double subband_floor_; void fill_buffer_(int start_frame_no, int frame_num); void estimate_Gn_(); void calc_Rr_(unsigned subbandX); void calc_Thetan_(); void load_R_(); unsigned set_band_width_(double bandWidth, double sampleRate); void increment_() { frame_no_++; } const gsl_vector_complex* get_lags_(unsigned subbandX, unsigned sampleX); SourceList_ sources_; const unsigned subbandsN_; const unsigned channelsN_; const unsigned lowerN_; const unsigned upperN_; const unsigned predictionN_; const unsigned iterationsN_; const unsigned totalPredictionN_; bool estimated_; unsigned framesN_; const double load_factor_; const unsigned lower_bandWidthN_; const unsigned upper_bandWidthN_; FrameBraceList_ frames_; gsl_matrix** thetan_; gsl_vector_complex*** Gn_; gsl_matrix_complex** R_; gsl_vector_complex** r_; gsl_vector_complex* lag_samples_; gsl_vector_complex** output_; const int initial_frame_no_; int frame_no_; const double diagonal_bias_; int printing_subbandX_; }; typedef refcountable_ptr<MultiChannelWPEDereverberation> MultiChannelWPEDereverberationPtr; // ----- definition for class `MultiChannelWPEDereverberationFeature' ----- // class MultiChannelWPEDereverberationFeature : public VectorComplexFeatureStream { public: MultiChannelWPEDereverberationFeature(MultiChannelWPEDereverberationPtr& source, unsigned channelX, unsigned primaryChannelX = 0, const String& nm = "MultiChannelWPEDereverberationFeature"); ~MultiChannelWPEDereverberationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset(); private: MultiChannelWPEDereverberationPtr source_; const unsigned channelX_; const unsigned primaryChannelX_; // compute the dereverbed output only when channelX_ == primaryChannelX_. Otherwise copy the precomputed output }; typedef Inherit<MultiChannelWPEDereverberationFeature, VectorComplexFeatureStreamPtr> MultiChannelWPEDereverberationFeaturePtr; #endif // DEREVERBERATION_H
{ "alphanum_fraction": 0.7483003708, "avg_line_length": 34.4255319149, "ext": "h", "hexsha": "67a4e570cb82108c38576e23d761511910f78422", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/dereverberation/dereverberation.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/dereverberation/dereverberation.h", "max_line_length": 279, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/dereverberation/dereverberation.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 1598, "size": 6472 }
#pragma once #include <iosfwd> #include <map> #include <memory> #include <vector> #include <gsl/gsl> namespace sframe { struct openssl_error : std::runtime_error { openssl_error(); }; struct unsupported_ciphersuite_error : std::runtime_error { unsupported_ciphersuite_error(); }; struct authentication_error : std::runtime_error { authentication_error(); }; struct buffer_too_small_error : std::runtime_error { using parent = std::runtime_error; using parent::parent; }; struct invalid_parameter_error : std::runtime_error { using parent = std::runtime_error; using parent::parent; }; enum class CipherSuite : uint16_t { AES_CM_128_HMAC_SHA256_4 = 1, AES_CM_128_HMAC_SHA256_8 = 2, AES_GCM_128_SHA256 = 3, AES_GCM_256_SHA512 = 4, }; constexpr size_t max_overhead = 17 + 16; using bytes = std::vector<uint8_t>; using input_bytes = gsl::span<const uint8_t>; using output_bytes = gsl::span<uint8_t>; std::ostream& operator<<(std::ostream& str, const input_bytes data); using KeyID = uint64_t; using Counter = uint64_t; class SFrame { protected: CipherSuite suite; SFrame(CipherSuite suite_in); virtual ~SFrame(); struct KeyState { static KeyState from_base_key(CipherSuite suite, const bytes& base_key); bytes key; bytes salt; Counter counter; }; output_bytes _protect(KeyID key_id, output_bytes ciphertext, input_bytes plaintext); output_bytes _unprotect(output_bytes ciphertext, input_bytes plaintext); virtual KeyState& get_state(KeyID key_id) = 0; }; class Context : public SFrame { public: Context(CipherSuite suite); void add_key(KeyID kid, const bytes& key); output_bytes protect(KeyID key_id, output_bytes ciphertext, input_bytes plaintext); output_bytes unprotect(output_bytes plaintext, input_bytes ciphertext); private: std::map<KeyID, KeyState> state; KeyState& get_state(KeyID key_id) override; }; class MLSContext : public SFrame { public: using EpochID = uint64_t; using SenderID = uint32_t; MLSContext(CipherSuite suite_in, size_t epoch_bits_in); void add_epoch(EpochID epoch_id, const bytes& sframe_epoch_secret); void purge_before(EpochID keeper); output_bytes protect(EpochID epoch_id, SenderID sender_id, output_bytes ciphertext, input_bytes plaintext); output_bytes unprotect(output_bytes plaintext, input_bytes ciphertext); private: const size_t epoch_bits; const size_t epoch_mask; struct EpochKeys { const EpochID full_epoch; const bytes sframe_epoch_secret; std::map<SenderID, KeyState> sender_keys; EpochKeys(EpochID full_epoch_in, bytes sframe_epoch_secret_in); KeyState& get(CipherSuite suite, SenderID sender_id); }; std::vector<std::unique_ptr<EpochKeys>> epoch_cache; KeyState& get_state(KeyID key_id) override; }; } // namespace sframe
{ "alphanum_fraction": 0.7147177419, "avg_line_length": 21.5652173913, "ext": "h", "hexsha": "c5bf936bef1c16f133c61c26c90671298c91b363", "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": "360dcc6546448c933f1974463aef257a61a6a25a", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "fanglinliu/sframe", "max_forks_repo_path": "include/sframe/sframe.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "360dcc6546448c933f1974463aef257a61a6a25a", "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": "fanglinliu/sframe", "max_issues_repo_path": "include/sframe/sframe.h", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "360dcc6546448c933f1974463aef257a61a6a25a", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "fanglinliu/sframe", "max_stars_repo_path": "include/sframe/sframe.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 724, "size": 2976 }
#include <math.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_linalg.h> #include <getopt.h> #include <string.h> #include "libhdr" #include "Library_DFE_v1.8.h" /******************************************************************************/ int get_average_egf_vecs_1_and_2(double s,int n1, int n2, double t2_real, int t2_lower, int t2_upper, double *egf_vec, char *buffer_p1_n2_t2_lower, char *buffer_p2_n2_t2_lower, char *buffer_p1_n2_t2_upper, char *buffer_p2_n2_t2_upper) { static double egf_vec1_lower[maxnd+1], egf_vec2_lower[maxnd+1], egf_vec1_upper[maxnd+1], egf_vec2_upper[maxnd+1], egf_vec1[maxnd+1], egf_vec2[maxnd+1]; double total_density; int i, res; int n1d=2*n1; int n2d=2*n2; if (s<-1) /* The contribution of strongly selected mutations is assumed to be inversely proportional to s, as expected from mutation selection balance, with a contribution from phase 2 mutations only. */ { for (i=0; i<=2*n2; i++) { egf_vec1[i] = 0; egf_vec2[i] = 0; } egf_vec2[1] = -2/s; } else { res = get_binary_egf_vec(buffer_p1_n2_t2_lower, n2, t2_lower, s, egf_vec1_lower); if (res==0) return 0; res = get_binary_egf_vec(buffer_p2_n2_t2_lower, n2, t2_lower, s, egf_vec2_lower); if (res==0) return 0; res = get_binary_egf_vec(buffer_p1_n2_t2_upper, n2, t2_upper, s, egf_vec1_upper); if (res==0) return 0; res = get_binary_egf_vec(buffer_p2_n2_t2_upper, n2, t2_upper, s, egf_vec2_upper); if (res==0) return 0; compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper, egf_vec1_lower, egf_vec1_upper, egf_vec1, 2*n2); // monitorinput(); compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper, egf_vec2_lower, egf_vec2_upper, egf_vec2, 2*n2); } total_density = compute_weighted_average(egf_vec, egf_vec1, egf_vec2, n1d, 2*n2); if (s==0) { total_density_s0 = total_density; // printf("s=0: total_density %lf\n", total_density); } return (1); } /******************************************************************************/ get_upper_lower_int(double parm, int *lower, int *upper, int n_int_evaluated, int *int_evaluated_vec) { int i; *lower = undefined_int; *upper = undefined_int; // printf("get_upper_lower_int parm %lf n_int_evaluated %d\n", // parm, n_int_evaluated); for (i=0; i<n_int_evaluated; i++) { // printf("int_evaluated_vec[%d] %d\n", i, int_evaluated_vec[i]); if ((double)int_evaluated_vec[i] >= parm) { *upper = int_evaluated_vec[i]; if (i != 0) *lower = int_evaluated_vec[i-1]; return; } } } /******************************************************************************/ get_upper_lower_double(double parm, double*lower, double *upper, int n_int_evaluated, double *double_evaluated_vec) { int i; *lower = undefined; *upper = undefined; // printf("get_upper_lower_int parm %lf n_int_evaluated %d\n", // parm, n_int_evaluated); for (i=0; i<n_int_evaluated; i++) { // printf("int_evaluated_vec[%d] %d\n", i, int_evaluated_vec[i]); if (double_evaluated_vec[i] >= parm) { *upper =double_evaluated_vec[i]; if (i != 0) *lower = double_evaluated_vec[i-1]; return; } } } /******************************************************************************/ get_s_ranges() { int i, stat, ind, i1; double d1, d2, d3; FILE *inf, *fopen(); inf = openforreadsilent(s_range_file); stat = fscanf(inf, "%d", &nranges); if (stat!=1) gabort("get_s_ranges: input error 1", 0); if (nranges >max_s_ranges) gabort("get_s_ranges: nranges >max_s_ranges", nranges); for (i=1; i<=nranges; i++) { stat = fscanf(inf, "%d %lf %lf %lf %d", &ind, &d1, &d2, &d3, &i1); if (stat!=5) gabort("get_s_ranges: input error 2", 0); if (ind!=i) gabort("get_s_ranges: ind!=i", i); s_ranges[i].s_lower = d1; s_ranges[i].s_upper = d2; s_ranges[i].s_step = d3; s_ranges[i].s_lower_index = i1; } } /******************************************************************************/ get_int_evaluated_vec(int *int_evaluated_vec, int *n_int_evaluated, int *int_lower, int *int_step, char *int_evaluated_vec_file) { int i, stat; FILE *inf, *fopen(); int int_input, first_int, second_int, int_upper; inf = openforreadsilent(int_evaluated_vec_file); i = 0; for (;;) { stat = fscanf(inf, "%d", &int_input); if (stat==EOF) break; if (stat!=1) gabort("get_int_evaluated_vec: read error 1", stat); if (*n_int_evaluated >= max_n_int_evaluated) gabort("Value of n_int_evaluated too large: get_int_evaluated_vec", get_int_evaluated_vec); int_evaluated_vec[*n_int_evaluated] = int_input; // printf("int_evaluated_vec[%d] %d\n", // *n_int_evaluated, int_evaluated_vec[*n_int_evaluated]); (*n_int_evaluated)++; if (i==0) { first_int = int_input; *int_lower = first_int; } if (i==1) { second_int = int_input; } int_upper = int_input; i++; } fclose (inf); *int_step = second_int - first_int; //printf("int_lower %d int_upper %d int_step %d\n", // *int_lower, int_upper, *int_step); } /******************************************************************************/ scale_vector(double *vec, int n2, double total_density_s0) { int i; double tot = 0; // printf("scale_vector: n2 %d total_density_s0 %lf\n", n2, total_density_s0); // monitorinput(); for (i=1; i<n2; i++) { vec[i] /= total_density_s0; tot += vec[i]; } vec[0] = 1.0 - tot; // Put all "missing" density in the lost mutant class } /******************************************************************************/ int get_binary_egf_vec(char *buffer, int n, int t2, double s, double *egf_vec) { int i, j, file_size_bytes, n_read, t2_read, offset, tab_num, tab_size, size_of_float; float s_read, freq_read; char *ptr, ch; // Each expected gene freq table has two integers (n, t2), a float (s), then // 2*n -1 floats (frequencies) tab_size = (2*sizeof(int)+sizeof(float) + sizeof(float)*(2*n -1)); file_size_bytes = n_s_evaluated_file*tab_size; // printf("tab_size %d file_size_bytes %d\n", tab_size, file_size_bytes); tab_num = compute_s_tab_num(s); // printf("tab_num assuming ranges %d\n", tab_num); // monitorinput(); if (tab_num>=n_s_evaluated_file) return 0; // printf("s %lf s_lower %lf s_step %lf (s - s_lower)/s_step %lf tab_num %d\n", // s, s_lower, s_step, (s - s_lower)/s_step, tab_num); // monitorinput(); offset = tab_num*tab_size; assign_int_from_read_buff(&n_read, buffer, offset); // printf("n_read %d\n", n_read); if (n_read!=n) { // printf("n %d n_read %d\n", n, n_read); gabort("get_binary_egf_vec: read error 1", n_read); } offset += sizeof(int); assign_int_from_read_buff(&t2_read, buffer, offset); //printf("t2 %d t2_read %d\n", t2, t2_read); if (t2_read!=t2) gabort("get_binary_egf_vec: read error 2", t2_read); offset += sizeof(int); s_read = assign_float_from_read_buff(buffer, offset); // printf("s_read %f\n", s_read); size_of_float = sizeof(float); for (i=1; i<2*n; i++) { offset += size_of_float; // assign_float_from_read_buff - in line code for speed ptr = &freq_read; for (j=0; j<size_of_float; j++) { // printf("assign_float_from_read_buff: ch %d\n", ch); *(ptr + j) = buffer[offset + j]; } // printf("freq_read %f\n", freq_read); egf_vec[i] = (double)freq_read; } // dumpvector(egf_vec, 1, 2*n -1, "egf_vec:"); // monitorinput(); return 1; } /******************************************************************************/ fold_vector_double(double *vec, int counter) { int i, j; j = 1; for (i=counter - 1; i > counter/2; i--) { vec[j] += vec[i]; vec[i] = 0; j++; } } /******************************************************************************/ fold_vector_int(int *vec, int counter) { int i, j; j = 1; for (i=counter - 1; i > counter/2; i--) { vec[j] += vec[i]; vec[i] = 0; j++; } } /******************************************************************************/ int nearest_n2_ind(int n2_real) { int i, ind = undefined_int; double min = undefined, diff, res; for (i=0; i<n_n2_evaluated; i++) { diff = n2_evaluated_vec[i] - n2_real; if (diff < 0) diff = -diff; if (min==undefined) { min = diff; ind = i; } else { if (min > diff) { min = diff; ind = i; } } } if (ind == undefined_int) gabort("nearest_n2: ind == undefined_int", ind); res = n2_evaluated_vec[ind];; // printf("nearest_n2: n2_real %lf result %lf\n", n2_real, res); // monitorinput(); return ind; } /******************************************************************************/ read_phase1_phase2_file_into_buffer(int n1, int phase, int n2, int t2, char *buffer, int file_size_bytes) { static char n1_str[max_str_len], n2_str[max_str_len], t2_str[max_str_len]; char file_str[max_str_len]; int n2d; FILE *inf, *fopen(); // printf("read_phase1_phase2_file_into_buffer: phase %d n2 %d t2 %d\n", // phase, n2, t2); n2d = 2*n2; int_to_string(n1, n1_str, max_str_len); int_to_string(n2, n2_str, max_str_len); int_to_string(t2, t2_str, max_str_len); if (strlen(n1_str) + strlen(n2_str) + strlen(t2_str) >= max_str_len) gabort("read_phase1_phase2_file_into_buffer: string too long", max_str_len); if (phase==1) { strcpy(file_str, phase_1_dir); strcat(file_str, "/n1:"); strcat(file_str, n1_str); strcat(file_str, ":"); } else { strcpy(file_str, phase_2_dir); strcat(file_str, "/"); } strcat(file_str, "n2:"); strcat(file_str, n2_str); strcat(file_str, ":t2:"); strcat(file_str, t2_str); inf = openforreadsilent(file_str); fread(buffer, 1, file_size_bytes, inf); fclose(inf); } /******************************************************************************/ read_const_pop_file_into_buffer(int n1, char *buffer, int file_size_bytes) { char file_str[max_str_len]; FILE *inf, *fopen(); // printf("read_const_pop_file_into_buffer: n1 %d file_size_bytes %d\n", // n1, file_size_bytes); strcpy(file_str, const_pop_dir); strcat(file_str, const_pop_file); // printf("read_const_pop_file_into_buffer: file_str %s\n", file_str); // monitorinput(); inf = openforreadsilent(file_str); fread(buffer, 1, file_size_bytes, inf); fclose(inf); } /******************************************************************************/ compute_weighted_average_egf_vec(double t2_real, int t2_lower, int t2_upper, double *egf_vec_lower, double *egf_vec_upper, double *egf_vec, int n2d) { int i; for (i=0; i<=n2d; i++) { egf_vec[i] = egf_vec_lower[i] + (egf_vec_upper[i] - egf_vec_lower[i])*(t2_real - (double)t2_lower)/(double)(t2_upper - t2_lower); } } /******************************************************************************/ double compute_weighted_average(double *weighted_vec, double *phase1_mut_vec, double *phase2_mut_vec, int n1d, int n2d) { int i; double total = 0; for (i=1; i<n2d; i++) { weighted_vec[i]= (n1d*phase1_mut_vec[i] + n2d*phase2_mut_vec[i])/ (n1d + n2d); total += weighted_vec[i]; } // dumpvector(weighted_vec, 0, n2d, "weighted average vector:"); monitorinput(); return(total); } /******************************************************************************/ int get_const_pop_egf_vec(double s, int n1, double *egf_vec, char *buffer_const_pop, int assign_tds0_mode) { double total_density; int i, res; if (s<-1) // The contribution of strongly selected mutations // is assumed to be inversely proportional to s, as // expected from mutation selection balance, with a // contribution from phase 2 mutations only. { for (i=0; i<=2*n1; i++) { egf_vec[i] = 0; } egf_vec[1] = -2/s; // printf("get_const_pop_egf_vec s %lf\n", s); // dumpvector(egf_vec, 0, 2*n1, "get_const_pop_egf_vec:"); // monitorinput(); } else { res = get_binary_egf_vec(buffer_const_pop, n1, 0, s, egf_vec); if (res==0) return 0; // dumpvector(egf_vec, 0, 2*n1, "get_const_pop_egf_vec:"); // monitorinput(); } total_density = compute_weighted_average(egf_vec, egf_vec, egf_vec, 2*n1, 2*n1); if (assign_tds0_mode) { total_density_s0 = total_density; } // printf("assign_tds0_mode %d: total_density_s0 %lf\n", assign_tds0_mode, total_density_s0); return (1); } /******************************************************************************/ assign_int_from_read_buff(int *res, char *buffer, int start) { int temp, i; char *ptr, ch; ptr = &temp; for (i=0; i<sizeof(int); i++) { ch = buffer[start+i]; *(ptr + i) = ch; } *res = temp; } /******************************************************************************/ float assign_float_from_read_buff(char *buffer, int start) { float temp; int i; char *ptr, ch; ptr = &temp; for (i=0; i<sizeof(float); i++) { ch = buffer[start+i]; // printf("assign_float_from_read_buff: ch %d\n", ch); *(ptr + i) = ch; } // printf("assign_float_from_read_buff: temp %f\n", temp); return temp; } /******************************************************************************/ int compute_s_tab_num(double s) { double s_lower, s_upper, s_step; int i, tab_num; for (i=1; i<=nranges; i++) { s_lower = s_ranges[i].s_lower; s_upper = s_ranges[i].s_upper; if ((s >= s_lower)&&(s <= s_upper)) { s_step = s_ranges[i].s_step; tab_num = (int)(floor((s - s_lower)/s_step + 0.0000000001)); return(tab_num + s_ranges[i].s_lower_index - 1); } } gabort("compute_s_tab_num: failure to find tab_num", 0); } /******************************************************************************/ int compute_file_size_bytes(int n) { int tab_size, file_size_bytes; tab_size = (2*sizeof(int)+sizeof(float) + sizeof(float)*(2*n - 1)); file_size_bytes = n_s_evaluated_file*tab_size; return (file_size_bytes); } /******************************************************************************/ set_up_file_name(int n1, char *froot, char *file_name) { int len; static char n1_str[max_str_len]; int_to_string(n1, n1_str, max_str_len); // printf("set_up_file_name n1 %d froot %s n1_str %s\n", n1, froot, n1_str); // monitorinput(); len = strlen(data_path); len += strlen(n1_str) + 1; len += strlen(froot); if (len >= max_str_len) gabort("set_up_file_name: string too long (1)", len); strcpy(file_name, data_path); strcat(file_name, "n1_"); strcat(file_name, n1_str); strcat(file_name, "/"); strcat(file_name, froot); // printf("set_up_file_name n1 file_name %s\n", file_name); // monitorinput(); } /******************************************************************************/ get_data_path(char *data_path) { FILE *inf, *fopen(); int stat; inf = openforread("directory_config.dat"); stat = fscanf(inf, "%s", data_path); if (stat!=1) gabort("get_data_path: read error", 1); // printf("get_data_path: data_path %s\n", data_path); monitorinput(); } /******************************************************************************/ get_s_evaluated_vec(double *s_evaluated_vec, int *n_s_evaluated, int *n_s_evaluated_file, char *s_evaluated_vec_file) { int stat; FILE *inf, *fopen(); double s; *n_s_evaluated = 0; inf = openforreadsilent(s_evaluated_vec_file); s = -100.0; // Set up large |s| values specially while (s < -1) { s_evaluated_vec[*n_s_evaluated] = s; (*n_s_evaluated)++; if (s > -20) s = s + 1.0; else s = s + 5.0; } *n_s_evaluated_file = 0; for (;;) { stat = fscanf(inf, "%lf", &s); if (stat==EOF) break; if (stat!=1) gabort("get_s_limits: read error 1", stat); if (*n_s_evaluated >= max_n_s_evaluated) gabort("Value of n_s_evaluated too large: get_s_evaluated_vec", get_s_evaluated_vec); s_evaluated_vec[*n_s_evaluated] = s; (*n_s_evaluated)++; (*n_s_evaluated_file)++; } fclose (inf); // printf("n_s_evaluated %d n_s_evaluated_file %d\n", *n_s_evaluated, // *n_s_evaluated_file); // monitorinput(); } /******************************************************************************/ get_lower_upper(int ind, double *s_evaluated_vec, int n_s_evaluated, double *lower, double *upper) { double x, temp_r; if ((ind<0)||(ind>=n_s_evaluated)) gabort("get_lower_upper: ind out of range", ind); x = s_evaluated_vec[ind]; if (ind<n_s_evaluated-1) *upper = (x + s_evaluated_vec[ind+1])/2.0; else *upper = x; if (ind!=0) *lower = (x + s_evaluated_vec[ind-1])/2.0; else *lower = x; if (x <=0.0) { temp_r = *lower; *lower = *upper; *upper = temp_r; if (*lower!=0.0) *lower = -*lower; if (*upper!=0.0) *upper = -*upper; } } /******************************************************************************/ dumpvector(double *v, int min, int max, char *s) { int i, control = 0; // printf("\n"); printf("%s", s); printf("\n"); for (i = min; i<max; i++) { printf("%3d %10.8lf ", i, v[i]); control++; if (control==5) { control = 0; printf("\n"); } } printf("\n"); } /******************************************************************************/ dumpmatrix(double **m, int s1, int rows, int s2, int cols, char *s) { int i, j; printf("\n%s\n", s); for (i = s1; i<=rows; i++) { for (j = s2; j<=cols; j++) { printf(" %2.3f", m[i][j]); } printf("\n"); } printf("\n"); } /******************************************************************************/ double selfn(double q, double s, double h) { double num, denom; num = s*q*(1-q)*(q + h*(1-2*q)); denom = 1 + 2.0*h*s*q*(1-q) + s*q*q; if (denom== 0) denom = .00000000000001; return( q + (num/denom)); } /******************************************************************************/ setuprow(double **a, double p, int row, int n) { double z; /*probability of zero failures*/ double x, y, temp1, temp2; int j; temp1 = 1.0 - p; if (temp1 == 0.0) temp1 = .000000000001; /*prevent zero divide*/ temp1 = p/temp1; /*First prevent negative log*/ if (temp1 <=0) temp1 = .000000000001; x = log(temp1); /*used for later multiplication of series*/ temp2 = 1.0-p; if (temp2<=0) temp2 = .000000000001; z = (double)n*log(temp2); if (z > 150) z = 150; a[row][0] = exp(z); y = a[row][0]; /*add up for later*/ for (j = 1;j<=n; j++) { z = z + log(((double)n + 1.0 - (double)j)/(double)j) + x; /* cumulative binomial coeff.*/ a[row][j] = exp(z); y = y + a[row][j]; /*add up*/ } if (y == 0.0) y = .0000000000001; for (j=0; j<=n; j++) a[row][j] = a[row][j]/y; } /******************************************************************************/ setupmatrix(double **a, int n1, int n2, double s, double h) { int i; double p; for (i = 1; i<=n1 - 1; i++) /*do variable rows*/ { p = (double)i/(double)n1; p = selfn(p, s,h); setuprow(a, p, i, n2); } for (i = 0; i<=n2; i++) { /*do constant edges*/ a[0][i] = 0; a[n1][i] = 0; } a[0][0] = 1.0; /*do absorbing corners*/ a[n1][n2] = 1.0; } /******************************************************************************/ matrixinvert(int N, double **a,double *inverter) { int i, j, lotkin_signum; gsl_matrix *lotkin_a,*lotkin_inv; gsl_vector *x, *lotkin_b, *lotkin_x; gsl_permutation *lotkin_perm; /* allocate a, x, b */ lotkin_a = gsl_matrix_alloc(N-1, N-1); lotkin_inv = gsl_matrix_alloc(N-1, N-1); x = gsl_vector_alloc(N-1); lotkin_b = gsl_vector_alloc(N-1); lotkin_x = gsl_vector_alloc(N-1); gsl_matrix *identity=gsl_matrix_alloc(N-1, N-1); for (i = 0; i<=N-2; i++) { for (j = 0; j<=N-2; j++) { gsl_matrix_set( identity, i, i,1); } ; } for (i = 0; i<=N-2; i++) { for (j = 0; j<=N-2; j++) { gsl_matrix_set(lotkin_a,i,j,gsl_matrix_get(identity,i,j)-a[i+1][j+1]); } } /* LU decomposition and forward&backward substition */ //gsl_blas_dgemv(CblasNoTrans, 1.0, lotkin_a, x, 0.0, lotkin_b); lotkin_perm = gsl_permutation_alloc(N-1); gsl_linalg_LU_decomp(lotkin_a, lotkin_perm, &lotkin_signum); gsl_linalg_LU_solve(lotkin_a, lotkin_perm, lotkin_b, lotkin_x); gsl_linalg_LU_invert (lotkin_a,lotkin_perm, lotkin_inv); /*apparently the inversion adds +1 to the first element of the vector so I substract it*/ gsl_matrix_set(lotkin_inv,0,0,gsl_matrix_get(lotkin_inv,0,0)-1); //printf("\n%s\n", "Equilibrium"); for (i = 0; i<1; i++) { for (j = 0; j<=N-2; j++) { // printf("%d: %2.3f ",j,gsl_matrix_get(lotkin_inv, i, j)); } //printf("\n"); } for (i=0;i<=N-2;i++){ inverter[i+1]=gsl_matrix_get(lotkin_inv,0,i); } gsl_matrix_free(lotkin_a); gsl_matrix_free(lotkin_inv); gsl_vector_free(x); gsl_vector_free(lotkin_b); gsl_vector_free(lotkin_x); gsl_matrix_free(identity); gsl_permutation_free(lotkin_perm); } /******************************************************************************/ tmiterate(double **a,double *mut1, int t, int n1, int n2,int decay,double *sumf) { int k, i, j = 0; double z; double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double)); double * mut2 = (double*) calloc (maxnd+1, sizeof(double)); for (k =1 ;k<=t; k++) { /*t iterations*/ /* Increment steadystatefreq. distribution*/ for (i = 0; i<=n1; i++) { steadystatefreq[i] = steadystatefreq[i] + mut1[i]; } /* Perform matrix multiplication*/ for (i = 0; i<=n2; i++) { z = 0; for (j = 0; j<=n1; j++) { z = z + a[j][i]*mut1[j]; } mut2[i] = z; } /* Copy result of multiplication*/ for (i=0; i<=n2; i++) {mut1[i] = mut2[i]; if (decay==0){ sumf[i]+=mut1[i];} if(decay==1){sumf[i]=mut1[i];} } } free(steadystatefreq); free(mut2); } /******************************************************************************/ tmiterate2(double **a,double *mut1, int t, int n1, int n2,int decay,double **a1) { double * steadystatefreq = (double*) calloc (maxnd+1, sizeof(double)); double * mut2 = (double*) calloc (maxnd+1, sizeof(double)); int k, i, j = 0; double z; for (k = 1; k<=t; k++){ /*t iterations*/ /* Increment steadystatefreq. distribution*/ for (i = 0; i<=n1; i++) { steadystatefreq[i] = steadystatefreq[i] + mut1[i]; } /* Perform matrix multiplication*/ for (i = 0; i<=n2; i++) { z = 0; for (j = 0; j<=n1; j++) { z = z + a[j][i]*mut1[j]; } mut2[i] = z; } /* Copy result of multiplication*/ for (i=0; i<=n2; i++) {mut1[i] = mut2[i]; if (decay==0){ a1[k][i]+=mut1[i]; if (k>1){a1[k][i]+=a1[k-1][i];} } if(decay==1){ a1[k][i]=mut1[i]; //if (k>0){ a1[k][i]+=a1[k-1][i];} } } //dumpvector(a1[k],0,n2,"matrix"); } free(steadystatefreq); free(mut2); } /******************************************************************************/ eqf_using_matrix_inversion(int n1,double s,double **a,double *egf_out) { setupmatrix(a, n1, n1, s, H); matrixinvert(n1,a,egf_out); } /******************************************************************************/ vector_average(int n1,int n2,double *fv1,double *fv2, double *fv_out) { int i; for (i=0;i<n2;i++) { fv_out[i]=((n1*fv1[i])+(n2*fv2[i]))/(n1+n2); } } /******************************************************************************/ vector_s_average(int n,double P1,double *fv1,double *fv2, double *fv_out) { int i; for (i=0;i<n;i++) { fv_out[i]=(P1*fv1[i])+((1-P1)*fv2[i]); } } /******************************************************************************/ output_sfs_to_file_thanasis_format(int n, int *sfs1,int *sfs2,char *sfs_filename) { FILE *file= fopen(sfs_filename, "w" ); int i; //neutral sites first for (i=0;i<n;i++){ fprintf(file,"%d ",sfs1[i]); } fprintf(file,"\n"); //selected sites second for (i=0;i<n;i++){ fprintf(file,"%d ",sfs2[i]); } fclose(file); } /******************************************************************************/ output_sfs_to_file_peter_format(int n,int sample1, int sample2, int *sfs1,int *sfs2,char *sfs_filename) { FILE *file= fopen(sfs_filename, "w" ); int i; fprintf(file,"1\n"); fprintf(file,"%d\n",n); //selected sites first fprintf(file,"%d\n",sample2); for (i=1;i<n;i++){ fprintf(file,"%d ",sfs2[i]); } fprintf(file,"\n"); //neutral sites second fprintf(file,"%d\n",sample1); for (i=1;i<n;i++){ fprintf(file,"%d ",sfs1[i]); } fclose(file); } /******************************************************************************/ output_sfs_to_file_peter_format2(int n,int sample1, int sample2, int *sfs1,int *sfs2,char *sfs_filename) { FILE *file= fopen(sfs_filename, "w" ); int i; fprintf(file,"name\n"); fprintf(file,"0 0\n0 0\n"); fprintf(file,"%d\n",n); for (i=0;i<n;i++){ fprintf(file,"%d ",sfs1[i]); } fprintf(file,"0\n"); //fprintf(file,"%d\n",sample1); for (i=0;i<n;i++){ fprintf(file,"%d ",sfs2[i]); } fprintf(file,"0"); fclose(file); } /******************************************************************************/ get_sfs(int alleles,int *par,char *sfs_filename) { int i; int read; // char line[80]; FILE *file= fopen(sfs_filename, "r" ); for (i =0 ;i<alleles; i++) { fscanf (file, "%d", &read); par[i]=read; } fclose(file); } /******************************************************************************/ get_sfs_peter1(int *total_neu,int *total_sel,int *nalleles,int *sfs_sel,int *sfs_neu,char *sfs_filename) { int i; int gene_number,sum; FILE *file= fopen(sfs_filename, "r" ); fscanf (file, "%d", &gene_number); fscanf (file, "%d", nalleles); //printf("%d %d\n",read_sfs,*nalleles); fscanf (file, "%d", total_sel); sum=0; for (i =1 ;i<*nalleles; i++) { fscanf (file, "%d", &sfs_sel[i]); //printf("%d\n",sfs_sel[i]); sum+=sfs_sel[i]; } sfs_sel[0]=*total_sel-sum; sfs_sel[*nalleles]=0; fscanf (file, "%d", total_neu); sum=0; for (i =1 ;i<*nalleles; i++) { fscanf (file, "%d", &sfs_neu[i]); //printf("%d\n",sfs_neu[i]); sum+=sfs_neu[i]; } sfs_neu[0]=*total_neu-sum; sfs_neu[*nalleles]=0; //printf("%d\n",sfs_neu[*nalleles]); //monitorinput(); fclose(file); } /******************************************************************************/ get_sfs_peter2(int *total_neu,int *total_sel,int *nalleles,int *sfs_sel,int *sfs_neu,char *sfs_filename,int *sel_sites,int *sel_diff,int *neu_sites,int *neu_diff) { int i; int gene_number,sum; char name[100]; FILE *file= fopen(sfs_filename, "r" ); fscanf (file, "%s", name); fscanf (file, "%d", sel_sites); fscanf (file, "%d", sel_diff); fscanf (file, "%d", neu_sites); fscanf (file, "%d", neu_diff); fscanf (file, "%d", nalleles); //printf("%s %d %d %d %d %d\n",name,sel_sites,sel_diff,neu_sites,neu_diff,*nalleles); fscanf (file, "%d", &sfs_sel[0]); //printf("%d\n",sfs_sel[0]); sum=0; for (i =1 ;i<=*nalleles; i++) { fscanf (file, "%d", &sfs_sel[i]); //printf("%d\n",sfs_sel[i]); sum+=sfs_sel[i]; } //printf("next\n"); fscanf (file, "%d", &sfs_neu[0]); //printf("%d\n",sfs_neu[0]); sum=0; for (i =1 ;i<=*nalleles; i++) { fscanf (file, "%d", &sfs_neu[i]); //printf("%d\n",sfs_neu[i]); sum+=sfs_neu[i]; } //monitorinput(); fclose(file); } /******************************************************************************/ double sfsfold_f(int nalleles,double *sfs,double *sfs_folded,int index) { int i; for (i=0;i<=nalleles/2;i++) { sfs_folded[index+i]=sfs[i]+sfs[index-i]; if(i==nalleles/2&&(!odd(nalleles))) { sfs_folded[index+i]=sfs[i]; } } } /******************************************************************************/ int binarysearchcumulative_from_zero(double *array, int size) { int cur, pre, post; double r; r = uniform(); /* printf("Uniform %f\n", r);*/ pre = 0; post = size; cur = (size + 1)/2; do { if (array[cur] < r) pre = cur; else post = cur; cur = (pre + post)/2; if ((cur==post) || (cur==pre)) { if (r < array[pre]) { /* printf("Returning pre %d\n", pre);*/ return(pre); } else { /* printf("Returning post %d\n", post);*/ return(post); } } } while (size > 0); } /******************************************************************************/ double randomly_select_allele_frequency(double *egf_vec, double *temp1, int nd) { double u, freq; int ind; ind = binarysearchcumulative_from_zero(egf_vec, nd-1); // printf("ind %d\n", ind); (temp1[ind])++; freq = (double)ind/(double)nd; // printf("ind %d freq %lf\n", ind, freq); monitorinput(); return(freq); } /******************************************************************************/ set_up_cumulative_allele_freq_vec(int nd, double *egf_vec, double *cum_vec, char *str) { int i; for (i=0; i<nd; i++) { cum_vec[i] = egf_vec[i]; } for (i=1; i<=nd; i++) { cum_vec[i] += cum_vec[i-1]; } } /******************************************************************************/ generate_simulated_data(double *egf_vec, int nsites, int sample_size, int nd, int *sfs) { int i, n_seg; double allele_freq; struct acc a; initacc(&a); for (i=1; i<=nsites; i++) { allele_freq = randomly_select_allele_frequency(egf_vec, allele_freq_sampled, nd); n_seg = bnldev(allele_freq, sample_size); accum(&a, (double)n_seg); (sfs[n_seg])++; } } /******************************************************************************/ egf_scaling_s(int n1,double f0,double *v_s_in, double *v_s_out) { double sumx,sumy; int i; sumx=0; sumy=0; for (i=1;i<n1;i++){ sumx+=v_s_in[i]; } for (i=1;i<n1;i++){ v_s_out[i]/=sumx; sumy+=v_s_out[i]; } v_s_out[0]=(1-sumy); } /******************************************************************************/ egf_scaling_f0(int n1,double f0,double *fv) { int i; for (i=0;i<n1;i++){ fv[i]*=(1-f0); } fv[0]+=f0; } /******************************************************************************/ egf_scaling(int N,double f0,double *FV0,double *FVS) { int n2d=N*2; egf_scaling_s(n2d,f0,FV0, FVS); egf_scaling_f0(n2d,f0,FVS); } /******************************************************************************/ binomial_sampling(int n1,int alleles,int sample, double *invy,int *discrete) { int s1,success; int i; int n1d=2*n1; double prob; const gsl_rng_type * T; T = gsl_rng_taus; gsl_rng *rgen =gsl_rng_alloc(T); /* based on equilibrium frequency vector (use it as a probability vector), I randomly generate numbers from 0 to n1d-1 for sample sites. */ for (i=0;i<sample;i++) { gsl_ran_discrete_t *r= gsl_ran_discrete_preproc (n1d,invy); s1=gsl_ran_discrete (rgen, r); prob=(double)(s1)/n1d; success=gsl_ran_binomial(rgen,prob,alleles-1); discrete[success]++; gsl_ran_discrete_free(r); } gsl_rng_free (rgen); } /******************************************************************************/ int set_up_density_vec_equal_effects(double s, int n_s_evaluated, double *gamma_density_vec) { double s_lower, s_upper, p_upper; int i, s_ind; s_lower = undefined; s_upper = undefined; // printf("set_up_gamma_density_vec_equal_effects s %lf\n", s); // monitorinput(); for (i=0; i<n_s_evaluated; i++) { gamma_density_vec[i] = 0.0; } for (i=1; i<n_s_evaluated; i++) { // printf("%d %lf ", i, s_evaluated_vec[i]); // printf("\n"); if (s_evaluated_vec[i] >= s) { s_upper = s_evaluated_vec[i]; s_ind = i; if (i != 0 ) s_lower = s_evaluated_vec[i-1]; break; } } if ((s_lower==undefined)||(s_upper==undefined)) return 0; p_upper = (s - s_lower)/(s_upper - s_lower); // printf("set_up_gamma_density_vec_equal_effects: s_lower %lf s_upper %lf\n", // s_lower, s_upper); // printf("p_upper %lf\n", p_upper); // monitorinput(); gamma_density_vec[s_ind] = p_upper; if (s_ind==1) gamma_density_vec[s_ind] += (1.0 - p_upper); else gamma_density_vec[s_ind-1] = (1.0 - p_upper); // for (i=1; i<n_s_evaluated; i++) // { // printf("s %lf gamma_density_vec[%d] %lf\n", s_evaluated_vec[i], i, // gamma_density_vec[i]); // } // monitorinput(); return (1); } /******************************************************************************/ int set_up_density_vec_step_effects(double alpha, double beta, int n_s_evaluated, double *gamma_density_vec) { if (alpha<0){alpha=-alpha;} if (beta<0){beta=-beta;} int i,s_ind; double lower, upper, area, total_area = 0.0, x, diff, step, inc_x, inc_y, gf; double mean; for (i=0; i<n_s_evaluated; i++) { x = s_evaluated_vec[i]; get_lower_upper(i, s_evaluated_vec, n_s_evaluated, &lower, &upper); /*calculate cumulative uniform distribution for lower and upper*/ inc_x=gsl_cdf_flat_P(lower,alpha,beta); inc_y=gsl_cdf_flat_P(upper,alpha,beta); area=inc_y-inc_x; gamma_density_vec[i] = area; total_area+=area; //printf("x %f inc_x %f inc_y %f area %f\n",x,inc_x,inc_y,area); } //printf("alpha:%f beta:%f total_area:%f\n",alpha,beta, total_area); //monitorinput(); // area =gsl_cdf_flat_P(-s_evaluated_vec[0], alpha, beta); // gamma_density_vec[0]+=1.0-area; //if (gamma_density_vec[0]>0){printf("%f\n",gamma_density_vec[0]);} return (1); } /******************************************************************************/ double compute_beta_densities(double alpha, double *s_evaluated_vec, int n_s_evaluated, double *gamma_density_vec, double beta) { int i; double lower, upper, area, total_area = 0.0, x, diff, step, inc_x, inc_y, gf; if (alpha <= 0) return undefined; if (beta <= 0) return undefined; for (i=0; i<n_s_evaluated; i++) { x = s_evaluated_vec[i]; get_lower_upper(i, s_evaluated_vec, n_s_evaluated, &lower, &upper); inc_x = gsl_cdf_beta_P (lower, alpha, beta); inc_y = gsl_cdf_beta_P (upper, alpha, beta); area = (inc_y - inc_x); gamma_density_vec[i] = area; //printf("x %f inc_x %f inc_y %f area %f\n",x,inc_x,inc_y,area); } area = gsl_cdf_beta_P(-s_evaluated_vec[0], alpha, beta); gamma_density_vec[0]+=1.0-area; return (1); } /******************************************************************************/ double compute_gamma_densities(double alpha, double *s_evaluated_vec, int n_s_evaluated, double *gamma_density_vec, double beta) { int i; double lower, upper, area, total_area = 0.0, x, diff, step, inc_x, inc_y, gf; if (alpha <= 0) return undefined; for (i=0; i<n_s_evaluated; i++) { x = s_evaluated_vec[i]; get_lower_upper(i, s_evaluated_vec, n_s_evaluated, &lower, &upper); inc_x = gsl_cdf_gamma_P(lower, beta,1/alpha); inc_y = gsl_cdf_gamma_P(upper, beta,1/alpha); area = (inc_y - inc_x); gamma_density_vec[i] = area; total_area+=area; //printf("x%f 1/alpha %f beta %f area %f\n",x,1/alpha,beta,area); } area = gsl_cdf_gamma_P(-s_evaluated_vec[0], beta,1/alpha); gamma_density_vec[0]+=1.0-area; //printf("x%f inc_x %f inc_y %f area %f\n",x,inc_x,inc_y,area); return (1); } /******************************************************************************/ double calculate_ne(int n1,int n2,int t) { double w1,w2,n_e; double N1=(double)n1; double N2=(double)n2; double t2=(double)t; /*compute weighted Ne*/ w1=N1*pow((1-1/(2*N2)),t2); w2=N2*(1-exp(-t2/(2*N2))); n_e=(N1*w1+N2*w2)/(w1+w2); return n_e; }
{ "alphanum_fraction": 0.5296904441, "avg_line_length": 26.5926986399, "ext": "c", "hexsha": "7948aef6f4fea207986f1963ae2023b86c4a6f85", "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": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kousathanas/simsfs_fast", "max_forks_repo_path": "Library_DFE_v1.8.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "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": "kousathanas/simsfs_fast", "max_issues_repo_path": "Library_DFE_v1.8.c", "max_line_length": 162, "max_stars_count": null, "max_stars_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kousathanas/simsfs_fast", "max_stars_repo_path": "Library_DFE_v1.8.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 11169, "size": 37150 }
// -------------------------------------------------------- // Dragon // Copyright(c) 2017 SeetaTech // Written by Ting Pan // -------------------------------------------------------- #ifndef DRAGON_UTILS_MATH_FUNCTIONS_H_ #define DRAGON_UTILS_MATH_FUNCTIONS_H_ #include <float.h> #include <cstdint> #include <climits> #ifdef WITH_BLAS extern "C" { #include <cblas.h> } #else // WITH_BLAS typedef enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112} CBLAS_TRANSPOSE; #endif #include "protos/dragon.pb.h" namespace dragon { namespace math { /******************** Level-0 ********************/ template <typename T, class Context> void Set(const int n, const T alpha, T* x); template <typename T, class Context> void RandomUniform(const int n, const float low, const float high, T *x); template <typename T, class Context> void RandomNormal(const int n, const float mu, const float sigma, T* x); template <typename T, class Context> void RandomTruncatedNormal(const int n, const float mu, const float sigma, const float low, const float high, T* x); template <typename T, class Context> void RandomBernoulli(const int n, const float p, uint32_t* x); /******************** Level-1 ********************/ template <typename T, class Context> void Add(const int n, const T* a, const T* b, T* y); template <typename T, class Context> void Sub(const int n, const T* a, const T* b, T* y); template <typename T, class Context> void Mul(const int n, const T* a, const T* b, T* y); template <typename T, class Context> void Div(const int n, const T* a, const T* b, T* y); template <typename T, class Context> void Clip(const int n, const float low, const float high, T* x); template <typename T, class Context> void Exp(const int n, const T* x, T* y); template <typename T, class Context> void Log(const int n, const T* x, T* y); template <typename T, class Context> void Square(const int n, const T* x, T* y); template <typename T, class Context> void Sqrt(const int n, const T* x, T* y); template <typename T, class Context> void Pow(const int n, const float alpha, const T* x, T* y); template <typename T, class Context> void Inv(const int n, const float numerator, const T* x, T* y); /******************** Level-2 ********************/ template <typename T, class Context> void Scal(const int n, const float alpha, T* y); template <typename T, class Context> void Scale(const int n, const float alpha, const T* x, T* y); template <typename T, class Context> T StridedDot(const int n, const T* a, const int incx, const T* b, const int incy); template <typename T, class Context> float Dot(const int n, const T* a, const T* b); template<typename T, class Context> float ASum(const int n, const T *x); template<typename T, class Context> void AddScalar(const int n, const float alpha, T* y); template<typename T, class Context> void MulScalar(const int n, const float alpha, T* y); template<typename T, class Context> void Axpy(const int n, float alpha, const T* x, T *y); template<typename T, class Context> void Axpby(const int n, float alpha, const T* x, float beta, T *y); /******************** Level-3 ********************/ template <typename T, class Context> void Gemm(const CBLAS_TRANSPOSE transA, const CBLAS_TRANSPOSE transB, const int M, const int N, const int K, const float alpha, const T* A, const T* B, const float beta, T* C, TensorProto_DataType math_type = TensorProto_DataType_FLOAT); template<typename T, class Context> void Gemv(const CBLAS_TRANSPOSE transA, const int M, const int N, const float alpha, const T* A, const T* x, const float beta, T* y, TensorProto_DataType math_type = TensorProto_DataType_FLOAT); } // namespace math } // namespace dragon #endif // DRAGON_UTILS_MATH_FUNCTIONS_H_
{ "alphanum_fraction": 0.611622276, "avg_line_length": 27.7181208054, "ext": "h", "hexsha": "11b5330eb39ab0581e1a8efa24b4d5d6f8c02fc5", "lang": "C", "max_forks_count": 71, "max_forks_repo_forks_event_max_datetime": "2021-06-03T01:52:41.000Z", "max_forks_repo_forks_event_min_datetime": "2016-03-24T09:02:41.000Z", "max_forks_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "neopenx/Dragon", "max_forks_repo_path": "Dragon/include/utils/math_functions.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_issues_repo_issues_event_max_datetime": "2017-12-12T02:21:15.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-07T14:31:56.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "neopenx/Dragon", "max_issues_repo_path": "Dragon/include/utils/math_functions.h", "max_line_length": 80, "max_stars_count": 212, "max_stars_repo_head_hexsha": "0e639a7319035ddc81918bd3df059230436ee0a1", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "neopenx/Dragon", "max_stars_repo_path": "Dragon/include/utils/math_functions.h", "max_stars_repo_stars_event_max_datetime": "2022-02-27T01:55:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-07-05T07:57:17.000Z", "num_tokens": 997, "size": 4130 }
/* # This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE */ #include <assert.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> #include <stdarg.h> #include "os-features.h" #include "gslutils.h" #include "errors.h" static void errhandler(const char * reason, const char * file, int line, int gsl_errno) { ERROR("GSL error: \"%s\" in %s:%i (gsl errno %i = %s)", reason, file, line, gsl_errno, gsl_strerror(gsl_errno)); } void gslutils_use_error_system() { gsl_set_error_handler(errhandler); } int gslutils_invert_3x3(const double* A, double* B) { gsl_matrix* LU; gsl_permutation *p; gsl_matrix_view mB; int rtn = 0; int signum; p = gsl_permutation_alloc(3); gsl_matrix_const_view mA = gsl_matrix_const_view_array(A, 3, 3); mB = gsl_matrix_view_array(B, 3, 3); LU = gsl_matrix_alloc(3, 3); gsl_matrix_memcpy(LU, &mA.matrix); if (gsl_linalg_LU_decomp(LU, p, &signum) || gsl_linalg_LU_invert(LU, p, &mB.matrix)) { ERROR("gsl_linalg_LU_decomp() or _invert() failed."); rtn = -1; } gsl_permutation_free(p); gsl_matrix_free(LU); return rtn; } void gslutils_matrix_multiply(gsl_matrix* C, const gsl_matrix* A, const gsl_matrix* B) { gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A, B, 0.0, C); } int gslutils_solve_leastsquares_v(gsl_matrix* A, int NB, ...) { int i, res; gsl_vector** B = malloc(NB * sizeof(gsl_vector*)); // Whoa, three-star programming! gsl_vector*** X = malloc(NB * sizeof(gsl_vector**)); gsl_vector*** R = malloc(NB * sizeof(gsl_vector**)); gsl_vector** Xtmp = malloc(NB * sizeof(gsl_vector*)); gsl_vector** Rtmp = malloc(NB * sizeof(gsl_vector*)); va_list va; va_start(va, NB); for (i=0; i<NB; i++) { B[i] = va_arg(va, gsl_vector*); X[i] = va_arg(va, gsl_vector**); R[i] = va_arg(va, gsl_vector**); } va_end(va); res = gslutils_solve_leastsquares(A, B, Xtmp, Rtmp, NB); for (i=0; i<NB; i++) { if (X[i]) *(X[i]) = Xtmp[i]; else gsl_vector_free(Xtmp[i]); if (R[i]) *(R[i]) = Rtmp[i]; else gsl_vector_free(Rtmp[i]); } free(Xtmp); free(Rtmp); free(X); free(R); free(B); return res; } int gslutils_solve_leastsquares(gsl_matrix* A, gsl_vector** B, gsl_vector** X, gsl_vector** resids, int NB) { int i; gsl_vector *tau, *resid = NULL; Unused int ret; int M, N; M = A->size1; N = A->size2; for (i=0; i<NB; i++) { assert(B[i]); assert(B[i]->size == M); } tau = gsl_vector_alloc(MIN(M, N)); assert(tau); ret = gsl_linalg_QR_decomp(A, tau); assert(ret == 0); // A,tau now contains a packed version of Q,R. for (i=0; i<NB; i++) { if (!resid) { resid = gsl_vector_alloc(M); assert(resid); } X[i] = gsl_vector_alloc(N); assert(X[i]); ret = gsl_linalg_QR_lssolve(A, tau, B[i], X[i], resid); assert(ret == 0); if (resids) { resids[i] = resid; resid = NULL; } } gsl_vector_free(tau); if (resid) gsl_vector_free(resid); return 0; }
{ "alphanum_fraction": 0.5551885494, "avg_line_length": 25.0551724138, "ext": "c", "hexsha": "a8607f557154c88aebfbea3ed3ace4660a1a5bf1", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "util/gslutils.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "util/gslutils.c", "max_line_length": 73, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "util/gslutils.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 1065, "size": 3633 }
#include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <math.h> #include "gauss.h" #include "ts_fac.h" #include "ts_tr_fac.h" static double v_func(double diff){ double denom = gsl_cdf_ugaussian_P(diff); double nom = gsl_ran_ugaussian_pdf(diff); return nom / denom; } static double w_func(double diff, double v){ return (v*(v+diff)); } static void ts_tr_fac_up(ts_fac_t *self, int useless){ ts_var_t *var = self->vars[TS_TR_SUM_VAR]; gauss_t msg = ts_fg_msg_to_var(var, self); gauss_t val = gauss_div(var->value, msg); double sqrt_pi = sqrt(gauss_pi(val)); double normal = gauss_tau(val) / sqrt_pi; double v = v_func(normal); double w = w_func(normal, v); double denom = 1.0 - w; double new_pi = gauss_pi(val) / denom; double new_tau = (gauss_tau(val) + (sqrt_pi * v)) / denom; gauss_t nv = gauss_init_prec(new_tau, new_pi); ts_var_update_val(var, self, nv); } static void ts_tr_fac_down(ts_fac_t *self, int useless){ } ts_fac_t* ts_tr_fac_new(ts_fg_t *fg, ts_var_t *sum_var){ ts_fac_t *self = ts_fac_new(fg); self->vars[TS_TR_SUM_VAR] = sum_var; self->up_func = ts_tr_fac_up; self->down_func = ts_tr_fac_down; ts_fg_msg_to_var(sum_var, self) = gauss_init_prec(0.0, 0.0); return self; }
{ "alphanum_fraction": 0.7039106145, "avg_line_length": 26.6595744681, "ext": "c", "hexsha": "e54e6624db6bc172770c0e7dbeeb3fd2d7beedee", "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": "caffee7a58ef60b962aee41d91da1f8f1808462f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cosmicturtle/gamesetmatch", "max_forks_repo_path": "ts_tr_fac.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "caffee7a58ef60b962aee41d91da1f8f1808462f", "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": "cosmicturtle/gamesetmatch", "max_issues_repo_path": "ts_tr_fac.c", "max_line_length": 61, "max_stars_count": null, "max_stars_repo_head_hexsha": "caffee7a58ef60b962aee41d91da1f8f1808462f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cosmicturtle/gamesetmatch", "max_stars_repo_path": "ts_tr_fac.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 380, "size": 1253 }
/** * @file pflow.h * @brief Public header file for power flow application */ #ifndef PFLOW_H #define PFLOW_H #include <petsc.h> #include "cJSON.h" typedef struct _p_PFLOW *PFLOW; PETSC_EXTERN PetscErrorCode PFLOWCreate(MPI_Comm,PFLOW*); PETSC_EXTERN PetscErrorCode PFLOWDestroy(PFLOW*); PETSC_EXTERN PetscErrorCode PFLOWReadMatPowerData(PFLOW,const char[]); PETSC_EXTERN PetscErrorCode PFLOWSolve(PFLOW); PETSC_EXTERN PetscErrorCode PFLOWPostSolve(PFLOW); /* FUNCTIONS FOR PARSING DATA */ int PFLOWParserGetVal(cJSON *, const char *, double *, int); double PFLOWParserGet(PFLOW,int,char *, const char *); void PFLOWParserSet(PFLOW,int,char *, PetscScalar, const char *); #endif
{ "alphanum_fraction": 0.7727930535, "avg_line_length": 23.8275862069, "ext": "h", "hexsha": "6d918b9bdaed163370d32983e9111f7d797fc2d4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "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": "GMLC-TDC/Use-Cases", "max_issues_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_line_length": 70, "max_stars_count": 1, "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_path": "ANL_adaptive_volt_var/include/pflow.h", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "num_tokens": 174, "size": 691 }
/* * 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_ROTOR_DATABASE_H_ #define SIM_PHYSICS_ROTOR_DATABASE_H_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <string> #include "common/macros.h" class RotorDatabase { public: explicit RotorDatabase(const std::string &filename); virtual ~RotorDatabase(); // Calculates the rotor's thrust [N], applied torque [N-m], or // generated power [W] based on the angular rate, freestream // velocity, and air density. Torque and power are defined to be // negative during thrusting. double CalcThrust(double angular_rate, double freestream_vel, double air_density) const; double CalcTorque(double angular_rate, double freestream_vel, double air_density) const; double CalcPower(double angular_rate, double freestream_vel, double air_density) const; // Looks-up the value of the rotor's thrust, torque, or power // coefficients [#] at a given angular rate and freestream velocity // in a 2-D look-up table. Values are interpolated linearly between // points and the inputs are saturated to the limits of the table. double LookupThrustCoeff(double angular_rate, double freestream_vel) const; double LookupTorqueCoeff(double angular_rate, double freestream_vel) const; double LookupPowerCoeff(double angular_rate, double freestream_vel) const; private: // Returns true if the rotor database follows our sign conventions: // // - Power coefficient decreases with increasing angular rate for // the low freestream velocity case, i.e. power is positive in // generation. // // - Thrust coefficient increases with increasing angular rate for // the low freestream velocity case. bool IsValid() const; // Diameter of the propeller [m]. double diameter_; // Vector of angular rates [rad/s], which define the rows of the // look-up table. gsl_vector *angular_rates_; // Vector of freestream velocities [m/s], which define the columns // of the look-up table. gsl_vector *freestream_vels_; // Matrix of thrust coefficients [#] defined over a tensor grid of // freestream velocities and angular rates. The thrust coefficient // is defined as: // // thrust_coeff = thrust / (air_density * angular_rate_hz^2 * diameter^4) // // See Eq. 9.18, Houghton & Carpenter, 4th ed. gsl_matrix *thrust_coeffs_; // Matrix of power coefficients [#] defined over a tensor grid of // freestream velocities and angular rates. The power coefficient // is defined as: // // power_coeff = power / (air_density * angular_rate_hz^3 * diameter^5) // // See Eq. 9.22, Houghton & Carpenter, 4th ed. gsl_matrix *power_coeffs_; DISALLOW_COPY_AND_ASSIGN(RotorDatabase); }; #endif // SIM_PHYSICS_ROTOR_DATABASE_H_
{ "alphanum_fraction": 0.7259062776, "avg_line_length": 35.7157894737, "ext": "h", "hexsha": "42c3bf91c5c31fc9aaea2e0bf7c11fc1cdf495bd", "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/rotor_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/rotor_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/rotor_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": 816, "size": 3393 }
#include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_statistics_double.h> #include "tz_error.h" #include "tz_constant.h" #include "tz_image_lib.h" #include "tz_objdetect.h" #include "tz_imatrix.h" #include "tz_stack_math.h" #include "tz_stack_bwdist.h" #include "tz_voxel_linked_list.h" #include "tz_stack_sampling.h" #include "tz_matlabio.h" #include "tz_voxel_graphics.h" #include "tz_darray.h" #include "tz_geo3d_scalar_field.h" INIT_EXCEPTION_MAIN(e) int main(int argc, char* argv[]) { char neuron_name[100]; char matlab_path[100]; if (argc == 1) { strcpy(neuron_name, "fly_neuron"); } else { strcpy(neuron_name, argv[1]); } if (argc < 3) { strcpy(matlab_path, "/Applications/MATLAB74/bin/matlab"); } else { strcpy(matlab_path, argv[2]); } char file_path[100]; /* sprintf(file_path, "../data/%s/mask.tif", neuron_name); Stack *stack = Read_Stack(file_path); Stack_Not(stack, stack); Set_Matlab_Path(matlab_path); Stack *dist = Stack_Bwdist(stack); */ sprintf(file_path, "../data/%s/dist.tif", neuron_name); Stack *dist = Read_Stack(file_path); //Stack *seeds = Stack_Local_Max(dist, NULL, STACK_LOCMAX_ALTER1); sprintf(file_path, "../data/%s/seeds.tif", neuron_name); Stack *seeds = Read_Stack(file_path); //sprintf(file_path, "../data/%s/grow_bundle.tif", neuron_name); sprintf(file_path, "../data/%s/bundle.tif", neuron_name); Stack *bundle = Read_Stack(file_path); Stack_And(seeds, bundle, seeds); sprintf(file_path, "../data/%s/bundle_seed.tif", neuron_name); Write_Stack(file_path, seeds); printf("%s created.\n", file_path); Voxel_List *list = Stack_To_Voxel_List(seeds); Pixel_Array *pa = Voxel_List_Sampling(dist, list); sprintf(file_path, "../data/%s/bundle_seeds.pa", neuron_name); Pixel_Array_Write(file_path, pa); printf("%s created.\n", file_path); int i; //double *pa_array = (double *) pa->array; uint16 *pa_array16 = (uint16 *) pa->array; double *pa_array = darray_malloc(pa->size); for (i = 0; i < pa->size; i++) { pa_array[i] = sqrt(pa_array16[i]); } Voxel_P *voxel_array = Voxel_List_To_Array(list, 1, NULL, NULL); Geo3d_Scalar_Field *field = Make_Geo3d_Scalar_Field(pa->size); for (i = 0; i < pa->size; i++) { field->points[i][0] = voxel_array[i]->x; field->points[i][1] = voxel_array[i]->y; field->points[i][2] = voxel_array[i]->z; field->values[i] = pa_array[i]; } sprintf(file_path, "../data/%s/seeds", neuron_name); Write_Geo3d_Scalar_Field(file_path, field); printf("%s created.\n", file_path); printf("mean: %g, std: %g\n", gsl_stats_mean(pa_array, 1, pa->size), sqrt(gsl_stats_variance(pa_array, 1, pa->size))); printf("%g\n", gsl_stats_max(pa_array, 1, pa->size)); return 0; }
{ "alphanum_fraction": 0.6769230769, "avg_line_length": 27.6732673267, "ext": "c", "hexsha": "b56578d6948b07f35002e3e716161f4be93d6e62", "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": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_seed.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_seed.c", "max_line_length": 71, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/fly_neuron_bundle_seed.c", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "num_tokens": 842, "size": 2795 }
#pragma once #include <gsl/gsl> #include <memory> #include <tuple> #include "../math/Constants.h" #include "../math/Exponentials.h" #include "../math/General.h" #include "../math/Point2.h" #include "../math/Point3.h" #include "../math/Random.h" #include "../math/TrigFuncs.h" #include "../math/Vec2.h" #include "../math/Vec3.h" #include "../utils/Concepts.h" /// @brief custom mathematics implementaitons namespace math { } // namespace math /// @brief utility types namespace utils { } // namespace utils using utils::concepts::ConstructibleFrom; // NOLINT using utils::concepts::Copyable; // NOLINT using utils::concepts::CopyOrMovable; // NOLINT using utils::concepts::DefaultConstructible; // NOLINT using utils::concepts::Derived; // NOLINT using utils::concepts::FloatingPoint; // NOLINT using utils::concepts::Integral; // NOLINT using utils::concepts::Movable; // NOLINT using utils::concepts::NotCopyable; // NOLINT using utils::concepts::NotCopyOrMovable; // NOLINT using utils::concepts::NotDefaultConstructible; // NOLINT using utils::concepts::NotMovable; // NOLINT using utils::concepts::NotPassable; // NOLINT using utils::concepts::NotPointer; // NOLINT using utils::concepts::NotReference; // NOLINT using utils::concepts::NotSemiRegular; // NOLINT using utils::concepts::Numeric; // NOLINT using utils::concepts::Passable; // NOLINT using utils::concepts::Pointer; // NOLINT using utils::concepts::Reference; // NOLINT using utils::concepts::SemiRegular; // NOLINT using utils::concepts::SignedIntegral; // NOLINT using utils::concepts::SignedNumeric; // NOLINT using math::Constants; // NOLINT using math::Exponentials; // NOLINT using math::General; // NOLINT using math::Point2; // NOLINT using math::Point2Idx; // NOLINT using math::Point3; // NOLINT using math::Point3Idx; // NOLINT using math::random_value; // NOLINT using math::Trig; // NOLINT using math::Vec2; // NOLINT using math::Vec2Idx; // NOLINT using math::Vec3; // NOLINT using math::Vec3Idx; // NOLINT using gsl::narrow_cast; // NOLINT template<typename T> using NotNull = gsl::not_null<T*>; // NOLINT template<typename T> using Owner = gsl::owner<T*>; // NOLINT template<FloatingPoint T = float> inline constexpr auto degrees_to_radians(T degrees) noexcept -> T { return degrees * Constants<T>::pi / narrow_cast<T>(180.0); } template<FloatingPoint T = float> inline constexpr auto radians_to_degrees(T radians) noexcept -> T { return radians * narrow_cast<T>(180.0) / Constants<T>::pi; } template<SignedNumeric T = float> inline constexpr auto clamp(T val, T min, T max) noexcept -> T { if(val < min) { return min; } else if(val > max) { return max; } else { return val; } } template<typename... Args> inline constexpr auto ignore(Args&&... args) noexcept -> void { std::ignore = std::tuple<Args...>(args...); } // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_UNUSED_MACROS_START \ _Pragma("GCC diagnostic push")\ _Pragma("GCC diagnostic ignored \"-Wunused-macros\"") #else // NOLINTNEXTLINE #define IGNORE_UNUSED_MACROS_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_UNUSED_MACROS_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_UNUSED_MACROS_STOP #endif // clang-format on IGNORE_UNUSED_MACROS_START // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_PADDING_START \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wpadded\"") #else // NOLINTNEXTLINE #define IGNORE_PADDING_START \ _Pragma("warning( push )") \ _Pragma("warning( disable : 4820 )") #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_PADDING_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_PADDING_STOP \ _Pragma("warning( pop )") #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_UNUSED_TEMPLATES_START \ _Pragma("GCC diagnostic push")\ _Pragma("GCC diagnostic ignored \"-Wunused-template\"") #else // NOLINTNEXTLINE #define IGNORE_UNUSED_TEMPLATES_START #endif // clang-format on // clang-format off #ifndef _MSC_VER // NOLINTNEXTLINE #define IGNORE_UNUSED_TEMPLATES_STOP \ _Pragma("GCC diagnostic pop") #else // NOLINTNEXTLINE #define IGNORE_UNUSED_TEMPLATES_STOP #endif // clang-format on IGNORE_UNUSED_MACROS_STOP
{ "alphanum_fraction": 0.7182848256, "avg_line_length": 26.4764705882, "ext": "h", "hexsha": "d2f6d13e89c12bfb20a0f9a478179537557e350e", "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": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_path": "src/base/StandardIncludes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "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": "braxtons12/ray_tracer", "max_issues_repo_path": "src/base/StandardIncludes.h", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_path": "src/base/StandardIncludes.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1346, "size": 4501 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName) { FILE *fp = fopen(input_fileName, "r"); fscanf(fp, "%*[^\n]\n"); for (int ii = 0; ii < N_kw; ii++) fscanf(fp, "%d,", &((*index)[ii])); fscanf(fp, "%*[^\n]\n"); int tmp; for (int ii = 0; ii < N_kw; ii++) { for (int jj = 0; jj < N_kw; jj++) { fscanf(fp, "%d,", &tmp); (*matrix)[ii*N_kw + jj] = (int) (tmp * scaling); } fscanf(fp, "%*[^\n]\n"); } fclose(fp); } void pad_matrix(int** matrix_padded, int** matrix, int N_kw, int N_doc, double sec_budget, int fixed_padding) { // Initialising RNG const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); // perform padding on the keywords int ii, jj; #pragma omp parallel for private(ii) for (int ii = 0; ii < N_kw; ii++) (*matrix_padded)[ii*N_kw + ii] = 2 * (*matrix)[ii*N_kw + ii] + fixed_padding + (int) gsl_ran_laplace(r, 2.0/sec_budget); // perform padding #pragma omp parallel for private(ii, jj) for (ii = 0; ii < N_kw; ii++) { for (jj = 0; jj < N_kw; jj++) { if (ii > jj) { int n1 = (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + ii]; int n2 = (*matrix_padded)[jj*N_kw + jj] - (*matrix)[jj*N_kw + jj]; int x1 = gsl_ran_hypergeometric(r, n1, 2*N_doc-n1, (*matrix_padded)[jj*N_kw + jj]); int x2 = gsl_ran_hypergeometric(r, n2, 2*N_doc-n2, (*matrix_padded)[ii*N_kw + ii]); (*matrix_padded)[ii*N_kw + jj] = (*matrix)[ii*N_kw + jj] + x1 + x2; (*matrix_padded)[jj*N_kw + ii] = (*matrix_padded)[ii*N_kw + jj]; } } } gsl_rng_free(r); } void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw) { // perform observed count generation for (int ii = 0; ii < N_kw; ii++) for (int jj = 0; jj < N_kw; jj++) gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj])); } void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, gsl_matrix* matrix_obs, int** matrix, int fixed_padding, int N_kw, int N_obs, int N_doc, double sec_budget) { double N1_lower, N1_upper, N2_lower, N2_upper; int check = -1; int count = 0; *idx1 = rand() % N_obs; *idx2 = -1; int idx_old = (*permutation)[*idx1]; int idx_new = 0; do { idx_new = rand() % N_kw; count++; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding; N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding; N2_lower = 2 * (*matrix)[idx_old*N_kw + idx_old] - 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) - 4 / sec_budget + fixed_padding; N2_upper = 2 * (*matrix)[idx_old*N_kw + idx_old] + 4 * sqrt((*matrix)[idx_old*N_kw + idx_old] * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) / N_doc) + 4 / sec_budget + fixed_padding; if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper)) if ((gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower) && (gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower)) check = 1; } else { *idx2 = -1; N1_lower = 2 * (*matrix)[idx_new*N_kw + idx_new] - 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) - 4 / sec_budget + fixed_padding; N1_upper = 2 * (*matrix)[idx_new*N_kw + idx_new] + 4 * sqrt((*matrix)[idx_new*N_kw + idx_new] * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) / N_doc) + 4 / sec_budget + fixed_padding; if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper)) check = 1; } } while ((check < 0) && (count < 200)); if (count == 200) *idx2 = *idx1; if (*idx1 != *idx2) { (*permutation_tmp)[*idx1] = idx_new; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; (*permutation_tmp)[*idx2] = idx_old; } } }
{ "alphanum_fraction": 0.5564694082, "avg_line_length": 37.4812030075, "ext": "c", "hexsha": "9de18facd8d7817fa83e5103486b1c9611911eb7", "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": "39602b0912b21afc45e73008e598f4377ba237eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_path": "DP-EMM/util.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_path": "DP-EMM/util.c", "max_line_length": 222, "max_stars_count": null, "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_path": "DP-EMM/util.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1568, "size": 4985 }
/* multifit_nlinear/fdfvv.c * * Copyright (C) 2015 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_multifit_nlinear.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> /* fdfvv() Compute approximate second directional derivative using finite differences. See Eq. 19 of: M. K. Transtrum, J. P. Sethna, Improvements to the Levenberg Marquardt algorithm for nonlinear least-squares minimization, arXiv:1201.5885, 2012. Inputs: h - step size for finite difference x - parameter vector, size p v - geodesic velocity, size p f - vector of function values f_i(x), size n J - Jacobian matrix J(x), n-by-p swts - data weights fdf - fdf struct fvv - (output) approximate second directional derivative vector D_v^2 f(x) work - workspace, size p Return: success or error */ static int fdfvv(const double h, const gsl_vector *x, const gsl_vector *v, const gsl_vector *f, const gsl_matrix *J, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, gsl_vector *fvv, gsl_vector *work) { int status; const size_t n = fdf->n; const size_t p = fdf->p; const double hinv = 1.0 / h; size_t i; /* compute work = x + h*v */ for (i = 0; i < p; ++i) { double xi = gsl_vector_get(x, i); double vi = gsl_vector_get(v, i); gsl_vector_set(work, i, xi + h * vi); } /* compute f(x + h*v) */ status = gsl_multifit_nlinear_eval_f (fdf, work, swts, fvv); if (status) return status; for (i = 0; i < n; ++i) { double fi = gsl_vector_get(f, i); /* f_i(x) */ double fip = gsl_vector_get(fvv, i); /* f_i(x + h*v) */ gsl_vector_const_view row = gsl_matrix_const_row(J, i); double u, fvvi; /* compute u = sum_{ij} J_{ij} D v_j */ gsl_blas_ddot(&row.vector, v, &u); fvvi = (2.0 * hinv) * ((fip - fi) * hinv - u); gsl_vector_set(fvv, i, fvvi); } return status; } /* gsl_multifit_nlinear_fdfvv() Compute approximate second directional derivative using finite differences Inputs: h - step size for finite difference x - parameter vector, size p v - geodesic velocity, size p f - function values f_i(x), size n J - Jacobian matrix J(x), n-by-p swts - sqrt data weights (set to NULL if not needed) fdf - fdf fvv - (output) approximate (weighted) second directional derivative vector, size n, sqrt(W) fvv work - workspace, size p Return: success or error */ int gsl_multifit_nlinear_fdfvv(const double h, const gsl_vector *x, const gsl_vector *v, const gsl_vector *f, const gsl_matrix *J, const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf, gsl_vector *fvv, gsl_vector *work) { return fdfvv(h, x, v, f, J, swts, fdf, fvv, work); }
{ "alphanum_fraction": 0.6393751683, "avg_line_length": 30.4344262295, "ext": "c", "hexsha": "612b4742a1f945ef0524c444f301340e47479bd5", "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/multifit_nlinear/fdfvv.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/multifit_nlinear/fdfvv.c", "max_line_length": 84, "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/multifit_nlinear/fdfvv.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": 1054, "size": 3713 }
/* monte/gsl_monte_miser.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth * Copyright (C) 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. */ /* Author: MJB */ #ifndef __GSL_MONTE_MISER_H__ #define __GSL_MONTE_MISER_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_rng.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t min_calls; size_t min_calls_per_bisection; double dither; double estimate_frac; double alpha; size_t dim; int estimate_style; int depth; int verbose; double * x; double * xmid; double * sigma_l; double * sigma_r; double * fmax_l; double * fmax_r; double * fmin_l; double * fmin_r; double * fsum_l; double * fsum_r; double * fsum2_l; double * fsum2_r; size_t * hits_l; size_t * hits_r; } gsl_monte_miser_state; GSL_FUN int gsl_monte_miser_integrate(gsl_monte_function * f, const double xl[], const double xh[], size_t dim, size_t calls, gsl_rng *r, gsl_monte_miser_state* state, double *result, double *abserr); GSL_FUN gsl_monte_miser_state* gsl_monte_miser_alloc(size_t dim); GSL_FUN int gsl_monte_miser_init(gsl_monte_miser_state* state); GSL_FUN void gsl_monte_miser_free(gsl_monte_miser_state* state); typedef struct { double estimate_frac; size_t min_calls; size_t min_calls_per_bisection; double alpha; double dither; } gsl_monte_miser_params; GSL_FUN void gsl_monte_miser_params_get (const gsl_monte_miser_state * state, gsl_monte_miser_params * params); GSL_FUN void gsl_monte_miser_params_set (gsl_monte_miser_state * state, const gsl_monte_miser_params * params); __END_DECLS #endif /* __GSL_MONTE_MISER_H__ */
{ "alphanum_fraction": 0.6855737705, "avg_line_length": 28.2407407407, "ext": "h", "hexsha": "2377fc8ca1cb01a658179b5a635b387b4f72baeb", "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_monte_miser.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_monte_miser.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_monte_miser.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": 803, "size": 3050 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // clang-format off #pragma once #pragma warning(push) // C #include <climits> #include <cwchar> #include <cwctype> // STL // Block minwindef.h min/max macros to prevent <algorithm> conflict #define NOMINMAX #include <algorithm> #include <atomic> #include <deque> #include <list> #include <memory> #include <map> #include <mutex> #include <shared_mutex> #include <new> #include <optional> #include <queue> #include <stdexcept> #include <string> #include <string_view> #include <thread> #include <tuple> #include <utility> #include <vector> #include <unordered_map> #include <iterator> #include <math.h> #include <sstream> #include <fstream> #include <iomanip> #include <filesystem> #include <functional> #include <set> #include <unordered_set> // WIL #include <wil/Common.h> #include <wil/Result.h> #include <wil/resource.h> #include <wil/wistd_memory.h> #include <wil/stl.h> #include <wil/com.h> #include <wil/filesystem.h> #include <wil/win32_helpers.h> // GSL // Block GSL Multi Span include because it both has C++17 deprecated iterators // and uses the C-namespaced "max" which conflicts with Windows definitions. #ifndef BLOCK_GSL #define GSL_MULTI_SPAN_H #include <gsl/gsl> #endif // CppCoreCheck #include <CppCoreCheck/Warnings.h> // IntSafe #define ENABLE_INTSAFE_SIGNED_FUNCTIONS #include <intsafe.h> // SAL #include <sal.h> // WRL #include <wrl.h> // TIL - Terminal Implementation Library #include "til.h" #pragma warning(pop) // clang-format on
{ "alphanum_fraction": 0.6941896024, "avg_line_length": 18.7931034483, "ext": "h", "hexsha": "3033cc1055c276390bd326665cc9b920dbf507d5", "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": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Vereis/terminal", "max_forks_repo_path": "src/inc/LibraryIncludes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "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": "Vereis/terminal", "max_issues_repo_path": "src/inc/LibraryIncludes.h", "max_line_length": 79, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6d6fb7f69058b78af0c77e376bed7228ad9eb41f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Vereis/terminal", "max_stars_repo_path": "src/inc/LibraryIncludes.h", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:56:42.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-08T06:55:45.000Z", "num_tokens": 375, "size": 1635 }
#pragma once #include <cuda/runtime_api.hpp> #include <gsl/gsl-lite.hpp> namespace thrustshift { namespace kernel { template <typename A, class RangeX, class RangeY, class RangeD> __global__ void axmy(A a, RangeX x, RangeY y, RangeD d) { const auto gtid = threadIdx.x + blockIdx.x * blockDim.x; gsl_Expects(x.size() == y.size()); gsl_Expects(y.size() == d.size()); if (gtid < x.size()) { d[gtid] = a * x[gtid] * y[gtid]; } } } // namespace kernel namespace async { template <typename A, class RangeX, class RangeY, class RangeD> void axmy(cuda::stream_t& stream, A a, RangeX&& x, RangeY&& y, RangeD&& d) { gsl_Expects(x.size() == y.size()); gsl_Expects(y.size() == d.size()); constexpr cuda::grid::block_dimension_t block_dim = 256; const cuda::grid::dimension_t grid_dim = (x.size() + block_dim - 1) / block_dim; using RangeXD = typename std::remove_reference<RangeX>::type; using RangeYD = typename std::remove_reference<RangeY>::type; using RangeDD = typename std::remove_reference<RangeD>::type; cuda::enqueue_launch(kernel::axmy<A, RangeXD, RangeYD, RangeDD>, stream, cuda::make_launch_config(grid_dim, block_dim), a, x, y, d); } } // namespace async } // namespace thrustshift
{ "alphanum_fraction": 0.6258351893, "avg_line_length": 27.4897959184, "ext": "h", "hexsha": "34321762a37f48f72a145705cd7e376670e6acef", "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": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_path": "include/thrustshift/axmy.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_path": "include/thrustshift/axmy.h", "max_line_length": 76, "max_stars_count": 1, "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_path": "include/thrustshift/axmy.h", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "num_tokens": 360, "size": 1347 }
#include "allelefreq.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <gsl/gsl_sf_psi.h> #include <gsl/gsl_errno.h> void P_update_simple(const uint8_t* G, const double* zetabeta, const double* zetagamma, const double* xi, const double* beta, const double* gamma, double* var_beta, double* var_gamma, long N, long L, long K) { uint8_t genotype; long idx, n, l, k; double theta_beta_sum, theta_gamma_sum; double *var_beta_tmp, *var_gamma_tmp; var_beta_tmp = (double*) malloc(K * sizeof(double)); var_gamma_tmp = (double*) malloc(K * sizeof(double)); // loop over loci for (l=0; l<L; l++) { for (k=0; k<K; k++) { var_beta_tmp[k] = 0.0; var_gamma_tmp[k] = 0.0; } // loop over samples for (n=0; n<N; n++) { genotype = G[n*L+l]; // missing data do not contribute if (genotype!=3) { // compute xi*zeta_{beta,gamma} theta_beta_sum = 0.0; theta_gamma_sum = 0.0; for (k=0; k<K; k++) { theta_beta_sum += xi[n*K+k] * zetabeta[l*K+k]; theta_gamma_sum += xi[n*K+k] * zetagamma[l*K+k]; } // increment var_{beta,gamma}_tmp for (k=0; k<K; k++) { var_beta_tmp[k] += (double) genotype * xi[n*K+k] / theta_beta_sum; var_gamma_tmp[k] += (double) (2-genotype) * xi[n*K+k] / theta_gamma_sum; } } } // compute var_{beta,gamma} for (k=0; k<K; k++) { idx = l*K+k; var_beta[idx] = beta[idx] + zetabeta[idx] * var_beta_tmp[k]; var_gamma[idx] = gamma[idx] + zetagamma[idx] * var_gamma_tmp[k]; } } free( var_beta_tmp ); free( var_gamma_tmp ); } void P_update_logistic(const double* Dvarbeta, const double* Dvargamma, const double* mu, const double* Lambda, double* var_beta, double* var_gamma, double mintol, long L, long K) { /* `Dvarbeta` and `Dvargamma` are a function of the values of `var_beta` and `var_gamma`. This dependence, however, is explicit on a set of latent populations assignments which in-turn depend on the variational parameters estimated at the previous step. So, the variables `Dvarbeta` and `Dvargamma` do not have to be updated. */ long l, k, idx, numvar, update; long iter = 0; double tol = 10.0; double tmptol; double beta, gamma; double A, pbetagamma, pbeta, pgamma, ppbeta, ppgamma; double A_1, B_1, C_1, A_2, B_2, C_2; /* Iterate until succesive estimates are sufficiently similar or the number of iterations exceeds 1000. */ while (tol>mintol && iter<1000) { numvar = 0; tol = 0.0; // loop over loci for (l=0; l<L; l++) { // only update a locus, if all its variational parameters // satisfy positivity constraints. update = 1; for (k=0; k<K; k++) { if (var_beta[l*K+k]<=0 || var_gamma[l*K+k]<=0) { update = 0; } } if (update==1) { // loop over populations for (k=0; k<K; k++) { idx = l*K+k; // compute pseudo-hyperparameters pbetagamma = gsl_sf_psi_1(var_beta[idx]+var_gamma[idx]); pbeta = gsl_sf_psi_1(var_beta[idx]); pgamma = gsl_sf_psi_1(var_gamma[idx]); ppbeta = gsl_sf_psi_n(2, var_beta[idx]); ppgamma = gsl_sf_psi_n(2, var_gamma[idx]); A_1 = pbeta-pbetagamma; B_1 = -1.*pbetagamma; A_2 = -1.*pbetagamma; B_2 = pgamma-pbetagamma; A = (gsl_sf_psi(var_beta[idx]) - gsl_sf_psi(var_gamma[idx]) - mu[l])*Lambda[k]; C_1 = -1.*A*pbeta - 0.5*Lambda[k]*ppbeta; C_2 = A*pgamma - 0.5*Lambda[k]*ppgamma; beta = (C_1*B_2-C_2*B_1)/(A_1*B_2-A_2*B_1); gamma = (C_1*A_2-C_2*A_1)/(B_1*A_2-B_2*A_1); // compute var_{beta,gamma} tmptol = var_beta[idx]; var_beta[idx] = beta + Dvarbeta[idx]; tol += fabs(var_beta[idx]-tmptol); tmptol = var_gamma[idx]; var_gamma[idx] = gamma + Dvargamma[idx]; tol += fabs(var_gamma[idx]-tmptol); numvar += 1; } } } // compute convergence tolerance tol = 0.5*tol/numvar; iter += 1; } // printf("tol = %.8f, iter = %lu\n",tol,iter); }
{ "alphanum_fraction": 0.5087574696, "avg_line_length": 32.5704697987, "ext": "c", "hexsha": "a1b0847c56a41ace9c91a294dee2b0046c0ea48b", "lang": "C", "max_forks_count": 45, "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:12:31.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-20T18:26:32.000Z", "max_forks_repo_head_hexsha": "98f85880562e2c4f4aacb4c8304d0e1aed551985", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gadgrandez/fastStructure", "max_forks_repo_path": "vars/C_allelefreq.c", "max_issues_count": 47, "max_issues_repo_head_hexsha": "98f85880562e2c4f4aacb4c8304d0e1aed551985", "max_issues_repo_issues_event_max_datetime": "2022-03-03T11:11:39.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T11:18:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gadgrandez/fastStructure", "max_issues_repo_path": "vars/C_allelefreq.c", "max_line_length": 207, "max_stars_count": 92, "max_stars_repo_head_hexsha": "98f85880562e2c4f4aacb4c8304d0e1aed551985", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gadgrandez/fastStructure", "max_stars_repo_path": "vars/C_allelefreq.c", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-16T20:05:46.000Z", "num_tokens": 1345, "size": 4853 }
/* simulate NMR peakshape for two-site chemical exchange written by Sung-Hun Bae Nov. 17, 2008 */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <complex> #include <gsl/gsl_fft_complex.h> #define TINY 1.0e-12 using namespace std; enum SITE_LABEL { A, B, N_SITE }; enum QUADRATURE { REAL, IMAG }; typedef struct { double Omegaa;// frequency of A site (rad/s) double Omegab;// frequency of B site (rad/s) double kab; // reaction rate constant, A -> B (1/s) double kba; // reaction rate constant, B -> A (1/s) double R20a; // transverse relaxation rate of A site (1/s) double R20b; // transverse relaxation rate of B site (1/s) double M0a; // initial magnetization double M0b; // initial magnetization SITE_LABEL site; // A or B QUADRATURE quad; // REAL or IMAG } two_site_exchange; // // Magnetization (two-site exchange) // void N (double t, double &R, double &I, void * params) { two_site_exchange * x = (two_site_exchange *) params; complex<double> c1,c2,c3,lp,lm,a11,a12,a21,a22; complex<double> Omegaa = sqrt(complex<double>(-1.))*x->Omegaa; complex<double> Omegab = sqrt(complex<double>(-1.))*x->Omegab; double mag; c1 = (-Omegaa - Omegab + x->R20a + x->R20b + x->kab + x->kba); c2 = (-Omegaa + Omegab + x->R20a - x->R20b + x->kab - x->kba); c3 = sqrt(c2*c2+4.*x->kab*x->kba); lp = 0.5*(c1+c3); lm = 0.5*(c1-c3); if (x->site == A) { a11 = 0.5*((1.-c2/c3)*exp(-t*lm)+(1.+c2/c3)*exp(-t*lp)); a12 = x->kba/c3*(exp(-t*lm)-exp(-t*lp)); R += real(a11*x->M0a+a12*x->M0b); I += imag(a11*x->M0a+a12*x->M0b); } if (x->site == B) { a22 = 0.5*((1.+c2/c3)*exp(-t*lm)+(1.-c2/c3)*exp(-t*lp)); a21 = x->kab/c3*(exp(-t*lm)-exp(-t*lp)); R += real(a21*x->M0a+a22*x->M0b); I += imag(a21*x->M0a+a22*x->M0b); } } int main (int argc, char *argv[]) { if (argc < 7 || argc > 17) { printf("\t\t\t\t\t\t\tSung-Hun Bae 2008.11\n"); printf(" "); printf("Usage: xpshape [-model AB|ACB]\n"); printf(" "); printf(" [-dw #(Hz)] [-kab #(1/s)] [-kba #(1/s)]\n"); printf(" "); printf(" [-R20a #(1/s)] [-R20b #(1/s)]\n"); printf(" "); printf(" [-a0 conc(M)] [-c0 conc(M)]\n"); printf(" "); printf(" [-swh Hz(600)] [-fid pts(8192)]\n\n"); printf(" "); printf("simulate NMR peakshape for two-site chemical exchange\n\n"); printf(" "); printf("-model,AB : A = B (dw,kab,kba,R20a,R20b required)\n"); printf(" "); printf(" ACB : A + C = B (dw,kab,kba,R20a,R20b,a0,c0 required)\n"); printf("\n"); printf(" "); printf("-dw, (A.frequency= -dw/2, B.frequency= +dw/2)\n"); printf(" "); printf("-R20a,(exchange-free R2 of A state)\n"); printf(" "); printf("-R20b,(exchange-free R2 of B state)\n"); printf(" "); printf("-kab, (rate constant of A->B)\n"); printf(" "); printf("-kba, (rate constant of B->A)\n"); printf(" "); printf("-a0, (initial concentration of A)\n"); printf(" "); printf("-c0, (initial concentration of C)\n"); printf(" "); printf("-swh, (spectrum = -swh/2 ... +swh/2)\n"); printf(" "); printf("-fid, (must be ...,1024,2048,4096,8192,16384,32768,65536,..)\n"); printf("\n"); exit (1); } // default settings double SWH = 600; // (Hz) unsigned int FID_SIZE = 8192; // (complex data points) // receiving parameters unsigned int i = 1; string model; double dw,R20a,R20b,kab,kba,concA0,concC0; bool dw_,R20a_,R20b_,kab_,kba_,concA0_,concC0_; double pb,Kd,concA,concB,concC,C,u,v; dw_ = R20a_ = R20b_ = kab_ = kba_ = concA0_ = concC0_ = false; while ((argc - i) > 0) { if ((argc-i) > 0 && !strcmp(argv[i],"-model")) { model = string(argv[++i]); i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-dw")) { dw = 2.*M_PI*atof(argv[++i]); // (Hz) -> (rad/s) dw_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-kab")) { kab = atof(argv[++i]); kab_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-kba")) { kba = atof(argv[++i]); kba_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-R20a")) { R20a = atof(argv[++i]); R20a_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-R20b")) { R20b = atof(argv[++i]); R20b_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-a0")) { concA0 = atof(argv[++i]); concA0_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-c0")) { concC0 = atof(argv[++i]); concC0_ = true; i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-swh")) { SWH = atof(argv[++i]); i++; } if ((argc-i) > 0 && !strcmp(argv[i],"-fid")) { FID_SIZE = atoi(argv[++i]); i++; } } double fid[2*FID_SIZE]; // complex points double dwell = 1./(SWH); // (sec) double norm = 1./sqrt(FID_SIZE); // scaling factor if (model == "AB" && dw_ && R20a_ && R20b_ && kab_ && kba_) { // dw, R20a, R20b, kab, kba Kd = kba/kab; pb = 1./(1.+Kd); C = 1.0; } else if (model == "ACB" && dw_ && R20a_ && R20b_ && kab_ && kba_ && concA0_ && concC0_) { // dw, R20a, R20b, kab(=kon), kba(=koff), concA0, concC0 kab = (concC0 > TINY ? kab : 0.0); kba = (concC0 > TINY ? kba : 0.0); Kd = ((kab > TINY) && (kba > TINY) ? kba/kab : 0.0); u = 0.5*(concA0+concC0+Kd); v = (concC0 > TINY ? (u-sqrt(u*u-concA0*concC0)) : 0.0); concA = (v > TINY ? concA0-v : concA0); concB = (v > TINY ? v : 0.0); concC = (v > TINY ? concC0 - v : concC0); pb = (concC0 > TINY ? kab*concC/(kab*concC+kba) : 0.0); C = concC; } else { printf("error: missing parameter(s)\n"); exit(1); } two_site_exchange x = {-dw/2.,dw/2.,kab*C,kba,R20a,R20b,(1.-pb),pb,A,REAL}; // header information printf("# peak shape simulation "); if (model == "AB") printf("[A = B]\n"); if (model == "ACB") printf("[A + C = B]\n"); printf("# dw = %g (rad/s)\n", dw); printf("# kab = %g (1/s)\n",kab); printf("# kba = %g (1/s)\n",kba); printf("# R20a = %g (1/s)\n",R20a); printf("# R20b = %g (1/s)\n",R20b); if (model == "AB") { printf("# pb = %g\n", pb); } if (model == "ACB") { printf("# kon = %g (1/s)\n",kab); printf("# koff = %g (1/s)\n",kba); printf("# Kd = %g (M)\n",Kd); printf("# pb = %g\n",pb); printf("# [A]ini = %g (M)\n",concA0); printf("# [C]ini = %g (M)\n",concC0); printf("# [A] = %g (M)\n",concA); printf("# [C] = %g (M)\n",concC); printf("# [B] = %g (M)\n",concB); } printf("# FID = %d (complex points)\n",FID_SIZE); printf("# SWH = %g (Hz)\n",SWH); printf("# X-axis unit: (Hz)\n"); // creating complex data points for (i = 0; i < FID_SIZE; i++) { fid[2*i] = fid[2*i+1] = 0.0; x.site = A; N (i*dwell, fid[2*i], fid[2*i+1], &x); // A x.site = B; N (i*dwell, fid[2*i], fid[2*i+1], &x); // B } // Fast Fourier Transform (FFT) gsl_fft_complex_radix2_forward (fid, 1, FID_SIZE); // spectrum for (i = FID_SIZE/2; i < FID_SIZE; i++) printf("%g %g\n",(-0.5*SWH + SWH*(i-FID_SIZE/2)/FID_SIZE),norm*fid[2*i]); for (i = 0; i <= FID_SIZE/2; i++) printf("%g %g\n",(-0.5*SWH + SWH*(i+FID_SIZE/2)/FID_SIZE),norm*fid[2*i]); printf("&\n"); return 0; } /* For physical applications it is important to remember that the index appearing in the DFT does not correspond directly to a physical frequency. If the time-step of the DFT is \Delta then the frequency-domain includes both positive and negative frequencies, ranging from -1/(2\Delta) through 0 to +1/(2\Delta). The positive frequencies are stored from the beginning of the array up to the middle, and the negative frequencies are stored backwards from the end of the array. index z x = FFT(z) 0 z(t = 0) x(f = 0) 1 z(t = 1) x(f = 1/(N Delta)) 2 z(t = 2) x(f = 2/(N Delta)) . ........ .................. N/2 z(t = N/2) x(f = +1/(2 Delta), -1/(2 Delta)) . ........ .................. N-3 z(t = N-3) x(f = -3/(N Delta)) N-2 z(t = N-2) x(f = -2/(N Delta)) N-1 z(t = N-1) x(f = -1/(N Delta)) */
{ "alphanum_fraction": 0.4996500233, "avg_line_length": 30.2897526502, "ext": "c", "hexsha": "f4a10e7a572f01f42096669e5267b77501ec423f", "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": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sunghunbae/xpshape", "max_forks_repo_path": "source/xpshape.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "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": "sunghunbae/xpshape", "max_issues_repo_path": "source/xpshape.c", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "b84dc8e190e2c0fb80a780c60ad1a2ff0e036da2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sunghunbae/xpshape", "max_stars_repo_path": "source/xpshape.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3206, "size": 8572 }
#pragma once #include "poll_event.h" #include "poll_response.h" #include "poll_target.h" #include <gsl/span> #include <optional> #include <vector> namespace wrappers::zmq { [[nodiscard]] std::optional<std::vector<poll_response>> blocking_poll(gsl::span<poll_target> targets) noexcept; } // namespace wrappers::zmq
{ "alphanum_fraction": 0.74375, "avg_line_length": 17.7777777778, "ext": "h", "hexsha": "25e035d3f8dd80cdfc1647d2dcf20a809620f201", "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": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Longhanks/linkollector-win", "max_forks_repo_path": "src/wrappers/zmq/poll.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "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": "Longhanks/linkollector-win", "max_issues_repo_path": "src/wrappers/zmq/poll.h", "max_line_length": 55, "max_stars_count": null, "max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Longhanks/linkollector-win", "max_stars_repo_path": "src/wrappers/zmq/poll.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 76, "size": 320 }
/* specfunc/zeta.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* This file was taken from the GNU Scientific Library. Some modifications * were done in order to make it independent from the rest of GSL */ /* #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_elementary.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_zeta.h> #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" */ #include <math.h> #include <stdio.h> #include "error.h" /*-*-*-*-*-*-*-*-*-*- From gsl_machine.h -*-*-*-*-*-*-*-*-*-*-*-*-*/ #define GSL_LOG_DBL_MIN (-7.0839641853226408e+02) #define GSL_LOG_DBL_MAX 7.0978271289338397e+02 #define GSL_DBL_EPSILON 2.2204460492503131e-16 /*-*-*-*-*-*-*-*-*-* From gsl_sf_result.h *-*-*-*-*-*-*-*-*-*-*-*/ struct gsl_sf_result_struct { double val; double err; }; typedef struct gsl_sf_result_struct gsl_sf_result; /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* coefficients for Maclaurin summation in hzeta() * B_{2j}/(2j)! */ static double hzeta_c[15] = { 1.00000000000000000000000000000, 0.083333333333333333333333333333, -0.00138888888888888888888888888889, 0.000033068783068783068783068783069, -8.2671957671957671957671957672e-07, 2.0876756987868098979210090321e-08, -5.2841901386874931848476822022e-10, 1.3382536530684678832826980975e-11, -3.3896802963225828668301953912e-13, 8.5860620562778445641359054504e-15, -2.1748686985580618730415164239e-16, 5.5090028283602295152026526089e-18, -1.3954464685812523340707686264e-19, 3.5347070396294674716932299778e-21, -8.9535174270375468504026113181e-23 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ static int gsl_sf_hzeta_e(const double s, const double q, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(s <= 1.0 || q <= 0.0) { PLFIT_ERROR("s must be larger than 1.0 and q must be larger than zero", PLFIT_EINVAL); } else { const double max_bits = 54.0; const double ln_term0 = -s * log(q); if(ln_term0 < GSL_LOG_DBL_MIN + 1.0) { PLFIT_ERROR("underflow", PLFIT_UNDRFLOW); } else if(ln_term0 > GSL_LOG_DBL_MAX - 1.0) { PLFIT_ERROR("overflow", PLFIT_OVERFLOW); } else if((s > max_bits && q < 1.0) || (s > 0.5*max_bits && q < 0.25)) { result->val = pow(q, -s); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return PLFIT_SUCCESS; } else if(s > 0.5*max_bits && q < 1.0) { const double p1 = pow(q, -s); const double p2 = pow(q/(1.0+q), s); const double p3 = pow(q/(2.0+q), s); result->val = p1 * (1.0 + p2 + p3); result->err = GSL_DBL_EPSILON * (0.5*s + 2.0) * fabs(result->val); return PLFIT_SUCCESS; } else { /* Euler-Maclaurin summation formula * [Moshier, p. 400, with several typo corrections] */ const int jmax = 12; const int kmax = 10; int j, k; const double pmax = pow(kmax + q, -s); double scp = s; double pcp = pmax / (kmax + q); double ans = pmax*((kmax+q)/(s-1.0) + 0.5); for(k=0; k<kmax; k++) { ans += pow(k + q, -s); } for(j=0; j<=jmax; j++) { double delta = hzeta_c[j+1] * scp * pcp; ans += delta; if(fabs(delta/ans) < 0.5*GSL_DBL_EPSILON) break; scp *= (s+2*j+1)*(s+2*j+2); pcp /= (kmax + q)*(kmax + q); } result->val = ans; result->err = 2.0 * (jmax + 1.0) * GSL_DBL_EPSILON * fabs(ans); return PLFIT_SUCCESS; } } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ double gsl_sf_hzeta(const double s, const double a) { gsl_sf_result result; gsl_sf_hzeta_e(s, a, &result); return result.val; }
{ "alphanum_fraction": 0.6306325823, "avg_line_length": 29.7806451613, "ext": "c", "hexsha": "c0bf6a451081675797c8abd610ff5c21a6bddb45", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-03-05T06:24:02.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-05T06:24:02.000Z", "max_forks_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jmazon/haskell-igraph", "max_forks_repo_path": "igraph/src/zeta.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "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": "jmazon/haskell-igraph", "max_issues_repo_path": "igraph/src/zeta.c", "max_line_length": 87, "max_stars_count": 4, "max_stars_repo_head_hexsha": "c000ec7939e73d4f563a85751aaeb973bfda7d40", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jmazon/haskell-igraph", "max_stars_repo_path": "igraph/src/zeta.c", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "num_tokens": 1560, "size": 4616 }
/** * The driver function and some auxillaries * to compute the spectrum from an image and * information on the location and distortion of the spectra. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <limits.h> #include <gsl/gsl_roots.h> #include <gsl/gsl_vector.h> #include "aXe_grism.h" #include "aXe_utils.h" #include "spce_sect.h" #include "spce_is_in.h" #include "spce_pathlength.h" #define DEBUG_ME 0x10 /** fill in the path length field (xi in ap_pixel) from the abscissas (xs in ap_pixel) (helper function for spc_extract). @param func the spectrum trace to use for the transformation from xs to xi @param table a pointer to the table of aperture pixels, terminated with x=-1 */ static int transform_to_pathlen (const trace_func * const func, ap_pixel * const table) { int i, len; ap_pixel *cur_p = table; gsl_vector *section_points; while (cur_p->p_x != -1) cur_p++; len = cur_p - table; if (len==0) return -1; // exit now if the table is empty section_points = gsl_vector_alloc (len); for (i = 0; i < len; i++) { gsl_vector_set (section_points, i, table[i].xs); } if (abscissa_to_pathlength (func, section_points)) { gsl_vector_free (section_points); return -1; } for (i = 0; i < len; i++) { table[i].xi = gsl_vector_get (section_points, i); } gsl_vector_free (section_points); return 0; } /** creates an ap_pixel. @param x x coordinate of pixel relative to beam's reference point @param y y coordinate of pixel relative to beam's reference point @param px absolute x coordinate of the pixel @param py absolute y coordinate of the pixel @param ob the observation to get the pixels from @param sf pointer to sectionfun structure for this beam @param cur_ap a pointer to the next free aperture pixel @return a pointer to the next free aperture pixel after the new pixels have been added. */ static ap_pixel * handle_one_pixel (const double x, const double y, const int px, const int py, const observation * const obs, sectionfun * const sf, const trace_func * const tracefun, ap_pixel * cur_ap) { double res; double sect_y; double tmp; double phi_trace; if (find_section_point (sf, x, y, &res)) { return cur_ap; /* FIXME: Issue warning here */ } /* set the extraction weight to 1. */ cur_ap->weight = 1.; cur_ap->xs = res; phi_trace = atan (tracefun->deriv (cur_ap->xs, tracefun->data)); cur_ap->dxs = phi_trace; cur_ap->ys = tracefun->func (cur_ap->xs, tracefun->data); sect_y = tracefun->func (res, tracefun->data); tmp = tracefun->func (x, tracefun->data); cur_ap->contam = -1.0; cur_ap->model = 0.0; cur_ap->p_x = px; cur_ap->p_y = py; cur_ap->x = x; cur_ap->y = y; cur_ap->dist = sqrt ((sect_y - y) * (sect_y - y) + (cur_ap->xs - x) * (cur_ap->xs - x)); if ( y < tmp ) { cur_ap->dist = cur_ap->dist * (-1.); /* If pixel is bwlow the trace, dist is neg. */ } cur_ap->count = gsl_matrix_get (obs->grism, px, py); cur_ap->error = gsl_matrix_get (obs->pixerrs, px, py); if (obs->dq != NULL) cur_ap->dq = (long) gsl_matrix_get (obs->dq, px, py); else cur_ap->dq = 0; cur_ap++; return cur_ap; } /** Does some sanity checks on make_spc_table's input. @param ob the object to check @return 0 if everything is ok, -1 otherwise */ static int sanitycheck (object * const ob) { int i; for (i = 0; i < ob->nbeams; i++) { while (ob->beams[i].orient < 0) { ob->beams[i].orient += M_PI; } while (ob->beams[i].orient > M_PI) { ob->beams[i].orient -= M_PI; } } return 0; } #define MIN(x,y) (((x)<(y))?(x):(y)) #define MAX(x,y) (((x)>(y))?(x):(y)) /** computes a table of aperture pixels, i.e. of tuples containing the source coordinates, the distance to the spectrum trace, the path length along the trace, and the intensity. The end of the table is marked with an ap_pixel->x==-1. This routine can do subsampling, whereby each pixel is divided into n_sub*n_sub smaller pixels. If n_sub==1, a special (faster) handling is enabled. @param ob the object struct to examine @param beamorder the order of the spectrum to examine @param flags warning flags like in the warning field of the spectrum structure. This has to be passed in initialized. */ ap_pixel * make_spc_table (object * const ob, const int beamorder, int *const flags) { int bb_x, bb_y, bb_w, bb_h; int x, y; beam *curbeam = ob->beams + beamorder; double dx, dy; ap_pixel *table, *cur_ap; is_in_descriptor iid; sectionfun sf; trace_func *tracefun = curbeam->spec_trace; quad_to_bbox (curbeam->corners, curbeam->bbox, curbeam->bbox + 1); bb_x = curbeam->bbox[0].x; bb_y = curbeam->bbox[0].y; bb_w = curbeam->bbox[1].x - curbeam->bbox[0].x + 1; bb_h = curbeam->bbox[1].y - curbeam->bbox[0].y + 1; if (sanitycheck (ob)) { aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Input data failed sanity check"); return NULL; } if (fill_is_in_descriptor (&iid, curbeam->corners)) return NULL; if (fill_in_sectionfun (&sf, curbeam->orient, curbeam)) return NULL; if (!(table = malloc ((bb_w * bb_h + 1) * sizeof (ap_pixel)))) return NULL; /* We have a little coordinate confusion here. There are three systems: (a) the absolute one, rooted in (0,0) of the image. (b) the relative one, rooted in the reference point and used when evaluating the spectrum trace. This one is used for finding the section points, etc. (c) one relative to the bounding box; x and y below live in this system and have to be converted into whatever system is required. dx, dy are used for the conversion to (b) */ dx = bb_x - curbeam->refpoint.x; dy = bb_y - curbeam->refpoint.y; cur_ap = table; for (y = 0; y <= bb_h; y++) { for (x = 0; x < bb_w; x++) { if ((bb_x + x < 0) || (bb_y + y < 0) || (bb_x + x >= (int)ob->grism_obs->grism->size1) || (bb_y + y >= (int)ob->grism_obs->grism->size2)) { *flags |= SPC_W_BORDER; continue; } // check whether the trace description has // an order higher than linear if (curbeam->spec_trace->type > 1) { // new criteria based on the true trace distance // which means the true distance from the section point if (!tracedist_criteria(x + dx, y + dy, &sf, tracefun, curbeam->width+2.0)) { continue; } } else { // old criteria based on the box model if (!is_in (bb_x + x, bb_y + y, &iid)) { continue; } } if (isnan (gsl_matrix_get (ob->grism_obs->grism, bb_x + x, bb_y + y))) { continue; } // if (ob->ID == 11 && x + bb_x == 59) // fprintf(stdout, "xx: %i, yy: %i: %i\n", x + bb_x, y + bb_y, is_in (x + bb_x, y + bb_y, &iid)); cur_ap = handle_one_pixel (x + dx, y + dy, x + bb_x, y + bb_y, ob->grism_obs, &sf, tracefun, cur_ap); } } cur_ap->p_x = -1; cur_ap->p_y = -1; cur_ap->count = -1; free_sectionfun (&sf); if (transform_to_pathlen (curbeam->spec_trace, table)) { // free (table); // table = NULL; // return NULL; } return table; } /** Similar to make_spc_table, it just works only on one spot given in the parameters. */ ap_pixel * make_gps_table (object * const ob, const int beamorder, int *const flags, int xval, int yval) { int bb_x, bb_y, bb_w, bb_h; int x, y; beam *curbeam = ob->beams + beamorder; double dx, dy; ap_pixel *table, *cur_ap; is_in_descriptor iid; sectionfun sf; trace_func *tracefun = curbeam->spec_trace; quad_to_bbox (curbeam->corners, curbeam->bbox, curbeam->bbox + 1); bb_x = curbeam->bbox[0].x; bb_y = curbeam->bbox[0].y; bb_w = curbeam->bbox[1].x - curbeam->bbox[0].x + 1; bb_h = curbeam->bbox[1].y - curbeam->bbox[0].y + 1; if (sanitycheck (ob)) { aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Input data failed sanity check"); return NULL; } if (fill_is_in_descriptor (&iid, curbeam->corners)) return NULL; if (fill_in_sectionfun (&sf, curbeam->orient, curbeam)) return NULL; if (! (table = malloc (2 * sizeof (ap_pixel)))) return NULL; /* We have a little coordinate confusion here. There are three systems: (a) the absolute one, rooted in (0,0) of the image. (b) the relative one, rooted in the reference point and used when evaluating the spectrum trace. This one is used for finding the section points, etc. (c) one relative to the bounding box; x and y below live in this system and have to be converted into whatever system is required. dx, dy are used for the conversion to (b) */ dx = bb_x - curbeam->refpoint.x; dy = bb_y - curbeam->refpoint.y; x = xval - bb_x; y = yval - bb_y; cur_ap = table; cur_ap = handle_one_pixel (x + dx, y + dy, x + bb_x, y + bb_y, ob->grism_obs, &sf, tracefun, cur_ap); cur_ap->p_x = -1; cur_ap->p_y = -1; cur_ap->count = -1; free_sectionfun (&sf); transform_to_pathlen (curbeam->spec_trace, table); return table; } void print_ap_pixel_table (const ap_pixel * ap_p) { printf ("# x y pathlen distance lambda count error\n"); while (ap_p->p_x != -1) { printf ("%d %d %f %f %f %f %f %f %f %ld\n", ap_p->p_x, ap_p->p_y, ap_p->x, ap_p->y, ap_p->xi, ap_p->dist, ap_p->lambda, ap_p->count, ap_p->error, ap_p->dq); ap_p++; } } /* int tracedist_criteria(const double x, const double y, sectionfun * const sf, const trace_func *tracefun, const double width) { double x_sect, y_sect; double dist, max_dist; int ireturn=0; find_section_point (sf, x, y, &x_sect); y_sect = tracefun->func (x_sect, tracefun->data); dist = sqrt((y_sect-y)*(y_sect-y)+(x_sect-x)*(x_sect-x)); if (dist < width) ireturn=1; return ireturn; } */
{ "alphanum_fraction": 0.6284636012, "avg_line_length": 25.4267676768, "ext": "c", "hexsha": "acb73275af737a8699e607e4390fee8b54bb7742", "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/spc_extract.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spc_extract.c", "max_line_length": 106, "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/spc_extract.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3135, "size": 10069 }
#ifndef INITIAL_POINT_H #define INITIAL_POINT_H #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> int pdip_initial_point_feasible_x( const gsl_matrix * A, const gsl_vector *b, gsl_vector *x ); int pdip_initial_point_feasible_s( const gsl_matrix * C, const gsl_vector *d, const gsl_vector *x, gsl_vector *s ); int pdip_initial_point_y( const gsl_matrix *Q, const gsl_vector *q, const gsl_matrix *A, const gsl_vector *x, gsl_vector *y ); int pdip_initial_point_z( gsl_vector *z ); int pdip_initial_point_strict_feasible( gsl_vector *x, gsl_vector *s ); #endif
{ "alphanum_fraction": 0.7834179357, "avg_line_length": 39.4, "ext": "h", "hexsha": "d73928458c27a25c24dd6e38de4a2863c99960d3", "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": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_path": "src/cqp/initial_point.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "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": "wmotte/toolkid", "max_issues_repo_path": "src/cqp/initial_point.h", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_path": "src/cqp/initial_point.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 170, "size": 591 }
#include "common.h" #include "dMatrix.h" #include "options.h" #include "linefile.h" #include <gsl/gsl_math.h> #include <gsl/gsl_statistics_double.h> struct rnaBinder /* Name and correlation of rna binding proteins. */ { struct rnaBinder *next; /* Next in list. */ char *psName; /* Name of probe set. Something like * E@NM_XXXXXX_a_at or GXXXXXXX_a_at.*/ char *geneName; /* Name of gene probed by probe * set. Hopefully something readable. */ char *pfamAcc; /* Name of pfam accession. */ char *pfamName; /* Name of pfam domain. */ double corr; /* Correlation between rnaBinder and cluster of interest. */ }; struct clusterMember /* Member of the cluster of interest. */ { struct clusterMember *next; /* Next in list. */ char *geneId; /* Gene id in cluster. */ char *psName; /* Name of the probe set. */ char *desc; /* Description of the probe set. */ }; static struct optionSpec optionSpecs[] = /* Our acceptable options to be called with. */ { {"help", OPTION_BOOLEAN}, {"sjIndexFile", OPTION_STRING}, {"psFile", OPTION_STRING}, {"clusterFile", OPTION_STRING}, {"rnaBindingFile", OPTION_STRING}, {"outputFile", OPTION_STRING}, {"antiCorrelation", OPTION_BOOLEAN}, {NULL, 0} }; static char *optionDescripts[] = /* Description of our options for usage summary. */ { "Display this messge.", "File with splice junction indexes.", "File with probe set intensities.", "File with probe sets in cluster of interest.", "File with rna binding gene sets.", "File to output correlation results to.", "Sort by anti-correlation rather than correlation." }; void usage() /* Print usage and quit. */ { int i=0; warn("rnaBindingClusterCorr - Program to calculate the correlation\n" "between rna binding protein expression data and splice junctions\n" "co-regulated as determined by clustering splice junction indexes.\n" "options are:"); for(i=0; i<ArraySize(optionSpecs) -1; i++) fprintf(stderr, " -%s -- %s\n", optionSpecs[i].name, optionDescripts[i]); errAbort("\nusage:\n" " rnaBindingClusterCorr -sjIndexFile=input/sjIndexTest.tab -psFile=input/psIntenTest.tab \\ \n" " -clusterFile=input/clusterTest.tab -rnaBindingFile=input/rnaBinderTest.tab \\ \n" " -outputFile=output/test.out.tab\n"); } double correlation(double *X, double *Y, int count) /* Compute the correlation between X and Y correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y)) page 332 Sheldon Ross "A First Course in Probability" 1998 */ { double varX = gsl_stats_variance(X, 1, count); double varY = gsl_stats_variance(Y, 1, count); double covXY = gsl_stats_covariance(X, 1, Y, 1, count); double correlation = covXY / sqrt(varX *varY); return correlation; } double calcDistanceFromCluster(struct rnaBinder *rb, struct clusterMember *cmList, struct dMatrix *sjIndex, struct dMatrix *psInten) /* Calculate the distance from the rnaBinder intensity measurement to the sjIndexes of the cluster members. If no intensity present use 0 as it will fall in the middle of [-1,1]. */ { double sum = 0; int count = 0; int sjIx = 0, gsIx = 0; struct clusterMember *cm = NULL; double corr = 0; if(sjIndex->colCount != psInten->colCount) errAbort("Splice Junction and Intensity files must have same number of columns."); /* Get the index of the gene set in the intensity file. */ gsIx = hashIntValDefault(psInten->nameIndex, rb->psName, -1); if(gsIx == -1) { /* warn("Probe Set %s not found in intensitiy file."); */ return 0; } for(cm = cmList; cm != NULL; cm = cm->next) { /* For each member get the index in the splice junction file. */ sjIx = hashIntValDefault(sjIndex->nameIndex, cm->psName, -1); if(sjIx == -1) errAbort("Probe Set %s not found in SJ index file."); corr = correlation(psInten->matrix[gsIx], sjIndex->matrix[sjIx], sjIndex->colCount); sum += corr; count++; } if(count == 0) errAbort("No junctions in cluster."); sum = sum / (double) count; return sum; } int rnaBinderCmp(const void *va, const void *vb) /* Compare to sort based correlation. */ { const struct rnaBinder *a = *((struct rnaBinder **)va); const struct rnaBinder *b = *((struct rnaBinder **)vb); return a->corr < b->corr; } struct rnaBinder *loadRnaBinders() /* Load the probe sets that encode genes thought to bind rnas. Expected order is probeSet, geneName, pfamAcc, pfamName */ { struct rnaBinder *rbList = NULL, *rb = NULL; char *words[4]; struct lineFile *lf = NULL; char *inputFile = optionVal("rnaBindingFile", NULL); assert(inputFile); lf = lineFileOpen(inputFile, TRUE); while(lineFileChopCharNext(lf, '\t', words, ArraySize(words))) { AllocVar(rb); rb->psName = cloneString(words[0]); rb->geneName = cloneString(words[1]); rb->pfamAcc = cloneString(words[2]); rb->pfamName = cloneString(words[3]); slAddHead(&rbList, rb); } lineFileClose(&lf); slReverse(&rbList); return rbList; } struct clusterMember *loadClusterMembers() /* Load the probe sets that are in our cluster of interest. */ { struct clusterMember *cmList = NULL, *cm = NULL; char *words[3]; struct lineFile *lf = NULL; char *inputFile = optionVal("clusterFile", NULL); int wordCount = 0; assert(inputFile); lf = lineFileOpen(inputFile, TRUE); while((wordCount = lineFileChopCharNext(lf, '\t', words, ArraySize(words))) != 0) { AllocVar(cm); if(wordCount == 3) { cm->geneId = cloneString(words[0]); cm->psName = cloneString(words[1]); cm->desc = cloneString(words[2]); } else if(wordCount == 2) { cm->psName = cloneString(words[0]); cm->desc = cloneString(words[1]); } else errAbort("Got %d words at line %d", wordCount, lf->lineIx); slAddHead(&cmList, cm); } lineFileClose(&lf); slReverse(&cmList); return cmList; } void reportRnaBinders(struct rnaBinder *rbList) /* Report the rnaBinder distances. */ { struct rnaBinder *rb = NULL; char *fileName = optionVal("outputFile", NULL); FILE *out = NULL; if(fileName == NULL) errAbort("Must specify an outputFile"); out = mustOpen(fileName, "w"); for(rb = rbList; rb != NULL; rb = rb->next) { fprintf(out, "%s\t%s\t%s\t%s\t%.4f\n", rb->psName, rb->geneName, rb->pfamAcc, rb->pfamName, rb->corr); } carefulClose(&out); } void rnaBindingClusterCorr() /* Top level function to calculate correlations. */ { char *sjIndexFile = optionVal("sjIndexFile", NULL); char *psFile = optionVal("psFile", NULL); struct dMatrix *sjIndex = NULL, *psInten = NULL; struct rnaBinder *rbList = NULL, *rb = NULL; struct clusterMember *cmList = NULL, *cm = NULL; warn("Loading Files."); sjIndex = dMatrixLoad(sjIndexFile); psInten = dMatrixLoad(psFile); rbList = loadRnaBinders(); cmList = loadClusterMembers(); warn("Calculating Distance."); /* Calculate distance. */ for(rb = rbList; rb != NULL; rb = rb->next) rb->corr = calcDistanceFromCluster(rb, cmList, sjIndex, psInten); /* Sort by distance (correlati2n) */ slSort(&rbList, rnaBinderCmp); /* If we want anti-correlation reverse. */ if(optionExists("antiCorrelation")) slReverse(&rbList); warn("Writing out results."); /* Do some outputting. */ reportRnaBinders(rbList); /* Cleanup. */ dMatrixFree(&sjIndex); dMatrixFree(&psInten); warn("Done."); } int main(int argc, char *argv[]) { if(argc == 1) usage(); optionInit(&argc, argv, optionSpecs); if(optionExists("help")) usage(); rnaBindingClusterCorr(); return 0; }
{ "alphanum_fraction": 0.6699247127, "avg_line_length": 29.6901960784, "ext": "c", "hexsha": "3218abce5bd7a80380981fba818f2146e7e46431", "lang": "C", "max_forks_count": 80, "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z", "max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z", "max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andypohl/kent", "max_forks_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_issues_count": 60, "max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andypohl/kent", "max_issues_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_line_length": 99, "max_stars_count": 171, "max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andypohl/kent", "max_stars_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z", "num_tokens": 2106, "size": 7571 }
#ifndef _linalg_h_included_ #define _linalg_h_included_ #include <boost/config.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/operation.hpp> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include <jsc/util/log.hpp> extern "C" { extern void dgetrf_(int *,int *,double *,int *,double *,int *); extern void dgetri_(int *,double *,int *,double *,double *,int *,int *); extern void dpotrf_(char *,int *,double *,int *,int *); extern void dpotri_(char *,int *,double *,int *,int *); }; using namespace boost; using namespace boost::numeric; using namespace jsc::util; class linalg { public: static void invert_matrix(const ublas::matrix<double> & A, ublas::matrix<double> & inv) { invert_matrix_gsl_lu(A, inv); // invert_matrix_lapack_lu(A, inv); // invert_matrix_lapack_cholesky(A, inv); unsigned long K = A.size1() + 1; ublas::matrix<double> rst(K-1, K-1); ublas::matrix<double> ident = ublas::identity_matrix<double>(K-1); axpy_prod(A, inv, rst); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { if (abs(rst(p,q) - ident(p,q)) > 1E-5) { L_(debug) << "A*(invA)[" << p << "," << q << "] = " << rst(p,q); } } } } private: static void invert_matrix_gsl_lu(const ublas::matrix<double> & A, ublas::matrix<double> & inv) { unsigned long K = A.size1() + 1; gsl_matrix* m = gsl_matrix_alloc(K - 1, K - 1); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { gsl_matrix_set(m, p, q, A(p,q)); } } gsl_matrix* inverse = gsl_matrix_alloc(K - 1, K - 1); gsl_permutation*perm = gsl_permutation_alloc(K-1); int s=0; gsl_linalg_LU_decomp(m, perm, &s); gsl_linalg_LU_invert(m, perm, inverse); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { inv(p,q) = gsl_matrix_get(inverse, p, q); } } gsl_permutation_free(perm); gsl_matrix_free(inverse); gsl_matrix_free(m); } static void invert_matrix_lapack_lu(const ublas::matrix<double> & A, ublas::matrix<double> & inv) { unsigned long K = A.size1() + 1; double * m = (double *)malloc((K - 1)*(K - 1)*sizeof(double)); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { m[p + q*(K-1)] = A(p,q); } } double * ipiv = (double *)malloc((K - 1)*sizeof(double)); int N = K - 1; int lda = N; int info; dgetrf_(&N, &N, &m[0], &lda, &ipiv[0], &info); assert(info == 0); double * work = (double *)malloc((K - 1)*sizeof(double)); int lwork = N; dgetri_(&N, &m[0], &lda, &ipiv[0], &work[0], &lwork, &info); assert(info == 0); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { inv(p,q) = m[p + q*(K-1)]; } } free(m); free(ipiv); free(work); } static void invert_matrix_lapack_cholesky(const ublas::matrix<double> & A, ublas::matrix<double> & inv) { unsigned long K = A.size1() + 1; double * m = (double *)malloc((K - 1)*(K - 1)*sizeof(double)); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { m[p + q*(K-1)] = A(p,q); } } int N = K - 1; int lda = N; int info; char UPLO = 'U'; dpotrf_(&UPLO, &N, &m[0], &lda, &info); assert(info == 0); dpotrf_(&UPLO, &N, &m[0], &lda, &info); assert(info == 0); for (unsigned long p = 0; p < K - 1; ++p) { for (unsigned long q = 0; q < K - 1; ++q) { inv(p,q) = m[p + q*(K-1)]; } } free(m); } }; #endif
{ "alphanum_fraction": 0.5615074024, "avg_line_length": 27.3161764706, "ext": "h", "hexsha": "07ae432e7194a122ebf6eec0de5cf0f7800f6007", "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/linalg.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/linalg.h", "max_line_length": 76, "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/linalg.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": 1366, "size": 3715 }
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #define _CRT_SECURE_NO_WARNINGS #define _SCL_SECURE_NO_WARNINGS #define _CRT_NON_CONFORMING_SWPRINTFS #define HPX_COMPONENT_EXPORTS #include "targetver.h" #include <gsl.h> #include <stdio.h> #include <tchar.h> #include <iostream> #include <string> // TODO: reference additional headers your program requires here #include <hpx/hpx_init.hpp> #include <hpx/include/actions.hpp> #include <hpx/include/lcos.hpp> #include <hpx/include/components.hpp> #include <hpx/include/serialization.hpp> #include <boost/any.hpp> #include <hpx/include/iostreams.hpp> #include "functions.hpp" #include "components.hpp" #include "stubs.h" #include "clients.h" // SmallServer references #include "../../Libs/SmallServer/SmallServer.h"
{ "alphanum_fraction": 0.7737961926, "avg_line_length": 24.8055555556, "ext": "h", "hexsha": "db4adde40c6d03584c6546c9bc34624c4f38bd98", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-01-17T02:27:20.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-23T06:29:57.000Z", "max_forks_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "brakmic/HPX_Projects", "max_forks_repo_path": "Apps/HpxTest_1/stdafx.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "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": "brakmic/HPX_Projects", "max_issues_repo_path": "Apps/HpxTest_1/stdafx.h", "max_line_length": 66, "max_stars_count": 17, "max_stars_repo_head_hexsha": "747f011e10b9201e78b1d605ee170931ef3b6b72", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "brakmic/HPX_Projects", "max_stars_repo_path": "Apps/HpxTest_1/stdafx.h", "max_stars_repo_stars_event_max_datetime": "2021-03-01T23:28:02.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-21T10:32:13.000Z", "num_tokens": 209, "size": 893 }
#include <cblas.h> #include <stdio.h> #include <stdlib.h> int main() { unsigned int const len = 1000; double x[len]; double y[len]; for (int i = 0; i < len; i++) { x[i] = rand() / (double)RAND_MAX; y[i] = rand() / (double)RAND_MAX; } double ret; int inc = 1; for (int i = 0; i < len*len; i++) ret = cblas_ddot(len, x, inc, y, inc); return (int)ret; }
{ "alphanum_fraction": 0.5718157182, "avg_line_length": 16.0434782609, "ext": "c", "hexsha": "d5e6b366284c62c32a33e5d25cedd6ebac764c22", "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": "2167172931f00d8af68a7c8744430d3cce16a17f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "charles-cooper/idylblas", "max_forks_repo_path": "src/foo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2167172931f00d8af68a7c8744430d3cce16a17f", "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": "charles-cooper/idylblas", "max_issues_repo_path": "src/foo.c", "max_line_length": 40, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2167172931f00d8af68a7c8744430d3cce16a17f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "charles-cooper/idylblas", "max_stars_repo_path": "src/foo.c", "max_stars_repo_stars_event_max_datetime": "2016-05-28T16:19:32.000Z", "max_stars_repo_stars_event_min_datetime": "2016-05-28T16:19:32.000Z", "num_tokens": 133, "size": 369 }
/* ode-initval/gear2.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. */ /* Gear 2 */ /* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "odeiv_util.h" #include <gsl/gsl_odeiv.h> /* gear2 state object */ typedef struct { int primed; /* flag indicating that yim1 is ready */ double t_primed; /* system was primed for this value of t */ double last_h; /* last step size */ gsl_odeiv_step *primer; /* stepper to use for priming */ double *yim1; /* y_{i-1} */ double *k; /* work space */ double *y0; /* work space */ double *y0_orig; double *y_onestep; int stutter; } gear2_state_t; static void * gear2_alloc (size_t dim) { gear2_state_t *state = (gear2_state_t *) malloc (sizeof (gear2_state_t)); if (state == 0) { GSL_ERROR_NULL ("failed to allocate space for gear2_state", GSL_ENOMEM); } state->yim1 = (double *) malloc (dim * sizeof (double)); if (state->yim1 == 0) { free (state); GSL_ERROR_NULL ("failed to allocate space for yim1", GSL_ENOMEM); } state->k = (double *) malloc (dim * sizeof (double)); if (state->k == 0) { free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for k", GSL_ENOMEM); } state->y0 = (double *) malloc (dim * sizeof (double)); if (state->y0 == 0) { free (state->k); free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } state->y0_orig = (double *) malloc (dim * sizeof (double)); if (state->y0_orig == 0) { free (state->y0); free (state->k); free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for y0_orig", GSL_ENOMEM); } state->y_onestep = (double *) malloc (dim * sizeof (double)); if (state->y_onestep == 0) { free (state->y0_orig); free (state->y0); free (state->k); free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for y0_orig", GSL_ENOMEM); } state->primed = 0; state->primer = gsl_odeiv_step_alloc (gsl_odeiv_step_rk4imp, dim); if (state->primer == 0) { free (state->y_onestep); free (state->y0_orig); free (state->y0); free (state->k); free (state->yim1); free (state); GSL_ERROR_NULL ("failed to allocate space for primer", GSL_ENOMEM); } state->last_h = 0.0; return state; } static int gear2_step (double *y, gear2_state_t * state, const double h, const double t, const size_t dim, const gsl_odeiv_system * sys) { /* Makes a Gear2 advance with step size h. y0 is the initial values of variables y. The implicit matrix equations to solve are: k = y0 + h * f(t + h, k) y = y0 + h * f(t + h, k) */ const int iter_steps = 3; int nu; size_t i; double *y0 = state->y0; double *yim1 = state->yim1; double *k = state->k; /* Iterative solution of k = y0 + h * f(t + h, k) Note: This method does not check for convergence of the iterative solution! */ for (nu = 0; nu < iter_steps; nu++) { int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, k); if (s != GSL_SUCCESS) { return s; } for (i = 0; i < dim; i++) { y[i] = ((4.0 * y0[i] - yim1[i]) + 2.0 * h * k[i]) / 3.0; } } return GSL_SUCCESS; } static int gear2_apply (void *vstate, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * sys) { gear2_state_t *state = (gear2_state_t *) vstate; state->stutter = 0; if (state->primed == 0 || t == state->t_primed || h != state->last_h) { /* Execute a single-step method to prime the process. Note that * we do this if the step size changes, so frequent step size * changes will cause the method to stutter. * * Note that we reuse this method if the time has not changed, * which can occur when the adaptive driver is attempting to find * an appropriate step-size on its first iteration */ int status; DBL_MEMCPY (state->yim1, y, dim); status = gsl_odeiv_step_apply (state->primer, t, h, y, yerr, dydt_in, dydt_out, sys); /* Make note of step size and indicate readiness for a Gear step. */ state->primed = 1; state->t_primed = t; state->last_h = h; state->stutter = 1; return status; } else { /* We have a previous y value in the buffer, and the step * sizes match, so we go ahead with the Gear step. */ double *const k = state->k; double *const y0 = state->y0; double *const y0_orig = state->y0_orig; double *const yim1 = state->yim1; double *y_onestep = state->y_onestep; int s; size_t i; DBL_MEMCPY (y0, y, dim); /* iterative solution */ if (dydt_out != NULL) { DBL_MEMCPY (k, dydt_out, dim); } /* First traverse h with one step (save to y_onestep) */ DBL_MEMCPY (y_onestep, y, dim); s = gear2_step (y_onestep, state, h, t, dim, sys); if (s != GSL_SUCCESS) { return s; } /* Then with two steps with half step length (save to y) */ s = gear2_step (y, state, h / 2.0, t, dim, sys); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } DBL_MEMCPY (y0, y, dim); s = gear2_step (y, state, h / 2.0, t + h / 2.0, dim, sys); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } /* Cleanup update */ if (dydt_out != NULL) { s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out); if (s != GSL_SUCCESS) { /* Restore original y vector */ DBL_MEMCPY (y, y0_orig, dim); return s; } } /* Estimate error and update the state buffer. */ for (i = 0; i < dim; i++) { yerr[i] = 4.0 * (y[i] - y_onestep[i]); yim1[i] = y0[i]; } /* Make note of step size. */ state->last_h = h; return 0; } } static int gear2_reset (void *vstate, size_t dim) { gear2_state_t *state = (gear2_state_t *) vstate; DBL_ZERO_MEMSET (state->yim1, dim); DBL_ZERO_MEMSET (state->k, dim); DBL_ZERO_MEMSET (state->y0, dim); state->primed = 0; state->last_h = 0.0; return GSL_SUCCESS; } static unsigned int gear2_order (void *vstate) { gear2_state_t *state = (gear2_state_t *) vstate; state = 0; /* prevent warnings about unused parameters */ return 3; } static void gear2_free (void *vstate) { gear2_state_t *state = (gear2_state_t *) vstate; free (state->yim1); free (state->k); free (state->y0); free (state->y0_orig); free (state->y_onestep); gsl_odeiv_step_free (state->primer); free (state); } static const gsl_odeiv_step_type gear2_type = { "gear2", /* name */ 1, /* can use dydt_in */ 0, /* gives exact dydt_out */ &gear2_alloc, &gear2_apply, &gear2_reset, &gear2_order, &gear2_free }; const gsl_odeiv_step_type *gsl_odeiv_step_gear2 = &gear2_type;
{ "alphanum_fraction": 0.5675485009, "avg_line_length": 24.7238372093, "ext": "c", "hexsha": "e1afe21840d8355f872b461e1d549f22ec32fd0b", "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/ode-initval/gear2.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/ode-initval/gear2.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/ode-initval/gear2.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": 2485, "size": 8505 }
/* ** ** G.Lohmann, MPI-KYB, May 2018 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #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_math.h> extern void VCheckImage(VImage src); extern VImage VFilterGauss3d (VImage src,VImage dest,double *sigma); void Gauss4d(VAttrList list,double *sigma) { /* get pointers to image data */ double u=0; int j,b,r,c; int nrows=0,ncols=0,nt=0; int nslices = VAttrListNumImages(list); VImage *src = VAttrListGetImages(list,nslices); VImageDimensions(src,nslices,&nt,&nrows,&ncols); fprintf(stderr," image dimensions: %d x %d x %d, nt: %d\n",nslices,nrows,ncols,nt); VImage tmp = VCreateImage(nslices,nrows,ncols,VFloatRepn); VFillImage(tmp,VAllBands,0); VImage dest = VCreateImage(nslices,nrows,ncols,VFloatRepn); VFillImage(dest,VAllBands,0); for (j=0; j<nt; j++) { if (j%5==0) fprintf(stderr," %5d of %d\r",j,nt); for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { u = VGetPixel(src[b],j,r,c); VSetPixel(tmp,b,r,c,u); } } } dest = VFilterGauss3d (tmp,dest,sigma); for (b=0; b<nslices; b++) { for (r=0; r<nrows; r++) { for (c=0; c<ncols; c++) { u = VGetPixel(dest,b,r,c); VSetPixel(src[b],j,r,c,u); } } } } fprintf(stderr,"\n"); VDestroyImage(tmp); VDestroyImage(dest); }
{ "alphanum_fraction": 0.6290743155, "avg_line_length": 23.2424242424, "ext": "c", "hexsha": "6fbe1bcdb7285c2e308479891a038f89b974f845", "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/prep/vpreprocess/Gauss4d.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/prep/vpreprocess/Gauss4d.c", "max_line_length": 87, "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/prep/vpreprocess/Gauss4d.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": 551, "size": 1534 }
#include "utilities.h" #include "compute_signal.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_histogram.h> #include <fftw3.h> #include <stdlib.h> #include <stdio.h> #include "parameters.h" int main(void){ gsl_rng * r = init_rng(); double * signal, * spectrum; allocate_arrays(&signal, &spectrum, LENGTH); gsl_histogram * hist = init_histogram(HIST_MIN, HIST_MAX, BIN_N); load_wisdom("wisdom"); fftw_plan plan = make_plan(signal, LENGTH); for(size_t i = 0; i < COUNT; i++){ printf("---- pass %zu ----\n", i); compute_signal(signal, LENGTH, DELTA, r, hist); if(i==0) output_signal("signal.dat", signal, LENGTH, DELTA, N_POINTS); remove_mean(signal, LENGTH); make_fft(plan); compute_spectrum(signal, spectrum, LENGTH); puts("Done."); } final_spectrum(spectrum, LENGTH, COUNT, DELTA, SMOOTH_NEIGHBORS); output_spectrum("spectrum.dat", spectrum, LENGTH, DELTA, N_POINTS); output_distribution("distribution.dat", hist); cleanup(signal, spectrum, plan, r, hist); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.6829035339, "avg_line_length": 23.2666666667, "ext": "c", "hexsha": "aa789bb043f8f90ec3527bba2f36dfa3b1018a6d", "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": "6204ac9d212fd6c73751d215c49e95373b573430", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_forks_repo_path": "spectrum.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_issues_repo_path": "spectrum.c", "max_line_length": 74, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step", "max_stars_repo_path": "spectrum.c", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z", "max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z", "num_tokens": 281, "size": 1047 }
#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 "../cosmolike_core/theory/basics.c" #include "../cosmolike_core/theory/structs.c" #include "../cosmolike_core/theory/parameters.c" #include "../cosmolike_core/emu17/P_cb/emu.c" #include "../cosmolike_core/theory/recompute.c" #include "../cosmolike_core/theory/cosmo3D.c" #include "../cosmolike_core/theory/redshift.c" #include "../cosmolike_core/theory/halo.c" #include "../cosmolike_core/theory/HOD.c" #include "../cosmolike_core/theory/cosmo2D_fourier.c" #include "../cosmolike_core/theory/IA.c" #include "../cosmolike_core/theory/cluster.c" #include "../cosmolike_core/theory/BAO.c" #include "../cosmolike_core/theory/external_prior.c" #include "../cosmolike_core/theory/covariances_3D.c" #include "../cosmolike_core/theory/covariances_fourier.c" #include "../cosmolike_core/theory/covariances_cluster.c" #include "init_SRD.c" void run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start); void run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start); void run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start); void run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster); void run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start); void run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start); void run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start); void run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start); void run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start); void run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start); void run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start); void run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start) { int nN1, nN2,i,j; double cov; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); i += Cluster.N200_Nbin*nzc1+nN1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); j += Cluster.N200_Nbin*nzc2+nN2; cov =cov_N_N(nzc1,nN1, nzc2, nN2); fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,0.0,0.0, nzc1, nN1, nzc2, nN2,cov,0.0); } } fclose(F1); } void run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start) { int nN1, nN2, nl1, nzc1, nzs1,i,j; double cov; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); nzc1 = ZC(N1); nzs1 = ZSC(N1); for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){ for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); j += Cluster.N200_Nbin*nzc2+nN2; cov =cov_cgl_N(ell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2); fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell_Cluster[nl1], 0., nzc1, nzs1, nzc2, nN2,cov,0.); } } } fclose(F1); } void run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start) { int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j; double c_g, c_ng; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); nzc1 = ZC(N1); nzs1 = ZSC(N1); nzc2 = ZC(N2); nzs2 = ZSC(N2); for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){ for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; c_g = 0; c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2); if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);} fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nzs1, nzc2, nzs2,c_g, c_ng); } } } } fclose(F1); } void run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster) { int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j, N1,N2; double c_g, c_ng; FILE *F1; char filename[300]; sprintf(filename,"%s%s",PATH,OUTFILE); F1 =fopen(filename,"w"); for (N1 = 0; N1 < tomo.cgl_Npowerspectra; N1 ++){ for (N2 = 0; N2 < tomo.cgl_Npowerspectra; N2 ++){ nzc1 = ZC(N1); nzs1 = ZSC(N1); nzc2 = ZC(N2); nzs2 = ZSC(N2); for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){ for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; c_g = 0; c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2); if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);} fprintf(F1,"%d %d %e %e %d %d %d %d %d %d %e %e\n",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nN1,nzs1, nzc2, nN2,nzs2,c_g, c_ng); } } } } } } fclose(F1); } void run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start) { int nz1,nz2, nN2, nl1, nzc1, i,j; double cov; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); nz1 = Z1(N1); nz2 = Z2(N1); for( nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ cov = 0.; i = like.Ncl*N1+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); j += Cluster.N200_Nbin*nzc2+nN2; if (ell[nl1] < like.lmax_shear){cov =cov_shear_N(ell[nl1],nz1,nz2, nzc2, nN2);} fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., nz1, nz2, nzc2, nN2,cov,0.); } } fclose(F1); } void run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start) { int nN1, nN2, nzs1, nzs2,nl2, nzc2, nzs3,i,j; double c_g, c_ng; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); nzs1 = Z1(N1); nzs2 = Z2(N1); nzc2 = ZC(N2); nzs3 = ZSC(N2); for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){ i = like.Ncl*N1+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; c_g = 0.; c_ng = 0.; if (ell[nl1] < like.lmax_shear){ c_ng = cov_NG_shear_cgl(ell[nl1],ell_Cluster[nl2],nzs1, nzs2, nzc2, nN2,nzs3); if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.001){ c_g =cov_G_shear_cgl(ell[nl1],dell_Cluster[nl2],nzs1,nzs2, nzc2, nN2,nzs3); } } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], nzs1, nzs2, nzc2, nzs3,c_g, c_ng); } } } fclose(F1); } void run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start) { int zl,zs, nN2, nl1, nzc1, i,j; double cov,weight; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl = ZL(N1); zs = ZS(N1); for( nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); j += Cluster.N200_Nbin*nzc2+nN2; cov = 0.; weight = test_kmax(ell[nl1],zl); if (weight){ cov =cov_ggl_N(ell[nl1],zl,zs, nzc2, nN2); } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., zl, zs, nzc2, nN2,cov,0.); } } fclose(F1); } void run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start) { int nN2, zl, zs, nzs1, nl2, nzc2, nzs3,i,j; double c_g, c_ng,weight; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl = ZL(N1); zs = ZS(N1); nzc2 = ZC(N2); nzs3 = ZSC(N2); for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; c_g = 0; c_ng = 0.; weight = test_kmax(ell[nl1],zl); if (weight){ c_ng = cov_NG_ggl_cgl(ell[nl1],ell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3); if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){c_g =cov_G_ggl_cgl(ell[nl1],dell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);} } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], zl, zs, nzc2, nzs3,c_g, c_ng); } } } fclose(F1); } void run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell,int N1, int nzc2, int start) { int zl,zs, nN2, nl1, nzc1, i,j; double cov,weight; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for( nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra); j += Cluster.N200_Nbin*nzc2+nN2; cov = 0.; weight = test_kmax(ell[nl1],N1); if (weight){ cov =cov_cl_N(ell[nl1],N1,N1,nzc2,nN2); } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j, ell[nl1], 0., N1, N1, nzc2, nN2,cov,0.); } } fclose(F1); } void run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start) { int nN2,nzc2, nzs3,i,j,nl2; double c_g, c_ng,weight; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); nzc2 = ZC(N2); nzs3 = ZSC(N2); for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){ for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){ i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1; j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin; j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; c_g = 0; c_ng = 0.; weight = test_kmax(ell[nl1],N1); if (weight){ c_ng = cov_NG_cl_cgl(ell[nl1],ell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3); if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){ c_g =cov_G_cl_cgl(ell[nl1],dell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3); } } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng); //printf("%d %d %e %e %d %d %d %d %e %e\n",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng); } } } fclose(F1); } void run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int zl,zs,z3,z4,nl1,nl2,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl = ZL(n1); zs = ZS(n1); printf("\nN_ggl = %d (%d, %d)\n", n1,zl,zs); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n", n2,z3,z4); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 <like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl); if (weight && ell[nl2] < like.lmax_shear){ if (test_zoverlap(zl,z3)*test_zoverlap(zl,z4)){ c_ng = cov_NG_gl_shear_tomo(ell[nl1],ell[nl2],zl,zs,z3,z4); } if (nl1 == nl2){ c_g = cov_G_gl_shear_tomo(ell[nl1],dell[nl1],zl,zs,z3,z4); } } fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],zl,zs,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl = %d \n", n1); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n", n2,z3,z4); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 <like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],z1); if (weight && ell[nl2] < like.lmax_shear){ if (test_zoverlap(z1,z3)*test_zoverlap(z1,z4)){ c_ng = cov_NG_cl_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_cl_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); } } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,zl,zs,nl1,nl2,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl_1 = %d \n", n1); zl = ZL(n2); zs = ZS(n2); printf("N_tomo_2 = %d (%d, %d)\n", n2,zl,zs); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (z1 == zl){ weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],zl); if (weight){ c_ng = cov_NG_cl_gl_tomo(ell[nl1],ell[nl2],z1,z2,zl,zs); if (nl1 == nl2){ c_g = cov_G_cl_gl_tomo(ell[nl1],dell[nl1],z1,z2,zl,zs); } } } fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2, ell[nl1],ell[nl2],z1,z2,zl,zs,c_g,c_ng); } } fclose(F1); } void run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,weight; double c_ng, c_g; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); z1 = n1; z2 = n1; printf("\nN_cl_1 = %d \n", n1); z3 = n2; z4 = n2; printf("N_cl_2 = %d\n", n2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (z1 == z3){ weight = test_kmax(ell[nl1],z1)*test_kmax(ell[nl2],z3); if (weight) { c_ng = cov_NG_cl_cl_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_cl_cl_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); } } fprintf(F1, "%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } void run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start) { int zl1,zl2,zs1,zs2,nl1,nl2, weight; double c_ng, c_g; double fsky = survey.area/41253.0; FILE *F1; char filename[300]; sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); zl1 = ZL(n1); zs1 = ZS(n1); printf("\nN_tomo_1 = %d (%d, %d)\n", n1,zl1,zs1); zl2 = ZL(n2); zs2 = ZS(n2); printf("N_tomo_2 = %d (%d, %d)\n", n2,zl2,zs2); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; weight = test_kmax(ell[nl1],zl1)*test_kmax(ell[nl2],zl2); if (weight && zl1 == zl2) { c_ng = cov_NG_gl_gl_tomo(ell[nl1],ell[nl2],zl1,zs1,zl2,zs2); } if (nl1 == nl2){ c_g = cov_G_gl_gl_tomo(ell[nl1],dell[nl1],zl1,zs1,zl2,zs2); } if (weight ==0 && n2 != n1){ c_g = 0; } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*(tomo.shear_Npowerspectra+n1)+nl1,like.Ncl*(tomo.shear_Npowerspectra+n2)+nl2, ell[nl1],ell[nl2],zl1,zs1,zl2,zs2,c_g,c_ng); } } fclose(F1); } void run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell,int n1, int n2,int start) { int z1,z2,z3,z4,nl1,nl2,weight; double c_ng, c_g; FILE *F1; char filename[300]; z1 = Z1(n1); z2 = Z2(n1); printf("N_shear = %d\n", n1); z3 = Z1(n2); z4 = Z2(n2); printf("N_shear = %d (%d, %d)\n",n2,z3,z4); sprintf(filename,"%s%s_%d",PATH,OUTFILE,start); F1 =fopen(filename,"w"); for (nl1 = 0; nl1 < like.Ncl; nl1 ++){ for (nl2 = 0; nl2 < like.Ncl; nl2 ++){ c_ng = 0.; c_g = 0.; if (ell[nl1] < like.lmax_shear && ell[nl2] < like.lmax_shear){ c_ng = cov_NG_shear_shear_tomo(ell[nl1],ell[nl2],z1,z2,z3,z4); } if (nl1 == nl2){ c_g = cov_G_shear_shear_tomo(ell[nl1],dell[nl1],z1,z2,z3,z4); if (ell[nl1] > like.lmax_shear && n1!=n2){c_g = 0.;} } fprintf(F1,"%d %d %e %e %d %d %d %d %e %e\n",like.Ncl*n1+nl1,like.Ncl*(n2)+nl2,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); //printf("%d %d %e %e %d %d %d %d %e %e\n", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng); } } fclose(F1); } int main(int argc, char** argv) { int i,l,m,n,o,s,p,nl1,t,k; char OUTFILE[400],filename[400],arg1[400],arg2[400]; int N_scenarios=12; double area_table[12]={7500.0,13000.0,16000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0}; double nsource_table[12]={9.8,12.1,15.1,15.1,18.9,23.5,20.3,23.5,26.9,26.9,30.8,35.0}; double nlens_table[12]={15.0,20.0,25.0,25.0,32.0,41.0,35.0,41.0,48.0,48.0,57.0,67.0}; char survey_designation[12][200]={"LSST_Y1","LSST_Y1","LSST_Y1","LSST_Y3","LSST_Y3","LSST_Y3","LSST_Y6","LSST_Y6","LSST_Y6","LSST_Y10","LSST_Y10","LSST_Y10"}; char source_zfile[12][400]={"WL_zdistri_model0_z0=1.940000e-01_alpha=8.830000e-01","WL_zdistri_model1_z0=1.900000e-01_alpha=8.620000e-01","WL_zdistri_model2_z0=1.860000e-01_alpha=8.410000e-01","WL_zdistri_model3_z0=1.860000e-01_alpha=8.410000e-01","WL_zdistri_model4_z0=1.830000e-01_alpha=8.210000e-01","WL_zdistri_model5_z0=1.790000e-01_alpha=8.000000e-01","WL_zdistri_model6_z0=1.810000e-01_alpha=8.140000e-01","WL_zdistri_model7_z0=1.790000e-01_alpha=8.000000e-01","WL_zdistri_model8_z0=1.760000e-01_alpha=7.860000e-01","WL_zdistri_model9_z0=1.760000e-01_alpha=7.860000e-01","WL_zdistri_model10_z0=1.740000e-01_alpha=7.720000e-01","WL_zdistri_model11_z0=1.710000e-01_alpha=7.590000e-01"}; char lens_zfile[12][400]={"LSS_zdistri_model0_z0=2.590000e-01_alpha=9.520000e-01","LSS_zdistri_model1_z0=2.610000e-01_alpha=9.370000e-01","LSS_zdistri_model2_z0=2.640000e-01_alpha=9.250000e-01","LSS_zdistri_model3_z0=2.640000e-01_alpha=9.250000e-01","LSS_zdistri_model4_z0=2.680000e-01_alpha=9.150000e-01","LSS_zdistri_model5_z0=2.740000e-01_alpha=9.070000e-01","LSS_zdistri_model6_z0=2.700000e-01_alpha=9.120000e-01","LSS_zdistri_model7_z0=2.740000e-01_alpha=9.070000e-01","LSS_zdistri_model8_z0=2.780000e-01_alpha=9.030000e-01","LSS_zdistri_model9_z0=2.780000e-01_alpha=9.030000e-01","LSS_zdistri_model10_z0=2.830000e-01_alpha=9.000000e-01","LSS_zdistri_model11_z0=2.880000e-01_alpha=8.980000e-01"}; int Ntomo_lens[12]={5,5,5,7,7,7,9,9,9,10,10,10}; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // use this remapping only if files fail !!!!!!!!! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // int fail[5]={1134, 259, 497, 623, 718}; // hit=fail[hit-1]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! int hit=atoi(argv[1]); Ntable.N_a=20; k=1; for(t=0;t<1;t++){ //RUN MODE setup init_cosmo(); init_binning_fourier(20,20.0,15000.0,3000.0,21.0,5,Ntomo_lens[t]); init_survey(survey_designation[t]); sprintf(arg1,"zdistris/%s",source_zfile[t]); sprintf(arg2,"zdistris/%s",lens_zfile[t]); init_galaxies(arg1,arg2,"none","none","source"); init_clusters(); init_IA("none", "GAMA"); init_probes("3x2pt_clusterN_clusterWL"); //set l-bins for shear, ggl, clustering, clusterWL double logdl=(log(like.lmax)-log(like.lmin))/like.Ncl; double *ell, *dell, *ell_Cluster, *dell_Cluster; ell=create_double_vector(0,like.Ncl-1); dell=create_double_vector(0,like.Ncl-1); ell_Cluster=create_double_vector(0,Cluster.lbin-1); dell_Cluster=create_double_vector(0,Cluster.lbin-1); int j=0; for(i=0;i<like.Ncl;i++){ ell[i]=exp(log(like.lmin)+(i+0.5)*logdl); dell[i]=exp(log(like.lmin)+(i+1)*logdl)-exp(log(like.lmin)+(i*logdl)); if(ell[i]<like.lmax_shear) printf("%le\n",ell[i]); if(ell[i]>like.lmax_shear){ ell_Cluster[j]=ell[i]; dell_Cluster[j]=dell[i]; printf("%le %le\n",ell[i],ell_Cluster[j]); j++; } } printf("----------------------------------\n"); survey.area=area_table[t]; survey.n_gal=nsource_table[t]; survey.n_lens=nlens_table[t]; sprintf(survey.name,"%s_area%le_ng%le_nl%le",survey_designation[t],survey.area,survey.n_gal,survey.n_lens); printf("area: %le n_source: %le n_lens: %le\n",survey.area,survey.n_gal,survey.n_lens); sprintf(covparams.outdir,"/home/u17/timeifler/covparallel/"); printf("----------------------------------\n"); sprintf(OUTFILE,"%s_ssss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=l;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_shear_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_lsls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=l;m<tomo.ggl_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_ggl(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } //printf("%d\n",k); k=k+1; } } sprintf(OUTFILE,"%s_llll_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ //auto bins only for now! for (m=l;m<tomo.clustering_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_clustering(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; //printf("%d %d %d\n",l,m,k); } } sprintf(OUTFILE,"%s_llss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_clustering_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_llls_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.ggl_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_clustering_ggl(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_lsss_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_ggl_shear(OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; //printf("%d\n",k); } } //****************************** //******cluster covariance****** //****************************** sprintf(OUTFILE,"%s_nn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.cluster_Nbin; l++){ for (m=0;m<tomo.cluster_Nbin; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_N_N (OUTFILE,covparams.outdir,l,m,k); } } k=k+1; //printf("%d\n",k); } } sprintf(OUTFILE,"%s_cscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.cgl_Npowerspectra; l++){ for (m=0;m<tomo.cgl_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_cgl_cgl (OUTFILE,covparams.outdir,ell_Cluster,dell_Cluster,l,m,k); } } k=k+1; } } sprintf(OUTFILE,"%s_csn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.cgl_Npowerspectra; l++){ for (m=0;m<tomo.cluster_Nbin; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_cgl_N (OUTFILE,covparams.outdir,ell_Cluster,dell_Cluster,l,m,k); } } k=k+1; } } //shear X cluster sprintf(OUTFILE,"%s_ssn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=0;m<tomo.cluster_Nbin; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_shear_N (OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; } } sprintf(OUTFILE,"%s_sscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=0;m<tomo.cgl_Npowerspectra; m++){ //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_shear_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k); } } k=k+1; //} } } // ggl X cluster sprintf(OUTFILE,"%s_lsn_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.cluster_Nbin; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_ggl_N (OUTFILE,covparams.outdir,ell,dell,l,m,k); } } k=k+1; } } sprintf(OUTFILE,"%s_lscs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.cgl_Npowerspectra; m++){ //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_ggl_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k); } } k=k+1; //} } } // clustering X cluster sprintf(OUTFILE,"%s_lln_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.cluster_Nbin; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_cl_N (OUTFILE,covparams.outdir,ell,dell,l,m,k); } } //printf("%d\n",k); k=k+1; } } sprintf(OUTFILE,"%s_llcs_cov_Ncl%d_Ntomo%d",survey.name,like.Ncl,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.cgl_Npowerspectra; m++){ //for(nl1 = 0; nl1 < like.Ncl; nl1 ++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else { run_cov_cl_cgl (OUTFILE,covparams.outdir,ell,dell,ell_Cluster,dell_Cluster,l,m,nl1,k); } } k=k+1; //} } } } printf("number of cov blocks for parallelization: %d\n",k-1); printf("-----------------\n"); printf("PROGRAM EXECUTED\n"); printf("-----------------\n"); return 0; }
{ "alphanum_fraction": 0.6017726161, "avg_line_length": 39.2326139089, "ext": "c", "hexsha": "005b07dc15f26e29b540f6798f9f9f9ea60242ec", "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": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CosmoLike/LSSTC_obsstrat", "max_forks_repo_path": "compute_covariances_fourier.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1", "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/LSSTC_obsstrat", "max_issues_repo_path": "compute_covariances_fourier.c", "max_line_length": 703, "max_stars_count": null, "max_stars_repo_head_hexsha": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CosmoLike/LSSTC_obsstrat", "max_stars_repo_path": "compute_covariances_fourier.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 12509, "size": 32720 }
#include <math.h> #include <stdlib.h> #if !defined(__APPLE__) #include <malloc.h> #endif #include <stdio.h> #include <assert.h> #include <string.h> #include <gsl/gsl_errno.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_deriv.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_sf_expint.h> #include "../cosmolike_light/theory/baryons.h" #include "../cosmolike_light/theory/basics.c" #include "../cosmolike_light/theory/structs.c" #include "../cosmolike_light/theory/parameters.c" #include "../cosmolike_light/emu17/P_cb/emu.c" #include "../cosmolike_light/theory/recompute.c" #include "../cosmolike_light/theory/cosmo3D.c" #include "../cosmolike_light/theory/redshift_spline.c" #include "../cosmolike_light/theory/halo.c" #include "../cosmolike_light/theory/HOD.c" #include "../cosmolike_light/theory/cosmo2D_fourier.c" #include "../cosmolike_light/theory/IA.c" #include "../cosmolike_light/theory/BAO.c" #include "../cosmolike_light/theory/external_prior.c" #include "../cosmolike_light/theory/covariances_3D.c" #include "../cosmolike_light/theory/covariances_fourier.c" #include "../cosmolike_light/theory/covariances_real.c" #include "../cosmolike_light/theory/run_covariances_real.c" #include "../cosmolike_light/theory/init.c" int main(int argc, char** argv) { int hit=atoi(argv[1]); FILE *F1,*F2; int i,l,m,n,o,s,p,output; double ktmp; char OUTFILE[400],filename[400]; printf("-----------------\n"); printf("This is not production mode covariance code\n"); printf("Please only use with care and at your own risk\n"); printf("-----------------\n"); Ntable.N_a=20; set_cov_parameters_to_("cov_Y1/cov_y1_mcal_revision.ini",1); //here: setting values internally // set this to zero to quickly run Gaussian-only covariances for testing if (covparams.ng==1){ NG = 1; } else { NG = 0; } // set this to one to output details about inputs for diagnostics output = 0; FILE *F; printf("running multi_covariance_real with NG = %d\n",NG); set_cosmological_parameters_to_("cov_Y1/cov_y1_mcal_revision.ini",1); //here: setting values internally // cosmology.Omega_m = 0.286; // cosmology.Omega_v = 1.0-cosmology.Omega_m; // cosmology.sigma_8 = 0.82; // cosmology.n_spec = 0.96; // cosmology.w0=-1.; // cosmology.wa=0.; // cosmology.omb=0.04868; // cosmology.h0=0.673; // cosmology.coverH0= 2997.92458; // cosmology.rho_crit = 7.4775e+21; // cosmology.f_NL = 0.0; // pdeltaparams.runmode="Halofit" set_survey_parameters_to_("cov_Y1/cov_y1_mcal_revision.ini",1); //here: setting values internally //survey.area=1000.0; //survey.m_lim= //survey.name= //survey.Kcorrect_File= // redshift.shear_REDSHIFT_FILE=source.nz // redshift.clustering_REDSHIFT_FILE=lens.nz // survey.sourcephotoz="multihisto"; // survey.lensphotoz="multihisto"; // survey.galsample= // tomo.shear_Nbin=5; // redshift.clustering_histogram_zbins = // tomo.clustering_Nbin=5; // tomo.clustering_Npowerspectra=tomo.clustering_Nbin; // survey.sigma_e=0.24; // survey.ggl_overlap_cut= // tomo.n_source[0]=1.07535691109; // tomo.n_source[1]=1.1606931903; // tomo.n_source[2]=1.2275933389; // tomo.n_source[3]=1.23453951309; // tomo.n_source[4]=1.3387876584; // tomo.n_lens[0]=0.02143277; // tomo.n_lens[1]=0.05426833; // tomo.n_lens[2]=0.08070083; // tomo.n_lens[3]=0.05130111; // tomo.n_lens[4]=0.01515694; // for (i=0;i<tomo.clustering_Nbin:i++) survey.n_lens+=tomo.n_lens[i]; // for (i=0;i<tomo.shear_Nbin:i++) survey.n_gal+=tomo.n_source[i]; init_source_sample_(); init_lens_sample_(); //init_clusters(); //init_IA("none", "GAMA"); //printf("test values: %d, %d, %s",redshift.clustering_photoz,tomo.clustering_Nbin,redshift.clustering_REDSHIFT_FILE); // printf("end of setup in main\n"); double theta_min= covparams.tmin; double theta_max= covparams.tmax; int Ntheta=covparams.ntheta; double logdt=(log(theta_max)-log(theta_min))/Ntheta; double *theta,*thetamin,*thetamax, *dtheta; theta=create_double_vector(0,Ntheta-1); thetamin=create_double_vector(0,Ntheta); thetamax=create_double_vector(0,Ntheta-1); dtheta=create_double_vector(0,Ntheta-1); for(i=0; i<Ntheta ; i++){ thetamin[i]=exp(log(theta_min)+(i+0.0)*logdt); thetamax[i]=exp(log(theta_min)+(i+1.0)*logdt); theta[i] = 2./3.*(pow(thetamax[i],3.)-pow(thetamin[i],3.))/(pow(thetamax[i],2.)-pow(thetamin[i],2.)); dtheta[i]=thetamax[i]-thetamin[i]; } thetamin[Ntheta] = thetamax[Ntheta-1]; int k=1; if (strcmp(covparams.ss,"true")==0) { sprintf(OUTFILE,"%s_ssss_++_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=l;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_shear_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,1,1,k);} } k=k+1; } } sprintf(OUTFILE,"%s_ssss_--_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=l;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_shear_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,0,0,k);} } k=k+1; } } sprintf(OUTFILE,"%s_ssss_+-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.shear_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_shear_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,1,0,k);} } k=k+1; } } } if (strcmp(covparams.ll,"true")==0) { sprintf(OUTFILE,"%s_llll_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=l;m<tomo.clustering_Npowerspectra; m++){ if(k==hit){ sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_clustering_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,k);} } k=k+1; } } } if (strcmp(covparams.ls,"true")==0) { sprintf(OUTFILE,"%s_lsls_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=l;m<tomo.ggl_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_ggl_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,k);} } k=k+1; } } } if (strcmp(covparams.ls,"true")==0 && strcmp(covparams.ss,"true")==0) { sprintf(OUTFILE,"%s_lsss_+_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_ggl_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,1,k);} } k=k+1; } } sprintf(OUTFILE,"%s_lsss_-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.ggl_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_ggl_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,0,k);} } k=k+1; } } } if (strcmp(covparams.ll,"true")==0 && strcmp(covparams.ss,"true")==0) { sprintf(OUTFILE,"%s_llss_+_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_clustering_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,1,k);} } k=k+1; } } sprintf(OUTFILE,"%s_llss_-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.shear_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_clustering_shear_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,0,k);} } k=k+1; } } } if (strcmp(covparams.ll,"true")==0 && strcmp(covparams.ls,"true")==0) { sprintf(OUTFILE,"%s_llls_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin); for (l=0;l<tomo.clustering_Npowerspectra; l++){ for (m=0;m<tomo.ggl_Npowerspectra; m++){ if(k==hit) { sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k); if (fopen(filename, "r") != NULL){exit(1);} else {run_cov_clustering_ggl_real_bin(OUTFILE,covparams.outdir,thetamin,Ntheta,l,m,k);} } k=k+1; } } } if (hit==0) { sprintf(OUTFILE,"%s%s",covparams.outdir,covparams.filename); write_gglensing_zbins(OUTFILE); sprintf(OUTFILE,"%s%s.blocks",covparams.outdir,covparams.filename); F1 = fopen(OUTFILE,"w"); fprintf(F1,"%d\n",k-1); fclose(F1); } printf("number of cov blocks for parallelization: %d\n",k-1); printf("-----------------\n"); printf("PROGRAM EXECUTED\n"); printf("-----------------\n"); return 0; }
{ "alphanum_fraction": 0.64399379, "avg_line_length": 34.3533333333, "ext": "c", "hexsha": "fa586793cfce08a1a9c9fdcc1d04796b68ff7792", "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": "485eb2fbf10841f741e3415665d5a97a96d510d5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "CosmoLike/lighthouse_cov", "max_forks_repo_path": "multi_covariances_real_mpp_home.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "485eb2fbf10841f741e3415665d5a97a96d510d5", "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/lighthouse_cov", "max_issues_repo_path": "multi_covariances_real_mpp_home.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "485eb2fbf10841f741e3415665d5a97a96d510d5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CosmoLike/lighthouse_cov", "max_stars_repo_path": "multi_covariances_real_mpp_home.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3340, "size": 10306 }
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it> * 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. * */ /* * * * Filename: stationary.c * * Description: Find the stationary state for the given generator * * Version: 1.0 * Created: 05/05/2014 15:27:48 * Revision: none * License: BSD * * Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it * Organization: Università degli Studi di Trieste * * */ #include "funcs.h" #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> /* * FUNCTION * Name: stationary * Description: Given the dissipator in Bloch form, reduce to a 3x3 problem and store * the stationary state in the 3x1 vector *X * * M X = 0 * * | 0 0 0 0 | | 1 | 0 * | M10 M11 M12 M13 | | X1 | 0 * | M20 M21 M22 M23 | | X2 | = 0 * | M30 M31 M32 M33 | | X3 | 0 * * * A x = b * * | M11 M12 M13 | | X1 | | -M10 | * | M21 M22 M23 | | X2 | = | -M20 | * | M31 M32 M33 | | X3 | | -M30 | */ int stationary ( const gsl_matrix* M, gsl_vector* stat_state ) { /* Store space for the stationary state */ gsl_vector* req = gsl_vector_calloc ( 4 ) ; gsl_vector_set ( req, 0, 1 ) ; /* Copy the dissipator matrix in a temporary local matrix m * (because the algorithm destroys it...) */ gsl_matrix* m = gsl_matrix_calloc ( 4, 4 ) ; gsl_matrix_memcpy ( m, M ) ; /* Create a view of the spatial part of vector req */ gsl_vector_view x = gsl_vector_subvector ( req, 1, 3 ) ; /* Create a submatrix view of the spatial part of m and a vector view * of the spatial part of the 0-th column, which goes into -b in the system * A x = b */ gsl_matrix_view A = gsl_matrix_submatrix ( m, 1, 1, 3, 3 ) ; gsl_vector_view b = gsl_matrix_subcolumn ( m, 0, 1, 3 ) ; int status1 = gsl_vector_scale ( &b.vector, -1.0 ) ; /* Solve the system A x = b using Householder transformations. * Changing the view x of req => also req is changed, in the spatial part */ int status2 = gsl_linalg_HH_solve ( &A.matrix, &b.vector, &x.vector ) ; /* Set the returning value for the state stat_state */ *stat_state = *req ; /* Free memory */ gsl_matrix_free(m) ; return status1 + status2 ; } /* ----- end of function stationary ----- */ /* * FUNCTION * Name: J * Description: Ohmic spectral density (divided by alpha) * */ double J ( double w, double oc ) { double W = w*exp(-w/oc) ; return (W); } /* ----- end of function J ----- */ /* * FUNCTION * Name: polarization * Description: Polarization P through the CP formula * */ double polarization ( void* params, double oc ) { struct f_params* pars = (struct f_params*) params ; double Omega, omega_1, b ; Omega = pars->Omega ; omega_1 = pars->omega_1 ; b = pars->beta ; double P, num, den, add1, add2, Jplus, Jminus ; Jplus = J(omega_1 + Omega, oc) ; Jminus = J(omega_1 - Omega, oc) ; add1 = POW_2(omega_1 - Omega)*Jplus ; add2 = POW_2(omega_1 + Omega)*Jminus ; num = add1 + add2 ; den = add1/(tanh((omega_1+Omega)*b/2)) + add2/(tanh((omega_1-Omega)*b/2)) ; P = num/den ; return (P); } /* ----- end of function polarization ----- */
{ "alphanum_fraction": 0.6414766558, "avg_line_length": 31.5410958904, "ext": "c", "hexsha": "3053135c56a4998eb4c2f909fd019bbb0354ff8b", "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": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_path": "stationary.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "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": "j-silver/quantum_dots", "max_issues_repo_path": "stationary.c", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_path": "stationary.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1355, "size": 4605 }
/* interpolation/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_interp.h> int test_bsearch(void) { double x_array[5] = { 0.0, 1.0, 2.0, 3.0, 4.0 }; size_t index_result; int status = 0; int s; /* check an interior point */ index_result = gsl_interp_bsearch(x_array, 1.5, 0, 4); s = (index_result != 1); status += s; gsl_test (s, "simple bsearch"); /* check that we get the last interval if x == last value */ index_result = gsl_interp_bsearch(x_array, 4.0, 0, 4); s = (index_result != 3); status += s; gsl_test (s, "upper endpoint bsearch"); /* check that we get the first interval if x == first value */ index_result = gsl_interp_bsearch(x_array, 0.0, 0, 4); s = (index_result != 0); status += s; gsl_test (s, "lower endpoint bsearch"); /* check that we get correct interior boundary behaviour */ index_result = gsl_interp_bsearch(x_array, 2.0, 0, 4); s = (index_result != 2); status += s; gsl_test (s, "degenerate bsearch"); /* check out of bounds above */ index_result = gsl_interp_bsearch(x_array, 10.0, 0, 4); s = (index_result != 3); status += s; gsl_test (s, "out of bounds bsearch +"); /* check out of bounds below */ index_result = gsl_interp_bsearch(x_array, -10.0, 0, 4); s = (index_result != 0); status += s; gsl_test (s, "out of bounds bsearch -"); return status; } typedef double TEST_FUNC (double); typedef struct _xy_table xy_table; struct _xy_table { double * x; double * y; size_t n; }; xy_table make_xy_table (double x[], double y[], size_t n); xy_table make_xy_table (double x[], double y[], size_t n) { xy_table t; t.x = x; t.y = y; t.n = n; return t; } static int test_interp ( const xy_table * data_table, const gsl_interp_type * T, xy_table * test_table, xy_table * test_d_table, xy_table * test_i_table ) { int status = 0; size_t i; gsl_interp_accel *a = gsl_interp_accel_alloc (); gsl_interp *interp = gsl_interp_alloc (T, data_table->n); gsl_interp_init (interp, data_table->x, data_table->y, data_table->n); for (i = 0; i < test_table->n; i++) { double x = test_table->x[i]; double y; double deriv; double integ; double diff_y, diff_deriv, diff_integ; gsl_interp_eval_e (interp, data_table->x, data_table->y, x, a, &y); gsl_interp_eval_deriv_e (interp, data_table->x, data_table->y, x, a, &deriv); gsl_interp_eval_integ_e (interp, data_table->x, data_table->y, 0.0, x, a, &integ); diff_y = y - test_table->y[i]; diff_deriv = deriv - test_d_table->y[i]; diff_integ = integ - test_i_table->y[i]; if (fabs (diff_y) > 1.e-10 || fabs(diff_deriv) > 1.0e-10 || fabs(diff_integ) > 1.0e-10) { status++; } } gsl_interp_accel_free (a); gsl_interp_free (interp); return status; } static int test_linear (void) { int s; double data_x[4] = { 0.0, 1.0, 2.0, 3.0 }; double data_y[4] = { 0.0, 1.0, 2.0, 3.0 }; double test_x[6] = { 0.0, 0.5, 1.0, 1.5, 2.5, 3.0 }; double test_y[6] = { 0.0, 0.5, 1.0, 1.5, 2.5, 3.0 }; double test_dy[6] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; double test_iy[6] = { 0.0, 0.125, 0.5, 9.0/8.0, 25.0/8.0, 9.0/2.0 }; xy_table data_table = make_xy_table(data_x, data_y, 4); xy_table test_table = make_xy_table(test_x, test_y, 6); xy_table test_d_table = make_xy_table(test_x, test_dy, 6); xy_table test_i_table = make_xy_table(test_x, test_iy, 6); s = test_interp (&data_table, gsl_interp_linear, &test_table, &test_d_table, &test_i_table); gsl_test (s, "linear interpolation"); return s; } static int test_cspline (void) { int s; double data_x[3] = { 0.0, 1.0, 2.0 }; double data_y[3] = { 0.0, 1.0, 2.0 }; double test_x[4] = { 0.0, 0.5, 1.0, 2.0 }; double test_y[4] = { 0.0, 0.5, 1.0, 2.0 }; double test_dy[4] = { 1.0, 1.0, 1.0, 1.0 }; double test_iy[4] = { 0.0, 0.125, 0.5, 2.0 }; xy_table data_table = make_xy_table(data_x, data_y, 3); xy_table test_table = make_xy_table(test_x, test_y, 4); xy_table test_d_table = make_xy_table(test_x, test_dy, 4); xy_table test_i_table = make_xy_table(test_x, test_iy, 4); s = test_interp (&data_table, gsl_interp_cspline, &test_table, &test_d_table, &test_i_table); gsl_test (s, "cspline interpolation"); return s; } static int test_akima (void) { int s; double data_x[5] = { 0.0, 1.0, 2.0, 3.0, 4.0 }; double data_y[5] = { 0.0, 1.0, 2.0, 3.0, 4.0 }; double test_x[4] = { 0.0, 0.5, 1.0, 2.0 }; double test_y[4] = { 0.0, 0.5, 1.0, 2.0 }; double test_dy[4] = { 1.0, 1.0, 1.0, 1.0 }; double test_iy[4] = { 0.0, 0.125, 0.5, 2.0 }; xy_table data_table = make_xy_table(data_x, data_y, 5); xy_table test_table = make_xy_table(test_x, test_y, 4); xy_table test_d_table = make_xy_table(test_x, test_dy, 4); xy_table test_i_table = make_xy_table(test_x, test_iy, 4); s = test_interp (&data_table, gsl_interp_akima, &test_table, &test_d_table, &test_i_table); gsl_test (s, "akima interpolation"); return s; } int main (int argc, char **argv) { int status = 0; argc = 0; /* prevent warnings about unused parameters */ argv = 0; status += test_bsearch(); status += test_linear(); status += test_cspline(); status += test_akima(); exit (gsl_test_summary()); }
{ "alphanum_fraction": 0.6463571889, "avg_line_length": 27.0917030568, "ext": "c", "hexsha": "b5b4f730e9e1825fe0891b693fc59c30a4342ffa", "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/interpolation/test.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/interpolation/test.c", "max_line_length": 95, "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/interpolation/test.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": 2188, "size": 6204 }
#include <model.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #define P_inv_gamma gsl_cdf_gamma_Pinv // invverse cumulative gamma dist #define P_inc_gamma gsl_sf_gamma_inc_P // regularised incomplete Gamma function #define lngamma gsl_sf_lngamma // ln Gamma function #define V0 9 #define NUMBER_SHEEP 30 #define NUM_DONORS 10 #define SHEEP_FIRST_TEST_WEEK 1 // month defined as 365/12 days // week defined as 7 days # define WEEKS_PER_MONTH ((365/12)/7) #include "Texel_clean_data.h" typedef struct { double a, b; double *lambda; double *Lambda; double **W4; double *W2; } parameters_t; double u(int, double*); double lngexpan(double, double, int*); double ln_inc_gamma_star(double, double); double w(int, int, int, parameters_t*); double Prob_seroconvert(int, parameters_t*); extern double R0(double, double, double, int, double*); void Variables(struct variables *V) { Var(V, 0, "week"); Var(V, 1, "field infected"); Var(V, 2, "new positives"); Var(V, 3, "cumulative new positives"); Var(V, 4, "seroconversion rate"); Var(V, 5, "number infectious"); Var(V, 6, "number infectious"); Var(V, 6, "housed infected"); Var(V, 7, "infected"); Var(V, 8, "infected"); Var(V, V0, "log_p_pos"); } void Parameters(int trt, int ind, double *p, struct parameterset *Q) { Par(Q, 0, Real, "beta_{field}", Exponential, 0.0008); Par(Q, 1, Real, "beta_{housed}", Gamma, 2.0, 0.1); Par(Q, 2, Real, "a", Exponential, 3.2); Par(Q, 3, Real, "k1", Gamma, 2.0, 4.0); // Par(Q, 0, Real, "beta_{field}", Exponential, 0.0082/WEEKS_PER_MONTH); // Par(Q, 1, Real, "beta_{housed}", Gamma, 2.0, 0.01); // Par(Q, 2, Real, "mu", Gamma, 2.0, 1.5); // Par(Q, 3, Real, "sigma", Gamma, 2.0, 1.5); // Par(Q, 8, Real, "a", Der); // Par(Q, 9, Real, "b", Der); // Par(Q, 10, Real, "beta_{housed}/beta_{field}", Der); // Par(Q, 12, Real, "E[inf_{field}]", Der); // Par(Q, 13, Real, "E[inf_{housed}]", Der); // Par(Q, 14, Real, "E[inf]", Der); // Par(Q, 15, Real, "s_{low}", Der); // Par(Q, 16, Real, "s_{high}", Der); } int Model(const uint trt, const uint ind, const uint nweeks, double *p, double **V, TimePoints *Data) { int i, j, m, *num_infected; double **p_seropos = V, *Einf_field, *Einf_housed; parameters_t pars; double beta_field = p[0]/WEEKS_PER_MONTH; double beta_housed = p[1]/WEEKS_PER_MONTH; double S_a = p[2]; double S_b = S_a/p[3]/WEEKS_PER_MONTH; int seroconversion = lrint(p[3]); for (m = 0; m < nweeks; m++) V[m][0] = m; int *num_infectious = integervector(nweeks); pars.Lambda = doublevector(nweeks); pars.lambda = doublevector(nweeks); pars.W4 = doublematrix(nweeks, nweeks); pars.W2 = doublevector(nweeks); pars.a = S_a; pars.b = S_b; // ewe to ewe transmission // the 10 donor sheep are infectious at start of experiment for (j = 0; j < NUM_DONORS; j++) for (m = 0; m <= sheep_last_week[j]; m++) num_infectious[m]++; for (m = 0; m < nweeks; m++) if (m == 20 || m == 21) pars.lambda[m] = num_infectious[m]*beta_housed; else pars.lambda[m] = num_infectious[m]*beta_field; // cumulative sum of lambda pars.Lambda[0] = 0; for (m = 1; m < nweeks; m++) pars.Lambda[m] = pars.Lambda[m-1]+pars.lambda[m-1]; for (m = 0; m < nweeks; m++) { for (i = 0; i < m; i++) pars.W4[i][m] = w(i, i+1, m+1, &pars) - w(i, i+1, m, &pars) - w(i, i, m+1, &pars) + w(i, i, m, &pars); pars.W2[m] = w(m, m, m+1, &pars); } // for each testing date calculate the probability that a sheep tests positive since the last test for (m = 0; m < nweeks; m++) p_seropos[m][V0] = Prob_seroconvert(m, &pars); /******************** OUTPUT ***********************/ if (Data->mode == OUTPUT) { for (m = 0; m < nweeks; m++) V[m][0] = m; // expected number of new positives on each test date for (j = NUM_DONORS; j < NUMBER_SHEEP; j++) for (i = 0; i < sheep_last_test_week[j]-1; i++) V[i+1][2] += p_seropos[i][V0]; // cumulative expected number of new positives V[0][3] = V[0][2]; for (i = 0; i < nweeks-1; i++) V[i+1][3] = V[i][3]+V[i+1][2]; // seroconversion rate (new positives per week) // V[0][4] = 0; // for (i = 1; i < Data->n; i++) // V[i][4] = V[i][2]/(test_weeks[i]-test_weeks[i-1]); // // number of infectious animals // for (i = 0; i < Data->n; i++) // V[i][5] = num_infectious[test_weeks[i]]; // Einf_field = doublevector(nweeks); // Einf_housed = doublevector(nweeks); // for (j = NUM_DONORS; j < NUMBER_SHEEP; j++) // for (m = 0; m <= SHEEP_LAST_WEEK; m++) // if (test_weeks[m] == 19 || test_weeks[m] == 20) // Einf_housed[m] += (1.-exp(-pars.lambda[m]))*u(m, pars.Lambda); // else // Einf_field[m] += (1.-exp(-pars.lambda[m]))*u(m, pars.Lambda); // for (m = 1; m < nweeks; m++) { // Einf_field[m] += Einf_field[m-1]; // Einf_housed[m] += Einf_housed[m-1]; // } // for (i = 0; i < Data->n; i++) { // V[i][1] = Einf_field[test_weeks[i]]; // V[i][6] = Einf_housed[test_weeks[i]]; // V[i][7] = V[i][1]+V[i][6]; // } // free(Einf_field); // free(Einf_housed); // number infected // num_infected = integervector(nweeks); // for (j = 0; j < NUMBER_SHEEP; j++) // if (sheep_pos_week[j] != -1) // for (m = max(0, sheep_pos_week[j]-seroconversion); m <= SHEEP_LAST_WEEK; m++) // num_infected[m]++; // for (i = 0; i < Data->n; i++) // V[i][8] = num_infected[test_weeks[i]]; // free(num_infected); } free(num_infectious); free(pars.lambda); free(pars.Lambda); free(pars.W4[0]); free(pars.W4); free(pars.W2); return SUCCESS; } double P_pos(int s1, int s2, double **V) { int m; double sum = 0; for (m = s1; m < s2; m++) sum += V[m][V0]; return sum; } double logLikelihood(const uint trt, const uint ind, const double *p, double **V, const TimePoints *Data) { int j, pos_idx; double lnL = 0; for (j = NUM_DONORS; j < NUMBER_SHEEP; j++) if (sheep_pos_index[j] != 0) { pos_idx = sheep_pos_index[j]; if (pos_idx > 0) { do { pos_idx--; } while (Data->t[pos_idx][j] == 0); // ewe is first seropositive at start of month m, therefore it seroconverted // sometime in the months from the last test to the month prior to seroconverting lnL += log(P_pos(lrint(Data->t[pos_idx][0]), sheep_pos_week[j], V)); } else // ewe never seroconverted lnL += log(1. - P_pos(SHEEP_FIRST_TEST_WEEK, sheep_last_test_week[j], V)); } return lnL; } void OutputModel(int trt, int ind, double *Output, double *V) { int i; for (i = 1; i < V0; i++) Output[i] = V[i]; } void OutputData(int trt, int ind, double *Output, double *Var, double *Data, uint *value, int index) { Output[2] = Data[31]; Output[3] = Data[32]; Output[4] = Data[33]; Output[5] = Data[34]; } int f0(int trt, int ind, double *x, double *y, double *p, TimePoints *TP) { // R0 2 month housed int i, n = 2; if (x == NULL) return n; for (i = 0; i < n; i++) { x[i] = 100*i+1; y[i] = R0(x[i], 2., 0.1, 5, p); } return n; } int f1(int trt, int ind, double *x, double *y, double *p, TimePoints *TP) { // R0 0 months housed int i, n = 2; if (x == NULL) return n; for (i = 0; i < n; i++) { x[i] = 100*i+1; y[i] = R0(x[i], 0., 0.1, 5, p); } return n; } int f2(int trt, int ind, double *x, double *y, double *p, TimePoints *TP) { // R0 for 25 sheep housed for different durations int i, n = 14; if (x == NULL) return n; for (i = 0; i < n; i++) { x[i] = i; y[i] = R0(25., x[i]*12./365., 0.1, 5, p); } return n; } int f3(int trt, int ind, double *x, double *y, double *p, TimePoints *TP) { // CDF of normal seroconversion period int i, n = 1000; if (x == NULL) return n; double S_a = p[2]; double S_k1 = p[3]; for (i = 0; i < n; i++) { x[i] = (double)i/20.; // y[i] = gsl_ran_gamma_pdf(x[i], a, 1./b); y[i] = gsl_cdf_gamma_P(x[i], S_a, S_k1); } return n; } void function_list(functions_t *F) { F->n_func = 0; // F->function_list = (function_ptr*) malloc(F->n_func*sizeof(function_ptr)); // F->function_list[0] = f0; // F->function_list[1] = f1; // F->function_list[2] = f2; // F->function_list[3] = f3; } double u(int m, double *Lambda) { // The probability a sheep is uninfected at the start of week m return exp(-Lambda[m]); } double lngseries(double a, double x, int *ierr) { double giant = HUGE_VAL/1000., eps = 1e-15; double t = 1./a, v = t; double p, q, lnigam; int k = 0; *ierr = 0; while ((fabs(t/v) > eps) && *ierr == 0) { p = (a+k)/(a+k+1); q = k+1; t *= -x*p/q; v += t; k += 1; if (t > giant) *ierr = 1; } if (*ierr == 0) if (lngamma(a) < log(giant)) lnigam = log(v)-lngamma(a); else { lnigam = 0; *ierr = 1; } else { lnigam = 0; *ierr = 1; } return lnigam; } double lngexpan(double a, double x, int *ierr) { double giant = HUGE_VAL/1000., eps = 1e-15; double t = 1, v = t; double p, lnigam; int k = 0; *ierr = 0; if (x > log(giant)) { *ierr = 1; return 0; } while ((fabs(t/v) > eps) && *ierr == 0) { p = 1-a+k; t *= p/x; v += t; k += 1; if (t > giant) *ierr = 1; } if (*ierr == 0) if (lngamma(a) < log(giant)) lnigam = log(v)+x-log(x)-lngamma(a); else { lnigam = 0; *ierr = 1; } else { lnigam = 0; *ierr = 1; } return lnigam; } double ln_inc_gamma_star(double a, double z) { int ierr; double lnigam; if (z < -50) { lnigam = lngexpan(a, -z, &ierr); if (ierr != 0) printf("error1\n"); } else { lnigam = lngseries(a, z, &ierr); if (ierr != 0) printf("error2\n"); } return lnigam; } double w(int n, int t, int s, parameters_t *p) { double a = p->a; double l = p->lambda[n]; double b = p->b; double r = (b-l)/b; double Z, z, v; Z = b*(s-t); if (Z == 0) return 0; z = r*Z; if (z <= 0) v = exp(a*log(Z) - l*Z/b + ln_inc_gamma_star(a, z)); else v = exp(-a*log(r) - l*Z/b + log(P_inc_gamma(a, z))); return exp(-l*(t-n))*(v - P_inc_gamma(a, Z)); } double Prob_seroconvert(int m, parameters_t *p) { int n; double P_m = 0; for (n = 0; n < m; n++) P_m += u(n, p->Lambda)*p->W4[n][m]; P_m -= u(m, p->Lambda)*p->W2[m]; return min(max(0, P_m), 1); } void DerivedParameters(int trt, int ind, int nmonths, double *p, double **V, TimePoints *Data) { // int i, j, m; // double a, b; // double beta_field = p[0]; // double beta_housed = p[1]; // double mu = p[2]; // double sd = p[3]; // int seroconversion = lrint(mu); // int latency = lrint(p[4]); // int nweeks = lrint(Data->t[Data->n-1][0])+1; // int *test_weeks = integervector(Data->n); // int *num_infectious = integervector(nweeks); // double *Lambda = doublevector(nweeks); // double *lambda = doublevector(nweeks); // p[8] = a = pow(mu/sd, 2.); // p[9] = b = a/mu; // p[10] = beta_housed/beta_field; // p[15] = P_inv_gamma(0.025, a, 1./b); // p[16] = P_inv_gamma(0.975, a, 1./b); // for (i = 0; i < Data->n; i++) // test_weeks[i] = lrint(Data->t[i][0]); // for (j = 0; j < NUM_DONORS; j++) // for (m = 0; m <= SHEEP_LAST_WEEK; m++) // num_infectious[m]++; // for (j = NUM_DONORS; j < NUMBER_SHEEP; j++) // if (sheep_pos_week[j] > 0) // for (m = max(0, sheep_pos_week[j]-seroconversion+latency); m <= SHEEP_LAST_WEEK; m++) // num_infectious[m]++; // for (m = 0; m < nweeks; m++) // if (test_weeks[m] == 19 || test_weeks[m] == 20) // lambda[m] = num_infectious[m]*beta_housed; // else // lambda[m] = num_infectious[m]*beta_field; // Lambda[0] = 0; // for (m = 1; m < nweeks; m++) // Lambda[m] = Lambda[m-1]+lambda[m-1]; // p[12] = 0; // p[13] = 0; // for (j = NUM_DONORS; j < NUMBER_SHEEP; j++) // for (m = 0; m <= SHEEP_LAST_WEEK; m++) // if (test_weeks[m] == 19 || test_weeks[m] == 20) // p[13] += (1.-exp(-lambda[m]))*u(m, Lambda); // else // p[12] += (1.-exp(-lambda[m]))*u(m, Lambda); // p[14] = p[12]+p[13]; // free(lambda); // free(Lambda); // free(num_infectious); // free(test_weeks); } void WAIC(int trt, int ind, double **lnL, double **V, double *p, const TimePoints *Data) {} void PredictData(int trt, int ind, double *Output, double *V, double *p, gsl_rng *stream) {} void SimulateData(int trt, int ind, double *Output, double *V, double *p, double *Data, uint *value, gsl_rng *stream) {} double timestep(void) {return 1;} void GlobalParameters() {} double UserPDF(double x) {return 0;} void HyperParameters(Treatments T, Hyperparameters *H) {} void SaturatedModel(int trt, int ind, double **V, double *p, const TimePoints *Data) {} void Residual(int trt, int ind, double *R, double *V, double *p, double *Data, uint *value) {}
{ "alphanum_fraction": 0.554863695, "avg_line_length": 26.7662601626, "ext": "c", "hexsha": "f6dbeccf839d7d117b6c9af925de00be74b86f53", "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": "00771289509727b5b25e3776a0964555f227442d", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "nicksavill/maedi-visna-epidemiology", "max_forks_repo_path": "Peterson/model60A.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "nicksavill/maedi-visna-epidemiology", "max_issues_repo_path": "Peterson/model60A.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "nicksavill/maedi-visna-epidemiology", "max_stars_repo_path": "Peterson/model60A.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4869, "size": 13169 }
/* eigen/gsl_eigen.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_EIGEN_H__ #define __GSL_EIGEN_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; double * d; double * sd; } gsl_eigen_symm_workspace; gsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n); void gsl_eigen_symm_free (gsl_eigen_symm_workspace * w); int gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w); typedef struct { size_t size; double * d; double * sd; double * gc; double * gs; } gsl_eigen_symmv_workspace; gsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n); void gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w); int gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w); typedef struct { size_t size; double * d; double * sd; double * tau; } gsl_eigen_herm_workspace; gsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n); void gsl_eigen_herm_free (gsl_eigen_herm_workspace * w); int gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval, gsl_eigen_herm_workspace * w); typedef struct { size_t size; double * d; double * sd; double * tau; double * gc; double * gs; } gsl_eigen_hermv_workspace; gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n); void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w); int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_hermv_workspace * w); typedef enum { GSL_EIGEN_SORT_VAL_ASC, GSL_EIGEN_SORT_VAL_DESC, GSL_EIGEN_SORT_ABS_ASC, GSL_EIGEN_SORT_ABS_DESC } gsl_eigen_sort_t; /* Sort eigensystem results based on eigenvalues. * Sorts in order of increasing value or increasing * absolute value. * * exceptions: GSL_EBADLEN */ int gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec, gsl_eigen_sort_t sort_type); int gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec, gsl_eigen_sort_t sort_type); /* The following functions are obsolete: */ /* Eigensolve by Jacobi Method * * The data in the matrix input is destroyed. * * exceptions: */ int gsl_eigen_jacobi(gsl_matrix * matrix, gsl_vector * eval, gsl_matrix * evec, unsigned int max_rot, unsigned int * nrot); /* Invert by Jacobi Method * * exceptions: */ int gsl_eigen_invert_jacobi(const gsl_matrix * matrix, gsl_matrix * ainv, unsigned int max_rot); __END_DECLS #endif /* __GSL_EIGEN_H__ */
{ "alphanum_fraction": 0.700508974, "avg_line_length": 26.475177305, "ext": "h", "hexsha": "ea7bfb1a52c8f0be89b3c294d82c621d753156b0", "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/eigen/gsl_eigen.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/eigen/gsl_eigen.h", "max_line_length": 106, "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/eigen/gsl_eigen.h", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 989, "size": 3733 }
/* # This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE */ #include <stdarg.h> #include "compat.h" #include "gslutils.h" #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> int gslutils_solve_leastsquares_v(gsl_matrix* A, int NB, ...) { int i, res; gsl_vector** B = malloc(NB * sizeof(gsl_vector*)); // Whoa, three-star programming! gsl_vector*** X = malloc(NB * sizeof(gsl_vector**)); gsl_vector*** R = malloc(NB * sizeof(gsl_vector**)); gsl_vector** Xtmp = malloc(NB * sizeof(gsl_vector*)); gsl_vector** Rtmp = malloc(NB * sizeof(gsl_vector*)); va_list va; va_start(va, NB); for (i=0; i<NB; i++) { B[i] = va_arg(va, gsl_vector*); X[i] = va_arg(va, gsl_vector**); R[i] = va_arg(va, gsl_vector**); } va_end(va); res = gslutils_solve_leastsquares(A, B, Xtmp, Rtmp, NB); for (i=0; i<NB; i++) { if (X[i]) *(X[i]) = Xtmp[i]; else gsl_vector_free(Xtmp[i]); if (R[i]) *(R[i]) = Rtmp[i]; else gsl_vector_free(Rtmp[i]); } free(Xtmp); free(Rtmp); free(X); free(R); free(B); return res; } int gslutils_solve_leastsquares(gsl_matrix* A, gsl_vector** B, gsl_vector** X, gsl_vector** resids, int NB) { int i; gsl_vector *tau, *resid = NULL; int ret; size_t M, N; M = A->size1; N = A->size2; for (i=0; i<NB; i++) { assert(B[i]); assert(B[i]->size == M); } tau = gsl_vector_alloc(MIN(M, N)); assert(tau); ret = gsl_linalg_QR_decomp(A, tau); assert(ret == 0); // A,tau now contains a packed version of Q,R. for (i=0; i<NB; i++) { if (!resid) { resid = gsl_vector_alloc(M); assert(resid); } X[i] = gsl_vector_alloc(N); assert(X[i]); ret = gsl_linalg_QR_lssolve(A, tau, B[i], X[i], resid); assert(ret == 0); if (resids) { resids[i] = resid; resid = NULL; } } gsl_vector_free(tau); if (resid) gsl_vector_free(resid); return 0; }
{ "alphanum_fraction": 0.5308953342, "avg_line_length": 23.3235294118, "ext": "c", "hexsha": "70d8223e76d5c329ee6db6c9484d23375e203700", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-19T22:59:43.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-19T22:59:43.000Z", "max_forks_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mgreter/astrometrylib", "max_forks_repo_path": "astrometrylib/src/util/gslutils.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "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": [ "BSD-3-Clause" ], "max_issues_repo_name": "mgreter/astrometrylib", "max_issues_repo_path": "astrometrylib/src/util/gslutils.c", "max_line_length": 68, "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": "astrometrylib/src/util/gslutils.c", "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": 703, "size": 2379 }
/// @file Span.h /// @author Braxton Salyer <braxtonsalyer@gmail.com> /// @brief A thin wrapper around `gsl::span`, providing `at` as a member function instead of a free /// function /// @version 0.1 /// @date 2021-10-15 /// /// MIT License /// @copyright Copyright (c) 2021 Braxton Salyer <braxtonsalyer@gmail.com> /// /// 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 #include <Hyperion/BasicTypes.h> #include <Hyperion/HyperionDef.h> #include <array> #include <gsl/gsl> #include <gsl/span> namespace hyperion { /// @brief Thin wrapper around `gsl::span` /// /// @tparam T - The type contained in the `Span` /// @tparam Size - The number of elements for constexpr sizes, or gsl::dynamic_extent (default) /// for run-time sizes /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename T, usize Size = gsl::dynamic_extent> class Span { public: using Iterator = typename gsl::span<T, Size>::iterator; using ReverseIterator = typename gsl::span<T, Size>::reverse_iterator; template<usize Offset, usize Count> using SubSpan = typename gsl::details::calculate_subspan_type<T, Size, Offset, Count>::type; Span() noexcept = default; /// @brief Constructs a `Span` from a `gsl::span` /// /// @param span - The `gsl::span` to wrap /// @ingroup utils /// @headerfile "Hyperion/Span.h" explicit constexpr Span(gsl::span<T, Size> span) noexcept : m_span_internal(span) { } /// @brief Copy constructs a `Span` from the given one /// /// @param span - The `Span` to copy /// @ingroup utils /// @headerfile "Hyperion/Span.h" constexpr Span(const Span<T, Size>& span) noexcept = default; /// @brief Move constructs the given `Span` /// /// @param span - The `Span` to move /// @ingroup utils /// @headerfile "Hyperion/Span.h" constexpr Span(Span<T, Size>&& span) noexcept = default; ~Span() noexcept = default; /// @brief Returns the element at the given `index` /// /// @param index - The index of the desired element /// @return - The element at `index` /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto at(usize index) noexcept -> T& { return gsl::at(m_span_internal, static_cast<gsl::index>(index)); } /// @brief Returns the first `Count` elements in the `Span` /// /// @tparam Count - The number of elements to get /// @tparam size - The size of the `Span`, this should always be left defaulted /// @return - The first `Count` elements in the `Span`, as a `Span` /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<usize Count, usize size = Size> requires(size != gsl::dynamic_extent) [[nodiscard]] inline constexpr auto first() const noexcept -> Span<T, Count> { return Span(m_span_internal.template first<Count>()); } /// @brief Returns the first `count` elements in the `Span` /// /// @tparam size - The size of the `Span`, this should always be left defaulted /// @param count - The number of elements to get /// @return - The first `count` elements in the `Span`, as a `Span` /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<usize size = Size> requires(size == gsl::dynamic_extent) [[nodiscard]] inline constexpr auto first(usize count) const noexcept -> Span<T, Size> { return Span(m_span_internal.first(count)); } /// @brief Returns the last `Count` elements in the `Span` /// /// @tparam Count - The number of elements to get /// @tparam size - The size of the `Span`, this should always be left defaulted /// @return - The last `Count` elements in the `Span`, as a `Span` /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<usize Count, usize size = Size> requires(size != gsl::dynamic_extent) [[nodiscard]] inline constexpr auto last() const noexcept -> Span<T, Count> { return Span(m_span_internal.template last<Count>()); } /// @brief Returns the last `count` elements in the `Span` /// /// @tparam size - The size of the `Span`, this should always be left defaulted /// @param count - The number of elements to get /// @return- The last `count` elements in the `Span` as a `Span` /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<usize size = Size> requires(size == gsl::dynamic_extent) [[nodiscard]] inline constexpr auto last(usize count) const noexcept -> Span<T, Size> { return Span(m_span_internal.last(count)); } /// @brief Returns a subspan starting at the given `Offset` with `Count` elements /// /// @tparam Offset - The offset to start the subspan at /// @tparam Count - The number of elements to get in the subspan /// @return - The subspan starting at `Offset` of size `Count` /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<usize Offset, usize Count = gsl::dynamic_extent> [[nodiscard]] inline constexpr auto subspan() const noexcept -> SubSpan<Offset, Count> { return Span(m_span_internal.template subspan<Offset, Count>()); } /// @brief Returns a subspan starting at the given `offset` with `count` elements /// /// @param offset - The offset to start the subspan at /// @param count - The number of elements to get in the subspan /// @return - The subspan starting at `offset` of size `count` /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto subspan(usize offset, usize count = gsl::dynamic_extent) const noexcept -> Span<T, gsl::dynamic_extent> { return Span(m_span_internal.subspan(offset, count)); } /// @brief Returns the number of elements in the `Span` /// /// @return - The number of elements in the `Span` /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto size() const noexcept -> usize { return m_span_internal.size(); } /// @brief Returns the size of the `Span` in bytes /// /// @return - The size of the `Span` in bytes /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto size_bytes() const noexcept -> usize { return m_span_internal.size_bytes(); } /// @brief Returns whether the `Span` is empty /// /// @return - If the `Span` is empty /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto is_empty() const noexcept -> bool { return size() == 0; } /// @brief A pointer to the data contained in the `Span` /// /// @return - A pointer to the data /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto data() const noexcept -> T* { return m_span_internal.data(); } /// @brief Returns the first element in the `Span` /// /// @return - The first element /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto front() const noexcept -> T& { return m_span_internal.front(); } /// @brief Returns the last element in the `Span` /// /// @return - The last element /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto back() const noexcept -> T& { return m_span_internal.back(); } /// @brief Returns an iterator at the beginning of the span /// /// @return an iterator at the beginning of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto begin() noexcept -> Iterator { return m_span_internal.begin(); } /// @brief Returns an iterator at the beginning of the span /// /// @return an iterator at the beginning of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto begin() const noexcept -> Iterator { return m_span_internal.begin(); } /// @brief Returns an iterator at the end of the span /// /// @return an iterator at the end of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto end() noexcept -> Iterator { return m_span_internal.end(); } /// @brief Returns an iterator at the end of the span /// /// @return an iterator at the end of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto end() const noexcept -> Iterator { return m_span_internal.end(); } /// @brief Returns an iterator at the beginning of the reversed iteration of the span /// /// @return an iterator at the beginning of the reversed iteration of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto rbegin() noexcept -> ReverseIterator { return m_span_internal.rbegin(); } /// @brief Returns an iterator at the beginning of the reversed iteration of the span /// /// @return an iterator at the beginning of the reversed iteration of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto rbegin() const noexcept -> ReverseIterator { return m_span_internal.rbegin(); } /// @brief Returns an iterator at the end of the reversed iteration of the span /// /// @return an iterator at the end of the reversed iteration of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto rend() noexcept -> ReverseIterator { return m_span_internal.rend(); } /// @brief Returns an iterator at the end of the reversed iteration of the span /// /// @return an iterator at the end of the reversed iteration of the span /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto rend() const noexcept -> ReverseIterator { return m_span_internal.rend(); } #if HYPERION_PLATFORM_COMPILER_MSVC [[nodiscard]] inline constexpr auto _Unchecked_begin() const noexcept -> T* { return m_span_internal._Unchecked_begin(); } [[nodiscard]] inline constexpr auto _Unchecked_end() const noexcept -> T* { return m_span_internal._Unchecked_end(); } #endif // HYPERION_PLATFORM_COMPILER_MSVC /// @brief Returns the element at the given `index` /// /// @param index - The index of the desired element /// @return - The element at `index` /// @ingroup utils /// @headerfile "Hyperion/Span.h" [[nodiscard]] inline constexpr auto operator[](usize index) noexcept -> T& { return this->at(index); } constexpr auto operator=(const Span<T, Size>& span) noexcept -> Span<T, Size>& = default; constexpr auto operator=(Span<T, Size>&& span) noexcept -> Span<T, Size>& = default; private: gsl::span<T, Size> m_span_internal = gsl::span<T, Size>(); }; IGNORE_UNUSED_TEMPLATES_START /// @brief Creates a `Span` from the given arguments /// /// @tparam T - The type stored in the array /// /// @param array - The array to get a `Span` over /// @param size - The size of the array /// /// @return a `Span` over the given array /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename T> [[nodiscard]] inline static constexpr auto make_span(T* array, usize size) noexcept -> Span<T> { return Span(gsl::make_span(array, static_cast<typename gsl::span<T>::size_type>(size))); } /// @brief Creates a `Span` from the given arguments /// /// @tparam T - The type stored in the array /// /// @param first - Pointer to the first element in the array /// @param last - Pointer to the last element in the array /// /// @return a `Span` over the given array /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename T> [[nodiscard]] inline static constexpr auto make_span(T* first, T* last) noexcept -> Span<T> { return Span(gsl::make_span(first, last)); } /// @brief Creates a `Span` from the given arguments /// /// @tparam T - The type stored in the array /// @tparam Size - The size of the array /// /// @param array - The array to get a `Span` over /// /// @return a `Span` over the given array /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename T, usize Size> [[nodiscard]] inline static constexpr auto make_span(T (&array)[Size]) noexcept -> Span<T, Size> { // NOLINT return Span(gsl::make_span(array)); } /// @brief Creates a `Span` from the given arguments /// /// @tparam Collection - The collection type to get a `Span` over /// /// @param collection - The collection to get a `Span` over /// /// @return a `Span` over the given collection /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename Collection> [[nodiscard]] inline static constexpr auto make_span(Collection& collection) noexcept -> Span<typename Collection::value_type> { return Span(gsl::make_span(collection)); } /// @brief Creates a `Span` from the given arguments /// /// @tparam Collection - The collection type to get a `Span` over /// /// @param collection - The collection to get a `Span` over /// /// @return a `Span` over the given collection /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename Collection> [[nodiscard]] inline static constexpr auto make_span(const Collection& collection) noexcept -> Span<const typename Collection::value_type> { return Span(gsl::make_span(collection)); } /// @brief Creates a `Span` from the given arguments /// /// @tparam SmartPtr - The smart pointer type wrapping the array /// /// @param array - The smart pointer wrapping the array to get a `Span` over /// @param size - The size of the array /// /// @return a `Span` over the given array /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename SmartPtr> [[nodiscard]] inline static constexpr auto make_span(SmartPtr& array, usize size) noexcept -> Span<typename SmartPtr::element_type> { return Span(gsl::make_span(array, size)); } /// @brief Creates a `Span` from the given arguments /// /// @tparam T - The type stored in the array /// @tparam Size - The size of the array /// /// @param array - The array to get a `Span` over /// /// @return a `Span` over the given array /// @ingroup utils /// @headerfile "Hyperion/Span.h" template<typename T, usize Size> [[nodiscard]] inline static constexpr auto make_span(std::array<T, Size> array) noexcept -> Span<T, Size> { return Span(gsl::make_span(array)); } IGNORE_UNUSED_TEMPLATES_STOP } // namespace hyperion
{ "alphanum_fraction": 0.6788912859, "avg_line_length": 35.5744186047, "ext": "h", "hexsha": "6e3cb8839b633ed784d675da0e64511dd4a39257", "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": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "braxtons12/Hyperion-Utils", "max_forks_repo_path": "include/Hyperion/Span.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "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": "braxtons12/Hyperion-Utils", "max_issues_repo_path": "include/Hyperion/Span.h", "max_line_length": 99, "max_stars_count": null, "max_stars_repo_head_hexsha": "3873a116e2ea76fc74c9c056925f3740eee6dcd8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "braxtons12/Hyperion-Utils", "max_stars_repo_path": "include/Hyperion/Span.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4094, "size": 15297 }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #include <sys/time.h> #include <mpi.h> #include "propagator.h" #include "options.h" #include <time.h> #include <limits.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "f2c.h" #include <gsl/gsl_statistics.h> #include "gsl/gsl_sf_legendre.h" ///////////////////////////////////////////////////////////////////////////////////////// // // Name: initialize_constellation // Purpose: Initializes a constellation based on the period of the 1st spacecraft // Assumptions: None. // References Various // // Change Log: // | Developer | Date | SCR | Notes // | --------------|---------------|-----------|------------------------------- // | J. Getchius | 05/20/2015 | --- | Initial Implementation // | C. Bussy-Virat| 07/23/2015 | --- | Initialization of ALL the orbital elements from the input file; Replace altitude by apogee altitude in the input file // ///////////////////////////////////////////////////////////////////////////////////////// int initialize_constellation(CONSTELLATION_T *CONSTELLATION, OPTIONS_T *OPTIONS, PARAMS_T *PARAMS, GROUND_STATION_T *GROUND_STATION, int iDebugLevel, int iProc, int nProcs ) { double **r_alongtrack_all, **r_crosstrack_all, **r_radial_all, **bc_pert_all, **srp_pert_all; double **v_alongtrack_all, **v_crosstrack_all, **v_radial_all; // Declarations double geodetic[3]; int bbb; int m_time_span; /* gsl_rng * r_gaussian_generator; */ /* long seed; */ /* r_gaussian_generator = gsl_rng_alloc(gsl_rng_mt19937); */ // int start_ensemble; double period; int ccc; double collision_equinoctial_sigma_in_diag_basis[6]; double collision_equinoctial_sigma_in_equinoctial_basis[6]; double collision_eci_sigma_in_diag_basis[6]; double collision_eci_sigma_in_eci_basis[6]; /* double collision_x_eci_sigma, collision_y_eci_sigma, collision_z_eci_sigma, collision_vx_eci_sigma, collision_vy_eci_sigma, collision_vz_eci_sigma; */ /* double collision_x_eci_sigma_in_diag_basis, collision_y_eci_sigma_in_diag_basis, collision_z_eci_sigma_in_diag_basis, collision_vx_eci_sigma_in_diag_basis, collision_vy_eci_sigma_in_diag_basis, collision_vz_eci_sigma_in_diag_basis; */ /* int aaa_count; */ /* int swpc_forecast_day; */ /* double nb_index_in_81_days; */ // int aaa_sigma; int write_attitude_file = 0; char time_attitude[256]; FILE *file_attitude[N_SATS]; char filename_attitude[N_SATS][256]; double et_initial_epoch, et_final_epoch; int iground; SpiceDouble xform[6][6]; double estate[6], jstate[6]; int hhh; char *next; int find_file_name; double altitude_perigee; int index_altitude_right_below_perigee_save = 1000000000; int iHeaderLength_gitm; FILE *gitm_file; int i,j,k; int ggg; double random_pitch_angular_velocity, random_roll_angular_velocity, random_yaw_angular_velocity; int time_before_reset; double inclination_sigma = 0; double w_sigma = 0; double long_an_sigma = 0; double f_sigma = 0; double eccentricity_sigma = 0; double sma_sigma = 0; int eee; double et; /* double T_J2000_to_ECEF[3][3]; */ /* double T_ECEF_to_J2000[3][3]; */ int ii,sss,nnn,aaa; double radius_perigee; FILE *gps_tle_file; // Begin Calcs // Initialize Time str2et_c(OPTIONS->initial_epoch, &et); // Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch (in /Users/cbv/cspice/src/cspice/str2et_c.c) (CBV) OPTIONS->et_initial_epoch = et; // should have done that in load_options.c str2et_c(OPTIONS->initial_epoch, &et_initial_epoch); str2et_c(OPTIONS->final_epoch, &et_final_epoch); r_alongtrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); r_crosstrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); r_radial_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); v_alongtrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); v_crosstrack_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); v_radial_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); bc_pert_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); srp_pert_all = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(double *) ); CONSTELLATION->et = et; CONSTELLATION->aaa_sigma = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(int) ); CONSTELLATION->aaa_mod = malloc( OPTIONS->nb_satellites_not_including_gps * sizeof(int) ); CONSTELLATION->sum_sigma_for_f107_average = malloc( ( OPTIONS->nb_satellites_not_including_gps ) * sizeof( double * ) ); if (CONSTELLATION->sum_sigma_for_f107_average == NULL){ print_error_any_iproc(iProc, "Not enough memory for sum_sigma_for_f107_average"); } if (OPTIONS->nb_ensembles_density) { // the user chose to run ensembles on the density using data from SWPC if (OPTIONS->swpc_need_predictions){ // if future predictions of F10.7 and Ap (not only past observations) CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time = malloc( nProcs * sizeof( double *)); CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted = malloc( nProcs * sizeof( double *)); CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time = malloc( nProcs * sizeof( double *)); CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted = malloc( nProcs * sizeof( double *)); } } CONSTELLATION->spacecraft = malloc( OPTIONS->n_satellites * sizeof(SPACECRAFT_T*) ); if ( CONSTELLATION->spacecraft == NULL){ printf("***! Could not allow memory to CONSTELLATION->spacecraft. The program will stop. !***\n"); MPI_Finalize(); exit(0); } /*************************************************************************************/ /*************************************************************************************/ /*********************** SET THINGS UP FOR PARALLEL PROGRAMMING **********************/ /*************************************************************************************/ /*************************************************************************************/ /* Things we set up here: */ /* - which iProc runs which main sc / which sc is run by which iProc */ int nProcs_that_are_gonna_run_ensembles; nProcs_that_are_gonna_run_ensembles = nProcs; if ( nProcs > OPTIONS->nb_ensembles_min ){ nProcs_that_are_gonna_run_ensembles = OPTIONS->nb_ensembles_min; } // For each iProc, set up the first main sc (iStart_save[iProcf]) and the last main sc (iEnd_save[iProcf]) that it's going to run. iStart_save and iEnd_save are two arrays that have the same values for all procs (so if you're iProc 0 or iProc 1, you have value recorded for iStart_save[0] and iEnd_save[0] and the same value recorded for iStart_save[1] and iEnd_save[1]) -> they are not "iProc-dependent" int *iStart_save, *iEnd_save; int nscEachPe, nscLeft; int iProcf; nscEachPe = (OPTIONS->n_satellites)/nProcs; nscLeft = (OPTIONS->n_satellites) - (nscEachPe * nProcs); iStart_save = malloc( nProcs * sizeof(int)); iEnd_save = malloc( nProcs * sizeof(int)); for (iProcf = 0; iProcf < nProcs; iProcf++){ iStart_save[iProcf] = 0; iEnd_save[iProcf] = 0; } for (iProcf = 0; iProcf < nProcs; iProcf++){ for (i=0; i<iProcf; i++) { iStart_save[iProcf] += nscEachPe; if (i < nscLeft && iProcf > 0) iStart_save[iProcf]++; } iEnd_save[iProcf] = iStart_save[iProcf]+nscEachPe; if (iProcf < nscLeft) iEnd_save[iProcf]++; iStart_save[iProcf] = iStart_save[iProcf]; iEnd_save[iProcf] = iEnd_save[iProcf]; } // if (iProc == 0){ /* for (iProcf = 0; iProcf < nProcs; iProcf++){ */ /* printf("%d - %d\n", iStart_save[iProcf], iEnd_save[iProcf] - 1) ; */ /* } */ //} // For each main sc, start_ensemble is 0 if the iProc runs this main sc. start_ensemble is 1 is the iProc does not run this main sc. (so each iProc has a different array start_ensemble -> start_ensemble is "iProc-dependent") int *start_ensemble; start_ensemble = malloc(OPTIONS->n_satellites * sizeof(int)); for (ii = 0; ii < OPTIONS->n_satellites; ii++){ if ( (ii >= iStart_save[iProc]) & ( ii < iEnd_save[iProc]) ){ start_ensemble[ii] = 0; } else{ start_ensemble[ii] = 1; } // printf("iProc %d | start_ensemble[%d] %d\n", iProc, ii, start_ensemble[ii]); } // array_sc is the array of sc (main and ensemble sc) run by this iProc. So array_sc is "iProc-dependent": each iProc has a different array array_sc. What array_sc has: the first elt is 0, whatever iProc it is (because it represents main sc. However, it does not mean that all iProc will run a main sc, this is decided later in the code (using start_ensemble)). The next elts (1, 2, ..., OPTIONS->nb_ensemble_min_per_proc) represent the ensemble sc run by this iProc. So for example if there are 20 ensembles and 2 iProc, array_sc is: // for iProc 0: [0, 1, 2, 3, ..., 9, 10] // for iProc 1: [0, 11, 12, 13, ..., 19, 20] int ielt; int *array_sc; array_sc = malloc((OPTIONS->nb_ensemble_min_per_proc + 2) * sizeof(int)); // + 2 (and not + 1) because if there is no ensemble, we still want array_sc[1] to exist (because later in the code we call array_sc[start_ensemble[ii]], and start_ensemble[ii] = 1 if the iProc does not run main sc ii). array_sc[0] = 0; array_sc[1] = -1; // if there is no ensemble, we still want array_sc[1] to exist (because later in the code we call array_sc[start_ensemble[ii]], and start_ensemble[ii] = 1 if the iProc does not run main sc ii). We set to -1 because we want to make sure that if there is no ensemble, eee will never be equal to array_sc[1]. If there are ensembles, array_sc[1] is overwritten right below anyway for ( ielt = 1; ielt < OPTIONS->nb_ensemble_min_per_proc + 1; ielt ++ ){ if (iProc < nProcs_that_are_gonna_run_ensembles){ array_sc[ielt] = iProc * OPTIONS->nb_ensemble_min_per_proc + ielt; } // printf("iProc %d: array_sc[%d] = %d\n", iProc, ielt, array_sc[ielt]); } /* nscEachPe = (OPTIONS->n_satellites)/nProcs; */ /* nscLeft = (OPTIONS->n_satellites) - (nscEachPe * nProcs); */ /* if (iProc == 0){ */ /* printf("XXXXXXXXX\nnscEachPe = %d | nscLeft = %d\nXXXXXXXXX\n", nscEachPe, nscLeft); */ /* } */ // for each main, which_iproc_is_running_main_sc is the iProc that runs it. For example, which_iproc_is_running_main_sc[3] is equal to the iProc that runs the main sc 3. So which_iproc_is_running_main_sc is the same array for all iProc -> which_iproc_is_running_main_sc is not "iProc-dependent" int *which_iproc_is_running_main_sc; which_iproc_is_running_main_sc = malloc( OPTIONS->n_satellites * sizeof(int)); for (ii = 0; ii < OPTIONS->n_satellites; ii++){ for (ccc = 0; ccc < nProcs; ccc++){ if ( ( ii >= iStart_save[ccc] ) && ( ii < iEnd_save[ccc] ) ){ which_iproc_is_running_main_sc[ii] = ccc; } } } /* for (ii = 0; ii < OPTIONS->n_satellites; ii++){ */ /* if (iProc == 0){ */ /* printf("iProc %d | which_iproc_is_running_main_sc[%d] = %d\n", iProc, ii, which_iproc_is_running_main_sc[ii]); */ /* } */ /* } */ /*************************************************************************************/ /*************************************************************************************/ /****************** end of SET THINGS UP FOR PARALLEL PROGRAMMING ********************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /**************************** SPACECRAFTS OTHER THAN GPS *****************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /************************************************************************************/ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- Number of spacecraft: %d\n", OPTIONS->n_satellites - OPTIONS->nb_gps); } for (ii = 0; ii < OPTIONS->n_satellites - OPTIONS->nb_gps; ii++){ // go through all main SC other than GPS CONSTELLATION->aaa_sigma[ii] = OPTIONS->aaa_sigma; CONSTELLATION->aaa_mod[ii] = OPTIONS->aaa_mod[ii]; // printf("ooooooooooooooooo %d %d\n",CONSTELLATION->aaa_mod[0], CONSTELLATION->aaa_mod[1]); // printf(" CONSTELLATION->aaa_mod[%d] %d\n", ii, CONSTELLATION->aaa_mod[ii]); CONSTELLATION->spacecraft[ii] = malloc( ( OPTIONS->nb_ensembles_min + 1 ) * sizeof(SPACECRAFT_T) ); r_alongtrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min ) * sizeof(double) ); r_crosstrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); r_radial_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); v_alongtrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min ) * sizeof(double) ); v_crosstrack_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); v_radial_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); bc_pert_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); srp_pert_all[ii] = malloc( ( OPTIONS->nb_ensembles_min) * sizeof(double) ); if ( CONSTELLATION->spacecraft[ii] == NULL){ printf("***! Could not allow memory to CONSTELLATION->spacecraft[ii]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->sum_sigma_for_f107_average[ii] = malloc( ( OPTIONS->nb_ensemble_min_per_proc * nProcs + 1 ) * sizeof( double ) ); if (CONSTELLATION->sum_sigma_for_f107_average[ii] == NULL){ print_error_any_iproc(iProc, "Not enough memory for sum_sigma_for_f107_average[ii]"); } // Initialize the ensemble parameters srand (time (NULL)); // Initialize the ensemble parameters on COE if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, "oe" ) == 0 )){ // if we run ensembles on the orbital elements sma_sigma = OPTIONS->apogee_alt_sigma[ii] / ( 1 + OPTIONS->eccentricity[ii] ); inclination_sigma = OPTIONS->inclination_sigma[ii] * DEG2RAD; w_sigma = OPTIONS->w_sigma[ii] * DEG2RAD; // argument of perigee (CBV) long_an_sigma = OPTIONS->long_an_sigma[ii] * DEG2RAD; // RAAN (CBV) f_sigma = OPTIONS->f_sigma[ii] * DEG2RAD; // true anomaly (CBV) eccentricity_sigma = OPTIONS->eccentricity_sigma[ii]; } /* if (iProc == 0){ */ /* start_ensemble = 0; */ /* } */ /* else{ */ /* start_ensemble = 1; */ /* } */ // for (eee = start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc; eee< 1 + iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc ; eee++){ // go through all sc (including ensembels, if you run ensembles) other than GPS for ( ielt = 0; ielt < OPTIONS->nb_ensemble_min_per_proc + 1; ielt ++ ){ // go through all sc (including ensembels, if you run ensembles) other than GPS. Each iProc runs OPTIONS->nb_ensemble_min_per_proc ensemble sc. But not all iProc run a main sc. If the iProc runs or not a main sc (and which main sc) is decided in the variable start_ensemble[ii]: if start_ensemble[ii] = 0 for this iProc, then this iProc runs main sc ii. If start_ensemble[ii] = 1 for this iProc, then this iProc does NOT run main sc ii. eee = array_sc[ielt]; // eee represents the sc that is run: eee = 0 represents a main sc. eee > 0 represents an ensemble sc if ( ( start_ensemble[ii] == 0 ) || ( ( start_ensemble[ii] != 0 ) && ( eee > 0 ) ) ){ // if main sc ii is run by this iProc OR ( if this main sc is not run by this iProc and eee corresponds to an ensemble sc (so this iProc does not run main sc ii but runs an ensemble corresponding to main sc ii)) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.isGPS = 0; /* if (iProc == 0){ */ /* printf("iProc %d runs main sc %d and ensemble sc %d\n", iProc, ii, eee); */ /* } */ /* if (iProc == 1){ */ /* printf("iProc: %d | eee = %d | from %d to %d | ii = %d\n", iProc, eee, start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc, iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc, ii); */ /* } */ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /********************* INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE ****************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /************** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC ***********/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ // if (eee == 0){ // eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble) if ( (start_ensemble[ii] == 0) && (eee == 0)){ // if this iProc runs main sc ii and that eee corresponds to the main sc. eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble). start_ensemble[ii] = 0 if main sc is run by this iProc /*************************************************************************************/ /*************************************************************************************/ /********** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY TLE ************/ /*************************************************************************************/ /*************************************************************************************/ if ( (strcmp( OPTIONS->type_orbit_initialisation, "tle" ) == 0 ) || (strcmp(OPTIONS->type_orbit_initialisation, "tle_sgp4" ) == 0 )){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from TLE.\n"); } /*** Convert the TLEs into inertial state (postion, velocity) ***/ // Initialize TLE parameters SpiceInt frstyr = 1961; // do not really care about this line (as long as the spacecrafts are not flying after 2060) // SpiceDouble geophs[8]; int pp; int lineln=0; size_t len = 0; char *line_temp = NULL; // SpiceDouble elems[10]; SpiceDouble state[6]; SpiceDouble epoch_sat; // epoch of TLE of the sat char sat_tle_file_temp[256]; FILE *sat_tle_file; ORBITAL_ELEMENTS_T OE_temp; /* Set up the geophysical quantities. At last check these were the values used by Space Command and SGP4 */ /* PARAMS->geophs[ 0 ] = 1.082616e-3; // J2 */ /* PARAMS->geophs[ 1 ] = -2.53881e-6; // J3 */ /* PARAMS->geophs[ 2 ] = -1.65597e-6; // J4 */ /* PARAMS->geophs[ 3 ] = 7.43669161e-2; // KE */ /* PARAMS->geophs[ 4 ] = 120.0; // QO */ /* PARAMS->geophs[ 5 ] = 78.0; // SO */ /* PARAMS->geophs[ 6 ] = 6378.135; // ER */ /* PARAMS->geophs[ 7 ] = 1.0; // AE */ /* Read in the next two lines from the text file that contains the TLEs. */ //newstructure /* strcpy(sat_tle_file_temp, OPTIONS->dir_input_tle); */ /* strcat(sat_tle_file_temp,"/"); */ strcpy(sat_tle_file_temp,""); //newstructure if ( OPTIONS->one_file_with_tle_of_all_sc == 0) { // one tle per file strcat(sat_tle_file_temp,OPTIONS->tle_initialisation[ii]); sat_tle_file = fopen(sat_tle_file_temp,"r"); } else{ // all tles in one file strcat(sat_tle_file_temp,OPTIONS->tle_initialisation[0]); sat_tle_file = fopen(sat_tle_file_temp,"r"); for (bbb = 0; bbb < ii; bbb++){ // skip the TLEs of the sc before the current sc getline( &line_temp, &len, sat_tle_file ); getline( &line_temp, &len, sat_tle_file ); } } // First line getline( &line_temp, &len, sat_tle_file ); lineln = strlen(line_temp)-1; SpiceChar line[2][lineln]; for (pp = 0; pp<lineln-1 ; pp++) line[0][pp] = line_temp[pp]; line[0][ lineln-1 ] = '\0'; // Second line getline( &line_temp, &len, sat_tle_file ); for (pp = 0; pp<lineln-1 ; pp++) line[1][pp] = line_temp[pp]; line[1][ lineln-1 ] = '\0'; fclose(sat_tle_file); // Convert the elements of the TLE into "elems" and "epoch" that can be then read by the SPICE routine ev2lin_ to convert into the inertial state // zzgetelm(frstyr, line, &epoch_sat,elems); getelm_c( frstyr, lineln, line, &epoch_sat, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems ); CONSTELLATION->spacecraft[ii][0].INTEGRATOR.bstar = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems[2]; // Now propagate the state using ev2lin_ to the epoch of interest extern /* Subroutine */ int ev2lin_(SpiceDouble *, SpiceDouble *, SpiceDouble *, SpiceDouble *); ev2lin_( &epoch_sat, PARAMS->geophs, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems, state ); CONSTELLATION->spacecraft[ii][eee].et = epoch_sat; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = epoch_sat; static doublereal precm[36]; static doublereal invprc[36] /* was [6][6] */; extern /* Subroutine */ int zzteme_(doublereal *, doublereal *); extern /* Subroutine */ int invstm_(doublereal *, doublereal *); extern /* Subroutine */ int mxvg_( doublereal *, doublereal *, integer *, integer *, doublereal *); zzteme_(&CONSTELLATION->spacecraft[ii][eee].et, precm); /* ...now convert STATE to J2000. Invert the state transformation */ /* operator (important to correctly do this). */ invstm_(precm, invprc); static integer c__6 = 6; static doublereal tmpsta[6]; mxvg_(invprc, state, &c__6, &c__6, tmpsta); moved_(tmpsta, &c__6, state); for (pp = 0; pp<3; pp++){ // printf("%f ", state[pp]); CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[pp] = state[pp]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[pp] = state[pp+3]; } /* printf("\n"); */ /* for (pp = 0; pp<3; pp++){ */ /* printf("%f ", state[pp+3]); */ /* } */ /* printf("\n"); */ /* MPI_Finalize();exit(0); */ // Initialize the Keplerian Elements cart2kep( &OE_temp, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu ); CONSTELLATION->spacecraft[ii][eee].OE.sma =OE_temp.sma; CONSTELLATION->spacecraft[ii][eee].OE.eccentricity =OE_temp.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.inclination =OE_temp.inclination; CONSTELLATION->spacecraft[ii][eee].OE.long_an =OE_temp.long_an; CONSTELLATION->spacecraft[ii][eee].OE.w =OE_temp.w; CONSTELLATION->spacecraft[ii][eee].OE.f =OE_temp.f; CONSTELLATION->spacecraft[ii][eee].OE.tp =OE_temp.tp; CONSTELLATION->spacecraft[ii][eee].OE.E =OE_temp.E; CONSTELLATION->spacecraft[ii][eee].OE.ra =OE_temp.ra; CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = OE_temp.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = OE_temp.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.9999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = OE_temp.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.9999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = OE_temp.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.9999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; /* printf("ecc = %e | %e\n", CONSTELLATION->spacecraft[ii][eee].OE.eccentricity, elems[5]); */ /* exit(0); */ radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from TLE.\n"); } } /*************************************************************************************/ /*************************************************************************************/ /********** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE ********/ /*************************************************************************************/ /*************************************************************************************/ if ( strcmp( OPTIONS->type_orbit_initialisation, "oe" ) == 0 ){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from orbital elements.\n"); } CONSTELLATION->spacecraft[ii][eee].et = et; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; // Initialize the Keplerian Elements CONSTELLATION->spacecraft[ii][eee].OE.sma = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ); // semi-major axis (CBV) // printf("sma = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.sma); radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - OPTIONS->eccentricity[ii] ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } CONSTELLATION->spacecraft[ii][eee].OE.inclination = OPTIONS->inclination[ii] * DEG2RAD; CONSTELLATION->spacecraft[ii][eee].OE.w = OPTIONS->w[ii] * DEG2RAD; // argument of perigee (CBV) CONSTELLATION->spacecraft[ii][eee].OE.long_an = OPTIONS->long_an[ii] * DEG2RAD; // RAAN (CBV) CONSTELLATION->spacecraft[ii][eee].OE.f = OPTIONS->f[ii] * DEG2RAD; // true anomaly (CBV) CONSTELLATION->spacecraft[ii][eee].OE.eccentricity = OPTIONS->eccentricity[ii]; CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = fmod(CONSTELLATION->spacecraft[ii][eee].OE.w + CONSTELLATION->spacecraft[ii][eee].OE.f, 2*M_PI); // Initialize the inertial state kep2cart( CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, &PARAMS->EARTH.GRAVITY.mu, &CONSTELLATION->spacecraft[ii][eee].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV) // !!!!!!!!!!!!!!!!!!!!!! REMOVE TWO LINES BELOW!!!!!!!!! /* // for molniya */ /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = -1529.8942870000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = -2672.8773570000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = -6150.1153400000; */ /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = 8.7175180000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = -4.9897090000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = 0.0000000000; */ /* // for geo */ /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = 36607.3548590000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = -20921.7217480000; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = -0.0000000000; */ /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = 1.5256360000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = 2.6694510000; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = 0.0000000000; */ // for iss /* CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = -4467.3083710453; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = -5053.5032161387; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = -427.6792780851; */ /* CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = 3.8279470371; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = -2.8757493806; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = -6.0045254246; */ // !!!!!!!!!!!!!!!!!!!!!! END OF REMOVE TWO LINES BELOW!!!!!!!!! // Right ascension CONSTELLATION->spacecraft[ii][eee].OE.ra = atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]); if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){ CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ; } // !!!!!!!!!!!!!!!!!!!!!!!!!! THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT! /* if ( strcmp( OPTIONS->type_orbit_initialisation, "oe" ) == 0 ){ */ /* if ( ii > 0){ */ /* v_copy( CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[0][0].r_i2cg_INRTL); */ /* v_copy( CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[0][0].v_i2cg_INRTL); */ /* CONSTELLATION->spacecraft[ii][0].OE.sma = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[0] ) / ( 1 + OPTIONS->eccentricity[0] ); // semi-major axis (CBV) */ /* // printf("sma = %f\n", CONSTELLATION->spacecraft[ii][0].OE.sma); */ /* radius_perigee = CONSTELLATION->spacecraft[ii][0].OE.sma * ( 1 - OPTIONS->eccentricity[0] ); */ /* if (radius_perigee < PARAMS->EARTH.radius){ */ /* printf("The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); */ /* exit(0); */ /* } */ /* CONSTELLATION->spacecraft[ii][0].OE.inclination = OPTIONS->inclination[0] * DEG2RAD; */ /* CONSTELLATION->spacecraft[ii][0].OE.w = OPTIONS->w[0] * DEG2RAD; // argument of perigee (CBV) */ /* CONSTELLATION->spacecraft[ii][0].OE.long_an = OPTIONS->long_an[0] * DEG2RAD; // RAAN (CBV) */ /* CONSTELLATION->spacecraft[ii][0].OE.f = OPTIONS->f[0] * DEG2RAD; // true anomaly (CBV) */ /* CONSTELLATION->spacecraft[ii][0].OE.eccentricity = OPTIONS->eccentricity[0]; */ /* CONSTELLATION->spacecraft[ii][0].OE.ra = atan2(CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[0]); */ /* if ( CONSTELLATION->spacecraft[ii][0].OE.ra < 0){ */ /* CONSTELLATION->spacecraft[ii][0].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][0].OE.ra ; */ /* } */ /* } */ /* } */ // !!!!!!!!!!!!!!!!!!!!!!!!!! END OF THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT! if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from orbital elements.\n"); } } // end of initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE /*************************************************************************************/ /*************************************************************************************/ /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECEF STATE (position and velocity in ECEF) **/ /*************************************************************************************/ /*************************************************************************************/ if ( strcmp( OPTIONS->type_orbit_initialisation, "state_ecef" ) == 0 ){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, orbital elements from ECEF state (position and velocity).\n"); } CONSTELLATION->spacecraft[ii][eee].et = et; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; // ECEF position and velocity CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0] = OPTIONS->x_ecef[ii]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1] = OPTIONS->y_ecef[ii]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2] = OPTIONS->z_ecef[ii]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0] = OPTIONS->vx_ecef[ii]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1] = OPTIONS->vy_ecef[ii]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2] = OPTIONS->vz_ecef[ii]; // ECI position and velocity estate[0] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0];estate[1] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1];estate[2] = CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2]; estate[3] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0];estate[4] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1];estate[5] = CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2]; sxform_c ( PARAMS->EARTH.earth_fixed_frame, "J2000", CONSTELLATION->spacecraft[ii][eee].et, xform ); mxvg_c ( xform, estate, 6, 6, jstate ); CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = jstate[0]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = jstate[1]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = jstate[2]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = jstate[3]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = jstate[4]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = jstate[5]; /* pxform_c( PARAMS->EARTH.earth_fixed_frame, "J2000", CONSTELLATION->spacecraft[ii][eee].et, T_ECEF_to_J2000); */ /* m_x_v(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, T_ECEF_to_J2000, CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF); */ /* m_x_v(CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, T_ECEF_to_J2000, CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF); */ // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, orbital elements from ECEF state (position and velocity).\n"); } } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECEF STATE /*************************************************************************************/ /*************************************************************************************/ /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY ECI STATE (position and velocity in ECI) **/ /*************************************************************************************/ /*************************************************************************************/ if ( strcmp( OPTIONS->type_orbit_initialisation, "state_eci" ) == 0 ){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state (position and velocity).\n"); } CONSTELLATION->spacecraft[ii][eee].et = et; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; // ECI position and velocity CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii]; // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF from ECI state (position and velocity).\n"); } } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECI STATE /*************************************************************************************/ /*************************************************************************************/ /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY ECI STATE FROM COLLISION INPUT FILE (position and velocity in ECI) **/ /*************************************************************************************/ /*************************************************************************************/ if ( (strcmp( OPTIONS->type_orbit_initialisation, "collision" ) == 0 ) || (strcmp( OPTIONS->type_orbit_initialisation, "collision_vcm" ) == 0 )){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state reead from the input collision file (position and velocity).\n"); } if (strcmp( OPTIONS->type_orbit_initialisation, "collision" ) == 0 ){ CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; CONSTELLATION->spacecraft[ii][eee].et = et; } else{ CONSTELLATION->spacecraft[ii][eee].et = OPTIONS->et_vcm[ii]; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->et_vcm[ii]; // the eoch time of the two VCMs are different /* if ( (OPTIONS->et_vcm[ii] > OPTIONS->swpc_et_first_prediction) && (OPTIONS->swpc_need_predictions == 1)){// overwrite aaa_mod written before */ /* previous_index( &OPTIONS->aaa_mod, OPTIONS->et_mod_f107_ap, OPTIONS->et_interpo[0] - OPTIONS->swpc_et_first_prediction, ( OPTIONS->nb_time_steps + (int)(( 2 * 24 * 3600. ) / OPTIONS->dt))); */ /* CONSTELLATION->aaa_mod[ii] = OPTIONS->aaa_mod + OPTIONS->et_vcm[ii] - CONSTE; */ /* } */ /* else{ */ /* CONSTELLATION->aaa_mod[ii] = 0; */ /* " */ } // ECI position and velocity CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii]; // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from ECI state reead from the input collision file (position and velocity).\n"); } } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, r_ecef2cg_ECEF, v_ecef2cg_ECEF, OE FOR MAIN SC BY ECI STATE FROM COLLISION INPUT FILE /*************************************************************************************/ /*************************************************************************************/ /** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY DEPLOYMENT **/ /*************************************************************************************/ /*************************************************************************************/ if ( strcmp( OPTIONS->type_orbit_initialisation, "deployment" ) == 0 ){ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from a deployment module.\n"); } CONSTELLATION->spacecraft[ii][eee].et = et; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; // Convert the deployment module orbital elements in ECI coordinates ORBITAL_ELEMENTS_T deployment_module_orbital_elements; deployment_module_orbital_elements.sma = ( PARAMS->EARTH.radius + OPTIONS->deployment_module_orbital_elements[ii][0] ) / ( 1 + OPTIONS->deployment_module_orbital_elements[ii][5] ); radius_perigee = deployment_module_orbital_elements.sma * ( 1 - OPTIONS->deployment_module_orbital_elements[ii][5] ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } deployment_module_orbital_elements.inclination = OPTIONS->deployment_module_orbital_elements[ii][1] * DEG2RAD; deployment_module_orbital_elements.w = OPTIONS->deployment_module_orbital_elements[ii][2] * DEG2RAD; deployment_module_orbital_elements.long_an = OPTIONS->deployment_module_orbital_elements[ii][3] * DEG2RAD; deployment_module_orbital_elements.f = OPTIONS->deployment_module_orbital_elements[ii][4] * DEG2RAD; deployment_module_orbital_elements.eccentricity = OPTIONS->deployment_module_orbital_elements[ii][5]; // printf("%f %f %f %f %f %f %f\n", OPTIONS->deployment_module_orbital_elements[ii][0], deployment_module_orbital_elements.sma,deployment_module_orbital_elements.inclination*RAD2DEG,deployment_module_orbital_elements.w,deployment_module_orbital_elements.long_an,deployment_module_orbital_elements.f,deployment_module_orbital_elements.eccentricity); double eci_position_deployment_module[3]; double eci_velocity_deployment_module[3]; kep2cart(eci_position_deployment_module, eci_velocity_deployment_module, &PARAMS->EARTH.GRAVITY.mu, &deployment_module_orbital_elements); // Convert the deployment velocity of the satellite from the deployment module LVLH coordinate system to ECI velocity double velocity_satellte_deployed_lvlh[3]; double velocity_satellte_deployed_eci[3]; velocity_satellte_deployed_lvlh[0] = OPTIONS->deployment_speed[ii] * cos(OPTIONS->deployment_angle[ii]*DEG2RAD) / 1000.; // / 1000. because the input is in m/s but we want km/s velocity_satellte_deployed_lvlh[1] = -OPTIONS->deployment_speed[ii] * sin(OPTIONS->deployment_angle[ii]*DEG2RAD) / 1000.; // "-" because LVLH _Y points to the left and we are considering that an angle of for example 30 degrees is counted from the in-track direction to the right (clockwise). If the sc is ejected to the left with an angle of for example 90 degrees, then deployment_angle is equal to 270 degrees velocity_satellte_deployed_lvlh[2] = 0; // for now we assume the satellites are deployed in the LVLH_X/Y plane double T_inrtl_2_lvlh_for_deployment[3][3]; double T_lvlh_2_inrtl_for_deployment[3][3]; compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh_for_deployment, eci_position_deployment_module, eci_velocity_deployment_module); m_trans(T_lvlh_2_inrtl_for_deployment, T_inrtl_2_lvlh_for_deployment); m_x_v(velocity_satellte_deployed_eci, T_lvlh_2_inrtl_for_deployment, velocity_satellte_deployed_lvlh); // Add deployment velocity of the satellite to the velocity of the deployment module (in ECI) v_add(CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, eci_velocity_deployment_module, velocity_satellte_deployed_eci); // ECI position of the satellite is the same as the ECI position of the deployment module v_copy(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, eci_position_deployment_module); // Right ascension CONSTELLATION->spacecraft[ii][eee].OE.ra = atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]); if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){ CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ; } // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL, orbital elements from a deployment module.\n"); } } // end of initializing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY DEPLOYMENT for (ccc = 0; ccc < nProcs; ccc++){ // the iProc that runs main sc ii sends to the other iProc (that do not run main sc ii) the orbital elements of main sc ii if (ccc != iProc){ MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); // printf("iProc %d sends to iProc %d for ii = %d\n", iProc, ccc, ii); } } /* if (nProcs > 1){ */ /* for (ccc = 0; ccc < nProcs; ccc++){ */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* MPI_Send(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); */ /* // printf("Sent to %d (out of %d)\n", ccc, nProcs); */ /* } */ /* } */ /* if (iProc == 0) printf("BEFORE\n"); */ /* MPI_Barrier(MPI_COMM_WORLD); */ /* if (iProc == 0) printf("RIG after\n"); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.inclination , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.w , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.long_an , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* MPI_Bcast(&CONSTELLATION->spacecraft[ii][0].OE.f , 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); */ /* if (iProc == 0) printf("AFTER\n"); */ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC by iProc 0 (voluntarily prnting all iProc here). (iProc %d)\n", iProc); } }// end of initiliazing et, r_i2cg_INRTL, v_i2cg_INRTL, OE FOR MAIN SC BY COE and TLE /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /************** INITIALIZE: et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions FOR ENSEMBLE SC ***********/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ else if ( ( start_ensemble[ii] != 0 ) && ( eee == array_sc[start_ensemble[ii]] ) ){// if this iProc is not runnning the main sc, then receives the orbital elements of main sc ii, which was run (and sent) by iProc which_iproc_is_running_main_sc[ii] (eee = array_sc[start_ensemble[ii]] is so that you receive only once) MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.inclination, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.w, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.long_an, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.f, 1, MPI_DOUBLE, which_iproc_is_running_main_sc[ii], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // printf("iProc %d receives from iProc %d for ii = %d\n", iProc, which_iproc_is_running_main_sc[ii], ii); } if (eee > 0){ // here eee > 0 so we are initializing et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions for the sc from an ensemble /* if (nProcs > 1){ */ /* if ( iProc > 0){ */ /* if (eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc){ // only receives this one time */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.sma, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.eccentricity, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.inclination, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.w, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.long_an, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* MPI_Recv(&CONSTELLATION->spacecraft[ii][0].OE.f, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); */ /* } */ /* } */ /* } */ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing et, r_i2cg_INRTL, v_i2cg_INRTL for ensemble spacecraft.\n"); } if (strcmp( OPTIONS->type_orbit_initialisation, "collision_vcm" ) == 0 ){ CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->et_vcm[ii]; // the eoch time of the two VCMs are different CONSTELLATION->spacecraft[ii][eee].et = OPTIONS->et_vcm[ii]; } else{ CONSTELLATION->spacecraft[ii][eee].et_sc_initial = et; CONSTELLATION->spacecraft[ii][eee].et = CONSTELLATION->et; } // COLLISION CONSTELLATION->spacecraft[ii][eee].number_of_collisions = 0; // end of COLLISION /*****************************************************************************************************************************/ /********************************************************* ENSEMBLES ON COE **************************************************/ /*****************************************************************************************************************************/ if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, "oe" ) == 0 )){ // initialize COE if we run ensembles on the COE // Initiate the COE to each ensemble as the same COE as for the spacecraft CONSTELLATION->spacecraft[ii][eee].OE.sma = ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ); // semi-major axis (CBV) CONSTELLATION->spacecraft[ii][eee].OE.inclination = OPTIONS->inclination[ii] * DEG2RAD; CONSTELLATION->spacecraft[ii][eee].OE.w = OPTIONS->w[ii] * DEG2RAD; CONSTELLATION->spacecraft[ii][eee].OE.long_an = OPTIONS->long_an[ii] * DEG2RAD; CONSTELLATION->spacecraft[ii][eee].OE.f = OPTIONS->f[ii] * DEG2RAD; CONSTELLATION->spacecraft[ii][eee].OE.eccentricity = OPTIONS->eccentricity[ii]; // For each COE to ensemble, replace it by a random normal number // eccentricity if ( OPTIONS->coe_to_ensemble[ii][0] == 1 ) { CONSTELLATION->spacecraft[ii][eee].OE.eccentricity = randn( OPTIONS->eccentricity[ii], eccentricity_sigma ); // printf("eccentricity = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.eccentricity); } // true anomaly if ( OPTIONS->coe_to_ensemble[ii][1] == 1 ) { CONSTELLATION->spacecraft[ii][eee].OE.f = randn( OPTIONS->f[ii] * DEG2RAD, f_sigma ); // printf("true ano = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.f * RAD2DEG); } // RAAN if ( OPTIONS->coe_to_ensemble[ii][2] == 1 ){ CONSTELLATION->spacecraft[ii][eee].OE.long_an = randn( OPTIONS->long_an[ii] * DEG2RAD, long_an_sigma ); // printf("RANN = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.long_an * RAD2DEG); } // argument of perigee if ( OPTIONS->coe_to_ensemble[ii][3] == 1 ) { CONSTELLATION->spacecraft[ii][eee].OE.w = randn( OPTIONS->w[ii] * DEG2RAD, w_sigma ); // printf("argument of perigee = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.w * RAD2DEG); } // inclination if ( OPTIONS->coe_to_ensemble[ii][4] == 1 ) { CONSTELLATION->spacecraft[ii][eee].OE.inclination = randn( OPTIONS->inclination[ii] * DEG2RAD, inclination_sigma ); // printf("inclination = %f\n",CONSTELLATION->spacecraft[ii][eee].OE.inclination * RAD2DEG); } // semi-major axis if ( OPTIONS->coe_to_ensemble[ii][5] == 1 ) { CONSTELLATION->spacecraft[ii][eee].OE.sma = randn( ( PARAMS->EARTH.radius + OPTIONS->apogee_alt[ii] ) / ( 1 + OPTIONS->eccentricity[ii] ), sma_sigma ); // printf("sma = %f\n", CONSTELLATION->spacecraft[ii][eee].OE.sma ); } } else if (( OPTIONS->nb_ensembles > 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, "state_eci" ) == 0 )){ // initialize state eci and OE if we run ensembles on state eci CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = randn( OPTIONS->x_eci[ii], OPTIONS->x_eci_sigma[ii] ); CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = randn( OPTIONS->y_eci[ii], OPTIONS->y_eci_sigma[ii] ); CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = randn( OPTIONS->z_eci[ii], OPTIONS->z_eci_sigma[ii] ); CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = randn( OPTIONS->vx_eci[ii], OPTIONS->vx_eci_sigma[ii] ); CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = randn( OPTIONS->vy_eci[ii], OPTIONS->vy_eci_sigma[ii] ); CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = randn( OPTIONS->vz_eci[ii], OPTIONS->vz_eci_sigma[ii] ); // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } } else if (( OPTIONS->nb_ensembles > 0 ) && (( strcmp(OPTIONS->type_orbit_initialisation, "collision" ) == 0 ) || ( strcmp(OPTIONS->type_orbit_initialisation, "collision_vcm" ) == 0 ) )){ // initialize state eci and OE if we run ensembles on state eci from a collision input file if ( strcmp(OPTIONS->type_orbit_initialisation, "collision_vcm" ) == 0 ){ // GOOD REFERENCE: http://www.prepacom.net/HEC2/math/cours/Changement%20de%20bases.pdf // generate random uncertainties from teh eigenvalues. These uncertainties corresponds to the the basis of the principal axes of the ellipsoid /* // !!!!!!! DELETE BLOCK BELOW AND UNCOMMENT THE ONE BELOW IT */ /* struct timeval t1; */ /* gettimeofday(&t1, NULL); */ /* seed = t1.tv_usec * t1.tv_sec;// time (NULL) + iProc; //\* getpid(); */ /* gsl_rng_set (r_gaussian_generator, seed); // set seed */ /* collision_equinoctial_sigma_in_diag_basis[0] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[1] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[2] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[3] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[4] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[5] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5] ) ); */ collision_equinoctial_sigma_in_diag_basis[0] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0] ) ); collision_equinoctial_sigma_in_diag_basis[1] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1] ) ); collision_equinoctial_sigma_in_diag_basis[2] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2] ) ); collision_equinoctial_sigma_in_diag_basis[3] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] ) ); collision_equinoctial_sigma_in_diag_basis[4] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4] ) ); collision_equinoctial_sigma_in_diag_basis[5] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5] ) ); /* collision_equinoctial_sigma_in_diag_basis[6] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][6] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[7] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][7] ) ); */ /* collision_equinoctial_sigma_in_diag_basis[8] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][8] ) ); */ // convert thes e unertainties rfom the ellipsoid basis to ECI p m_x_v6( collision_equinoctial_sigma_in_equinoctial_basis, OPTIONS->rotation_matrix_for_diagonalization[ii], collision_equinoctial_sigma_in_diag_basis ); /// !!!!! maybe invert of rotation_matrix_for_diagonalization? /* // printf("\n"); */ /* for (ccc = 0; ccc < 6; ccc++){ */ /* collision_equinoctial_sigma_in_equinoctial_basis[ccc] = collision_equinoctial_sigma_in_equinoctial_basis[ccc] / 1000.; // / 1000. to convert the eigenvalues from m to km (or from m/s to km/s) */ /* // printf("%15.10e %15.10e %d %d %d\n", collision_equinoctial_sigma_in_equinoctial_basis[ccc], OPTIONS->eigenvalue_covariance_matrix[ii][ccc] / 1000. ,eee, ccc, ii); */ /* } */ double af, ag, lequin, nequin, chi, psi; double af_mean, ag_mean, lequin_mean, nequin_mean, chi_mean, psi_mean; // calculate the mean equinotication elemnts (ie the eq elts of the mean psoiton and velcoity) double mu = 398600.4418; // km^3/s^2 (ideally, should read from propagator.c -> load_params but the call to load_params is later) double fr; // fr is 1 for prograde orbits, -1 for retrograde orbits. !!!! this is a convention, but there are others that assume fr to be 1 all the time. make sure that the VCM was generated using the same convention ORBITAL_ELEMENTS_T oe_temp; double rvec[3], vvec[3]; rvec[0] = OPTIONS->x_eci[ii]; rvec[1] = OPTIONS->y_eci[ii]; rvec[2] = OPTIONS->z_eci[ii]; vvec[0] = OPTIONS->vx_eci[ii]; vvec[1] = OPTIONS->vy_eci[ii]; vvec[2] = OPTIONS->vz_eci[ii]; cart2kep(&oe_temp, rvec, vvec, OPTIONS->et_vcm[ii] , mu); if (oe_temp.inclination <= M_PI/2.){ fr = 1; } else{ fr = -1; } cart_to_equin( &af_mean, &ag_mean, &lequin_mean, &nequin_mean, &chi_mean, &psi_mean, mu, fr, rvec, vvec); // r and v in km km/s af = af_mean + collision_equinoctial_sigma_in_equinoctial_basis[0]; ag = ag_mean + collision_equinoctial_sigma_in_equinoctial_basis[1]; lequin = lequin_mean + collision_equinoctial_sigma_in_equinoctial_basis[2]; nequin = nequin_mean + collision_equinoctial_sigma_in_equinoctial_basis[3] * nequin_mean; // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here chi = chi_mean + collision_equinoctial_sigma_in_equinoctial_basis[4]; psi = psi_mean + collision_equinoctial_sigma_in_equinoctial_basis[5]; // bc and srp for the main sc will be calcucalted later CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_cdm[ii] + randn( 0, (OPTIONS->bc_cdm_std[ii])); //OPTIONS->bc_vcm[ii] + randn( 0, sqrt(OPTIONS->covariance_matrix_equinoctial[ii][6][6])) * OPTIONS->bc_vcm[ii]; // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_cdm[ii] + randn( 0, (OPTIONS->srp_cdm_std[ii])); //OPTIONS->srp_vcm[ii] + randn( 0, sqrt(OPTIONS->covariance_matrix_equinoctial[ii][8][8])) * OPTIONS->srp_vcm[ii]; // elemts of the covaraicen amtrix in the VCM were adimentionless, ie divied by their mean value. so need to multiply here ([7] is for bdot) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg double rvec_pert[3], vvec_pert[3]; equin_to_cart(rvec_pert, vvec_pert, af, ag, lequin, nequin, chi, psi, mu, fr); CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = rvec_pert[0]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = rvec_pert[1]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = rvec_pert[2]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = vvec_pert[0]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = vvec_pert[1]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = vvec_pert[2]; /* v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, "r_pert"); */ /* v_print(rvec, "r_mean"); */ double dr_pert[3], dr_pert_lvlh[3]; double dv_pert[3], dv_pert_lvlh[3]; v_sub(dr_pert, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, rvec); v_sub(dv_pert, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, vvec); double T_inrtl_2_lvlh_pert[3][3]; compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh_pert, rvec, vvec); m_x_v(dr_pert_lvlh, T_inrtl_2_lvlh_pert, dr_pert); m_x_v(dv_pert_lvlh, T_inrtl_2_lvlh_pert, dv_pert); /* v_print(dr_pert_lvlh, "dr_lvlh"); */ /* v_print(dv_pert_lvlh, "dv_lvlh"); */ r_alongtrack_all[ii][eee] = dr_pert_lvlh[0]; r_crosstrack_all[ii][eee] = dr_pert_lvlh[1]; r_radial_all[ii][eee] = dr_pert_lvlh[2]; v_alongtrack_all[ii][eee] = dv_pert_lvlh[0]; v_crosstrack_all[ii][eee] = dv_pert_lvlh[1]; v_radial_all[ii][eee] = dv_pert_lvlh[2]; bc_pert_all[ii][eee] = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm; srp_pert_all[ii][eee] = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm; // bc_pert_all[ii][eee] = /* if ( ( ii == 0 ) && ( eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc ) ){ */ /* printf("delta_vx_eci: %.10e - delta_vx_diag: %.10e - eee: %d - iProc: %d - vxsigma: %e - total vx_eci: %.10e\n", collision_equinoctial_sigma_in_equinoctial_basis[3], collision_equinoctial_sigma_in_diag_basis[3]/1000., eee, iProc, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] )/1000., CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] ); */ /* // m_print6(OPTIONS->inverse_rotation_matrix_for_diagonalization[ii], "OPTIONS->inverse_rotation_matrix_for_diagonalization[ii]"); */ /* } */ // This will be used to save position of sc in the time span of the TCA if collisions assessment is on CONSTELLATION->spacecraft[ii][eee].ispan = 0; // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = CONSTELLATION->spacecraft[ii][eee].OE.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = CONSTELLATION->spacecraft[ii][eee].OE.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } } else if ( strcmp(OPTIONS->type_orbit_initialisation, "collision" ) == 0 ){ // GOOD REFERENCE: http://www.prepacom.net/HEC2/math/cours/Changement%20de%20bases.pdf // generate random uncertainties from teh eigenvalues. These uncertainties corresponds to the the basis of the principal axes of the ellipsoid /* // !!!!!!! DELETE BLOCK BELOW AND UNCOMMENT THE ONE BELOW IT */ /* struct timeval t1; */ /* gettimeofday(&t1, NULL); */ /* seed = t1.tv_usec * t1.tv_sec;// time (NULL) + iProc; //\* getpid(); */ /* gsl_rng_set (r_gaussian_generator, seed); // set seed */ /* collision_eci_sigma_in_diag_basis[0] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0] ) ); */ /* collision_eci_sigma_in_diag_basis[1] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1] ) ); */ /* collision_eci_sigma_in_diag_basis[2] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2] ) ); */ /* collision_eci_sigma_in_diag_basis[3] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] ) ); */ /* collision_eci_sigma_in_diag_basis[4] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4] ) ); */ /* collision_eci_sigma_in_diag_basis[5] = gsl_ran_gaussian(r_gaussian_generator, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5] ) ); */ collision_eci_sigma_in_diag_basis[0] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][0] ) ); collision_eci_sigma_in_diag_basis[1] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][1] ) ); collision_eci_sigma_in_diag_basis[2] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][2] ) ); collision_eci_sigma_in_diag_basis[3] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] ) ); collision_eci_sigma_in_diag_basis[4] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][4] ) ); collision_eci_sigma_in_diag_basis[5] = randn( 0, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][5] ) ); // convert thes e unertainties rfom the ellipsoid basis to ECI p m_x_v6( collision_eci_sigma_in_eci_basis, OPTIONS->rotation_matrix_for_diagonalization[ii], collision_eci_sigma_in_diag_basis ); // printf("\n"); for (ccc = 0; ccc < 6; ccc++){ collision_eci_sigma_in_eci_basis[ccc] = collision_eci_sigma_in_eci_basis[ccc] / 1000.; // / 1000. to convert the eigenvalues from m to km (or from m/s to km/s) // printf("%15.10e %15.10e %d %d %d\n", collision_eci_sigma_in_eci_basis[ccc], OPTIONS->eigenvalue_covariance_matrix[ii][ccc] / 1000. ,eee, ccc, ii); } CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0] = OPTIONS->x_eci[ii] + collision_eci_sigma_in_eci_basis[0]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1] = OPTIONS->y_eci[ii] + collision_eci_sigma_in_eci_basis[1]; CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2] = OPTIONS->z_eci[ii] + collision_eci_sigma_in_eci_basis[2]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] = OPTIONS->vx_eci[ii] + collision_eci_sigma_in_eci_basis[3]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1] = OPTIONS->vy_eci[ii] + collision_eci_sigma_in_eci_basis[4]; CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2] = OPTIONS->vz_eci[ii] + collision_eci_sigma_in_eci_basis[5]; /* if ( ( ii == 0 ) && ( eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc ) ){ */ /* printf("delta_vx_eci: %.10e - delta_vx_diag: %.10e - eee: %d - iProc: %d - vxsigma: %e - total vx_eci: %.10e\n", collision_eci_sigma_in_eci_basis[3], collision_eci_sigma_in_diag_basis[3]/1000., eee, iProc, sqrt( OPTIONS->eigenvalue_covariance_matrix[ii][3] )/1000., CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0] ); */ /* // m_print6(OPTIONS->inverse_rotation_matrix_for_diagonalization[ii], "OPTIONS->inverse_rotation_matrix_for_diagonalization[ii]"); */ /* } */ // This will be used to save position of sc in the time span of the TCA if collisions assessment is on CONSTELLATION->spacecraft[ii][eee].ispan = 0; // Orbital elements cart2kep( &CONSTELLATION->spacecraft[ii][eee].OE, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].et, PARAMS->EARTH.GRAVITY.mu); radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][eee].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } } } // end of initialize state eci and OE if we run ensembles on state eci from a collision input file else { // initialize COE if we do not run ensembles on the orbital elements or on state eci (including collision case) CONSTELLATION->spacecraft[ii][eee].OE.sma = CONSTELLATION->spacecraft[ii][0].OE.sma; // semi-major axis (CBV) // printf("sma = %f\n", CONSTELLATION->spacecraft[ii][0].OE.sma); radius_perigee = CONSTELLATION->spacecraft[ii][eee].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][0].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } CONSTELLATION->spacecraft[ii][eee].OE.inclination = CONSTELLATION->spacecraft[ii][0].OE.inclination ; CONSTELLATION->spacecraft[ii][eee].OE.w = CONSTELLATION->spacecraft[ii][0].OE.w ; // argument of perigee (CBV) CONSTELLATION->spacecraft[ii][eee].OE.long_an = CONSTELLATION->spacecraft[ii][0].OE.long_an ; // RAAN (CBV) CONSTELLATION->spacecraft[ii][eee].OE.f = CONSTELLATION->spacecraft[ii][0].OE.f ; // true anomaly (CBV) CONSTELLATION->spacecraft[ii][eee].OE.eccentricity = CONSTELLATION->spacecraft[ii][0].OE.eccentricity; } // end of initialize COE if we do not run ensembles on the orbital elements or on state eci (including collision case) if ( ( OPTIONS->nb_ensembles <= 0 ) || ( ( strcmp(OPTIONS->type_orbit_initialisation, "state_eci" ) != 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, "collision" ) != 0 ) && ( strcmp(OPTIONS->type_orbit_initialisation, "collision_vcm" ) != 0 ) ) ){ // intialize eci r/v if we do not run ensembles on state eci or on collision // Initialize the inertial state kep2cart( CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, &PARAMS->EARTH.GRAVITY.mu, &CONSTELLATION->spacecraft[ii][eee].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV) // Right ascension CONSTELLATION->spacecraft[ii][eee].OE.ra = atan2(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1], CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0]); if ( CONSTELLATION->spacecraft[ii][eee].OE.ra < 0){ CONSTELLATION->spacecraft[ii][eee].OE.ra = 2*M_PI + CONSTELLATION->spacecraft[ii][eee].OE.ra ; } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing et, r_i2cg_INRTL, v_i2cg_INRTL for ensemble spacecraft.\n"); } } // end of intialize eci r/v if we do not run ensembles on state eci or on collision } // end of the initialization of et, r_i2cg_INRTL, v_i2cg_INRTL, OE, number_of_collisions for the sc from an ensemble /*************************************************************************************/ /*************************************************************************************/ /************* COE AND TLE INITIALIZE for main SC and for ensemble SC: - r_ecef2cg_ECEF, v_ecef2cg_ECEF - geodetic - filename, filenameecef, filenameout, filenamepower for main SC ONLY - name_sat - INTEGRATOR: dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar, sc_main_nb, sc_ensemble_nb **************/ /*************************************************************************************/ /*************************************************************************************/ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing r_ecef2cg_ECEF, v_ecef2cg_ECEF, geodetic, output file names, name_sat, dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\n"); } CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.sc_main_nb = ii; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.sc_ensemble_nb = eee; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.initialize_geo_with_bstar = OPTIONS->initialize_geo_with_bstar; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.coll_vcm = OPTIONS->coll_vcm; // !!!! REMOVE BLOCK BELOW // OPTIONS->bc_vcm_std[ii] = 0.23 * OPTIONS->bc_vcm[ii]; //OPTIONS->srp_vcm_std[ii] = 0;//0.23 * OPTIONS->srp_vcm[ii]; // !!!! END OF REMOVE BLOCK BELOW if (eee == 0){ // bc_vcm and srp_vcm were calculated prevously (eigen value block). here only the main sc /// CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_vcm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg // CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_vcm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_cdm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_cdm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg CONSTELLATION->spacecraft[ii][eee].already_output_cd_ensemble = 0; CONSTELLATION->spacecraft[ii][eee].already_output_srp_ensemble = 0; // printf("MAIN %d %d %e (%e) %e (%e)\n", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm * 1e6, OPTIONS->bc_vcm_std[ii], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm * 1e6, OPTIONS->srp_vcm_std[ii]); } /* else{ */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = fabs(randn(OPTIONS->bc_vcm[ii], OPTIONS->bc_vcm_std[ii])); */ /* // printf("bc sc[%d][%d] %e %e\n", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm, OPTIONS->bc_vcm[ii]); */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = fabs(randn(OPTIONS->srp_vcm[ii], OPTIONS->srp_vcm_std[ii])); */ /* //printf("srp sc[%d][%d] %e %e\n", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm, OPTIONS->srp_vcm[ii]); */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg */ /* } */ // uncomment block below to ingore uncertainties in Bc or SRP /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.bc_vcm = OPTIONS->bc_vcm[ii] / 1000. / 1000.; // OPTIONS->bc_vcm in m2/kg. convert in km2/kg */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.srp_vcm = OPTIONS->srp_vcm[ii] / 1000. / 1000.; // OPTIONS->srp_vcm in m2/kg. convert in km2/kg */ /* // end of uncomment block below to ingore uncertainties in Bc or SRP */ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.et_vcm = OPTIONS->et_vcm[ii]; /* // Initialize the geodetic state- */ /* if (iDebugLevel >= 2){ */ /* if (iProc == 0) printf("--- (initialize_constellation) Initializing geodetic for all spacecraft.\n"); */ /* } */ /* eci2lla(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL , CONSTELLATION->spacecraft[ii][eee].et, geodetic ); */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude = geodetic[2]; */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude = geodetic[0]; */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude = geodetic[1]; */ /* if (iDebugLevel >= 2){ */ /* if (iProc == 0) printf("--- (initialize_constellation) Done initializing geodetic for all spacecraft.\n"); */ /* } */ // Initialize the planet fixed state if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Initializing r_ecef2cg_ECEF and v_ecef2cg_ECEF for all spacecraft.\n"); } if ( strcmp( OPTIONS->type_orbit_initialisation, "state_ecef" ) != 0 ){ // already initialized if state_ecef chosen by user /* geodetic_to_geocentric(PARAMS->EARTH.flattening, */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude, */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude, */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude, */ /* PARAMS->EARTH.radius, */ /* CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF) ; */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, "ECI"); */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, "ECEF"); */ /* printf("(%f, %f) # %f\n", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */ estate[0] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[0];estate[1] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[1];estate[2] = CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL[2]; estate[3] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[0];estate[4] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[1];estate[5] = CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL[2]; sxform_c ( "J2000", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][eee].et, xform ); mxvg_c ( xform, estate, 6, 6, jstate ); CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[0] = jstate[0]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[1] = jstate[1]; CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF[2] = jstate[2]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[0] = jstate[3]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[1] = jstate[4]; CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF[2] = jstate[5]; /* v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, "ECI"); */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, "ECEF"); */ /* v_print(CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF, "velocity ECEF"); */ /* printf("(%f, %f) # %f\n", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */ } /* double T_J2000_to_ECEF[3][3]; */ /* printf("CONSTELLATION->spacecraft[ii][eee].et = %f\n",CONSTELLATION->spacecraft[ii][eee].et); */ /* pxform_c( "J2000", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][eee].et, T_J2000_to_ECEF); // Return the matrix (here T_J2000_to_ECEF) that transforms position vectors from one specified frame (here J2000) to another (here ITRF93) at a specified epoch (in /Users/cbv/cspice/src/cspice/pxform_c.c) (CBV) */ /* m_x_v(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, T_J2000_to_ECEF, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL); // multiply a matrix by a vector (in prop_math.c). So here we convert ECI (J2000) to ECEF coordinates (CBV) */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF,"uu"); */ if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Done initializing r_ecef2cg_ECEF and v_ecef2cg_ECEF for all spacecraft.\n"); } geocentric_to_geodetic( CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, &PARAMS->EARTH.radius, &PARAMS->EARTH.flattening, &CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude, &CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude, &CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude ); // Computes lat/long/altitude based on ECEF coordinates and planet fixed state (planetary semimajor axis, flattening parameter) (in propagator.c) (CBV) // !!!!!!!!!!!!!!! ERASE /* double x[6]; */ /* double lt; */ /* spkez_c(10, CONSTELLATION->spacecraft[ii][eee].et, "J2000", "NONE", 399, x, &lt); // Return the state (position and velocity) of a target bodyrelative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. */ /* double sun_norm[3]; */ /* double sun[3]; */ /* sun[0] = x[0]; sun[1] = x[1]; sun[2] = x[2]; */ /* v_norm(sun_norm, sun); */ /* v_scale(sun_norm,sun_norm,6.878137e+03); */ /* v_print(sun_norm,"sun_norm"); */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL,"CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL"); */ /* v_print(CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF,"CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF"); */ /* printf("lat = %f| lon = %f| alt = %f\n", CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude*RAD2DEG, CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude*RAD2DEG,CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude); */ /* v_print(sun,"sun"); */ /* exit(0); */ // !!!!!!!!!!!!!!! END OF ERASE // !!!!!!!!!!!!!!!!!!!!!!!!!! THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT! /* if ( strcmp( OPTIONS->type_orbit_initialisation, "oe" ) == 0 ){ */ /* if (ii > 0){ */ /* v_copy( CONSTELLATION->spacecraft[ii][eee].r_ecef2cg_ECEF, CONSTELLATION->spacecraft[0][eee].r_ecef2cg_ECEF); */ /* v_copy( CONSTELLATION->spacecraft[ii][eee].v_ecef2cg_ECEF, CONSTELLATION->spacecraft[0][eee].v_ecef2cg_ECEF); */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.altitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.altitude ; */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.latitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.latitude ; */ /* CONSTELLATION->spacecraft[ii][eee].GEODETIC.longitude = CONSTELLATION->spacecraft[0][eee].GEODETIC.longitude ; */ /* } */ /* } */ // !!!!!!!!!!!!!!!!!!!!!!!!!! END OF THE BLOCK BELOW IS TO INITIALIZE SATELLLITE 2 WITH THE CORRECT SPACING WITH RESPECT TO SATELLITE 1. IT IS JUST FOR A TRY, AND SHOULD BE REMOVED AND IMPLEMENTED IN THE CODE ITSELF. SO IF IT'S STILL HERE AFTER JUNE 10TH, 2016 THEN REMOVE IT! // Output file for each spacecraft if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Initializing the output file names and name_sat.\n"); } if (eee == 0){ // filenames are only for the main sc // COLLISION strcpy(CONSTELLATION->filename_collision, OPTIONS->dir_output_run_name); strcat( CONSTELLATION->filename_collision, "/"); strcat( CONSTELLATION->filename_collision,OPTIONS->filename_collision); // end of COLLISION strcpy(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filename, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->filename_output[ii]); if (( strcmp( OPTIONS->type_orbit_initialisation, "tle" ) == 0) || (strcmp(OPTIONS->type_orbit_initialisation, "tle_sgp4" ) == 0 )){ strcpy(CONSTELLATION->spacecraft[ii][0].filenametle, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenametle, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenametle, "TLE_"); strcat(CONSTELLATION->spacecraft[ii][0].filenametle, OPTIONS->filename_output[ii]); } // Now CONSTELLATION->spacecraft[ii][0].filenameecef is moved to generate_ephemerides because we want iProc 0 to know CONSTELLATION->spacecraft[ii][0].filenameecef even for the main sc ii that it does not run (this is because iProc 0 will gather all ECEF files at the end of the propagation) /* strcpy(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->dir_output_run_name_sat_name[ii]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, "/"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, "ECEF_"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->filename_output[ii]); */ strcpy(CONSTELLATION->spacecraft[ii][0].filenameout, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenameout, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenameout, "LLA_"); strcat(CONSTELLATION->spacecraft[ii][0].filenameout,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenamerho, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, "density_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenameatt, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, "attitude_"); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, "kalman_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, "meas_converted_kalman_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filename_kalman_init, OPTIONS->filename_kalman_init); strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, "/"); strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, "given_output_"); strcat(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output,OPTIONS->filename_output[ii]); if (OPTIONS->nb_ground_stations > 0){ for ( iground = 0; iground < OPTIONS->nb_ground_stations; iground ++){ strcpy(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->dir_output_run_name_sat_name_coverage[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], "/"); strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->name_ground_station[iground]); strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], "_by_"); strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground],OPTIONS->filename_output[ii]); } } if (OPTIONS->solar_cell_efficiency != -1){ strcpy(CONSTELLATION->spacecraft[ii][0].filenamepower, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, "power_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamepower,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenameeclipse, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, "eclipse_"); strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse,OPTIONS->filename_output[ii]); } } // end of eee = 0 // if (eee == start_ensemble + iProc * OPTIONS->nb_ensemble_min_per_proc){ // only receives it one time if (eee == array_sc[start_ensemble[ii]]){ // if eee is the first sc run by iProc for this given main sc ii if (write_attitude_file == 1){ strcpy(filename_attitude[ii], OPTIONS->dir_output_run_name_sat_name[ii]); strcat(filename_attitude[ii], "/"); strcat(filename_attitude[ii], "attitude_"); strcat(filename_attitude[ii],OPTIONS->filename_output[ii]); file_attitude[ii] = NULL; file_attitude[ii] = fopen(filename_attitude[ii], "w+"); if (file_attitude[ii] == NULL){ printf("***! Could not open the output file for the attitude called %s. The program will stop. !***\n", filename_attitude[ii]); MPI_Finalize(); exit(0); } fprintf(file_attitude[ii], "This file shows the attitude of each ensemble spacecraft of the main spacecraft %s. One block per ensemble spacecraft. First line is the pitch, roll, and yaw angular velocities, as well as the order of rotation (pitch, roll, yaw). Recall that this order is the same for all ensemble spacecraft. Following lines show time vs pitch, roll, yaw (rotation of the body reference system with respect to the LVLH reference system). All angles are given in degrees.\n", OPTIONS->name_sat[ii]); } } // Name of each satellites strcpy(CONSTELLATION->spacecraft[ii][eee].name_sat, ""); strcpy(CONSTELLATION->spacecraft[ii][eee].name_sat, OPTIONS->name_sat[ii]); if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Done initializing the output file names and name_sat.\n"); } // Compute the Orbital period of the first state if ( ( ii == 0 ) && ( eee == 0 ) ){ // !!!!!!!!!! FOR NOW WORKS ONLY IF TWO REFERENCE SATELLIES ONLY period = pow( CONSTELLATION->spacecraft[ii][0].OE.sma, 3.0); period = period / PARAMS->EARTH.GRAVITY.mu; period = 2.0 * M_PI * sqrt( period ); CONSTELLATION->collision_time_span = period / 10. ; // the time span is half of the orbit of the first sc (considered to be the primary sc) // ptd(CONSTELLATION->collision_time_span , "old"); // Actually, we re-evaluate the time span so it is an EVEN multiple of OPTIONS->dt (the closest possible to period/2) if ( fmod(CONSTELLATION->collision_time_span, OPTIONS->dt) == 0 ){ if ( fmod( CONSTELLATION->collision_time_span / OPTIONS->dt, 2 ) == 1 ){ // if time span is an odd multiple of dt then remove dt from it to make it even CONSTELLATION->collision_time_span = CONSTELLATION->collision_time_span - OPTIONS->dt; } } else{ m_time_span = (int)( CONSTELLATION->collision_time_span / OPTIONS->dt ); if ( fmod( m_time_span, 2 ) == 1 ){ m_time_span = m_time_span + 1; CONSTELLATION->collision_time_span = m_time_span * OPTIONS->dt; } else{ CONSTELLATION->collision_time_span = m_time_span * OPTIONS->dt; } } CONSTELLATION->collision_time_span = CONSTELLATION->collision_time_span + 2 * OPTIONS->dt; // for the reason why we add 2 * OPTIONS->dt, see comment "ABOUT THE TIME SPAN" at the end of generate_ephemerides /* ptd(CONSTELLATION->collision_time_span , "new"); */ /* exitall(); */ // end of actually, we re-evaluate the time span so it is an EVEN multiple of OPTIONS->dt (the closest possible to period/2) if (nProcs > 1){ for (ccc = 1; ccc < nProcs; ccc++){ // main sc 0 is for sure run by iProc 0, not matter how many main sc/ensemble sc/iProc there are MPI_Send(&CONSTELLATION->collision_time_span, 1, MPI_DOUBLE, ccc, 0, MPI_COMM_WORLD); } } } if (nProcs > 1){ if ( iProc > 0){ if ((ii == 0) && (eee == array_sc[start_ensemble[ii]])){ // only receives it one time (array_sc[start_ensemble[ii]] is the first sc run by this iProc. Since main sc 0 is never run by iProc > 0, array_sc[start_ensemble[ii]] corresponds to the first ensemble sc run by this iProc) MPI_Recv(&CONSTELLATION->collision_time_span, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Initializing dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\n"); } // Integrator CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.dt = OPTIONS->dt; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.dt_pos_neg = OPTIONS->dt_pos_neg; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces = OPTIONS->n_surfaces; // Number of surfaces on the SC CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff = OPTIONS->n_surfaces_eff; // Number of surfaces on the SC CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.mass = OPTIONS->mass; // Mass of spacecraft CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.solar_cell_efficiency = OPTIONS->solar_cell_efficiency; // Solar cell efficiency strcpy( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl_filename_solar_power, OPTIONS->opengl_filename_solar_power ); // Solar cell efficiency CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl = OPTIONS->opengl; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.opengl_power = OPTIONS->opengl_power; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.degree = OPTIONS->degree; // Gravity degree CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.order = OPTIONS->order; // Gravity order CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag = OPTIONS->include_drag; // include drag (CBV) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.thrust = OPTIONS->thrust; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_solar_pressure = OPTIONS->include_solar_pressure; // include drag (CBV) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_earth_pressure = OPTIONS->include_earth_pressure; // include drag (CBV) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_sun = OPTIONS->include_sun; // include Sun perturbations (CBV) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_moon = OPTIONS->include_moon; // include Moon perturbations (CBV) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod = OPTIONS->density_mod; // // the desnity given by msis is multiplied by density_mod + density_amp * sin(2*pi*t/T + density_phase*T) where T is the orbital period CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod_amp = OPTIONS->density_mod_amp; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density_mod_phase = OPTIONS->density_mod_phase; if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag == 1 ){ // if the user wants to use drag strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.format_density_driver, OPTIONS->format_density_driver); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( ( strcmp(OPTIONS->format_density_driver, "density_file") != 0 ) && ( strcmp(OPTIONS->format_density_driver, "gitm") != 0 ) ){ // the user chooses f107 and Ap for the density if ( strcmp(OPTIONS->format_density_driver, "static") == 0 ){ // if the user chooses a constant f107 and Ap for the density CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_static = OPTIONS->Ap_static; // magnetic index(daily) for (hhh = 0; hhh < 7; hhh++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist_static[hhh] = OPTIONS->Ap_hist_static[hhh]; // magnetic index(historical) } CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107_static = OPTIONS->f107_static; // Daily average of F10.7 flux CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A_static = OPTIONS->f107A_static; // 81 day average of F10.7 flux } else{ // if the user chooses a time-varying f107 and Ap for the density CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); // "* 2.0" because of the Runge Kunta order 4 method if (OPTIONS->use_ap_hist == 1){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist = malloc( 7 * sizeof(double *) ); // historical ap for (hhh = 0; hhh < 7; hhh++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist[hhh] = malloc(OPTIONS->nb_time_steps * 2 * sizeof(double )); } } CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if (OPTIONS->use_ap_hist == 1){ if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107 \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107A \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } /* for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ // "* 2.0" because of the Runge Kunta order 4 method */ /* if ( OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) { */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap[aaa] = OPTIONS->Ap[aaa]; // magnetic index(daily) */ /* if (OPTIONS->use_ap_hist == 1){ */ /* for (hhh = 0; hhh < 7; hhh++){ */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.Ap_hist[hhh][aaa] = OPTIONS->Ap_hist[hhh][aaa]; // magnetic index(historical) */ /* } */ /* } */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.f107[aaa] = OPTIONS->f107[aaa]; // Daily average of F10.7 flux */ /* } */ /* } */ if ((strcmp(OPTIONS->test_omniweb_or_external_file, "swpc_mod") == 0) && (OPTIONS->swpc_need_predictions)){ CONSTELLATION->sum_sigma_for_f107_average[ii][eee] = 0; } if (OPTIONS->nb_ensembles_density) { // the user chose to run ensembles on the density using data from SWPC if (OPTIONS->swpc_need_predictions){ // if future predictions of F10.7 and Ap (not only past observations) CONSTELLATION->sum_sigma_for_f107_average[ii][eee] = 0; if (eee == 1 + iProc * OPTIONS->nb_ensemble_min_per_proc){ // allocate memory for arrays only once per iProc CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); if (CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc] == NULL){ printf("***! (propagate_spacecraft)(compute_drag) (generate_ensemble_f107_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc]. The program will stop. !***\n"); MPI_Finalize();exit(0); } CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); if (CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc] == NULL){ printf("***! (propagate_spacecraft)(compute_drag) (generate_ensemble_f107_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc]. The program will stop. !***\n"); MPI_Finalize();exit(0); } CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); if (CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc] == NULL){ printf("***! (propagate_spacecraft)(compute_drag) (generate_ensemble_ap_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc]. The program will stop. !***\n"); MPI_Finalize();exit(0); } CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc] = malloc( OPTIONS->nb_ensemble_min_per_proc * sizeof( double ) ); if (CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc] == NULL){ printf("***! (propagate_spacecraft)(compute_drag) (generate_ensemble_ap_ap) There is not enough memory for CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc]. The program will stop. !***\n"); MPI_Finalize();exit(0); } } // end of allocate memory for arrays only once per iProc } // end of if future predictions of F10.7 and Ap (not only past observations) } // end of the user chose to run ensembles on the density using data from SWPC /* if ( (OPTIONS->nb_ensembles_density) && (OPTIONS->swpc_need_predictions) && ( et_initial_epoch >= OPTIONS->swpc_et_first_prediction ) ) { */ /* // if the user chose to run ensembles on the density using data from SWPC */ /* // if future predictions of F10.7 and Ap (not only past observations) (past values (value before the current time at running) are perfectly known (result from observations, not predictions)) */ /* // only overwrite predictions of ensembles (not observations). OPTIONS->et_interpo[aaa] corresponds to the first say of predictions */ /* start_ensemble_bis = 1; */ /* nb_index_in_81_days = 81. * 24 * 3600 / (OPTIONS->dt/2.) + 1 ; */ /* if ( eee == start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc){ // initialize array only once per iProc */ /* // // Generate nb_ensembles_density normal random values */ /* for ( eee_bis = 0; eee_bis < OPTIONS->nb_ensemble_min_per_proc; eee_bis++){ */ /* CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc][eee_bis] = randn( OPTIONS->f107[0], OPTIONS->sigma_f107[CONSTELLATION->aaa_sigma]); */ /* CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc][eee_bis] = randn( OPTIONS->Ap[0], OPTIONS->sigma_ap[CONSTELLATION->aaa_sigma]); */ /* /\* if (eee_bis == 0){ *\/ */ /* /\* etprint(OPTIONS->et_interpo[aaa], "time"); *\/ */ /* /\* printf("Ap[%d]: %f | sigma_ap[%d]: %f \n",aaa, OPTIONS->Ap[aaa],CONSTELLATION->aaa_sigma, OPTIONS->sigma_ap[CONSTELLATION->aaa_sigma]); *\/ */ /* /\* } *\/ */ /* } */ /* // // Order values in ascending order */ /* sort_asc_order(CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc], CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time[iProc], OPTIONS->nb_ensemble_min_per_proc); */ /* sort_asc_order(CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc], CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time[iProc], OPTIONS->nb_ensemble_min_per_proc); */ /* // Initialization of swpc_et_first_prediction for the calculation of F10.7A for an ensemble */ /* if ( et_initial_epoch > OPTIONS->swpc_et_first_prediction){ // if the propagation starts in the future. Otherwise, sum_sigma_for_f107_average = 0 for all ensemble sc */ /* if ( CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] == 0 ) {// for the first time that variable et gets bigger than swpc_et_first_prediction (0.01 for numerical reasons) */ /* // initialize sum_sigma_for_f107_average as the sum of all sigma on F10.7 from first prediction to inital epoch. There is no mathematical logic in here. The exact solution would be to sum all the deviations between f107_ensemble and f107_refce from first prediciton until intial epoch, and sum them up. This is KIND OF similar. The reason I don't do the correct approach is that I did not calculate f107_ensemble for times before initial epoch */ /* for (aaa_a = 0; aaa_a < CONSTELLATION->aaa_sigma; aaa_a++){ */ /* CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] = CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] + OPTIONS->sigma_f107[aaa_a]; */ /* // ptd( OPTIONS->sigma_f107[aaa_a], "s"); */ /* } */ /* // printf("eee_bis: %d | index: %d | iProc: %d | sum: %f\n", CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, index_in_driver_interpolated, iProc, CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb]);exit(0); */ /* } // end of for the first time that variable et gets bigger than swpc_et_first_prediction */ /* }// end of if the propagation starts in the future */ /* // End of initialization of swpc_et_first_prediction for the calculation of F10.7A for an ensemble */ /* } // initialize array only once per iProc */ /* else if ( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb == 0){ // also need to calculate f107 and ap for reference sc (no perturbation so directly equal to the values in the prediction files) */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0] = OPTIONS->Ap[0]; // magnetic index(daily) */ /* if (OPTIONS->use_ap_hist == 1){ */ /* for (hhh = 0; hhh < 7; hhh++){ */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap_hist[hhh][0] = OPTIONS->Ap_hist[hhh][0]; // magnetic index(historical) */ /* } */ /* } */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0] = OPTIONS->f107[0]; // Daily average of F10.7 flux */ /* /\* print_test(); *\/ */ /* /\* printf(" CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[%d]: %f\n", 0, CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0]); *\/ */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0] = OPTIONS->f107A[0]; // 81 day average of F10.7 flux */ /* } // end of also need to calculate f107 and ap for reference sc (no perturbation so directly equal to the values in the prediction files) */ /* if ( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb != 0) { // don't overwrite previously written values of f107 and Ap for reference sc */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0] = CONSTELLATION->ensemble_array_per_iproc_ap_at_given_time_sorted[iProc][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb-1-iProc*OPTIONS->nb_ensemble_min_per_proc]; */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0] = CONSTELLATION->ensemble_array_per_iproc_f107_at_given_time_sorted[iProc][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb-1-iProc*OPTIONS->nb_ensemble_min_per_proc]; */ /* CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] = CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] + ( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0] - OPTIONS->f107[0] ); */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0] = OPTIONS->f107A[0] + CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb] / nb_index_in_81_days; // derivation of F10.7A considering uncerainties in F10.7 */ /* // printf("eee_bis: %d | index: %d | iProc: %d | sum: %f | 81: %f | opeion %f\n", CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, index_in_driver_interpolated, iProc, CONSTELLATION->sum_sigma_for_f107_average[ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_main_nb][ CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb], nb_index_in_81_days, OPTIONS->dt); */ /* // print_test(); */ /* /\* if (iProc == 0){ *\/ */ /* /\* // if (( CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb == start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc + 1)){ *\/ */ /* /\* if (index_in_driver_interpolated == 4){ *\/ */ /* /\* printf("eee_bis: %d | f107: %f | index: %d | iProc: %d\n", CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[index_in_driver_interpolated], index_in_driver_interpolated, iProc); *\/ */ /* /\* } *\/ */ /* /\* } *\/ */ /* } // end of don't overwrite previously written values of f107 and Ap for reference sc */ /* } // end of: */ /* // if the user chose to run ensembles on the density using data from SWPC AND */ /* // if future predictions of F10.7 and Ap (not only past observations) (past values (value before the current time at running) are perfectly known (result from observations, not predictions)) */ /* // only overwrite predictions of ensembles (not observations). OPTIONS->et_interpo[aaa] corresponds to the first say of predictions */ /* else{ // if we don't run ensembles on F10.7/Ap or that we run ensemble on F10.7/Ap but that the initial epoch is before the first prediction (so there is no uncertainty in F10.7/Ap because the initial epooch corresponds to an observation, not a prediction) */ /* // print_test(); */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap[0] = OPTIONS->Ap[0]; // magnetic index(daily) */ /* if (OPTIONS->use_ap_hist == 1){ */ /* for (hhh = 0; hhh < 7; hhh++){ */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.Ap_hist[hhh][0] = OPTIONS->Ap_hist[hhh][0]; // magnetic index(historical) */ /* } */ /* } */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[0] = OPTIONS->f107[0]; // Daily average of F10.7 flux */ /* CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107A[0] = OPTIONS->f107A[0]; // 81 day average of F10.7 flux */ /* // printf("%d %f %d %f\n", CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.sc_ensemble_nb, CONSTELLATION->spacecraft[ii][eee_bis].INTEGRATOR.f107[index_in_driver_interpolated], index_in_driver_interpolated, OPTIONS->f107[index_in_driver_interpolated]); */ /* } // end of if we don't run ensembles on F10.7/Ap or that we run ensemble on F10.7/Ap but that the initial epoch is before the first prediction (so there is no uncertainty in F10.7/Ap because the inital epoch corresponds to an observation, not a prediction) */ } // end of if the user chooses a time-varying f107 and Ap for the density } // end of the user chooses f107 and Ap and Ap_hist for the density else if ( strcmp(OPTIONS->format_density_driver, "density_file") == 0 ){ // the user chooses to directly input the density from a file for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ // "* 2.0" because of the Runge Kunta order 4 method if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) { CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.density[aaa] = OPTIONS->density[aaa] * 1e9; // Convert from kg/m^3 to kg/km^3 } } } // end of the user chooses to directly input the density from a file else if ( strcmp(OPTIONS->format_density_driver, "gitm") == 0 ){ // the user chooses GITM if ( (ii ==0) && (eee == 0) ) { // here we initialize ATMOSPHERE if gitm is chosen so it doesn't have to be done for all satellites, just the first one (since ATMOSPHERE is the same for all satellites/ensembles) if (OPTIONS->nb_gitm_file < 1){ printf("***! No GITM file has been found. The program will stop. !***\n"); MPI_Finalize(); exit(0); } else{ for (ggg = 0; ggg < OPTIONS->nb_gitm_file; ggg++){ PARAMS->ATMOSPHERE.nb_gitm_file = OPTIONS->nb_gitm_file; strcpy(PARAMS->ATMOSPHERE.array_gitm_file[ggg], OPTIONS->array_gitm_file[ggg]); PARAMS->ATMOSPHERE.array_gitm_date[ggg][0] = OPTIONS->array_gitm_date[ggg][0] ; PARAMS->ATMOSPHERE.array_gitm_date[ggg][1]= OPTIONS->array_gitm_date[ggg][1] ; PARAMS->ATMOSPHERE.is_first_step_of_run = 1; } // Read the first data file to get the number of lon/lat/alt and allocate memory accordingly gitm_file = fopen(PARAMS->ATMOSPHERE.array_gitm_file[0],"rb"); // NLONS, NLATS, NALTS fseek(gitm_file, 20, SEEK_SET ); fread(&PARAMS->ATMOSPHERE.nLons_gitm,sizeof(PARAMS->ATMOSPHERE.nLons_gitm),1,gitm_file); fread(&PARAMS->ATMOSPHERE.nLats_gitm,sizeof(PARAMS->ATMOSPHERE.nLats_gitm),1,gitm_file); fread(&PARAMS->ATMOSPHERE.nAlts_gitm,sizeof(PARAMS->ATMOSPHERE.nAlts_gitm),1,gitm_file); fseek(gitm_file , 4, SEEK_CUR ); // Allocate for the GITM file which date is right BEFORE the epoch of the sc PARAMS->ATMOSPHERE.longitude_gitm = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ PARAMS->ATMOSPHERE.longitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *)); for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ PARAMS->ATMOSPHERE.longitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double)); } } PARAMS->ATMOSPHERE.latitude_gitm = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ PARAMS->ATMOSPHERE.latitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *)); for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ PARAMS->ATMOSPHERE.latitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double)); } } PARAMS->ATMOSPHERE.altitude_gitm = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ PARAMS->ATMOSPHERE.altitude_gitm[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *)); for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ PARAMS->ATMOSPHERE.altitude_gitm[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double)); } } PARAMS->ATMOSPHERE.density_gitm_right_before = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ PARAMS->ATMOSPHERE.density_gitm_right_before[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *)); for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ PARAMS->ATMOSPHERE.density_gitm_right_before[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double)); } } if ( PARAMS->ATMOSPHERE.longitude_gitm == NULL ){ printf("***! Could not allow memory for PARAMS->ATMOSPHERE.longitude_gitm. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( PARAMS->ATMOSPHERE.latitude_gitm == NULL ){ printf("***! Could not allow memory for PARAMS->ATMOSPHERE.latitude_gitm. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( PARAMS->ATMOSPHERE.altitude_gitm == NULL ){ printf("***! Could not allow memory for PARAMS->ATMOSPHERE.altitude_gitm. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( PARAMS->ATMOSPHERE.density_gitm_right_before == NULL ){ printf("***! Could not allow memory for PARAMS->ATMOSPHERE.density_gitm_right_before. The program will stop. !***\n"); MPI_Finalize(); exit(0); } // Allocate for the GITM file which date is right AFTER the epoch of the sc PARAMS->ATMOSPHERE.density_gitm_right_after = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); PARAMS->ATMOSPHERE.density_gitm_right_after = malloc( PARAMS->ATMOSPHERE.nLons_gitm * sizeof(double **) ); for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ PARAMS->ATMOSPHERE.density_gitm_right_after[i] = malloc(PARAMS->ATMOSPHERE.nLats_gitm * sizeof(double *)); for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ PARAMS->ATMOSPHERE.density_gitm_right_after[i][j] = malloc(PARAMS->ATMOSPHERE.nAlts_gitm * sizeof(double)); } } if ( PARAMS->ATMOSPHERE.density_gitm_right_after == NULL ){ printf("***! Could not allow memory for PARAMS->ATMOSPHERE.density_gitm_right_after. The program will stop. !***\n"); MPI_Finalize(); exit(0); } // Read the lon/lat/alt array (same for all files in the propagation) and nVars // NVARS fseek(gitm_file, 4, SEEK_CUR ); fread(&PARAMS->ATMOSPHERE.nVars_gitm,sizeof(PARAMS->ATMOSPHERE.nVars_gitm),1,gitm_file); fseek(gitm_file, 4, SEEK_CUR ); iHeaderLength_gitm = 8L + 4+4 + 3*4 + 4+4 + 4 + 4+4 + PARAMS->ATMOSPHERE.nVars_gitm*40 + PARAMS->ATMOSPHERE.nVars_gitm*(4+4) + 7*4 + 4+4; fseek(gitm_file, iHeaderLength_gitm, SEEK_SET); // READ THE LONGITUDE fseek(gitm_file, 4, SEEK_CUR ); for (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){ for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ fread(&PARAMS->ATMOSPHERE.longitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.longitude_gitm[i][j][k]), 1, gitm_file); } } } fseek(gitm_file, 4, SEEK_CUR ); //printf("\n %f\n", PARAMS->ATMOSPHERE.longitude_gitm[11][40][21]); // READ THE LATITUDE fseek(gitm_file, 4, SEEK_CUR ); for (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){ for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ fread(&PARAMS->ATMOSPHERE.latitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.latitude_gitm[i][j][k]), 1, gitm_file); } } } fseek(gitm_file, 4, SEEK_CUR ); // printf("\n %f\n", PARAMS->ATMOSPHERE.latitude_gitm[11][40][21]); // READ THE ALTITUDE fseek(gitm_file, 4, SEEK_CUR ); for (k = 0; k < PARAMS->ATMOSPHERE.nAlts_gitm; k++){ for (j = 0; j < PARAMS->ATMOSPHERE.nLats_gitm; j++){ for (i = 0; i < PARAMS->ATMOSPHERE.nLons_gitm; i++){ fread(&PARAMS->ATMOSPHERE.altitude_gitm[i][j][k], sizeof(PARAMS->ATMOSPHERE.altitude_gitm[i][j][k]), 1, gitm_file); PARAMS->ATMOSPHERE.altitude_gitm[i][j][k] = PARAMS->ATMOSPHERE.altitude_gitm[i][j][k] / 1000.0; // conversion meters to kilometers } } } // printf("\n %f\n", PARAMS->ATMOSPHERE.altitude_gitm[11][40][21]); fclose(gitm_file); } // printf("%s | %d\n", PARAMS->ATMOSPHERE.array_gitm_file[ggg], ggg); } if (eee == 0){ // find the altitude that is right below the perigee altitude. Note: if the duration of the run is long (so that the sc looses a good amount of altitude, so like 6 months) then index_altitude_right_below_perigee is set to 0 so that we go over all the altitudes and not only the ones that start below the perigee calcualted at the initialization. //if many main satellites with different altitude of the perigee, then take the min of these perigee to calculate index_altitude_right_below_perigee int found_altitude_right_below_perigee = 0; if ( et_final_epoch - et_initial_epoch < 6 * 31 * 24 * 3600.0 ){ // if the duration of the run is long (so that the sc looses a good amount of altitude, so like 6 months) then index_altitude_right_below_perigee is set to 0 so that we go over all the altitudes and not only the ones that start below the perigee calcualted at the initialization. altitude_perigee = radius_perigee - PARAMS->EARTH.radius; k = 0; while ( (k < PARAMS->ATMOSPHERE.nAlts_gitm ) && (found_altitude_right_below_perigee == 0) ){ if (PARAMS->ATMOSPHERE.altitude_gitm[0][0][k] >= altitude_perigee){ if ( (k-1) < index_altitude_right_below_perigee_save ){ index_altitude_right_below_perigee_save = k-1; } found_altitude_right_below_perigee = 1; } k = k+1; } if (ii == OPTIONS->n_satellites - OPTIONS->nb_gps - 1){ PARAMS->ATMOSPHERE.index_altitude_right_below_perigee = index_altitude_right_below_perigee_save; } } else{ PARAMS->ATMOSPHERE.index_altitude_right_below_perigee = 0; } } } // end of the user chooses GITM } // end of if the user wants to use drag if (iDebugLevel >= 2){ if (iProc == 0) printf("--- (initialize_constellation) Done initializing dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\n"); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing r_ecef2cg_ECEF, geodetic, output file names, name_sat, dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar for all spacecraft.\n"); } /*************************************************************************************/ /*************************************************************************************/ /************* END OF COE AND TLE INITIALIZE for main SC and for ensemble SC: - r_ecef2cg_ECEF - geodetic - filename, filenameecef, filenameout, filenamepower for main SC ONLY - name_sat - INTEGRATOR: dt, nb_surfaces, mass, solar_cell_efficiency, degree, order, include_drag/solar_pressure/earth_pressure/moon/sun, Ap, Ap_hist, f107, f107A, density, initialize_geo_with_bstar, sc_main_nb, sc_ensemble_nb **************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*********************** COE AND TLE INITIALIZE: attitude ****************************/ /*************************************************************************************/ /*************************************************************************************/ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing the attitude.\n"); } if ( ( strcmp(OPTIONS->attitude_profile, "ensemble_angular_velocity") != 0 ) && ( strcmp(OPTIONS->attitude_profile, "ensemble_initial_attitude") != 0 ) ) { // if we do not run ensembles on the initial angular velocity // Give memory to attitude variables CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.file_is_quaternion = OPTIONS->file_is_quaternion; if ( OPTIONS->file_is_quaternion == 0){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); // "* 2.0" because of the Runge Kunta order 4 method CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double) ); } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion = malloc( OPTIONS->nb_time_steps * 2 * sizeof(double*) ); // "* 2.0" because of the Runge Kunta order 4 method for (ccc = 0; ccc < OPTIONS->nb_time_steps * 2; ccc++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[ccc] = malloc( 4* sizeof(double) ); } } CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated_first = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt *2.; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated_first = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt * 2.; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt *2.; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated = (int)( CONSTELLATION->spacecraft[ii][eee].et - OPTIONS->et_oldest_tle_epoch ) / OPTIONS->dt * 2.; // printf("%d %d | %d %d | %d %d\n", ii, eee, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated_first , CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated_first ); if ( OPTIONS->file_is_quaternion == 1){ if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } } else{ if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw == NULL ){ printf("***! Could not allow memory space for CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw \n. The program will stop. !***\n"); MPI_Finalize(); exit(0); } } strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // nadir, sun_pointed, ... /*************************************************************************************/ /******************* COE AND TLE INITIALIZE: attitude for main SC ********************/ /*************************************************************************************/ if (eee == 0){ // eee = 0 represents the main spacecraft (eee > 0 is a sc from an ensemble) for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ // "* 2.0" because of the Runge Kunta order 4 method if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01) { if ( OPTIONS->file_is_quaternion == 0){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = OPTIONS->pitch[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = OPTIONS->roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = OPTIONS->yaw[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa] = OPTIONS->order_roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] = OPTIONS->order_yaw[aaa]; } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][0] = OPTIONS->quaternion[aaa][0]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][1] = OPTIONS->quaternion[aaa][1]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][2] = OPTIONS->quaternion[aaa][2]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.quaternion[aaa][3] = OPTIONS->quaternion[aaa][3]; } } } } // end of initializing the attitude for the main SC /*************************************************************************************/ /******************* COE AND TLE INITIALIZE: attitude for ensemble SC ****************/ /*************************************************************************************/ /*****************************************************************************************************************************/ /**************************************************** ENSEMBLES ON ATTITUDE **************************************************/ /*****************************************************************************************************************************/ else{ // here eee > 0 so we are initializing the attitude for the sc from an ensemble if (OPTIONS->nb_ensembles_attitude > 0){ // initialize the attitude if we run ensembles on the attitude. So it's not with ensemble_angular_velocity and not with ensemble_initial_attitude (these would have had to be put in section #ATTITUDE). But it corresponds to a drift of the sc from a reference attitude (specified in section #ATTITUDE (nadir, sun_pointed, ...)) for with a given time (set by time_before_reset) with a random angular velocity. // if (iProc == 0){ CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_ensemble = OPTIONS->pitch_sigma_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_ensemble = OPTIONS->roll_sigma_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_ensemble = OPTIONS->yaw_sigma_ensemble; // } //for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ // "* 2.0" because of the Runge Kunta order 4 method // last_aaa_previous_loop = 0; aaa = 0; if (write_attitude_file == 1){ fprintf(file_attitude[ii], "#START_ATTITUDE_ENSEMBLE for ensemble %d\n", eee); } while ( aaa < OPTIONS->nb_time_steps * 2 ){ // printf("%d %d %d || %f %f\n", iProc, aaa, OPTIONS->nb_time_steps * 2, OPTIONS->et_interpo[aaa], et_final_epoch); if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) { time_before_reset = 0; // every OPTIONS->attitude_reset_delay seconds, the attitude is set equal to the attitude of the main spacecraft (nadir or sun pointed or from an atttitude file) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = OPTIONS->pitch[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = OPTIONS->roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = OPTIONS->yaw[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa] = OPTIONS->order_roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] = OPTIONS->order_yaw[aaa]; // during OPTIONS->attitude_reset_delay seconds, the satellite's attitude changes with a constant random angular velocity random_pitch_angular_velocity = randn( 0.0, OPTIONS->pitch_sigma_angular_velocity_ensemble); random_roll_angular_velocity = randn( 0.0, OPTIONS->roll_sigma_angular_velocity_ensemble); random_yaw_angular_velocity = randn( 0.0, OPTIONS->yaw_sigma_angular_velocity_ensemble); if (write_attitude_file == 1){ if (aaa==0){ fprintf(file_attitude[ii], "%e %e %e %d %d %d\n", random_pitch_angular_velocity, random_roll_angular_velocity, random_yaw_angular_velocity, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa],CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] ); } et2utc_c(OPTIONS->et_oldest_tle_epoch+aaa*OPTIONS->dt/2., "ISOC" ,0 ,255 , time_attitude); fprintf(file_attitude[ii], "%s %e %e %e\n", time_attitude,CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa]); } // if (iProc == 0){ /* if ( (ii == 1) && (eee == array_sc[start_ensemble[ii]]) ){ */ /* printf("iProc %d | aaa = %d out of %d | time reset %f out of %f\n", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay); */ /* } */ //} while ( ( time_before_reset * OPTIONS->dt / 2.0 < ( OPTIONS->attitude_reset_delay - OPTIONS->dt / 2.0 ) ) && ( aaa < OPTIONS->nb_time_steps * 2 ) ){ time_before_reset = time_before_reset + 1 ; aaa = aaa + 1; /* if (iProc == 2){ */ /* printf("iProc %d | aaa = %d out of %d | time reset %f out of %f\n", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay); */ /* } */ if (aaa < OPTIONS->nb_time_steps * 2){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = random_pitch_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->pitch[aaa]; // the angular velocity is distributed as gaussian with a 0 rad/s mean and a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble chosen by the user. The attitude is calculated from this random angular velocity around the attitude of the main spacecraft (nadir or from an attitude file (FOR NOW NOT POSSIBLE TO RUN ENSEMBLES IF ATTITUDE IS SUN_POINTED)): OPTIONS->pitch/roll/yaw[aaa] CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = random_roll_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = random_yaw_angular_velocity * time_before_reset * OPTIONS->dt / 2.0 + OPTIONS->yaw[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa] = OPTIONS->order_roll[aaa]; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] = OPTIONS->order_yaw[aaa]; /* if (iProc == 0){ */ /* if ( (ii == 0) && (eee == 1) ){ */ /* printf("IN iProc %d | aaa = %d out of %d | time reset %f out of %f | pitch %f\n", iProc, aaa, OPTIONS->nb_time_steps * 2, time_before_reset * OPTIONS->dt / 2.0 , OPTIONS->attitude_reset_delay, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa]); */ /* } */ /* } */ if (write_attitude_file == 1){ if (fmod(aaa, 2) == 0){ et2utc_c(OPTIONS->et_oldest_tle_epoch+aaa*OPTIONS->dt/2., "ISOC" ,0 ,255 , time_attitude); fprintf(file_attitude[ii], "%s %e %e %e\n", time_attitude,CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] ); } } } } // end of while loop for the attitude with a constant random angular velocity aaa = aaa + 1; //last_aaa_previous_loop = aaa; } } // end of initializing the attitude for the ensemble spacecrafts if (write_attitude_file == 1){ fprintf(file_attitude[ii], "#END_ATTITUDE_ENSEMBLE\n\n"); } } // end of initialize the attitude if we run ensembles on the attitude else{ // initialize the attitude if we do not run ensembles on the attitude // WE DON'T INITALIZE THE ATTIUDE HERE ANYMORE BUT IN THE FUNCTION SET_ATTITUDE CALLED IN PROPAGATE_SPACECRAFT. This is to avoid going through all time steps for all ensembles. Note that for all other cases, ie if we run any kind of ensembles on the attitude, the initialization of the attitude is still set in initialize_constellation (and not in propagate_spacecraft) /* for (aaa = 0; aaa< OPTIONS->nb_time_steps * 2; aaa++){ */ /* if (OPTIONS->et_interpo[aaa] <= et_final_epoch + 0.01 ) { */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch[aaa] = OPTIONS->pitch[aaa]; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll[aaa] = OPTIONS->roll[aaa]; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw[aaa] = OPTIONS->yaw[aaa]; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_pitch[aaa] = OPTIONS->order_pitch[aaa]; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_roll[aaa] = OPTIONS->order_roll[aaa]; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.order_yaw[aaa] = OPTIONS->order_yaw[aaa]; */ /* } */ /* } */ //end of WE DON'T INITALIZE THE ATTIUDE HERE ANYMORE BUT IN THE FUNCTION SET_ATTITUDE CALLED IN PROPAGATE_SPACECRAFT } // end of initialize the attitude if we do not run ensembles on the attitude } // end of initializinf the attitude for the ensemble spacecraft } // end of if we do not run ensembles on the initial angular velocity /*********************************************************************************************************************************/ /******************************************* ENSEMBLES ON INITIAL ANGULAR VELOCITY ***********************************************/ /*********************************************************************************************************************************/ else if ( strcmp(OPTIONS->attitude_profile, "ensemble_angular_velocity") == 0 ){ // if we run ensembles on the initial angular velocity. The attitude is defined by its initial angle (pitch; roll; yaw), the mean angular velocity (mean ang velo pitch; mean ang velo roll; mean ang velo yaw), and the standard deviation on the angular velo (sigma ang velo pitch; sigma ang velo roll; sigma ang velo yaw) // if ( (eee == 0) && (ii == 0)){ // initialize attitude for main spacecraft if we run ensembles on the initial angular velocity // !!!!!!!!!!!! for now works only if there one satellite in the constellation if ( eee == 0){ // initialize attitude for main spacecraft if we run ensembles on the initial angular velocity strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = "ensemble_angular_velocity" // pitch CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_ini_ensemble = OPTIONS->pitch_ini_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = OPTIONS->pitch_mean_angular_velocity_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_angular_velocity_ensemble = OPTIONS->pitch_sigma_angular_velocity_ensemble / 2.0; // roll CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_ini_ensemble = OPTIONS->roll_ini_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_angular_velocity_ensemble = OPTIONS->roll_mean_angular_velocity_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_angular_velocity_ensemble = OPTIONS->roll_sigma_angular_velocity_ensemble / 2.0; // yaw CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_ini_ensemble = OPTIONS->yaw_ini_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = OPTIONS->yaw_mean_angular_velocity_ensemble; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_angular_velocity_ensemble = OPTIONS->yaw_sigma_angular_velocity_ensemble / 2.0; } // end of initialize attitude for main spacecraft if we run ensembles on the initial angular velocity // else if (ii == 0){ // initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity else{ // initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = "ensemble_angular_velocity" // calculate the random angular velocity = normal distribution around the mean angular velocity OPTIONS->pitch/roll/yaw_mean_angular_velocity_ensemble with a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = randn( OPTIONS->pitch_mean_angular_velocity_ensemble, OPTIONS->pitch_sigma_angular_velocity_ensemble / 2.0); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_ensemble = randn( OPTIONS->roll_mean_angular_velocity_ensemble, OPTIONS->roll_sigma_angular_velocity_ensemble / 2.0); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = randn( OPTIONS->yaw_mean_angular_velocity_ensemble, OPTIONS->yaw_sigma_angular_velocity_ensemble / 2.0); // fprintf(fp_temp, "%f \n", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_ini_ensemble = OPTIONS->pitch_ini_ensemble; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_ini_ensemble = OPTIONS->roll_ini_ensemble; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_ini_ensemble = OPTIONS->yaw_ini_ensemble; /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_sigma_angular_velocity_ensemble); */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_sigma_angular_velocity_ensemble); */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_ensemble = randn( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_angular_velocity_ensemble, CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_sigma_angular_velocity_ensemble); */ /* // fprintf(fp_temp, "%f \n", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_ensemble); */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.pitch_ini_ensemble; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.roll_ini_ensemble; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_ini_ensemble = CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.yaw_ini_ensemble; */ } // end of initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity } // end of if we run ensembles on the initial angular velocity else if ( strcmp(OPTIONS->attitude_profile, "ensemble_initial_attitude") == 0 ){ //if we run ensembles on the initial attitude. The ensembles all have different initial attitude but same constant angular velocities // if ( (eee == 0) && (ii == 0)){ // initialize attitude for main spacecraft if we run ensembles on the initial attitude // !!!!!!!!!!!! for now works only if there one satellite in the constellation if ( eee == 0 ){ // initialize attitude for main spacecraft if we run ensembles on the initial attitude strcpy(CONSTELLATION->spacecraft[ii][0].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = "ensemble_initial_attitude" // the reference satellite has the same attitude as the mean attitude chosen by the user (first line of ###ENSEMBLES_INITIAL_ATTITUDE) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_for_attitude_ensemble = OPTIONS->pitch_mean_ensemble; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_for_attitude_ensemble = OPTIONS->roll_mean_ensemble; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_for_attitude_ensemble = OPTIONS->yaw_mean_ensemble; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_constant = OPTIONS->pitch_angular_velocity_constant; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_constant = OPTIONS->roll_angular_velocity_constant; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_constant = OPTIONS->yaw_angular_velocity_constant; } // end of initialize attitude for main spacecraft if we run ensembles on the initial angular velocity // else if (ii == 0){ // initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity else{ // initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.attitude_profile, OPTIONS->attitude_profile); // here attitude_profile = "ensemble_angular_velocity" // calculate the random angular velocity = normal distribution around the mean angular velocity OPTIONS->pitch/roll/yaw_mean_angular_velocity_ensemble with a standard deviation OPTIONS->pitch/roll/yaw_sigma_angular_velocity_ensemble CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_for_attitude_ensemble = randn( OPTIONS->pitch_mean_ensemble, OPTIONS->pitch_sigma_for_ensemble_initial_attitude / 2.); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_for_attitude_ensemble = randn( OPTIONS->roll_mean_ensemble, OPTIONS->roll_sigma_for_ensemble_initial_attitude / 2.); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_for_attitude_ensemble = randn( OPTIONS->yaw_mean_ensemble, OPTIONS->yaw_sigma_for_ensemble_initial_attitude / 2.); CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.pitch_angular_velocity_constant = OPTIONS->pitch_angular_velocity_constant; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.roll_angular_velocity_constant = OPTIONS->roll_angular_velocity_constant; CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude.yaw_angular_velocity_constant = OPTIONS->yaw_angular_velocity_constant; } // end of initialize attitude for ensemble spacecraft if we run ensembles on the initial angular velocity } // end of if we run ensembles on the initial attitude if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing the attitude.\n"); } /*************************************************************************************/ /*************************************************************************************/ /********************** END OF COE AND TLE INITIALIZE: attitude **********************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*********************** COE AND TLE INITIALIZE: surface *****************************/ /*************************************************************************************/ /*************************************************************************************/ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing the geometry.\n"); } for (sss = 0; sss < OPTIONS->n_surfaces; sss++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].area = OPTIONS->surface[sss].area / (1e10); // !!!!!!!!!!!!!!!!!! TO ERASE /* if (ii == 3 || ii == 7){ */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[8].area = 5000.0 / (1e10); */ /* } */ // !!!!!!!!!!!!!!!!!! END OF TO ERASE CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].area_solar_panel = OPTIONS->surface[sss].area_solar_panel / (1e10); /*************************************************************************************/ /*********************** COE AND TLE INITIALIZE: ensembles on Cd *****************************/ /*************************************************************************************/ if (OPTIONS->nb_ensembles_cd > 0){ // if we run ensembles on Cd if (eee == 0){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii]; } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = randn( OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii], OPTIONS->surface[sss].Cd_sigma); // CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * 2 * eee; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS LINE AND UNCOMMENT THE PREVIOUS ONE!!! } } // end of if we run ensembles on Cd else{ // if we do not run ensembles on Cd // new cd if (OPTIONS->new_cd == 1){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].acco_coeff = OPTIONS->surface[sss].acco_coeff; } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * OPTIONS->cd_modification[ii]; // Coefficient of drag } // end of new cd // !!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS BLOCK BELOW //if ( ( ii == 2 ) || ( ii == 7 ) ){ //CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd*6; //} // !!!!!!!!!!!!!!!!!!!!!!!! END OF ERASE THIS BLOCK BELOW }// end of if we do not run ensembles on Cd // !!!!!!!!!!! THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].solar_radiation_coefficient = OPTIONS->surface[sss].solar_radiation_coefficient; // !!!!!!!!!!! END OF THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) // !!!!!!!!!! THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].specular_reflectivity = OPTIONS->surface[sss].specular_reflectivity; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].diffuse_reflectivity = OPTIONS->surface[sss].diffuse_reflectivity; */ // !!!!!!!!!! END OF THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].name_of_surface, OPTIONS->surface[sss].name_of_surface); // for (nnn = 0; nnn < 3; nnn++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].normal[nnn] = OPTIONS->surface[sss].normal[nnn]; // normal vector in the SC reference system } } for (sss = 0; sss < OPTIONS->n_surfaces_eff; sss++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].area = OPTIONS->surface_eff[sss].area / (1e10); // !!!!!!!!!!!!!!!!!! TO ERASE /* if (ii == 3 || ii == 7){ */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[8].area = 5000.0 / (1e10); */ /* } */ // !!!!!!!!!!!!!!!!!! END OF TO ERASE /*************************************************************************************/ /*********************** COE AND TLE INITIALIZE: ensembles on Cd *****************************/ /*************************************************************************************/ if (OPTIONS->nb_ensembles_cd > 0){ // if we run ensembles on Cd if (eee == 0){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd = OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii]; // !!!!!!!!! assumes that for all effective have the same cd } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd = randn( OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii], OPTIONS->surface[0].Cd_sigma); // !!!!!!!!! assumes that for all effective have the same cd // CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd * 2 * eee; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS LINE AND UNCOMMENT THE PREVIOUS ONE!!! } } // end of if we run ensembles on Cd else{ // if we do not run ensembles on Cd // new cd if (OPTIONS->new_cd == 1){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].acco_coeff = OPTIONS->surface[0].acco_coeff; // !!!!!!!!! assumes that for all effective have the same acco_coeff } else{ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].Cd = OPTIONS->surface[0].Cd * OPTIONS->cd_modification[ii]; // Coefficient of drag } // end of new cd // !!!!!!!!!!!!!!!!!!!!!!!! ERASE THIS BLOCK BELOW //if ( ( ii == 2 ) || ( ii == 7 ) ){ //CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].Cd = OPTIONS->surface[sss].Cd*6; //} // !!!!!!!!!!!!!!!!!!!!!!!! END OF ERASE THIS BLOCK BELOW }// end of if we do not run ensembles on Cd // !!!!!!!!!!! THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].solar_radiation_coefficient = OPTIONS->surface[0].solar_radiation_coefficient; // !!!!!!!!! assumes that for all effective have the same solar_radiation_coefficient // !!!!!!!!!!! END OF THIS BLOCK IS USING THE EQUATION FROM STK (http://www.agi.com/resources/help/online/stk/10.1/index.html?page=source%2Fhpop%2Fhpop-05.htm). UNCOMMENT THE BLOCK BELOW THAT USES VALLADO AND COMMENT THIS STK BLOCK IF YOU WANT TO USE VALLADO'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) // !!!!!!!!!! THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].specular_reflectivity = OPTIONS->surface[sss].specular_reflectivity; */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface[sss].diffuse_reflectivity = OPTIONS->surface[sss].diffuse_reflectivity; */ // !!!!!!!!!! END OF THIS BLOCK USES VALLADO'S EQUATIONS. COMMENT IT AND UNCOMMENT THE BLOCK ABOVE THAT USES STK IF YOU WANT TO USE STK'S EQUATIONS. ALSO NEED TO CHANGE initialize_constellation.c AND load_options.c TO READ THE SPECULAR AND DIFFUSE REFLECIVITIES IF YOU WANT TO USE VALLADO'S EQUATIONS (SEE COMMENTS IN THESE CODES) strcpy(CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].name_of_surface, "Area effective - ignore name"); // for (nnn = 0; nnn < 3; nnn++){ CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[nnn] = OPTIONS->surface_eff[sss].normal[nnn]; // normal vector in the SC reference system } } // end of surface effective if (OPTIONS->opengl == 1){ CONSTELLATION->area_attitude_opengl_phi0 = OPTIONS->area_attitude_opengl_phi0; CONSTELLATION->area_attitude_opengl_theta0 = OPTIONS->area_attitude_opengl_theta0; CONSTELLATION->area_attitude_opengl_dtheta = OPTIONS->area_attitude_opengl_dtheta; CONSTELLATION->area_attitude_opengl_dphi = OPTIONS->area_attitude_opengl_dphi; int nb_phi, nb_theta; nb_theta = (int)((180 - CONSTELLATION->area_attitude_opengl_theta0) / CONSTELLATION->area_attitude_opengl_dtheta ) + 1;// 180 is included (because different from theta = 0) nb_phi = (int)((360 - CONSTELLATION->area_attitude_opengl_phi0) / CONSTELLATION->area_attitude_opengl_dphi ) ; // 360 is not included (because same as phi = 0) CONSTELLATION->area_attitude_opengl = NULL; CONSTELLATION->area_attitude_opengl = malloc(nb_theta * sizeof(double **)); if ( CONSTELLATION->area_attitude_opengl == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_attitude_opengl. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->which_face_theta_phi = NULL; CONSTELLATION->which_face_theta_phi = malloc(nb_theta * sizeof(int **)); if ( CONSTELLATION->which_face_theta_phi == NULL){ printf("***! Could not allow memory to CONSTELLATION->which_face_theta_phi. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->area_attitude_opengl_total = NULL; CONSTELLATION->area_attitude_opengl_total = malloc(nb_theta * sizeof(double *)); if ( CONSTELLATION->area_attitude_opengl_total == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_attitude_opengl_total. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){ CONSTELLATION->area_solar_panel_attitude_opengl = NULL; CONSTELLATION->area_solar_panel_attitude_opengl = malloc(nb_theta * sizeof(double *)); if ( CONSTELLATION->area_solar_panel_attitude_opengl == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_solar_panel_attitude_opengl. The program will stop. !***\n"); MPI_Finalize(); exit(0); } } CONSTELLATION->nb_faces = OPTIONS->nb_faces; CONSTELLATION->nb_faces_theta_phi = NULL; CONSTELLATION->nb_faces_theta_phi = malloc(nb_theta * sizeof(double *)); if ( CONSTELLATION->nb_faces_theta_phi == NULL){ printf("***! Could not allow memory to CONSTELLATION->nb_faces_theta_phi. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->normal_face = NULL; CONSTELLATION->normal_face = malloc(OPTIONS->nb_faces * sizeof(double *)); if ( CONSTELLATION->normal_face == NULL){ printf("***! Could not allow memory to CONSTELLATION->normal_face. The program will stop. !***\n"); MPI_Finalize(); exit(0); } int itheta, iphi, iface, iface_here; for (iface = 0; iface < OPTIONS->nb_faces; iface++){ CONSTELLATION->normal_face[iface] = malloc(3 * sizeof(double)); if ( CONSTELLATION->normal_face[iface] == NULL){ printf("***! Could not allow memory to CONSTELLATION->normal_face[iface]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->normal_face[iface][0] = OPTIONS->normal_face[iface][0]; CONSTELLATION->normal_face[iface][1] = OPTIONS->normal_face[iface][1]; CONSTELLATION->normal_face[iface][2] = OPTIONS->normal_face[iface][2]; } for (itheta = 0; itheta < nb_theta; itheta++){ CONSTELLATION->area_attitude_opengl[itheta] = malloc(nb_phi * sizeof(double *)); if ( CONSTELLATION->area_attitude_opengl[itheta] == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_attitude_opengl[itheta]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->which_face_theta_phi[itheta] = malloc(nb_phi * sizeof(int *)); if ( CONSTELLATION->which_face_theta_phi[itheta] == NULL){ printf("***! Could not allow memory to CONSTELLATION->which_face_theta_phi[itheta]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->nb_faces_theta_phi[itheta] = malloc(nb_phi * sizeof(double)); if ( CONSTELLATION->nb_faces_theta_phi[itheta] == NULL){ printf("***! Could not allow memory to CONSTELLATION->nb_faces_theta_phi[itheta]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } CONSTELLATION->area_attitude_opengl_total[itheta] = malloc(nb_phi * sizeof(double)); if ( CONSTELLATION->area_attitude_opengl_total[itheta] == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_attitude_opengl_total[itheta]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){ CONSTELLATION->area_solar_panel_attitude_opengl[itheta] = malloc(nb_phi * sizeof(double)); if ( CONSTELLATION->area_solar_panel_attitude_opengl[itheta] == NULL){ printf("***! Could not allow memory to CONSTELLATION->area_solar_panel_attitude_opengl[itheta]. The program will stop. !***\n"); MPI_Finalize(); exit(0); } } for (iphi = 0; iphi < nb_phi; iphi++){ CONSTELLATION->nb_faces_theta_phi[itheta][iphi] = OPTIONS->nb_faces_theta_phi[itheta][iphi]; CONSTELLATION->area_attitude_opengl[itheta][iphi] = malloc(OPTIONS->nb_faces * sizeof(double)); CONSTELLATION->which_face_theta_phi[itheta][iphi] = malloc(OPTIONS->nb_faces * sizeof(int)); CONSTELLATION->area_attitude_opengl_total[itheta][iphi] = OPTIONS->area_attitude_opengl_total[itheta][iphi] / (1e10); if (( OPTIONS->solar_cell_efficiency != -1) && (OPTIONS->opengl_power == 1)){ CONSTELLATION->area_solar_panel_attitude_opengl[itheta][iphi] = OPTIONS->area_solar_panel_attitude_opengl[itheta][iphi]/ (1e10); } for (iface = 0; iface < OPTIONS->nb_faces_theta_phi[itheta][iphi]; iface++){ iface_here = OPTIONS->which_face_theta_phi[itheta][iphi][iface]; CONSTELLATION->area_attitude_opengl[itheta][iphi][iface_here] = OPTIONS->area_attitude_opengl[itheta][iphi][iface_here] / (1e10); // OPTIONS->area_attitude_opengl is in cm^2. Convert it here to km^2 CONSTELLATION->which_face_theta_phi[itheta][iphi][iface] = OPTIONS->which_face_theta_phi[itheta][iphi][iface] ; } } } /* for (itheta = 0; itheta < nb_theta; itheta++){ */ /* for (iphi = 0; iphi < nb_phi; iphi++){ */ /* printf("# %f %f %d\n", itheta * CONSTELLATION->area_attitude_opengl_dtheta + CONSTELLATION->area_attitude_opengl_theta0, iphi * CONSTELLATION->area_attitude_opengl_dphi + CONSTELLATION->area_attitude_opengl_phi0, CONSTELLATION->nb_faces_theta_phi[itheta][iphi]); */ /* for (iface = 0; iface < CONSTELLATION->nb_faces_theta_phi[itheta][iphi]; iface++){ */ /* iface_here = CONSTELLATION->which_face_theta_phi[itheta][iphi][iface]; */ /* printf("%d %f\n", iface_here, CONSTELLATION->area_attitude_opengl[itheta][iphi][iface_here]*1e10); */ /* } */ /* printf("%f\n", CONSTELLATION->area_attitude_opengl_total[itheta][iphi]*1e10); */ /* } */ /* } */ // exitf(); /* for (itheta = 0; itheta < nb_theta; itheta++){ */ /* for (iphi = 0; iphi < nb_phi; iphi++){ */ /* printf("ddd # %f %f %f\n", itheta * OPTIONS->area_attitude_opengl_dtheta + OPTIONS->area_attitude_opengl_theta0, iphi * OPTIONS->area_attitude_opengl_dphi + OPTIONS->area_attitude_opengl_phi0, OPTIONS->area_solar_panel_attitude_opengl[itheta][iphi]); */ /* } */ /* } */ /* exitf(); */ } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing the geometry.\n"); } /*************************************************************************************/ /*************************************************************************************/ /********************* END OF COE AND TLE INITIALIZE: surface ************************/ /*************************************************************************************/ /*************************************************************************************/ // printf("iProc: %d | eee = %d | from %d to %d | ii = %d\n", iProc, eee, start_ensemble_bis + iProc * OPTIONS->nb_ensemble_min_per_proc, iProc * OPTIONS->nb_ensemble_min_per_proc + OPTIONS->nb_ensemble_min_per_proc, ii); // the conversion of the acceleration from inrtl to lvlh is done in propagate_spacecraft but if init_flag = 1 the function propagate_spacecraft has not been called yet so the conversion inrtl to lvlh has not been done. Actually, the acceleration in the inertial frame has not been calculated yet either because it's calculated in propagate_spacecraft (with compute_dxdt) double v_dummy[3]; double test_density; if (eee == 0){ CONSTELLATION->spacecraft[ii][0].INTEGRATOR.file_given_output = fopen( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, "w+" ); } CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.write_given_output = 1; // printf("iProc %d start_ensemble[%d (%d)]: %d | dxdt\n", iProc, ii, eee, start_ensemble[ii]); // the only case where the attitute needs to be set is if there is no ensemble at all run on the attitude if ( ( strcmp(OPTIONS->attitude_profile, "ensemble_angular_velocity") != 0 ) && ( strcmp(OPTIONS->attitude_profile, "ensemble_initial_attitude") != 0 ) ) { // if we do not run ensembles on the initial angular velocity if (OPTIONS->nb_ensembles_attitude <= 0){ // if we dont' run ensembles of any kind on the attitude if ( ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.solar_cell_efficiency != -1) || (GROUND_STATION->nb_ground_stations > 0) || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_solar_pressure == 1) || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_earth_pressure == 1) || ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.include_drag == 1) ){ // these are the case where SpOCK uses the attitude if ( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.isGPS == 0){ // no attitude to set up for GPS because we dont compute the drag, solar rariatin pressu,re, power, and gorund station coverage (attitude is needed for coverage because we calculate azimuth and levation angles form the spaceecraft reference system) set_attitude( CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.attitude, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, OPTIONS, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.file_is_quaternion); } } } } // end of if the only case where the attitute needs to be set is the only case where it has not been set initially in initialize_constellation, which is if there is no ensemble at all run on the attitude compute_dxdt( v_dummy, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL, &CONSTELLATION->spacecraft[ii][eee].et, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, PARAMS, &CONSTELLATION->spacecraft[ii][eee].INTEGRATOR, et_initial_epoch, OPTIONS->et_oldest_tle_epoch, &test_density, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION, OPTIONS, iProc, iDebugLevel, &CONSTELLATION->spacecraft[ii][eee]); double T_inrtl_2_lvlh[3][3]; compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL); m_x_v(CONSTELLATION->spacecraft[ii][eee].a_i2cg_LVLH, T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL); } // end of if main sc ii is run by this iProc OR ( if this main sc is not run by this iProc and eee corresponds to an ensemble sc /* printf("%d\n", CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff); */ /* for (sss = 0; sss < CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.nb_surfaces_eff; sss++){ */ /* printf("normal[%d]: (%f, %f, %f) | total area: %f\n", sss, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[0], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[1], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].normal[2], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.surface_eff[sss].area*1e10); */ /* } */ /* exitf(); */ } // end go through all sc (including ensembels, if you run ensembles) other than GPS if (write_attitude_file == 1){ fclose(file_attitude[ii]); } /* // the conversion of the acceleration from inrtl to lvlh is done in propagate_spacecraft but if init_flag = 1 the function propagate_spacecraft has not been called yet so the conversion inrtl to lvlh has not been done. Actually, the acceleration in the inertial frame has not been calculated yet either because it's calculated in propagate_spacecraft (with compute_dxdt) */ /* double v_dummy[3]; */ /* double test_density; */ /* if (eee == 0){ */ /* CONSTELLATION->spacecraft[ii][0].INTEGRATOR.file_given_output = fopen( CONSTELLATION->spacecraft[ii][0].INTEGRATOR.filename_given_output, "w+" ); */ /* } */ /* CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.write_given_output = 1; */ /* printf("iProc %d start_ensemble[%d (%d)]: %d | dxdt\n", iProc, ii, eee, start_ensemble[ii]); */ /* compute_dxdt( v_dummy, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL, &CONSTELLATION->spacecraft[ii][eee].et, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL, PARAMS, &CONSTELLATION->spacecraft[ii][eee].INTEGRATOR, et_initial_epoch, OPTIONS->et_oldest_tle_epoch, &test_density, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_attitude_interpolated, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.index_in_driver_interpolated, CONSTELLATION, OPTIONS, iProc, iDebugLevel, &CONSTELLATION->spacecraft[ii][eee]); */ /* double T_inrtl_2_lvlh[3][3]; */ /* compute_T_inrtl_2_lvlh(T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][eee].v_i2cg_INRTL); */ /* m_x_v(CONSTELLATION->spacecraft[ii][eee].a_i2cg_LVLH, T_inrtl_2_lvlh, CONSTELLATION->spacecraft[ii][eee].a_i2cg_INRTL); */ // !!!!!!!!!!!!! below can be computed and printed only with one iproc if ((nProcs == 1) && (strcmp( OPTIONS->type_orbit_initialisation, "collision_vcm" ) == 0 )){ double std_r_alongtrack, std_r_crosstrack, std_r_radial, std_v_alongtrack, std_v_crosstrack, std_v_radial, std_bc, std_srp; double mean_r_alongtrack, mean_r_crosstrack, mean_r_radial, mean_v_alongtrack, mean_v_crosstrack, mean_v_radial, mean_bc, mean_srp; std_r_alongtrack = gsl_stats_sd(r_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_r_crosstrack = gsl_stats_sd(r_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_r_radial = gsl_stats_sd(r_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_v_alongtrack = gsl_stats_sd(v_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_v_crosstrack = gsl_stats_sd(v_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_v_radial = gsl_stats_sd(v_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_bc = gsl_stats_sd(bc_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); std_srp = gsl_stats_sd(srp_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_r_alongtrack = gsl_stats_mean(r_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_r_crosstrack = gsl_stats_mean(r_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_r_radial = gsl_stats_mean(r_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_v_alongtrack = gsl_stats_mean(v_alongtrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_v_crosstrack = gsl_stats_mean(v_crosstrack_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_v_radial = gsl_stats_mean(v_radial_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_bc = gsl_stats_mean(bc_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); mean_srp = gsl_stats_mean(srp_pert_all[ii], 1, ( OPTIONS->nb_ensembles_min ) ); printf("\nSC %d by iProc %d\nSTD:\n", ii, iProc); printf("pos: %.4f (radial) %.4f (along) %.4f (cross) km\n", std_r_radial, std_r_alongtrack, std_r_crosstrack); printf("vel: %.4e (radial) %.4e (along) %.4e (cross) km/s\n", std_v_radial, std_v_alongtrack, std_v_crosstrack ); // printf("bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\n", std_bc * 1e6, OPTIONS->bc_vcm[ii] * sqrt( OPTIONS->covariance_matrix_equinoctial[ii][6][6] ) , std_srp * 1e6 , OPTIONS->srp_vcm[ii] * sqrt( OPTIONS->covariance_matrix_equinoctial[ii][8][8] ) ); //i noticed that if the normalized variance in the vcm for bc or srp if very small (ie the std is very small compared to the mean vvalue) then my randm algoirthm can't compute distibutino to reprouce this very small std. it will run fine but the std will tend to be larger (by a factor 10 for sitnace). it deosnt really matter for wha ti want to do because if the std on bc is super small, its exact value doesnt matter too much (even by a factor 10) printf("bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\n", std_bc*std_bc * 1e12, OPTIONS->bc_cdm_std[ii]*OPTIONS->bc_cdm_std[ii] , std_srp*std_bc * 1e12 , OPTIONS->srp_cdm_std[ii] * OPTIONS->srp_cdm_std[ii] ); printf("\n MEAN:\n"); printf("pos: %.4e (radial) %.4e (along) %.4e (cross) m\n", mean_r_radial*1000, mean_r_alongtrack*1000, mean_r_crosstrack*1000); printf("vel: %.4e (radial) %.4e (along) %.4e (cross) m/s\n", mean_v_radial*1000, mean_v_alongtrack*1000, mean_v_crosstrack*1000 ); // printf("bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\n", mean_bc * 1e6, OPTIONS->bc_vcm[ii] , mean_srp * 1e6 , OPTIONS->srp_vcm[ii] ); printf("bc: %.4e (%.4e) | srp %.4e (%.4e) m2/kg\n", mean_bc * 1e6, OPTIONS->bc_cdm[ii] , mean_srp * 1e6 , OPTIONS->srp_cdm[ii] ); } } // end of go through all main SC other than GPS /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************** GPS *****************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ /*************************************************************************************/ if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Initializing the orbit for all GPS (%d GPS).\n", OPTIONS->nb_gps); } if (OPTIONS->nb_gps > 0){ gps_tle_file = fopen(OPTIONS->tle_constellation_gps_filename,"r"); } for (ii = OPTIONS->n_satellites - OPTIONS->nb_gps ; ii < OPTIONS->n_satellites; ii++){ // go over all GPS sc CONSTELLATION->spacecraft[ii] = malloc( sizeof(SPACECRAFT_T) ); // no ensemble for GPS satellites if ( start_ensemble[ii] == 0){ // if this iProc runs main sc ii CONSTELLATION->spacecraft[ii][0].INTEGRATOR.isGPS = 1; /*** Convert the TLEs into inertial state (postion, velocity) ***/ SpiceInt frstyr = 1961; // do not really care about this line (as long as the spacecrafts are not flying after 2060) // SpiceDouble geophs[8]; int pp; int lineln=0; size_t len = 0; char *line_temp = NULL; // SpiceDouble elems[10]; SpiceDouble state[6]; if ( ii == iStart_save[iProc] ){ for (bbb = 0; bbb < ii - (OPTIONS->n_satellites - OPTIONS->nb_gps); bbb++){ // for the first time the iProc opens the TLE file, it needs to skip the TLEs of the GPS that it is not running getline( &line_temp, &len, gps_tle_file ); getline( &line_temp, &len, gps_tle_file ); getline( &line_temp, &len, gps_tle_file ); } } /* /\* Set up the geophysical quantities. At last check these were the values used by Space Command and SGP4 *\/ */ /* PARAMS->geophs[ 0 ] = 1.082616e-3; // J2 */ /* PARAMS->geophs[ 1 ] = -2.53881e-6; // J3 */ /* PARAMS->geophs[ 2 ] = -1.65597e-6; // J4 */ /* PARAMS->geophs[ 3 ] = 7.43669161e-2; // KE */ /* PARAMS->geophs[ 4 ] = 120.0; // QO */ /* PARAMS->geophs[ 5 ] = 78.0; // SO */ /* PARAMS->geophs[ 6 ] = 6378.135; // ER */ /* PARAMS->geophs[ 7 ] = 1.0; // AE */ /* Read in the next two lines from the text file that contains the TLEs. */ // Skip the name of the GPS satellite that is being read getline( &line_temp, &len, gps_tle_file ); // printf("GPS %d by iProc %d:\n<%s>\n",ii-(OPTIONS->n_satellites - OPTIONS->nb_gps),iProc , line_temp); // First line getline( &line_temp, &len, gps_tle_file ); lineln = strlen(line_temp)-1; SpiceChar line[2][lineln]; for (pp = 0; pp<lineln-1 ; pp++) line[0][pp] = line_temp[pp]; line[0][ lineln-1 ] = '\0'; // Second line getline( &line_temp, &len, gps_tle_file ); for (pp = 0; pp<lineln-1 ; pp++) line[1][pp] = line_temp[pp]; line[1][ lineln-1 ] = '\0'; // Convert the elements of the TLE into "elems" and "epoch" that can be then read by the SPICE routine ev2lin_ to convert into the inertial state getelm_c( frstyr, lineln, line, &OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )], CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems ); // Now propagate the state using ev2lin_ to the epoch of interest extern /* Subroutine */ int ev2lin_(SpiceDouble *, SpiceDouble *, SpiceDouble *, SpiceDouble *); ev2lin_( &OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )], PARAMS->geophs, CONSTELLATION->spacecraft[ii][eee].INTEGRATOR.elems, state ); CONSTELLATION->spacecraft[ii][0].et = OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )]; CONSTELLATION->spacecraft[ii][eee].et_sc_initial = OPTIONS->epoch_gps[ii-(OPTIONS->n_satellites - OPTIONS->nb_gps )]; static doublereal precm[36]; static doublereal invprc[36] /* was [6][6] */; extern /* Subroutine */ int zzteme_(doublereal *, doublereal *); extern /* Subroutine */ int invstm_(doublereal *, doublereal *); extern /* Subroutine */ int mxvg_( doublereal *, doublereal *, integer *, integer *, doublereal *); zzteme_(&CONSTELLATION->spacecraft[ii][0].et, precm); /* ...now convert STATE to J2000. Invert the state transformation */ /* operator (important to correctly do this). */ invstm_(precm, invprc); static integer c__6 = 6; static doublereal tmpsta[6]; mxvg_(invprc, state, &c__6, &c__6, tmpsta); moved_(tmpsta, &c__6, state); for (pp = 0; pp<3; pp++){ CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[pp] = state[pp]; CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[pp] = state[pp+3]; } // Initialize the Keplerian Elements ORBITAL_ELEMENTS_T OE_temp; cart2kep( &OE_temp, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].et, PARAMS->EARTH.GRAVITY.mu); CONSTELLATION->spacecraft[ii][eee].OE.initial_an_to_sc = OE_temp.an_to_sc; CONSTELLATION->spacecraft[ii][eee].OE.w_ave_temp = OE_temp.w; CONSTELLATION->spacecraft[ii][eee].OE.w_ave = 9999.999999/RAD2DEG; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave_temp = OE_temp.sma; CONSTELLATION->spacecraft[ii][eee].OE.sma_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave_temp = OE_temp.eccentricity; CONSTELLATION->spacecraft[ii][eee].OE.ecc_ave = 9999.999999; CONSTELLATION->spacecraft[ii][eee].OE.ave_increm = 1; CONSTELLATION->spacecraft[ii][eee].et_last_orbit = CONSTELLATION->spacecraft[ii][eee].et; CONSTELLATION->spacecraft[ii][eee].orbit_number = 0; CONSTELLATION->spacecraft[ii][0].OE.sma =OE_temp.sma; CONSTELLATION->spacecraft[ii][0].OE.eccentricity =OE_temp.eccentricity; CONSTELLATION->spacecraft[ii][0].OE.inclination =OE_temp.inclination; CONSTELLATION->spacecraft[ii][0].OE.long_an =OE_temp.long_an; CONSTELLATION->spacecraft[ii][0].OE.w =OE_temp.w; CONSTELLATION->spacecraft[ii][0].OE.f =OE_temp.f; CONSTELLATION->spacecraft[ii][0].OE.tp =OE_temp.tp; CONSTELLATION->spacecraft[ii][0].OE.E =OE_temp.E; CONSTELLATION->spacecraft[ii][0].OE.ra =OE_temp.ra; radius_perigee = CONSTELLATION->spacecraft[ii][0].OE.sma * ( 1 - CONSTELLATION->spacecraft[ii][0].OE.eccentricity ); if (radius_perigee < PARAMS->EARTH.radius){ printf("***! The orbit of satellite %d intersects the Earth (altitude of perigee = %f km). The program will stop. !***\n",ii, radius_perigee-PARAMS->EARTH.radius); MPI_Finalize(); exit(0); } //// !!!!!! WEIRD: In this block, I test if going back to cart then to kep gives the same OE. It does. BUT, the cart is different (meaning the next line finds different cart than the one calculated a bit above but still results in the same OE). The reason for that is still not clear and if has to be found in the future! Future tests will validate that these results are correct, though. // Initialize the inertial state /* kep2cart( CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, */ /* &PARAMS->EARTH.GRAVITY.mu, */ /* &CONSTELLATION->spacecraft[ii][0].OE); // Computes the ECI coordinates based on the Keplerian inputs (orbital elements and mu) (in propagator.c) (CBV) */ /* ORBITAL_ELEMENTS_T OE_temp2; */ /* cart2kep( &OE_temp2, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL, CONSTELLATION->spacecraft[ii][0].et , PARAMS->EARTH.GRAVITY.mu); */ /* printf("\nsma = %f | %f\n",CONSTELLATION->spacecraft[ii][0].OE.sma, OE_temp2.sma); */ /* printf("inclination = %f | %f\n",CONSTELLATION->spacecraft[ii][0].OE.inclination*RAD2DEG, OE_temp2.inclination*RAD2DEG); */ /* printf("eccentricity = %f | %f\n", CONSTELLATION->spacecraft[ii][0].OE.eccentricity, OE_temp2.eccentricity); */ /* printf("long_an = %f | %f\n", CONSTELLATION->spacecraft[ii][0].OE.long_an, OE_temp2.long_an); */ /* printf("w = %f | %f\n", CONSTELLATION->spacecraft[ii][0].OE.w*RAD2DEG, OE_temp2.w*RAD2DEG); */ /* printf("tp = %f | %f\n", CONSTELLATION->spacecraft[ii][0].OE.tp, OE_temp2.tp); */ /* printf("E = %f | %f\n", CONSTELLATION->spacecraft[ii][0].OE.E, OE_temp2.E); */ /* eci2lla(CONSTELLATION->spacecraft[ii][eee].r_i2cg_INRTL , CONSTELLATION->spacecraft[ii][eee].et, geodetic ); */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.altitude = geodetic[2]; */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.latitude = geodetic[0]; */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.longitude = geodetic[1]; */ /* // Initialize the planet fixed state */ /* geodetic_to_geocentric(PARAMS->EARTH.flattening, */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.altitude, */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.latitude, */ /* CONSTELLATION->spacecraft[ii][0].GEODETIC.longitude, */ /* PARAMS->EARTH.radius, */ /* CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF) ; */ // Initialize the planet fixed state estate[0] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[0];estate[1] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[1];estate[2] = CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL[2]; estate[3] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[0];estate[4] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[1];estate[5] = CONSTELLATION->spacecraft[ii][0].v_i2cg_INRTL[2]; sxform_c ( "J2000", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][0].et, xform ); mxvg_c ( xform, estate, 6, 6, jstate ); CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[0] = jstate[0]; CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[1] = jstate[1]; CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF[2] = jstate[2]; CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[0] = jstate[3]; CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[1] = jstate[4]; CONSTELLATION->spacecraft[ii][0].v_ecef2cg_ECEF[2] = jstate[5]; /* pxform_c( "J2000", PARAMS->EARTH.earth_fixed_frame, CONSTELLATION->spacecraft[ii][0].et, T_J2000_to_ECEF); // Return the matrix (here T_J2000_to_ECEF) that transforms position vectors from one specified frame (here J2000) to another (here ITRF93) at a specified epoch (in /Users/cbv/cspice/src/cspice/pxform_c.c) (CBV) */ /* m_x_v(CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF, T_J2000_to_ECEF, CONSTELLATION->spacecraft[ii][0].r_i2cg_INRTL); // multiply a matrix by a vector (in prop_math.c). So here we convert ECI (J2000) to ECEF coordinates (CBV) */ // initialize the geodetic state- geocentric_to_geodetic( CONSTELLATION->spacecraft[ii][0].r_ecef2cg_ECEF, &PARAMS->EARTH.radius, &PARAMS->EARTH.flattening, &CONSTELLATION->spacecraft[ii][0].GEODETIC.altitude, &CONSTELLATION->spacecraft[ii][0].GEODETIC.latitude, &CONSTELLATION->spacecraft[ii][0].GEODETIC.longitude ); // Computes lat/long/altitude based on ECEF coordinates and planet fixed state (planetary semimajor axis, flattening parameter) (in propagator.c) (CBV) // Output file for each spacecraft strcpy(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filename, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filename, OPTIONS->filename_output[ii]); // Now CONSTELLATION->spacecraft[ii][0].filenameecef is moved to generate_ephemerides because we want iProc 0 to know CONSTELLATION->spacecraft[ii][0].filenameecef even for the main sc ii that it does not run (this is because iProc 0 will gather all ECEF files at the end of the propagation) /* strcpy(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->dir_output_run_name_sat_name[ii]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, "/"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, "ECEF_"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameecef, OPTIONS->filename_output[ii]); */ strcpy(CONSTELLATION->spacecraft[ii][0].filenamerho, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho, "density_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamerho,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenameout, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenameout, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenameout, "LLA_"); strcat(CONSTELLATION->spacecraft[ii][0].filenameout,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenameatt, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt, "LLA_"); strcat(CONSTELLATION->spacecraft[ii][0].filenameatt,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman, "kalman_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, OPTIONS->dir_output_run_name_sat_name[ii]); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, "/"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas, "meas_converted_kalman_"); strcat(CONSTELLATION->spacecraft[ii][0].filenamekalman_meas,OPTIONS->filename_output[ii]); strcpy(CONSTELLATION->spacecraft[ii][0].filename_kalman_init, OPTIONS->filename_kalman_init); // I COMMENTED BELOW EBCAUSE I DON'T SEE ANY REASON TO COMPUTE THE GROUND STATION COVERAGE FOR GPS /* if (OPTIONS->nb_ground_stations > 0){ */ /* for ( iground = 0; iground < OPTIONS->nb_ground_stations; iground ++){ */ /* strcpy(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->dir_output_run_name_sat_name_coverage[ii]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], "/"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], OPTIONS->name_ground_station[iground]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground], "_by_"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filename_coverage_ground_station[iground],OPTIONS->filename_output[ii]); */ /* } */ /* } */ // cbv COMMENTED THIS BLOCK ON APRIL 22 218 BECASESUE SOLAR POWER IS NOT COMPUTED FOR GPS /* if (CONSTELLATION->spacecraft[ii][0].INTEGRATOR.solar_cell_efficiency != -1){ */ /* strcpy(CONSTELLATION->spacecraft[ii][0].filenamepower, OPTIONS->dir_output_run_name_sat_name[ii]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, "/"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenamepower, "power_"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenamepower,OPTIONS->filename_output[ii]); */ /* strcpy(CONSTELLATION->spacecraft[ii][0].filenameeclipse, OPTIONS->dir_output_run_name_sat_name[ii]); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, "/"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse, "eclipse_"); */ /* strcat(CONSTELLATION->spacecraft[ii][0].filenameeclipse,OPTIONS->filename_output[ii]); */ /* } */ // end of cbv COMMENTED THIS BLOCK ON APRIL 22 218 BECASESUE SOLAR POWER IS NOT COMPUTED FOR GPS // Name of each satellite strcpy(CONSTELLATION->spacecraft[ii][0].name_sat, ""); strcpy(CONSTELLATION->spacecraft[ii][0].name_sat, OPTIONS->gps_file_name[ii - (OPTIONS->n_satellites - OPTIONS->nb_gps)]); /* // Compute the Orbital period of the first state */ /* period = pow( CONSTELLATION->spacecraft[ii][0].OE.sma, 3.0); */ /* period = period / PARAMS->EARTH.GRAVITY.mu; */ /* period = 2.0 * M_PI * sqrt( period ); */ // Integrator CONSTELLATION->spacecraft[ii][0].INTEGRATOR.sc_main_nb = ii; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.sc_ensemble_nb = 0; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.dt = OPTIONS->dt; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.dt_pos_neg = OPTIONS->dt_pos_neg; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.nb_surfaces = 1; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.nb_surfaces_eff = 1; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.mass = 1630.0; // Wikipedia... CONSTELLATION->spacecraft[ii][0].INTEGRATOR.solar_cell_efficiency = -1; // do not care for now CONSTELLATION->spacecraft[ii][0].INTEGRATOR.degree = OPTIONS->degree; // Gravity degree CONSTELLATION->spacecraft[ii][0].INTEGRATOR.order = OPTIONS->order; // Gravity order CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_drag = 0; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_solar_pressure = 0; // do not care for now CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_earth_pressure = 0; // do not care for now CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_sun = OPTIONS->include_sun; // include Sun perturbations (CBV) CONSTELLATION->spacecraft[ii][0].INTEGRATOR.include_moon = OPTIONS->include_moon; // include Moon perturbations (CBV) CONSTELLATION->spacecraft[ii][0].INTEGRATOR.index_in_attitude_interpolated = 0; // do not care for now because the attitude is for the power, solar radiation pressure, earth_pressure, or drag. For GPS satellite, we do not compute these (the main reason is that the TLE do not give the geometry). However, we need to set it to 0 (like a regular spacecraft) because to compute coverage, the variable index_in_attitude_interpolated is used CONSTELLATION->spacecraft[ii][0].INTEGRATOR.index_in_driver_interpolated = 0; // do not care for now because the attitude is for the power, solar radiation pressure, or drag. For GPS satellite, we do not compute these (the main reason is that the TLE do not give the geometry) CONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod = OPTIONS->density_mod; // // the desnity given by msis is multiplied by density_mod + density_amp * sin(2*pi*t/T + density_phase*T) where T is the orbital period CONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod_amp = OPTIONS->density_mod_amp; CONSTELLATION->spacecraft[ii][0].INTEGRATOR.density_mod_phase = OPTIONS->density_mod_phase; } // end of if this iProc runs main sc ii } // end of go over all GPS sc if (OPTIONS->nb_gps > 0){ fclose(gps_tle_file); } if (iDebugLevel >= 1){ if (iProc == 0) printf("-- (initialize_constellation) Done initializing the orbit for all GPS (%d GPS).\n", OPTIONS->nb_gps); } /* For the specular points computation */ if (OPTIONS->nb_gps > 0){ strcpy(CONSTELLATION->filename_CYGNSS_constellation_for_specular, OPTIONS->dir_output_run_name); strcat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, "/CONSTELLATION_CYGNSS_for_run_"); next = OPTIONS->filename_output[0]; find_file_name = (int)(strchr(next, '.') - next); strncat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, next, find_file_name); strcat(CONSTELLATION->filename_CYGNSS_constellation_for_specular, ".txt"); strcpy(CONSTELLATION->filename_GPS_constellation_for_specular, OPTIONS->dir_output_run_name); strcat(CONSTELLATION->filename_GPS_constellation_for_specular, "/CONSTELLATION_GPS_for_run_"); next = OPTIONS->filename_output[0]; find_file_name = (int)(strchr(next, '.') - next); strncat(CONSTELLATION->filename_GPS_constellation_for_specular, next, find_file_name); strcat(CONSTELLATION->filename_GPS_constellation_for_specular, ".txt"); } /* end of for the specular points computation */ if (OPTIONS->nb_ground_stations > 0){ for (iground = 0; iground < OPTIONS->nb_ground_stations; iground++){ strcpy( GROUND_STATION->name_ground_station[iground], OPTIONS->name_ground_station[iground]); GROUND_STATION->latitude_ground_station[iground] = OPTIONS->latitude_ground_station[iground] * DEG2RAD; GROUND_STATION->longitude_ground_station[iground] = OPTIONS->longitude_ground_station[iground] * DEG2RAD; GROUND_STATION->altitude_ground_station[iground] = OPTIONS->altitude_ground_station[iground]; GROUND_STATION->min_elevation_angle_ground_station[iground] = OPTIONS->min_elevation_angle_ground_station[iground] * DEG2RAD; // Convert lla position of ground station into ECEF geodetic_to_geocentric( PARAMS->EARTH.flattening, GROUND_STATION->altitude_ground_station[iground]/1000., GROUND_STATION->latitude_ground_station[iground], GROUND_STATION->longitude_ground_station[iground], PARAMS->EARTH.radius, GROUND_STATION->ecef_ground_station[iground]); } GROUND_STATION->nb_ground_stations = OPTIONS->nb_ground_stations; } /* if ( ( strcmp(OPTIONS->format_density_driver, "density_file") != 0 ) && ( strcmp(OPTIONS->format_density_driver, "gitm") != 0 ) ){ */ /* if ( strcmp(OPTIONS->format_density_driver, "dynamic") == 0 ){ */ /* /\* free(OPTIONS->Ap); *\/ */ /* /\* // if (OPTIONS->use_ap_hist == 1){ *\/ */ /* /\* free(OPTIONS->Ap_hist); *\/ */ /* /\* // } *\/ */ /* /\* free(OPTIONS->f107); *\/ */ /* /\* free(OPTIONS->f107A); *\/ */ /* } */ /* } */ /* else{ */ /* free(OPTIONS->density); */ /* } */ /* free(OPTIONS->et_interpo); */ // printf("uudpqw90jdwqdpwuuuuuu %f\n", CONSTELLATION->spacecraft[0][0].INTEGRATOR.attitude.pitch[0]); return 0; } double randu ( double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/ { double U1; struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); U1 = -1 + ((double) rand () / RAND_MAX) * 2; return (mu + sigma * (double) U1); } double randn ( double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/ { double U1, U2, W, mult; static double X1, X2; static int call = 0; struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec); // srand(time(NULL) + iProc); if (call == 1) { call = !call; return (mu + sigma * (double) X2); } do { U1 = -1 + ((double) rand () / RAND_MAX) * 2; U2 = -1 + ((double) rand () / RAND_MAX) * 2; W = pow (U1, 2) + pow (U2, 2); } while (W >= 1 || W == 0); mult = sqrt ((-2 * log (W)) / W); X1 = U1 * mult; X2 = U2 * mult; call = !call; return (mu + sigma * (double) X1); } double randn_iproc (int iProc, double mu, double sigma) // source: http://phoxis.org/2013/05/04/plot-histogram-in-terminal/ // note: the only difference with rand is that the seed here depends on iProc (the seed should actually also depends on iProcs in rand because it depends on the time with microsecond accuracy so each iProcs calls it at a different time) { double U1, U2, W, mult; static double X1, X2; static int call = 0; struct timeval t1; gettimeofday(&t1, NULL); srand(t1.tv_usec * t1.tv_sec + iProc); // srand(time(NULL) + iProc); if (call == 1) { call = !call; return (mu + sigma * (double) X2); } do { U1 = -1 + ((double) rand () / RAND_MAX) * 2; U2 = -1 + ((double) rand () / RAND_MAX) * 2; W = pow (U1, 2) + pow (U2, 2); } while (W >= 1 || W == 0); mult = sqrt ((-2 * log (W)) / W); X1 = U1 * mult; X2 = U2 * mult; call = !call; return (mu + sigma * (double) X1); } int sign(double x){ if (x > 0) return 1; if (x < 0) return -1; return 0; } /* LocalWords: min */
{ "alphanum_fraction": 0.6549094819, "avg_line_length": 66.4046367852, "ext": "c", "hexsha": "8a87da88bbc6befd1754c4c55a6162206ca3934f", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-09-23T10:31:06.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-09T15:55:59.000Z", "max_forks_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "splowitz1/spock-1", "max_forks_repo_path": "src/initialize_constellation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "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": "splowitz1/spock-1", "max_issues_repo_path": "src/initialize_constellation.c", "max_line_length": 712, "max_stars_count": 3, "max_stars_repo_head_hexsha": "855e5af02564a07118716ea8cb0b37f0a992df7b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "splowitz1/spock-1", "max_stars_repo_path": "src/initialize_constellation.c", "max_stars_repo_stars_event_max_datetime": "2021-06-15T18:13:51.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-07T08:44:06.000Z", "num_tokens": 61609, "size": 214819 }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_randist.h> #include "allvars.h" #include "proto.h" int mcmc_sampling(char *fname_mcmc, double (* prob_fun)(double *theta)) { const int n_cov_update=10000; double prob, prob_new, scale, ratio, u; double theta[ntheta], theta_new[ntheta]; double var_cov_mat[ntheta*ntheta], Pmatrix[ntheta*ntheta], Prandvec[ntheta], Py[ntheta]; double *theta_mcmc; int istep, iaccpt, i, j, info, flag; FILE *fmcmc; fmcmc = fopen(fname_mcmc, "w"); theta_mcmc = array_malloc(ntheta*n_cov_update); /* * sampling in logrithm space. */ memcpy(theta, theta_input, ntheta*sizeof(double)); for(i=0; i<ntheta; i++) { var_cov_mat[i*ntheta+i] = sigma_input[i] * sigma_input[i]; for(j=0; j<i; j++) var_cov_mat[i*ntheta+j] = var_cov_mat[j*ntheta + i] = 0.0; } memcpy(Pmatrix, var_cov_mat, ntheta*ntheta*sizeof(double)); Chol_decomp_U(Pmatrix, ntheta, &info); scale = 1.0; prob = prob_fun(theta); istep = 0; iaccpt = 0; printf("step:%6d", 0); while(istep < nmcmc) { flag = 1; while(flag) { for(i=0; i<ntheta; i++) { Prandvec[i] = gsl_ran_gaussian(gsl_r, 1.0); } multiply_matvec(Pmatrix, Prandvec, ntheta, Py); flag = 0; for(i=0; i<ntheta; i++) { if(theta_fixed[i]==1) { theta_new[i] = theta[i]; } else { theta_new[i] = theta[i] + scale * Py[i]; if(theta_new[i]<theta_range[i][0] || theta_new[i]>theta_range[i][1]) { flag = 1; break; } } } } prob_new = prob_fun(theta_new); ratio = prob_new - prob; if(ratio > 0.0) { memcpy(theta, theta_new, ntheta*sizeof(double)); prob = prob_new; iaccpt++; } else { u = gsl_rng_uniform(gsl_r); if(log(u) < ratio) { memcpy(theta, theta_new, ntheta*sizeof(double)); prob = prob_new; iaccpt++; } } for(i=0; i<ntheta; i++) theta_mcmc[i*n_cov_update + istep%n_cov_update] = theta[i]; if(istep%10==0)printf("\b\b\b\b\b\b%6d", istep); fprintf(fmcmc, "%d", istep); for(i=0;i<ntheta;i++) { fprintf(fmcmc,"\t%f", theta[i]); } fprintf(fmcmc, "\t%e\n", prob); istep++; if(istep%n_cov_update == 0) { get_cov_matrix_diag(theta_mcmc, n_cov_update, ntheta); memcpy(var_cov_mat, cov_matrix, ntheta*ntheta*sizeof(double)); //display_mat(var_cov_mat, ntheta, ntheta); memcpy(Pmatrix, var_cov_mat, ntheta*ntheta*sizeof(double)); Chol_decomp_U(Pmatrix, ntheta, &info); } } printf("\n"); printf("Accept rate: %f\n", 1.0*iaccpt/istep); fclose(fmcmc); free(theta_mcmc); return 0; }
{ "alphanum_fraction": 0.5751905752, "avg_line_length": 23.2741935484, "ext": "c", "hexsha": "726e49a755faa2fd89679cccc74f995f6891a054", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z", "max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z", "max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/MICA", "max_forks_repo_path": "src/mcmc.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/MICA", "max_issues_repo_path": "src/mcmc.c", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/MICA", "max_stars_repo_path": "src/mcmc.c", "max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z", "num_tokens": 898, "size": 2886 }
/* * Copyright 2008-2014 NVIDIA 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. */ #include <cblas.h> #include <cusp/complex.h> #define CUSP_CBLAS_EXPAND_REAL_DEFS(FUNC_MACRO) \ FUNC_MACRO(float , float , s) \ FUNC_MACRO(double, double, d) #define CUSP_CBLAS_AMAX(T,V,name) \ template<int dummy> \ int amax( const int n, const T* X, const int incX ) \ { \ return cblas_i##name##amax(n, (const V*) X, incX); \ } #define CUSP_CBLAS_ASUM(T,V,name) \ template<int dummy> \ V asum( const int n, const T* X, const int incX ) \ { \ return cblas_##name##asum(n, (const V*) X, incX); \ } #define CUSP_CBLAS_AXPY(T,V,name) \ template<int dummy> \ void axpy( const int n, const T alpha, const T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##axpy(n, alpha, (const V*) X, incX, (V*) Y, incY); \ } #define CUSP_CBLAS_COPY(T,V,name) \ template<int dummy> \ void copy( const int n, const T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##copy(n, (const V*) X, incX, (V*) Y, incY); \ } #define CUSP_CBLAS_DOT(T,V,name) \ template<int dummy> \ T dot( const int n, const T* X, const int incX, const T* Y, const int incY ) \ { \ return cblas_##name##dot(n, (const V*) X, incX, (const V*) Y, incY); \ } #define CUSP_CBLAS_NRM2(T,V,name) \ template<int dummy> \ V nrm2( const int n, const T* X, const int incX ) \ { \ return cblas_##name##nrm2(n, (const V*) X, incX); \ } #define CUSP_CBLAS_SCAL(T,V,name) \ template<int dummy> \ void scal( const int n, const T alpha, T* X, const int incX ) \ { \ cblas_##name##scal(n, alpha, (V*) X, incX); \ } #define CUSP_CBLAS_SWAP(T,V,name) \ template<int dummy> \ void swap( const int n, T* X, const int incX, T* Y, const int incY ) \ { \ cblas_##name##swap(n, (V*) X, incX, (V*) Y, incY); \ } #define CUSP_CBLAS_GEMV(T,V,name) \ template<int dummy> \ void gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, \ int m, int n, T alpha, const T* A, int lda, \ const T* x, int incx, T beta, T* y, int incy) \ { \ cblas_##name##gemv(order, trans, m, n, alpha, A, lda, x, incx, beta, y, incy); \ } #define CUSP_CBLAS_GER(T,V,name) \ template<int dummy> \ void ger( CBLAS_ORDER order, int m, int n, T alpha, const T* x, int incx, \ const T* y, int incy, T* A, int lda) \ { \ cblas_##name##ger(order, m, n, alpha, \ (const V*) x, incx, (const V*) y, incy, \ (V*) A, lda); \ } #define CUSP_CBLAS_SYMV(T,V,name) \ template<int dummy> \ void symv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ int n, T alpha, const T* A, int lda, \ const T* x, int incx, T beta, T* y, int incy) \ { \ cblas_##name##symv(order, uplo, n, alpha, (const V*) A, lda, \ (const V*) x, incx, beta, (V*) y, incy); \ } #define CUSP_CBLAS_SYR(T,V,name) \ template<int dummy> \ void syr( CBLAS_ORDER order, CBLAS_UPLO uplo, \ int n, T alpha, const T* x, int incx, T* A, int lda) \ { \ cblas_##name##syr(order, uplo, n, alpha, \ (const V*) x, incx, (V*) A, lda); \ } #define CUSP_CBLAS_TRMV(T,V,name) \ template<int dummy> \ void trmv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int n, const T* A, int lda, T* x, int incx) \ { \ cblas_##name##trmv(order, uplo, trans, diag, n, \ (const V*) A, lda, (V*) x, incx); \ } #define CUSP_CBLAS_TRSV(T,V,name) \ template<int dummy> \ void trsv( CBLAS_ORDER order, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int n, const T* A, int lda, T* x, int incx) \ { \ cblas_##name##trsv(order, uplo, trans, diag, n, \ (const V*) A, lda, (V*) x, incx); \ } #define CUSP_CBLAS_GEMM(T,V,name) \ template<int dummy> \ void gemm( CBLAS_ORDER order, \ CBLAS_TRANSPOSE transa, CBLAS_TRANSPOSE transb, \ int m, int n, int k, T alpha, const T* A, int lda, \ const T* B, int ldb, T beta, T* C, int ldc) \ { \ cblas_##name##gemm(order, transa, transb, \ m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); \ } #define CUSP_CBLAS_SYMM(T,V,name) \ template<int dummy> \ void symm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ int m, int n, T alpha, const T* A, int lda, \ const T* B, int ldb, T beta, T* C, int ldc) \ { \ cblas_##name##symm(order, side, uplo, m, n, \ (V) alpha, (const V*) A, lda, (const V*) B, ldb, \ (V) beta, (V*) C, ldc); \ } #define CUSP_CBLAS_SYRK(T,V,name) \ template<int dummy> \ void syrk( CBLAS_ORDER order, \ CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \ int n, int k, T alpha, const T* A, int lda, \ T beta, T* C, int ldc) \ { \ cblas_##name##syrk(order, uplo, trans, n, k, \ (V) alpha, (const V*) A, lda, \ (V) beta, (V*) C, ldc); \ } #define CUSP_CBLAS_SYR2K(T,V,name) \ template<int dummy> \ void syr2k( CBLAS_ORDER order, \ CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \ int n, int k, T& alpha, const T* A, int lda, \ const T* B, int ldb, T& beta, T* C, int ldc) \ { \ cblas_##name##syr2k(order, uplo, trans, n, k, \ alpha, (const V*) A, lda, \ (const V*) B, ldb, beta, (V*) C, ldc); \ } #define CUSP_CBLAS_TRMM(T,V,name) \ template<int dummy> \ void trmm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int m, int n, T alpha, const T* A, int lda, \ T* B, int ldb) \ { \ cblas_##name##trmm(order, side, uplo, trans, diag, m, n, \ (V) alpha, (const V*) A, lda, (V*) B, ldb); \ } #define CUSP_CBLAS_TRSM(T,V,name) \ template<int dummy> \ void trsm( CBLAS_ORDER order, \ CBLAS_SIDE side, CBLAS_UPLO uplo, \ CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \ int m, int n, T alpha, const T* A, int lda, \ T* B, int ldb) \ { \ cblas_##name##trsm(order, side, uplo, trans, diag, m, n, \ (V) alpha, (const V*) A, lda, (V*) B, ldb); \ } namespace cusp { namespace system { namespace cpp { namespace detail { namespace cblas { // LEVEL 1 CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_AMAX); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_ASUM); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_AXPY); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_COPY); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_DOT); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_NRM2); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SCAL); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SWAP); // LEVEL 2 CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GEMV); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GER); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYMV); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYR); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRMV); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRSV); // LEVEL 3 CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GEMM); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYMM); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYRK); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYR2K); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRMM); CUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRSM); } // end namespace cblas } // end namespace detail } // end namespace cpp } // end namespace system } // end namespace cusp
{ "alphanum_fraction": 0.3118456951, "avg_line_length": 62.2964426877, "ext": "h", "hexsha": "94dab50004729dcb731f883ab2e9f60dbe192c1a", "lang": "C", "max_forks_count": 106, "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z", "max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "njh19/cusplibrary", "max_forks_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_issues_count": 41, "max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "njh19/cusplibrary", "max_issues_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_line_length": 93, "max_stars_count": 270, "max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Raman-sh/cusplibrary", "max_stars_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z", "num_tokens": 2977, "size": 15761 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_syr (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; int N = 1; int lda = 1; float alpha = 0.1f; float A[] = { -0.291f }; float X[] = { 0.845f }; int incX = -1; float A_expected[] = { -0.219597f }; cblas_ssyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], flteps, "ssyr(case 1402)"); } }; }; { int order = 101; int uplo = 122; int N = 1; int lda = 1; float alpha = 0.1f; float A[] = { -0.291f }; float X[] = { 0.845f }; int incX = -1; float A_expected[] = { -0.219597f }; cblas_ssyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], flteps, "ssyr(case 1403)"); } }; }; { int order = 102; int uplo = 121; int N = 1; int lda = 1; float alpha = 0.1f; float A[] = { -0.291f }; float X[] = { 0.845f }; int incX = -1; float A_expected[] = { -0.219597f }; cblas_ssyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], flteps, "ssyr(case 1404)"); } }; }; { int order = 102; int uplo = 122; int N = 1; int lda = 1; float alpha = 0.1f; float A[] = { -0.291f }; float X[] = { 0.845f }; int incX = -1; float A_expected[] = { -0.219597f }; cblas_ssyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], flteps, "ssyr(case 1405)"); } }; }; { int order = 101; int uplo = 121; int N = 1; int lda = 1; double alpha = -0.3; double A[] = { -0.65 }; double X[] = { -0.891 }; int incX = -1; double A_expected[] = { -0.8881643 }; cblas_dsyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr(case 1406)"); } }; }; { int order = 101; int uplo = 122; int N = 1; int lda = 1; double alpha = -0.3; double A[] = { -0.65 }; double X[] = { -0.891 }; int incX = -1; double A_expected[] = { -0.8881643 }; cblas_dsyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr(case 1407)"); } }; }; { int order = 102; int uplo = 121; int N = 1; int lda = 1; double alpha = -0.3; double A[] = { -0.65 }; double X[] = { -0.891 }; int incX = -1; double A_expected[] = { -0.8881643 }; cblas_dsyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr(case 1408)"); } }; }; { int order = 102; int uplo = 122; int N = 1; int lda = 1; double alpha = -0.3; double A[] = { -0.65 }; double X[] = { -0.891 }; int incX = -1; double A_expected[] = { -0.8881643 }; cblas_dsyr(order, uplo, N, alpha, X, incX, A, lda); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(A[i], A_expected[i], dbleps, "dsyr(case 1409)"); } }; }; }
{ "alphanum_fraction": 0.4812426729, "avg_line_length": 19.8372093023, "ext": "c", "hexsha": "a54378e6dea513c42d613f1694fea9bf67a65028", "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/cblas/test_syr.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/cblas/test_syr.c", "max_line_length": 68, "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/cblas/test_syr.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": 1350, "size": 3412 }
/* histogram/test2d.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 <stdio.h> #include <gsl/gsl_histogram2d.h> #include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #define M 107 #define N 239 #define M1 17 #define N1 23 #define MR 10 #define NR 5 int main (void) { double xr[MR + 1] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; double yr[NR + 1] = {90.0, 91.0, 92.0, 93.0, 94.0, 95.0}; gsl_histogram2d *h, *h1, *g, *hr; size_t i, j, k; gsl_ieee_env_setup (); h = gsl_histogram2d_calloc (M, N); h1 = gsl_histogram2d_calloc (M, N); g = gsl_histogram2d_calloc (M, N); gsl_test (h->xrange == 0, "gsl_histogram2d_calloc returns valid xrange pointer"); gsl_test (h->yrange == 0, "gsl_histogram2d_calloc returns valid yrange pointer"); gsl_test (h->bin == 0, "gsl_histogram2d_calloc returns valid bin pointer"); gsl_test (h->nx != M, "gsl_histogram2d_calloc returns valid nx"); gsl_test (h->ny != N, "gsl_histogram2d_calloc returns valid ny"); hr = gsl_histogram2d_calloc_range (MR, NR, xr, yr); gsl_test (hr->xrange == 0, "gsl_histogram2d_calloc_range returns valid xrange pointer"); gsl_test (hr->yrange == 0, "gsl_histogram2d_calloc_range returns valid yrange pointer"); gsl_test (hr->bin == 0, "gsl_histogram2d_calloc_range returns valid bin pointer"); gsl_test (hr->nx != MR, "gsl_histogram2d_calloc_range returns valid nx"); gsl_test (hr->ny != NR, "gsl_histogram2d_calloc_range returns valid ny"); { int status = 0; for (i = 0; i <= MR; i++) { if (hr->xrange[i] != xr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram2d_calloc_range creates xrange correctly"); } { int status = 0; for (i = 0; i <= NR; i++) { if (hr->yrange[i] != yr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram2d_calloc_range creates yrange correctly"); } for (i = 0; i <= MR; i++) { hr->xrange[i] = 0.0; } for (i = 0; i <= NR; i++) { hr->yrange[i] = 0.0; } { int status = gsl_histogram2d_set_ranges (hr, xr, MR+1, yr, NR+1); for (i = 0; i <= MR; i++) { if (hr->xrange[i] != xr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram2d_set_ranges sets xrange correctly"); } { int status = 0; for (i = 0; i <= NR; i++) { if (hr->yrange[i] != yr[i]) { status = 1; } }; gsl_test (status, "gsl_histogram2d_set_ranges sets yrange correctly"); } k = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { k++; gsl_histogram2d_accumulate (h, (double) i, (double) j, (double) k); }; } { int status = 0; k = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { k++; if (h->bin[i * N + j] != (double) k) { status = 1; } } } gsl_test (status, "gsl_histogram2d_accumulate writes into array correctly"); } { int status = 0; k = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { k++; if (gsl_histogram2d_get (h, i, j) != (double) k) status = 1; }; } gsl_test (status, "gsl_histogram2d_get reads from array correctly"); } for (i = 0; i <= M; i++) { h1->xrange[i] = 100.0 + i; } for (i = 0; i <= N; i++) { h1->yrange[i] = 900.0 + i*i; } gsl_histogram2d_memcpy (h1, h); { int status = 0; for (i = 0; i <= M; i++) { if (h1->xrange[i] != h->xrange[i]) status = 1; }; gsl_test (status, "gsl_histogram2d_memcpy copies bin xranges correctly"); } { int status = 0; for (i = 0; i <= N; i++) { if (h1->yrange[i] != h->yrange[i]) status = 1; }; gsl_test (status, "gsl_histogram2d_memcpy copies bin yranges correctly"); } { int status = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { if (gsl_histogram2d_get (h1, i, j) != gsl_histogram2d_get (h, i, j)) status = 1; } } gsl_test (status, "gsl_histogram2d_memcpy copies bin values correctly"); } gsl_histogram2d_free (h1); h1 = gsl_histogram2d_clone (h); { int status = 0; for (i = 0; i <= M; i++) { if (h1->xrange[i] != h->xrange[i]) status = 1; }; gsl_test (status, "gsl_histogram2d_clone copies bin xranges correctly"); } { int status = 0; for (i = 0; i <= N; i++) { if (h1->yrange[i] != h->yrange[i]) status = 1; }; gsl_test (status, "gsl_histogram2d_clone copies bin yranges correctly"); } { int status = 0; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { if (gsl_histogram2d_get (h1, i, j) != gsl_histogram2d_get (h, i, j)) status = 1; } } gsl_test (status, "gsl_histogram2d_clone copies bin values correctly"); } gsl_histogram2d_reset (h); { int status = 0; for (i = 0; i < M * N; i++) { if (h->bin[i] != 0) status = 1; } gsl_test (status, "gsl_histogram2d_reset zeros array correctly"); } gsl_histogram2d_free (h); h = gsl_histogram2d_calloc (M1, N1); { int status = 0; for (i = 0; i < M1; i++) { for (j = 0; j < N1; j++) { gsl_histogram2d_increment (h, (double) i, (double) j); for (k = 0; k <= i * N1 + j; k++) { if (h->bin[k] != 1) { status = 1; } } for (k = i * N1 + j + 1; k < M1 * N1; k++) { if (h->bin[k] != 0) { status = 1; } } } } gsl_test (status, "gsl_histogram2d_increment works correctly"); } gsl_histogram2d_free (h); h = gsl_histogram2d_calloc (M, N); { int status = 0; for (i = 0; i < M; i++) { double x0 = 0, x1 = 0; gsl_histogram2d_get_xrange (h, i, &x0, &x1); if (x0 != i || x1 != i + 1) { status = 1; } } gsl_test (status, "gsl_histogram2d_get_xlowerlimit and xupperlimit works correctly"); } { int status = 0; for (i = 0; i < N; i++) { double y0 = 0, y1 = 0; gsl_histogram2d_get_yrange (h, i, &y0, &y1); if (y0 != i || y1 != i + 1) { status = 1; } } gsl_test (status, "gsl_histogram2d_get_ylowerlimit and yupperlimit works correctly"); } { int status = 0; if (gsl_histogram2d_xmax (h) != M) status = 1; gsl_test (status, "gsl_histogram2d_xmax works correctly"); } { int status = 0; if (gsl_histogram2d_xmin (h) != 0) status = 1; gsl_test (status, "gsl_histogram2d_xmin works correctly"); } { int status = 0; if (gsl_histogram2d_nx (h) != M) status = 1; gsl_test (status, "gsl_histogram2d_nx works correctly"); } { int status = 0; if (gsl_histogram2d_ymax (h) != N) status = 1; gsl_test (status, "gsl_histogram2d_ymax works correctly"); } { int status = 0; if (gsl_histogram2d_ymin (h) != 0) status = 1; gsl_test (status, "gsl_histogram2d_ymin works correctly"); } { int status = 0; if (gsl_histogram2d_ny (h) != N) status = 1; gsl_test (status, "gsl_histogram2d_ny works correctly"); } h->bin[3*N+2] = 123456.0; h->bin[4*N+3] = -654321; { double max = gsl_histogram2d_max_val (h); gsl_test (max != 123456.0, "gsl_histogram2d_max_val finds maximum value"); } { double min = gsl_histogram2d_min_val (h); gsl_test (min != -654321.0, "gsl_histogram2d_min_val finds minimum value"); } { size_t imax, jmax; gsl_histogram2d_max_bin (h, &imax, &jmax); gsl_test (imax != 3 || jmax != 2, "gsl_histogram2d_max_bin finds maximum value bin"); } { size_t imin, jmin; gsl_histogram2d_min_bin (h, &imin, &jmin); gsl_test (imin != 4 || jmin != 3, "gsl_histogram2d_min_bin find minimum value bin"); } for (i = 0; i < M*N; i++) { h->bin[i] = i + 27; g->bin[i] = (i + 27) * (i + 1); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_add (h1, h); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != g->bin[i] + h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_add works correctly"); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_sub (h1, h); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != g->bin[i] - h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_sub works correctly"); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_mul (h1, h); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != g->bin[i] * h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_mul works correctly"); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_div (h1, h); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != g->bin[i] / h->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_div works correctly"); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_scale (h1, 0.5); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != 0.5 * g->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_scale works correctly"); } gsl_histogram2d_memcpy (h1, g); gsl_histogram2d_shift (h1, 0.25); { int status = 0; for (i = 0; i < M*N; i++) { if (h1->bin[i] != 0.25 + g->bin[i]) status = 1; } gsl_test (status, "gsl_histogram2d_shift works correctly"); } gsl_histogram2d_free (h); /* free whatever is in h */ h = gsl_histogram2d_calloc_uniform (M1, N1, 0.0, 5.0, 0.0, 5.0); gsl_test (h->xrange == 0, "gsl_histogram2d_calloc_uniform returns valid range pointer"); gsl_test (h->yrange == 0, "gsl_histogram2d_calloc_uniform returns valid range pointer"); gsl_test (h->bin == 0, "gsl_histogram2d_calloc_uniform returns valid bin pointer"); gsl_test (h->nx != M1, "gsl_histogram2d_calloc_uniform returns valid nx"); gsl_test (h->ny != N1, "gsl_histogram2d_calloc_uniform returns valid ny"); gsl_histogram2d_accumulate (h, 0.0, 3.01, 1.0); gsl_histogram2d_accumulate (h, 0.1, 2.01, 2.0); gsl_histogram2d_accumulate (h, 0.2, 1.01, 3.0); gsl_histogram2d_accumulate (h, 0.3, 0.01, 4.0); { size_t i1, i2, i3, i4; size_t j1, j2, j3, j4; double expected; int status; status = gsl_histogram2d_find (h, 0.0, 3.01, &i1, &j1); status = gsl_histogram2d_find (h, 0.1, 2.01, &i2, &j2); status = gsl_histogram2d_find (h, 0.2, 1.01, &i3, &j3); status = gsl_histogram2d_find (h, 0.3, 0.01, &i4, &j4); for (i = 0; i < M1; i++) { for (j = 0; j < N1; j++) { if (i == i1 && j == j1) { expected = 1.0; } else if (i == i2 && j == j2) { expected = 2.0; } else if (i == i3 && j == j3) { expected = 3.0; } else if (i == i4 && j == j4) { expected = 4.0; } else { expected = 0.0; } if (h->bin[i * N1 + j] != expected) { status = 1; } } } gsl_test (status, "gsl_histogram2d_find works correctly"); } { FILE *f = fopen ("test.txt", "w"); gsl_histogram2d_fprintf (f, h, "%.19g", "%.19g"); fclose (f); } { FILE *f = fopen ("test.txt", "r"); gsl_histogram2d *hh = gsl_histogram2d_calloc (M1, N1); int status = 0; gsl_histogram2d_fscanf (f, hh); for (i = 0; i <= M1; i++) { if (h->xrange[i] != hh->xrange[i]) { printf ("xrange[%d] : %g orig vs %g\n", (int)i, h->xrange[i], hh->xrange[i]); status = 1; } } for (j = 0; j <= N1; j++) { if (h->yrange[j] != hh->yrange[j]) { printf ("yrange[%d] : %g orig vs %g\n", (int)j, h->yrange[j], hh->yrange[j]); status = 1; } } for (i = 0; i < M1 * N1; i++) { if (h->bin[i] != hh->bin[i]) { printf ("bin[%d] : %g orig vs %g\n", (int)i, h->bin[i], hh->bin[i]); status = 1; } } gsl_test (status, "gsl_histogram2d_fprintf and fscanf work correctly"); gsl_histogram2d_free (hh); fclose (f); } { FILE *f = fopen ("test.dat", "wb"); gsl_histogram2d_fwrite (f, h); fclose (f); } { FILE *f = fopen ("test.dat", "rb"); gsl_histogram2d *hh = gsl_histogram2d_calloc (M1, N1); int status = 0; gsl_histogram2d_fread (f, hh); for (i = 0; i <= M1; i++) { if (h->xrange[i] != hh->xrange[i]) { printf ("xrange[%d] : %g orig vs %g\n", (int)i, h->xrange[i], hh->xrange[i]); status = 1; } } for (j = 0; j <= N1; j++) { if (h->yrange[j] != hh->yrange[j]) { printf ("yrange[%d] : %g orig vs %g\n", (int)j, h->yrange[j], hh->yrange[j]); status = 1; } } for (i = 0; i < M1 * N1; i++) { if (h->bin[i] != hh->bin[i]) { printf ("bin[%d] : %g orig vs %g\n", (int)i, h->bin[i], hh->bin[i]); status = 1; } } gsl_test (status, "gsl_histogram2d_fwrite and fread work correctly"); gsl_histogram2d_free (hh); fclose (f); } gsl_histogram2d_free (h); gsl_histogram2d_free (h1); gsl_histogram2d_free (g); gsl_histogram2d_free (hr); exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.5394475921, "avg_line_length": 21.1694152924, "ext": "c", "hexsha": "89a23b8e566397a38bec677f737e70e2ccda5366", "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/histogram/test2d.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/histogram/test2d.c", "max_line_length": 89, "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/histogram/test2d.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": 5053, "size": 14120 }
// Implementation of interface described in float_blob.h. #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <glib.h> #include <glib/gstdio.h> #include <gsl/gsl_math.h> #include "float_blob.h" #include "float_image.h" #include "utilities.h" FloatBlob * float_blob_new (gssize size_x, gssize size_y, const char *scratch_dir, const char *name) { g_assert (size_x > 0 && size_y > 0); g_assert (g_file_test (scratch_dir, G_FILE_TEST_IS_DIR)); g_assert (g_access (scratch_dir, R_OK | W_OK | X_OK) == 0); FloatBlob *self = g_new (FloatBlob, 1); self->size_x = size_x; self->size_y = size_y; self->swapped_bytes = FALSE; if ( name != NULL ) { self->file = ensure_slash_terminated (g_string_new (scratch_dir)); g_string_append (self->file, name); } else { self->file = make_unique_tmp_file_name (scratch_dir, "float_blob_tmp_"); g_assert (!g_file_test (self->file->str, G_FILE_TEST_EXISTS)); } self->is_file_owner = TRUE; self->fd = open (self->file->str, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); g_assert (self->fd != -1); // Out of carefulness we didn't truncate, but we want to make sure // we really got a new file. g_assert (file_size (self->fd) == 0); // Seek to last byte of file. off_t last_byte_offset = (off_t) self->size_x * (off_t) self->size_y * sizeof (float) - 1; off_t file_offset = lseek (self->fd, last_byte_offset, SEEK_SET); g_assert (file_offset == last_byte_offset); // Write a byte at the end of the file. size_t bytes_to_write = 1; g_assert (sizeof (unsigned char) == 1); unsigned char good_old_zero = 0x0; ssize_t bytes_written = write (self->fd, &good_old_zero, bytes_to_write); g_assert (bytes_written == bytes_to_write); // We should now have reserved all the space needed in this file. g_assert (file_size (self->fd) == last_byte_offset + 1); self->reference_count = 1; return self; } FloatBlob * float_blob_new_using (gssize size_x, gssize size_y, const char *file, gboolean swapped_bytes) { g_assert (size_x > 0 && size_y > 0); g_assert (g_file_test (file, G_FILE_TEST_IS_REGULAR)); g_assert (g_access (file, R_OK | W_OK) == 0); FloatBlob *self = g_new (FloatBlob, 1); self->fd = open (file, O_RDWR); g_assert (self->fd != -1); g_assert (file_size (self->fd) >= (off_t) size_x * size_y * sizeof (float)); self->size_x = size_x; self->size_y = size_y; self->swapped_bytes = swapped_bytes; self->file = g_string_new (file); self->is_file_owner = FALSE; self->reference_count = 1; return self; } static void float_blob_region_transfer (FloatBlob *self, gssize start_x, gssize start_y, gssize w, gssize h, float *buffer, gboolean is_get_transfer) { g_assert (start_x >= 0 && start_x < self->size_x); g_assert (start_y >= 0 && start_y < self->size_y); g_assert (w > 0 && start_x + w <= self->size_x); g_assert (h > 0 && start_y + h <= self->size_y); ssize_t (*transfer)(int fd, void *buf, size_t count) = is_get_transfer ? read : ((ssize_t (*)(int, void *, size_t)) write); size_t jj; for ( jj = start_y ; jj < start_y + h ; jj++ ) { off_t file_offset = lseek (self->fd, sizeof (float) * ((off_t) jj * self->size_x + start_x), SEEK_SET); g_assert (file_offset != (off_t) -1); size_t transfer_size = w * sizeof (float); ssize_t transfer_result = transfer (self->fd, buffer + (jj - start_y) * w, transfer_size); if ( transfer_result == -1 ) { g_error ("I/O error: %s\n", strerror (errno)); } g_assert (transfer_result == transfer_size); } } void float_blob_get_region (FloatBlob *self, gssize start_x, gssize start_y, gssize w, gssize h, float *buffer) { float_blob_region_transfer (self, start_x, start_y, w, h, buffer, TRUE); if ( self->swapped_bytes ) { swap_array_bytes_32 (buffer, w * h); } } void float_blob_set_region (FloatBlob *self, gssize start_x, gssize start_y, gssize w, gssize h, float *buffer) { if ( self->swapped_bytes ) { swap_array_bytes_32 (buffer, w * h); } float_blob_region_transfer (self, start_x, start_y, w, h, buffer, FALSE); if ( self->swapped_bytes ) { swap_array_bytes_32 (buffer, w * h); } } GString * float_blob_steal_file (FloatBlob *self) { g_assert (self->is_file_owner == TRUE); self->is_file_owner = FALSE; return g_string_new (self->file->str); } void float_blob_export_as_jpeg (FloatBlob *self, const char *file, double mask) { // Self as float image. FloatImage *safi = float_image_new (self->size_x, self->size_y); float *row_buffer = g_new (float, self->size_x); // We are about to use swap_32 type function, so we have a quick // attack of paranoia and check sizeof float... g_assert (sizeof (float) == 4); // Seek to the beginning of the file. off_t resultant_offset = lseek (self->fd, 0, SEEK_SET); if ( resultant_offset == (off_t) -1 ) { g_error ("lseek failed: %s\n", strerror (errno)); } g_assert (resultant_offset == 0); size_t ii, jj; for ( jj = 0 ; jj < self->size_y ; jj++ ) { // Read one row of data from the file underlying self. ssize_t bytes_to_read = self->size_x * sizeof (float); ssize_t read_count = read (self->fd, row_buffer, bytes_to_read); g_assert (read_count == bytes_to_read); // Swap row bytes if necessary. if ( self->swapped_bytes ) { swap_array_bytes_32 (row_buffer, self->size_x); } // Write that row to the FloatImage. for ( ii = 0 ; ii < self->size_x ; ii++ ) { float_image_set_pixel (safi, ii, jj, row_buffer[ii]); } } g_free (row_buffer); float_image_export_as_jpeg (safi, file, GSL_MAX (safi->size_x, safi->size_y), mask); float_image_unref (safi); } FloatBlob * float_blob_ref (FloatBlob *self) { g_assert (self->reference_count > 0); self->reference_count++; return self; } void float_blob_unref (FloatBlob *self) { g_assert (self->reference_count > 0); self->reference_count--; if ( self->reference_count == 0 ) { int return_code = close (self->fd); g_assert (return_code == 0); if ( self->is_file_owner ) { return_code = unlink (self->file->str); if ( return_code != 0 ) { g_error ("unlink of float_blob file '%s' in function %s, (file " __FILE__ ", line %d) failed: %s", self->file->str, __func__, __LINE__, strerror (errno)); } g_assert (return_code == 0); } g_string_free (self->file, TRUE); g_free (self); self = NULL; } }
{ "alphanum_fraction": 0.6556561086, "avg_line_length": 26.2055335968, "ext": "c", "hexsha": "97b228bbac84bdad7f7707da57d6db54f554e03a", "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/ssv/float_blob.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/ssv/float_blob.c", "max_line_length": 79, "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/ssv/float_blob.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": 1973, "size": 6630 }
/* * 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. */ #ifndef SRC_RUNTIME_LOCAL_KERNELS_SYRK_H #define SRC_RUNTIME_LOCAL_KERNELS_SYRK_H #include <runtime/local/context/DaphneContext.h> #include <runtime/local/datastructures/CSRMatrix.h> #include <runtime/local/datastructures/DataObjectFactory.h> #include <runtime/local/datastructures/DenseMatrix.h> #include <cblas.h> // **************************************************************************** // Struct for partial template specialization // **************************************************************************** template<class DTRes, class DTArg> struct Syrk { static void apply(DTRes *& res, const DTArg * arg, DCTX(ctx)) = delete; }; // **************************************************************************** // Convenience function // **************************************************************************** template<class DTRes, class DTArg> void syrk(DTRes *& res, const DTArg * arg, DCTX(ctx)) { Syrk<DTRes, DTArg>::apply(res, arg, ctx); } // **************************************************************************** // (Partial) template specializations for different data/value types // **************************************************************************** // ---------------------------------------------------------------------------- // DenseMatrix <- DenseMatrix // ---------------------------------------------------------------------------- template<> struct Syrk<DenseMatrix<double>, DenseMatrix<double>> { static void apply(DenseMatrix<double> *& res, const DenseMatrix<double> * arg, DCTX(ctx)) { const size_t numRows = arg->getNumRows(); const size_t numCols = arg->getNumCols(); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<double>>(numCols, numCols, false); cblas_dsyrk(CblasRowMajor, CblasUpper, CblasTrans, numCols, numRows, 1.0, arg->getValues(), arg->getRowSkip(), 0.0, res->getValues(), res->getRowSkip()); for (auto r = 0u; r < numCols; ++r) { for (auto c = r + 1; c < numCols; ++c) { res->set(c, r, res->get(r, c)); } } } }; template<> struct Syrk<DenseMatrix<float>, DenseMatrix<float>> { static void apply(DenseMatrix<float> *& res, const DenseMatrix<float> * arg, DCTX(ctx)) { const size_t numRows = arg->getNumRows(); const size_t numCols = arg->getNumCols(); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<float>>(numCols, numCols, false); cblas_ssyrk(CblasRowMajor, CblasUpper, CblasTrans, numCols, numRows, 1.0, arg->getValues(), arg->getRowSkip(), 0.0, res->getValues(), res->getRowSkip()); for (auto r = 0u; r < numCols; ++r) { for (auto c = r + 1; c < numCols; ++c) { res->set(c, r, res->get(r, c)); } } } }; // ---------------------------------------------------------------------------- // CSRMatrix <- CSRMatrix // ---------------------------------------------------------------------------- template<typename VT> struct Syrk<CSRMatrix<VT>, CSRMatrix<VT>> { static void apply(CSRMatrix<VT> *& res, const CSRMatrix<VT> * arg, DCTX(ctx)) { const size_t numRows = arg->getNumRows(); const size_t numCols = arg->getNumCols(); if(res == nullptr) res = DataObjectFactory::create<CSRMatrix<VT>>(numCols, numRows, arg->getNumNonZeros(), false); assert(false && "TODO: Syrk for Sparse"); } }; #endif //SRC_RUNTIME_LOCAL_KERNELS_SYRK_H
{ "alphanum_fraction": 0.5031992687, "avg_line_length": 35.008, "ext": "h", "hexsha": "e26d66318ec5ea31d7e9e67d95bb74c8207d01c5", "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/Syrk.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/Syrk.h", "max_line_length": 107, "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/Syrk.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": 910, "size": 4376 }
#include <iostream> #include <vector> #include <memory> #include <cstdlib> #include <cstddef> #ifdef ENABLE_GSL #include <gsl/gsl_integration.h> #include <gsl/gsl_deriv.h> #include <cmath> #endif #ifndef PI #define PI 3.141593 #endif #ifndef Grav #define Grav 4.7788e-20 // Newton's over c^2 in Mpc / Msun #endif #ifndef lightspeed #define lightspeed 2.99792458e5 // km / s #endif #ifndef error_message #define error_message #define ERROR_MESSAGE() std::cerr << "ERROR: file: " << __FILE__ << " line: " << __LINE__ << std::endl; #endif #define CRITD 2.49783e18 /* critical density / Ho^2 solar/Mpc */ #define CRITD2 2.7752543e11 /* critical density / h^2 M_sun/Mpc^3 */ #ifndef cosmo_declare enum CosmoParamSet {WMAP5yr,Millennium,Planck1yr,Planck15,Planck18,BigMultiDark,none}; std::ostream &operator<<(std::ostream &os, CosmoParamSet p); /** * * \brief The cosmology and all the functions required to calculated quantities based on the cosmology. * * This class is used to store the cosmological parameters, calculate cosmological distances, calculate * the power spectrum of density fluctuations and the mass function of halos. * * As set now, there are no baryon acoustic oscillations in the power spectrum, but this can be changed * at the expense of not including neutrinos. */ class COSMOLOGY{ public: COSMOLOGY(CosmoParamSet cosmo_p = WMAP5yr); /// if justdistances== true COSMOLOGY(double omegam,double omegal,double h, double w = -1,double wa = 0 ,bool justdistances=false /// if true the internals needed calculate structure formation will not be calculated making constructuion faster ); COSMOLOGY(const COSMOLOGY &cosmo); ~COSMOLOGY(); COSMOLOGY& operator=(const COSMOLOGY &cosmo); // returns the parameter set if any CosmoParamSet ParamSet(){return cosmo_set;} void PrintCosmology(short physical = 0) const; std::string print(short physical= 0) const; // Lengths double rcurve() const; //double emptyDist(double zo,double z); double coorDist(double zo,double z) const; double coorDist(double z) const {return coorDist(0,z);} double radDist(double zo,double z) const; double radDist(double z) const {return radDist(0,z);} double angDist(double zo,double z) const; double angDist(double z) const {return angDist(0,z);} double lumDist(double zo,double z) const; double lumDist(double z) const {return lumDist(0,z);} /// derivative of coordinate distance with respect to Omo in flat cosmology. Useful for Fisher matrix calculations double d_coorDist_dOmo(double zo,double z) const; /// derivative of coordinate distance with respect to w. Useful for Fisher matrix calculations double d_coorDist_dw(double zo,double z) const; /// derivative of coordinate distance with respect to w1. Useful for Fisher matrix calculations double d_coorDist_dw1(double zo,double z) const; double DRradius(double zo,double z,double pfrac); double DRradius2(double zo,double z); double invCoorDist(double d) const; double invRadDist(double d) const; double invComovingDist(double d) const; double scalefactor(double rad) const; double Omegam(double z) const; double rho_crit_comoving(double z) const; //double drdz_empty(double x); double drdz(double x) const; //double adrdz(double x) const; double drdz_dark(double x) const; inline double dark_factor(double x) const; //double adrdz_dark(double x) const; /// the critical over density double delta_c() const; double DeltaVir(double z,int caseunit=0) const; double Deltao(double m) const; double time(double z) const; double nonlinMass(double z) const; // Stuff having to do with the power spectrum double power_normalize(double sigma8); /** * \brief Linear power spectrum P(k,z)/a^2 */ double power_linear(double k,double z); double Dgrowth(double z) const; /** * \brief powerCDM.c calculates the nonlinear P(k,z)/a(r)^2 * * The method of Peacock & Dodds 1996 is used to convert the linear * power spectrum into the nonlinear one. * This could be updated to a more recent nonlinear power spectrum */ double powerCDMz(double k,double z); double psdfdm(double z,double m,int caseunit=0); double halo_bias (double m, double z, int t=0); double stdfdm(double z,double m,int caseunit=0); double powerlawdfdm(double z,double m,double alpha,int caseunit=0); double haloNumberDensity(double m,double z,double a, int t,double alpha = 0.0); /** \brief Dark matter correlation function * * This integrates powerCDMz() to get the correlation function as a function of comoving radius. * Care should be taken that the right range of k is integrated over if the radius is very small or large. */ double CorrelationFunction(double radius,double redshift ,double k_max = 100,double k_min = 1.0e-3); struct CorrFunctorType{ CorrFunctorType(COSMOLOGY *cosmo,double radius,double redshift) : cosmology(cosmo),z(redshift),r(radius) { norm = 0.5/PI/PI/(1+z)/(1+z); }; COSMOLOGY *cosmology; double z; double r; double norm; double operator () (double k) { double rk = r*k; double jo = sin(rk)/rk; if(rk < 1.0e-3) jo = 1.0; return norm*jo*k*k*cosmology->powerCDMz(k,z); } }; double haloNumberDensityOnSky (double m,double z1,double z2,int t,double alpha = 0.0); double haloNumberInBufferedCone (double mass ,double z1,double z2,double fov,double buffer ,int type ,double alpha=0.0); double haloMassInBufferedCone (double mass ,double z1,double z2,double fov,double buffer ,int type ,double alpha=0.0); double TopHatVariance(double m) const; double TopHatVarianceR(double R,double z); double TopHatVarianceM(double M,double z); //double gradius(double R,double rd); double getTimefromDeltaC(double dc); double getZfromDeltaC(double dc); /// accesser functions: /// Hubble paremters in units of 100 km/s/Mpc, renormalizes P(k) to keep sig8 fixed void sethubble(double ht){ h = ht; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;} double gethubble() const {return h;} /// Hubble parameter in 1/Mpc units double getHubble() const {return 100*h/lightspeed;} /// Primordial spectral index, renormalizes P(k) to keep sig8 fixed void setindex(double nn){ n = nn; power_normalize(sig8); cosmo_set = none;} double getindex() const { return n;} /// Omega matter, renormalizes P(k) to keep sig8 fixed void setOmega_matter(double Omega_matter,bool FLAT = false){Omo = Omega_matter; if(FLAT) Oml = 1-Omo ; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;} double getOmega_matter() const {return Omo;} /// Omega lambda, renormalizes P(k) to keep sig8 fixed void setOmega_lambda(double Omega_lambda,bool FLAT = false){Oml = Omega_lambda; if(FLAT) Oml = 1-Omo ; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none;} double getOmega_lambda() const {return Oml;} /// Omega baryon, renormalizes P(k) to keep sig8 fixed void setOmega_baryon(double Omega_baryon){Omb = Omega_baryon; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none; } double getOmega_baryon() const {return Omb;} /// Omega neutrino, renormalizes P(k) to keep sig8 fixed void setOmega_neutrino(double Omega_neutrino){Omnu = Omega_neutrino; TFmdm_set_cosm(); power_normalize(sig8); calc_interp_dist(); cosmo_set = none; } double getOmega_neutrino() const {return Omnu;} /// Number of neutrino species, renormalizes P(k) to keep sig8 fixed void setNneutrino(double Nneutrino){Nnu = Nneutrino; TFmdm_set_cosm(); power_normalize(sig8); cosmo_set = none;} double getNneutrino() const {return Nnu;} /// Dark energy equation of state parameter p/rho = w + w_1 (1+z) void setW(double w){ww = w; calc_interp_dist(); cosmo_set = none;} double getW() const {return ww;} void setW1(double w){ww1 = w; calc_interp_dist(); cosmo_set = none;} double getW1() const {return ww1;} /// Running of primordial spectral index, P(k)_primordial \propto pow(k/h,n+dndlnk*log(k)), renormalizes P(k) to keep sig8 fixed void setdndlnk(double w){dndlnk = w; power_normalize(sig8); cosmo_set = none;} double getdndlnk() const {return dndlnk;} /// Alternative to w for dark energy/ alt. grav. structure evolution void setgamma(double gamm){gamma = gamm; cosmo_set = none;} double getgamma() const {return gamma;} // If physical = 1 all Omega are Omega*h^2 otherwise they have the usual definitions. // 2 gamma parameterization is used for dark energy void setDEtype(short tt){darkenergy = tt; cosmo_set = none;} short getDEtype() const {return darkenergy;} void setSigma8(double my_sig8){power_normalize(my_sig8); cosmo_set = none;} double getSigma8() const {return sig8;} void dzdangDist(double D,double z[],double dzdD[]); double totalMassDensityinHalos(int t,double alpha,double m_min,double z,double z1,double z2); /// set interpolation range and number of points void setInterpolation(double z_interp, std::size_t n_interp); /// The lensing critical density in Msun / Mpc^2 double SigmaCrit(double zlens,double zsource) const; protected: void SetConcordenceCosmology(CosmoParamSet cosmo_p); CosmoParamSet cosmo_set; // structure rappers to make integration thread safe struct drdz_struct{ drdz_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.drdz(x);} COSMOLOGY const &cos; }; struct drdzdark_struct{ drdzdark_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.drdz_dark(x);} COSMOLOGY const &cos; }; struct adrdz_struct{ adrdz_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.drdz(x)/x;} COSMOLOGY const &cos; }; struct adrdzdark_struct{ adrdzdark_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.drdz_dark(x)/x;} COSMOLOGY const &cos; }; struct normL_struct{ normL_struct(COSMOLOGY &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.normL(x);} COSMOLOGY &cos; }; double ddrdzdOmo(double x) const; double ddrdzdw(double x) const; double ddrdzdw1(double x) const; struct ddrdzdOmo_struct{ ddrdzdOmo_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.ddrdzdOmo(x);} COSMOLOGY const &cos; }; struct ddrdzdw_struct{ ddrdzdw_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.ddrdzdw(x);} COSMOLOGY const &cos; }; struct ddrdzdw1_struct{ ddrdzdw1_struct(COSMOLOGY const &cosmo):cos(cosmo){}; double operator()(double x) const {return cos.ddrdzdw1(x);} COSMOLOGY const &cos; }; bool init_structure_functions; /// Hubble paremters in units of 100 km/s/Mpc double h; /// Primordial spectral index double n; /// Omega matter, dark matter + baryons double Omo; /// Omega lambda double Oml; /// Omega baryon double Omb; /// Omega neutrino double Omnu; /// Number of neutrino species double Nnu; /// Dark energy equation of state parameter p/rho = ww + ww_1 (1+z) double ww; /// Dark energy equation of state parameter p/rho = ww + ww_1 (1+z) double ww1; /// Running of primordial spectral index, P(k)_primordial \propto pow(k/h,n+dndlnk*log(k)) double dndlnk; /// Alternative to w for dark energy/ alt. grav. structure evolution double gamma; // If physical = 1 all Omega are Omega*h^2 otherwise they have the usual definitions. //short physical; // 2 gamma parameterization is used for dark energy short darkenergy; /* table for growth parameter */ //std::auto_ptr<double> *aa; //std::auto_ptr<double> *growth; //int Ntable; double A; double sig8; /* do not access these normalization outside */ double Rtophat; double ztmp; double powerEH(double k,double z); double powerEHv2(double k); double powerloc(double k,double z); double npow(double k); double normL(double lgk); double gradius(double R,double rd) const; int nbin; // number of points when binning to interpolate std:: vector<double> vDeltaCz,vlz,vt; double DpropDz(double z); double dsigdM(double m); double timeEarly(double a) const; double dNdz(double z); typedef double (COSMOLOGY::*pt2MemFunc)(double) const; typedef double (COSMOLOGY::*pt2MemFuncNonConst)(double); double nintegrateDcos(pt2MemFunc func,double a,double b,double tols) const; double trapzdDcoslocal(pt2MemFunc func, double a, double b, int n, double *s2) const; void polintD(double xa[], double ya[], int n, double x, double *y, double *dy) const; double nintegrateDcos(pt2MemFuncNonConst func,double a,double b,double tols); double trapzdDcoslocal(pt2MemFuncNonConst func, double a, double b, int n, double *s2); double dfridrDcos(pt2MemFunc func, double x, double h, double *err); double f4(double u) const; int ni; std::vector<float> xf, wf; // The parameters used in Eisenstein & Hu power spectrum /* in powerEH.c */ short TFmdm_set_cosm_change_z(double redshift); short TFmdm_set_cosm(); double TFmdm_onek_mpc(double kk); double TFmdm_onek_hmpc(double kk); double f_baryon; // Baryon fraction double f_bnu; // Baryon + Massive Neutrino fraction double f_cb; // Baryon + CDM fraction double f_cdm; // CDM fraction double f_hdm; // Massive Neutrino fraction double alpha_gamma; // sqrt(alpha_nu) double alpha_nu; // The small-scale suppression double beta_c; // The correction to the log in the small-scale double num_degen_hdm; // Number of degenerate massive neutrino species double growth_k0; // D_1(z) -- the growth function as k->0 double growth_to_z0; // D_1(z)/D_1(0) -- the growth relative to z=0 double k_equality; // The comoving wave number of the horizon at equality double obhh; // Omega_baryon * hubble^2 double omega_curv; // = 1 - omega_matter - omega_lambda double omega_lambda_z; // Omega_lambda at the given redshift double omega_matter_z; // Omega_matter at the given redshift double omhh; // Omega_matter * hubble^2 double onhh; // Omega_hdm * hubble^2 double p_c; // The correction to the exponent before drag epoch double p_cb; // The correction to the exponent after drag epoch double sound_horizon_fit; // The sound horizon at the drag epoch double theta_cmb; // The temperature of the CMB, in units of 2.7 K double y_drag; // Ratio of z_equality to z_drag double z_drag; // Redshift of the drag epoch double z_equality; // Redshift of matter-radiation equality void setinternals(); // in powerEHv2.c void TFset_parameters(double omega0hh, double f_baryon, double Tcmb); double TFfit_onek(double k, double *tf_baryon, double *tf_cdm); double R_drag; // Photon-baryon ratio at drag epoch double R_equality; // Photon-baryon ratio at equality epoch double sound_horizon; // Sound horizon at drag epoch, in Mpc double k_silk; // Silk damping scale, in Mpc^-1 double alpha_c; // CDM suppression double alpha_b; // Baryon suppression double beta_b; // Baryon envelope shift double beta_node; // Sound horizon shift double k_peak; // Fit to wavenumber of first peak, in Mpc^-1 // temporary variables for doing interations int tmp_type; double tmp_alpha; double tmp_mass; double tmp_a; // interpolation of functions double z_interp; std::size_t n_interp; void calc_interp_dist(); double interp(const std::vector<double>& table, double z) const; double invert(const std::vector<double>& table, double f_z) const; std::vector<double> redshift_interp; std::vector<double> coorDist_interp; std::vector<double> radDist_interp; }; typedef COSMOLOGY *CosmoHndl; /** * \brief Class for calculating properties of NFW halo profile. * * This class does not take into affect the cosmological correlation between concentration and mass. * For this see the HALOCalculator class. */ class NFW_Utility { public: NFW_Utility(){return;} ~NFW_Utility(){}; // methods for NFW profile double NFW_V200(double M200,double R200); double NFW_Vmax(double cons,double M200,double R200); double NFW_Vr(double x,double cons,double M200,double R200); double NFW_M(double x,double cons,double M200); double NFW_deltac(double cons); double NFW_Concentration(double Vmax,double M200,double R200); double NFW_rho(double cons,double x); void match_nfw(float Vmax,float R_half,float mass,float *cons,float *Rsize); float Rsize(float cons,float Vmax,float mass); float g_func(float x); private: float Vmax,R_half,mass; /// Mass (solar masses) typedef float (NFW_Utility::*MemFunc)(float); float zbrentD(MemFunc func, float a,float b,float tols); float nfwfunc(float cons); float funcforconcentration(float cons); }; /// wrapper functions for gsl integration / differentiation double drdz_wrapper(double x, void *params); double drdz_dark_wrapper(double x, void *params); double Deltao_wrapper(double m, void *params); #define cosmo_declare #endif /*** in cosmo.c ***/ int cosmo_compare(CosmoHndl cos1,CosmoHndl cos2); void cosmo_copy(CosmoHndl cos1,CosmoHndl cos2); void ders(double z,double Da[],double dDdz[]); void dir(double r,double a[],double dadr[]); double arctanh(double x); double fmini(double a,double b); double fmaxi(double a,double b); double **dmatrixcos(long nrl, long nrh, long ncl, long nch); void free_dmatrixcos(double **m, long nrl, long nrh, long ncl, long nch); /* in nfw.c */ /* in powerEHv2.c */ void TFset_parameters(double omega0hh, double f_baryon, double Tcmb); double TFfit_onek(double k, double *tf_baryon, double *tf_cdm);
{ "alphanum_fraction": 0.7162042175, "avg_line_length": 36.6260162602, "ext": "h", "hexsha": "ae5b28e83eda546bd526c2e368bb8d7edcc02157", "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": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "glenco/CosmoLib", "max_forks_repo_path": "include/cosmo.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_issues_repo_issues_event_max_datetime": "2016-09-29T10:27:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-09-29T10:22:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "glenco/CosmoLib", "max_issues_repo_path": "include/cosmo.h", "max_line_length": 185, "max_stars_count": null, "max_stars_repo_head_hexsha": "37bb47448946c0af2747a12c5e5949c8a060e4d0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "glenco/CosmoLib", "max_stars_repo_path": "include/cosmo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5140, "size": 18020 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "parmt_mtsearch.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "parmt_utils.h" #include "iscl/memory/memory.h" /*! * @brief Computes a synthetic seismogram corresponding for the * given observations, location (depth), and moment tensor. * * @param[in] iobs Observations number. * @param[in] ilocOpt Location index. * @param[in] imtOpt Moment tensor number. * @param[in] ldm Leading dimension of mts. This must be at leats 6. * @param[in] mts Matrix of moement tensors with dimension [nmt x ldm]. * * @param[in,out] data On input contains the data. * @param[in,out] data On exit contains the corresponding synthetic. * * @result 0 indicates success. * */ int parmt_computeSynthetic(const int iobs, const int ilocOpt, const int imtOpt, const int ldm, const double *__restrict__ mts, struct parmtData_struct *data) { double *G; int k, npts; k = iobs*data->nlocs + ilocOpt; fprintf(stdout, "%s: Processing observation=%d, location=%d, mt=%d, k=%d\n", __func__, iobs, ilocOpt, imtOpt, k); npts = data->sacGxx[k].header.npts; G = memory_calloc64f(6*npts); sacio_copyHeader(data->sacGxx[k].header, &data->est[iobs].header); cblas_dcopy(data->sacGxx[k].header.npts, data->sacGxx[k].data, 1, &G[0*npts], 1); cblas_dcopy(data->sacGyy[k].header.npts, data->sacGyy[k].data, 1, &G[1*npts], 1); cblas_dcopy(data->sacGzz[k].header.npts, data->sacGzz[k].data, 1, &G[2*npts], 1); cblas_dcopy(data->sacGxy[k].header.npts, data->sacGxy[k].data, 1, &G[3*npts], 1); cblas_dcopy(data->sacGxz[k].header.npts, data->sacGxz[k].data, 1, &G[4*npts], 1); cblas_dcopy(data->sacGyz[k].header.npts, data->sacGyz[k].data, 1, &G[5*npts], 1); data->est[iobs].data = memory_calloc64f(npts); data->est[iobs].npts = npts; strcpy(data->est[iobs].header.kcmpnm, data->data[iobs].header.kcmpnm); cblas_dgemv(CblasColMajor, CblasNoTrans, npts, 6, 1.0, G, npts, &mts[ldm*imtOpt], 1, 0.0, data->est[iobs].data, 1); memory_free64f(&G); return 0; }
{ "alphanum_fraction": 0.5941370768, "avg_line_length": 37.2615384615, "ext": "c", "hexsha": "f9ff82569c9da874da8352334bdd1c902b194cb6", "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": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": [ "Intel" ], "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_path": "src/synthetic.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "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/parmt", "max_issues_repo_path": "src/synthetic.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": [ "Intel" ], "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_path": "src/synthetic.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 771, "size": 2422 }
/* movstat/movSn.c * * Compute moving "S_n" statistic from Croux and Rousseeuw, 1992 * * 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_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_movstat.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> /* gsl_movstat_Sn() Calculate moving S_n statistic for input vector Inputs: endtype - how to handle end points x - input vector, size n xscale - (output) vector of "S_n" statistics, size n xscale_i = (S_n)_i for i-th window: w - workspace */ int gsl_movstat_Sn(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xscale, gsl_movstat_workspace * w) { int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_Sn, NULL, xscale, NULL, w); return status; }
{ "alphanum_fraction": 0.7091463415, "avg_line_length": 32.8, "ext": "c", "hexsha": "53d3479e56f80d58ca302ae9b030add4e7b87b06", "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/movSn.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/movSn.c", "max_line_length": 96, "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/movSn.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": 436, "size": 1640 }